code
stringlengths
3
1.01M
repo_name
stringlengths
5
116
path
stringlengths
3
311
language
stringclasses
30 values
license
stringclasses
15 values
size
int64
3
1.01M
/* +----------------------------------------------------------------------+ | PHP Version 5 | +----------------------------------------------------------------------+ | Copyright (c) 1997-2012 The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: Edin Kadribasic <edink@emini.dk> | +----------------------------------------------------------------------+ */ /* $Id$ */ #ifndef PHP_PDO_PGSQL_H #define PHP_PDO_PGSQL_H #include <libpq-fe.h> extern zend_module_entry pdo_pgsql_module_entry; #define phpext_pdo_pgsql_ptr &pdo_pgsql_module_entry #ifdef ZTS #include "TSRM.h" #endif PHP_MINIT_FUNCTION(pdo_pgsql); PHP_MSHUTDOWN_FUNCTION(pdo_pgsql); PHP_MINFO_FUNCTION(pdo_pgsql); #endif /* PHP_PDO_PGSQL_H */ /* * Local variables: * tab-width: 4 * c-basic-offset: 4 * End: * vim600: noet sw=4 ts=4 fdm=marker * vim<600: noet sw=4 ts=4 */
ssanglee/capstone
php-5.4.6/ext/pdo_pgsql/php_pdo_pgsql.h
C
gpl-2.0
1,621
<?php // Jeff Hannan include_once("TableTopics/TableTopicsSQL.php"); include_once("TableTopics/TableTopicsQueries.php"); // // potentially one-off functions. None of these call each other, only the above functions. // // none of the functions in here call each other, they only call tabletopicsqueries or tabletopicsSQL function tabletopics_get_record_by_id_first($id_topic_is_set, $id_topic, $topic_name) { // Prioritise by id for searching if ($id_topic_is_set){ list($success, $error_message, $result) = tabletopics_select_by_id($id_topic); } else{ list($success, $error_message, // Query by name for the topic record - enforce name when searching by name $result_select) = tabletopics_select_by_enforced_name($topic_name); } if (!$success) { $error_message = utils_prepend_error_message($error_message, "tabletopics_get_record_by_id_first"); } /* if ($success){ list($success, $error_message) = // Check that a topic is found sql_check_result($result); } */ if ($success){ // Check the result for a valid record $success = sql_rows_found($result_select); if ($id_topic_is_set){ if (!$success){$error_message = utils_create_user_error_message("Topic with id " . $id_topic . " not found.");} } else { if (!$success){$error_message = utils_create_user_error_message("Topic with name " . $topic_name . " not found.");} } } /* if (!$success) { $error_message = utils_prepend_error_message($error_message, "tabletopics_get_record_by_id_first"); } */ return array($success, $error_message, $result_select); } function tabletopics_get_topic_id_by_id_first($id_topic_is_set, $id_topic, $topic_name) { // Prioritise by id for searching. These functions both check for a valid result. if ($id_topic_is_set){ list($success, $error_message) = tabletopics_confirm_topic_id($id_topic); } else{ list($success, $error_message, $id_topic) = tabletopics_get_topic_id($topic_name); } if (!$success) { $error_message = utils_prepend_error_message($error_message, "tabletopics_get_topic_id_by_id_first"); } return array($success, $error_message, $id_topic); } function tabletopics_get_topic_id_if_not_set($topic_id_is_set, $topic_name) { if (!$topic_id_is_set){ list($success, $error_message, $topic_id_value) = tabletopics_get_topic_id($topic_name); } if (!$success) { $error_message = utils_prepend_error_message($error_message, "tabletopics_get_topic_id_if_not_set"); } return array($success, $error_message, $topic_id_value); } function tabletopics_add_topic_if_not_in($topic_name) { $id_topic = -1; // Make an initial query on the topic name, to see if it is in the database $enforced_topic_name = tabletopics_enforce_name_format($topic_name); list($success, $error_message, $result) = tabletopics_select_by_name($enforced_topic_name); // Insert the topic, if not already in. If it is already in, that's fine. if ($success){ $topic_exists = sql_rows_found($result); if ($topic_exists){ // If the topic exists, extract topic id from result list( $id_topic) = tabletopics_extract_topic_id($result); } else { // If the topic doesn't exist in the database, insert it list($success, $error_message, $id_topic) = tabletopics_insert_enforced_topic($enforced_topic_name); } } if (!$success) { $error_message = utils_prepend_error_message($error_message, "tabletopics_add_topic_if_not_in"); } return array($success, $error_message, $id_topic); } ?>
jeffhannan/argvark
php/TableTopics/TableTopicsUtils.php
PHP
gpl-2.0
3,945
x = rand(1,14760000) y = rand(1,14760000) tic() atan2(x,y) toc()
altieresdelsent/FSFM
src/other/testBox.jl
Julia
gpl-2.0
70
/* * gui_flightdetail.cpp * * Created on: 22.02.2017 * Author: tilmann@bubecks.de */ #include "gui_flightdetail.h" #include "../gui_list.h" #include "../gui_dialog.h" #include "../../fc/conf.h" #include "../../fc/logger/logger.h" uint32_t log_duration; uint32_t log_start; struct flight_stats_t log_stat; /*-----------------------------------------------------------------------*/ /* Get a string from the file */ /*-----------------------------------------------------------------------*/ TCHAR* f_gets ( TCHAR* buff, /* Pointer to the string buffer to read */ int len, /* Size of string buffer (characters) */ FIL* fp /* Pointer to the file object */ ) { int n = 0; TCHAR c, *p = buff; BYTE s[2]; UINT rc; while (n < len - 1) { /* Read characters until buffer gets filled */ f_read(fp, s, 1, &rc); if (rc != 1) break; c = s[0]; *p++ = c; n++; if (c == '\n') break; /* Break on EOL */ } *p = 0; return n ? buff : 0; /* When no data read (eof or error), return with error. */ } #define LOG_NODATA_u32 (0xFFFFFFFF) #define LOG_NODATA_i16 (-32768) void gui_flightdetail_parse_logfile(const char *filename) { FIL fp; FRESULT f_r; char line[80]; char *p; // Set defaults, if nothing could be found in the file: log_start = LOG_NODATA_u32; log_duration = LOG_NODATA_u32; log_stat.max_alt = LOG_NODATA_i16; log_stat.min_alt = LOG_NODATA_i16; log_stat.max_climb = LOG_NODATA_i16; log_stat.max_sink = LOG_NODATA_i16; DEBUG("parse_logfile(%s)\n", filename); f_r = f_open(&fp, filename, FA_READ); if ( f_r != FR_OK ) return; // Read from the end of the file f_lseek(&fp, f_size(&fp) - 512); while(1) { if ( f_gets(line, sizeof(line), &fp) == NULL ) break; p = strstr_P(line, PSTR("SKYDROP-START-s: ")); if ( p != NULL ) { log_start = atol(p + 17); continue; } p = strstr_P(line, PSTR("SKYDROP-DURATION-ms: ")); if ( p != NULL ) { log_duration = atol(p + 21); continue; } p = strstr_P(line, PSTR("SKYDROP-ALT-MAX-m: ")); if ( p != NULL ) { log_stat.max_alt = atoi(p + 19); continue; } p = strstr_P(line, PSTR("SKYDROP-ALT-MIN-m: ")); if ( p != NULL ) { log_stat.min_alt = atoi(p + 19); continue; } p = strstr_P(line, PSTR("SKYDROP-CLIMB-MAX-cm: ")); if ( p != NULL ) { log_stat.max_climb = atoi(p + 22); continue; } p = strstr_P(line, PSTR("SKYDROP-SINK-MAX-cm: ")); if ( p != NULL ) { log_stat.max_sink = atoi(p + 21); continue; } } DEBUG("closing log file\n"); f_close(&fp); } void gui_flightdetail_init() { gui_list_set(gui_flightdetail_item, gui_flightdetail_action, 7, GUI_FLIGHTLOG); } void gui_flightdetail_stop() {} void gui_flightdetail_loop() { gui_list_draw(); } void gui_flightdetail_irqh(uint8_t type, uint8_t * buff) { gui_list_irqh(type, buff); } void gui_flightdetail_action(uint8_t index) {} void gui_flightdetail_item(uint8_t idx, char * text, uint8_t * flags, char * sub_text) { uint32_t diff; uint8_t sec, min, hour, day, wday, month; uint16_t year; *flags |= GUI_LIST_SUB_TEXT; switch (idx) { case 0: strcpy_P(text, PSTR("Start (date):")); if (log_start == LOG_NODATA_u32) { sprintf_P(sub_text, PSTR("<no data>")); break; } datetime_from_epoch(log_start, &sec, &min, &hour, &day, &wday, &month, &year); sprintf_P(sub_text, PSTR("%02d.%02d.%04d"), day, month, year); break; case 1: strcpy_P(text, PSTR("Start (time):")); if (log_start == LOG_NODATA_u32) { sprintf_P(sub_text, PSTR("<no data>")); break; } datetime_from_epoch(log_start, &sec, &min, &hour, &day, &wday, &month, &year); sprintf_P(sub_text, PSTR("%02d:%02d.%02d"), hour, min, sec); break; case 2: strcpy_P(text, PSTR("Duration:")); if (log_duration == LOG_NODATA_u32) { sprintf_P(sub_text, PSTR("<no data>")); break; } diff = log_duration / 1000; hour = diff / 3600; diff %= 3600; min = diff / 60; diff %= 60; if (hour > 0) sprintf_P(sub_text, PSTR("%02d:%02d"), hour, min); else sprintf_P(sub_text, PSTR("%02d.%02d"), min, diff); break; case 3: strcpy_P(text, PSTR("Altitude(max):")); if (log_stat.max_alt == LOG_NODATA_i16) { sprintf_P(sub_text, PSTR("<no data>")); break; } sprintf_P(sub_text, PSTR("%dm"), log_stat.max_alt); break; case 4: strcpy_P(text, PSTR("Altitude(min):")); if (log_stat.min_alt == LOG_NODATA_i16) { sprintf_P(sub_text, PSTR("<no data>")); break; } sprintf_P(sub_text, PSTR("%dm"), log_stat.min_alt); break; case 5: strcpy_P(text, PSTR("Sink(max):")); if (log_stat.max_sink == LOG_NODATA_i16) { sprintf_P(sub_text, PSTR("<no data>")); break; } sprintf_P(sub_text, PSTR("%0.1fm/s"), log_stat.max_sink / 100.0); break; case 6: strcpy_P(text, PSTR("Climb(max):")); if (log_stat.max_climb == LOG_NODATA_i16) { sprintf_P(sub_text, PSTR("<no data>")); break; } sprintf_P(sub_text, PSTR("%0.1fm/s"), log_stat.max_climb / 100.0 ); break; // case 7: // strcpy_P(text, PSTR("Delete")); // *flags |= 0; // break; } }
dpsfotocestou/SkyDrop
skydrop/src/gui/settings/gui_flightdetail.cpp
C++
gpl-2.0
5,162
<?php /** * @version SEBLOD 3.x Core ~ $Id: _CREDITS.php sebastienheraud $ * @package SEBLOD (App Builder & CCK) // SEBLOD nano (Form Builder) * @url http://www.seblod.com * @editor Octopoos - www.octopoos.com * @copyright Copyright (C) 2009 - 2016 SEBLOD. All Rights Reserved. * @license GNU General Public License version 2 or later; see _LICENSE.php **/ defined( '_JEXEC' ) or die; ?> CREDITS: ------------------------------------------------------------- -------------------- SEBLOD 3.x Credits --------------------- Dynarch Calendar --------------------------------------- @author http://www.dynarch.com/projects/calendar/ @copyright Dynarch.com @license Dynarch.com jQuery --------------------------------------- @author http://jquery.com/ @copyright John Resig @license Dual licensed under the MIT or GPL Version 2 licenses. jQuery Calculation --------------------------------------- @author http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm @copyright Dan G. Switzer @license Dual licensed under the MIT and GPL licenses. jQuery ColorBox --------------------------------------- @author http://colorpowered.com/colorbox/ @copyright Jack Moore @license Licensed under the MIT license. jQuery Colorpicker --------------------------------------- @author http://eyecon.ro/colorpicker/ @copyright Stefan Petre @license Dual licensed under the MIT and GPL licenses. jQuery Cookie --------------------------------------- @author http://stilbuero.de @copyright Klaus Hartl @license Dual licensed under the MIT and GPL licenses. jQuery Json --------------------------------------- @author http://code.google.com/p/jquery-json/ @copyright Brantley Harris @license Licensed under the MIT license. jQuery LavaLamp --------------------------------------- @author http://gmarwaha.com/blog/?p=7 @copyright Ganeshji Marwaha @license Dual licensed under the MIT and GPL licenses. jQuery qTip2 --------------------------------------- @author http://craigsworks.com/projects/qtip2/ @copyright Craig Thompson @license Licensed under the MIT license. jQuery Sly --------------------------------------- @author https://github.com/Darsain @Copyright https://github.com/Darsain/sly @license Licensed under the MIT license. jQuery UI --------------------------------------- @author http://jqueryui.com/ @copyright http://jqueryui.com/about @license Dual licensed under the MIT or GPL Version 2 licenses. jQuery Validation Engine --------------------------------------- @author https://github.com/posabsolute/jQuery-Validation-Engine @copyright Cedric Dugas (v2: Olivier Refalo) @license Licensed under the MIT License. Mobile Detect --------------------------------------- @author https://github.com/serbanghita/Mobile-Detect @copyright Serban Ghita, Nick Ilyin, Victor Stanciu @license Licensed under the MIT License. PclZip --------------------------------------- @author http://www.phpconcept.net/pclzip @copyright Vincent Blavet @license License GNU/LGPL -------------------------------------------------------------- -------------------- Joomla! 3.x Credits --------------------- Many Thanks to everyone involved in the Joomla! Project.
Silasfelipegarcia/pdvoluntario
libraries/cck/_CREDITS.php
PHP
gpl-2.0
3,242
<?php if(!isset($_SESSION)) { session_start(); } ; ob_start(); include '../connectToDB.php'; $id = $_GET['id']; if (isset($_SESSION['userid'])) { $stmt = $db->prepare("UPDATE `orion`.`g_user_videogames` SET `completed`='1', `g_first`=now() WHERE `g_id`= :gid"); $stmt->bindParam(':gid', $id); $result = $stmt->execute(); if ( false===$result ) { error_log( serialize ($stmt->errorInfo())); } header("Location: videogame.php"); exit; } else { header("location: ../users/signin.php"); } ?>
ALeonard9/sandbox-src
cgi-bin/videogame/played.php
PHP
gpl-2.0
535
//Dont change it requirejs(['ext_editor_1', 'jquery_190', 'raphael_210'], function (ext, $, TableComponent) { var cur_slide = {}; ext.set_start_game(function (this_e) { }); ext.set_process_in(function (this_e, data) { cur_slide["in"] = data[0]; }); ext.set_process_out(function (this_e, data) { cur_slide["out"] = data[0]; }); ext.set_process_ext(function (this_e, data) { cur_slide.ext = data; this_e.addAnimationSlide(cur_slide); cur_slide = {}; }); ext.set_process_err(function (this_e, data) { cur_slide['error'] = data[0]; this_e.addAnimationSlide(cur_slide); cur_slide = {}; }); ext.set_animate_success_slide(function (this_e, options) { var $h = $(this_e.setHtmlSlide('<div class="animation-success"><div></div></div>')); this_e.setAnimationHeight(115); }); var sizeN = 3; var cell = 60; var padding = 0; var innerCell = cell - padding * 2; var cornerRadius = 4; var zeroX = 5; var zeroY = 5; var colorBase = "#294270"; var colorOrange = "#FABA00"; var colorBlue = "#8FC7ED"; var colorWhite = "#FFFFFF"; var opacityTrue = 1; var opacityFalse = 1; var delay = 200; var stepDelay = delay * 1.5; var goalLocation = [ [2, 2], [0, 0], [0, 1], [0, 2], [1, 0], [1, 1], [1, 2], [2, 0], [2, 1] ]; var attrInLine = {"stroke": colorBase, "stroke-width": 1}; var attrText = {"stroke": colorBase, "font-size": 18, "fill": colorBase}; var attrRect = {"stroke": colorBase, "stroke-width": 4}; var moves = {'U': [-1, 0], 'D': [1, 0], 'L': [0, -1], 'R': [0, 1]}; function createField(paper, locations) { // var imageO = paper.image("Octocat.png", zeroX, zeroY, 180, 180).attr("clip-rect", "10,10,60,60"); var mainRect = paper.rect(zeroX, zeroY, cell * sizeN, cell * sizeN, 4).attr({"stroke": colorBase, "stroke-width": 2}); // mainRect.node.setAttribute("fill", 'url(Octocat.png)'); for (var k = 1; k < sizeN; k++) { paper.path(createLinePath(zeroX, zeroY + cell * k, zeroX + cell * sizeN, zeroY + cell * k)).attr(attrInLine); paper.path(createLinePath(zeroX + cell * k, zeroY, zeroX + cell * k, zeroY + cell * sizeN)).attr(attrInLine); } var figureSet = paper.set(); for (var i = 1; i < sizeN * sizeN; i++) { var row = locations[i][0]; var column = locations[i][1]; var figure = paper.set(); figure.push(paper.rect(zeroX + cell * column + padding, zeroY + cell * row + padding, innerCell, innerCell, cornerRadius).attr(attrRect)); figure.push(paper.image("/media/files/octocat/octocat" + i + ".png", zeroX + cell * column, zeroY + cell * row, cell, cell).attr({"opacity": opacityTrue, "stroke": colorBase, "stroke-width": 2})); figure.push(paper.text(zeroX + cell * column + cell / 6 + cell / 3 * goalLocation[i][1], zeroY + cell * row + cell / 6 + cell / 3 * goalLocation[i][0], String(i)).attr(attrText)); figure.push(paper.rect(zeroX + cell * column + padding, zeroY + cell * row + padding, innerCell, innerCell, cornerRadius).attr(attrRect)); if (String(locations[i]) === String(goalLocation[i])) { figure[1].attr("opacity", opacityTrue); figure[0].attr("fill", colorBlue); } else { figure[1].attr("opacity", opacityFalse); figure[0].attr("fill", colorOrange); } figure[0].node.setAttribute("class", "chip"); figure[1].node.setAttribute("class", "chip"); figure[2].node.setAttribute("class", "chip"); figure[3].node.setAttribute("class", "chip"); figureSet[i] = figure; } return figureSet; } function matrixToLocations(matrix) { var n = matrix.length; var locations = []; for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { locations[matrix[i][j]] = [i, j]; } } return locations; } function locationsToMatrix(inLocations) { var matrix = []; for (var i=0; i < sizeN; i++) { matrix.push([]); } for (var j=0; j < inLocations.length; j++) { var x = inLocations[j][0]; var y = inLocations[j][1]; matrix[x][y] = j; } return matrix; } function createLinePath(x1, y1, x2, y2) { return "M" + x1 + "," + y1 + "L" + x2 + "," + y2; } function movePlayer(route, fSet, inLocations, timeouts) { var tempLocations = inLocations.slice(); for (var i = 0; i < route.length; i++) { var x = tempLocations[0][0]; var y = tempLocations[0][1]; var nx = x + moves[route[i]][0]; var ny = y + moves[route[i]][1]; var moved; for (var j = 0; j < tempLocations.length; j++) { if (String([nx, ny]) === String(tempLocations[j])) { moved = j; break; } } tempLocations[moved] = [x, y]; tempLocations[0] = [nx, ny]; timeouts.push(setTimeout(function () { var m = moved; var dx = -1 * moves[route[i]][0]; var dy = -1 * moves[route[i]][1]; var newColor = String(tempLocations[m]) === String(goalLocation[m]) ? colorBlue : colorOrange; var newOpacity = String(tempLocations[m]) === String(goalLocation[m]) ? opacityTrue : opacityFalse; return function () { fSet[m].animate({"transform": "...t" + dy * cell + "," + dx * cell}, delay); fSet[m][0].animate({"fill": newColor}, delay); fSet[m][1].animate({"opacity": newOpacity}, delay); } }(), i * stepDelay)); } } ext.set_animate_slide(function (this_e, data, options) { var $content = $(this_e.setHtmlSlide(ext.get_template('animation'))).find('.animation-content'); if (!data) { console.log("data is undefined"); return false; } var checkioInput = data.in; if (data.error) { $content.find('.call').html('Fail: checkio(' + JSON.stringify(checkioInput) + ')'); $content.find('.output').html(data.error.replace(/\n/g, ",")); $content.find('.output').addClass('error'); $content.find('.call').addClass('error'); $content.find('.answer').remove(); $content.find('.explanation').remove(); this_e.setAnimationHeight($content.height() + 60); return false; } var rightResult = data.ext["answer"]; var userResult = data.out; var result = data.ext["result"]; var result_message = data.ext["result_addon"][1]; var route = data.ext["result_addon"][0]; //if you need additional info from tests (if exists) var explanation = data.ext["explanation"]; $content.find('.output').html('&nbsp;Your result:&nbsp;' + JSON.stringify(userResult)); if (!result) { $content.find('.call').html('Fail: checkio(' + JSON.stringify(checkioInput) + ')'); $content.find('.answer').html(result_message); $content.find('.answer').addClass('error'); $content.find('.output').addClass('error'); $content.find('.call').addClass('error'); } else { $content.find('.call').html('Pass: checkio(' + JSON.stringify(checkioInput) + ')'); $content.find('.answer').remove(); } var canvas = Raphael($content.find(".explanation")[0], cell * sizeN + zeroX * 2, cell * sizeN + zeroY * 2, 0, 0); var locations = matrixToLocations(checkioInput); var gameSet = createField(canvas, locations); movePlayer(route, gameSet, locations, []); this_e.setAnimationHeight($content.height() + 60); }); function checkRoute(route, locations) { var tempLocations = locations.slice(0); var chRoute = ''; if (route.length < 1) { return [false, '', "I didn't see familar letters."]; } for (var i = 0; i < route.length; i++) { var zx = tempLocations[0][0]; var zy = tempLocations[0][1]; var cx = zx + moves[route[i]][0]; var cy = zy + moves[route[i]][1]; if (0 <= cx && cx < sizeN && 0 <= cy && cy < sizeN) { var moved; for (var j = 0; j < tempLocations.length; j++) { if (String([cx, cy]) === String(tempLocations[j])) { moved = j; break; } } tempLocations[moved] = [zx, zy]; tempLocations[0] = [cx, cy]; chRoute += route[i]; } } if (String(tempLocations) === String(goalLocation)) { return [true, chRoute, "Puzzle solved."]; } else { return [false, chRoute, "Puzzle didn't solved."]; } } function shuffle() { while (true) { var numbsList = []; for (var i = 1; i < sizeN * sizeN; i++) { numbsList.push(i); } var linearPuzzle = []; for (i = 1; i < sizeN * sizeN; i++) { var rIndex = Math.floor(Math.random() * numbsList.length); var n = numbsList.splice(rIndex, 1); linearPuzzle.push(n); } linearPuzzle.push(0); var inversions = 0; for (i = 0; i < linearPuzzle.length - 1; i++) { for (var j = i + 1; j < linearPuzzle.length; j++) { if (linearPuzzle[j] < linearPuzzle[i]) { inversions++; } } } if (inversions % 2 === 0) { break; } } var sLocations = []; for (i = 0; i < linearPuzzle.length; i++) { sLocations[linearPuzzle[i]] = [Math.floor(i / sizeN), i % sizeN]; } return sLocations; } var $tryit; var tPaper; var tIds = []; var tFigureSet; var tLocations; var tooltip = false; var animated = false; ext.set_console_process_ret(function(this_e, ret){ ret = String(ret); ret = ret.replace(/'/g, ""); var routeArray = ret.match(/[UDLR]/g); var route = ''; if (routeArray && routeArray.length > 0) { route = routeArray.join(''); } var resCheck = checkRoute(route, tLocations); animated = true; movePlayer(resCheck[1], tFigureSet, tLocations, tIds); $tryit.find(".checkio-result .in-result").html(resCheck[2]); }); ext.set_generate_animation_panel(function(this_e){ $tryit = $(this_e.setHtmlTryIt(ext.get_template('tryit'))); var startState = [ [1, 2, 3], [4, 5, 6], [7, 8, 0] ]; tPaper = Raphael($tryit.find(".tryit-canvas")[0], cell * sizeN + zeroX * 2, cell * sizeN + zeroY * 2, 0, 0); tLocations = matrixToLocations(startState); tFigureSet = createField(tPaper, tLocations); var reset = function () { animated = false; for (var i = 0; i < tIds.length; i++) { clearTimeout(tIds[i]); } for (var i = 1; i < sizeN * sizeN; i++) { var row = tLocations[i][0]; var column = tLocations[i][1]; tFigureSet[i].attr("transform", ""); tFigureSet[i][1].attr({"x": zeroX + cell * column + padding, "y": zeroY + cell * row + padding}); tFigureSet[i][3].attr({"x": zeroX + cell * column + padding, "y": zeroY + cell * row + padding}); tFigureSet[i][0].attr({"x": zeroX + cell * column + padding, "y": zeroY + cell * row + padding}); tFigureSet[i][2].attr({"x": zeroX + cell * column + cell / 6 + cell / 3 * goalLocation[i][1], "y": zeroY + cell * row + cell / 6 + cell / 3 * goalLocation[i][0]}); if (String(tLocations[i]) === String(goalLocation[i])) { tFigureSet[i][0].attr("fill", colorBlue); tFigureSet[i][1].animate({"opacity": opacityTrue}); } else { tFigureSet[i][0].attr("fill", colorOrange); tFigureSet[i][1].animate({"opacity": opacityFalse}); } } }; reset(); //Tooltip $tryit.find(".tryit-canvas").mouseenter(function (e) { if (tooltip) { return false; } var $tooltip = $tryit.find(".tryit-canvas .tooltip"); $tooltip.fadeIn(1000); setTimeout(function () { $tooltip.fadeOut(1000); }, 2000); tooltip = true; }); for (var f = 1; f < sizeN * sizeN; f++) { var temp = f; tFigureSet[f].click(function () { var numb = f; return function () { if (animated) { reset(); return false; } var cx = tLocations[numb][0]; var cy = tLocations[numb][1]; var zx = tLocations[0][0]; var zy = tLocations[0][1]; if (Math.abs(cx - zx) + Math.abs(cy - zy) === 1) { tLocations[0] = [cx, cy]; tLocations[numb] = [zx, zy]; var dx = zx - cx; var dy = zy - cy; var newColor = String(tLocations[numb]) === String(goalLocation[numb]) ? colorBlue : colorOrange; tFigureSet[numb].animate({"transform": "...t" + dy * cell + "," + dx * cell}, delay); tFigureSet[numb][0].animate({"fill": newColor}, delay); } } }()) } $tryit.find('.bn-check').click(function (e) { reset(); // result_return("UDRL1PLRDURRLLDDUU"); var inPuzzle = locationsToMatrix(tLocations); this_e.sendToConsoleCheckiO(inPuzzle); e.stopPropagation(); return false; }); $tryit.find('.bn-shuffle').click(function (e) { tLocations = shuffle(); reset(); return false; }); }); } );
Bryukh-Checkio-Tasks/checkio-task-8-puzzle
editor/animation/init.js
JavaScript
gpl-2.0
17,783
/* * Copyright (C) 2001-2003 FhG Fokus * * This file is part of opensips, a free SIP server. * * opensips 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 * * opensips 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 * * History: * -------- * 2003-03-10 switched to new module_exports format: updated find_export, * find_export_param, find_module (andrei) * 2003-03-19 replaced all mallocs/frees w/ pkg_malloc/pkg_free (andrei) * 2003-03-19 Support for flags in find_export (janakj) * 2003-03-29 cleaning pkg_mallocs introduced (jiri) * 2003-04-24 module version checking introduced (jiri) * 2004-09-19 compile flags are checked too (andrei) * 2006-03-02 added find_cmd_export_t(), killed find_exportp() and * find_module() (bogdan) * 2006-11-28 added module_loaded() (Jeffrey Magder - SOMA Networks) */ /*! * \file * \brief modules/plug-in structures declarations */ #include "sr_module.h" #include "dprint.h" #include "error.h" #include "globals.h" #include "mem/mem.h" #include "pt.h" #include "ut.h" #include "daemonize.h" #include <strings.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> #include <unistd.h> #include "net/api_proto.h" #include "net/proto_udp/proto_udp_handler.h" #include "net/proto_tcp/proto_tcp_handler.h" struct sr_module* modules=0; #ifdef STATIC_EXEC extern struct module_exports exec_exports; #endif #ifdef STATIC_TM extern struct module_exports tm_exports; #endif #ifdef STATIC_MAXFWD extern struct module_exports maxfwd_exports; #endif #ifdef STATIC_AUTH extern struct module_exports auth_exports; #endif #ifdef STATIC_RR extern struct module_exports rr_exports; #endif #ifdef STATIC_USRLOC extern struct module_exports usrloc_exports; #endif #ifdef STATIC_SL extern struct module_exports sl_exports; #endif char *mpath=NULL; char mpath_buf[256]; int mpath_len = 0; /* initializes statically built (compiled in) modules*/ int register_builtin_modules(void) { int ret; ret=0; #ifdef STATIC_TM ret=register_module(&tm_exports,"built-in", 0); if (ret<0) return ret; #endif #ifdef STATIC_EXEC ret=register_module(&exec_exports,"built-in", 0); if (ret<0) return ret; #endif #ifdef STATIC_MAXFWD ret=register_module(&maxfwd_exports, "built-in", 0); if (ret<0) return ret; #endif #ifdef STATIC_AUTH ret=register_module(&auth_exports, "built-in", 0); if (ret<0) return ret; #endif #ifdef STATIC_RR ret=register_module(&rr_exports, "built-in", 0); if (ret<0) return ret; #endif #ifdef STATIC_USRLOC ret=register_module(&usrloc_exports, "built-in", 0); if (ret<0) return ret; #endif #ifdef STATIC_SL ret=register_module(&sl_exports, "built-in", 0); if (ret<0) return ret; #endif return ret; } /* registers a module, register_f= module register functions * returns <0 on error, 0 on success */ int register_module(struct module_exports* e, char* path, void* handle) { int ret; struct sr_module* mod; ret=-1; /* add module to the list */ if ((mod=pkg_malloc(sizeof(struct sr_module)))==0){ LM_ERR("no more pkg memory\n"); ret=E_OUT_OF_MEM; goto error; } memset(mod,0, sizeof(struct sr_module)); mod->path=path; mod->handle=handle; mod->exports=e; mod->next=modules; modules=mod; /* register module pseudo-variables */ if (e->items) { LM_DBG("register_pv: %s\n", e->name); if (register_pvars_mod(e->name, e->items)!=0) { LM_ERR("failed to register pseudo-variables for module %s\n", e->name); pkg_free(mod); return -1; } } /* register all module dependencies */ if (e->deps) { ret = add_module_dependencies(mod); if (ret != 0) { LM_CRIT("failed to add module dependencies [%d]\n", ret); return ret; } } return 0; error: return ret; } #ifndef DLSYM_PREFIX /* define it to null */ #define DLSYM_PREFIX #endif static inline int version_control(struct module_exports* exp, char *path) { if ( !exp->version ) { LM_CRIT("BUG - version not defined in module <%s>\n", path ); return 0; } if ( !exp->compile_flags ) { LM_CRIT("BUG - compile flags not defined in module <%s>\n", path ); return 0; } if (strcmp(OPENSIPS_FULL_VERSION, exp->version)==0){ if (strcmp(OPENSIPS_COMPILE_FLAGS, exp->compile_flags)==0) return 1; else { LM_ERR("module compile flags mismatch for %s " " \ncore: %s \nmodule: %s\n", exp->name, OPENSIPS_COMPILE_FLAGS, exp->compile_flags); return 0; } } LM_ERR("module version mismatch for %s; core: %s; module: %s\n", exp->name, OPENSIPS_FULL_VERSION, exp->version ); return 0; } /* returns 0 on success , <0 on error */ int sr_load_module(char* path) { void* handle; unsigned int moddlflags; char* error; struct module_exports* exp; struct sr_module* t; /* load module */ handle=dlopen(path, OPENSIPS_DLFLAGS); /* resolve all symbols now */ if (handle==0){ LM_ERR("could not open module <%s>: %s\n", path, dlerror() ); goto error; } /* check for duplicates */ for(t=modules;t; t=t->next){ if (t->handle==handle){ LM_WARN("attempting to load the same module twice (%s)\n", path); goto skip; } } /* import module interface */ exp = (struct module_exports*)dlsym(handle, DLSYM_PREFIX "exports"); if ( (error =(char*)dlerror())!=0 ){ LM_ERR("load_module: %s\n", error); goto error1; } if(exp->dlflags!=DEFAULT_DLFLAGS && exp->dlflags!=OPENSIPS_DLFLAGS) { moddlflags = exp->dlflags; dlclose(handle); LM_DBG("reloading module %s with flags %d\n", path, moddlflags); handle = dlopen(path, moddlflags); if (handle==0){ LM_ERR("could not open module <%s>: %s\n", path, dlerror() ); goto error; } exp = (struct module_exports*)dlsym(handle, DLSYM_PREFIX "exports"); if ( (error =(char*)dlerror())!=0 ){ LM_ERR("failed to load module : %s\n", error); goto error1; } } /* version control */ if (!version_control(exp, path)) { exit(0); } /* launch register */ if (register_module(exp, path, handle)<0) goto error1; return 0; error1: dlclose(handle); error: skip: return -1; } /* built-in modules with static exports */ struct static_modules { str name; struct module_exports *exp; }; struct static_modules static_modules[] = { { str_init(PROTO_PREFIX "udp"), &proto_udp_exports }, { str_init(PROTO_PREFIX "tcp"), &proto_tcp_exports }, }; static int load_static_module(char *path) { int len = strlen(path); char *end = path + len; struct sr_module* t; unsigned int i; /* eliminate the .so, if found */ if (len > 3 && strncmp(end - 3, ".so", 3)==0) { end -= 3; len -= 3; } /* we check whether the protocol is found within the static_modules */ for (i = 0; i < (sizeof(static_modules)/sizeof(static_modules[0])); i++) { if (len >= static_modules[i].name.len && /* the path ends in the module's name */ memcmp(end - static_modules[i].name.len, static_modules[i].name.s, static_modules[i].name.len) == 0 && /* check if the previous char is '/' or nothing */ (len == static_modules[i].name.len || (*(end-len-1) == '/'))) { /* yey, found the module - check if it was loaded twice */ for(t=modules;t; t=t->next){ if (t->handle==static_modules[i].exp){ LM_WARN("attempting to load the same module twice (%s)\n", path); return 0; } } /* version control */ if (!version_control(static_modules[i].exp, path)) { exit(0); } /* launch register */ if (register_module(static_modules[i].exp, path, static_modules[i].exp)<0) return -1; return 0; } } return -1; } /* returns 0 on success , <0 on error */ int load_module(char* name) { int i_tmp; struct stat statf; /* if this is a static module, load it directly */ if (load_static_module(name) == 0) return 0; if(*name!='/' && mpath!=NULL && strlen(name)+mpath_len<255) { strcpy(mpath_buf+mpath_len, name); if (stat(mpath_buf, &statf) == -1 || S_ISDIR(statf.st_mode)) { i_tmp = strlen(mpath_buf); if(strchr(name, '/')==NULL && strncmp(mpath_buf+i_tmp-3, ".so", 3)==0) { if(i_tmp+strlen(name)<255) { strcpy(mpath_buf+i_tmp-3, "/"); strcpy(mpath_buf+i_tmp-2, name); if (stat(mpath_buf, &statf) == -1) { mpath_buf[mpath_len]='\0'; LM_ERR("module '%s' not found in '%s'\n", name, mpath_buf); return -1; } } else { LM_ERR("failed to load module - path too long\n"); return -1; } } else { LM_ERR("failed to load module - not found\n"); return -1; } } LM_DBG("loading module %s\n", mpath_buf); if (sr_load_module(mpath_buf)!=0){ LM_ERR("failed to load module\n"); return -1; } mpath_buf[mpath_len]='\0'; } else { LM_DBG("loading module %s\n", name); if (sr_load_module(name)!=0){ LM_ERR("failed to load module\n"); return -1; } } return 0; } /* searches the module list and returns pointer to the "name" function or * 0 if not found * flags parameter is OR value of all flags that must match */ cmd_function find_export(char* name, int param_no, int flags) { cmd_export_t* cmd; cmd = find_cmd_export_t(name, param_no, flags); if (cmd==0) return 0; return cmd->function; } /* searches the module list and returns pointer to the "name" cmd_export_t * structure or 0 if not found * In order to find the module the name, flags parameter number and type and * the value of all flags in the config must match to the module export */ cmd_export_t* find_cmd_export_t(char* name, int param_no, int flags) { struct sr_module* t; cmd_export_t* cmd; for(t=modules;t;t=t->next){ for(cmd=t->exports->cmds; cmd && cmd->name; cmd++){ if((strcmp(name, cmd->name)==0)&& (cmd->param_no==param_no) && ((cmd->flags & flags) == flags) ){ LM_DBG("found <%s>(%d) in module %s [%s]\n", name, param_no, t->exports->name, t->path); return cmd; } } } LM_DBG("<%s> not found \n", name); return 0; } /* searches the module list and returns pointer to the async "name" cmd_export_t * structure or 0 if not found * In order to find the module the name, flags parameter number in the config * must match to the module export */ acmd_export_t* find_acmd_export_t(char* name, int param_no) { struct sr_module* t; acmd_export_t* cmd; for(t=modules;t;t=t->next){ for(cmd=t->exports->acmds; cmd && cmd->name; cmd++){ if((strcmp(name, cmd->name)==0)&& (cmd->param_no==param_no) ){ LM_DBG("found async <%s>(%d) in module %s [%s]\n", name, param_no, t->exports->name, t->path); return cmd; } } } LM_DBG("async <%s> not found \n", name); return 0; } /* * searches the module list and returns pointer to "name" function in module * "mod" or 0 if not found * flags parameter is OR value of all flags that must match */ cmd_function find_mod_export(char* mod, char* name, int param_no, int flags) { struct sr_module* t; cmd_export_t* cmd; for (t = modules; t; t = t->next) { if (strcmp(t->exports->name, mod) == 0) { for (cmd = t->exports->cmds; cmd && cmd->name; cmd++) { if ((strcmp(name, cmd->name) == 0) && (cmd->param_no == param_no) && ((cmd->flags & flags) == flags) ){ LM_DBG("found <%s> in module %s [%s]\n", name, t->exports->name, t->path); return cmd->function; } } } } LM_DBG("<%s> in module %s not found\n", name, mod); return 0; } void* find_param_export(char* mod, char* name, modparam_t type) { struct sr_module* t; param_export_t* param; for(t = modules; t; t = t->next) { if (strcmp(mod, t->exports->name) == 0) { for(param=t->exports->params;param && param->name ; param++) { if ((strcmp(name, param->name) == 0) && (param->type == type)) { LM_DBG("found <%s> in module %s [%s]\n", name, t->exports->name, t->path); return param->param_pointer; } } } } LM_DBG("parameter <%s> or module <%s> not found\n", name, mod); return 0; } void destroy_modules(void) { struct sr_module* t, *foo; t = modules; while (t) { foo = t->next; if (t->init_done && t->exports && t->exports->destroy_f) t->exports->destroy_f(); pkg_free(t); t = foo; } modules = NULL; } /* recursive module child initialization; (recursion is used to process the module linear list in the same order in which modules are loaded in config file */ static int init_mod_child( struct sr_module* m, int rank, char *type ) { if (m) { /* iterate through the list; if error occurs, propagate it up the stack */ if (init_mod_child(m->next, rank, type)!=0) return -1; if (m->exports && m->exports->init_child_f) { LM_DBG("type=%s, rank=%d, module=%s\n", type, rank, m->exports->name); if (m->exports->init_child_f(rank)<0) { LM_ERR("failed to initializing module %s, rank %d\n", m->exports->name,rank); return -1; } else { /* module correctly initialized */ return 0; } } /* no init function -- proceed with success */ return 0; } else { /* end of list */ return 0; } } /* * per-child initialization */ int init_child(int rank) { char* type; type = 0; switch(rank) { case PROC_MAIN: type = "PROC_MAIN"; break; case PROC_TIMER: type = "PROC_TIMER"; break; case PROC_MODULE: type = "PROC_MODULE"; break; case PROC_TCP_MAIN: type = "PROC_TCP_MAIN"; break; case PROC_BIN: type = "PROC_BIN"; break; } if (!type) { if (rank>0) type = "CHILD"; else type = "UNKNOWN"; } return init_mod_child(modules, rank, type); } /* recursive module initialization; (recursion is used to process the module linear list in the same order in which modules are loaded in config file */ static int init_mod( struct sr_module* m, int skip_others) { struct sr_module_dep *dep; if (m) { /* iterate through the list; if error occurs, propagate it up the stack */ if (!skip_others && init_mod(m->next, 0) != 0) return -1; /* our module might have been already init'ed through dependencies! */ if (m->init_done) return 0; if (!m->exports) return 0; /* make sure certain modules get loaded before this one */ for (dep = m->sr_deps; dep; dep = dep->next) { if (!dep->mod->init_done) if (init_mod(dep->mod, 1) != 0) return -1; } if (m->exports->init_f) { LM_DBG("initializing module %s\n", m->exports->name); if (m->exports->init_f()!=0) { LM_ERR("failed to initialize module %s\n", m->exports->name); return -1; } } m->init_done = 1; /* no init function -- proceed further */ #ifdef STATISTICS if (m->exports->stats) { LM_DBG("registering stats for %s\n", m->exports->name); if (register_module_stats(m->exports->name,m->exports->stats)!=0) { LM_ERR("failed to registering " "statistics for module %s\n", m->exports->name); return -1; } } #endif /* register MI functions */ if (m->exports->mi_cmds) { LM_DBG("register MI for %s\n", m->exports->name); if (register_mi_mod(m->exports->name,m->exports->mi_cmds)!=0) { LM_ERR("failed to register MI functions for module %s\n", m->exports->name); } } /* proceed with success */ return 0; } else { /* end of list */ return 0; } } /* * Initialize all loaded modules, the initialization * is done *AFTER* the configuration file is parsed */ int init_modules(void) { int ret; if (solve_module_dependencies(modules) != 0) { LM_ERR("failed to solve module dependencies\n"); return -1; } ret = init_mod(modules, 0); free_module_dependencies(modules); return ret; } /* Returns 1 if the module with name 'name' is loaded, and zero otherwise. */ int module_loaded(char *name) { struct sr_module *currentMod; for (currentMod=modules; currentMod; currentMod=currentMod->next) { if (strcasecmp(name,currentMod->exports->name)==0) { return 1; } } return 0; } /* Counts the additional the number of processes requested by modules */ int count_module_procs(void) { struct sr_module *m; unsigned int cnt; unsigned int n; for( m=modules,cnt=0 ; m ; m=m->next) { if (m->exports->procs) { for( n=0 ; m->exports->procs[n].name ; n++) if (m->exports->procs[n].function) cnt += m->exports->procs[n].no; } } LM_DBG("modules require %d extra processes\n",cnt); return cnt; } int start_module_procs(void) { struct sr_module *m; unsigned int n; unsigned int l; pid_t x; for( m=modules ; m ; m=m->next) { if (m->exports->procs==NULL) continue; for( n=0 ; m->exports->procs[n].name ; n++) { if ( !m->exports->procs[n].no || !m->exports->procs[n].function ) continue; /* run pre-fork function */ if (m->exports->procs[n].pre_fork_function) if (m->exports->procs[n].pre_fork_function()!=0) { LM_ERR("pre-fork function failed for process \"%s\" " "in module %s\n", m->exports->procs[n].name, m->exports->name); return -1; } /* fork the processes */ for ( l=0; l<m->exports->procs[n].no ; l++) { LM_DBG("forking process \"%s\"/%d for module %s\n", m->exports->procs[n].name, l, m->exports->name); x = internal_fork(m->exports->procs[n].name); if (x<0) { LM_ERR("failed to fork process \"%s\"/%d for module %s\n", m->exports->procs[n].name, l, m->exports->name); return -1; } else if (x==0) { /* new process */ /* initialize the process for the rest of the modules */ if ( m->exports->procs[n].flags&PROC_FLAG_INITCHILD ) { if (init_child(PROC_MODULE) < 0) { LM_ERR("error in init_child for PROC_MODULE\n"); report_failure_status(); exit(-1); } report_conditional_status( (!no_daemon_mode), 0); } else clean_write_pipeend(); /* run the function */ m->exports->procs[n].function(l); /* we shouldn't get here */ exit(0); } } /* run post-fork function */ if (m->exports->procs[n].post_fork_function) if (m->exports->procs[n].post_fork_function()!=0) { LM_ERR("post-fork function failed for process \"%s\" " "in module %s\n", m->exports->procs[n].name, m->exports->name); return -1; } } } return 0; }
chiforbogdan/opensips
sr_module.c
C
gpl-2.0
18,671
/* * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information * * 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/>. */ #include "WorldSession.h" #include "CollectionMgr.h" #include "Common.h" #include "DatabaseEnv.h" #include "GameObjectAI.h" #include "GameObjectPackets.h" #include "Guild.h" #include "GuildMgr.h" #include "Item.h" #include "Log.h" #include "Map.h" #include "Player.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "ScriptMgr.h" #include "Spell.h" #include "SpellAuraEffects.h" #include "SpellMgr.h" #include "SpellPackets.h" #include "Totem.h" #include "TotemPackets.h" #include "World.h" void WorldSession::HandleUseItemOpcode(WorldPackets::Spells::UseItem& packet) { Player* user = _player; // ignore for remote control state if (user->m_unitMovedByMe != user) return; Item* item = user->GetUseableItemByPos(packet.PackSlot, packet.Slot); if (!item) { user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (item->GetGUID() != packet.CastItem) { user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } ItemTemplate const* proto = item->GetTemplate(); if (!proto) { user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr); return; } // some item classes can be used only in equipped state if (proto->GetInventoryType() != INVTYPE_NON_EQUIP && !item->IsEquipped()) { user->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr); return; } InventoryResult msg = user->CanUseItem(item); if (msg != EQUIP_ERR_OK) { user->SendEquipError(msg, item, nullptr); return; } // only allow conjured consumable, bandage, poisons (all should have the 2^21 item flag set in DB) if (proto->GetClass() == ITEM_CLASS_CONSUMABLE && !(proto->GetFlags() & ITEM_FLAG_IGNORE_DEFAULT_ARENA_RESTRICTIONS) && user->InArena()) { user->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, item, nullptr); return; } // don't allow items banned in arena if (proto->GetFlags() & ITEM_FLAG_NOT_USEABLE_IN_ARENA && user->InArena()) { user->SendEquipError(EQUIP_ERR_NOT_DURING_ARENA_MATCH, item, nullptr); return; } if (user->IsInCombat()) { for (ItemEffectEntry const* effect : item->GetEffects()) { if (SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(effect->SpellID, user->GetMap()->GetDifficultyID())) { if (!spellInfo->CanBeUsedInCombat()) { user->SendEquipError(EQUIP_ERR_NOT_IN_COMBAT, item, nullptr); return; } } } } // check also BIND_ON_ACQUIRE and BIND_QUEST for .additem or .additemset case by GM (not binded at adding to inventory) if (item->GetBonding() == BIND_ON_USE || item->GetBonding() == BIND_ON_ACQUIRE || item->GetBonding() == BIND_QUEST) { if (!item->IsSoulBound()) { item->SetState(ITEM_CHANGED, user); item->SetBinding(true); GetCollectionMgr()->AddItemAppearance(item); } } SpellCastTargets targets(user, packet.Cast); // Note: If script stop casting it must send appropriate data to client to prevent stuck item in gray state. if (!sScriptMgr->OnItemUse(user, item, targets, packet.Cast.CastID)) { // no script or script not process request by self user->CastItemUseSpell(item, targets, packet.Cast.CastID, packet.Cast.Misc); } } void WorldSession::HandleOpenItemOpcode(WorldPackets::Spells::OpenItem& packet) { Player* player = GetPlayer(); // ignore for remote control state if (player->m_unitMovedByMe != player) return; TC_LOG_INFO("network", "bagIndex: %u, slot: %u", packet.Slot, packet.PackSlot); // additional check, client outputs message on its own if (!player->IsAlive()) { player->SendEquipError(EQUIP_ERR_PLAYER_DEAD, nullptr, nullptr); return; } Item* item = player->GetItemByPos(packet.Slot, packet.PackSlot); if (!item) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } ItemTemplate const* proto = item->GetTemplate(); if (!proto) { player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr); return; } // Verify that the bag is an actual bag or wrapped item that can be used "normally" if (!(proto->GetFlags() & ITEM_FLAG_HAS_LOOT) && !item->HasItemFlag(ITEM_FIELD_FLAG_WRAPPED)) { player->SendEquipError(EQUIP_ERR_CLIENT_LOCKED_OUT, item, nullptr); TC_LOG_ERROR("entities.player.cheat", "Possible hacking attempt: Player %s [%s] tried to open item [%s, entry: %u] which is not openable!", player->GetName().c_str(), player->GetGUID().ToString().c_str(), item->GetGUID().ToString().c_str(), proto->GetId()); return; } // locked item uint32 lockId = proto->GetLockID(); if (lockId) { LockEntry const* lockInfo = sLockStore.LookupEntry(lockId); if (!lockInfo) { player->SendEquipError(EQUIP_ERR_ITEM_LOCKED, item, nullptr); TC_LOG_ERROR("network", "WORLD::OpenItem: item [%s] has an unknown lockId: %u!", item->GetGUID().ToString().c_str(), lockId); return; } // was not unlocked yet if (item->IsLocked()) { player->SendEquipError(EQUIP_ERR_ITEM_LOCKED, item, nullptr); return; } } if (item->HasItemFlag(ITEM_FIELD_FLAG_WRAPPED))// wrapped? { CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_SEL_CHARACTER_GIFT_BY_ITEM); stmt->setUInt64(0, item->GetGUID().GetCounter()); _queryProcessor.AddCallback(CharacterDatabase.AsyncQuery(stmt) .WithPreparedCallback(std::bind(&WorldSession::HandleOpenWrappedItemCallback, this, item->GetPos(), item->GetGUID(), std::placeholders::_1))); } else player->SendLoot(item->GetGUID(), LOOT_CORPSE); } void WorldSession::HandleOpenWrappedItemCallback(uint16 pos, ObjectGuid itemGuid, PreparedQueryResult result) { if (!GetPlayer()) return; Item* item = GetPlayer()->GetItemByPos(pos); if (!item) return; if (item->GetGUID() != itemGuid || !item->HasItemFlag(ITEM_FIELD_FLAG_WRAPPED)) // during getting result, gift was swapped with another item return; if (!result) { TC_LOG_ERROR("network", "Wrapped item %s don't have record in character_gifts table and will deleted", item->GetGUID().ToString().c_str()); GetPlayer()->DestroyItem(item->GetBagSlot(), item->GetSlot(), true); return; } CharacterDatabaseTransaction trans = CharacterDatabase.BeginTransaction(); Field* fields = result->Fetch(); uint32 entry = fields[0].GetUInt32(); uint32 flags = fields[1].GetUInt32(); item->SetGiftCreator(ObjectGuid::Empty); item->SetEntry(entry); item->SetItemFlags(ItemFieldFlags(flags)); item->SetMaxDurability(item->GetTemplate()->MaxDurability); item->SetState(ITEM_CHANGED, GetPlayer()); GetPlayer()->SaveInventoryAndGoldToDB(trans); CharacterDatabasePreparedStatement* stmt = CharacterDatabase.GetPreparedStatement(CHAR_DEL_GIFT); stmt->setUInt64(0, itemGuid.GetCounter()); trans->Append(stmt); CharacterDatabase.CommitTransaction(trans); } void WorldSession::HandleGameObjectUseOpcode(WorldPackets::GameObject::GameObjUse& packet) { if (GameObject* obj = GetPlayer()->GetGameObjectIfCanInteractWith(packet.Guid)) { // ignore for remote control state if (GetPlayer()->m_unitMovedByMe != GetPlayer()) if (!(GetPlayer()->IsOnVehicle(GetPlayer()->m_unitMovedByMe) || GetPlayer()->IsMounted()) && !obj->GetGOInfo()->IsUsableMounted()) return; obj->Use(GetPlayer()); } } void WorldSession::HandleGameobjectReportUse(WorldPackets::GameObject::GameObjReportUse& packet) { // ignore for remote control state if (_player->m_unitMovedByMe != _player) return; if (GameObject* go = GetPlayer()->GetGameObjectIfCanInteractWith(packet.Guid)) { if (go->AI()->OnReportUse(_player)) return; _player->UpdateCriteria(CRITERIA_TYPE_USE_GAMEOBJECT, go->GetEntry()); } } void WorldSession::HandleCastSpellOpcode(WorldPackets::Spells::CastSpell& cast) { // ignore for remote control state (for player case) Unit* mover = _player->m_unitMovedByMe; if (mover != _player && mover->GetTypeId() == TYPEID_PLAYER) return; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(cast.Cast.SpellID, mover->GetMap()->GetDifficultyID()); if (!spellInfo) { TC_LOG_ERROR("network", "WORLD: unknown spell id %u", cast.Cast.SpellID); return; } if (spellInfo->IsPassive()) return; Unit* caster = mover; if (caster->GetTypeId() == TYPEID_UNIT && !caster->ToCreature()->HasSpell(spellInfo->Id)) { // If the vehicle creature does not have the spell but it allows the passenger to cast own spells // change caster to player and let him cast if (!_player->IsOnVehicle(caster) || spellInfo->CheckVehicle(_player) != SPELL_CAST_OK) return; caster = _player; } // check known spell or raid marker spell (which not requires player to know it) if (caster->GetTypeId() == TYPEID_PLAYER && !caster->ToPlayer()->HasActiveSpell(spellInfo->Id) && !spellInfo->HasEffect(SPELL_EFFECT_CHANGE_RAID_MARKER) && !spellInfo->HasAttribute(SPELL_ATTR8_RAID_MARKER)) return; // Check possible spell cast overrides spellInfo = caster->GetCastSpellInfo(spellInfo); // Client is resending autoshot cast opcode when other spell is cast during shoot rotation // Skip it to prevent "interrupt" message if (spellInfo->IsAutoRepeatRangedSpell() && caster->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL) && caster->GetCurrentSpell(CURRENT_AUTOREPEAT_SPELL)->m_spellInfo == spellInfo) return; // can't use our own spells when we're in possession of another unit, if (_player->isPossessing()) return; // client provided targets SpellCastTargets targets(caster, cast.Cast); // auto-selection buff level base at target level (in spellInfo) if (targets.GetUnitTarget()) { SpellInfo const* actualSpellInfo = spellInfo->GetAuraRankForLevel(targets.GetUnitTarget()->GetLevelForTarget(caster)); // if rank not found then function return NULL but in explicit cast case original spell can be cast and later failed with appropriate error message if (actualSpellInfo) spellInfo = actualSpellInfo; } if (cast.Cast.MoveUpdate) HandleMovementOpcode(CMSG_MOVE_STOP, *cast.Cast.MoveUpdate); Spell* spell = new Spell(caster, spellInfo, TRIGGERED_NONE, ObjectGuid::Empty, false); WorldPackets::Spells::SpellPrepare spellPrepare; spellPrepare.ClientCastID = cast.Cast.CastID; spellPrepare.ServerCastID = spell->m_castId; SendPacket(spellPrepare.Write()); spell->m_fromClient = true; spell->m_misc.Raw.Data[0] = cast.Cast.Misc[0]; spell->m_misc.Raw.Data[1] = cast.Cast.Misc[1]; spell->prepare(&targets); } void WorldSession::HandleCancelCastOpcode(WorldPackets::Spells::CancelCast& packet) { if (_player->IsNonMeleeSpellCast(false)) _player->InterruptNonMeleeSpells(false, packet.SpellID, false); } void WorldSession::HandleCancelAuraOpcode(WorldPackets::Spells::CancelAura& cancelAura) { SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(cancelAura.SpellID, _player->GetMap()->GetDifficultyID()); if (!spellInfo) return; // not allow remove spells with attr SPELL_ATTR0_CANT_CANCEL if (spellInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL)) return; // channeled spell case (it currently cast then) if (spellInfo->IsChanneled()) { if (Spell* curSpell = _player->GetCurrentSpell(CURRENT_CHANNELED_SPELL)) if (curSpell->GetSpellInfo()->Id == uint32(cancelAura.SpellID)) _player->InterruptSpell(CURRENT_CHANNELED_SPELL); return; } // non channeled case: // don't allow remove non positive spells // don't allow cancelling passive auras (some of them are visible) if (!spellInfo->IsPositive() || spellInfo->IsPassive()) return; _player->RemoveOwnedAura(cancelAura.SpellID, cancelAura.CasterGUID, 0, AURA_REMOVE_BY_CANCEL); // If spell being removed is a resource tracker, see if player was tracking both (herbs / minerals) and remove the other if (sWorld->getBoolConfig(CONFIG_ALLOW_TRACK_BOTH_RESOURCES) && spellInfo->HasAura(SPELL_AURA_TRACK_RESOURCES)) { Unit::AuraEffectList const& auraEffects = _player->GetAuraEffectsByType(SPELL_AURA_TRACK_RESOURCES); if (!auraEffects.empty()) { // Build list of spell IDs to cancel. Trying to cancel the aura while iterating // over AuraEffectList caused "incompatible iterator" errors on second pass std::list<uint32> spellIDs; for (Unit::AuraEffectList::const_iterator auraEffect = auraEffects.begin(); auraEffect != auraEffects.end(); ++auraEffect) spellIDs.push_back((*auraEffect)->GetId()); // Remove all auras related to resource tracking (only Herbs and Minerals in 3.3.5a) for (std::list<uint32>::iterator it = spellIDs.begin(); it != spellIDs.end(); ++it) _player->RemoveOwnedAura(*it, cancelAura.CasterGUID, 0, AURA_REMOVE_BY_CANCEL); } } } void WorldSession::HandlePetCancelAuraOpcode(WorldPackets::Spells::PetCancelAura& packet) { if (sSpellMgr->GetSpellInfo(packet.SpellID, DIFFICULTY_NONE)) { TC_LOG_ERROR("network", "WORLD: unknown PET spell id %u", packet.SpellID); return; } Creature* pet = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, packet.PetGUID); if (!pet) { TC_LOG_ERROR("network", "HandlePetCancelAura: Attempt to cancel an aura for non-existant %s by player '%s'", packet.PetGUID.ToString().c_str(), GetPlayer()->GetName().c_str()); return; } if (pet != GetPlayer()->GetGuardianPet() && pet != GetPlayer()->GetCharm()) { TC_LOG_ERROR("network", "HandlePetCancelAura: %s is not a pet of player '%s'", packet.PetGUID.ToString().c_str(), GetPlayer()->GetName().c_str()); return; } if (!pet->IsAlive()) { pet->SendPetActionFeedback(PetActionFeedback::Dead, 0); return; } pet->RemoveOwnedAura(packet.SpellID, ObjectGuid::Empty, 0, AURA_REMOVE_BY_CANCEL); } void WorldSession::HandleCancelGrowthAuraOpcode(WorldPackets::Spells::CancelGrowthAura& /*cancelGrowthAura*/) { _player->RemoveAurasByType(SPELL_AURA_MOD_SCALE, [](AuraApplication const* aurApp) { SpellInfo const* spellInfo = aurApp->GetBase()->GetSpellInfo(); return !spellInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL) && spellInfo->IsPositive() && !spellInfo->IsPassive(); }); } void WorldSession::HandleCancelMountAuraOpcode(WorldPackets::Spells::CancelMountAura& /*cancelMountAura*/) { _player->RemoveAurasByType(SPELL_AURA_MOUNTED, [](AuraApplication const* aurApp) { SpellInfo const* spellInfo = aurApp->GetBase()->GetSpellInfo(); return !spellInfo->HasAttribute(SPELL_ATTR0_CANT_CANCEL) && spellInfo->IsPositive() && !spellInfo->IsPassive(); }); } void WorldSession::HandleCancelAutoRepeatSpellOpcode(WorldPackets::Spells::CancelAutoRepeatSpell& /*cancelAutoRepeatSpell*/) { // may be better send SMSG_CANCEL_AUTO_REPEAT? // cancel and prepare for deleting _player->InterruptSpell(CURRENT_AUTOREPEAT_SPELL); } void WorldSession::HandleCancelChanneling(WorldPackets::Spells::CancelChannelling& /*cancelChanneling*/) { // ignore for remote control state (for player case) Unit* mover = _player->m_unitMovedByMe; if (mover != _player && mover->GetTypeId() == TYPEID_PLAYER) return; mover->InterruptSpell(CURRENT_CHANNELED_SPELL); } void WorldSession::HandleTotemDestroyed(WorldPackets::Totem::TotemDestroyed& totemDestroyed) { // ignore for remote control state if (_player->m_unitMovedByMe != _player) return; uint8 slotId = totemDestroyed.Slot; slotId += SUMMON_SLOT_TOTEM; if (slotId >= MAX_TOTEM_SLOT) return; if (!_player->m_SummonSlot[slotId]) return; Creature* totem = ObjectAccessor::GetCreature(*_player, _player->m_SummonSlot[slotId]); if (totem && totem->IsTotem() && totem->GetGUID() == totemDestroyed.TotemGUID) totem->ToTotem()->UnSummon(); } void WorldSession::HandleSelfResOpcode(WorldPackets::Spells::SelfRes& selfRes) { if (_player->HasAuraType(SPELL_AURA_PREVENT_RESURRECTION)) return; // silent return, client should display error by itself and not send this opcode auto const& selfResSpells = _player->m_activePlayerData->SelfResSpells; if (std::find(selfResSpells.begin(), selfResSpells.end(), selfRes.SpellID) == selfResSpells.end()) return; SpellInfo const* spellInfo = sSpellMgr->GetSpellInfo(selfRes.SpellID, _player->GetMap()->GetDifficultyID()); if (spellInfo) _player->CastSpell(_player, spellInfo, false, nullptr); _player->RemoveSelfResSpell(selfRes.SpellID); } void WorldSession::HandleSpellClick(WorldPackets::Spells::SpellClick& spellClick) { // this will get something not in world. crash Creature* unit = ObjectAccessor::GetCreatureOrPetOrVehicle(*_player, spellClick.SpellClickUnitGuid); if (!unit) return; /// @todo Unit::SetCharmedBy: 28782 is not in world but 0 is trying to charm it! -> crash if (!unit->IsInWorld()) return; unit->HandleSpellClick(_player); } void WorldSession::HandleMirrorImageDataRequest(WorldPackets::Spells::GetMirrorImageData& getMirrorImageData) { ObjectGuid guid = getMirrorImageData.UnitGUID; // Get unit for which data is needed by client Unit* unit = ObjectAccessor::GetUnit(*_player, guid); if (!unit) return; if (!unit->HasAuraType(SPELL_AURA_CLONE_CASTER)) return; // Get creator of the unit (SPELL_AURA_CLONE_CASTER does not stack) Unit* creator = unit->GetAuraEffectsByType(SPELL_AURA_CLONE_CASTER).front()->GetCaster(); if (!creator) return; if (Player* player = creator->ToPlayer()) { WorldPackets::Spells::MirrorImageComponentedData mirrorImageComponentedData; mirrorImageComponentedData.UnitGUID = guid; mirrorImageComponentedData.DisplayID = creator->GetDisplayId(); mirrorImageComponentedData.RaceID = creator->getRace(); mirrorImageComponentedData.Gender = creator->getGender(); mirrorImageComponentedData.ClassID = creator->getClass(); for (UF::ChrCustomizationChoice const& customization : player->m_playerData->Customizations) mirrorImageComponentedData.Customizations.push_back(customization); Guild* guild = player->GetGuild(); mirrorImageComponentedData.GuildGUID = (guild ? guild->GetGUID() : ObjectGuid::Empty); mirrorImageComponentedData.ItemDisplayID.reserve(11); static EquipmentSlots const itemSlots[] = { EQUIPMENT_SLOT_HEAD, EQUIPMENT_SLOT_SHOULDERS, EQUIPMENT_SLOT_BODY, EQUIPMENT_SLOT_CHEST, EQUIPMENT_SLOT_WAIST, EQUIPMENT_SLOT_LEGS, EQUIPMENT_SLOT_FEET, EQUIPMENT_SLOT_WRISTS, EQUIPMENT_SLOT_HANDS, EQUIPMENT_SLOT_TABARD, EQUIPMENT_SLOT_BACK, }; // Display items in visible slots for (EquipmentSlots slot : itemSlots) { uint32 itemDisplayId; if (Item const* item = player->GetItemByPos(INVENTORY_SLOT_BAG_0, slot)) itemDisplayId = item->GetDisplayId(player); else itemDisplayId = 0; mirrorImageComponentedData.ItemDisplayID.push_back(itemDisplayId); } SendPacket(mirrorImageComponentedData.Write()); } else { WorldPackets::Spells::MirrorImageCreatureData mirrorImageCreatureData; mirrorImageCreatureData.UnitGUID = guid; mirrorImageCreatureData.DisplayID = creator->GetDisplayId(); SendPacket(mirrorImageCreatureData.Write()); } } void WorldSession::HandleMissileTrajectoryCollision(WorldPackets::Spells::MissileTrajectoryCollision& packet) { Unit* caster = ObjectAccessor::GetUnit(*_player, packet.Target); if (!caster) return; Spell* spell = caster->FindCurrentSpellBySpellId(packet.SpellID); if (!spell || !spell->m_targets.HasDst()) return; Position pos = *spell->m_targets.GetDstPos(); pos.Relocate(packet.CollisionPos); spell->m_targets.ModDst(pos); // we changed dest, recalculate flight time spell->RecalculateDelayMomentForDst(); WorldPackets::Spells::NotifyMissileTrajectoryCollision notify; notify.Caster = packet.Target; notify.CastID = packet.CastID; notify.CollisionPos = packet.CollisionPos; caster->SendMessageToSet(notify.Write(), true); } void WorldSession::HandleUpdateMissileTrajectory(WorldPackets::Spells::UpdateMissileTrajectory& packet) { Unit* caster = ObjectAccessor::GetUnit(*_player, packet.Guid); Spell* spell = caster ? caster->GetCurrentSpell(CURRENT_GENERIC_SPELL) : nullptr; if (!spell || spell->m_spellInfo->Id != uint32(packet.SpellID) || !spell->m_targets.HasDst() || !spell->m_targets.HasSrc()) return; spell->m_targets.ModSrc(packet.FirePos); spell->m_targets.ModDst(packet.ImpactPos); spell->m_targets.SetPitch(packet.Pitch); spell->m_targets.SetSpeed(packet.Speed); if (packet.Status) HandleMovementOpcode(CMSG_MOVE_STOP, *packet.Status); } void WorldSession::HandleRequestCategoryCooldowns(WorldPackets::Spells::RequestCategoryCooldowns& /*requestCategoryCooldowns*/) { _player->SendSpellCategoryCooldowns(); }
Aszune/TrinityCoreRP
src/server/game/Handlers/SpellHandler.cpp
C++
gpl-2.0
22,993
#ifndef SPRITE_SET_H #define SPRITE_SET_H #include <vector> #include "Shape.h" namespace rgl { // // SPRITESET // class SpriteSet : public Shape { private: ARRAY<Vertex> vertex; ARRAY<float> size; public: SpriteSet(Material& material, int nvertex, double* vertex, int nsize, double* size, int ignoreExtent, int count = 0, Shape** shapelist = NULL, double* userMatrix = NULL); ~SpriteSet(); /** * overload **/ virtual void render(RenderContext* renderContext); virtual void getTypeName(char* buffer, int buflen) { strncpy(buffer, "sprites", buflen); }; virtual int getElementCount(void); int getAttributeCount(AABox& bbox, AttribID attrib); void getAttribute(AABox& bbox, AttribID attrib, int first, int count, double* result); String getTextAttribute(AABox& bbox, AttribID attrib, int index); /** * location of individual items **/ virtual Vertex getElementCenter(int index); /** * begin sending items **/ virtual void drawBegin(RenderContext* renderContext); /** * send one item **/ virtual void drawElement(RenderContext* renderContext, int index); /** * end sending items **/ virtual void drawEnd(RenderContext* renderContext); /** * extract individual shape */ virtual Shape* get_shape(int id); private: GLdouble userMatrix[16]; /* Transformation for 3D sprites */ Matrix4x4 m; /* Modelview matrix cache */ bool doTex; std::vector<Shape*> shapes; }; } // namespace rgl #endif // SPRITE_SET_H
trestletech/rgl
src/SpriteSet.h
C
gpl-2.0
1,545
#ifndef ECP_WII_JOINT_GENERATOR_H #define ECP_WII_JOINT_GENERATOR_H #include "base/ecp/ecp_generator.h" #include "application/wii_teach/sensor/ecp_mp_s_wiimote.h" #include "application/wii_teach/generator/ecp_g_wii.h" namespace mrrocpp { namespace ecp { namespace irp6ot_m { namespace generator { /** @addtogroup wii_teach * * @{ */ class wii_joint : public generator::wii { public: /** * Tworzy generator odtwarzajacy orientacje kontrolera * @param zadanie * @param major_axis wartosc wiekszej polosi * @param minor_axis wartosc mniejszej polosi * @author jedrzej */ wii_joint (common::task::task& _ecp_task,ecp_mp::sensor::wiimote* _wiimote); /** * Generuje pierwszy krok * @author jedrzej */ virtual bool first_step(); void preset_position(void); virtual void set_position(bool changed); }; /** @} */ // end of wii_teach } } // namespace irp6ot } // namespace ecp } // namespace mrrocpp #endif //ECP_WII_JOINT_GENERATOR_H
ptroja/mrrocpp
src/application/wii_teach/generator/ecp_g_wii_joint.h
C
gpl-2.0
1,023
<?php /** * 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; under version 2 * of the License (non-upgradable). * * 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. * * Copyright (c) 2018 (original work) Open Assessment Technologies SA; * */ namespace oat\taoTestCenter\test\unit\gui\form; use core_kernel_classes_Resource; use oat\taoTestCenter\model\gui\form\formFactory\FormFactoryInterface; use oat\taoTestCenter\model\gui\form\TreeFormFactory; use tao_helpers_form_GenerisTreeForm; use oat\generis\test\TestCase; class TreeFormFactoryTest extends TestCase { public function testGetForms() { $treeFormFactory = $this->getService(); $forms = $treeFormFactory->getForms(); $this->assertIsArray($forms); $this->assertCount(3, $forms); $this->assertInstanceOf(FormFactoryInterface::class, $forms[0]); $this->assertInstanceOf(FormFactoryInterface::class, $forms[1]); $this->assertInstanceOf(FormFactoryInterface::class, $forms[2]); } /** * @throws \oat\oatbox\service\exception\InvalidService * @throws \oat\oatbox\service\exception\InvalidServiceManagerException */ public function testRenderForms() { $treeFormFactory = $this->getService(); $renderForms = $treeFormFactory->renderForms( $this->getMockBuilder(core_kernel_classes_Resource::class)->disableOriginalConstructor()->getMock() ); $this->assertIsArray($renderForms); $this->assertCount(3, $renderForms); $this->assertIsString(tao_helpers_form_GenerisTreeForm::class, $renderForms[0]); $this->assertIsString(tao_helpers_form_GenerisTreeForm::class, $renderForms[1]); $this->assertIsString(tao_helpers_form_GenerisTreeForm::class, $renderForms[2]); } /** * @return TreeFormFactory */ protected function getService() { $service = $this->getMockBuilder(TreeFormFactory::class) ->setMethods(['buildService']) ->getMock(); $service ->method('buildService') ->willReturn($this->mockFormFactory()); $service->setOption(TreeFormFactory::OPTION_FORM_FACTORIES, [ $this->mockFormFactory(), $this->mockFormFactory(), $this->mockFormFactory(), ]); return $service; } protected function mockFormFactory() { $form = $this->getMockForAbstractClass(FormFactoryInterface::class); $form ->method('__invoke') ->willReturn( $this->mockForm() ); return $form; } protected function mockForm() { $form = $this->getMockBuilder(tao_helpers_form_GenerisTreeForm::class) ->setMethods(['render'])->disableOriginalConstructor()->getMock(); $form->method('render')->willReturn('rendered form'); return $form; } }
oat-sa/extension-tao-testcenter
test/unit/gui/form/TreeFormFactoryTest.php
PHP
gpl-2.0
3,464
/*------------------------------------------------------------------------------ Hello, this is the RTL version of the main WordPress admin CSS file. All the important stuff is in here. TABLE OF CONTENTS: ------------------ 1.0 - Text Elements 2.0 - Forms 3.0 - Actions 4.0 - Notifications 5.0 - TinyMCE 6.0 - Admin Header 6.1 - Screen Options Tabs 7.0 - Main Navigation 8.0 - Layout Blocks 9.0 - Dashboard 10.0 - List Posts 10.1 - Inline Editing 11.0 - Write/Edit Post Screen 11.1 - Custom Fields 11.2 - Post Revisions 12.0 - Categories 13.0 - Tags 14.0 - Media Screen 14.1 - Media Uploader 14.2 - Image Editor 15.0 - Comments Screen 16.0 - Themes 16.1 - Custom Header 16.2 - Custom Background 16.3 - Tabbed Admin Screen Interface 17.0 - Plugins 18.0 - Users 19.0 - Tools 20.0 - Settings 21.0 - Admin Footer 22.0 - About Pages 23.0 - Misc 24.0 - Dead 25.0 - TinyMCE tweaks 26.0 - Full Overlay w/ Sidebar 27.0 - Customize Loader ------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------ 1.0 - Text Styles ------------------------------------------------------------------------------*/ ol { margin-left: 0; margin-right: 2em; } .code, code { font-family: monospace; direction: ltr; } .quicktags, .search { font: 12px Tahoma, Arial, sans-serif; } .icon32 { float: right; margin-right: 0; margin-left: 8px; } .icon16 { float: right; margin-right: -8px; margin-left: 0; } .howto { font-style: normal; font-family: Tahoma, Arial, sans-serif; } p.install-help { font-style: normal; } /*------------------------------------------------------------------------------ 2.0 - Forms ------------------------------------------------------------------------------*/ #doaction, #doaction2, #post-query-submit { margin-right: 0; margin-left: 8px; } #timezone_string option { margin-left: 0; margin-right: 1em; } #pass-strength-result { float: right; margin: 13px 1px 5px 5px; } p.search-box { float: left; } input[type=password] { direction: ltr; } input[type="text"].ui-autocomplete-loading { background: transparent url('../images/loading.gif') no-repeat left center; } ul#add-to-blog-users { margin: 0 14px 0 0; } .ui-autocomplete li { text-align: right; } /*------------------------------------------------------------------------------ 3.0 - Actions ------------------------------------------------------------------------------*/ #delete-action { float: right; } #publishing-action { float: left; } #post-body .misc-pub-section { border-right:0; border-left-width: 1px; border-left-style: solid; } #post-body .misc-pub-section-last { border-left: 0; } #minor-publishing-actions { padding: 10px 8px 2px 10px; text-align: left; } #save-post { float: right; } #minor-publishing .ajax-loading { padding: 3px 4px 0 0; float: right; } .preview { float: left; } #sticky-span { margin-left: 0; margin-right: 18px; } .side-info ul { padding-left: 0; padding-right: 18px; } td.action-links, th.action-links { text-align: left; } .describe .del-link { padding-left: 0; padding-right: 5px; } /*------------------------------------------------------------------------------ 4.0 - Notifications ------------------------------------------------------------------------------*/ form.upgrade .hint { font-style: normal; } #ajax-response.alignleft { margin-left: 0; margin-right: 2em; } /*------------------------------------------------------------------------------ 5.0 - TinyMCE ------------------------------------------------------------------------------*/ #quicktags { background-position: right top; } #ed_reply_toolbar input { margin: 1px 1px 1px 2px; } /*------------------------------------------------------------------------------ 6.0 - Admin Header ------------------------------------------------------------------------------*/ #wphead { height: 32px; margin-left: 15px; margin-right: 2px; } #header-logo { float: right; } #wphead h1 { float: right; } /*------------------------------------------------------------------------------ 6.1 - Screen Options Tabs ------------------------------------------------------------------------------*/ #screen-meta-links { margin-right: 0; margin-left: 24px; } #screen-meta { margin-right: 5px; margin-left: 15px; } #screen-options-link-wrap, #contextual-help-link-wrap { float: left; margin-left: 0; margin-right: 6px; } #screen-meta-links a.show-settings { padding-right: 6px; padding-left: 16px; } .toggle-arrow { background-position: top right; } .toggle-arrow-active { background-position: bottom right; } .metabox-prefs label { padding-right: 0; padding-left: 15px; } .metabox-prefs label input { margin-right: 2px; margin-left: 5px; } /*------------------------------------------------------------------------------ 6.2 - Help Menu ------------------------------------------------------------------------------*/ #contextual-help-wrap { margin-left: 0; margin-right: -4px; } #contextual-help-back { left: 170px; right: 150px; } #contextual-help-wrap.no-sidebar #contextual-help-back { left: 0; right: 150px; border-right-width: 1px; border-left-width: 0; -webkit-border-bottom-right-radius: 0; border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 2px; border-bottom-left-radius: 2px; } .contextual-help-tabs { float: right; } .contextual-help-tabs a { padding-left: 5px; padding-right: 12px; } .contextual-help-tabs .active { margin-right: 0; margin-left: -1px; } .contextual-help-tabs .active, .contextual-help-tabs-wrap { border-left: 0; border-right-width: 1px; } .help-tab-content { margin-right: 0; margin-left: 22px; } .help-tab-content li { margin-left: 0; margin-right: 18px; } .contextual-help-sidebar { float: left; padding-right: 12px; padding-left: 8px; } /*------------------------------------------------------------------------------ 7.0 - Main Navigation (Right Menu) (RTL: Left Menu) ------------------------------------------------------------------------------*/ #adminmenuback, #adminmenuwrap { border-width: 0 0 0 1px; } #adminmenushadow { right: auto; left: 0; } #adminmenu li .wp-submenu { left: auto; right: 146px; } .folded #adminmenu .wp-submenu, .folded #adminmenu .wp-has-current-submenu .wp-submenu { left: auto; right: 26px; } #adminmenu .wp-submenu.sub-open, #adminmenu li.focused.wp-not-current-submenu .wp-submenu, .folded #adminmenu li.focused.wp-has-current-submenu .wp-submenu, .folded #adminmenu .wp-has-current-submenu .wp-submenu.sub-open, .no-js #adminmenu .wp-has-submenu:hover .wp-submenu, .no-js.folded #adminmenu .wp-has-current-submenu:hover .wp-submenu { padding: 0 0 8px 8px; } #adminmenu div.wp-menu-image { float: right; } #adminmenu li li { margin-left: 0; margin-right: 8px } #adminmenu .wp-submenu a, #adminmenu li li a, .folded #adminmenu .wp-not-current-submenu li a { padding-left: 0; padding-right: 12px; } #adminmenu .wp-not-current-submenu li a { padding-left: 0; padding-right: 18px; } .folded #adminmenu li li { margin-left: inherit; margin-right: 0 } .folded #adminmenu li li a { padding-left: inherit; padding-right: 0 } .wp-menu-arrow { right: 0; -moz-transform: translate( -139px ); -webkit-transform: translate( -139px ); -o-transform: translate( -139px ); -ms-transform: translate( -139px ); transform: translate( -139px ); } .ie8 .wp-menu-arrow { right: -20px; } #adminmenu .wp-menu-arrow div { left: -8px; width: 16px; } #adminmenu li.wp-not-current-submenu .wp-menu-arrow { -moz-transform: translate( -138px ); -webkit-transform: translate( -138px ); -o-transform: translate( -138px ); -ms-transform: translate( -138px ); transform: translate( -138px ); } .folded .wp-menu-arrow { -moz-transform: translate( -27px ); -webkit-transform: translate( -27px ); -o-transform: translate( -27px ); -ms-transform: translate( -27px ); transform: translate( -27px ); } #adminmenu .wp-not-current-submenu .wp-menu-arrow div { border-style: solid solid none none; border-width: 1px 1px 0 0; } #adminmenu .wp-menu-image img { float: right; padding: 5px 2px 0 0; } #adminmenu .wp-submenu .wp-submenu-head { padding: 6px 10px 5px 4px; } #adminmenu li .wp-submenu-wrap { border-width: 1px 0 1px 1px; border-style: solid none solid solid; -webkit-border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 3px; -webkit-border-top-right-radius: 0; -webkit-border-top-left-radius: 3px; border-bottom-right-radius: 0; border-bottom-left-radius: 3px; border-top-right-radius: 0; border-top-left-radius: 3px; } .folded #adminmenu .wp-submenu ul { border-width: 0 1px 0 0; } .folded #adminmenu .wp-submenu a { padding-left: 0; padding-right: 10px; } .folded #adminmenu a.wp-has-submenu { margin-left: 0; margin-right: 40px; } #adminmenu .awaiting-mod, #adminmenu span.update-plugins, #sidemenu li a span.update-plugins { font-family: Tahoma, Arial, sans-serif; margin-left: 0; margin-right: 7px; } #collapse-button { float: right; } /* Auto-folding of the admin menu */ @media only screen and (max-width: 900px) { #adminmenu li .wp-submenu, #adminmenu .wp-has-current-submenu .wp-submenu { left: auto; right: 26px; } #adminmenu li.focused.wp-has-current-submenu .wp-submenu, #adminmenu .wp-has-current-submenu .wp-submenu.sub-open { padding: 0 0 8px 8px; } .folded #adminmenu .wp-not-current-submenu li a { padding-left: 0; padding-right: 12px; } #adminmenu li li, #adminmenu li li a { padding-left: inherit; padding-right: 0 } .wp-menu-arrow { -moz-transform: translate( -27px ); -webkit-transform: translate( -27px ); -o-transform: translate( -27px ); -ms-transform: translate( -27px ); transform: translate( -27px ); } #adminmenu .wp-submenu ul { border-width: 0 1px 0 0; } #adminmenu .wp-submenu a { padding-left: 0; padding-right: 10px; } #adminmenu a.wp-has-submenu { margin-left: 0; margin-right: 40px; } body #wpcontent { margin-left: 0; margin-right: 52px; } body .wp-admin #footer { margin-left: 15px; margin-right: 52px; } } /* List table styles */ .post-com-count-wrapper { font-family: Tahoma, Arial, sans-serif; } .column-response .post-com-count { float: right; margin-right: 0; margin-left: 5px; } .response-links { float: right; } /*------------------------------------------------------------------------------ 8.0 - Layout Blocks ------------------------------------------------------------------------------*/ .widefat th { font-family: Tahoma, Arial, sans-serif; } .widefat td p { margin: 2px 0 0.8em; } .postbox-container { float: right; } .postbox .handlediv { float: left; } /*------------------------------------------------------------------------------ 9.0 - Dashboard ------------------------------------------------------------------------------*/ #the-comment-list p.comment-author img { float: right; margin-right: 0; margin-left: 8px; } /* Browser Nag */ #dashboard_browser_nag p.browser-update-nag.has-browser-icon { padding-right: 0; padding-left: 125px; } .welcome-panel .welcome-panel-close { right: auto; left: 10px; } .welcome-panel .welcome-panel-close:before { left: auto; right: -12px; } .welcome-panel .wp-badge { float: right; } .welcome-panel-content .about-description, .welcome-panel h3 { margin-left: 0; margin-right: 190px; } .welcome-panel .welcome-panel-column { margin: 0 -25px 0 5%; padding-left: 0; padding-right: 25px; float: right; } .welcome-panel .welcome-panel-column.welcome-panel-last { margin-right: auto; padding-right: 0; margin-left: 0; } .welcome-panel h4 .icon16 { margin-left: 0; margin-right: -32px; } .welcome-panel .welcome-panel-column-container { padding: 0 25px 0 0; } .welcome-panel .welcome-panel-column ul { margin: 1.6em 1.3em 1em 1em; } .welcome-panel .welcome-panel-column li { padding-left: 0; padding-right: 2px; } /*------------------------------------------------------------------------------ 10.0 - List Posts (/Pages/etc) ------------------------------------------------------------------------------*/ .fixed .column-comments { text-align: right; } .fixed .column-comments .vers { padding-left: 0; padding-right: 3px; } .fixed .column-comments a { float: right; } .sorting-indicator { margin-left: 0; margin-right: 7px; } th.sortable a span, th.sorted a span { float: right; } /* Bulk Actions */ .tablenav-pages a { margin-right: 0; margin-left: 1px; } .tablenav-pages .next-page { margin-left: 0; margin-right: 2px; } .tablenav a.button-secondary { margin: 3px 0 0 8px; } .tablenav .tablenav-pages { float: left; } .tablenav .displaying-num { margin-right: 0; margin-left: 10px; font-family: Tahoma, Arial, sans-serif; font-style: normal; } .tablenav .actions { padding: 2px 0 0 8px; } .tablenav .delete { margin-right: 0; margin-left: 20px; } .view-switch { float: left; } .filter { float: right; margin: -5px 10px 0 0; } .filter .subsubsub { margin-left: 0; margin-right: -10px; } #posts-filter fieldset { float: right; margin: 0 0 1em 1.5ex; } #posts-filter fieldset legend { padding: 0 1px .2em 0; } /*------------------------------------------------------------------------------ 10.1 - Inline Editing ------------------------------------------------------------------------------*/ #wpbody-content .inline-edit-row fieldset { float: right; } #wpbody-content .quick-edit-row-page fieldset.inline-edit-col-right .inline-edit-col { border-width: 0 1px 0 0; } #wpbody-content .bulk-edit-row .inline-edit-col-bottom { float: left; } .inline-edit-row fieldset label span.title { float: right; } .inline-edit-row fieldset label span.input-text-wrap { margin-left: 0; margin-right: 5em; } .quick-edit-row-post fieldset.inline-edit-col-right label span.title { padding-right: 0; padding-left: 0.5em; } #wpbody-content .quick-edit-row fieldset .inline-edit-group label.alignleft:first-child { margin-right: 0; margin-left: 0.5em } /* Styling */ .inline-edit-row fieldset span.title, .inline-edit-row fieldset span.checkbox-title { font-family: Tahoma, Arial, sans-serif; font-style: normal; } .inline-edit-row fieldset .inline-edit-date { float: right; } .inline-edit-row fieldset ul.cat-checklist label, .inline-edit-row .catshow, .inline-edit-row .cathide, .inline-edit-row #bulk-titles div { font-family: Tahoma, Arial, sans-serif; } .quick-edit-row-post fieldset label.inline-edit-status { float: right; } #bulk-titles div a { float: right; margin: 3px -2px 0 3px; overflow: hidden; text-indent: -9999px; } /*------------------------------------------------------------------------------ 11.0 - Write/Edit Post Screen ------------------------------------------------------------------------------*/ /* structural/layout */ #post-body-content { float: right; } #poststuff #post-body.columns-2 { margin-left: 300px; margin-right: 0; } #post-body.columns-2 #postbox-container-1 { float: left; margin-left: -300px; margin-right: 0; } @media only screen and (max-width: 850px) { #wpbody-content #post-body.columns-2 #postbox-container-1 { margin-left: 0; } } #titlediv #title-prompt-text, #wp-fullscreen-title-prompt-text { right:0; } #sample-permalink { direction:ltr; } #sample-permalink #editable-post-name { unicode-bidi:embed; } #wp-fullscreen-title-prompt-text { left: auto; right: 0; } .postarea h3 label { float: right; } .submitbox .submit { text-align: right; } .inside-submitbox #post_status { margin: 2px -2px 2px 0; } .submitbox .submit input { margin-right: 0; margin-left: 4px; } #normal-sortables .postbox .submit { float: left; } .taxonomy div.tabs-panel { margin: 0 125px 0 5px; } #side-sortables .comments-box thead th, #normal-sortables .comments-box thead th { font-style: normal; } #commentsdiv img.waiting { padding-left: 0; padding-right: 5px; } #post-body .add-menu-item-tabs li.tabs { border-width: 1px 1px 1px 0; margin-right: 0; margin-left: -1px; } /* Global classes */ #post-body .tagsdiv #newtag { margin-right: 0; margin-left: 5px; } .autosave-info { padding: 2px 2px 2px 15px; text-align: left; } #post-body .wp_themeSkin .mceStatusbar a.mceResize { background: transparent url(../images/resize-rtl.gif) no-repeat scroll left bottom; cursor: sw-resize; } .curtime #timestamp { background-position: right top; padding-left: 0; padding-right: 18px; } /*------------------------------------------------------------------------------ 11.1 - Custom Fields ------------------------------------------------------------------------------*/ #postcustomstuff table input, #postcustomstuff table select, #postcustomstuff table textarea { margin: 8px 8px 8px 0; } /*------------------------------------------------------------------------------ 11.2 - Post Revisions ------------------------------------------------------------------------------*/ table.diff td, table.diff th { font-family: Consolas, Monaco, monospace; } /*------------------------------------------------------------------------------ 12.0 - Categories ------------------------------------------------------------------------------*/ .category-adder { margin-left: 0; margin-right: 120px; } #post-body ul.add-menu-item-tabs { float: right; text-align: left; /* Negative margin for the sake of those without JS: all tabs display */ margin: 0 5px 0 -120px; } #post-body ul.add-menu-item-tabs li.tabs { -webkit-border-top-left-radius: 0; -webkit-border-top-right-radius: 3px; -webkit-border-bottom-left-radius: 0; -webkit-border-bottom-right-radius: 3px; border-top-left-radius: 0; border-top-right-radius: 3px; border-bottom-left-radius: 0; border-bottom-right-radius: 3px; } #front-page-warning, #front-static-pages ul, ul.export-filters, .inline-editor ul.cat-checklist ul, .categorydiv ul.categorychecklist ul, .customlinkdiv ul.categorychecklist ul, .posttypediv ul.categorychecklist ul, .taxonomydiv ul.categorychecklist ul { margin-left: 0; margin-right: 18px; } #post-body .add-menu-item-tabs li.tabs { border-style: solid solid solid none; border-width: 1px 1px 1px 0; margin-right: 0; margin-left: -1px; } p.help, p.description, span.description, .form-wrap p { font-style: normal; font-family: Tahoma, Arial, sans-serif; } /*------------------------------------------------------------------------------ 13.0 - Tags ------------------------------------------------------------------------------*/ .taghint { margin: 15px 12px -24px 0; } #poststuff .tagsdiv .howto { margin: 0 8px 6px 0; } .ac_results li { text-align: right; } .links-table th { text-align: right; } /*------------------------------------------------------------------------------ 14.0 - Media Screen ------------------------------------------------------------------------------*/ #wpbody-content .describe th { text-align: right; } .describe .media-item-info .A1B1 { padding: 0 10px 0 0; } .media-upload-form td label { margin-left: 6px; margin-right: 2px; } .media-upload-form .align .field label { padding: 0 23px 0 0; margin: 0 3px 0 1em; } .media-upload-form tr.image-size label { margin: 0 5px 0 0; } #wpbody-content .describe p.help { padding: 0 5px 0 0; } .media-item .error-div a.dismiss, .describe-toggle-on, .describe-toggle-off { float: left; margin-right: 0; margin-left: 15px; } .media-item .error-div a.dismiss { padding: 0 15px 0 0; } .media-item .error-div { padding-left: 0; padding-right: 10px; } .media-item .pinkynail { float: right; } .media-item .describe td { padding: 0 0 8px 8px; } .media-item .progress { float: left; margin: 6px 0 0 10px; } /*------------------------------------------------------------------------------ 14.1 - Media Uploader ------------------------------------------------------------------------------*/ #find-posts-response .found-radio { padding: 5px 8px 0 0; } .find-box-search label { padding-right: 0; padding-left: 6px; } .find-box #resize-se { right: auto; left: 1px; } form.upgrade .hint { font-style: normal; } /*------------------------------------------------------------------------------ 14.2 - Image Editor ------------------------------------------------------------------------------*/ .imgedit-menu div { float: right; } .imgedit-help { font-style: normal; } .imgedit-submit-btn { margin-left: 0; margin-right: 20px; } /*------------------------------------------------------------------------------ 15.0 - Comments Screen ------------------------------------------------------------------------------*/ .form-table th { text-align: right; } .form-table input.tog { margin-right: 0; margin-left: 2px; float: right; } .form-table table.color-palette { float: right; } /* reply to comments */ #replysubmit img.waiting, .inline-edit-save img.waiting { float: left; } #replysubmit .button { margin-right: 0; margin-left: 5px; } #edithead .inside { float: right; padding: 3px 5px 2px 0; } .comment-ays th { border-right-style: none; border-left-style: solid; border-right-width: 0; border-left-width: 1px; } .spam-undo-inside .avatar, .trash-undo-inside .avatar { margin-left: 8px; } #comment-status-radio input { margin: 2px 0 5px 3px; } /*------------------------------------------------------------------------------ 16.0 - Themes ------------------------------------------------------------------------------*/ h3.available-themes { float: right; } .available-theme { margin-right: 0; margin-left: 10px; padding: 20px 0 20px 20px; } #current-theme .theme-info li, .theme-options li, .available-theme .action-links li { float: right; padding-right: 0; padding-left: 10px; margin-right: 0; margin-left: 10px; border-right: none; border-left: 1px solid #dfdfdf; } .available-theme .action-links li { padding-left: 8px; margin-left: 8px; } #current-theme .theme-info li:last-child, .theme-options li:last-child, .available-theme .action-links li:last-child { padding-left: 0; margin-right: 0; border-left: 0; } .available-theme .action-links .delete-theme { float: left; margin-left: 0; margin-right: 8px; } .available-theme .action-links p { float: right; } #current-theme.has-screenshot { padding-left: 0; padding-right: 330px; } #current-theme h4 span { margin-left: 0; margin-right: 20px; } #current-theme img { float: right; width: 300px; margin-left: 0; margin-right: -330px; } .theme-options .load-customize { margin-right: 0; margin-left: 30px; float: right; } .theme-options span { float: right; margin-right: 0; margin-left: 10px; } .theme-options ul { float: right; } /* Allow for three-up on 1024px wide screens, e.g. tablets */ @media only screen and (max-width: 1200px) { #current-theme.has-screenshot { padding-right: 270px; } #current-theme img { margin-right: -270px; width: 240px; } } #broken-themes { text-align: right; } /*------------------------------------------------------------------------------ 16.1 - Custom Header Screen ------------------------------------------------------------------------------*/ .appearance_page_custom-header .available-headers .default-header { float: right; margin: 0 0 20px 20px; } .appearance_page_custom-header .random-header { margin: 0 0 20px 20px; } .appearance_page_custom-header .available-headers label input, .appearance_page_custom-header .random-header label input { margin-right: 0; margin-left: 10px; } /*------------------------------------------------------------------------------ 16.2 - Custom Background Screen ------------------------------------------------------------------------------*/ /* No RTL for now, this space intentionally left blank */ /*------------------------------------------------------------------------------ 16.3 - Tabbed Admin Screen Interface (Experimental) ------------------------------------------------------------------------------*/ .nav-tab { margin: 0 0 -1px 6px; } h2 .nav-tab { font-family: Tahoma, Arial, sans-serif; } /*------------------------------------------------------------------------------ 17.0 - Plugins ------------------------------------------------------------------------------*/ .plugins .desc ul, .plugins .desc ol { margin: 0 2em 0 0; } #wpbody-content .plugins .plugin-title, #wpbody-content .plugins .theme-title { padding-right: 0; padding-left: 12px; } /*------------------------------------------------------------------------------ 18.0 - Users ------------------------------------------------------------------------------*/ #profile-page .form-table #rich_editing { margin-right: 0; margin-left: 5px } #profile-page #pass1, #profile-page #pass2, #profile-page #user_login { direction: ltr; } #your-profile legend { font-family: Tahoma, Arial, sans-serif; } /*------------------------------------------------------------------------------ 19.0 - Tools ------------------------------------------------------------------------------*/ .pressthis a span { background-position: right 5px; padding: 8px 27px 8px 11px; } .pressthis a:after { right: auto; left: 10px; background: transparent; transform: skew(-20deg) rotate(-6deg); -webkit-transform: skew(-20deg) rotate(-6deg); -moz-transform: skew(-20deg) rotate(-6deg); } .pressthis a:hover:after { transform: skew(-20deg) rotate(-9deg); -webkit-transform: skew(-20deg) rotate(-9deg); -moz-transform: skew(-20deg) rotate(-9deg); } /*------------------------------------------------------------------------------ 20.0 - Settings ------------------------------------------------------------------------------*/ #utc-time, #local-time { padding-left: 0; padding-right: 25px; font-style: normal; font-family: Tahoma, Arial, sans-serif; } /*------------------------------------------------------------------------------ 21.0 - Admin Footer ------------------------------------------------------------------------------*/ #footer { margin-left: 20px; } #wpcontent, #footer { margin-right: 165px; } /*------------------------------------------------------------------------------ 22.0 - About Pages ------------------------------------------------------------------------------*/ .wrap.about-wrap { margin-left: 40px; margin-right: 20px; } .about-wrap h1, .about-text { margin-right: 0; margin-left: 200px; } .about-wrap h2.nav-tab-wrapper { padding-left: 0px; padding-right: 6px; } .about-wrap .wp-badge { right: auto; left: 0; } .about-wrap h2 .nav-tab { margin-right: 0; margin-left: 3px; } .about-wrap .changelog li { margin-left: 0; margin-right: 3em; } .about-wrap .three-col-images .last-feature { float: left; } .about-wrap .three-col-images .first-feature { float: right; } .about-wrap .feature-section.three-col div { margin-right: 0; margin-left: 4.999999999%; float: right; } .about-wrap .feature-section.three-col h4 { text-align: right; } .about-wrap .feature-section.three-col img { margin-right: 5px; margin-left: 0; } .about-wrap .feature-section.three-col .last-feature { margin-left: 0; } .about-wrap .feature-section img { margin: 0 0 10px 0.7%; } .about-wrap .feature-section.images-stagger-right img { float: left; margin: 0 12px 12px 5px; } .about-wrap .feature-section.images-stagger-left img { float: right; margin: 0 5px 12px 12px; } .about-wrap li.wp-person, .about-wrap li.wp-person img.gravatar { float: right; margin-right: 0; margin-left: 10px; } /*------------------------------------------------------------------------------ 23.0 - Misc ------------------------------------------------------------------------------*/ #template div { margin-right: 0; margin-left: 190px; } .column-author img, .column-username img { float: right; margin-right: 0; margin-left: 10px; } .tagchecklist { margin-left: 0; margin-right: 14px; } .tagchecklist strong { margin-left: 0; margin-right: -8px; } .tagchecklist span { margin-right: 0; margin-left: 25px; float: right; } .tagchecklist span a { margin: 6px -9px 0pt 0pt; float: right; } #poststuff h2 { clear: right; } #poststuff h3, .metabox-holder h3 { font-family: Tahoma, Arial, sans-serif; } .tool-box .title { font-family: Tahoma, Arial, sans-serif; } #sidemenu { margin: -30px 315px 0 15px; float: left; padding-left: 0; padding-right: 10px; } #sidemenu a { float: right; } table .vers, table .column-visible, table .column-rating { text-align: right; } .screen-meta-toggle { right: auto; left: 15px; } /*------------------------------------------------------------------------------ 24.0 - Dead ------------------------------------------------------------------------------*/ /* - Not used anywhere in WordPress - verify and then deprecate ------------------------------------------------------------------------------*/ /* No RTL for now, this space intentionally left blank */ /* - Only used once or twice in all of WP - deprecate for global style ------------------------------------------------------------------------------*/ * html #template div {margin-left: 0;} .list-ajax-loading { float: left; margin-right: 0; margin-left: 9px; } /* - Used - but could/should be deprecated with a CSS reset ------------------------------------------------------------------------------*/ /* No RTL for now, this space intentionally left blank */ /*------------------------------------------------------------------------------ 25.0 - TinyMCE tweaks Small tweaks for until tinymce css files are proprely RTLized ------------------------------------------------------------------------------*/ #editorcontainer .wp_themeSkin .mceStatusbar { padding-left: 0; padding-right: 5px; } #editorcontainer .wp_themeSkin .mceStatusbar div { float: right; } #editorcontainer .wp_themeSkin .mceStatusbar a.mceResize { float: left; } /*------------------------------------------------------------------------------ 26.0 - Full Overlay w/ Sidebar ------------------------------------------------------------------------------*/ .wp-full-overlay .wp-full-overlay-sidebar { margin: 0; left: auto; right: 0; border-right: 0; border-left: 1px solid rgba( 0, 0, 0, 0.2 ); } .wp-full-overlay-sidebar:after { right: auto; left: 0; box-shadow: inset 5px 0 4px -4px rgba(0, 0, 0, 0.1); } .wp-full-overlay.collapsed, .wp-full-overlay.expanded .wp-full-overlay-sidebar { margin-right: 0 !important; } .wp-full-overlay.expanded { margin-right: 300px; margin-left: 0; } .wp-full-overlay.collapsed .wp-full-overlay-sidebar { margin-right: -300px; margin-left: 0; } /* Collapse Button */ .wp-full-overlay .collapse-sidebar { right: 0; left: auto; margin-right: 15px; } .wp-full-overlay.collapsed .collapse-sidebar { right: 100%; } .wp-full-overlay .collapse-sidebar-arrow { margin-right: 2px; margin-left: 0; background: transparent url('../../wp-admin/images/arrows.png') no-repeat 0 -108px; } .wp-full-overlay.collapsed .collapse-sidebar-arrow { background-position: 0 -72px; } .wp-full-overlay .collapse-sidebar-label { right: 100%; left: auto; margin-right: 10px; margin-left: 0; } /*------------------------------------------------------------------------------ 27.0 - Customize Loader ------------------------------------------------------------------------------*/ .install-theme-info .theme-install { float: left; } /* MERGED */ /* global */ /* 2 column liquid layout */ #wpcontent { margin-left: 0; margin-right: 165px; } .folded #wpcontent { margin-left: 0; margin-right: 52px; } .folded.wp-admin #footer { margin-left: 15px; margin-right: 52px; } #wpbody-content { float: right; } #adminmenuwrap { float: right; } #adminmenu { clear: right; } /* inner 2 column liquid layout */ .inner-sidebar { float: left; clear: left; } .has-right-sidebar #post-body { float: right; clear: right; margin-right: 0; margin-left: -340px; } .has-right-sidebar #post-body-content { margin-right: 0; margin-left: 300px; } /* 2 columns main area */ #col-right { float: left; clear: left; } /* utility classes*/ .alignleft { float: right; } .alignright { float: left; } .textleft { text-align: right; } .textright { text-align: left; } /* styles for use by people extending the WordPress interface */ body, td, textarea, input, select { font-family: Tahoma, Arial, sans-serif; } ul.ul-disc, ul.ul-square, ol.ol-decimal { margin-left: 0; margin-right: 1.8em; } .subsubsub { float: right; } .widefat thead th:first-of-type { -webkit-border-top-left-radius: 0; -webkit-border-top-right-radius: 3px; border-top-left-radius: 0; border-top-right-radius: 3px; } .widefat thead th:last-of-type { -webkit-border-top-right-radius: 0; -webkit-border-top-left-radius: 3px; border-top-right-radius: 0; border-top-left-radius: 3px; } .widefat tfoot th:first-of-type { -webkit-border-bottom-left-radius: 0; -webkit-border-bottom-right-radius: 3px; border-bottom-left-radius: 0; border-bottom-right-radius: 3px; } .widefat tfoot th:last-of-type { -webkit-border-bottom-right-radius: 0; -webkit-border-bottom-left-radius: 3px; border-bottom-right-radius: 0; border-bottom-left-radius: 3px; } .widefat th { text-align: right; } .widefat th input { margin: 0 8px 0 0; } .wrap { margin-right: 0; margin-left: 15px; } .wrap h2, .subtitle { font-family: Tahoma, Arial, sans-serif; } .wrap h2 { padding-right: 0; padding-left: 15px; } .subtitle { padding-left: 0; padding-right: 25px; } .wrap .add-new-h2 { font-family: Tahoma, Arial, sans-serif; margin-left: 0; margin-right: 4px; } .wrap h2.long-header { padding-left: 0; } /* dashboard */ #dashboard-widgets-wrap .has-sidebar { margin-right: 0; margin-left: -51%; } #dashboard-widgets-wrap .has-sidebar .has-sidebar-content { margin-right: 0; margin-left: 51%; } .view-all { right: auto; left: 0; } #dashboard_right_now p.sub, #dashboard-widgets h4, a.rsswidget, #dashboard_plugins h4, #dashboard_plugins h5, #dashboard_recent_comments .comment-meta .approve, #dashboard_right_now td.b, #dashboard_right_now .versions a { font-family: Tahoma, Arial, sans-serif; } #dashboard_right_now p.sub { left:auto; right:15px; } #dashboard_right_now td.b { padding-right: 0; padding-left: 6px; text-align: left; } #dashboard_right_now .t { padding-right: 0; padding-left: 12px; } #dashboard_right_now .table_content { float:right; } #dashboard_right_now .table_discussion { float:left; } #dashboard_right_now a.button { float: left; clear: left; } #dashboard_plugins .inside span { padding-left: 0; padding-right: 5px; } #dashboard-widgets h3 .postbox-title-action { right: auto; left: 30px; } #the-comment-list .pingback { padding-left: 0 !important; padding-right: 9px !important; } /* Recent Comments */ #the-comment-list .comment-item { padding: 1em 70px 1em 10px; } #the-comment-list .comment-item .avatar { float: right; margin-left: 0; margin-right: -60px; } /* Feeds */ .rss-widget cite { text-align: left; } .rss-widget span.rss-date { font-family: Tahoma, Arial, sans-serif; margin-left: 0; margin-right: 3px; } /* QuickPress */ #dashboard_quick_press h4 { float: right; text-align: left; } #dashboard_quick_press .wp-media-buttons { margin: 0 5em 0.5em 0; } #dashboard_quick_press h4 label { margin-right: 0; margin-left: 10px; } #dashboard_quick_press .input-text-wrap, #dashboard_quick_press .textarea-wrap { margin: 0 5em 1em 0; } #dashboard_quick_press #media-buttons { margin: 0 5em .5em 0; padding: 0; } #dashboard-widgets #dashboard_quick_press form p.submit { margin-left: 0; margin-right: 4.6em; } #dashboard-widgets #dashboard_quick_press form p.submit input { float: right; } #dashboard-widgets #dashboard_quick_press form p.submit #save-post { margin: 0 10px 0 1em; } #dashboard-widgets #dashboard_quick_press form p.submit #publish { float: left; } #dashboard-widgets #dashboard_quick_press form p.submit img.waiting { margin: 4px 0 0 6px; } /* Recent Drafts */ #dashboard_recent_drafts h4 abbr { font-family: Tahoma, Arial, sans-serif; margin-left:0; margin-right: 3px; } /* login */ body.login { font-family: Tahoma, Arial, sans-serif; } .login form { margin-right: 8px; margin-left: 0; } .login form .forgetmenot { float: right; } .login form .submit { float: left; } #login form .submit input { font-family: Tahoma, Arial, sans-serif; } .login #nav, .login #backtoblog { margin: 0 16px 0 0; } #login_error, .login .message { margin: 0 8px 16px 0; } .login #user_pass, .login #user_login, .login #user_email { margin-left: 6px; margin-right: 0; direction: ltr; } .login h1 a { text-decoration: none; } .login .button-primary { float: left; } /* nav-menu */ #nav-menus-frame { margin-right: 300px; margin-left: 0; } #wpbody-content #menu-settings-column { margin-right: -300px; margin-left: 0; float: right; } /* Menu Container */ #menu-management-liquid { float: right; } #menu-management { margin-left: 20px; margin-right: 0; } .post-body-plain { padding: 10px 0 0 10px; } /* Menu Tabs */ #menu-management .nav-tabs-arrow-left { right: 0; left:auto; } #menu-management .nav-tabs-arrow-right { left: 0; right:auto; text-align: left; font-family: Tahoma, Arial, sans-serif; } #menu-management .nav-tabs { padding-right: 20px; padding-left: 10px; } .js #menu-management .nav-tabs { float: right; margin-right: 0px; margin-left: -400px; } #select-nav-menu-container { text-align: left; } #wpbody .open-label { float:right; } #wpbody .open-label span { padding-left: 10px; padding-right:0; } .js .input-with-default-title { font-style: normal; font-weight: bold; } /* Add Menu Item Boxes */ .postbox .howto input { float: left; } #nav-menu-theme-locations .button-controls { text-align: left; } /* Button Primary Actions */ .meta-sep, .submitcancel { float: right; } #cancel-save { margin-left: 0; margin-right: 20px; } /* Button Secondary Actions */ .list-controls { float: right; } .add-to-menu { float: left; } /* Custom Links */ #add-custom-link label span { float: right; padding-left: 5px; padding-right: 0; } .nav-menus-php .howto span { float: right; } .list li .menu-item-title input { margin-left: 3px; margin-right: 0; } /* Nav Menu */ .menu-item-handle { padding-right: 10px; padding-left: 0; } .menu-item-edit-active .menu-item-handle { -webkit-border-bottom-left-radius: 0; -webkit-border-bottom-right-radius: 0; border-bottom-left-radius: 0; border-bottom-right-radius: 0; } .menu-item-handle .item-title { margin-left:13em; margin-right:0; } .menu-item-handle .item-edit { right: auto; left: -20px; } /* WARNING: The factor of 30px is hardcoded into the nav-menus javascript. */ .menu-item-depth-0 { margin-right: 0px; margin-left:0;} .menu-item-depth-1 { margin-right: 30px; margin-left:0;} .menu-item-depth-2 { margin-right: 60px; margin-left:0;} .menu-item-depth-3 { margin-right: 90px; margin-left:0;} .menu-item-depth-4 { margin-right: 120px; margin-left:0;} .menu-item-depth-5 { margin-right: 150px; margin-left:0;} .menu-item-depth-6 { margin-right: 180px; margin-left:0;} .menu-item-depth-7 { margin-right: 210px; margin-left:0;} .menu-item-depth-8 { margin-right: 240px; margin-left:0;} .menu-item-depth-9 { margin-right: 270px; margin-left:0;} .menu-item-depth-10 { margin-right: 300px; margin-left:0;} .menu-item-depth-11 { margin-right: 330px; margin-left:0;} .menu-item-depth-0 .menu-item-transport { margin-right: 0px; margin-left:0;} .menu-item-depth-1 .menu-item-transport { margin-right: -30px; margin-left:0;} .menu-item-depth-2 .menu-item-transport { margin-right: -60px; margin-left:0;} .menu-item-depth-3 .menu-item-transport { margin-right: -90px; margin-left:0;} .menu-item-depth-4 .menu-item-transport { margin-right: -120px; margin-left:0;} .menu-item-depth-5 .menu-item-transport { margin-right: -150px; margin-left:0;} .menu-item-depth-6 .menu-item-transport { margin-right: -180px; margin-left:0;} .menu-item-depth-7 .menu-item-transport { margin-right: -210px; margin-left:0;} .menu-item-depth-8 .menu-item-transport { margin-right: -240px; margin-left:0;} .menu-item-depth-9 .menu-item-transport { margin-right: -270px; margin-left:0;} .menu-item-depth-10 .menu-item-transport { margin-right: -300px; margin-left:0;} .menu-item-depth-11 .menu-item-transport { margin-right: -330px; margin-left:0;} /* Menu item controls */ .item-type { padding-left: 10px; padding-right:0; } .item-controls { left: 20px; right: auto; } .item-controls .item-order { padding-left: 10px; padding-right: 0; } .item-edit { left: -20px; right:auto; -webkit-border-bottom-right-radius: 3px; -webkit-border-bottom-left-radius: 0; border-bottom-right-radius: 3px; border-bottom-left-radius: 0; } /* Menu editing */ .menu-item-settings { padding: 10px 10px 10px 0; border-width: 0 1px 1px 1px; } #custom-menu-item-url { direction: ltr; } .link-to-original { font-style: normal; font-weight: bold; } .link-to-original a { padding-right: 4px; padding-left:0; } .menu-item-settings .description-thin, .menu-item-settings .description-wide { margin-left: 10px; margin-right:0; float: right; } /* Major/minor publishing actions (classes) */ .major-publishing-actions .publishing-action { text-align: left; float: left; } .major-publishing-actions .delete-action { text-align: right; float: right; padding-left: 15px; padding-right:0; } .menu-name-label { margin-left: 15px; margin-right:0; } .auto-add-pages { float: right; } /* Star ratings */ div.star-holder { background: url('../images/stars-rtl.png?ver=20120506.png') repeat-x bottom right; } div.star-holder .star-rating { background: url('../images/stars-rtl.png?ver=20120506.png') repeat-x top right; float: right; } #plugin-information ul#sidemenu { left: auto; right: 0; } #plugin-information h2 { margin-right: 0; margin-left: 200px; } #plugin-information .fyi { margin-left: 5px; margin-right: 20px; } #plugin-information .fyi h2 { margin-left: 0; } #plugin-information .fyi ul { padding: 10px 7px 10px 5px; } #plugin-information #section-screenshots li p { padding-left: 0; padding-right: 20px; } #plugin-information #section-screenshots ol, #plugin-information .updated, #plugin-information pre { margin-right: 0; margin-left: 215px; } #plugin-information .updated, #plugin-information .error { clear: none; direction: rtl; } #plugin-information #section-holder .section { direction: ltr; } /* Editor/Main Column */ .posting { margin-left: 212px; margin-right: 0; position: relative; } h3.tb { margin-left: 0; margin-right: 5px; } #publish { float: left; } .postbox .handlediv { float: left; } .actions li { float: right; margin-right: 0; margin-left: 10px; } #extra-fields .actions { margin: -23px 0 0 -7px; } /* Photo Styles */ #img_container a { float: right; } #category-add input, #category-add select { font-family: Tahoma, Arial, sans-serif; } /* Tags */ #tagsdiv #newtag { margin-right: 0; margin-left: 5px; } #tagadd { margin-left: 0; margin-right: 3px; } #tagchecklist span { margin-left: .5em; margin-right: 10px; float: right; } #tagchecklist span a { margin: 6px -9px 0 0; float: right; } .submit input, .button, .button-primary, .button-secondary, .button-highlighted, #postcustomstuff .submit input { font-family: Tahoma, Arial, sans-serif; } .ac_results li { text-align: right; } #TB_ajaxContent #options { right: auto; left: 25px; } #post_status { margin-left: 0; margin-right: 10px; } /* theme-editor, plugin-editor */ #templateside { float: left; } #template textarea, #docs-list { direction: ltr; } /* theme-install */ .theme-details .theme-version { float: right; } .theme-details .star-holder { float: left; } .feature-filter .feature-group { float: right; } .feature-filter .feature-name { float: right; text-align: left; } .feature-filter .feature-group li { float: right; padding-right: 0; padding-left: 25px; } /* widgets */ /* 2 column liquid layout */ div.widget-liquid-left { float: right; clear: right; margin-right: 0; margin-left: -325px; } div#widgets-left { margin-right: 5px; margin-left: 325px; } div.widget-liquid-right { float: left; clear: left; } .inactive-sidebar .widget { float: right; } div.sidebar-name h3 { font-family: Tahoma, Arial, sans-serif; } #widget-list .widget { float: right; } .inactive-sidebar .widget-placeholder { float: right; } .widget-top .widget-title-action { float: left; } .widget-control-edit { padding: 0 0 0 8px; } .sidebar-name-arrow { float: left; } /* Press This */ .press-this-sidebar { float: left; } .press-this #header-logo, .press-this #wphead h1 { float: right; } /* RTL */ .ltr { direction: ltr; } /* =Localized CSS -------------------------------------------------------------- */ /* he_IL: Remove Tahoma from the font stack. Arial is best for Hebrew. */ body.locale-he-il, .locale-he-il .quicktags, .locale-he-il .search, .locale-he-il .howto, .locale-he-il #adminmenu .awaiting-mod, .locale-he-il #adminmenu span.update-plugins, .locale-he-il #sidemenu li a span.update-plugins, .locale-he-il .post-com-count-wrapper, .locale-he-il .widefat th, .locale-he-il .tablenav .displaying-num, .locale-he-il .inline-edit-row fieldset span.title, .locale-he-il .inline-edit-row fieldset span.checkbox-title, .locale-he-il .inline-edit-row fieldset ul.cat-checklist label, .locale-he-il .inline-edit-row .catshow, .locale-he-il .inline-edit-row .cathide, .locale-he-il .inline-edit-row #bulk-titles div, .locale-he-il p.help, .locale-he-il p.description, .locale-he-il span.description, .locale-he-il .form-wrap p, .locale-he-il h2 .nav-tab, .locale-he-il #your-profile legend, .locale-he-il #utc-time, .locale-he-il #local-time, .locale-he-il #poststuff h3, .locale-he-il .metabox-holder h3, .locale-he-il .tool-box .title, .locale-he-il td, .locale-he-il textarea, .locale-he-il input, .locale-he-il select, .locale-he-il .wrap h2, .locale-he-il .subtitle, .locale-he-il .wrap .add-new-h2, .locale-he-il #dashboard_right_now p.sub, .locale-he-il #dashboard-widgets h4, .locale-he-il a.rsswidget, .locale-he-il #dashboard_plugins h4, .locale-he-il #dashboard_plugins h5, .locale-he-il #dashboard_recent_comments .comment-meta .approve, .locale-he-il #dashboard_right_now td.b, .locale-he-il #dashboard_right_now .versions a, .locale-he-il .rss-widget span.rss-date, .locale-he-il #dashboard_recent_drafts h4 abbr, body.login.locale-he-il, .locale-he-il #login form .submit input, .locale-he-il #menu-management .nav-tabs-arrow-right, .locale-he-il #category-add input, .locale-he-il #category-add select, .locale-he-il .submit input, .locale-he-il .button, .locale-he-il .button-primary, .locale-he-il .button-secondary, .locale-he-il .button-highlighted, .locale-he-il #postcustomstuff .submit input, .locale-he-il div.sidebar-name h3 { font-family: Arial, sans-serif; } /* he_IL: Have <em> be bold rather than italic. */ .locale-he-il em { font-style: normal; font-weight: bold; }
maintainweb/maintainweb
wp-admin/css/wp-admin-rtl.dev.css
CSS
gpl-2.0
47,218
using Artworks.Container.Interceptors.InterceptionBehaviors; using Artworks.Log; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Artworks.Examples.Codes.Application.Code.Behaviors { /// <summary> /// 日志 /// </summary> public class LogAttribute : InterceptionBehaviorAttribute { public override void BeginInvoke(InterceptionBehaviorContext context) { LogHelper.Debug(string.Format(" BeginInvoke {0}", context.MethodInfo.Name)); } public override void EndInvoke(InterceptionBehaviorContext context) { LogHelper.Debug(string.Format(" EndInvoke {0}", context.MethodInfo.Name)); } public override void ExceptionInvoke(ExceptionInterceptionBehaviorContext context) { LogHelper.Debug(string.Format(" ExceptionInvoke {0} Message : {1}", context.MethodInfo.Name, context.Exception.Message)); } } }
cuicq/Artworks
src/Artworks.Examples/Codes/Application/Code/Behaviors/LogAttribute.cs
C#
gpl-2.0
1,013
-- DB/SPELL RANKS: Fix all errors with spell ranks on start up -- Bear Form (Passive) rank 2 is not more need it on Cataclyms (http://www.wowhead.com/spell=1178) -- When spell only have a rank don't need to be present on spell_ranks, so delted DELETE FROM `spell_ranks` WHERE `first_spell_id` IN ('1178');
avalonfr/ArkCORE-4.3.4
sql/old_updates_406a/world/already_applied/11_12_21_04_World_spell_ranks.sql
SQL
gpl-2.0
305
import greengraph if __name__ == '__main__': from matplotlib import pyplot as plt mygraph = greengraph.Greengraph('New York','Chicago') data = mygraph.green_between(20) plt.plot(data) plt.show()
padraic-padraic/MPHYSG001_CW1
example.py
Python
gpl-2.0
216
package mg.egg.eggc.compiler.libegg.base; import mg.egg.eggc.compiler.libegg.type.Resolveur; public interface IAction { // la position dans la règle public int getPos(); public BLOC getBloc(); public String getCode(); public Resolveur getResolveur(); public void setCode(String c); public void maj_code(String code); /* * meta fonctions pour générer du code source */ // début d'action public String mkStart(); // fin d'action public String mkEnd(); // début des locales public String mkStartLocs(); // déclaration d'une locale public String mkLoc(ENTREE e); // affectation public String mkCopy(ENTREE e1, ENTREE e2); // début des instructions public String mkStartInsts(); // fin des instructions public String mkEndInsts(); // commentaire public String mkComment(String com); // appel de procedure public String mkCall(); // début de if public String mkStartIf(); // début de else d'un if public String mkElseIf(); // début de elsif d'un if public String mkElsifIf(); // fin d'un if public String mkEndIf(); // début d'un match public String mkStartMatch(); // cas d'un match public String mkWithMatch(); // else d'un match public String mkElseMatch(); // fin d'un match public String mkEndMatch(); // accès à un attribut de la premiere occurence public ENTREE mkAtt(String non_terminal, ATTRIBUT att); // accès à un attribut de la i+1eme occurence public ENTREE mkAtt(String non_terminal, int i, ATTRIBUT att); // accès à un attribut de la premiere occurence (sans specification du type) public ENTREE mkAtt(String nom, String string); // accès à un attribut de la i+1eme occurence (sans specification du type) public ENTREE mkAtt(String non_terminal, int i, String att); }
arthaud/egg
src/mg/egg/eggc/compiler/libegg/base/IAction.java
Java
gpl-2.0
1,779
# daisyworld [![Build Status](https://travis-ci.org/ogruen/daisyworld.svg)](https://travis-ci.org/ogruen/daisyworld) Implementation of daisyworld by Lovelock and Watson and a spatial grid based approach using C++. ### Compile and run Clone the repo, you will find a directory code/cc with a Makefile. A gcc compiler is needed. I am using Linux, maybe Windows needs more configuration. I suggest Cygwin to get it running. ``` cd code/cc make ./Simulation ``` The simulation writes data to folder /data/raw/. The data format is tab-separated values so it should be easy to plot it with your favourite plotting tool. I used Gnuplot, Version 4.4 patchlevel 3. You can find the Gnuplot script in folder /plots/plotit.gp. Run it with the command load './plotit.gp' in gnuplot. It creates plots and saves the images to /plots/exploratory/ The main function found in Simulation.cc is fairly simple. It uses one of three implemented methods: - SimpleGrowth: Simple cellular automata model. If a cell has daisies in its neighbourhood, a daisy is grown at cell. - DaisyworldClassic: vanilla daisyworld using the formulas and descriptions found in the references below (data exported to data_rule2.txt) - DaisyworldCA: Grid based daisyworld. Daisies now cover a grid and spread to neighbour cells (data exported to data_rule3.txt) For a SDL visualization of the environment growing daisies over time, check out branch daisyworld_sdl. You'll need SDL2 to compile it as well as SDL2_image and SDL2_gfxPrimitives. In case your distribution doesn't provide gfxPrimitives, you can find it here: http://cms.ferzkopp.net/index.php/software/13-sdl-gfx Feel free to send me suggestions, ideas, bugs via pull request or email. Issue tracker ============= GitHub Issue Tracker is used. You'll find planned features and known bugs there. Thanks ====== - Tyler Streeter for creating and sharing his unit testing framework QuickTest (http://quicktest.sourceforge.net/) - John Snow, Dave Bice and all the other people who wrote articles and explanations of daisyworld and shared them. References =========== @article{daisy1983, author = {Watson J., Andrew and Lovelock, James E.}, title = {Biological homeostasis of the global environment: The parable of Daisyworld.}, journal = {Tellus}, volume = {35B}, year = {1983}, pages = {286--289}, } @misc{Snow2005, author = {Snow T., John}, title = {A PARABLE ABOUT A PLANETARY SYSTEM: Watson and Lovelock's Daisy World}, year = {2005}, HOWPUBLISHED = {\url{http://eo.ucar.edu/staff/dward/carbon/jt_snow/Daisyworld/DAISY_WORLD_MODELS.html}}, note = {last visited: 29.03.2014} } @misc{sdaisy1, AUTHOR = {Bice, Dave}, TITLE = {Modeling Daisyworld}, YEAR = {2009}, HOWPUBLISHED = {\url{http://www3.geosc.psu.edu/~dmb53/DaveSTELLA/Daisyworld/daisyworld_model.htm}}, note = {last visited: 29.03.2014} }
ogruen/daisyworld
README.md
Markdown
gpl-2.0
2,904
'use strict'; const mongoose = require('mongoose'); const Promise = require('bluebird'); mongoose.Promise = Promise; mongoose.connect('mongodb://192.168.132.129/test'); const Schema = mongoose.Schema; const schema = new Schema({ name: { type: String }, val: {type: Number}, user: {type: String} }); let InCode = mongoose.model('InCodeSchema', schema); let task = Promise.coroutine(function* () { yield InCode.remove(); yield InCode.create({ name: 'dd', val: 100, user: 'dd' }); let entry = yield InCode.findOne({name: 'dd'}).exec(); console.log(entry); for (let i = 0; i< 10; i++) { yield InCode.update({}, {$set: {val: 1}}); let entry = yield InCode.findOne().exec(); console.log(`${i} entry:${entry.__v}`); } }) task().then((r) => { console.log(r) })
gensmusic/test
third_party/nodejs/third-party/mongoose/__v.js
JavaScript
gpl-2.0
806
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD 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. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file economy.cpp Handling of the economy. */ #include "stdafx.h" #include "company_func.h" #include "command_func.h" #include "industry.h" #include "town.h" #include "news_func.h" #include "network/network.h" #include "network/network_func.h" #include "ai/ai.hpp" #include "aircraft.h" #include "train.h" #include "newgrf_engine.h" #include "engine_base.h" #include "ground_vehicle.hpp" #include "newgrf_cargo.h" #include "newgrf_sound.h" #include "newgrf_industrytiles.h" #include "newgrf_station.h" #include "newgrf_airporttiles.h" #include "object.h" #include "strings_func.h" #include "date_func.h" #include "vehicle_func.h" #include "sound_func.h" #include "autoreplace_func.h" #include "company_gui.h" #include "signs_base.h" #include "subsidy_base.h" #include "subsidy_func.h" #include "station_base.h" #include "waypoint_base.h" #include "economy_base.h" #include "core/pool_func.hpp" #include "core/backup_type.hpp" #include "cargo_type.h" #include "water.h" #include "game/game.hpp" #include "cargomonitor.h" #include "goal_base.h" #include "story_base.h" #include "linkgraph/refresh.h" #include "table/strings.h" #include "table/pricebase.h" #include "safeguards.h" /* Initialize the cargo payment-pool */ CargoPaymentPool _cargo_payment_pool("CargoPayment"); INSTANTIATE_POOL_METHODS(CargoPayment) /** * Multiply two integer values and shift the results to right. * * This function multiplies two integer values. The result is * shifted by the amount of shift to right. * * @param a The first integer * @param b The second integer * @param shift The amount to shift the value to right. * @return The shifted result */ static inline int32 BigMulS(const int32 a, const int32 b, const uint8 shift) { return (int32)((int64)a * (int64)b >> shift); } typedef SmallVector<Industry *, 16> SmallIndustryList; /** * Score info, values used for computing the detailed performance rating. */ const ScoreInfo _score_info[] = { { 120, 100}, // SCORE_VEHICLES { 80, 100}, // SCORE_STATIONS { 10000, 100}, // SCORE_MIN_PROFIT { 50000, 50}, // SCORE_MIN_INCOME { 100000, 100}, // SCORE_MAX_INCOME { 40000, 400}, // SCORE_DELIVERED { 8, 50}, // SCORE_CARGO {10000000, 50}, // SCORE_MONEY { 250000, 50}, // SCORE_LOAN { 0, 0} // SCORE_TOTAL }; int _score_part[MAX_COMPANIES][SCORE_END]; Economy _economy; Prices _price; Money _additional_cash_required; static PriceMultipliers _price_base_multiplier; /** * Calculate the value of the company. That is the value of all * assets (vehicles, stations, etc) and money minus the loan, * except when including_loan is \c false which is useful when * we want to calculate the value for bankruptcy. * @param c the company to get the value of. * @param including_loan include the loan in the company value. * @return the value of the company. */ Money CalculateCompanyValue(const Company *c, bool including_loan) { Owner owner = c->index; Station *st; uint num = 0; FOR_ALL_STATIONS(st) { if (st->owner == owner) num += CountBits((byte)st->facilities); } Money value = num * _price[PR_STATION_VALUE] * 25; Vehicle *v; FOR_ALL_VEHICLES(v) { if (v->owner != owner) continue; if (v->type == VEH_TRAIN || v->type == VEH_ROAD || (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) || v->type == VEH_SHIP) { value += v->value * 3 >> 1; } } /* Add real money value */ if (including_loan) value -= c->current_loan; value += c->money; return max(value, (Money)1); } /** * if update is set to true, the economy is updated with this score * (also the house is updated, should only be true in the on-tick event) * @param update the economy with calculated score * @param c company been evaluated * @return actual score of this company * */ int UpdateCompanyRatingAndValue(Company *c, bool update) { Owner owner = c->index; int score = 0; memset(_score_part[owner], 0, sizeof(_score_part[owner])); /* Count vehicles */ { Vehicle *v; Money min_profit = 0; bool min_profit_first = true; uint num = 0; FOR_ALL_VEHICLES(v) { if (v->owner != owner) continue; if (IsCompanyBuildableVehicleType(v->type) && v->IsPrimaryVehicle()) { if (v->profit_last_year > 0) num++; // For the vehicle score only count profitable vehicles if (v->age > 730) { /* Find the vehicle with the lowest amount of profit */ if (min_profit_first || min_profit > v->profit_last_year) { min_profit = v->profit_last_year; min_profit_first = false; } } } } min_profit >>= 8; // remove the fract part _score_part[owner][SCORE_VEHICLES] = num; /* Don't allow negative min_profit to show */ if (min_profit > 0) { _score_part[owner][SCORE_MIN_PROFIT] = ClampToI32(min_profit); } } /* Count stations */ { uint num = 0; const Station *st; FOR_ALL_STATIONS(st) { /* Only count stations that are actually serviced */ if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities); } _score_part[owner][SCORE_STATIONS] = num; } /* Generate statistics depending on recent income statistics */ { int numec = min(c->num_valid_stat_ent, 12); if (numec != 0) { const CompanyEconomyEntry *cee = c->old_economy; Money min_income = cee->income + cee->expenses; Money max_income = cee->income + cee->expenses; do { min_income = min(min_income, cee->income + cee->expenses); max_income = max(max_income, cee->income + cee->expenses); } while (++cee, --numec); if (min_income > 0) { _score_part[owner][SCORE_MIN_INCOME] = ClampToI32(min_income); } _score_part[owner][SCORE_MAX_INCOME] = ClampToI32(max_income); } } /* Generate score depending on amount of transported cargo */ { int numec = min(c->num_valid_stat_ent, 4); if (numec != 0) { const CompanyEconomyEntry *cee = c->old_economy; OverflowSafeInt64 total_delivered = 0; do { total_delivered += cee->delivered_cargo.GetSum<OverflowSafeInt64>(); } while (++cee, --numec); _score_part[owner][SCORE_DELIVERED] = ClampToI32(total_delivered); } } /* Generate score for variety of cargo */ { _score_part[owner][SCORE_CARGO] = c->old_economy->delivered_cargo.GetCount(); } /* Generate score for company's money */ { if (c->money > 0) { _score_part[owner][SCORE_MONEY] = ClampToI32(c->money); } } /* Generate score for loan */ { _score_part[owner][SCORE_LOAN] = ClampToI32(_score_info[SCORE_LOAN].needed - c->current_loan); } /* Now we calculate the score for each item.. */ { int total_score = 0; int s; score = 0; for (ScoreID i = SCORE_BEGIN; i < SCORE_END; i++) { /* Skip the total */ if (i == SCORE_TOTAL) continue; /* Check the score */ s = Clamp(_score_part[owner][i], 0, _score_info[i].needed) * _score_info[i].score / _score_info[i].needed; score += s; total_score += _score_info[i].score; } _score_part[owner][SCORE_TOTAL] = score; /* We always want the score scaled to SCORE_MAX (1000) */ if (total_score != SCORE_MAX) score = score * SCORE_MAX / total_score; } if (update) { c->old_economy[0].performance_history = score; UpdateCompanyHQ(c->location_of_HQ, score); c->old_economy[0].company_value = CalculateCompanyValue(c); } SetWindowDirty(WC_PERFORMANCE_DETAIL, 0); return score; } /** * Change the ownership of all the items of a company. * @param old_owner The company that gets removed. * @param new_owner The company to merge to, or INVALID_OWNER to remove the company. */ void ChangeOwnershipOfCompanyItems(Owner old_owner, Owner new_owner) { /* We need to set _current_company to old_owner before we try to move * the client. This is needed as it needs to know whether "you" really * are the current local company. */ Backup<CompanyByte> cur_company(_current_company, old_owner, FILE_LINE); #ifdef ENABLE_NETWORK /* In all cases, make spectators of clients connected to that company */ if (_networking) NetworkClientsToSpectators(old_owner); #endif /* ENABLE_NETWORK */ if (old_owner == _local_company) { /* Single player cheated to AI company. * There are no spectators in single player, so we must pick some other company. */ assert(!_networking); Backup<CompanyByte> cur_company2(_current_company, FILE_LINE); Company *c; FOR_ALL_COMPANIES(c) { if (c->index != old_owner) { SetLocalCompany(c->index); break; } } cur_company2.Restore(); assert(old_owner != _local_company); } Town *t; assert(old_owner != new_owner); { Company *c; uint i; /* See if the old_owner had shares in other companies */ FOR_ALL_COMPANIES(c) { for (i = 0; i < 4; i++) { if (c->share_owners[i] == old_owner) { /* Sell his shares */ CommandCost res = DoCommand(0, c->index, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY); /* Because we are in a DoCommand, we can't just execute another one and * expect the money to be removed. We need to do it ourself! */ SubtractMoneyFromCompany(res); } } } /* Sell all the shares that people have on this company */ Backup<CompanyByte> cur_company2(_current_company, FILE_LINE); c = Company::Get(old_owner); for (i = 0; i < 4; i++) { cur_company2.Change(c->share_owners[i]); if (_current_company != INVALID_OWNER) { /* Sell the shares */ CommandCost res = DoCommand(0, old_owner, 0, DC_EXEC | DC_BANKRUPT, CMD_SELL_SHARE_IN_COMPANY); /* Because we are in a DoCommand, we can't just execute another one and * expect the money to be removed. We need to do it ourself! */ SubtractMoneyFromCompany(res); } } cur_company2.Restore(); } /* Temporarily increase the company's money, to be sure that * removing his/her property doesn't fail because of lack of money. * Not too drastically though, because it could overflow */ if (new_owner == INVALID_OWNER) { Company::Get(old_owner)->money = UINT64_MAX >> 2; // jackpot ;p } Subsidy *s; FOR_ALL_SUBSIDIES(s) { if (s->awarded == old_owner) { if (new_owner == INVALID_OWNER) { delete s; } else { s->awarded = new_owner; } } } if (new_owner == INVALID_OWNER) RebuildSubsidisedSourceAndDestinationCache(); /* Take care of rating and transport rights in towns */ FOR_ALL_TOWNS(t) { /* If a company takes over, give the ratings to that company. */ if (new_owner != INVALID_OWNER) { if (HasBit(t->have_ratings, old_owner)) { if (HasBit(t->have_ratings, new_owner)) { /* use max of the two ratings. */ t->ratings[new_owner] = max(t->ratings[new_owner], t->ratings[old_owner]); } else { SetBit(t->have_ratings, new_owner); t->ratings[new_owner] = t->ratings[old_owner]; } } } /* Reset the ratings for the old owner */ t->ratings[old_owner] = RATING_INITIAL; ClrBit(t->have_ratings, old_owner); /* Transfer exclusive rights */ if (t->exclusive_counter > 0 && t->exclusivity == old_owner) { if (new_owner != INVALID_OWNER) { t->exclusivity = new_owner; } else { t->exclusive_counter = 0; t->exclusivity = INVALID_COMPANY; } } } { Vehicle *v; FOR_ALL_VEHICLES(v) { if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) { if (new_owner == INVALID_OWNER) { if (v->Previous() == NULL) delete v; } else { if (v->IsEngineCountable()) GroupStatistics::CountEngine(v, -1); if (v->IsPrimaryVehicle()) GroupStatistics::CountVehicle(v, -1); } } } } /* In all cases clear replace engine rules. * Even if it was copied, it could interfere with new owner's rules */ RemoveAllEngineReplacementForCompany(Company::Get(old_owner)); if (new_owner == INVALID_OWNER) { RemoveAllGroupsForCompany(old_owner); } else { Group *g; FOR_ALL_GROUPS(g) { if (g->owner == old_owner) g->owner = new_owner; } } { FreeUnitIDGenerator unitidgen[] = { FreeUnitIDGenerator(VEH_TRAIN, new_owner), FreeUnitIDGenerator(VEH_ROAD, new_owner), FreeUnitIDGenerator(VEH_SHIP, new_owner), FreeUnitIDGenerator(VEH_AIRCRAFT, new_owner) }; /* Override company settings to new company defaults in case we need to convert them. * This is required as the CmdChangeServiceInt doesn't copy the supplied value when it is non-custom */ if (new_owner != INVALID_OWNER) { Company *old_company = Company::Get(old_owner); Company *new_company = Company::Get(new_owner); old_company->settings.vehicle.servint_aircraft = new_company->settings.vehicle.servint_aircraft; old_company->settings.vehicle.servint_trains = new_company->settings.vehicle.servint_trains; old_company->settings.vehicle.servint_roadveh = new_company->settings.vehicle.servint_roadveh; old_company->settings.vehicle.servint_ships = new_company->settings.vehicle.servint_ships; old_company->settings.vehicle.servint_ispercent = new_company->settings.vehicle.servint_ispercent; } Vehicle *v; FOR_ALL_VEHICLES(v) { if (v->owner == old_owner && IsCompanyBuildableVehicleType(v->type)) { assert(new_owner != INVALID_OWNER); /* Correct default values of interval settings while maintaining custom set ones. * This prevents invalid values on mismatching company defaults being accepted. */ if (!v->ServiceIntervalIsCustom()) { Company *new_company = Company::Get(new_owner); /* Technically, passing the interval is not needed as the command will query the default value itself. * However, do not rely on that behaviour. */ int interval = CompanyServiceInterval(new_company, v->type); DoCommand(v->tile, v->index, interval | (new_company->settings.vehicle.servint_ispercent << 17), DC_EXEC | DC_BANKRUPT, CMD_CHANGE_SERVICE_INT); } v->owner = new_owner; /* Owner changes, clear cache */ v->colourmap = PAL_NONE; v->InvalidateNewGRFCache(); if (v->IsEngineCountable()) { GroupStatistics::CountEngine(v, 1); } if (v->IsPrimaryVehicle()) { GroupStatistics::CountVehicle(v, 1); v->unitnumber = unitidgen[v->type].NextID(); } /* Invalidate the vehicle's cargo payment "owner cache". */ if (v->cargo_payment != NULL) v->cargo_payment->owner = NULL; } } if (new_owner != INVALID_OWNER) GroupStatistics::UpdateAutoreplace(new_owner); } /* Change ownership of tiles */ { TileIndex tile = 0; do { ChangeTileOwner(tile, old_owner, new_owner); } while (++tile != MapSize()); if (new_owner != INVALID_OWNER) { /* Update all signals because there can be new segment that was owned by two companies * and signals were not propagated * Similar with crossings - it is needed to bar crossings that weren't before * because of different owner of crossing and approaching train */ tile = 0; do { if (IsTileType(tile, MP_RAILWAY) && IsTileOwner(tile, new_owner) && HasSignals(tile)) { TrackBits tracks = GetTrackBits(tile); do { // there may be two tracks with signals for TRACK_BIT_HORZ and TRACK_BIT_VERT Track track = RemoveFirstTrack(&tracks); if (HasSignalOnTrack(tile, track)) AddTrackToSignalBuffer(tile, track, new_owner); } while (tracks != TRACK_BIT_NONE); } else if (IsLevelCrossingTile(tile) && IsTileOwner(tile, new_owner)) { UpdateLevelCrossing(tile); } } while (++tile != MapSize()); } /* update signals in buffer */ UpdateSignalsInBuffer(); } /* Add airport infrastructure count of the old company to the new one. */ if (new_owner != INVALID_OWNER) Company::Get(new_owner)->infrastructure.airport += Company::Get(old_owner)->infrastructure.airport; /* convert owner of stations (including deleted ones, but excluding buoys) */ Station *st; FOR_ALL_STATIONS(st) { if (st->owner == old_owner) { /* if a company goes bankrupt, set owner to OWNER_NONE so the sign doesn't disappear immediately * also, drawing station window would cause reading invalid company's colour */ st->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner; } } /* do the same for waypoints (we need to do this here so deleted waypoints are converted too) */ Waypoint *wp; FOR_ALL_WAYPOINTS(wp) { if (wp->owner == old_owner) { wp->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner; } } Sign *si; FOR_ALL_SIGNS(si) { if (si->owner == old_owner) si->owner = new_owner == INVALID_OWNER ? OWNER_NONE : new_owner; } /* Remove Game Script created Goals, CargoMonitors and Story pages. */ Goal *g; FOR_ALL_GOALS(g) { if (g->company == old_owner) delete g; } ClearCargoPickupMonitoring(old_owner); ClearCargoDeliveryMonitoring(old_owner); StoryPage *sp; FOR_ALL_STORY_PAGES(sp) { if (sp->company == old_owner) delete sp; } /* Change colour of existing windows */ if (new_owner != INVALID_OWNER) ChangeWindowOwner(old_owner, new_owner); cur_company.Restore(); MarkWholeScreenDirty(); } /** * Check for bankruptcy of a company. Called every three months. * @param c Company to check. */ static void CompanyCheckBankrupt(Company *c) { /* If the company has money again, it does not go bankrupt */ if (c->money - c->current_loan >= -_economy.max_loan) { c->months_of_bankruptcy = 0; c->bankrupt_asked = 0; return; } c->months_of_bankruptcy++; switch (c->months_of_bankruptcy) { /* All the boring cases (months) with a bad balance where no action is taken */ case 0: case 1: case 2: case 3: case 5: case 6: case 8: case 9: break; /* Warn about bankruptcy after 3 months */ case 4: { CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1); cni->FillData(c); SetDParam(0, STR_NEWS_COMPANY_IN_TROUBLE_TITLE); SetDParam(1, STR_NEWS_COMPANY_IN_TROUBLE_DESCRIPTION); SetDParamStr(2, cni->company_name); AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni); AI::BroadcastNewEvent(new ScriptEventCompanyInTrouble(c->index)); Game::NewEvent(new ScriptEventCompanyInTrouble(c->index)); break; } /* Offer company for sale after 6 months */ case 7: { /* Don't consider the loan */ Money val = CalculateCompanyValue(c, false); c->bankrupt_value = val; c->bankrupt_asked = 1 << c->index; // Don't ask the owner c->bankrupt_timeout = 0; /* The company assets should always have some value */ assert(c->bankrupt_value > 0); break; } /* Bankrupt company after 6 months (if the company has no value) or latest * after 9 months (if it still had value after 6 months) */ default: case 10: { if (!_networking && _local_company == c->index) { /* If we are in offline mode, leave the company playing. Eg. there * is no THE-END, otherwise mark the client as spectator to make sure * he/she is no long in control of this company. However... when you * join another company (cheat) the "unowned" company can bankrupt. */ c->bankrupt_asked = MAX_UVALUE(CompanyMask); break; } /* Actually remove the company, but not when we're a network client. * In case of network clients we will be getting a command from the * server. It is done in this way as we are called from the * StateGameLoop which can't change the current company, and thus * updating the local company triggers an assert later on. In the * case of a network game the command will be processed at a time * that changing the current company is okay. In case of single * player we are sure (the above check) that we are not the local * company and thus we won't be moved. */ if (!_networking || _network_server) DoCommandP(0, 2 | (c->index << 16), CRR_BANKRUPT, CMD_COMPANY_CTRL); break; } } } /** * Update the finances of all companies. * Pay for the stations, update the history graph, update ratings and company values, and deal with bankruptcy. */ static void CompaniesGenStatistics() { /* Check for bankruptcy each month */ Company *c; FOR_ALL_COMPANIES(c) { CompanyCheckBankrupt(c); } Backup<CompanyByte> cur_company(_current_company, FILE_LINE); if (!_settings_game.economy.infrastructure_maintenance) { Station *st; FOR_ALL_STATIONS(st) { cur_company.Change(st->owner); CommandCost cost(EXPENSES_PROPERTY, _price[PR_STATION_VALUE] >> 1); SubtractMoneyFromCompany(cost); } } else { /* Improved monthly infrastructure costs. */ FOR_ALL_COMPANIES(c) { cur_company.Change(c->index); CommandCost cost(EXPENSES_PROPERTY); uint32 rail_total = c->infrastructure.GetRailTotal(); for (RailType rt = RAILTYPE_BEGIN; rt < RAILTYPE_END; rt++) { if (c->infrastructure.rail[rt] != 0) cost.AddCost(RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total)); } cost.AddCost(SignalMaintenanceCost(c->infrastructure.signal)); for (RoadType rt = ROADTYPE_BEGIN; rt < ROADTYPE_END; rt++) { if (c->infrastructure.road[rt] != 0) cost.AddCost(RoadMaintenanceCost(rt, c->infrastructure.road[rt])); } cost.AddCost(CanalMaintenanceCost(c->infrastructure.water)); cost.AddCost(StationMaintenanceCost(c->infrastructure.station)); cost.AddCost(AirportMaintenanceCost(c->index)); SubtractMoneyFromCompany(cost); } } cur_company.Restore(); /* Only run the economic statics and update company stats every 3rd month (1st of quarter). */ if (!HasBit(1 << 0 | 1 << 3 | 1 << 6 | 1 << 9, _cur_month)) return; FOR_ALL_COMPANIES(c) { /* Drop the oldest history off the end */ std::copy_backward(c->old_economy, c->old_economy + MAX_HISTORY_QUARTERS - 1, c->old_economy + MAX_HISTORY_QUARTERS); c->old_economy[0] = c->cur_economy; c->cur_economy = {}; if (c->num_valid_stat_ent != MAX_HISTORY_QUARTERS) c->num_valid_stat_ent++; UpdateCompanyRatingAndValue(c, true); if (c->block_preview != 0) c->block_preview--; } SetWindowDirty(WC_INCOME_GRAPH, 0); SetWindowDirty(WC_OPERATING_PROFIT, 0); SetWindowDirty(WC_DELIVERED_CARGO, 0); SetWindowDirty(WC_PERFORMANCE_HISTORY, 0); SetWindowDirty(WC_COMPANY_VALUE, 0); SetWindowDirty(WC_COMPANY_LEAGUE, 0); } /** * Add monthly inflation * @param check_year Shall the inflation get stopped after 170 years? * @return true if inflation is maxed and nothing was changed */ bool AddInflation(bool check_year) { /* The cargo payment inflation differs from the normal inflation, so the * relative amount of money you make with a transport decreases slowly over * the 170 years. After a few hundred years we reach a level in which the * games will become unplayable as the maximum income will be less than * the minimum running cost. * * Furthermore there are a lot of inflation related overflows all over the * place. Solving them is hardly possible because inflation will always * reach the overflow threshold some day. So we'll just perform the * inflation mechanism during the first 170 years (the amount of years that * one had in the original TTD) and stop doing the inflation after that * because it only causes problems that can't be solved nicely and the * inflation doesn't add anything after that either; it even makes playing * it impossible due to the diverging cost and income rates. */ if (check_year && (_cur_year - _settings_game.game_creation.starting_year) >= (ORIGINAL_MAX_YEAR - ORIGINAL_BASE_YEAR)) return true; if (_economy.inflation_prices == MAX_INFLATION || _economy.inflation_payment == MAX_INFLATION) return true; /* Approximation for (100 + infl_amount)% ** (1 / 12) - 100% * scaled by 65536 * 12 -> months per year * This is only a good approximation for small values */ _economy.inflation_prices += (_economy.inflation_prices * _economy.infl_amount * 54) >> 16; _economy.inflation_payment += (_economy.inflation_payment * _economy.infl_amount_pr * 54) >> 16; if (_economy.inflation_prices > MAX_INFLATION) _economy.inflation_prices = MAX_INFLATION; if (_economy.inflation_payment > MAX_INFLATION) _economy.inflation_payment = MAX_INFLATION; return false; } /** * Computes all prices, payments and maximum loan. */ void RecomputePrices() { /* Setup maximum loan */ _economy.max_loan = (_settings_game.difficulty.max_loan * _economy.inflation_prices >> 16) / 50000 * 50000; /* Setup price bases */ for (Price i = PR_BEGIN; i < PR_END; i++) { Money price = _price_base_specs[i].start_price; /* Apply difficulty settings */ uint mod = 1; switch (_price_base_specs[i].category) { case PCAT_RUNNING: mod = _settings_game.difficulty.vehicle_costs; break; case PCAT_CONSTRUCTION: mod = _settings_game.difficulty.construction_cost; break; default: break; } switch (mod) { case 0: price *= 6; break; case 1: price *= 8; break; // normalised to 1 below case 2: price *= 9; break; default: NOT_REACHED(); } /* Apply inflation */ price = (int64)price * _economy.inflation_prices; /* Apply newgrf modifiers, remove fractional part of inflation, and normalise on medium difficulty. */ int shift = _price_base_multiplier[i] - 16 - 3; if (shift >= 0) { price <<= shift; } else { price >>= -shift; } /* Make sure the price does not get reduced to zero. * Zero breaks quite a few commands that use a zero * cost to see whether something got changed or not * and based on that cause an error. When the price * is zero that fails even when things are done. */ if (price == 0) { price = Clamp(_price_base_specs[i].start_price, -1, 1); /* No base price should be zero, but be sure. */ assert(price != 0); } /* Store value */ _price[i] = price; } /* Setup cargo payment */ CargoSpec *cs; FOR_ALL_CARGOSPECS(cs) { cs->current_payment = ((int64)cs->initial_payment * _economy.inflation_payment) >> 16; } SetWindowClassesDirty(WC_BUILD_VEHICLE); SetWindowClassesDirty(WC_REPLACE_VEHICLE); SetWindowClassesDirty(WC_VEHICLE_DETAILS); SetWindowClassesDirty(WC_COMPANY_INFRASTRUCTURE); InvalidateWindowData(WC_PAYMENT_RATES, 0); } /** Let all companies pay the monthly interest on their loan. */ static void CompaniesPayInterest() { const Company *c; Backup<CompanyByte> cur_company(_current_company, FILE_LINE); FOR_ALL_COMPANIES(c) { cur_company.Change(c->index); /* Over a year the paid interest should be "loan * interest percentage", * but... as that number is likely not dividable by 12 (pay each month), * one needs to account for that in the monthly fee calculations. * To easily calculate what one should pay "this" month, you calculate * what (total) should have been paid up to this month and you subtract * whatever has been paid in the previous months. This will mean one month * it'll be a bit more and the other it'll be a bit less than the average * monthly fee, but on average it will be exact. * In order to prevent cheating or abuse (just not paying interest by not * taking a loan we make companies pay interest on negative cash as well */ Money yearly_fee = c->current_loan * _economy.interest_rate / 100; if (c->money < 0) { yearly_fee += -c->money *_economy.interest_rate / 100; } Money up_to_previous_month = yearly_fee * _cur_month / 12; Money up_to_this_month = yearly_fee * (_cur_month + 1) / 12; SubtractMoneyFromCompany(CommandCost(EXPENSES_LOAN_INT, up_to_this_month - up_to_previous_month)); SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, _price[PR_STATION_VALUE] >> 2)); } cur_company.Restore(); } static void HandleEconomyFluctuations() { if (_settings_game.difficulty.economy != 0) { /* When economy is Fluctuating, decrease counter */ _economy.fluct--; } else if (EconomyIsInRecession()) { /* When it's Steady and we are in recession, end it now */ _economy.fluct = -12; } else { /* No need to do anything else in other cases */ return; } if (_economy.fluct == 0) { _economy.fluct = -(int)GB(Random(), 0, 2); AddNewsItem(STR_NEWS_BEGIN_OF_RECESSION, NT_ECONOMY, NF_NORMAL); } else if (_economy.fluct == -12) { _economy.fluct = GB(Random(), 0, 8) + 312; AddNewsItem(STR_NEWS_END_OF_RECESSION, NT_ECONOMY, NF_NORMAL); } } /** * Reset changes to the price base multipliers. */ void ResetPriceBaseMultipliers() { memset(_price_base_multiplier, 0, sizeof(_price_base_multiplier)); } /** * Change a price base by the given factor. * The price base is altered by factors of two. * NewBaseCost = OldBaseCost * 2^n * @param price Index of price base to change. * @param factor Amount to change by. */ void SetPriceBaseMultiplier(Price price, int factor) { assert(price < PR_END); _price_base_multiplier[price] = Clamp(factor, MIN_PRICE_MODIFIER, MAX_PRICE_MODIFIER); } /** * Initialize the variables that will maintain the daily industry change system. * @param init_counter specifies if the counter is required to be initialized */ void StartupIndustryDailyChanges(bool init_counter) { uint map_size = MapLogX() + MapLogY(); /* After getting map size, it needs to be scaled appropriately and divided by 31, * which stands for the days in a month. * Using just 31 will make it so that a monthly reset (based on the real number of days of that month) * would not be needed. * Since it is based on "fractional parts", the leftover days will not make much of a difference * on the overall total number of changes performed */ _economy.industry_daily_increment = (1 << map_size) / 31; if (init_counter) { /* A new game or a savegame from an older version will require the counter to be initialized */ _economy.industry_daily_change_counter = 0; } } void StartupEconomy() { _economy.interest_rate = _settings_game.difficulty.initial_interest; _economy.infl_amount = _settings_game.difficulty.initial_interest; _economy.infl_amount_pr = max(0, _settings_game.difficulty.initial_interest - 1); _economy.fluct = GB(Random(), 0, 8) + 168; /* Set up prices */ RecomputePrices(); StartupIndustryDailyChanges(true); // As we are starting a new game, initialize the counter too } /** * Resets economy to initial values */ void InitializeEconomy() { _economy.inflation_prices = _economy.inflation_payment = 1 << 16; ClearCargoPickupMonitoring(); ClearCargoDeliveryMonitoring(); } /** * Determine a certain price * @param index Price base * @param cost_factor Price factor * @param grf_file NewGRF to use local price multipliers from. * @param shift Extra bit shifting after the computation * @return Price */ Money GetPrice(Price index, uint cost_factor, const GRFFile *grf_file, int shift) { if (index >= PR_END) return 0; Money cost = _price[index] * cost_factor; if (grf_file != NULL) shift += grf_file->price_base_multipliers[index]; if (shift >= 0) { cost <<= shift; } else { cost >>= -shift; } return cost; } Money GetTransportedGoodsIncome(uint num_pieces, uint dist, byte transit_days, CargoID cargo_type) { const CargoSpec *cs = CargoSpec::Get(cargo_type); if (!cs->IsValid()) { /* User changed newgrfs and some vehicle still carries some cargo which is no longer available. */ return 0; } /* Use callback to calculate cargo profit, if available */ if (HasBit(cs->callback_mask, CBM_CARGO_PROFIT_CALC)) { uint32 var18 = min(dist, 0xFFFF) | (min(num_pieces, 0xFF) << 16) | (transit_days << 24); uint16 callback = GetCargoCallback(CBID_CARGO_PROFIT_CALC, 0, var18, cs); if (callback != CALLBACK_FAILED) { int result = GB(callback, 0, 14); /* Simulate a 15 bit signed value */ if (HasBit(callback, 14)) result -= 0x4000; /* "The result should be a signed multiplier that gets multiplied * by the amount of cargo moved and the price factor, then gets * divided by 8192." */ return result * num_pieces * cs->current_payment / 8192; } } static const int MIN_TIME_FACTOR = 31; static const int MAX_TIME_FACTOR = 255; const int days1 = cs->transit_days[0]; const int days2 = cs->transit_days[1]; const int days_over_days1 = max( transit_days - days1, 0); const int days_over_days2 = max(days_over_days1 - days2, 0); /* * The time factor is calculated based on the time it took * (transit_days) compared two cargo-depending values. The * range is divided into three parts: * * - constant for fast transits * - linear decreasing with time with a slope of -1 for medium transports * - linear decreasing with time with a slope of -2 for slow transports * */ const int time_factor = max(MAX_TIME_FACTOR - days_over_days1 - days_over_days2, MIN_TIME_FACTOR); return BigMulS(dist * time_factor * num_pieces, cs->current_payment, 21); } /** The industries we've currently brought cargo to. */ static SmallIndustryList _cargo_delivery_destinations; /** * Transfer goods from station to industry. * All cargo is delivered to the nearest (Manhattan) industry to the station sign, which is inside the acceptance rectangle and actually accepts the cargo. * @param st The station that accepted the cargo * @param cargo_type Type of cargo delivered * @param num_pieces Amount of cargo delivered * @param source The source of the cargo * @return actually accepted pieces of cargo */ static uint DeliverGoodsToIndustry(const Station *st, CargoID cargo_type, uint num_pieces, IndustryID source) { /* Find the nearest industrytile to the station sign inside the catchment area, whose industry accepts the cargo. * This fails in three cases: * 1) The station accepts the cargo because there are enough houses around it accepting the cargo. * 2) The industries in the catchment area temporarily reject the cargo, and the daily station loop has not yet updated station acceptance. * 3) The results of callbacks CBID_INDUSTRY_REFUSE_CARGO and CBID_INDTILE_CARGO_ACCEPTANCE are inconsistent. (documented behaviour) */ uint accepted = 0; for (uint i = 0; i < st->industries_near.Length() && num_pieces != 0; i++) { Industry *ind = st->industries_near[i]; if (ind->index == source) continue; uint cargo_index; for (cargo_index = 0; cargo_index < lengthof(ind->accepts_cargo); cargo_index++) { if (cargo_type == ind->accepts_cargo[cargo_index]) break; } /* Check if matching cargo has been found */ if (cargo_index >= lengthof(ind->accepts_cargo)) continue; /* Check if industry temporarily refuses acceptance */ if (IndustryTemporarilyRefusesCargo(ind, cargo_type)) continue; /* Insert the industry into _cargo_delivery_destinations, if not yet contained */ _cargo_delivery_destinations.Include(ind); uint amount = min(num_pieces, 0xFFFFU - ind->incoming_cargo_waiting[cargo_index]); ind->incoming_cargo_waiting[cargo_index] += amount; ind->last_cargo_accepted_at[cargo_index] = _date; num_pieces -= amount; accepted += amount; } return accepted; } /** * Delivers goods to industries/towns and calculates the payment * @param num_pieces amount of cargo delivered * @param cargo_type the type of cargo that is delivered * @param dest Station the cargo has been unloaded * @param source_tile The origin of the cargo for distance calculation * @param days_in_transit Travel time * @param company The company delivering the cargo * @param src_type Type of source of cargo (industry, town, headquarters) * @param src Index of source of cargo * @return Revenue for delivering cargo * @note The cargo is just added to the stockpile of the industry. It is due to the caller to trigger the industry's production machinery */ static Money DeliverGoods(int num_pieces, CargoID cargo_type, StationID dest, TileIndex source_tile, byte days_in_transit, Company *company, SourceType src_type, SourceID src) { assert(num_pieces > 0); Station *st = Station::Get(dest); /* Give the goods to the industry. */ uint accepted = DeliverGoodsToIndustry(st, cargo_type, num_pieces, src_type == ST_INDUSTRY ? src : INVALID_INDUSTRY); /* If this cargo type is always accepted, accept all */ if (HasBit(st->always_accepted, cargo_type)) accepted = num_pieces; /* Update station statistics */ if (accepted > 0) { SetBit(st->goods[cargo_type].status, GoodsEntry::GES_EVER_ACCEPTED); SetBit(st->goods[cargo_type].status, GoodsEntry::GES_CURRENT_MONTH); SetBit(st->goods[cargo_type].status, GoodsEntry::GES_ACCEPTED_BIGTICK); } /* Update company statistics */ company->cur_economy.delivered_cargo[cargo_type] += accepted; /* Increase town's counter for town effects */ const CargoSpec *cs = CargoSpec::Get(cargo_type); st->town->received[cs->town_effect].new_act += accepted; /* Determine profit */ Money profit = GetTransportedGoodsIncome(accepted, DistanceManhattan(source_tile, st->xy), days_in_transit, cargo_type); /* Update the cargo monitor. */ AddCargoDelivery(cargo_type, company->index, accepted, src_type, src, st); /* Modify profit if a subsidy is in effect */ if (CheckSubsidised(cargo_type, company->index, src_type, src, st)) { switch (_settings_game.difficulty.subsidy_multiplier) { case 0: profit += profit >> 1; break; case 1: profit *= 2; break; case 2: profit *= 3; break; default: profit *= 4; break; } } return profit; } /** * Inform the industry about just delivered cargo * DeliverGoodsToIndustry() silently incremented incoming_cargo_waiting, now it is time to do something with the new cargo. * @param i The industry to process */ static void TriggerIndustryProduction(Industry *i) { const IndustrySpec *indspec = GetIndustrySpec(i->type); uint16 callback = indspec->callback_mask; i->was_cargo_delivered = true; if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL) || HasBit(callback, CBM_IND_PRODUCTION_256_TICKS)) { if (HasBit(callback, CBM_IND_PRODUCTION_CARGO_ARRIVAL)) { IndustryProductionCallback(i, 0); } else { SetWindowDirty(WC_INDUSTRY_VIEW, i->index); } } else { for (uint ci_in = 0; ci_in < lengthof(i->incoming_cargo_waiting); ci_in++) { uint cargo_waiting = i->incoming_cargo_waiting[ci_in]; if (cargo_waiting == 0) continue; for (uint ci_out = 0; ci_out < lengthof(i->produced_cargo_waiting); ci_out++) { i->produced_cargo_waiting[ci_out] = min(i->produced_cargo_waiting[ci_out] + (cargo_waiting * indspec->input_cargo_multiplier[ci_in][ci_out] / 256), 0xFFFF); } i->incoming_cargo_waiting[ci_in] = 0; } } TriggerIndustry(i, INDUSTRY_TRIGGER_RECEIVED_CARGO); StartStopIndustryTileAnimation(i, IAT_INDUSTRY_RECEIVED_CARGO); } /** * Makes us a new cargo payment helper. * @param front The front of the train */ CargoPayment::CargoPayment(Vehicle *front) : front(front), current_station(front->last_station_visited) { } CargoPayment::~CargoPayment() { if (this->CleaningPool()) return; this->front->cargo_payment = NULL; if (this->visual_profit == 0 && this->visual_transfer == 0) return; Backup<CompanyByte> cur_company(_current_company, this->front->owner, FILE_LINE); SubtractMoneyFromCompany(CommandCost(this->front->GetExpenseType(true), -this->route_profit)); this->front->profit_this_year += (this->visual_profit + this->visual_transfer) << 8; if (this->route_profit != 0 && IsLocalCompany() && !PlayVehicleSound(this->front, VSE_LOAD_UNLOAD)) { SndPlayVehicleFx(SND_14_CASHTILL, this->front); } if (this->visual_transfer != 0) { ShowFeederIncomeAnimation(this->front->x_pos, this->front->y_pos, this->front->z_pos, this->visual_transfer, -this->visual_profit); } else if (this->visual_profit != 0) { ShowCostOrIncomeAnimation(this->front->x_pos, this->front->y_pos, this->front->z_pos, -this->visual_profit); } cur_company.Restore(); } /** * Handle payment for final delivery of the given cargo packet. * @param cp The cargo packet to pay for. * @param count The number of packets to pay for. */ void CargoPayment::PayFinalDelivery(const CargoPacket *cp, uint count) { if (this->owner == NULL) { this->owner = Company::Get(this->front->owner); } /* Handle end of route payment */ Money profit = DeliverGoods(count, this->ct, this->current_station, cp->SourceStationXY(), cp->DaysInTransit(), this->owner, cp->SourceSubsidyType(), cp->SourceSubsidyID()); this->route_profit += profit; /* The vehicle's profit is whatever route profit there is minus feeder shares. */ this->visual_profit += profit - cp->FeederShare(count); } /** * Handle payment for transfer of the given cargo packet. * @param cp The cargo packet to pay for; actual payment won't be made!. * @param count The number of packets to pay for. * @return The amount of money paid for the transfer. */ Money CargoPayment::PayTransfer(const CargoPacket *cp, uint count) { Money profit = GetTransportedGoodsIncome( count, /* pay transfer vehicle for only the part of transfer it has done: ie. cargo_loaded_at_xy to here */ DistanceManhattan(cp->LoadedAtXY(), Station::Get(this->current_station)->xy), cp->DaysInTransit(), this->ct); profit = profit * _settings_game.economy.feeder_payment_share / 100; this->visual_transfer += profit; // accumulate transfer profits for whole vehicle return profit; // account for the (virtual) profit already made for the cargo packet } /** * Prepare the vehicle to be unloaded. * @param front_v the vehicle to be unloaded */ void PrepareUnload(Vehicle *front_v) { Station *curr_station = Station::Get(front_v->last_station_visited); curr_station->loading_vehicles.push_back(front_v); /* At this moment loading cannot be finished */ ClrBit(front_v->vehicle_flags, VF_LOADING_FINISHED); /* Start unloading at the first possible moment */ front_v->load_unload_ticks = 1; assert(front_v->cargo_payment == NULL); /* One CargoPayment per vehicle and the vehicle limit equals the * limit in number of CargoPayments. Can't go wrong. */ assert_compile(CargoPaymentPool::MAX_SIZE == VehiclePool::MAX_SIZE); assert(CargoPayment::CanAllocateItem()); front_v->cargo_payment = new CargoPayment(front_v); StationIDStack next_station = front_v->GetNextStoppingStation(); if (front_v->orders.list == NULL || (front_v->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) { Station *st = Station::Get(front_v->last_station_visited); for (Vehicle *v = front_v; v != NULL; v = v->Next()) { const GoodsEntry *ge = &st->goods[v->cargo_type]; if (v->cargo_cap > 0 && v->cargo.TotalCount() > 0) { v->cargo.Stage( HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE), front_v->last_station_visited, next_station, front_v->current_order.GetUnloadType(), ge, front_v->cargo_payment); if (v->cargo.UnloadCount() > 0) SetBit(v->vehicle_flags, VF_CARGO_UNLOADING); } } } } /** * Gets the amount of cargo the given vehicle can load in the current tick. * This is only about loading speed. The free capacity is ignored. * @param v Vehicle to be queried. * @return Amount of cargo the vehicle can load at once. */ static uint GetLoadAmount(Vehicle *v) { const Engine *e = v->GetEngine(); uint load_amount = e->info.load_amount; /* The default loadamount for mail is 1/4 of the load amount for passengers */ bool air_mail = v->type == VEH_AIRCRAFT && !Aircraft::From(v)->IsNormalAircraft(); if (air_mail) load_amount = CeilDiv(load_amount, 4); if (_settings_game.order.gradual_loading) { uint16 cb_load_amount = CALLBACK_FAILED; if (e->GetGRF() != NULL && e->GetGRF()->grf_version >= 8) { /* Use callback 36 */ cb_load_amount = GetVehicleProperty(v, PROP_VEHICLE_LOAD_AMOUNT, CALLBACK_FAILED); } else if (HasBit(e->info.callback_mask, CBM_VEHICLE_LOAD_AMOUNT)) { /* Use callback 12 */ cb_load_amount = GetVehicleCallback(CBID_VEHICLE_LOAD_AMOUNT, 0, 0, v->engine_type, v); } if (cb_load_amount != CALLBACK_FAILED) { if (e->GetGRF()->grf_version < 8) cb_load_amount = GB(cb_load_amount, 0, 8); if (cb_load_amount >= 0x100) { ErrorUnknownCallbackResult(e->GetGRFID(), CBID_VEHICLE_LOAD_AMOUNT, cb_load_amount); } else if (cb_load_amount != 0) { load_amount = cb_load_amount; } } } /* Scale load amount the same as capacity */ if (HasBit(e->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER) && !air_mail) load_amount = CeilDiv(load_amount * CargoSpec::Get(v->cargo_type)->multiplier, 0x100); /* Zero load amount breaks a lot of things. */ return max(1u, load_amount); } /** * Iterate the articulated parts of a vehicle, also considering the special cases of "normal" * aircraft and double headed trains. Apply an action to each vehicle and immediately return false * if that action does so. Otherwise return true. * @tparam Taction Class of action to be applied. Must implement bool operator()([const] Vehicle *). * @param v First articulated part. * @param action Instance of Taction. * @return false if any of the action invocations returned false, true otherwise. */ template<class Taction> bool IterateVehicleParts(Vehicle *v, Taction action) { for (Vehicle *w = v; w != NULL; w = w->HasArticulatedPart() ? w->GetNextArticulatedPart() : NULL) { if (!action(w)) return false; if (w->type == VEH_TRAIN) { Train *train = Train::From(w); if (train->IsMultiheaded() && !action(train->other_multiheaded_part)) return false; } } if (v->type == VEH_AIRCRAFT && Aircraft::From(v)->IsNormalAircraft()) return action(v->Next()); return true; } /** * Action to check if a vehicle has no stored cargo. */ struct IsEmptyAction { /** * Checks if the vehicle has stored cargo. * @param v Vehicle to be checked. * @return true if v is either empty or has only reserved cargo, false otherwise. */ bool operator()(const Vehicle *v) { return v->cargo.StoredCount() == 0; } }; /** * Refit preparation action. */ struct PrepareRefitAction { CargoArray &consist_capleft; ///< Capacities left in the consist. CargoTypes &refit_mask; ///< Bitmask of possible refit cargoes. /** * Create a refit preparation action. * @param consist_capleft Capacities left in consist, to be updated here. * @param refit_mask Refit mask to be constructed from refit information of vehicles. */ PrepareRefitAction(CargoArray &consist_capleft, CargoTypes &refit_mask) : consist_capleft(consist_capleft), refit_mask(refit_mask) {} /** * Prepares for refitting of a vehicle, subtracting its free capacity from consist_capleft and * adding the cargoes it can refit to to the refit mask. * @param v The vehicle to be refitted. * @return true. */ bool operator()(const Vehicle *v) { this->consist_capleft[v->cargo_type] -= v->cargo_cap - v->cargo.ReservedCount(); this->refit_mask |= EngInfo(v->engine_type)->refit_mask; return true; } }; /** * Action for returning reserved cargo. */ struct ReturnCargoAction { Station *st; ///< Station to give the returned cargo to. StationID next_hop; ///< Next hop the cargo should be assigned to. /** * Construct a cargo return action. * @param st Station to give the returned cargo to. * @param next_one Next hop the cargo should be assigned to. */ ReturnCargoAction(Station *st, StationID next_one) : st(st), next_hop(next_one) {} /** * Return all reserved cargo from a vehicle. * @param v Vehicle to return cargo from. * @return true. */ bool operator()(Vehicle *v) { v->cargo.Return(UINT_MAX, &this->st->goods[v->cargo_type].cargo, this->next_hop); return true; } }; /** * Action for finalizing a refit. */ struct FinalizeRefitAction { CargoArray &consist_capleft; ///< Capacities left in the consist. Station *st; ///< Station to reserve cargo from. StationIDStack &next_station; ///< Next hops to reserve cargo for. bool do_reserve; ///< If the vehicle should reserve. /** * Create a finalizing action. * @param consist_capleft Capacities left in the consist. * @param st Station to reserve cargo from. * @param next_station Next hops to reserve cargo for. * @param do_reserve If we should reserve cargo or just add up the capacities. */ FinalizeRefitAction(CargoArray &consist_capleft, Station *st, StationIDStack &next_station, bool do_reserve) : consist_capleft(consist_capleft), st(st), next_station(next_station), do_reserve(do_reserve) {} /** * Reserve cargo from the station and update the remaining consist capacities with the * vehicle's remaining free capacity. * @param v Vehicle to be finalized. * @return true. */ bool operator()(Vehicle *v) { if (this->do_reserve) { this->st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(), &v->cargo, st->xy, this->next_station); } this->consist_capleft[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount(); return true; } }; /** * Refit a vehicle in a station. * @param v Vehicle to be refitted. * @param consist_capleft Added cargo capacities in the consist. * @param st Station the vehicle is loading at. * @param next_station Possible next stations the vehicle can travel to. * @param new_cid Target cargo for refit. */ static void HandleStationRefit(Vehicle *v, CargoArray &consist_capleft, Station *st, StationIDStack next_station, CargoID new_cid) { Vehicle *v_start = v->GetFirstEnginePart(); if (!IterateVehicleParts(v_start, IsEmptyAction())) return; Backup<CompanyByte> cur_company(_current_company, v->owner, FILE_LINE); CargoTypes refit_mask = v->GetEngine()->info.refit_mask; /* Remove old capacity from consist capacity and collect refit mask. */ IterateVehicleParts(v_start, PrepareRefitAction(consist_capleft, refit_mask)); bool is_auto_refit = new_cid == CT_AUTO_REFIT; if (is_auto_refit) { /* Get a refittable cargo type with waiting cargo for next_station or INVALID_STATION. */ CargoID cid; new_cid = v_start->cargo_type; FOR_EACH_SET_CARGO_ID(cid, refit_mask) { if (st->goods[cid].cargo.HasCargoFor(next_station)) { /* Try to find out if auto-refitting would succeed. In case the refit is allowed, * the returned refit capacity will be greater than zero. */ DoCommand(v_start->tile, v_start->index, cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_QUERY_COST, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts. /* Try to balance different loadable cargoes between parts of the consist, so that * all of them can be loaded. Avoid a situation where all vehicles suddenly switch * to the first loadable cargo for which there is only one packet. If the capacities * are equal refit to the cargo of which most is available. This is important for * consists of only a single vehicle as those will generally have a consist_capleft * of 0 for all cargoes. */ if (_returned_refit_capacity > 0 && (consist_capleft[cid] < consist_capleft[new_cid] || (consist_capleft[cid] == consist_capleft[new_cid] && st->goods[cid].cargo.AvailableCount() > st->goods[new_cid].cargo.AvailableCount()))) { new_cid = cid; } } } } /* Refit if given a valid cargo. */ if (new_cid < NUM_CARGO && new_cid != v_start->cargo_type) { /* INVALID_STATION because in the DT_MANUAL case that's correct and in the DT_(A)SYMMETRIC * cases the next hop of the vehicle doesn't really tell us anything if the cargo had been * "via any station" before reserving. We rather produce some more "any station" cargo than * misrouting it. */ IterateVehicleParts(v_start, ReturnCargoAction(st, INVALID_STATION)); CommandCost cost = DoCommand(v_start->tile, v_start->index, new_cid | 1U << 6 | 0xFF << 8 | 1U << 16, DC_EXEC, GetCmdRefitVeh(v_start)); // Auto-refit and only this vehicle including artic parts. if (cost.Succeeded()) v->First()->profit_this_year -= cost.GetCost() << 8; } /* Add new capacity to consist capacity and reserve cargo */ IterateVehicleParts(v_start, FinalizeRefitAction(consist_capleft, st, next_station, is_auto_refit || (v->First()->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0)); cur_company.Restore(); } struct ReserveCargoAction { Station *st; StationIDStack *next_station; ReserveCargoAction(Station *st, StationIDStack *next_station) : st(st), next_station(next_station) {} bool operator()(Vehicle *v) { if (v->cargo_cap > v->cargo.RemainingCount()) { st->goods[v->cargo_type].cargo.Reserve(v->cargo_cap - v->cargo.RemainingCount(), &v->cargo, st->xy, *next_station); } return true; } }; /** * Reserves cargo if the full load order and improved_load is set or if the * current order allows autorefit. * @param st Station where the consist is loading at the moment. * @param u Front of the loading vehicle consist. * @param consist_capleft If given, save free capacities after reserving there. * @param next_station Station(s) the vehicle will stop at next. */ static void ReserveConsist(Station *st, Vehicle *u, CargoArray *consist_capleft, StationIDStack *next_station) { /* If there is a cargo payment not all vehicles of the consist have tried to do the refit. * In that case, only reserve if it's a fixed refit and the equivalent of "articulated chain" * a vehicle belongs to already has the right cargo. */ bool must_reserve = !u->current_order.IsRefit() || u->cargo_payment == NULL; for (Vehicle *v = u; v != NULL; v = v->Next()) { assert(v->cargo_cap >= v->cargo.RemainingCount()); /* Exclude various ways in which the vehicle might not be the head of an equivalent of * "articulated chain". Also don't do the reservation if the vehicle is going to refit * to a different cargo and hasn't tried to do so, yet. */ if (!v->IsArticulatedPart() && (v->type != VEH_TRAIN || !Train::From(v)->IsRearDualheaded()) && (v->type != VEH_AIRCRAFT || Aircraft::From(v)->IsNormalAircraft()) && (must_reserve || u->current_order.GetRefitCargo() == v->cargo_type)) { IterateVehicleParts(v, ReserveCargoAction(st, next_station)); } if (consist_capleft == NULL || v->cargo_cap == 0) continue; (*consist_capleft)[v->cargo_type] += v->cargo_cap - v->cargo.RemainingCount(); } } /** * Update the vehicle's load_unload_ticks, the time it will wait until it tries to load or unload * again. Adjust for overhang of trains and set it at least to 1. * @param front The vehicle to be updated. * @param st The station the vehicle is loading at. * @param ticks The time it would normally wait, based on cargo loaded and unloaded. */ static void UpdateLoadUnloadTicks(Vehicle *front, const Station *st, int ticks) { if (front->type == VEH_TRAIN) { /* Each platform tile is worth 2 rail vehicles. */ int overhang = front->GetGroundVehicleCache()->cached_total_length - st->GetPlatformLength(front->tile) * TILE_SIZE; if (overhang > 0) { ticks <<= 1; ticks += (overhang * ticks) / 8; } } /* Always wait at least 1, otherwise we'll wait 'infinitively' long. */ front->load_unload_ticks = max(1, ticks); } /** * Loads/unload the vehicle if possible. * @param front the vehicle to be (un)loaded */ static void LoadUnloadVehicle(Vehicle *front) { assert(front->current_order.IsType(OT_LOADING)); StationID last_visited = front->last_station_visited; Station *st = Station::Get(last_visited); StationIDStack next_station = front->GetNextStoppingStation(); bool use_autorefit = front->current_order.IsRefit() && front->current_order.GetRefitCargo() == CT_AUTO_REFIT; CargoArray consist_capleft; if (_settings_game.order.improved_load && use_autorefit ? front->cargo_payment == NULL : (front->current_order.GetLoadType() & OLFB_FULL_LOAD) != 0) { ReserveConsist(st, front, (use_autorefit && front->load_unload_ticks != 0) ? &consist_capleft : NULL, &next_station); } /* We have not waited enough time till the next round of loading/unloading */ if (front->load_unload_ticks != 0) return; if (front->type == VEH_TRAIN && (!IsTileType(front->tile, MP_STATION) || GetStationIndex(front->tile) != st->index)) { /* The train reversed in the station. Take the "easy" way * out and let the train just leave as it always did. */ SetBit(front->vehicle_flags, VF_LOADING_FINISHED); front->load_unload_ticks = 1; return; } int new_load_unload_ticks = 0; bool dirty_vehicle = false; bool dirty_station = false; bool completely_emptied = true; bool anything_unloaded = false; bool anything_loaded = false; CargoTypes full_load_amount = 0; CargoTypes cargo_not_full = 0; CargoTypes cargo_full = 0; CargoTypes reservation_left = 0; front->cur_speed = 0; CargoPayment *payment = front->cargo_payment; uint artic_part = 0; // Articulated part we are currently trying to load. (not counting parts without capacity) for (Vehicle *v = front; v != NULL; v = v->Next()) { if (v == front || !v->Previous()->HasArticulatedPart()) artic_part = 0; if (v->cargo_cap == 0) continue; artic_part++; GoodsEntry *ge = &st->goods[v->cargo_type]; if (HasBit(v->vehicle_flags, VF_CARGO_UNLOADING) && (front->current_order.GetUnloadType() & OUFB_NO_UNLOAD) == 0) { uint cargo_count = v->cargo.UnloadCount(); uint amount_unloaded = _settings_game.order.gradual_loading ? min(cargo_count, GetLoadAmount(v)) : cargo_count; bool remaining = false; // Are there cargo entities in this vehicle that can still be unloaded here? assert(payment != NULL); payment->SetCargo(v->cargo_type); if (!HasBit(ge->status, GoodsEntry::GES_ACCEPTANCE) && v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER) > 0) { /* The station does not accept our goods anymore. */ if (front->current_order.GetUnloadType() & (OUFB_TRANSFER | OUFB_UNLOAD)) { /* Transfer instead of delivering. */ v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_TRANSFER>( v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER), INVALID_STATION); } else { uint new_remaining = v->cargo.RemainingCount() + v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER); if (v->cargo_cap < new_remaining) { /* Return some of the reserved cargo to not overload the vehicle. */ v->cargo.Return(new_remaining - v->cargo_cap, &ge->cargo, INVALID_STATION); } /* Keep instead of delivering. This may lead to no cargo being unloaded, so ...*/ v->cargo.Reassign<VehicleCargoList::MTA_DELIVER, VehicleCargoList::MTA_KEEP>( v->cargo.ActionCount(VehicleCargoList::MTA_DELIVER)); /* ... say we unloaded something, otherwise we'll think we didn't unload * something and we didn't load something, so we must be finished * at this station. Setting the unloaded means that we will get a * retry for loading in the next cycle. */ anything_unloaded = true; } } if (v->cargo.ActionCount(VehicleCargoList::MTA_TRANSFER) > 0) { /* Mark the station dirty if we transfer, but not if we only deliver. */ dirty_station = true; if (!ge->HasRating()) { /* Upon transfering cargo, make sure the station has a rating. Fake a pickup for the * first unload to prevent the cargo from quickly decaying after the initial drop. */ ge->time_since_pickup = 0; SetBit(ge->status, GoodsEntry::GES_RATING); } } amount_unloaded = v->cargo.Unload(amount_unloaded, &ge->cargo, payment); remaining = v->cargo.UnloadCount() > 0; if (amount_unloaded > 0) { dirty_vehicle = true; anything_unloaded = true; new_load_unload_ticks += amount_unloaded; /* Deliver goods to the station */ st->time_since_unload = 0; } if (_settings_game.order.gradual_loading && remaining) { completely_emptied = false; } else { /* We have finished unloading (cargo count == 0) */ ClrBit(v->vehicle_flags, VF_CARGO_UNLOADING); } continue; } /* Do not pick up goods when we have no-load set or loading is stopped. */ if (front->current_order.GetLoadType() & OLFB_NO_LOAD || HasBit(front->vehicle_flags, VF_STOP_LOADING)) continue; /* This order has a refit, if this is the first vehicle part carrying cargo and the whole vehicle is empty, try refitting. */ if (front->current_order.IsRefit() && artic_part == 1) { HandleStationRefit(v, consist_capleft, st, next_station, front->current_order.GetRefitCargo()); ge = &st->goods[v->cargo_type]; } /* As we're loading here the following link can carry the full capacity of the vehicle. */ v->refit_cap = v->cargo_cap; /* update stats */ int t; switch (front->type) { case VEH_TRAIN: case VEH_SHIP: t = front->vcache.cached_max_speed; break; case VEH_ROAD: t = front->vcache.cached_max_speed / 2; break; case VEH_AIRCRAFT: t = Aircraft::From(front)->GetSpeedOldUnits(); // Convert to old units. break; default: NOT_REACHED(); } /* if last speed is 0, we treat that as if no vehicle has ever visited the station. */ ge->last_speed = min(t, 255); ge->last_age = min(_cur_year - front->build_year, 255); ge->time_since_pickup = 0; assert(v->cargo_cap >= v->cargo.StoredCount()); /* If there's goods waiting at the station, and the vehicle * has capacity for it, load it on the vehicle. */ uint cap_left = v->cargo_cap - v->cargo.StoredCount(); if (cap_left > 0 && (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0 || ge->cargo.AvailableCount() > 0)) { if (v->cargo.StoredCount() == 0) TriggerVehicle(v, VEHICLE_TRIGGER_NEW_CARGO); if (_settings_game.order.gradual_loading) cap_left = min(cap_left, GetLoadAmount(v)); uint loaded = ge->cargo.Load(cap_left, &v->cargo, st->xy, next_station); if (v->cargo.ActionCount(VehicleCargoList::MTA_LOAD) > 0) { /* Remember if there are reservations left so that we don't stop * loading before they're loaded. */ SetBit(reservation_left, v->cargo_type); } /* Store whether the maximum possible load amount was loaded or not.*/ if (loaded == cap_left) { SetBit(full_load_amount, v->cargo_type); } else { ClrBit(full_load_amount, v->cargo_type); } /* TODO: Regarding this, when we do gradual loading, we * should first unload all vehicles and then start * loading them. Since this will cause * VEHICLE_TRIGGER_EMPTY to be called at the time when * the whole vehicle chain is really totally empty, the * completely_emptied assignment can then be safely * removed; that's how TTDPatch behaves too. --pasky */ if (loaded > 0) { completely_emptied = false; anything_loaded = true; st->time_since_load = 0; st->last_vehicle_type = v->type; if (ge->cargo.TotalCount() == 0) { TriggerStationRandomisation(st, st->xy, SRT_CARGO_TAKEN, v->cargo_type); TriggerStationAnimation(st, st->xy, SAT_CARGO_TAKEN, v->cargo_type); AirportAnimationTrigger(st, AAT_STATION_CARGO_TAKEN, v->cargo_type); } new_load_unload_ticks += loaded; dirty_vehicle = dirty_station = true; } } if (v->cargo.StoredCount() >= v->cargo_cap) { SetBit(cargo_full, v->cargo_type); } else { SetBit(cargo_not_full, v->cargo_type); } } if (anything_loaded || anything_unloaded) { if (front->type == VEH_TRAIN) { TriggerStationRandomisation(st, front->tile, SRT_TRAIN_LOADS); TriggerStationAnimation(st, front->tile, SAT_TRAIN_LOADS); } } /* Only set completely_emptied, if we just unloaded all remaining cargo */ completely_emptied &= anything_unloaded; if (!anything_unloaded) delete payment; ClrBit(front->vehicle_flags, VF_STOP_LOADING); if (anything_loaded || anything_unloaded) { if (_settings_game.order.gradual_loading) { /* The time it takes to load one 'slice' of cargo or passengers depends * on the vehicle type - the values here are those found in TTDPatch */ const uint gradual_loading_wait_time[] = { 40, 20, 10, 20 }; new_load_unload_ticks = gradual_loading_wait_time[front->type]; } /* We loaded less cargo than possible for all cargo types and it's not full * load and we're not supposed to wait any longer: stop loading. */ if (!anything_unloaded && full_load_amount == 0 && reservation_left == 0 && !(front->current_order.GetLoadType() & OLFB_FULL_LOAD) && front->current_order_time >= (uint)max(front->current_order.GetTimetabledWait() - front->lateness_counter, 0)) { SetBit(front->vehicle_flags, VF_STOP_LOADING); } UpdateLoadUnloadTicks(front, st, new_load_unload_ticks); } else { UpdateLoadUnloadTicks(front, st, 20); // We need the ticks for link refreshing. bool finished_loading = true; if (front->current_order.GetLoadType() & OLFB_FULL_LOAD) { if (front->current_order.GetLoadType() == OLF_FULL_LOAD_ANY) { /* if the aircraft carries passengers and is NOT full, then * continue loading, no matter how much mail is in */ if ((front->type == VEH_AIRCRAFT && IsCargoInClass(front->cargo_type, CC_PASSENGERS) && front->cargo_cap > front->cargo.StoredCount()) || (cargo_not_full != 0 && (cargo_full & ~cargo_not_full) == 0)) { // There are still non-full cargoes finished_loading = false; } } else if (cargo_not_full != 0) { finished_loading = false; } /* Refresh next hop stats if we're full loading to make the links * known to the distribution algorithm and allow cargo to be sent * along them. Otherwise the vehicle could wait for cargo * indefinitely if it hasn't visited the other links yet, or if the * links die while it's loading. */ if (!finished_loading) LinkRefresher::Run(front, true, true); } SB(front->vehicle_flags, VF_LOADING_FINISHED, 1, finished_loading); } /* Calculate the loading indicator fill percent and display * In the Game Menu do not display indicators * If _settings_client.gui.loading_indicators == 2, show indicators (bool can be promoted to int as 0 or 1 - results in 2 > 0,1 ) * if _settings_client.gui.loading_indicators == 1, _local_company must be the owner or must be a spectator to show ind., so 1 > 0 * if _settings_client.gui.loading_indicators == 0, do not display indicators ... 0 is never greater than anything */ if (_game_mode != GM_MENU && (_settings_client.gui.loading_indicators > (uint)(front->owner != _local_company && _local_company != COMPANY_SPECTATOR))) { StringID percent_up_down = STR_NULL; int percent = CalcPercentVehicleFilled(front, &percent_up_down); if (front->fill_percent_te_id == INVALID_TE_ID) { front->fill_percent_te_id = ShowFillingPercent(front->x_pos, front->y_pos, front->z_pos + 20, percent, percent_up_down); } else { UpdateFillingPercent(front->fill_percent_te_id, percent, percent_up_down); } } if (completely_emptied) { /* Make sure the vehicle is marked dirty, since we need to update the NewGRF * properties such as weight, power and TE whenever the trigger runs. */ dirty_vehicle = true; TriggerVehicle(front, VEHICLE_TRIGGER_EMPTY); } if (dirty_vehicle) { SetWindowDirty(GetWindowClassForVehicleType(front->type), front->owner); SetWindowDirty(WC_VEHICLE_DETAILS, front->index); front->MarkDirty(); } if (dirty_station) { st->MarkTilesDirty(true); SetWindowDirty(WC_STATION_VIEW, last_visited); InvalidateWindowData(WC_STATION_LIST, last_visited); } } /** * Load/unload the vehicles in this station according to the order * they entered. * @param st the station to do the loading/unloading for */ void LoadUnloadStation(Station *st) { /* No vehicle is here... */ if (st->loading_vehicles.empty()) return; Vehicle *last_loading = NULL; std::list<Vehicle *>::iterator iter; /* Check if anything will be loaded at all. Otherwise we don't need to reserve either. */ for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) { Vehicle *v = *iter; if ((v->vehstatus & (VS_STOPPED | VS_CRASHED))) continue; assert(v->load_unload_ticks != 0); if (--v->load_unload_ticks == 0) last_loading = v; } /* We only need to reserve and load/unload up to the last loading vehicle. * Anything else will be forgotten anyway after returning from this function. * * Especially this means we do _not_ need to reserve cargo for a single * consist in a station which is not allowed to load yet because its * load_unload_ticks is still not 0. */ if (last_loading == NULL) return; for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end(); ++iter) { Vehicle *v = *iter; if (!(v->vehstatus & (VS_STOPPED | VS_CRASHED))) LoadUnloadVehicle(v); if (v == last_loading) break; } /* Call the production machinery of industries */ const Industry * const *isend = _cargo_delivery_destinations.End(); for (Industry **iid = _cargo_delivery_destinations.Begin(); iid != isend; iid++) { TriggerIndustryProduction(*iid); } _cargo_delivery_destinations.Clear(); } /** * Monthly update of the economic data (of the companies as well as economic fluctuations). */ void CompaniesMonthlyLoop() { CompaniesGenStatistics(); if (_settings_game.economy.inflation) { AddInflation(); RecomputePrices(); } CompaniesPayInterest(); HandleEconomyFluctuations(); } static void DoAcquireCompany(Company *c) { CompanyID ci = c->index; CompanyNewsInformation *cni = MallocT<CompanyNewsInformation>(1); cni->FillData(c, Company::Get(_current_company)); SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE); SetDParam(1, c->bankrupt_value == 0 ? STR_NEWS_MERGER_TAKEOVER_TITLE : STR_NEWS_COMPANY_MERGER_DESCRIPTION); SetDParamStr(2, cni->company_name); SetDParamStr(3, cni->other_company_name); SetDParam(4, c->bankrupt_value); AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni); AI::BroadcastNewEvent(new ScriptEventCompanyMerger(ci, _current_company)); Game::NewEvent(new ScriptEventCompanyMerger(ci, _current_company)); ChangeOwnershipOfCompanyItems(ci, _current_company); if (c->bankrupt_value == 0) { Company *owner = Company::Get(_current_company); owner->current_loan += c->current_loan; } if (c->is_ai) AI::Stop(c->index); DeleteCompanyWindows(ci); InvalidateWindowClassesData(WC_TRAINS_LIST, 0); InvalidateWindowClassesData(WC_SHIPS_LIST, 0); InvalidateWindowClassesData(WC_ROADVEH_LIST, 0); InvalidateWindowClassesData(WC_AIRCRAFT_LIST, 0); delete c; } extern int GetAmountOwnedBy(const Company *c, Owner owner); /** * Acquire shares in an opposing company. * @param tile unused * @param flags type of operation * @param p1 company to buy the shares from * @param p2 unused * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { CommandCost cost(EXPENSES_OTHER); CompanyID target_company = (CompanyID)p1; Company *c = Company::GetIfValid(target_company); /* Check if buying shares is allowed (protection against modified clients) * Cannot buy own shares */ if (c == NULL || !_settings_game.economy.allow_shares || _current_company == target_company) return CMD_ERROR; /* Protect new companies from hostile takeovers */ if (_cur_year - c->inaugurated_year < 6) return_cmd_error(STR_ERROR_PROTECTED); /* Those lines are here for network-protection (clients can be slow) */ if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 0) return cost; if (GetAmountOwnedBy(c, COMPANY_SPECTATOR) == 1) { if (!c->is_ai) return cost; // We can not buy out a real company (temporarily). TODO: well, enable it obviously. if (GetAmountOwnedBy(c, _current_company) == 3 && !MayCompanyTakeOver(_current_company, target_company)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME); } cost.AddCost(CalculateCompanyValue(c) >> 2); if (flags & DC_EXEC) { OwnerByte *b = c->share_owners; while (*b != COMPANY_SPECTATOR) b++; // share owners is guaranteed to contain at least one COMPANY_SPECTATOR *b = _current_company; for (int i = 0; c->share_owners[i] == _current_company;) { if (++i == 4) { c->bankrupt_value = 0; DoAcquireCompany(c); break; } } InvalidateWindowData(WC_COMPANY, target_company); CompanyAdminUpdate(c); } return cost; } /** * Sell shares in an opposing company. * @param tile unused * @param flags type of operation * @param p1 company to sell the shares from * @param p2 unused * @param text unused * @return the cost of this operation or an error */ CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { CompanyID target_company = (CompanyID)p1; Company *c = Company::GetIfValid(target_company); /* Cannot sell own shares */ if (c == NULL || _current_company == target_company) return CMD_ERROR; /* Check if selling shares is allowed (protection against modified clients). * However, we must sell shares of companies being closed down. */ if (!_settings_game.economy.allow_shares && !(flags & DC_BANKRUPT)) return CMD_ERROR; /* Those lines are here for network-protection (clients can be slow) */ if (GetAmountOwnedBy(c, _current_company) == 0) return CommandCost(); /* adjust it a little to make it less profitable to sell and buy */ Money cost = CalculateCompanyValue(c) >> 2; cost = -(cost - (cost >> 7)); if (flags & DC_EXEC) { OwnerByte *b = c->share_owners; while (*b != _current_company) b++; // share owners is guaranteed to contain company *b = COMPANY_SPECTATOR; InvalidateWindowData(WC_COMPANY, target_company); CompanyAdminUpdate(c); } return CommandCost(EXPENSES_OTHER, cost); } /** * Buy up another company. * When a competing company is gone bankrupt you get the chance to purchase * that company. * @todo currently this only works for AI companies * @param tile unused * @param flags type of operation * @param p1 company to buy up * @param p2 unused * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { CompanyID target_company = (CompanyID)p1; Company *c = Company::GetIfValid(target_company); if (c == NULL) return CMD_ERROR; /* Disable takeovers when not asked */ if (!HasBit(c->bankrupt_asked, _current_company)) return CMD_ERROR; /* Disable taking over the local company in single player */ if (!_networking && _local_company == c->index) return CMD_ERROR; /* Do not allow companies to take over themselves */ if (target_company == _current_company) return CMD_ERROR; /* Disable taking over when not allowed. */ if (!MayCompanyTakeOver(_current_company, target_company)) return CMD_ERROR; /* Get the cost here as the company is deleted in DoAcquireCompany. */ CommandCost cost(EXPENSES_OTHER, c->bankrupt_value); if (flags & DC_EXEC) { DoAcquireCompany(c); } return cost; }
shoter/N.A.S.Z-OpenTTD
src/economy.cpp
C++
gpl-2.0
74,819
#include "ClickLabel.h" #include "Source Files/Fonction/Fonction.h" #include "Source Files/Application/Input/InputController.h" ClickLabel::ClickLabel(QWidget* parent, const sf::Vector2i& range, enum_size e_size, bool auto_emit) : ViewLabel(parent, e_size) { this->range = range; this->auto_emit = auto_emit; setFocusPolicy(Qt::TabFocus); setMouseTracking(true); QObject::connect(&timer, SIGNAL(timeout()), this, SLOT(run())); timer.setInterval(16); } void ClickLabel::mousePressEvent(QMouseEvent* Qm) { switch (Qm->button()) { case Qt::LeftButton: add = true; ex_value = value; frame_cpt = 0; run(); timer.start(); break; case Qt::RightButton: sub = true; ex_value = value; frame_cpt = 0; run(); timer.start(); break; default: break; } Qm->accept(); } void ClickLabel::mouseReleaseEvent(QMouseEvent* Qm) { switch (Qm->button()) { case Qt::LeftButton: add = false; timer.stop(); break; case Qt::RightButton: sub = false; timer.stop(); break; default: break; } if (!auto_emit) if (ex_value != value) emit valueChanged(value); Qm->accept(); } void ClickLabel::mouseMoveEvent(QMouseEvent* Qm) { if (!hasFocus()) setFocus(); Qm->accept(); } void ClickLabel::wheelEvent(QWheelEvent* Qw) { QPoint numDegrees = Qw->angleDelta(); if (!numDegrees.isNull()) { add = numDegrees.y() > 0; sub = numDegrees.y() < 0; ex_value = value; frame_cpt = 0; run(); add = false; sub = false; } if (!auto_emit) if (ex_value != value) emit valueChanged(value); Qw->accept(); } int ClickLabel::checkRange(int& value) { int return_value = DEFAULT; if (value > range.y) { value = range.y; return_value += UP_LIMIT_REACHED + LIMIT_REACHED; } else if (value < range.x) { value = range.x; return_value += DOWN_LIMIT_REACHED + LIMIT_REACHED; } int num_digits = Fonction::numDigits(value); if (num_digits == 1) return_value += ONE_DIGIT; else if (num_digits == Fonction::numDigits(range.y)) return_value += MAX_DIGIT; return return_value; } void ClickLabel::endValueTyping() { if (text_initiated) { write_back = false; text_initiated = false; if (!auto_emit) if (ex_keyboard_value != value) emit valueChanged(value); } } void ClickLabel::keyPressEvent(QKeyEvent* Qk) { int key = Qk->key(); if (key >= 0x30 && key <= 0x39) { // Key_0 - Key_9 if (!text_initiated) { ex_keyboard_value = value; text_initiated = true; } if (!write_back) { write_back = true; int new_value = key - 0x30; if (checkRange(new_value) & UP_LIMIT_REACHED) write_back = false; setValue(new_value); } else { int new_value = value*10 + key - 0x30; if (checkRange(new_value) & UP_LIMIT_REACHED) write_back = false; setValue(new_value); } } else if (key == Qt::Key_Backspace) { if (!text_initiated) { ex_keyboard_value = value; text_initiated = true; } int new_value = value / 10; if (checkRange(new_value) & DOWN_LIMIT_REACHED) write_back = false; else write_back = true; setValue(new_value); } else endValueTyping(); Qk->accept(); } void ClickLabel::focusInEvent(QFocusEvent* event) { QWidget::focusInEvent(event); setText(QString()); // Force text display (see QTBUG-53982) setText(QString::fromStdString(prefixe + std::to_string(value))); write_back = false; value_at_focus_in = value; emit focusIn(); } void ClickLabel::focusOutEvent(QFocusEvent* event) { QWidget::focusOutEvent(event); endValueTyping(); if (value_at_focus_in != value) emit focusOut(); } void ClickLabel::run() { write_back = false; if (frame_cpt == 0 || frame_cpt > 20) { int incr_value = static_cast<int>(add) - static_cast<int>(sub); // No QApplication:keyboardModifiers() due to a bug (?) if (INPUT->pressed(Qt::Key_Shift) && INPUT->pressed(Qt::Key_Control)) incr_value = incr_value * 100; else if (INPUT->pressed(Qt::Key_Shift)) incr_value = incr_value * 50; else if (INPUT->pressed(Qt::Key_Control)) incr_value = incr_value * 5; int new_value = value + incr_value; checkRange(new_value); setValue(new_value); } frame_cpt++; } void ClickLabel::setValue(int value) { if (this->value != value) { setText(QString::fromStdString(prefixe + std::to_string(value))); this->value = value; if (auto_emit) emit valueChanged(value); } } void ClickLabel::changeValue(int value) { if (this->value != value) { setText(QString::fromStdString(prefixe + std::to_string(value))); this->value = value; } }
FlorianPO/SpriteEditor
SQT/Source Files/Widget/Various/Label/ClickLabel.cpp
C++
gpl-2.0
4,536
/* opensslconf.h */ /* WARNING: Generated automatically from opensslconf.h.in by Configure. */ #ifdef __cplusplus extern "C" { #endif /* OpenSSL was configured with the following options: */ #ifndef OPENSSL_SYSNAME_iOS # define OPENSSL_SYSNAME_iOS #endif #ifndef OPENSSL_DOING_MAKEDEPEND #ifndef OPENSSL_NO_EC_NISTP_64_GCC_128 # define OPENSSL_NO_EC_NISTP_64_GCC_128 #endif #ifndef OPENSSL_NO_GMP # define OPENSSL_NO_GMP #endif #ifndef OPENSSL_NO_JPAKE # define OPENSSL_NO_JPAKE #endif #ifndef OPENSSL_NO_KRB5 # define OPENSSL_NO_KRB5 #endif #ifndef OPENSSL_NO_MD2 # define OPENSSL_NO_MD2 #endif #ifndef OPENSSL_NO_RC5 # define OPENSSL_NO_RC5 #endif #ifndef OPENSSL_NO_RFC3779 # define OPENSSL_NO_RFC3779 #endif #ifndef OPENSSL_NO_SCTP # define OPENSSL_NO_SCTP #endif #ifndef OPENSSL_NO_STORE # define OPENSSL_NO_STORE #endif #ifndef OPENSSL_NO_UNIT_TEST # define OPENSSL_NO_UNIT_TEST #endif #endif /* OPENSSL_DOING_MAKEDEPEND */ #ifndef OPENSSL_THREADS # define OPENSSL_THREADS #endif #ifndef OPENSSL_NO_DYNAMIC_ENGINE # define OPENSSL_NO_DYNAMIC_ENGINE #endif /* The OPENSSL_NO_* macros are also defined as NO_* if the application asks for it. This is a transient feature that is provided for those who haven't had the time to do the appropriate changes in their applications. */ #ifdef OPENSSL_ALGORITHM_DEFINES # if defined(OPENSSL_NO_EC_NISTP_64_GCC_128) && !defined(NO_EC_NISTP_64_GCC_128) # define NO_EC_NISTP_64_GCC_128 # endif # if defined(OPENSSL_NO_GMP) && !defined(NO_GMP) # define NO_GMP # endif # if defined(OPENSSL_NO_JPAKE) && !defined(NO_JPAKE) # define NO_JPAKE # endif # if defined(OPENSSL_NO_KRB5) && !defined(NO_KRB5) # define NO_KRB5 # endif # if defined(OPENSSL_NO_MD2) && !defined(NO_MD2) # define NO_MD2 # endif # if defined(OPENSSL_NO_RC5) && !defined(NO_RC5) # define NO_RC5 # endif # if defined(OPENSSL_NO_RFC3779) && !defined(NO_RFC3779) # define NO_RFC3779 # endif # if defined(OPENSSL_NO_SCTP) && !defined(NO_SCTP) # define NO_SCTP # endif # if defined(OPENSSL_NO_STORE) && !defined(NO_STORE) # define NO_STORE # endif # if defined(OPENSSL_NO_UNIT_TEST) && !defined(NO_UNIT_TEST) # define NO_UNIT_TEST # endif #endif /* crypto/opensslconf.h.in */ /* Generate 80386 code? */ #undef I386_ONLY #if !(defined(VMS) || defined(__VMS)) /* VMS uses logical names instead */ #if defined(HEADER_CRYPTLIB_H) && !defined(OPENSSLDIR) #define ENGINESDIR "/Users/t/dev/OpenSSL_build101j/bin/iPhoneSimulator8.0-i386.sdk/lib/engines" #define OPENSSLDIR "/Users/t/dev/OpenSSL_build101j/bin/iPhoneSimulator8.0-i386.sdk" #endif #endif #undef OPENSSL_UNISTD #define OPENSSL_UNISTD <unistd.h> #undef OPENSSL_EXPORT_VAR_AS_FUNCTION #if defined(HEADER_IDEA_H) && !defined(IDEA_INT) #define IDEA_INT unsigned int #endif #if defined(HEADER_MD2_H) && !defined(MD2_INT) #define MD2_INT unsigned int #endif #if defined(HEADER_RC2_H) && !defined(RC2_INT) /* I need to put in a mod for the alpha - eay */ #define RC2_INT unsigned int #endif #if defined(HEADER_RC4_H) #if !defined(RC4_INT) /* using int types make the structure larger but make the code faster * on most boxes I have tested - up to %20 faster. */ /* * I don't know what does "most" mean, but declaring "int" is a must on: * - Intel P6 because partial register stalls are very expensive; * - elder Alpha because it lacks byte load/store instructions; */ #define RC4_INT unsigned char #endif #if !defined(RC4_CHUNK) /* * This enables code handling data aligned at natural CPU word * boundary. See crypto/rc4/rc4_enc.c for further details. */ #define RC4_CHUNK unsigned long #endif #endif #if (defined(HEADER_NEW_DES_H) || defined(HEADER_DES_H)) && !defined(DES_LONG) /* If this is set to 'unsigned int' on a DEC Alpha, this gives about a * %20 speed up (longs are 8 bytes, int's are 4). */ #ifndef DES_LONG #define DES_LONG unsigned long #endif #endif #if defined(HEADER_BN_H) && !defined(CONFIG_HEADER_BN_H) #define CONFIG_HEADER_BN_H #define BN_LLONG /* Should we define BN_DIV2W here? */ /* Only one for the following should be defined */ #undef SIXTY_FOUR_BIT_LONG #undef SIXTY_FOUR_BIT #define THIRTY_TWO_BIT #endif #if defined(HEADER_RC4_LOCL_H) && !defined(CONFIG_HEADER_RC4_LOCL_H) #define CONFIG_HEADER_RC4_LOCL_H /* if this is defined data[i] is used instead of *data, this is a %20 * speedup on x86 */ #undef RC4_INDEX #endif #if defined(HEADER_BF_LOCL_H) && !defined(CONFIG_HEADER_BF_LOCL_H) #define CONFIG_HEADER_BF_LOCL_H #define BF_PTR #endif /* HEADER_BF_LOCL_H */ #if defined(HEADER_DES_LOCL_H) && !defined(CONFIG_HEADER_DES_LOCL_H) #define CONFIG_HEADER_DES_LOCL_H #ifndef DES_DEFAULT_OPTIONS /* the following is tweaked from a config script, that is why it is a * protected undef/define */ #ifndef DES_PTR #undef DES_PTR #endif /* This helps C compiler generate the correct code for multiple functional * units. It reduces register dependancies at the expense of 2 more * registers */ #ifndef DES_RISC1 #undef DES_RISC1 #endif #ifndef DES_RISC2 #undef DES_RISC2 #endif #if defined(DES_RISC1) && defined(DES_RISC2) YOU SHOULD NOT HAVE BOTH DES_RISC1 AND DES_RISC2 DEFINED!!!!! #endif /* Unroll the inner loop, this sometimes helps, sometimes hinders. * Very mucy CPU dependant */ #ifndef DES_UNROLL #define DES_UNROLL #endif /* These default values were supplied by * Peter Gutman <pgut001@cs.auckland.ac.nz> * They are only used if nothing else has been defined */ #if !defined(DES_PTR) && !defined(DES_RISC1) && !defined(DES_RISC2) && !defined(DES_UNROLL) /* Special defines which change the way the code is built depending on the CPU and OS. For SGI machines you can use _MIPS_SZLONG (32 or 64) to find even newer MIPS CPU's, but at the moment one size fits all for optimization options. Older Sparc's work better with only UNROLL, but there's no way to tell at compile time what it is you're running on */ #if defined( sun ) /* Newer Sparc's */ # define DES_PTR # define DES_RISC1 # define DES_UNROLL #elif defined( __ultrix ) /* Older MIPS */ # define DES_PTR # define DES_RISC2 # define DES_UNROLL #elif defined( __osf1__ ) /* Alpha */ # define DES_PTR # define DES_RISC2 #elif defined ( _AIX ) /* RS6000 */ /* Unknown */ #elif defined( __hpux ) /* HP-PA */ /* Unknown */ #elif defined( __aux ) /* 68K */ /* Unknown */ #elif defined( __dgux ) /* 88K (but P6 in latest boxes) */ # define DES_UNROLL #elif defined( __sgi ) /* Newer MIPS */ # define DES_PTR # define DES_RISC2 # define DES_UNROLL #elif defined(i386) || defined(__i386__) /* x86 boxes, should be gcc */ # define DES_PTR # define DES_RISC1 # define DES_UNROLL #endif /* Systems-specific speed defines */ #endif #endif /* DES_DEFAULT_OPTIONS */ #endif /* HEADER_DES_LOCL_H */ #ifdef __cplusplus } #endif
mkttanabe/stone-for-iOS
stone/OpenSSL/include/openssl/opensslconf.h
C
gpl-2.0
6,763
# # some backup SW doesn't restore mountpoints properly # # # create missing directories pushd /mnt/local >&8 if [ -z "$MOUNTPOINTS_TO_RESTORE" ]; then mkdir -p mnt proc run sys tmp dev/pts dev/shm else LogPrint "Restore the Mountpoints $MOUNTPOINTS_TO_RESTORE". mkdir -p $MOUNTPOINTS_TO_RESTORE # ensure some important mountpoints will be restored: for _dir in mnt proc sys tmp dev/pts dev/shm do ! [ -d "$_dir" ] && mkdir -p $_dir done fi chmod 1777 tmp popd >&8
rg-fine/rear
usr/share/rear/restore/default/90_create_missing_directories.sh
Shell
gpl-2.0
500
cmd_net/bluetooth/bnep/bnep.o := /home/knesi/arm-2010q1/bin/arm-none-linux-gnueabi-ld -EL -r -o net/bluetooth/bnep/bnep.o net/bluetooth/bnep/core.o net/bluetooth/bnep/sock.o net/bluetooth/bnep/netdev.o
DrGrip/tiamat-2.6.38-LEO-Dr_Grip
net/bluetooth/bnep/.bnep.o.cmd
Batchfile
gpl-2.0
206
using System; namespace Server.Mobiles { [CorpseName("a grubber corpse")] public class Grubber : BaseCreature { [Constructable] public Grubber() : base(AIType.AI_Animal, FightMode.None, 10, 1, 0.06, 0.1) { Name = "a grubber"; Body = 270; SetStr(15); SetDex(2000); SetInt(1000); SetHits(200); SetStam(500); SetMana(0); SetDamage(1); SetDamageType(ResistanceType.Physical, 100); SetSkill(SkillName.MagicResist, 200.0); SetSkill(SkillName.Tactics, 5.0); SetSkill(SkillName.Wrestling, 5.0); Fame = 1000; Karma = 0; } public override IDamageable Combatant { get { return base.Combatant; } set { base.Combatant = value; if (0.10 > Utility.RandomDouble()) StopFlee(); else if (!CheckFlee()) BeginFlee(TimeSpan.FromSeconds(10)); } } public Grubber(Serial serial) : base(serial) { } public override int Meat => 1; public override int Hides => 1; public override int GetAttackSound() { return 0xC9; } public override int GetHurtSound() { return 0xCA; } public override int GetDeathSound() { return 0xCB; } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write(0); } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Argalep/ServUO
Scripts/Mobiles/Normal/Grubber.cs
C#
gpl-2.0
1,886
--- layout: post title: Shell tools are incredibly useful published: true --- So this is a small post on something pretty cool I was able to do that I thought was worth sharing. This summer I'll be doing research on speedreading as well as taking a course for school called [Cyber Physical Systems](https://classroom.udacity.com/courses/ud279). I got interested in the question of whether I'd be able to speedread the course materials. So I downloaded the transcripts and took a look. The transcripts all come in the form of .srt files which are a little inconvenient to work with, and there was a LOT of them, 302 to be specific. ```shell $ ls -la ./transcripts/* ... -rw------- 1.2K 89 - Intro to Industrial Networks - lang_en_vs1.srt -rw------- 2.8K 9 - Class Structure - lang_en_vs51.srt -rw------- 3.0K 90 - Industrial Control System - lang_en_vs51.srt -rw------- 2.1K 91 - Industrial Protocols - lang_en_vs51.srt -rw------- 3.8K 92 - Routable Networks - lang_en_vs51.srt -rw------- 2.8K 93 - Enterprise or Business Network - lang_en_vs51.srt -rw------- 1.8K 94 - Zones and Enclaves - lang_en_vs51.srt $ cat ./transcripts/* | wc -l 38744 # here's a random file in the corpus for an example of what we're dealing with. $ cat 93\ -\ Enterprise\ or\ Business\ Network\ -\ lang_en_vs51.srt 1 00:00:00,360 --> 00:00:03,340 An ICS is really an isolated network. 2 00:00:03,340 --> 00:00:08,270 For every factory floor, electric generator, petroleum refinery or 3 00:00:08,270 --> 00:00:11,450 pipeline, theres a corporation or organization that owns and 4 00:00:11,450 --> 00:00:12,850 operates the facility. . . . ``` So as you can see there's a lot of space being wasted and a lot of cleaning we can do here. ```shell # let's concat all the transcript files in numerical order into one file for i in {1..302}; do cat $i\ * >> OUTPUT; done # then I'll use vim to open the massive file and start carving it up $ vim OUTPUT # delete all empty lines :g/^\s*$/d # delete all lines containing only numbers :g/^[0-9]$/d # remove all lines with timestamps :g/^00\:*/d # removed all <i> tags and removed all </i> tags :s/<i>//g :s/<\/i>//g ``` These steps together trimmed over `12000` lines of needless text. I then converted from windows to unix line endings : ``` tr -d '\15\32' < windows.txt > unix.txt ``` To remove the `&gt;`s I highlighted the entire corpus and just cleared them out. ``` :s/&gt; //g ```` Text all looks like this : ``` And we earnestly hope that it will prepare you to secure the next generation of cyber-physical systems. We're eager to hear what you end up doing next. The fate of the world is in your hands. ``` To clean this up a bit I replaced all `\n\n` with a single `\n`. Now it looks something like this : ``` the low voltage looks like. We can add to the lower terminal power a little power supply to the low or common terminal, connected the high terminal of the power supply to the input switches. That's all it took to simulate our system. So now we know how the system was set up. So how's the PLC actually programmed? For this project, we programmed the PLC using which is a graphical programming language that is based on the old practice of programming logic with hardware relays. The programming environment that we . . . ``` It's not perfect but very usable for my purposes, as I wanted the filtered raw text to put into another platform. There were a few other cleanups like removing `[INAUDIBLE]` from the corpus. My original input size of `38744` lines was down to just `7000` lines. That's just 18% of text content that actually needed to be there!! Fun stuff. The lesson here? Learn the shell tools. They are so great and will come in handy all the time. > Now it remains to be seen whether I can speedread the entire course in an hour. Wish me luck!
DavidAwad/davidawad.github.io
_posts/2019-05-9-shellparsing.md
Markdown
gpl-2.0
3,840
<?php $GLOBALS['tstart'] = array_sum(explode(" ", microtime())); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <HTML xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?= $title; ?></title> <!--[if lt IE 7 ]><style type="text/css"> img { behavior: url(themes/NB-52/images/iepngfix.htc) } </style><![endif]--> <meta http-equiv="Content-Type" content="text/html; charset=<?= $site_config["CHARSET"]; ?>"> <link href="themes/NB-52/style.css" rel="stylesheet" type="text/css" /> <script type="text/javascript" src="themes/NB-52/js/jquery-1.3.2.min.js"></script> <script type="text/javascript" src="themes/NB-52/js/menu.js"></script> <script type="text/javascript" src="themes/NB-52/js/xbreadcrumbs.js"></script> <script src="themes/NB-52/js/jquery.easing.1.3.js" type="text/javascript"></script> <script src="themes/NB-52/js/jquery.kwicks-1.5.1.pack.js" type="text/javascript"></script> <script type="text/javascript"> $().ready(function() { $('.kwicks').kwicks({ max : 90, spacing : 0 }); }); </script> <script type="text/javascript"> $(document).ready(function(){ $('#jCrumbs').xBreadcrumbs(); }); </script> <script type="text/javascript" src="<?= $site_config["SITEURL"]; ?>/backend/java_klappe.js"></script> </head> <BODY> <div class='wrapperA'> <div class='wrapperB'> <table width='100%' border='0' cellspacing='0' cellpadding='0'> <tr> <td height='55'> <div class='navigation'> <ul class='jCrumbs' id='jCrumbs'> <li><a href='index.php'><span>Home</span></a></li> <li><a href='forums.php'><span>Forum</span></a></li> <li><a href='#'><span>Torrents</span></a> <ul> <li><a href='torrents-upload.php'>Upload A Torrent</a></li> <li><a href='torrents.php'>Browse Torrents</a></li> <li><a href='torrents-today.php'>Todays Torrents</a></li> <li><a href='torrents-search.php'>Search</a></li> <li><a href=torrents-needseed.php>Needing Seeds</a></li> </ul> </li> <li><a href='faq.php'><span>FAQ</span></a></li> </ul> </div> </td> </tr> <tr> <td height='13'><img src='themes/NB-52/images/head-t.png' width='1106' height='13' /></td> </tr> <tr> <td height='100' background='themes/NB-52/images/head-bg.png'><div class='logo'> <table width='100%' border='0' cellspacing='0' cellpadding='0'> <tr> <td height='39' valign='top'> <? if (!$CURUSER) { ?> <div class='myLogin'> <form method=post action=account-login.php> <fieldset> <input class='myLogin-n' type='text' name='username' /> <input class='myLogin-p' type='password' name='password' /> <input class='myLogin-b' type='submit' value=''> </fieldset> </form> </div> <? }else{ ?> <div class='mySearch'> <form method="get" action="torrents-search.php"> <fieldset> <?php if (!empty($searchstr)) { $value = stripslashes(htmlspecialchars($searchstr)); } else { $value = 'Search ...'; } ?> <input type='text' value="<?php echo $value; ?>" onfocus="if (this.value == 'Search ...') this.value = '';" onblur="if (this.value == '') this.value = 'Search ...';" name='search' id='q' class='mySearch-t'/> <input name="incldead" value="1" type="hidden"> <input type='submit' value='' class='mySearch-b' /> </fieldset> </form> </div> <div class="rss"><a href='rss.php'><img src="themes/NB-52/images/blank.gif" alt="RSS" title="RSS Feed" width="32" height="29" /></a></div> <? } ?> <div class='user'> <!-- START INFOBAR CODE --> <? if (!$CURUSER){ echo "[<a href=\"account-login.php\">". LOGIN . "</a>]<B> or </B>[<a href=\"account-signup.php\">" . SIGNUP . "</a>]&nbsp;&nbsp;"; }else{ print ("".LOGGEDINAS.": <span><b>".$CURUSER["username"]."</span>"); } ?> <!-- END INFOBAR CODE --> </div> </td> <td width='100' height='100' rowspan='2' align='center' valign='middle'> <div class='avatar'> <? $avatar = $CURUSER["avatar"]; if (!$avatar) { $avatar = "themes/NB-52/images/noavatar.png"; } if (!$CURUSER) { $avatar = "themes/NB-52/images/loggedout.png"; $salt = ""; }else{ $salt = "'s avatar"; } print ('<img src="' . $avatar . '" alt="' . $CURUSER[username] . $salt . '" name="' . $CURUSER[username] . $salt . '" title="' . $CURUSER[username] . $salt . '" border="0" width="70" height="70"" />'); ?> </div> </td> </tr> <tr> <td height='61'> <? if (!$CURUSER) { ?> <div id="toolbar"> <div id="kwick"> <ul class='kwicks'> <li id='kwick8'></li> <li id='kwick9'></li> <li id='kwick1'><a href='account-signup.php'>Sign Up</a></li> <li id='kwick2'><a href='account-recover.php'>Recover Account</a></li> </ul> </div> </div> <? } else { ?> <div id="toolbar"> <div id="kwick"> <ul class="kwicks"> <? if ($CURUSER["control_panel"]=="yes") {print("<li id='kwick6'><a href='admincp.php'>Admin CP</a></li>");}?> <li id='kwick4'><a href='account.php'>Account Settings</a></li> <? //check for new pm's $res = mysql_query("SELECT COUNT(*) FROM messages WHERE receiver=" . $CURUSER["id"] . " and unread='yes' AND location IN ('in','both')") or print(mysql_error()); $arr = mysql_fetch_row($res); $unreadmail = $arr[0]; if ($unreadmail){ print("<li id='kwick7'><a title='($unreadmail) New Messages' href='mailbox.php?inbox'>New Mail</a></li>"); }else{ print("<li id='kwick5'><a href='mailbox.php'>Mailbox</a></li>"); } ?> <li id='kwick3'><a href='account-logout.php'>Logout</a></li> </ul> </div> </div> <? } ?> </td> </tr> </table> </div></td> </tr> <tr> <td height='3'><img src='themes/NB-52/images/body-t.png' width='1106' height='3' /></td> </tr> <tr> <td valign='top' background='themes/NB-52/images/body-m.png'> <div class="lcol"> <?php //CODE if (isset($_COOKIE["blockswitcher"]) && $_COOKIE["blockswitcher"] == "left") { $blocks = leftblocks(); $block = "left"; } if (isset($_COOKIE["blockswitcher"]) && $_COOKIE["blockswitcher"] == "right"){ $blocks = rightblocks(); $block = "right"; } if (!isset($_COOKIE["blockswitcher"])){ leftblocks(); }else{ echo $blocks; } // echo $blocks; if ($block == "left") $link = "<a href='themes/NB-52/blockswitcher.php?switch=right'><img src='themes/NB-52/images/rcol.gif' border='0'></a>"; else $link = "<a href='themes/NB-52/blockswitcher.php?switch=left'><img src='themes/NB-52/images/lcol.gif' border='0'></a>"; ?> </div> <div class="col-switch"> <?php echo $link; ?> </div> <div class='mcol'> <? if ($site_config["MIDDLENAV"]){ middleblocks(); } //MIDDLENAV ON/OFF END ?>
thebananafish/gtracker-tt
themes/NB-52/header.php
PHP
gpl-2.0
7,623
__author__ = 'Andy Gallagher <andy.gallagher@theguardian.com>' import xml.etree.ElementTree as ET import dateutil.parser from .vidispine_api import always_string class VSMetadata: def __init__(self, initial_data={}): self.contentDict=initial_data self.primaryGroup = None def addValue(self,key,value): if key in self.contentDict: self.contentDict[key].append(value) else: self.contentDict[key]=[] self.contentDict[key].append(value) def setPrimaryGroup(self,g): self.primaryGroup = g def toXML(self,mdGroup=None): from datetime import datetime xmldoc=ET.ElementTree() ns = "{http://xml.vidispine.com/schema/vidispine}" rootEl=ET.Element('{0}MetadataDocument'.format(ns)) xmldoc._setroot(rootEl) timespanEl=ET.Element('{0}timespan'.format(ns), attrib={'start': '-INF', 'end': '+INF'}) rootEl.append(timespanEl) if mdGroup is None and self.primaryGroup is not None: mdGroup = self.primaryGroup if(mdGroup): groupEl=ET.Element('{0}group'.format(ns)) groupEl.text=mdGroup rootEl.append(groupEl) for key,value in list(self.contentDict.items()): fieldEl=ET.Element('{0}field'.format(ns)) nameEl=ET.Element('{0}name'.format(ns)) nameEl.text = key fieldEl.append(nameEl) if not isinstance(value,list): value = [value] for line in value: valueEl=ET.Element('{0}value'.format(ns)) if isinstance(line,datetime): line = line.strftime("%Y-%m-%dT%H:%M:%S%Z") valueEl.text = always_string(line) fieldEl.append(valueEl) timespanEl.append(fieldEl) return ET.tostring(rootEl,encoding="utf8").decode("utf8") class VSMetadataMixin(object): _xmlns = "{http://xml.vidispine.com/schema/vidispine}" @staticmethod def _safe_get_attrib(xmlnode, attribute, default): try: return xmlnode.attrib[attribute] except AttributeError: return default @staticmethod def _safe_get_subvalue(xmlnode, subnode_name, default): try: node = xmlnode.find(subnode_name) if node is not None: return node.text else: return default except AttributeError: return default class VSMetadataValue(VSMetadataMixin): def __init__(self, valuenode=None, uuid=None): self.user = None self.uuid = None self.timestamp = None self.change = None self.value = None if valuenode is not None: self.uuid = self._safe_get_attrib(valuenode,"uuid", None) self.user = self._safe_get_attrib(valuenode, "user", None) try: self.timestamp = dateutil.parser.parse(self._safe_get_attrib(valuenode,"timestamp", None)) except TypeError: #dateutil.parser got nothing self.timestamp = None self.change = self._safe_get_attrib(valuenode, "change", None) self.value = valuenode.text elif uuid is not None: self.uuid = uuid def __repr__(self): return "VSMetadataValue(\"{0}\")".format(self.value) def __eq__(self, other): return other.uuid==self.uuid class VSMetadataReference(VSMetadataMixin): def __init__(self, refnode=None, uuid=None): """ Initialises, either to an empty reference, to an existing uuid or to an xml fragment :param uuid: string representing the uuid of something to reference :param refnode: pointer to an elementtree node of <referenced> in a MetadataDocument """ if refnode is not None: self.uuid = self._safe_get_attrib(refnode,"uuid",None) self.id = self._safe_get_attrib(refnode,"id",None) self.type = self._safe_get_attrib(refnode,"type",None) if refnode is None and uuid is not None: self.uuid=uuid self.id = None self.type = None def __repr__(self): return "VSMetadataReference {0} to {1} {2}".format(self.uuid,self.type,self.id) def __eq__(self, other): return other.uuid==self.uuid class VSMetadataAttribute(VSMetadataMixin): """ this class represents the full metadata present in an xml <field> entry """ def __init__(self, fieldnode=None): if fieldnode is not None: self.uuid = self._safe_get_attrib(fieldnode,"uuid", None) self.user = self._safe_get_attrib(fieldnode, "user", None) try: self.timestamp = dateutil.parser.parse(self._safe_get_attrib(fieldnode,"timestamp", None)) except TypeError: #dateutil.parser got nothing self.timestamp = None self.change = self._safe_get_attrib(fieldnode,"change",None) self.name = self._safe_get_subvalue(fieldnode, "{0}name".format(self._xmlns), None) self.values = [VSMetadataValue(value_node) for value_node in fieldnode.findall('{0}value'.format(self._xmlns))] self.references = [VSMetadataReference(ref_node) for ref_node in fieldnode.findall('{0}referenced'.format(self._xmlns))] else: self.uuid = None self.user = None self.timestamp = None self.change = None self.name = None self.values = [] self.references = [] def __eq__(self, other): return other.uuid==self.uuid
fredex42/gnmvidispine
gnmvidispine/vs_metadata.py
Python
gpl-2.0
5,748
/* * OSPF Flooding -- RFC2328 Section 13. * Copyright (C) 1999, 2000 Toshiaki Takada * * This file is part of GNU Zebra. * * GNU Zebra 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, or (at your * option) any later version. * * GNU Zebra 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; see the file COPYING; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _ZEBRA_OSPF_FLOOD_H #define _ZEBRA_OSPF_FLOOD_H extern int ospf_flood(struct ospf *, struct ospf_neighbor *, struct ospf_lsa *, struct ospf_lsa *); extern int ospf_flood_through(struct ospf *, struct ospf_neighbor *, struct ospf_lsa *); extern int ospf_flood_through_area(struct ospf_area *, struct ospf_neighbor *, struct ospf_lsa *); extern int ospf_flood_through_as(struct ospf *, struct ospf_neighbor *, struct ospf_lsa *); extern unsigned long ospf_ls_request_count(struct ospf_neighbor *); extern int ospf_ls_request_isempty(struct ospf_neighbor *); extern struct ospf_lsa *ospf_ls_request_new(struct lsa_header *); extern void ospf_ls_request_free(struct ospf_lsa *); extern void ospf_ls_request_add(struct ospf_neighbor *, struct ospf_lsa *); extern void ospf_ls_request_delete(struct ospf_neighbor *, struct ospf_lsa *); extern void ospf_ls_request_delete_all(struct ospf_neighbor *); extern struct ospf_lsa *ospf_ls_request_lookup(struct ospf_neighbor *, struct ospf_lsa *); extern unsigned long ospf_ls_retransmit_count(struct ospf_neighbor *); extern unsigned long ospf_ls_retransmit_count_self(struct ospf_neighbor *, int); extern int ospf_ls_retransmit_isempty(struct ospf_neighbor *); extern void ospf_ls_retransmit_add(struct ospf_neighbor *, struct ospf_lsa *); extern void ospf_ls_retransmit_delete(struct ospf_neighbor *, struct ospf_lsa *); extern void ospf_ls_retransmit_clear(struct ospf_neighbor *); extern struct ospf_lsa *ospf_ls_retransmit_lookup(struct ospf_neighbor *, struct ospf_lsa *); extern void ospf_ls_retransmit_delete_nbr_area(struct ospf_area *, struct ospf_lsa *); extern void ospf_ls_retransmit_delete_nbr_as(struct ospf *, struct ospf_lsa *); extern void ospf_ls_retransmit_add_nbr_all(struct ospf_interface *, struct ospf_lsa *); extern void ospf_flood_lsa_area(struct ospf_lsa *, struct ospf_area *); extern void ospf_flood_lsa_as(struct ospf_lsa *); extern void ospf_lsa_flush_area(struct ospf_lsa *, struct ospf_area *); extern void ospf_lsa_flush_as(struct ospf *, struct ospf_lsa *); extern void ospf_lsa_flush(struct ospf *, struct ospf_lsa *); extern struct external_info *ospf_external_info_check(struct ospf_lsa *); extern void ospf_lsdb_init(struct ospf_lsdb *); #endif /* _ZEBRA_OSPF_FLOOD_H */
rtrlib/frr
ospfd/ospf_flood.h
C
gpl-2.0
3,187
<?php if (count(get_included_files()) == 1) exit("Direct access not permitted."); class Model_Navigation extends Model { protected $data = array(); protected $statement = null; public function Read($id) { $prefix = Database::instance() -> table_prefix(); $query = "SELECT terms.term_id FROM " . $prefix . "terms AS terms WHERE terms.slug = :id"; $query = DB::select(array("p.ID", "ID"), array("p.post_title", "title"), array("p.post_name", "post_name"), array("p.menu_order","menu_order"), array("n.post_name", "n_name"), array("n.post_title", "n_title"), array("m.meta_value", "m_meta_value"), array("pp.meta_value", "menu_parent"), array("pt.meta_value", "type")) -> from(array("term_relationships", "txr")) -> join(array("posts", "p"), "INNER") -> on("txr.object_id", "=", "p.ID") -> join(array("postmeta", "m"), "LEFT") -> on("p.ID", "=", "m.post_id") -> join(array("postmeta", "pl"), "LEFT") -> on("p.ID", "=", "pl.post_id") -> and_where("pl.meta_key", "=", "_menu_item_object_id") -> join(array("postmeta", "pp"), "LEFT") -> on("p.ID", "=", "pp.post_id") -> and_where("pp.meta_key", "=", "_menu_item_menu_item_parent") -> join(array("postmeta", "pt"), "LEFT") -> on("p.ID", "=", "pt.post_id") -> and_where("pt.meta_key", "=", "_menu_item_object") -> join(array("posts", "n"), "LEFT") -> on("pl.meta_value", "=", "n.ID") -> where("p.post_status", "=", "publish") -> and_where("p.post_type", "=", "nav_menu_item") -> and_where("m.meta_key", "=", "_menu_item_url") -> and_where("txr.term_taxonomy_id", "=", Db::query(Database::SELECT, $query) -> bind(":id", $id)) -> order_by("p.menu_order", "ASC") -> execute(); $this -> data = $this -> _FormatTree($query -> as_array(), 0, $id); return ($this -> data); } public function Write() { } public function Delete() { } private function _FormatTree($tree, $parent, $id) { $node = array(); $nodes = array(); foreach ($tree as $i => $item) { if ($item["menu_parent"] == $parent) { $node["id"] = $item["ID"]; $node["title"] = $item["n_title"]; $state = ""; $state_key = "({Key: '" . $item["n_name"] . "'})"; //print_r($item) ; switch ($item["type"]) { case "page" : $state = "home.page"; switch ($item["n_name"]) { case "home": $state = "home"; $state_key = ""; break; case "shop" : $state = "home.inspiration"; $state_key = ""; break; case "checkout": $state = "home.inspiration.like"; $state_key = ""; break; } break; case "post" : $state = "home.weddings"; break; } $node["state"] = $state . $state_key; $node["nodes"] = $this -> _FormatTree($tree, $item["ID"], $id); array_push($nodes, $node); } } return $nodes; } } ?>
benshez/DreamWeddingCeremomies
JsonApiApplication/server/application/classes/Model/Navigation.php
PHP
gpl-2.0
3,750
find . -name "*.pyc" -exec rm -rf {} \; rm -rf build/ rm -rf dist/ rm src/transliterate.egg-info -rf rm builddocs.zip
akosiaris/transliterate
scripts/clean_up.sh
Shell
gpl-2.0
117
/* DVR Commander for TiVo allows control of a TiVo Premiere device. Copyright (C) 2011 Anthony Lieuallen (arantius@gmail.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 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. */ package com.arantius.tivocommander.rpc.request; import com.arantius.tivocommander.Utils; import com.fasterxml.jackson.databind.JsonNode; public class SuggestionsSearch extends CollectionSearch { private static final JsonNode mImageRulset = Utils .parseJson("[{\"type\": \"imageRuleset\", \"name\": \"movie\", \"rule\": [{\"width\": 100, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"moviePoster\"], \"height\": 150}]}, {\"type\": \"imageRuleset\", \"name\": \"tvPortrait\", \"rule\": [{\"width\": 120, \"ruleType\": \"exactMatchDimension\", \"type\": \"imageRule\", \"imageType\": [\"showcaseBanner\"], \"height\": 90}]}]"); private static final String[] mNote = new String[] { "bodyLineupCorrelatedCollectionForCollectionId" }; private static final JsonNode mResponseTemplate = Utils .parseJson("[{\"type\": \"responseTemplate\", \"fieldName\": [\"collection\"], \"typeName\": \"collectionList\"}, {\"fieldInfo\": [{\"maxArity\": [2], \"fieldName\": [\"category\"], \"type\": \"responseTemplateFieldInfo\"}], \"fieldName\": [\"image\", \"title\", \"collectionId\", \"collectionType\", \"correlatedCollectionForCollectionId\"], \"typeName\": \"collection\", \"type\": \"responseTemplate\"}, {\"type\": \"responseTemplate\", \"fieldName\": [\"displayRank\", \"image\"], \"typeName\": \"category\"}] "); public SuggestionsSearch(String collectionId) { super(collectionId); mDataMap.put("imageRuleset", mImageRulset); mDataMap.put("note", mNote); mDataMap.put("responseTemplate", mResponseTemplate); } }
arantius/TiVo-Commander
src/com/arantius/tivocommander/rpc/request/SuggestionsSearch.java
Java
gpl-2.0
2,417
<!DOCTYPE html> <html> <head> <title>MobiDuctor</title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> </head> <body> <h1>MobiDuctor</h1> <script data-main="scripts/main" src="scripts/require.js" type="application/javascript"></script> </body> </html>
hdvianna/webductor
www/index.html
HTML
gpl-2.0
355
#include "AirspaceClass.hpp" #include <assert.h> const TCHAR * airspace_class_as_text(const AirspaceClass_t item, const bool concise) { switch(item) { case RESTRICT: if (!concise) { return _T("Restricted"); } else { return _T("R"); // was LxR } case PROHIBITED: if (!concise) { return _T("Prohibited"); } else { return _T("P"); // was LxP } case DANGER: if (!concise) { return _T("Danger Area"); } else { return _T("Q"); // was lxD } case CLASSA: if (!concise) { return _T("Class A"); } else { return _T("A"); } case CLASSB: if (!concise) { return _T("Class B"); } else { return _T("B"); } case CLASSC: if (!concise) { return _T("Class C"); } else { return _T("C"); } case CLASSD: if (!concise) { return _T("Class D"); } else { return _T("D"); } case CLASSE: if (!concise) { return _T("Class E"); } else { return _T("E"); } case CLASSF: if (!concise) { return _T("Class F"); } else { return _T("F"); } case CLASSG: if (!concise) { return _T("Class G"); } else { return _T("G"); } case NOGLIDER: if (!concise) { return _T("No Glider"); } else { return _T("GP"); // was NoGld } case CTR: if (!concise) { return _T("CTR"); } else { return _T("CTR"); } case WAVE: if (!concise) { return _T("Wave"); } else { return _T("W"); // was Wav } case TMZ: if (!concise) { return _T("Transponder Mandatory Zone"); } else { return _T("TMZ"); } case AATASK: if (!concise) { return _T("AAT"); } else { return _T("T"); } default: break; }; assert(1); return _T("Unknown"); }
joachimwieland/xcsoar-jwieland
src/Engine/Airspace/AirspaceClass.cpp
C++
gpl-2.0
1,886
\documentclass[titlepage,11pt]{article} \usepackage{pslatex} \usepackage[T1]{fontenc} \usepackage{graphicx} \author{Canadian Curling Association\\ Level 4 Research Project\\ Ron Mills} \date{September 1992} \title{Planning Takeouts and Raises} \newlength\leftcolumnwid % width of picture left column \leftcolumnwid = \textwidth \advance\leftcolumnwid by -\columnsep \advance\leftcolumnwid by -75mm \newlength\picwidth %\picwidth=\textwidth\advance\picwidth by 3cm \picwidth=\textwidth \parindent=0mm \parskip=1em \renewcommand{\baselinestretch}{1.2} \setcounter{topnumber}{5} \setcounter{bottomnumber}{5} \setcounter{totalnumber}{10} \renewcommand{\topfraction}{0.75} \renewcommand{\bottomfraction}{0.75} \renewcommand{\textfraction}{0.25} \renewcommand{\floatpagefraction}{0.75} \floatsep=1.5\parskip \textfloatsep=1.5\parskip \intextsep=1.5\parskip \newcommand{\myfrac}[2]{\ensuremath{ \,{}^{#1}\!/_{#2} }} \newcommand{\img}[2]{\includegraphics[#1]{#2}} \newcommand{\pict}[4]{% \begin{figure}[htp]% \centering% {#4} \def\boxX{#3}\ifx\boxX\empty \caption{\label{#1} #2}% \else \caption[#3]{\label{#1} #2}% \fi \end{figure}% } %\newcommand{\picfile}[4]{\pict{#1}{#2}{#3}{\img{}{#4}}} \newcommand{\picfileB}[5]{\pict{#1}{#2}{#3}{\img{#4}{#5}}} \newcommand{\picb}[5]{% \def\BoXx{#4} \ifx\BoXx\empty \pict{#1}{#2}{#3}{#5} \else \pict{#1}{#2}{#3}{\makebox[0mm]{\makebox[\picwidth]{% \begin{minipage}{\leftcolumnwid}\sloppy #4% \end{minipage}\hspace{\columnsep}\raisebox{-.5\totalheight}{#5}}}}% \fi } \newcommand{\prtfloats}{\clearpage} \begin{document} \DeclareGraphicsExtensions{.pdf} \maketitle \listoffigures \section{Introduction} The purpose of this presentation is to give curlers and coaches a better understanding of the principles involved in the selection and execution of shots when other rocks are involved in take-outs and raises. This knowledge will become more important when more rocks come into play as a result of any rule changes. \section{Dimensions and Geometry} Figure \ref{size}\ reviews the dimensions of the house area used in this project. A curling rock must have a maximum circumference of 36", giving a maximum diameter of $ 36 / \pi = 11.5" $ $(\rm C = \pi D )$. Rocks at curling clubs locally were in the 10.5" to 10.75" range (can navigate smaller ports!). Rocks in this study were $ 10 \myfrac{5}{8}" $ in diameter. \picb{formula}{Formulae}{}{% \begin{math}\begin{array}[t]{lll} \displaystyle \frac{a}{d} &=& \displaystyle\frac{r}{l} \\[1.5em] \displaystyle a &=& \displaystyle\frac{r \cdot d}{l} \end{array}\end{math}% }{% \unitlength=1mm \begin{picture}(20,35)%(0,16) \put(-10,0){\line(1,0){20}} \put(-10,0){\line(1,2){16}} \put( 10,0){\line(-1,2){16}} \put( -6,32){\line(1,0){12}} \put( 0,0){\line(0,1){32}} \put( 0,33){\makebox(0,0)[cb]{a}} \put( 1,29){\makebox(0,0)[lc]{r}} \put( 1, 7){\makebox(0,0)[lc]{l}} \put( 1,-1){\makebox(0,0)[ct]{d}} \end{picture}% } \picfileB{size}{Dimensions}{}{height=100mm}{size.pdf} \subsection*{Assumptions} \begin{itemize} \item The striking band of the rocks are free from pitting and chips. \item The ice surface is free of debri. \item The ice is broken in over all areas and is 13--14 seconds hog to hog for a tee weight draw (23-24 seconds hog to tee). \end{itemize} \subsection*{Formulae} The formula in figure \ref{formula}\ will be used later in this presentation. \prtfloats \section{Proper angles} Many curlers judge angles by instinct with varying degrees of success. Judging angles does not come naturally and is learned by experience. A common mistake is shown in figure \ref{fig-2}. Rock B is to be raised onto rock C and rock A is the thrown rock. "$\times$" is the proper spot to hit since it is a direct line between the centres of rocks B and C. If an attempt is made to hit mark $\times$ with the centre of the thrown rock, then rock B will be too full since the contact point is wrong. \picfileB{fig-2}{A Common Mistake}{}{width=100mm}{fig02.pdf} \subsection*{Line up the centres} The proper way to play the shot is shown in figure \ref{fig-3}. Visualize the thrown rock A touching rock B at spot "$\times$" so that the three centres are lined up, then visualize an \emph{area of overlap} between the thrown rock and rock B. The skip and vice skip can then call the line properly. Figure \ref{fig-4}\ shows five common areas of overlap that curlers should become familiar with. \picfileB{fig-3}{Rock A coming from above hitting B, B moves on to position C. Touching spot A/B is on line with centre of A, B, C.}{Area of Overlap}{height=100mm}{fig03.pdf} \pict{fig-4}{Common Areas of Overlap}{}{% \begin{minipage}{.8\textwidth} \hspace*{\fill}\img{height=80mm}{fig04a.pdf} \hspace*{\fill}\img{height=80mm}{fig04b.pdf} \hspace*{\fill}\img{height=80mm}{fig04c.pdf} \hspace*{\fill}\\[1.5em] \hspace*{\fill}\img{height=80mm}{fig04d.pdf} \hspace*{\fill}\img{height=80mm}{fig04e.pdf} \hspace*{\fill} \end{minipage}} \subsection*{The "T" principle} When playing a horizontal double as in figure \ref{fig-5}, the $\times$ point to hit rock B is determined by visualizing the letter "T" as shown, then visualize the thrown rock in position A to then determine the area of overlap to make the shot. \picfileB{fig-5}{The T-priciple}{}{width=120mm}{fig05.pdf} This "T" principle is very important and can be used in many crucial situations. An example is shown in figure \ref{fig-6}. Figure \ref{fig-7}\ is Scotland's famous triple against the Canadian men's team at the 1992 World Championship (Hammy McMillan vs Vic Peters). The spot to hit rock A can be determined by using the "T" rule starting with rock C. This will prove why the shot was possible. \picb{fig-6}{T-priciple in action}{}{% \begin{itemize} \item Last rock on last end \item A, B are opposition rocks \item You need a 3 ender \item C, D are your rocks \item Where will A go on a full or \myfrac{3}{4} hit? \end{itemize}}{\img{width=60mm}{fig06.pdf}} \picfileB{fig-7}{\emph{The} Triple Scotland vs Canada, 1992 world mens semi final.}{\emph{The} Triple}{width=60mm}{fig07.pdf} \clearpage \subsection*{Turn selection} Figures \ref{fig-8}\ and \ref{fig-9}\ demonstrate the options of playing an in turn or an out turn double on rocks B and C assuming the ice curls quite a bit. \textbf{Regardless of which turn to play you must hit rock B at exactly the same spot.} The out turn in figure \ref{fig-8}\ gives you a larger area of overlap and thus is the better percentage shot. Similarly, the in turn in figure \ref{fig-9}\ is the better shot. \picb{fig-8}{Turn decisions}{}{% \begin{itemize} \item Out turn the best here \item Ice curls a lot \end{itemize} }{\img{width=80mm}{fig08.pdf}} \picb{fig-9}{Turn decisions}{}{% \begin{itemize} \item In turn the best here \item Ice curls a lot \end{itemize} }{\img{width=80mm}{fig09.pdf}} This \emph{area of overlap} is the most important factor in determining which turn to play. Many curlers believe the out turn in figure \ref{fig-8}\ causes the shooter to \emph{"jump"} across at a bigger angle than an in turn. I believe this effect to be very minimal with a normal rotation. The major consideration should be the larger area of overlap in the different turns. On straight ice either turn can be used. Another interesting fact is shown in figure \ref{fig-10}. Rocks A and B are both on the same angle from rock C, but rock B has a smaller \emph{area of overlap} than A to make the double. You can not make a fixed rule that a $ 30^\circ $ double for example is always a half hit on the first rock. \picb{fig-10}{Doubles}{}{Area of overlap decreases as rocks on the same angle get closer together.}{\img{width=80mm}{fig10.pdf}} \prtfloats \section{Accuracy required for raises} Figure \ref{fig-11}\ shows two rocks a distance "L" apart. Assume rock B will be raised onto rock C with at least half hit on rock C. This will ensure C is removed from play. \picb{fig-11}{Accuracy}{}{% \begin{math}\begin{array}[t]{lll} \displaystyle a &=& \displaystyle\frac{ r \cdot d }{ l } \\[1em] &\approx& \displaystyle\frac{ 5.5'' \cdot 11'' }{ l } \\[1em] &=& \displaystyle\frac{ 60.5 }{ l } \\ \end{array}\end{math} }{\img{height=80mm}{fig11.pdf}} \iffalse From the formula in the introduction $(a/d = r/L)$ $ a = r \times \frac{ d }{ L } $ where $ r $ = radius = 5.5" and $ d $ = diameter = 11". Thus $ a = \frac{60.5"}{L} $ when $ L $ = distance apart. In figure \ref{fig-12}\ the rocks are 20 feet apart, thus $ a = \frac{60.5}{240} = 0.25"$ In figure \ref{fig-13}\ the rocks are 10 feet apart, thus $ a = \frac{60.5}{120} = 0.5"$ In figure \ref{fig-14}\ the rocks are 5 feet apart, thus $ a = \frac{60.5}{ 60} = 1.0"$ Figure \ref{fig-15}\ is an %actual relative size drawing of the accuracy required at the three distances. \fi \picb{fig-12}{Accuracy --- 20 foot raise}{}{% \begin{math}\begin{array}[t]{lll} a &=& \mbox{area to hit} \\[1.5em] % &=& \mbox{radius} \cdot \mbox{diameter} / \mbox{length} \\[1.5em] &\approx& \mbox{radius} \cdot \frac{\mbox{diameter}}{\mbox{length}} \\[1.5em] &=& 5.5 \cdot 11 / 240 \\[1.5em] &=& 0.25" \end{array}\end{math} }{\img{width=80mm}{fig12.pdf}} \picb{fig-13}{Accuracy --- 10 foot raise}{}{% \begin{math}\begin{array}[t]{lll} a &=& \mbox{area to hit} \\[1.5em] % &=& \mbox{radius} \cdot \mbox{diameter} / \mbox{length} \\[1.5em] &\approx& \mbox{radius} \cdot \frac{\mbox{diameter}}{\mbox{length}} \\[1.5em] &=& 5.5 \cdot 11 / 120 \\[1.5em] &=& 0.50" \end{array}\end{math} }{\img{width=80mm}{fig13.pdf}} \picb{fig-14}{Accuracy --- 5 foot raise}{}{% \begin{math}\begin{array}[t]{lll} a &=& \mbox{area to hit} \\[1.5em] % &=& \mbox{radius} \cdot \mbox{diameter} / \mbox{length} \\[1.5em] &\approx& \mbox{radius} \cdot \frac{\mbox{diameter}}{\mbox{length}} \\[1.5em] &=& 5.5 \cdot 11 / 60 \\[1.5em] &=& 1" \end{array}\end{math} }{\img{width=80mm}{fig14.pdf}} \picfileB{fig-15}{Accuracy --- in relation to diameter}{}{height=60mm}{fig15.pdf} \subsection*{Propabilities} The odds of making the raises above depend on \begin{enumerate} \item The distance apart \item The skill level of your team \begin{itemize} \item reading ice \item sweeping \item throwing \item calling line \end{itemize} \item Ice conditions \end{enumerate} For example, on the 20" raise you have to be accurate to within \myfrac{1}{4}". If your team is only accurate to with 11" (ie.\ a half hit on either side), then the odds of making this shot are about 1 in 44 since there are 44 -- \myfrac{1}{4} inches in 11 inches. A highly skilled team may be accurate within 2" and thus have a 1 in 8 chance of making a 20" raise. \prtfloats \section{Loss of momentum} When a thrown rock strikes another rock there is a slight loss of momentum when struck full on. This is of no consequences in take outs, but is important in tap back raises. After many test trails, the pattern in figure \ref{fig-16}\ emerged. The general rule is that a diameter of one rock is lost for each rock raised. Remember our assumptions on broken in ice with no debri under any of the rocks (watch out for straw). \picb{fig-16}{Loss of momentum}{}{% \begin{itemize} \item same weight on three draws \item A, B, C are the outcome \item A, no raise \item B, raise one rock \item C, raise two rocks \end{itemize} }{\img{width=80mm}{fig16.pdf}} Figure \ref{fig-17}\ shows the other way momentum is lost. When raising rocks at an angle you need more weight. The smaller the area of overlap, the more weight you need. Path C shows the weight required to raise rock A onto the button. Distance C is about the sum of distances A and B. \picfileB{fig-17}{Angle draw raises. Distance $ C \approx A + B $.}{Angle draw raises}{width=80mm}{fig17.pdf} This principle can be useful on "free" draws that are heavy but are going to hit one of your rocks in the house. An alert sweeping call would be to get a \myfrac{1}{2} hit to save both rocks. \prtfloats \section{The \emph{"Drag"} Effect} An interesting phenomenon occurs when playing raise take outs on rocks that are touching (frozen together). Figure \ref{fig-18}\ shows this effect. Rocks B and C are touching. Rock A is the thrown rock and is a half hit on B. C should go along the normal path but in this case C is \emph{"dragged"} by B slightly towards B's path. \textbf{This drag effect disappears only after B and C are more than \myfrac{1}{2}" apart}. \picfileB{fig-18}{The \emph{"Drag"} Effect}{}{height=60mm}{fig18.pdf} You can use this principle to your advantage but ist should be used only if you have practiced it and no other shots are available. Figures \ref{fig-19}\ and \ref{fig-20}\ show two examples. \picb{fig-19}{Drag Effect}{}{% \begin{itemize} \item B and C are lined up to just miss D \item A half hit on the right side of B will cause C to hit D \item The drag effect disappears after B and C are one half inch apart \end{itemize} }{\img{width=80mm}{fig19.pdf}} \picb{fig-20}{Drag Effect}{}{% \begin{itemize} \item A \myfrac{3}{4} hit on the right side of B will cause C to hit D \item Paths 1, 2 or 3 or any in-between are possible depending on where it is hit \end{itemize} }{\img{width=80mm}{fig20.pdf}} Figure \ref{fig-21}\ shows a set up which many curlers believe is an \emph{"automatic"} in that you can hit B anywhere. You must hit B in spot $\times$ to avoid the \emph{"drag"} effect. \picfileB{fig-21}{Avoid the Drag Effect. Hit B at the position $\times$, the same as if C wasn't there.}{Avoid the Drag Effect}{width=80mm}{fig21.pdf} \prtfloats \section{Ports} Figure \ref{fig-22}\ to \ref{fig-24}\ show the path the thrown rock takes when comingg through ports and wicking on one or both of the rocks. In figure \ref{fig-22}\ there is a small port between rocks B and C (1 or 2 inches to spare to each side). In figure \ref{fig-23}\ the port is slightly narrower than one rock. Figure \ref{fig-24}\ demonstrates the follow-through effect if simultaneously striking B and C when the port is narrowe than one rock. With $10\myfrac{3}{4}$" diameter rocks a port size down to 8" can be navigated. This is exactly the width of the plastic handle covers used in many clubs. \picb{fig-22}{Splitting rocks}{}{% \begin{itemize} \item B and C are 13 to 15 inches apart. Fine hit C first, glancing off B \item A very fine hit on C causes A to take path 1 \item Slightly fuller hits on C progress A's position to 5 \end{itemize} }{\img{width=80mm}{fig22.pdf}} \picb{fig-23}{Splitting rocks}{}{% \begin{itemize} \item B and C are about 10 inches apart \item Fine hitting C first results in path 1 \item Fine hitting B first results in path 2 \end{itemize} }{\img{width=80mm}{fig23.pdf}} \picb{fig-24}{Splitting through a port}{}{% \begin{itemize} \item Port sizes of less than 8 inches cannot be navigated. (Width of plastic handle). \item B, C must be hit simultaneously. \end{itemize} }{\img{width=80mm}{fig24.pdf}} Figure \ref{fig-25}\ shows two different double situations. D, E is a \emph{"natural"} double, in that a half hit on D is required. B, C is a very difficult double unless played properly. A half hit on the centre line side of B makes it as easy as a \emph{"natural"} double. \picb{fig-25}{Natural doubles}{}{% \begin{itemize} \item Defined as two rocks situated so that a half hit on the first one hits the second one directly. \item D and E are a natural double. \item Characteristics: You cannot roll across the face of E. \item B, C are an extremely tough double if you attempt to split them. A half hit on the centre line side of B makes it as easy as a natural double. \end{itemize} }{\img{width=80mm}{fig25.pdf}} \prtfloats \section{Practice routines} All of the principles shown here should be set up in practices. Rocks can be delivered (pushed) from the nearest hog line to save time. A very good off season routine would be to have the team practice various shots on a pool table. Specially: \begin{itemize} \item learning about proper area of overlap (full, three quarter, half, one quarter hits) \item learning to visualize the "T" rule for doubles \item learning about the drag effect \end{itemize} A more realistic environment can be set up on a pool table by making a scale drawing of the house area out to hog line on a sheet of paper. The scale is 5.5 to 1 since a billiard ball is 2 inches in diameter vs 11 inches for a rock. \end{document}
mro/jcurl
science/mills/mills.tex
TeX
gpl-2.0
16,496
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the examples of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:BSD$ ** You may use this file under the terms of the BSD license as follows: ** ** "Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions are ** met: ** * Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** * Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in ** the documentation and/or other materials provided with the ** distribution. ** * Neither the name of Nokia Corporation and its Subsidiary(-ies) nor ** the names of its contributors may be used to endorse or promote ** products derived from this software without specific prior written ** permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE." ** $QT_END_LICENSE$ ** ****************************************************************************/ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> #include "MVDataManager/mvdatamanager.h" #include "../matrixTools/parser.h" #include "Dialogs/importdilaog.h" QT_BEGIN_NAMESPACE class QAction; class QListWidget; class QMenu; class QTextEdit; class PlotWidget; class EventViewer; class MaskManager; QT_END_NAMESPACE //! [0] class MainWindow : public QMainWindow { Q_OBJECT public: MainWindow(); void showWelcome(); public slots: void centerMainWindowGeometry(); private slots: void tryClose(); void save(); void about(); void openFile(); void import(); void raiseEVDock(); void raiseDMDock(); void raisePlotDock(); void raiseMMDock(); void updateOutput(); private: void createActions(); void createMenus(); void createToolBars(); void createStatusBar(); void createDockWindows(); QDesktopWidget *desktop; QProcess *process; QTextEdit *outputLog; MVdataManager *dataManager; QDockWidget * DMdock; QDockWidget * PlotDock; QDockWidget * eventViewerDock; //QDockWidget * maskEditorDock; MaskManager * maskManager; QDockWidget * MMDock; PlotWidget * plotWidget; EventViewer * eventViewer; // checkableMatrix * maskMatrix; QList<QTabBar*> tabBars; QMenu *fileMenu; //QMenu *editMenu; QMenu *analyzerMenu; QMenu *DMmenu; QMenu * MMmenu; QMenu *viewMenu; QMenu *helpMenu; QToolBar *fileToolBar; QToolBar *DMtoolBar; QToolBar *MMtoolBar; QToolBar *viewToolBar; QToolBar *editToolBar; //actions from DataManager QAction *newDataSetAct; QAction *rmDataSetAct; QAction *rmAllDataSetAct; QAction *plotDataSetAct; QAction *saveDataSetAct; QAction *inspectEventAct; QAction *renameDataSetAct; //actions from MaskManager QAction * newMaskSetAct; QAction * renameMaskSetAct; QAction * editMaskAct; QAction * printMaskAct; QAction * rmMaskSetAct; //action toggle view QAction *DMviewAct; QAction *MMviewAct; QAction *plotViewAct; QAction *EVviewAct; QAction *saveAct; QAction *undoAct; QAction *aboutAct; QAction *aboutQtAct; QAction *quitAct; QAction *openFileAct; QAction *importAct; }; //! [0] #endif
f-giorgi/MTG
MTG/mainwindow.h
C
gpl-2.0
4,342
/* Author: Richard McKenna Stony Brook University Computer Science Department WindowsTimer.cpp See WindowsTimer.h for a class description. */ #include "sssf_VS\stdafx.h" #include "sssf\game\Game.h" #include "sssf\platforms\Windows\WindowsTimer.h" #include "sssf\text\TextFileWriter.h" #include "sssf\timer\GameTimer.h" /* WindowsTimer - Default constructor, this method initializes the timer resolution to the best the system has to offer. In order to start timing, call the resetTimer method outside the main game loop, right before it starts. The timeGameLoop method is the only one needed inside the game loop. */ WindowsTimer::WindowsTimer() { // LET'S START WITH A TARGET FPS OF 33 FRAMES PER SECOND, // THAT'S 30 ms PER FRAME targetFPS = 33; // GET INFORMATION ABOUT HOW GOOD // THE SYSTEM'S TIMER IS timerResolution = getMinSystemTimerResolution(); // AND THEN USE THAT RESOLUTION FOR ALL SUBSEQUENT TIMING timeBeginPeriod(timerResolution); // CALCULATE THE NUMBER OF MILLISECONDS WE // WANT PER FRAME ACCORDING TO THE TARGET_FPS targetMillisPerFrame = (DWORD)(1000/targetFPS); } /* ~WindowsTimer - Destructor, we only have to clean up the writer, since we declared it as a pointer instance variable. */ WindowsTimer::~WindowsTimer() {} /* calculateAverageActualFramerate - This method calculates how long on average a frame takes in the game loop, including time spent sleeping. */ unsigned int WindowsTimer::calculateAverageActualFramerate() { if (loopCounter == 0) return DWORD(0); else { int averageTime = totalTime/loopCounter; if (averageTime != 0) return DWORD(1000/averageTime); else // IT IS AT LEAST 1000, BUT WE REALLY // DON'T KNOW DUE TO TIMER RESOLUTION return DWORD(1000); } } /* calculateAverageSleeplessFramerate - This method calculates how long on average a frame takes in the game loop, not including time spent sleeping. */ unsigned int WindowsTimer::calculateAverageSleeplessFramerate() { if (loopCounter == 0) return DWORD(0); else { float averageTime = (float)sleeplessTotalTime/(float)loopCounter; if ((int)averageTime != 0) return DWORD(1000/averageTime); else // IT IS AT LEAST 1000, BUT WE REALLY // DON'T KNOW DUE TO TIMER RESOLUTION return DWORD(1000); } } /* calculateAverageSleepTime - This method calculates on average how much time is spent sleeping each frame since the game loop started. */ unsigned int WindowsTimer::calculateAverageSleepTime() { if (loopCounter == 0) return DWORD(0); else return totalSleepTime/loopCounter; } /* getMinSystemTimeResolution - This method queries the local operating system and asks how good the system resolution is for timing purposes. The best we can expect to be returned would be 1 millisecond. */ unsigned int WindowsTimer::getMinSystemTimerResolution() { TIMECAPS timer; timeGetDevCaps(&timer, sizeof(TIMECAPS)); UINT min = timer.wPeriodMin; return min; } /* resetTimer - This method resents all variables used for compiling statistics as well as getting the first start times for the first iteration through the game loop. This should be placed outside the game loop, right before it is to start. */ void WindowsTimer::resetTimer() { gameLoopStartTime = timeGetTime(); sleeplessGameLoopStartTime = timeGetTime(); loopCounter = 0; totalTime = 0; sleeplessTotalTime = 0; totalSleepTime = 0; actualLoopRate = 0; sleeplessLoopRate = 0; } /* timeGameLoop - This method gets the current time and then calculates the difference between now and the last time it got the time. This is the game time, which can then be used to calculate the current frame rate. If the current frame rate is too fast, we sleep for a little to clamp it to the TARGET_FPS. If it is too slow, we calculate a scaling factor that can be used for moving sprites and for scrolling. */ void WindowsTimer::timeGameLoop() { // GET THE END OF FRAME TIME gameLoopEndTime = timeGetTime(); // HOW MUCH TIME PASSED DURING THE LAST FRAME? loopTime = gameLoopEndTime - gameLoopStartTime; // GET THE START TIME FOR NEXT FRAME, IF THERE IS ONE gameLoopStartTime = timeGetTime(); // ADD THE LAST FRAME'S TIME TO THE TOTAL totalTime += loopTime; // HOW MUCH TIME PASSED NOT INCLUDING // OUR FORCED SLEEPING? sleeplessLoopTime = gameLoopEndTime - sleeplessGameLoopStartTime; // ADD THE LAST FRAME'S SLEEPLESS TIME TO THE TOTAL sleeplessTotalTime += sleeplessLoopTime; if (loopTime == DWORD(0)) actualLoopRate = DWORD(1000); else actualLoopRate = 1000 / loopTime; if (sleeplessLoopTime == DWORD(0)) actualLoopRate = DWORD(1000); else sleeplessLoopRate = 1000 / sleeplessLoopTime; // IF THIS PAST FRAME RAN TOO FAST IT'S // LIKELY THE NEXT FRAME WILL RUN FAST ALSO if (targetMillisPerFrame > sleeplessLoopTime) { // SO LET'S CLAMP IT TO OUR TARGET FRAME RATE sleepTime = targetMillisPerFrame - sleeplessLoopTime; totalSleepTime += sleepTime; Sleep(sleepTime); timeScaleFactor = 1; } else { sleepTime = 0; // WE MIGHT USE THIS timeScaleFactor TO SCALE // MOVEMENTS OF GAME SPRITES AND SCROLLING TO // MAKE UP FOR THE SLOWING DOWN OF THE GAME LOOP timeScaleFactor = ((float)targetFPS)/ ((float)sleeplessLoopRate); } // GET THE START TIME FOR THE LOOP // NOT INCLUDING THE SLEEP TIME FROM THE LAST LOOP sleeplessGameLoopStartTime = timeGetTime(); loopCounter++; }
cristianomj/LastBonfire
SimpleSideScrollerFramework/src/sssf/platforms/Windows/WindowsTimer.cpp
C++
gpl-2.0
5,413
#ifndef _ASM_X86_PROCESSOR_H #define _ASM_X86_PROCESSOR_H #include <asm/processor-flags.h> /* Forward declaration, a strange C thing */ struct task_struct; struct mm_struct; #include <asm/vm86.h> #include <asm/math_emu.h> #include <asm/segment.h> #include <asm/types.h> #include <asm/sigcontext.h> #include <asm/current.h> #include <asm/cpufeature.h> #include <asm/system.h> #include <asm/page.h> #include <asm/pgtable_types.h> #include <asm/percpu.h> #include <asm/msr.h> #include <asm/desc_defs.h> #include <asm/nops.h> #include <linux/personality.h> #include <linux/cpumask.h> #include <linux/cache.h> #include <linux/threads.h> #include <linux/math64.h> #include <linux/init.h> #include <linux/err.h> #define HBP_NUM 4 /* * Default implementation of macro that returns current * instruction pointer ("program counter"). */ static inline void *current_text_addr(void) { void *pc; asm volatile("mov $1f, %0; 1:":"=r" (pc)); return pc; } #ifdef CONFIG_X86_VSMP # define ARCH_MIN_TASKALIGN (1 << INTERNODE_CACHE_SHIFT) # define ARCH_MIN_MMSTRUCT_ALIGN (1 << INTERNODE_CACHE_SHIFT) #else # define ARCH_MIN_TASKALIGN 16 # define ARCH_MIN_MMSTRUCT_ALIGN 0 #endif /* * CPU type and hardware bug flags. Kept separately for each CPU. * Members of this structure are referenced in head.S, so think twice * before touching them. [mj] */ struct cpuinfo_x86 { __u8 x86; /* CPU family */ __u8 x86_vendor; /* CPU vendor */ __u8 x86_model; __u8 x86_mask; #ifdef CONFIG_X86_32 char wp_works_ok; /* It doesn't on 386's */ /* Problems on some 486Dx4's and old 386's: */ char hlt_works_ok; char hard_math; char rfu; char fdiv_bug; char f00f_bug; char coma_bug; char pad0; #else /* Number of 4K pages in DTLB/ITLB combined(in pages): */ int x86_tlbsize; #endif __u8 x86_virt_bits; __u8 x86_phys_bits; /* CPUID returned core id bits: */ __u8 x86_coreid_bits; /* Max extended CPUID function supported: */ __u32 extended_cpuid_level; /* Maximum supported CPUID level, -1=no CPUID: */ int cpuid_level; __u32 x86_capability[NCAPINTS]; char x86_vendor_id[16]; char x86_model_id[64]; /* in KB - valid for CPUS which support this call: */ int x86_cache_size; int x86_cache_alignment; /* In bytes */ int x86_power; unsigned long loops_per_jiffy; /* cpuid returned max cores value: */ u16 x86_max_cores; u16 apicid; u16 initial_apicid; u16 x86_clflush_size; #ifdef CONFIG_SMP /* number of cores as seen by the OS: */ u16 booted_cores; /* Physical processor id: */ u16 phys_proc_id; /* Core id: */ u16 cpu_core_id; /* Compute unit id */ u8 compute_unit_id; /* Index into per_cpu list: */ u16 cpu_index; #endif u32 microcode; } __attribute__((__aligned__(SMP_CACHE_BYTES))); /* 빈숫자 4, 6은 뭘까요?*/ #define X86_VENDOR_INTEL 0 #define X86_VENDOR_CYRIX 1 #define X86_VENDOR_AMD 2 #define X86_VENDOR_UMC 3 #define X86_VENDOR_CENTAUR 5 #define X86_VENDOR_TRANSMETA 7 #define X86_VENDOR_NSC 8 #define X86_VENDOR_NUM 9 #define X86_VENDOR_UNKNOWN 0xff /* * capabilities of CPUs */ extern struct cpuinfo_x86 boot_cpu_data; extern struct cpuinfo_x86 new_cpu_data; extern struct tss_struct doublefault_tss; extern __u32 cpu_caps_cleared[NCAPINTS]; extern __u32 cpu_caps_set[NCAPINTS]; #ifdef CONFIG_SMP DECLARE_PER_CPU_SHARED_ALIGNED(struct cpuinfo_x86, cpu_info); #define cpu_data(cpu) per_cpu(cpu_info, cpu) #else #define cpu_info boot_cpu_data #define cpu_data(cpu) boot_cpu_data #endif extern const struct seq_operations cpuinfo_op; static inline int hlt_works(int cpu) { #ifdef CONFIG_X86_32 return cpu_data(cpu).hlt_works_ok; #else return 1; #endif } #define cache_line_size() (boot_cpu_data.x86_cache_alignment) extern void cpu_detect(struct cpuinfo_x86 *c); extern struct pt_regs *idle_regs(struct pt_regs *); extern void early_cpu_init(void); extern void identify_boot_cpu(void); extern void identify_secondary_cpu(struct cpuinfo_x86 *); extern void print_cpu_info(struct cpuinfo_x86 *); extern void init_scattered_cpuid_features(struct cpuinfo_x86 *c); extern unsigned int init_intel_cacheinfo(struct cpuinfo_x86 *c); extern unsigned short num_cache_leaves; extern void detect_extended_topology(struct cpuinfo_x86 *c); extern void detect_ht(struct cpuinfo_x86 *c); /* 그냥 cpuid 명령을 이용해 넣어줌 */ static inline void native_cpuid(unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx) { /* ecx is often an input as well as an output. */ asm volatile("cpuid" : "=a" (*eax), "=b" (*ebx), "=c" (*ecx), "=d" (*edx) : "0" (*eax), "2" (*ecx) : "memory"); } static inline void load_cr3(pgd_t *pgdir) { write_cr3(__pa(pgdir)); } #ifdef CONFIG_X86_32 /* This is the TSS defined by the hardware. */ struct x86_hw_tss { unsigned short back_link, __blh; unsigned long sp0; unsigned short ss0, __ss0h; unsigned long sp1; /* ss1 caches MSR_IA32_SYSENTER_CS: */ unsigned short ss1, __ss1h; unsigned long sp2; unsigned short ss2, __ss2h; unsigned long __cr3; unsigned long ip; unsigned long flags; unsigned long ax; unsigned long cx; unsigned long dx; unsigned long bx; unsigned long sp; unsigned long bp; unsigned long si; unsigned long di; unsigned short es, __esh; unsigned short cs, __csh; unsigned short ss, __ssh; unsigned short ds, __dsh; unsigned short fs, __fsh; unsigned short gs, __gsh; unsigned short ldt, __ldth; unsigned short trace; unsigned short io_bitmap_base; } __attribute__((packed)); #else struct x86_hw_tss { u32 reserved1; u64 sp0; u64 sp1; u64 sp2; u64 reserved2; u64 ist[7]; u32 reserved3; u32 reserved4; u16 reserved5; u16 io_bitmap_base; } __attribute__((packed)) ____cacheline_aligned; #endif /* * IO-bitmap sizes: */ #define IO_BITMAP_BITS 65536 #define IO_BITMAP_BYTES (IO_BITMAP_BITS/8) #define IO_BITMAP_LONGS (IO_BITMAP_BYTES/sizeof(long)) #define IO_BITMAP_OFFSET offsetof(struct tss_struct, io_bitmap) #define INVALID_IO_BITMAP_OFFSET 0x8000 struct tss_struct { /* * The hardware state: */ struct x86_hw_tss x86_tss; /* * The extra 1 is there because the CPU will access an * additional byte beyond the end of the IO permission * bitmap. The extra byte must be all 1 bits, and must * be within the limit. */ unsigned long io_bitmap[IO_BITMAP_LONGS + 1]; /* * .. and then another 0x100 bytes for the emergency kernel stack: */ unsigned long stack[64]; } ____cacheline_aligned; DECLARE_PER_CPU_SHARED_ALIGNED(struct tss_struct, init_tss); /* * Save the original ist values for checking stack pointers during debugging */ struct orig_ist { unsigned long ist[7]; }; #define MXCSR_DEFAULT 0x1f80 struct i387_fsave_struct { u32 cwd; /* FPU Control Word */ u32 swd; /* FPU Status Word */ u32 twd; /* FPU Tag Word */ u32 fip; /* FPU IP Offset */ u32 fcs; /* FPU IP Selector */ u32 foo; /* FPU Operand Pointer Offset */ u32 fos; /* FPU Operand Pointer Selector */ /* 8*10 bytes for each FP-reg = 80 bytes: */ u32 st_space[20]; /* Software status information [not touched by FSAVE ]: */ u32 status; }; struct i387_fxsave_struct { u16 cwd; /* Control Word */ u16 swd; /* Status Word */ u16 twd; /* Tag Word */ u16 fop; /* Last Instruction Opcode */ union { struct { u64 rip; /* Instruction Pointer */ u64 rdp; /* Data Pointer */ }; struct { u32 fip; /* FPU IP Offset */ u32 fcs; /* FPU IP Selector */ u32 foo; /* FPU Operand Offset */ u32 fos; /* FPU Operand Selector */ }; }; u32 mxcsr; /* MXCSR Register State */ u32 mxcsr_mask; /* MXCSR Mask */ /* 8*16 bytes for each FP-reg = 128 bytes: */ u32 st_space[32]; /* 16*16 bytes for each XMM-reg = 256 bytes: */ u32 xmm_space[64]; u32 padding[12]; union { u32 padding1[12]; u32 sw_reserved[12]; }; } __attribute__((aligned(16))); struct i387_soft_struct { u32 cwd; u32 swd; u32 twd; u32 fip; u32 fcs; u32 foo; u32 fos; /* 8*10 bytes for each FP-reg = 80 bytes: */ u32 st_space[20]; u8 ftop; u8 changed; u8 lookahead; u8 no_update; u8 rm; u8 alimit; struct math_emu_info *info; u32 entry_eip; }; struct ymmh_struct { /* 16 * 16 bytes for each YMMH-reg = 256 bytes */ u32 ymmh_space[64]; }; struct xsave_hdr_struct { u64 xstate_bv; u64 reserved1[2]; u64 reserved2[5]; } __attribute__((packed)); struct xsave_struct { struct i387_fxsave_struct i387; struct xsave_hdr_struct xsave_hdr; struct ymmh_struct ymmh; /* new processor state extensions will go here */ } __attribute__ ((packed, aligned (64))); union thread_xstate { struct i387_fsave_struct fsave; struct i387_fxsave_struct fxsave; struct i387_soft_struct soft; struct xsave_struct xsave; }; struct fpu { union thread_xstate *state; }; #ifdef CONFIG_X86_64 DECLARE_PER_CPU(struct orig_ist, orig_ist); union irq_stack_union { char irq_stack[IRQ_STACK_SIZE]; /* * GCC hardcodes the stack canary as %gs:40. Since the * irq_stack is the object at %gs:0, we reserve the bottom * 48 bytes of the irq stack for the canary. */ struct { char gs_base[40]; unsigned long stack_canary; }; }; DECLARE_PER_CPU_FIRST(union irq_stack_union, irq_stack_union); DECLARE_INIT_PER_CPU(irq_stack_union); DECLARE_PER_CPU(char *, irq_stack_ptr); DECLARE_PER_CPU(unsigned int, irq_count); extern unsigned long kernel_eflags; extern asmlinkage void ignore_sysret(void); #else /* X86_64 */ #ifdef CONFIG_CC_STACKPROTECTOR /* * Make sure stack canary segment base is cached-aligned: * "For Intel Atom processors, avoid non zero segment base address * that is not aligned to cache line boundary at all cost." * (Optim Ref Manual Assembly/Compiler Coding Rule 15.) */ struct stack_canary { char __pad[20]; /* canary at %gs:20 */ unsigned long canary; }; DECLARE_PER_CPU_ALIGNED(struct stack_canary, stack_canary); #endif #endif /* X86_64 */ extern unsigned int xstate_size; extern void free_thread_xstate(struct task_struct *); extern struct kmem_cache *task_xstate_cachep; struct perf_event; struct thread_struct { /* Cached TLS descriptors: */ struct desc_struct tls_array[GDT_ENTRY_TLS_ENTRIES]; unsigned long sp0; unsigned long sp; #ifdef CONFIG_X86_32 unsigned long sysenter_cs; #else unsigned long usersp; /* Copy from PDA */ unsigned short es; unsigned short ds; unsigned short fsindex; unsigned short gsindex; #endif #ifdef CONFIG_X86_32 unsigned long ip; #endif #ifdef CONFIG_X86_64 unsigned long fs; #endif unsigned long gs; /* Save middle states of ptrace breakpoints */ struct perf_event *ptrace_bps[HBP_NUM]; /* Debug status used for traps, single steps, etc... */ unsigned long debugreg6; /* Keep track of the exact dr7 value set by the user */ unsigned long ptrace_dr7; /* Fault info: */ unsigned long cr2; unsigned long trap_no; unsigned long error_code; /* floating point and extended processor state */ struct fpu fpu; #ifdef CONFIG_X86_32 /* Virtual 86 mode info */ struct vm86_struct __user *vm86_info; unsigned long screen_bitmap; unsigned long v86flags; unsigned long v86mask; unsigned long saved_sp0; unsigned int saved_fs; unsigned int saved_gs; #endif /* IO permissions: */ unsigned long *io_bitmap_ptr; unsigned long iopl; /* Max allowed port in the bitmap, in bytes: */ unsigned io_bitmap_max; }; static inline unsigned long native_get_debugreg(int regno) { unsigned long val = 0; /* Damn you, gcc! */ switch (regno) { case 0: asm("mov %%db0, %0" :"=r" (val)); break; case 1: asm("mov %%db1, %0" :"=r" (val)); break; case 2: asm("mov %%db2, %0" :"=r" (val)); break; case 3: asm("mov %%db3, %0" :"=r" (val)); break; case 6: asm("mov %%db6, %0" :"=r" (val)); break; case 7: asm("mov %%db7, %0" :"=r" (val)); break; default: BUG(); } return val; } static inline void native_set_debugreg(int regno, unsigned long value) { switch (regno) { case 0: asm("mov %0, %%db0" ::"r" (value)); break; case 1: asm("mov %0, %%db1" ::"r" (value)); break; case 2: asm("mov %0, %%db2" ::"r" (value)); break; case 3: asm("mov %0, %%db3" ::"r" (value)); break; case 6: asm("mov %0, %%db6" ::"r" (value)); break; case 7: asm("mov %0, %%db7" ::"r" (value)); break; default: BUG(); } } /* * Set IOPL bits in EFLAGS from given mask */ static inline void native_set_iopl_mask(unsigned mask) { #ifdef CONFIG_X86_32 unsigned int reg; asm volatile ("pushfl;" "popl %0;" "andl %1, %0;" "orl %2, %0;" "pushl %0;" "popfl" : "=&r" (reg) : "i" (~X86_EFLAGS_IOPL), "r" (mask)); #endif } static inline void native_load_sp0(struct tss_struct *tss, struct thread_struct *thread) { tss->x86_tss.sp0 = thread->sp0; #ifdef CONFIG_X86_32 /* Only happens when SEP is enabled, no need to test "SEP"arately: */ if (unlikely(tss->x86_tss.ss1 != thread->sysenter_cs)) { tss->x86_tss.ss1 = thread->sysenter_cs; wrmsr(MSR_IA32_SYSENTER_CS, thread->sysenter_cs, 0); } #endif } static inline void native_swapgs(void) { #ifdef CONFIG_X86_64 asm volatile("swapgs" ::: "memory"); #endif } #ifdef CONFIG_PARAVIRT #include <asm/paravirt.h> #else #define __cpuid native_cpuid #define paravirt_enabled() 0 /* * These special macros can be used to get or set a debugging register */ #define get_debugreg(var, register) \ (var) = native_get_debugreg(register) #define set_debugreg(value, register) \ native_set_debugreg(register, value) static inline void load_sp0(struct tss_struct *tss, struct thread_struct *thread) { native_load_sp0(tss, thread); } #define set_iopl_mask native_set_iopl_mask #endif /* CONFIG_PARAVIRT */ /* * Save the cr4 feature set we're using (ie * Pentium 4MB enable and PPro Global page * enable), so that any CPU's that boot up * after us can get the correct flags. */ extern unsigned long mmu_cr4_features; /* CR4에서 특정 플래그를 on */ static inline void set_in_cr4(unsigned long mask) { unsigned long cr4; mmu_cr4_features |= mask; cr4 = read_cr4(); cr4 |= mask; write_cr4(cr4); } static inline void clear_in_cr4(unsigned long mask) { unsigned long cr4; mmu_cr4_features &= ~mask; cr4 = read_cr4(); cr4 &= ~mask; write_cr4(cr4); } typedef struct { unsigned long seg; } mm_segment_t; /* * create a kernel thread without removing it from tasklists */ extern int kernel_thread(int (*fn)(void *), void *arg, unsigned long flags); /* Free all resources held by a thread. */ extern void release_thread(struct task_struct *); /* Prepare to copy thread state - unlazy all lazy state */ extern void prepare_to_copy(struct task_struct *tsk); unsigned long get_wchan(struct task_struct *p); /* * Generic CPUID function * clear %ecx since some cpus (Cyrix MII) do not set or clear %ecx * resulting in stale register contents being returned. * op = eax, ecx 가 0 인 이유는? 밑에 주석에서 보듯이 분류 */ static inline void cpuid(unsigned int op, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx) { *eax = op; *ecx = 0; __cpuid(eax, ebx, ecx, edx); } /* Some CPUID calls want 'count' to be placed in ecx */ /* cx를 사용하는 cpuid */ static inline void cpuid_count(unsigned int op, int count, unsigned int *eax, unsigned int *ebx, unsigned int *ecx, unsigned int *edx) { *eax = op; *ecx = count; __cpuid(eax, ebx, ecx, edx); } /* * CPUID functions returning a single datum */ static inline unsigned int cpuid_eax(unsigned int op) { unsigned int eax, ebx, ecx, edx; cpuid(op, &eax, &ebx, &ecx, &edx); return eax; } static inline unsigned int cpuid_ebx(unsigned int op) { unsigned int eax, ebx, ecx, edx; cpuid(op, &eax, &ebx, &ecx, &edx); return ebx; } static inline unsigned int cpuid_ecx(unsigned int op) { unsigned int eax, ebx, ecx, edx; cpuid(op, &eax, &ebx, &ecx, &edx); return ecx; } static inline unsigned int cpuid_edx(unsigned int op) { unsigned int eax, ebx, ecx, edx; cpuid(op, &eax, &ebx, &ecx, &edx); return edx; } /* REP NOP (PAUSE) is a good thing to insert into busy-wait loops. */ static inline void rep_nop(void) { asm volatile("rep; nop" ::: "memory"); } static inline void cpu_relax(void) { rep_nop(); } /* Stop speculative execution and prefetching of modified code. */ static inline void sync_core(void) { int tmp; /* 386과 486은 투기적 분기 실행을 하지 않기 때문에 jmp로 장벽을 친다. */ #if defined(CONFIG_M386) || defined(CONFIG_M486) if (boot_cpu_data.x86 < 5) /* There is no speculative execution. * jmp is a barrier to prefetching. */ asm volatile("jmp 1f\n1:\n" ::: "memory"); else #endif /* cpuid is a barrier to speculative execution. * Prefetched instructions are automatically * invalidated when modified. */ asm volatile("cpuid" : "=a" (tmp) : "0" (1) : "ebx", "ecx", "edx", "memory"); } static inline void __monitor(const void *eax, unsigned long ecx, unsigned long edx) { /* "monitor %eax, %ecx, %edx;" */ asm volatile(".byte 0x0f, 0x01, 0xc8;" :: "a" (eax), "c" (ecx), "d"(edx)); } static inline void __mwait(unsigned long eax, unsigned long ecx) { /* "mwait %eax, %ecx;" */ asm volatile(".byte 0x0f, 0x01, 0xc9;" :: "a" (eax), "c" (ecx)); } static inline void __sti_mwait(unsigned long eax, unsigned long ecx) { trace_hardirqs_on(); /* "mwait %eax, %ecx;" */ asm volatile("sti; .byte 0x0f, 0x01, 0xc9;" :: "a" (eax), "c" (ecx)); } extern void select_idle_routine(const struct cpuinfo_x86 *c); extern void init_amd_e400_c1e_mask(void); extern unsigned long boot_option_idle_override; extern bool amd_e400_c1e_detected; enum idle_boot_override {IDLE_NO_OVERRIDE=0, IDLE_HALT, IDLE_NOMWAIT, IDLE_POLL, IDLE_FORCE_MWAIT}; extern void enable_sep_cpu(void); extern int sysenter_setup(void); extern void early_trap_init(void); /* Defined in head.S */ extern struct desc_ptr early_gdt_descr; extern void cpu_set_gdt(int); extern void switch_to_new_gdt(int); extern void load_percpu_segment(int); extern void cpu_init(void); static inline unsigned long get_debugctlmsr(void) { unsigned long debugctlmsr = 0; #ifndef CONFIG_X86_DEBUGCTLMSR if (boot_cpu_data.x86 < 6) return 0; #endif rdmsrl(MSR_IA32_DEBUGCTLMSR, debugctlmsr); return debugctlmsr; } static inline void update_debugctlmsr(unsigned long debugctlmsr) { #ifndef CONFIG_X86_DEBUGCTLMSR if (boot_cpu_data.x86 < 6) return; #endif wrmsrl(MSR_IA32_DEBUGCTLMSR, debugctlmsr); } /* * from system description table in BIOS. Mostly for MCA use, but * others may find it useful: */ extern unsigned int machine_id; extern unsigned int machine_submodel_id; extern unsigned int BIOS_revision; /* Boot loader type from the setup header: */ extern int bootloader_type; extern int bootloader_version; extern char ignore_fpu_irq; #define HAVE_ARCH_PICK_MMAP_LAYOUT 1 #define ARCH_HAS_PREFETCHW #define ARCH_HAS_SPINLOCK_PREFETCH #ifdef CONFIG_X86_32 # define BASE_PREFETCH ASM_NOP4 # define ARCH_HAS_PREFETCH #else # define BASE_PREFETCH "prefetcht0 (%1)" #endif /* * Prefetch instructions for Pentium III (+) and AMD Athlon (+) * * It's not worth to care about 3dnow prefetches for the K6 * because they are microcoded there and very slow. */ static inline void prefetch(const void *x) { alternative_input(BASE_PREFETCH, "prefetchnta (%1)", X86_FEATURE_XMM, "r" (x)); } /* * 3dnow prefetch to get an exclusive cache line. * Useful for spinlocks to avoid one state transition in the * cache coherency protocol: */ static inline void prefetchw(const void *x) { alternative_input(BASE_PREFETCH, "prefetchw (%1)", X86_FEATURE_3DNOW, "r" (x)); } static inline void spin_lock_prefetch(const void *x) { prefetchw(x); } #ifdef CONFIG_X86_32 /* * User space process size: 3GB (default). */ #define TASK_SIZE PAGE_OFFSET #define TASK_SIZE_MAX TASK_SIZE #define STACK_TOP TASK_SIZE #define STACK_TOP_MAX STACK_TOP #define INIT_THREAD { \ .sp0 = sizeof(init_stack) + (long)&init_stack, \ .vm86_info = NULL, \ .sysenter_cs = __KERNEL_CS, \ .io_bitmap_ptr = NULL, \ } /* * Note that the .io_bitmap member must be extra-big. This is because * the CPU will access an additional byte beyond the end of the IO * permission bitmap. The extra byte must be all 1 bits, and must * be within the limit. */ #define INIT_TSS { \ .x86_tss = { \ .sp0 = sizeof(init_stack) + (long)&init_stack, \ .ss0 = __KERNEL_DS, \ .ss1 = __KERNEL_CS, \ .io_bitmap_base = INVALID_IO_BITMAP_OFFSET, \ }, \ .io_bitmap = { [0 ... IO_BITMAP_LONGS] = ~0 }, \ } extern unsigned long thread_saved_pc(struct task_struct *tsk); #define THREAD_SIZE_LONGS (THREAD_SIZE/sizeof(unsigned long)) #define KSTK_TOP(info) \ ({ \ unsigned long *__ptr = (unsigned long *)(info); \ (unsigned long)(&__ptr[THREAD_SIZE_LONGS]); \ }) /* * The below -8 is to reserve 8 bytes on top of the ring0 stack. * This is necessary to guarantee that the entire "struct pt_regs" * is accessible even if the CPU haven't stored the SS/ESP registers * on the stack (interrupt gate does not save these registers * when switching to the same priv ring). * Therefore beware: accessing the ss/esp fields of the * "struct pt_regs" is possible, but they may contain the * completely wrong values. */ #define task_pt_regs(task) \ ({ \ struct pt_regs *__regs__; \ __regs__ = (struct pt_regs *)(KSTK_TOP(task_stack_page(task))-8); \ __regs__ - 1; \ }) #define KSTK_ESP(task) (task_pt_regs(task)->sp) #else /* * User space process size. 47bits minus one guard page. */ #define TASK_SIZE_MAX ((1UL << 47) - PAGE_SIZE) /* This decides where the kernel will search for a free chunk of vm * space during mmap's. */ #define IA32_PAGE_OFFSET ((current->personality & ADDR_LIMIT_3GB) ? \ 0xc0000000 : 0xFFFFe000) #define TASK_SIZE (test_thread_flag(TIF_IA32) ? \ IA32_PAGE_OFFSET : TASK_SIZE_MAX) #define TASK_SIZE_OF(child) ((test_tsk_thread_flag(child, TIF_IA32)) ? \ IA32_PAGE_OFFSET : TASK_SIZE_MAX) #define STACK_TOP TASK_SIZE #define STACK_TOP_MAX TASK_SIZE_MAX #define INIT_THREAD { \ .sp0 = (unsigned long)&init_stack + sizeof(init_stack) \ } #define INIT_TSS { \ .x86_tss.sp0 = (unsigned long)&init_stack + sizeof(init_stack) \ } /* * Return saved PC of a blocked thread. * What is this good for? it will be always the scheduler or ret_from_fork. */ #define thread_saved_pc(t) (*(unsigned long *)((t)->thread.sp - 8)) #define task_pt_regs(tsk) ((struct pt_regs *)(tsk)->thread.sp0 - 1) extern unsigned long KSTK_ESP(struct task_struct *task); #endif /* CONFIG_X86_64 */ extern void start_thread(struct pt_regs *regs, unsigned long new_ip, unsigned long new_sp); /* * This decides where the kernel will search for a free chunk of vm * space during mmap's. */ #define TASK_UNMAPPED_BASE (PAGE_ALIGN(TASK_SIZE / 3)) #define KSTK_EIP(task) (task_pt_regs(task)->ip) /* Get/set a process' ability to use the timestamp counter instruction */ #define GET_TSC_CTL(adr) get_tsc_mode((adr)) #define SET_TSC_CTL(val) set_tsc_mode((val)) extern int get_tsc_mode(unsigned long adr); extern int set_tsc_mode(unsigned int val); extern int amd_get_nb_id(int cpu); struct aperfmperf { u64 aperf, mperf; }; static inline void get_aperfmperf(struct aperfmperf *am) { WARN_ON_ONCE(!boot_cpu_has(X86_FEATURE_APERFMPERF)); rdmsrl(MSR_IA32_APERF, am->aperf); rdmsrl(MSR_IA32_MPERF, am->mperf); } #define APERFMPERF_SHIFT 10 static inline unsigned long calc_aperfmperf_ratio(struct aperfmperf *old, struct aperfmperf *new) { u64 aperf = new->aperf - old->aperf; u64 mperf = new->mperf - old->mperf; unsigned long ratio = aperf; mperf >>= APERFMPERF_SHIFT; if (mperf) ratio = div64_u64(aperf, mperf); return ratio; } /* * AMD errata checking */ #ifdef CONFIG_CPU_SUP_AMD extern const int amd_erratum_383[]; extern const int amd_erratum_400[]; extern bool cpu_has_amd_erratum(const int *); #define AMD_LEGACY_ERRATUM(...) { -1, __VA_ARGS__, 0 } #define AMD_OSVW_ERRATUM(osvw_id, ...) { osvw_id, __VA_ARGS__, 0 } #define AMD_MODEL_RANGE(f, m_start, s_start, m_end, s_end) \ ((f << 24) | (m_start << 16) | (s_start << 12) | (m_end << 4) | (s_end)) #define AMD_MODEL_RANGE_FAMILY(range) (((range) >> 24) & 0xff) #define AMD_MODEL_RANGE_START(range) (((range) >> 12) & 0xfff) #define AMD_MODEL_RANGE_END(range) ((range) & 0xfff) #else #define cpu_has_amd_erratum(x) (false) #endif /* CONFIG_CPU_SUP_AMD */ #endif /* _ASM_X86_PROCESSOR_H */
x86-8/linux-3.2
arch/x86/include/asm/processor.h
C
gpl-2.0
25,169
package LOOKANDFEEL; // UIManager.put("nimbusBase", new Color(115,164,209)); // UIManager.put("nimbusBlueGrey", new Color(200,200,200)); // UIManager.put("control", new Color(140,190,234)); // JFormPrincipal.ponerLookAndFeelReal( // JDatosGeneralesP.getDatosGenerales().getLookAndFeelObjeto(), // JDatosGeneralesP.getDatosGenerales().getLookAndFeel(), // JDatosGeneralesP.getDatosGenerales().getLookAndFeelTema()); import com.sun.java.swing.Painter; import java.io.*; import java.net.URI; import java.util.*; import java.util.List; import java.util.regex.Pattern; import java.awt.*; import java.awt.event.*; import java.beans.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.plaf.ColorUIResource; import javax.swing.table.*; import javax.swing.GroupLayout.Alignment; import javax.tools.JavaCompiler; import javax.tools.SimpleJavaFileObject; import javax.tools.ToolProvider; import javax.tools.JavaCompiler.CompilationTask; //import com.sun.java.swing.Painter; public class NimbusThemeCreator implements ActionListener, ChangeListener, ItemListener, PropertyChangeListener, TableModelListener { private static final int TABLE_WIDTH = 450; private static final int VALUE_WIDTH = 100; private static final int DEFAULT_WIDTH = 50; public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { public void run() { setNimbusLookAndFeel(); //loadRandom(); JFrame frame = new JFrame(NimbusThemeCreator.class.getSimpleName()); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); NimbusThemeCreator creator = new NimbusThemeCreator(); frame.add(creator.createBody(), BorderLayout.CENTER); frame.getRootPane().setDefaultButton(creator.defaultButton); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } private static void setNimbusLookAndFeel() { try { for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { UIManager.setLookAndFeel(info.getClassName()); return; } } throw new ClassNotFoundException(); } catch (Exception e) { throw new IllegalStateException(e); } } private static void loadRandom() { Random rdm = new Random(); for (Map.Entry<Object,Object> entry : UIManager.getLookAndFeelDefaults().entrySet()) { Type type = Type.getType(entry.getValue()); switch (type) { case Color: UIManager.put(entry.getKey(), new Color(rdm.nextInt(256), rdm.nextInt(256), rdm.nextInt(256))); break; case Insets: UIManager.put(entry.getKey(), new Insets(rdm.nextInt(10), rdm.nextInt(10), rdm.nextInt(10), rdm.nextInt(10))); break; case Font: Font font = (Font)entry.getValue(); UIManager.put(entry.getKey(), font.deriveFont(font.getSize2D()+(rdm.nextBoolean()?1:-1))); break; case Boolean: UIManager.put(entry.getKey(), Boolean.FALSE.equals(entry.getValue())); break; case Integer: Integer i = (Integer)entry.getValue(); UIManager.put(entry.getKey(), i+rdm.nextInt(5)); } } } private JButton update; private JCheckBox autoUpdate; private JTable primaryTable; private JTable secondaryTable; private JTable otherTable; private JComboBox keyFilter; private JComboBox keyFilterMethod; private JComboBox typeFilter; private JButton defaultButton; private static String[] painterKeys; private NimbusThemeCreator() { List<String> primary = new ArrayList<String>(); List<String> secondary = new ArrayList<String>(); List<String> other = new ArrayList<String>(); Set<String> filters = new HashSet<String>(); List<String> painters = new ArrayList<String>(); for (Map.Entry<Object,Object> entry : UIManager.getLookAndFeelDefaults().entrySet()) { if (!(entry.getKey() instanceof String)) continue; String str = (String)entry.getKey(); if (Character.isLowerCase(str.charAt(0))) { if (entry.getValue() instanceof Color) { if (entry.getValue() instanceof ColorUIResource) { primary.add(str); } else { secondary.add(str); } } else { other.add(str); } } else { if (str.endsWith("Painter")) painters.add(str); int i = str.indexOf('.'); if (i < 0) continue; other.add(str); if (Character.isLetter(str.charAt(0))) { int j = str.indexOf('['); if (j >= 0 && j < i) i = j; j = str.indexOf(':'); if (j >= 0 && j < i) i = j; filters.add(str.substring(0, i)); } } } painterKeys = painters.toArray(new String[painters.size()]); Arrays.sort(painterKeys); primaryTable = createUITable(false, 0, Type.Color, primary); primaryTable.getModel().addTableModelListener(this); secondaryTable = createUITable(false, 0, Type.Color, secondary); otherTable = createUITable(true, 75, null, other); otherTable.setAutoCreateRowSorter(true); DefaultRowSorter<?,?> sorter = (DefaultRowSorter<?,?>)otherTable.getRowSorter(); sorter.setSortable(2, false); String[] filterArray = filters.toArray(new String[filters.size()+1]); filterArray[filterArray.length-1] = ""; Arrays.sort(filterArray); keyFilter = new JComboBox(filterArray); keyFilter.setToolTipText("Filter Key Column"); keyFilter.setEditable(true); keyFilter.addActionListener(this); keyFilterMethod = new JComboBox(new Object[]{"Starts With","Ends With","Contains","Regex"}); keyFilterMethod.addActionListener(this); Object[] types = Type.values(); Object[] typeArray = new Object[types.length+1]; System.arraycopy(types, 0, typeArray, 1, types.length); typeArray[0] = ""; typeFilter = new JComboBox(typeArray); typeFilter.setToolTipText("Filter Type Column"); typeFilter.addActionListener(this); update = new JButton("Update UI"); update.addActionListener(this); autoUpdate = new JCheckBox("Auto Update", false); autoUpdate.addItemListener(this); defaultButton = new JButton("Default"); defaultButton.setDefaultCapable(true); } JComponent createBody() { JScrollPane primary = titled(new JScrollPane( primaryTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), "Primary"); JScrollPane secondary = titled(new JScrollPane( secondaryTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER), "Secondary"); JPanel colors = new JPanel(new StackedTableLayout(3, 10, true)); colors.add(primary); colors.add(secondary); Dimension size = new Dimension(TABLE_WIDTH, primaryTable.getRowHeight()*20); otherTable.setPreferredScrollableViewportSize(size); JScrollPane other = new JScrollPane(otherTable); other.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); JPanel otherPanel = new JPanel(null); JPanel filters = new JPanel(new FiltersLayout()); filters.add(keyFilter); filters.add(keyFilterMethod); filters.add(typeFilter); otherTable.getColumnModel().getColumn(0).addPropertyChangeListener(this); GroupLayout layout = new GroupLayout(otherPanel); otherPanel.setLayout(layout); layout.setHorizontalGroup(layout.createSequentialGroup() .addGap(2) .addGroup(layout.createParallelGroup() .addComponent(filters).addComponent(other))); final int prf = GroupLayout.PREFERRED_SIZE; layout.setVerticalGroup(layout.createSequentialGroup() .addGap(2).addComponent(other).addComponent(filters, prf, prf, prf)); JTabbedPane options = new JTabbedPane(); options.addTab("UI Base", colors); options.addTab("UI Controls", otherPanel); JComponent preview = createPreview(); JButton imp = new JButton("Import"); imp.addActionListener(this); JButton exp = new JButton("Export"); exp.addActionListener(this); JPanel body = new JPanel(null); layout = new GroupLayout(body); body.setLayout(layout); layout.setHorizontalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.LEADING, false) .addComponent(options) .addGroup(layout.createSequentialGroup() .addGap(4) .addComponent(imp).addComponent(exp) .addGap(0, 100, Short.MAX_VALUE) .addComponent(autoUpdate).addGap(5).addComponent(update))) .addComponent(preview)); layout.setVerticalGroup(layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addComponent(options) .addGroup(layout.createBaselineGroup(false, true) .addComponent(imp).addComponent(exp) .addComponent(update).addComponent(autoUpdate)) .addGap(4)) .addComponent(preview)); return body; } private static String getPrototypeString(int chars) { char[] c = new char[chars]; Arrays.fill(c, 'w'); return new String(c); } private void createCollections() { JList list = new JList(painterKeys); list.setPrototypeCellValue(getPrototypeString(50)); JTree tree = new JTree(); for (int row=0; row<tree.getRowCount(); row++) tree.expandRow(row); TableColumnModel columns = new DefaultTableColumnModel(); TableColumn nameColumn = new TableColumn(0, 300); nameColumn.setHeaderValue("Name"); columns.addColumn(nameColumn); TableColumn typeColumn = new TableColumn(1, 100); typeColumn.setHeaderValue("Type"); columns.addColumn(typeColumn); JTable table = new JTable(otherTable.getModel(), columns); table.setPreferredScrollableViewportSize(new Dimension(400, table.getRowHeight()*15)); JSplitPane hor = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, titled(new JScrollPane(tree), "JTree"), titled(new JScrollPane(list), "JList")); collections.setTopComponent(hor); collections.setBottomComponent(titled(new JScrollPane(table), JTable.class.getSimpleName())); collections.validate(); collections.setDividerLocation(0.55); hor.setDividerLocation(0.35); } private void createTexts() { JTextArea area = new JTextArea(10, 40); Exception ex = new Exception("Little something for the Text Components"); StringWriter writer = new StringWriter(); PrintWriter pw = new PrintWriter(writer); ex.printStackTrace(pw); pw.flush(); pw.close(); String str = writer.toString(); area.setText(str); area.select(0, 0); final JEditorPane editor = new JEditorPane(); editor.setText(str); texts.setTopComponent(titled(new JScrollPane(area), JTextArea.class.getSimpleName())); texts.setBottomComponent(titled(new JScrollPane(editor), JEditorPane.class.getSimpleName())); texts.setDividerLocation(0.5); } private void createOptions() { options.add(createOptionPane("Plain Message", JOptionPane.PLAIN_MESSAGE)); options.add(createOptionPane("Error Message", JOptionPane.ERROR_MESSAGE)); options.add(createOptionPane("Information Message", JOptionPane.INFORMATION_MESSAGE)); options.add(createOptionPane("Warning Message", JOptionPane.WARNING_MESSAGE)); options.add(createOptionPane("Want to do something?", JOptionPane.QUESTION_MESSAGE)); JComboBox choiceCombo = new JComboBox(Type.values()); options.add(titled(new JOptionPane(choiceCombo, JOptionPane.QUESTION_MESSAGE, JOptionPane.OK_CANCEL_OPTION), "Question Message")); } private void createDesktop() { final JDesktopPane desktop = new JDesktopPane(); JPopupMenu popup = new JPopupMenu(); ActionListener al = new ActionListener() { public void actionPerformed(ActionEvent e) { JInternalFrame frame = new JInternalFrame( JInternalFrame.class.getSimpleName(), true, true, true, true); frame.setVisible(true); frame.setBounds(50, 100, 600, 500); desktop.add(frame); desktop.moveToFront(frame); desktop.setSelectedFrame(frame); } }; al.actionPerformed(null); popup.add("New Internal Frame").addActionListener(al); desktop.setComponentPopupMenu(popup); this.desktop.add(desktop, BorderLayout.CENTER); } private void createFileChooser() { fileChooser.add(titled( new JFileChooser(), JFileChooser.class.getSimpleName())); } private void createColorChooser() { colorChooser.add((titled( new JColorChooser(), JColorChooser.class.getSimpleName()))); } public void stateChanged(ChangeEvent e) { JTabbedPane tabs = (JTabbedPane)e.getSource(); int idx = tabs.getSelectedIndex(); if (idx >= 0 && !created[idx]) { created[idx] = true; switch (idx) { case 1: createCollections(); break; case 2: createOptions(); break; case 3: createTexts(); break; case 4: createFileChooser(); break; case 5: createColorChooser(); break; case 6: createDesktop(); break; } } } private boolean[] created; private JSplitPane collections; private JPanel options; private JSplitPane texts; private JPanel fileChooser; private JPanel colorChooser; private JPanel desktop; private JComponent createPreview() { JLabel label1 = new JLabel("Hover Here for Tooltip"); label1.setToolTipText("Tooltip"); JLabel label2 = disabled(new JLabel("Disabled")); JButton button1 = new JButton("Button"); JButton button2 = disabled(new JButton("Disabled")); JToggleButton toggle1 = new JToggleButton("Toggle", true); JToggleButton toggle2 = new JToggleButton("Toggle", false); JToggleButton toggle3 = disabled(new JToggleButton("Disabled", true)); JToggleButton toggle4 = disabled(new JToggleButton("Disabled", false)); JRadioButton radio1 = new JRadioButton("Radio", true); JRadioButton radio2 = new JRadioButton("Radio", false); JRadioButton radio3 = disabled(new JRadioButton("Disabled", true)); JRadioButton radio4 = disabled(new JRadioButton("Disabled", false)); JCheckBox check1 = new JCheckBox("Check", true); JCheckBox check2 = new JCheckBox("Check", false); JCheckBox check3 = disabled(new JCheckBox("Disabled", true)); JCheckBox check4 = disabled(new JCheckBox("Disabled", false)); JPopupMenu popup = new JPopupMenu(); JMenu menu = new JMenu("Menu"); menu.add("Item"); popup.add(menu); popup.add(new JMenuItem("Item")); JMenuItem item1 = new JMenuItem("Accelerator"); item1.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_A, InputEvent.CTRL_DOWN_MASK)); popup.add(item1); popup.add(disabled(new JMenuItem("Disabled"))); popup.addSeparator(); popup.add(new JRadioButtonMenuItem("Radio", true)); popup.add(new JRadioButtonMenuItem("Radio", false)); popup.add(disabled(new JRadioButtonMenuItem("Disabled", false))); popup.addSeparator(); popup.add(new JCheckBoxMenuItem("Check", true)); popup.add(new JCheckBoxMenuItem("Check", false)); popup.add(disabled(new JCheckBoxMenuItem("Disabled", false))); JTextField text1 = new JTextField("Click Here for Popup"); text1.setComponentPopupMenu(popup); JTextField text2 = disabled(new JTextField("Disabled")); JSlider slider1 = new JSlider(); JSlider slider2 = disabled(new JSlider()); JSlider slider3 = tickedSlider(false); JSlider slider4 = disabled(tickedSlider(false)); JSlider slider5 = tickedSlider(true); JSlider slider6 = disabled(tickedSlider(true)); JSpinner spinner1 = new JSpinner(new SpinnerNumberModel(100, 0, Short.MAX_VALUE, 100)); JSpinner spinner2 = disabled(new JSpinner(new SpinnerNumberModel(100, 0, Short.MAX_VALUE, 100))); JSpinner spinner3 = new JSpinner(new SpinnerDateModel()); JSpinner spinner4 = disabled(new JSpinner(new SpinnerDateModel())); Type[] values = Type.values(); JSpinner spinner5 = new JSpinner(new SpinnerListModel(values)); JSpinner spinner6 = disabled(new JSpinner(new SpinnerListModel(values))); JComboBox combo1 = new JComboBox(values); JComboBox combo2 = disabled(new JComboBox(values)); JComboBox combo3 = new JComboBox(values); combo3.setEditable(true); JComboBox combo4 = disabled(new JComboBox(values)); combo4.setEditable(true); JProgressBar prog1 = progress(0, false); JProgressBar prog2 = progress(50, false); JProgressBar prog3 = progress(100, false); JProgressBar progA = progress(0, true); JProgressBar progB = progress(50, true); JProgressBar progC = progress(100, true); final JProgressBar indeterminate = new JProgressBar(); indeterminate.setIndeterminate(true); JCheckBox hide = new JCheckBox("Hide Indeterminate Progress Bar:", false); hide.setHorizontalAlignment(SwingConstants.RIGHT); hide.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { indeterminate.setVisible(evt.getStateChange() != ItemEvent.SELECTED); } }); JPanel other = new JPanel(null); GroupLayout layout = new GroupLayout(other); other.setLayout(layout); final int prf = GroupLayout.PREFERRED_SIZE; JPanel toggles = createPanel(JToggleButton.class, 2, 0, toggle1, toggle2, toggle3, toggle4); JPanel buttons = createPanel(JButton.class, 1, 0, defaultButton, button1, button2); JPanel combos = createPanel(JComboBox.class, 0, 2, combo1, combo2, combo3, combo4); JPanel spinners = createPanel(JSpinner.class, 0, 2, spinner1, spinner2, spinner3, spinner4, spinner5, spinner6); JPanel checks = createPanel(JCheckBox.class, 2, 0, check1, check2, check3, check4); JPanel radios = createPanel(JRadioButton.class, 2, 0, radio1, radio2, radio3, radio4); JPanel progs = createPanel(JProgressBar.class, 0, 2, prog1, progA, prog2, progB, prog3, progC, hide, indeterminate); JPanel texts = createPanel(JTextField.class, 0, 1, text1, text2); JPanel labels = createPanel(JLabel.class, 1, 0, label1, label2); JPanel sliders = createPanel(JSlider.class, 0, 2, slider1, slider2, slider3, slider4, slider5, slider6); layout.linkSize(SwingConstants.HORIZONTAL, combos, spinners); layout.setHorizontalGroup(layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(buttons, prf, prf, prf) .addComponent(toggles, prf, prf, prf) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addComponent(radios) .addComponent(checks)) .addGap(0, 0, 20))) .addGroup(layout.createParallelGroup() .addComponent(texts) .addComponent(combos, prf, prf, prf) .addComponent(spinners, prf, prf, prf))) .addComponent(labels) .addComponent(sliders) .addComponent(progs)); layout.setVerticalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup() .addGroup(layout.createSequentialGroup() .addComponent(buttons, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(toggles, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(radios, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(checks, prf, prf, prf)) .addGroup(layout.createSequentialGroup() .addComponent(texts, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(combos, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(spinners, prf, prf, prf))) .addGap(0, 0, Short.MAX_VALUE) .addComponent(labels, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(sliders, prf, prf, prf) .addGap(0, 0, Short.MAX_VALUE) .addComponent(progs, prf, prf, prf)); this.texts = new JSplitPane(JSplitPane.VERTICAL_SPLIT); collections = new JSplitPane(JSplitPane.VERTICAL_SPLIT); options = new JPanel(new GridLayout(0, 2)); desktop = new JPanel(new BorderLayout()); fileChooser = new JPanel(new GridBagLayout()); colorChooser = new JPanel(new GridBagLayout()); JTabbedPane tabs = new JTabbedPane(); tabs.addTab("Controls", other); tabs.addTab("Collections", collections); tabs.addTab("Options", centered(options)); tabs.addTab("Texts", this.texts); tabs.addTab("File Chooser", fileChooser); tabs.addTab("Color Chooser", colorChooser); tabs.addTab("Desktop Pane", desktop); created = new boolean[tabs.getTabCount()]; created[0] = true; tabs.addChangeListener(this); return tabs; } private static JPanel centered(JComponent c) { JPanel panel = new JPanel(new GridBagLayout()); panel.add(c); return panel; } private static JOptionPane createOptionPane(String message, int type) { JOptionPane pane = new JOptionPane(message, type); String title = message; if (type == JOptionPane.QUESTION_MESSAGE) { title = "Question Message"; pane.setOptionType(JOptionPane.YES_NO_CANCEL_OPTION); } return titled(pane, title); } private static JProgressBar progress(int value, boolean paint) { JProgressBar bar = new JProgressBar(); bar.setValue(value); bar.setStringPainted(paint); return bar; } private static JSlider tickedSlider(boolean paintLabels) { JSlider s = new JSlider(0, 100); s.setMajorTickSpacing(25); s.setMinorTickSpacing(5); s.setPaintTicks(true); s.setPaintLabels(paintLabels); return s; } private static <T extends JComponent> T disabled(T c) { c.setEnabled(false); return c; } private static <T extends JComponent> T titled(T c, String title) { c.setBorder(BorderFactory.createTitledBorder(title)); return c; } private static JPanel createPanel(Class<?> cls, int rows, int cols, Component...components) { JPanel panel = new JPanel(new GridLayout(rows, cols, 5, 0)); for (Component c : components) panel.add(c); return titled(panel, cls.getSimpleName()); } private class StackedTableLayout implements LayoutManager { StackedTableLayout() { this(5, 15, true); } StackedTableLayout(int minRows, int prefRows, boolean fillHeight) { this.minRows = minRows; this.prefRows = prefRows; this.fillHeight = fillHeight; } int minRows; int prefRows; boolean fillHeight; @Override public void addLayoutComponent(String name, Component comp) {} private JScrollPane[] scrollers(Container parent) { synchronized (parent.getTreeLock()) { int n = parent.getComponentCount(); if (n == 0) return null; JScrollPane[] scrollers = new JScrollPane[n]; while (--n>=0) scrollers[n] = (JScrollPane)parent.getComponent(n); return scrollers; } } @Override public void layoutContainer(Container parent) { JScrollPane[] scrollers = scrollers(parent); if (scrollers == null) return; int[] max = new int[scrollers.length]; int[] rowHeights = new int[scrollers.length]; int[] yInsets = new int[scrollers.length]; int maxTot = 0; Insets insets = parent.getInsets(); int y = insets.top; int x = insets.left; int height = parent.getHeight() - y - insets.bottom; int width = parent.getWidth() - x - insets.right; for (int i=scrollers.length; --i>=0;) { JTable table = (JTable)scrollers[i].getViewport().getView(); Dimension size = scrollers[i].getPreferredSize(); int h = size.height; size = table.getPreferredScrollableViewportSize(); yInsets[i] = h - size.height; rowHeights[i] = table.getRowHeight(); max[i] = table.getRowHeight() * table.getRowCount(); maxTot += max[i] + yInsets[i]; } if (maxTot <= height) { for (int i=0; i<scrollers.length; i++) { int h = max[i]+yInsets[i]; scrollers[i].setBounds(x, y, width, h); y += h; } } else { int count = max.length; int availableHeight = height; while (count > 1) { int min = Integer.MAX_VALUE; int minIdx = -1; for (int i=max.length; --i>=0;) { if (max[i] >= 0 && max[i]+yInsets[i] < min) { min = max[i]+yInsets[i]; minIdx = i; } } if (min > availableHeight/count) break; availableHeight -= min; max[minIdx] = -min; count--; } int rem = availableHeight % count; availableHeight /= count; for (int i=scrollers.length; --i>=0;) { int h = max[i]; if (h < 0) continue; if (h+yInsets[i] > availableHeight) { h = availableHeight; int r = (h - yInsets[i]) % rowHeights[i]; h -= r; rem += r; max[i] = h; } else { max[i] = -h - yInsets[i]; } } for (int i=0; i<scrollers.length; i++) { int h = max[i]; if (h < 0) { h = -h; } else { if (rem > rowHeights[i]) { h += rowHeights[i]; rem -= rowHeights[i]; } } scrollers[i].setBounds(x, y, width, h); y += h; } } if (fillHeight) { JScrollPane s = scrollers[scrollers.length-1]; s.setSize(width, s.getHeight()+height-y); } } @Override public Dimension minimumLayoutSize(Container parent) { return size(parent, true); } @Override public Dimension preferredLayoutSize(Container parent) { return size(parent, false); } private Dimension size(Container parent, boolean min) { JScrollPane[] scrollers = scrollers(parent); if (scrollers == null) return new Dimension(0, 0); Insets insets = parent.getInsets(); int height = insets.top + insets.bottom; int xInsets = insets.left + insets.right; int maxWidth = 0; int rows = min ? minRows : prefRows; for (int i=scrollers.length; --i>=0;) { JTable table = (JTable)scrollers[i].getViewport().getView(); Dimension size = scrollers[i].getPreferredSize(); int w = size.width; int h = size.height; size = table.getPreferredScrollableViewportSize(); height += h - size.height + Math.min(rows, table.getRowCount()) * table.getRowHeight(); w -= size.width; size = min ? table.getMinimumSize() : table.getPreferredSize(); w += size.width; if (w > maxWidth) maxWidth = w; } return new Dimension(maxWidth+xInsets, height); } @Override public void removeLayoutComponent(Component comp) {} } private class FiltersLayout implements LayoutManager { @Override public void addLayoutComponent(String name, Component comp) {} @Override public void layoutContainer(Container parent) { TableColumnModel mdl = otherTable.getColumnModel(); int cw = mdl.getColumn(0).getWidth(); Dimension size = keyFilterMethod.getPreferredSize(); int kfmw = size.width; int kfw = cw - kfmw - 10; keyFilter.setBounds(0, 0, kfw, size.height); keyFilterMethod.setBounds(kfw, 0, kfmw, size.height); size = typeFilter.getPreferredSize(); typeFilter.setBounds(cw, 0, size.width, size.height); } @Override public Dimension minimumLayoutSize(Container parent) { return size(300); } @Override public Dimension preferredLayoutSize(Container parent) { return size(TABLE_WIDTH); } private Dimension size(int width) { Dimension size = keyFilter.getPreferredSize(); size.width = width; return size; } @Override public void removeLayoutComponent(Component comp) {} } private static class Table extends JTable implements ComponentListener { Table(TableModel mdl, TableColumnModel clm) { super(mdl, clm); } @Override public void addNotify() { super.addNotify(); Container parent = getParent(); if (parent instanceof JViewport) { parent.addComponentListener(this); } } @Override public void removeNotify() { super.removeNotify(); Container parent = getParent(); if (parent instanceof JViewport) { parent.removeComponentListener(this); } } /** * Overridden to supply hasFocus as false to the renderers * but still allow the table to be focusable. */ @Override public Component prepareRenderer(TableCellRenderer renderer, int row, int column) { Object value = getValueAt(row, column); boolean isSelected = false; // Only indicate the selection and focused cell if not printing if (!isPaintingForPrint()) { isSelected = isCellSelected(row, column); } return renderer.getTableCellRendererComponent( this, value, isSelected, false, row, column); } @Override public void componentHidden(ComponentEvent e) {} @Override public void componentMoved(ComponentEvent e) {} @Override public void componentResized(ComponentEvent e) { JViewport port = (JViewport)e.getSource(); TableColumnModel columns = getColumnModel(); int width = port.getWidth(); Insets in = port.getInsets(); width -= in.left + in.right; for (int i=columns.getColumnCount(); --i>0;) width -= columns.getColumn(i).getWidth(); if (width < 210) width = 210; TableColumn col = columns.getColumn(0); if (width != col.getPreferredWidth()) { col.setMinWidth(width); col.setPreferredWidth(width); } } @Override public void componentShown(ComponentEvent e) {} } private static JTable createUITable(boolean keyColumnResizable, int typeWidth, Type type, List<String> lst) { String[] keys = lst.toArray(new String[lst.size()]); Arrays.sort(keys); TableModel mdl = type == null ? new UITableModel(keys) : new UITypeTableModel(keys, type, true); JTable table = new Table(mdl, null); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setRowHeight(25); TableColumnModel columns = table.getColumnModel(); int keyWidth = TABLE_WIDTH-typeWidth-VALUE_WIDTH-DEFAULT_WIDTH; columns.getColumn(0).setMinWidth(keyWidth); columns.getColumn(0).setPreferredWidth(keyWidth); columns.getColumn(0).setResizable(keyColumnResizable); setWidth(columns.getColumn(1), typeWidth); TableColumn column = columns.getColumn(2); setWidth(column, VALUE_WIDTH); column.setCellRenderer(new UIDefaultsRenderer()); column.setCellEditor(new UIDefaultsEditor()); setWidth(columns.getColumn(3), DEFAULT_WIDTH); return table; } private static void setWidth(TableColumn column, int width) { column.setPreferredWidth(width); column.setResizable(false); column.setMinWidth(width); column.setMaxWidth(width); } @Override public void tableChanged(TableModelEvent e) { if (e.getSource() == primaryTable.getModel()) { UITableModel mdl = (UITableModel)secondaryTable.getModel(); mdl.fireTableRowsUpdated(0, mdl.getRowCount()-1); } if (autoUpdate.isSelected() && updater == null) { updater = new Runnable() { public void run() { updater = null; updateUI(); } }; SwingUtilities.invokeLater(updater); } } private Runnable updater; @Override public void propertyChange(PropertyChangeEvent e) { if ("width".equals(e.getPropertyName())) { JComponent c = (JComponent)keyFilter.getParent(); if (c != null) { c.revalidate(); c.repaint(); } } } @Override public void itemStateChanged(ItemEvent e) { boolean b = autoUpdate.isSelected(); update.setEnabled(!b); if (b) { secondaryTable.getModel().addTableModelListener(this); otherTable.getModel().addTableModelListener(this); } else { secondaryTable.getModel().removeTableModelListener(this); otherTable.getModel().removeTableModelListener(this); } } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == update) { updateUI(); } else if (e.getSource() == keyFilter || e.getSource() == keyFilterMethod || e.getSource() == typeFilter) { updateFilter(); } else if (e.getActionCommand() == "Import") { if (importer == null) importer = new Importer( (JFrame)SwingUtilities.getWindowAncestor(defaultButton)); importer.showDialog(); } else if (e.getActionCommand() == "Export") { if (exporter == null) exporter = new Exporter( (JFrame)SwingUtilities.getWindowAncestor(defaultButton)); exporter.showDialog(); } } private Importer importer; private Exporter exporter; private JFileChooser browse; private JFileChooser getFileChooser() { if (browse == null) browse = new JFileChooser(); return browse; } private JComponent createContentPane(JTabbedPane tabs, JButton ok, JButton cancel) { JPanel content = new JPanel(null); GroupLayout layout = new GroupLayout(content); content.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup() .addComponent(tabs).addGroup(layout.createSequentialGroup() .addGap(0, 200, Short.MAX_VALUE).addComponent(ok) .addGap(3).addComponent(cancel).addGap(5))); layout.setVerticalGroup(layout.createSequentialGroup() .addComponent(tabs, 0, GroupLayout.PREFERRED_SIZE, Short.MAX_VALUE) .addGroup(layout.createBaselineGroup(false, true) .addComponent(ok).addComponent(cancel)) .addGap(5)); layout.linkSize(SwingConstants.HORIZONTAL, ok, cancel); return content; } private class Importer implements ActionListener { Importer(JFrame frame) { location = new JTextField(25); JButton browse = new JButton("Browse..."); browse.addActionListener(this); JPanel file = new JPanel(new BorderLayout()); file.add(titled(createLocation(location, browse), "File Location"), BorderLayout.SOUTH); text = new JTextArea(10, 20); tabs = new JTabbedPane(); tabs.addTab("Import from File", file); tabs.addTab("Import from Text", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); ok = new JButton("OK"); ok.addActionListener(this); JButton cancel = new JButton("Cancel"); cancel.addActionListener(this); dialog = new JDialog(frame, true); dialog.setContentPane(createContentPane(tabs, ok, cancel)); dialog.pack(); dialog.setLocationRelativeTo(null); } JDialog dialog; JTabbedPane tabs; JTextArea text; JTextField location; JButton ok; File browseFile; public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == "Browse...") { JFileChooser browse = getFileChooser(); browse.setFileSelectionMode(JFileChooser.FILES_ONLY); browse.setMultiSelectionEnabled(false); if (browseFile != null) browse.setSelectedFile(browseFile); if (JFileChooser.APPROVE_OPTION == browse.showOpenDialog(null)) { browseFile = browse.getSelectedFile(); location.setText(browseFile.getPath()); } } else if (e.getActionCommand() == "OK") { if (tabs.getSelectedIndex() == 0) { try { File file = new File(location.getText()); if (!file.isFile()) { error("Invalid File:\n\t" + file.getCanonicalPath()); return; } error("Not Implemented."); } catch (IOException x) { error("IOException: "+x.getMessage()); return; } } else if (tabs.getSelectedIndex() == 1) { JavaCompiler compiler = ToolProvider.getSystemJavaCompiler(); if (compiler == null) { error("No compiler available."); return; } String statements = text.getText(); StringBuilder s = new StringBuilder(statements.length()+200); String cls = "NimbusTheme"; s.append("import javax.swing.*;\n"); s.append("import javax.swing.plaf.*;\n"); s.append("import java.awt.*;\n"); s.append("public class ").append(cls).append(" {\n"); s.append("\tpublic static void loadTheme() {\n"); s.append(statements); s.append("\t}\n}"); CompilationTask task = compiler.getTask(null, null, null, null, null, Arrays.asList(new MemoryFileObject(cls, s.toString()))); boolean success = task.call(); if (!success) { error("Unable to compile code."); return; } else { try { Class.forName(cls).getDeclaredMethod("loadTheme", (Class[])null) .invoke(null, (Object[])null); File file = new File(".", cls.replace('.', File.separatorChar).concat(".class")); if (file.exists()) file.delete(); } catch (Exception x) { error(x.getClass().getSimpleName() + ": " + x.getMessage()); return; } } } dialog.dispose(); } else if (e.getActionCommand() == "Cancel") { dialog.dispose(); } } void showDialog() { ok.getRootPane().setDefaultButton(ok); dialog.setVisible(true); } } private class MemoryFileObject extends SimpleJavaFileObject { final String code; MemoryFileObject(String name, String code) { super(URI.create("string:///" + name.replace('.','/') + Kind.SOURCE.extension),Kind.SOURCE); this.code = code; } @Override public CharSequence getCharContent(boolean ignoreEncodingErrors) { return code; } } private JComponent createLocation(JTextField location, JButton browse) { JPanel panel = new JPanel(null); GroupLayout layout = new GroupLayout(panel); panel.setLayout(layout); layout.setHorizontalGroup(layout.createSequentialGroup() .addComponent(location).addComponent(browse)); int prf = GroupLayout.PREFERRED_SIZE; layout.setVerticalGroup(layout.createBaselineGroup(false, true) .addComponent(location, prf, prf, prf) .addComponent(browse, prf, prf, prf)); return panel; } private void error(String msg) { JOptionPane.showMessageDialog( null, msg, "Error", JOptionPane.ERROR_MESSAGE); } private boolean confirm(String msg) { return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog( null, msg, "Confirm", JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE); } private class Exporter implements ActionListener, ChangeListener { Exporter(JFrame frame) { JLabel pkgLabel = new JLabel("Package Name:"); JLabel clsLabel = new JLabel("Class Name:"); JLabel mtdLabel = new JLabel("Method Name:"); packageField = new JTextField(); classField = new JTextField("NimbusTheme"); methodField = new JTextField("loadTheme"); location = new JTextField(25); JButton browse = new JButton("Browse..."); browse.addActionListener(this); JPanel options = titled(new JPanel(null), "Naming Options"); GroupLayout layout = new GroupLayout(options); options.setLayout(layout); layout.setHorizontalGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(Alignment.TRAILING, false) .addComponent(pkgLabel).addComponent(clsLabel).addComponent(mtdLabel)) .addGap(5) .addGroup(layout.createParallelGroup() .addComponent(packageField).addComponent(classField).addComponent(methodField))); layout.setVerticalGroup(layout.createSequentialGroup() .addGroup(layout.createBaselineGroup(false, true) .addComponent(pkgLabel).addComponent(packageField)) .addGroup(layout.createBaselineGroup(false, true) .addComponent(clsLabel).addComponent(classField)) .addGroup(layout.createBaselineGroup(false, true) .addComponent(mtdLabel).addComponent(methodField))); JComponent save = titled(createLocation(location, browse), "Save Location"); JPanel file = new JPanel(null); layout = new GroupLayout(file); file.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup() .addComponent(options).addComponent(save)); final int prf = GroupLayout.PREFERRED_SIZE; layout.setVerticalGroup(layout.createSequentialGroup() .addComponent(options, prf, prf, prf).addComponent(save, prf, prf, prf)); text = new JTextArea(); text.setEditable(false); tabs = new JTabbedPane(); tabs.addChangeListener(this); tabs.addTab("Export to File", file); tabs.addTab("Export to Text", new JScrollPane(text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED)); ok = new JButton("OK"); ok.addActionListener(this); JButton cancel = new JButton("Cancel"); cancel.addActionListener(this); dialog = new JDialog(frame, true); dialog.setContentPane(createContentPane(tabs, ok, cancel)); dialog.pack(); dialog.setLocationRelativeTo(null); } private JDialog dialog; private JTabbedPane tabs; private JTextField packageField; private JTextField classField; private JTextField methodField; private JTextField location; private JButton ok; private JTextArea text; private boolean validTextArea; private File browseDirectory; public void stateChanged(ChangeEvent e) { if (!validTextArea && tabs.getSelectedIndex() == 1) { validTextArea = true; StringWriter writer = new StringWriter(); try { export(writer, null); text.setText(writer.toString()); } catch (IOException x) {} } } public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == "Browse...") { JFileChooser browse = getFileChooser(); browse.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); browse.setMultiSelectionEnabled(false); if (browseDirectory != null) browse.setSelectedFile(browseDirectory); if (JFileChooser.APPROVE_OPTION == browse.showSaveDialog(null)) { browseDirectory = browse.getSelectedFile(); location.setText(browseDirectory.getPath()); } } else if (e.getActionCommand() == "OK") { if (tabs.getSelectedIndex() == 0) { String pkg = packageField.getText(); String cls = classField.getText(); String mtd = methodField.getText(); File dir = new File(location.getText()); try { if (!dir.isDirectory()) { if (dir.isFile()) { error("Invalid location:\n\t"+dir.getCanonicalPath()+"\nLocation must be a directory."); return; } if (!confirm("Directory does not exist:\n\t"+dir.getCanonicalPath()+"\nCreate?")) return; dir.mkdirs(); if (!dir.isDirectory()) { error("Unable to create directory:\n\t" + dir.getCanonicalPath()); return; } } File file = new File(dir, cls.concat(".java")); if (file.exists()) { if (!confirm("File already exists:\n\t"+file.getCanonicalPath()+"\nOverwrite?")) return; } BufferedWriter writer = new BufferedWriter(new FileWriter(file)); if (pkg != null && !pkg.isEmpty()) { writer.write(pkg); writer.newLine(); writer.newLine(); } writer.write("import javax.swing.*;"); writer.newLine(); writer.write("import javax.swing.plaf.*;"); writer.newLine(); writer.write("import java.awt.*;"); writer.newLine(); writer.newLine(); writer.write("public class "); writer.write(cls); writer.write(" {"); writer.newLine(); writer.write("\tpublic static void "); writer.write(mtd); writer.write(" {"); writer.newLine(); export(writer, "\t\t"); writer.write("\t}"); writer.newLine(); writer.write("}"); writer.flush(); writer.close(); } catch (IOException x) { error("IOException: "+x.getMessage()); return; } } dialog.dispose(); } else if (e.getActionCommand() == "Cancel") { dialog.dispose(); } } void showDialog() { ok.getRootPane().setDefaultButton(ok); validTextArea = false; tabs.setSelectedIndex(0); dialog.setVisible(true); } private void export(Writer writer, String prefix) throws IOException { BufferedWriter buf = writer instanceof BufferedWriter ? (BufferedWriter)writer : null; UIDefaults def = UIManager.getDefaults(); for (Map.Entry<Object,Object> entry : def.entrySet()) { if (def.containsKey(entry.getKey())) { if (prefix != null) writer.write(prefix); writer.write("UIManager.put(\""); writer.write(entry.getKey().toString()); Object obj = entry.getValue(); Type type = Type.getType(obj); switch (type) { case Color: Color color = (Color)obj; writer.write("\", new ColorUIResource(0x"); writer.write(Integer.toHexString(color.getRGB() & 0xffffff)); writer.write("));"); break; case Painter: break; case Insets: Insets insets = (Insets)obj; writer.write("\", new InsetsUIResource("); writer.write(Integer.toString(insets.top)); writer.write(", "); writer.write(Integer.toString(insets.left)); writer.write(", "); writer.write(Integer.toString(insets.bottom)); writer.write(", "); writer.write(Integer.toString(insets.right)); writer.write("));"); break; case Font: Font font = (Font)obj; writer.write("\", new FontUIResource(\""); writer.write(font.getFamily()); writer.write("\", "); String style = font.isBold() ? "Font.BOLD" : null; style = font.isItalic() ? style == null ? "Font.ITALIC" : style + " | " + "Font.ITALIC" : "Font.PLAIN"; writer.write(style); writer.write(", "); writer.write(font.getSize()); writer.write("));"); break; case Boolean: writer.write("\", Boolean."); writer.write(obj == Boolean.TRUE ? "TRUE" : "FALSE"); writer.write(");"); break; case Integer: writer.write("\", new Integer("); writer.write(obj.toString()); writer.write("));"); break; case String: writer.write("\", \""); writer.write(obj.toString()); writer.write('"'); writer.write(");"); break; case Icon: break; case Dimension: Dimension size = (Dimension)obj; writer.write("\", new DimensionUIResource("); writer.write(Integer.toString(size.width)); writer.write(", "); writer.write(Integer.toString(size.height)); writer.write("));"); break; case Object: break; } if (buf != null) { buf.newLine(); } else { writer.write('\n'); } } } } } private void updateUI() { for (Window window : Window.getWindows()) { SwingUtilities.updateComponentTreeUI(window); } defaultButton.getRootPane().setDefaultButton(defaultButton); } private void updateFilter() { DefaultRowSorter<TableModel,Object> sorter = (DefaultRowSorter<TableModel,Object>)otherTable.getRowSorter(); String key = keyFilter.getSelectedItem().toString(); RowFilter<TableModel,Object> filter = null; if (!key.isEmpty()) { Object method = keyFilterMethod.getSelectedItem(); if (method == "Starts With") { filter = RowFilter.regexFilter('^'+Pattern.quote(key), 0); } else if (method == "Ends With") { filter = RowFilter.regexFilter(Pattern.quote(key)+'$', 0); } else if (method == "Contains") { filter = RowFilter.regexFilter(Pattern.quote(key), 0); } else { filter = RowFilter.regexFilter(key, 0); } } String type = typeFilter.getSelectedItem().toString(); if (!type.isEmpty()) { RowFilter<TableModel,Object> typeFilter = RowFilter.regexFilter('^'+type+'$', 1); filter = filter == null ? typeFilter : RowFilter.<TableModel,Object>andFilter(Arrays.asList(filter, typeFilter)); } sorter.setRowFilter(filter); } private enum Type { Color(ColorChooser.class), Painter(null), Insets(InsetsChooser.class), Font(FontChooser.class), Boolean(BooleanChooser.class), Integer(IntegerChooser.class), String(StringChooser.class), Icon(null), Dimension(DimensionChooser.class), Object(null); private Type(Class<? extends ValueChooser> cls) { chooserClass = cls; } ValueChooser chooser; Class<? extends ValueChooser> chooserClass; ValueChooser getValueChooser() { if (chooser == null) { if (chooserClass == null) return null; try { chooser = chooserClass.newInstance(); } catch (Exception e) { e.printStackTrace(); chooserClass = null; return null; } } return chooser; } static Type getType(Object obj) { if (obj instanceof Color) { return Color; } else if (obj instanceof Painter<?>) { return Painter; } else if (obj instanceof Insets) { return Insets; } else if (obj instanceof Font) { return Font; } else if (obj instanceof Boolean) { return Boolean; } else if (obj instanceof Integer) { return Integer; } else if (obj instanceof Icon) { return Icon; } else if (obj instanceof String) { return String; } else if (obj instanceof Dimension) { return Dimension; } else { return Object; } } } private static class UITypeTableModel extends UITableModel { UITypeTableModel(String[] keys, Type typ, boolean edt) { super(keys, null); type = typ; editable = edt; } private Type type; private boolean editable; @Override Type getType(int row) { return type; } @Override public String getColumnName(int col) { return col == 2 ? type.name() : super.getColumnName(col); } @Override public boolean isCellEditable(int row, int col) { return editable ? super.isCellEditable(row, col) : false; } } private static class UITableModel extends AbstractTableModel { UITableModel(String[] kys) { this(kys, new Type[kys.length]); } UITableModel(String[] kys, Type[] tys) { keys = kys; types = tys; } private String[] keys; private Type[] types; @Override public int getColumnCount() { return 4; } @Override public String getColumnName(int col) { switch (col) { case 0: return "Key"; case 1: return "Type"; case 2: return "Value"; case 3: return "Default"; } throw new IllegalArgumentException(); } @Override public Class<?> getColumnClass(int col) { switch (col) { case 2: return UIDefaults.class; case 3: return Boolean.class; } return Object.class; } @Override public int getRowCount() { return keys.length; } @Override public Object getValueAt(int row, int col) { switch (col) { case 0: return keys[row]; case 1: return getType(row); case 2: return UIManager.get(keys[row]); case 3: return !UIManager.getDefaults().containsKey(keys[row]); } throw new IllegalArgumentException(); } Type getType(int row) { if (types[row] == null) types[row] = Type.getType(UIManager.get(keys[row])); return types[row]; } @Override public boolean isCellEditable(int row, int col) { return col == 2 || col == 3; } // Font.equals() is too sensitive, so use this. private boolean fontEquals(Font a, Font b) { return a.getSize2D() == b.getSize2D() && a.getStyle() == b.getStyle() && a.getFamily().equals(b.getFamily()); } @Override public void setValueAt(Object aValue, int row, int col) { switch (col) { case 2: Object def = UIManager.getLookAndFeel().getDefaults().get(keys[row]); if ((getType(row) == Type.Font && fontEquals((Font)aValue, (Font)def)) || aValue.equals(def)) { UIManager.put(keys[row], null); } else { UIManager.put(keys[row], aValue); } fireTableCellUpdated(row, 3); break; case 3: if (aValue == Boolean.TRUE) { UIManager.put(keys[row], null); fireTableCellUpdated(row, 2); } break; } } } private static class UIDefaultsRenderer extends JComponent implements TableCellRenderer { private static final Font BOOLEAN_FONT = Font.decode("sansserif-bold"); Object value; Type type; int row = -1; boolean selected = false; @Override public Component getTableCellRendererComponent(JTable tbl, Object val, boolean isSelected, boolean hasFocus, int row, int column) { UITableModel mdl = (UITableModel)tbl.getModel(); value = val; type = mdl.getType(tbl.convertRowIndexToModel(row)); this.row = row; selected = isSelected; return this; } protected void paintComponent(Graphics g) { if (selected) { g.setColor(UIManager.getColor("Table[Enabled+Selected].textBackground")); g.fillRect(0, 0, getWidth(), getHeight()); } else if (row%2==0) { g.setColor(UIManager.getColor("Table.alternateRowColor")); g.fillRect(0, 0, getWidth(), getHeight()); } switch (type) { case Color: { Color col = (Color)value; g.setColor(col); Graphics2D g2 = (Graphics2D)g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2.fillRoundRect(2, 2, getWidth()-4, getHeight()-4, 10, 10); } break; case Painter: { Painter<JComponent> painter = (Painter<JComponent>)value; g.translate((getWidth()-getHeight())/2, 0); painter.paint((Graphics2D)g, this, getHeight(), getHeight()); } break; case Insets: { Insets in = (Insets)value; g.setColor(Color.BLACK); g.drawRect(2, 2, getWidth()-4, getHeight()-4); g.setColor(Color.GRAY); g.drawRect(3+in.left, 3+in.top, getWidth()-6-in.right-in.left, getHeight()-6-in.bottom-in.top); } break; case Font: { Font font = (Font)value; drawString(g, font.getFamily(), font); } break; case Boolean: drawString(g, value.toString(), BOOLEAN_FONT); break; case Integer: case String: drawString(g, value.toString(), getFont()); break; case Icon: { Icon icn = (Icon)value; int x = (getWidth()-icn.getIconWidth())/2; int y = (getHeight()-icn.getIconHeight())/2; icn.paintIcon(this, g, x, y); } break; case Dimension: { Dimension d = (Dimension)value; if (d.width < getWidth()-2 && d.height < getHeight()-2) { g.setColor(Color.GRAY); g.drawRect((getWidth()-d.width)/2, (getHeight()-d.height)/2, d.width, d.height); } else { drawString(g, d.width+" x "+d.height, getFont()); } } break; case Object: { System.out.println(value.getClass()); } break; } } private void drawString(Graphics g, String str, Font font) { g.setColor(selected ? UIManager.getColor("Table[Enabled+Selected].textForeground") : UIManager.getColor("Table.textForeground")); g.setFont(font); ((Graphics2D)g).setRenderingHint( RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON); FontMetrics metrics = g.getFontMetrics(); int w = metrics.stringWidth(str); int y =(getHeight()-metrics.getHeight())/2+metrics.getAscent(); int x; int cw = getWidth(); if (w > cw) { w = metrics.charWidth('.')*3; int i = 0; while (w < cw) w += metrics.charWidth(str.charAt(i++)); str = str.substring(0, i-1).concat("..."); x = 0; } else { x = (cw-w)/2; } g.drawString(str, x, y); } } private static class UIDefaultsEditor extends AbstractCellEditor implements TableCellEditor, ActionListener, MouseListener { private static final String OK = "OK"; private static final String CANCEL = "Cancel"; public UIDefaultsEditor() { renderer = new UIDefaultsRenderer(); renderer.addMouseListener(this); popup = new JPopupMenu(); popup.setLayout(new BorderLayout()); JButton ok = new JButton(OK); ok.addActionListener(this); JButton cancel = new JButton(CANCEL); cancel.addActionListener(this); JPanel buttons = new JPanel(null); GroupLayout layout = new GroupLayout(buttons); buttons.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(Alignment.CENTER, true) .addGroup(layout.createSequentialGroup() .addGap(8).addComponent(ok).addGap(5).addComponent(cancel).addGap(8)) .addGap(100, 100, Short.MAX_VALUE)); layout.setVerticalGroup(layout.createBaselineGroup(false, true) .addComponent(ok).addComponent(cancel)); layout.linkSize(SwingUtilities.HORIZONTAL, ok, cancel); popup.add(buttons, BorderLayout.SOUTH); } UIDefaultsRenderer renderer; JPopupMenu popup; ValueChooser currentChooser; @Override public Object getCellEditorValue() { return renderer.value; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { return renderer.getTableCellRendererComponent(table, value, true, false, row, column); } @Override public boolean isCellEditable(EventObject e) { if (e instanceof MouseEvent) { MouseEvent me = (MouseEvent)e; return (me.getModifiersEx() & ( InputEvent.ALT_DOWN_MASK | InputEvent.CTRL_DOWN_MASK | InputEvent.META_DOWN_MASK | InputEvent.SHIFT_DOWN_MASK)) == 0; } return super.isCellEditable(e); } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == OK) { Object value = currentChooser.getValue(); if (!value.equals(renderer.value)) renderer.value = value; currentChooser = null; popup.setVisible(false); fireEditingStopped(); } else if (e.getActionCommand() == CANCEL) { currentChooser = null; popup.setVisible(false); fireEditingCanceled(); } } @Override public void mouseClicked(MouseEvent e) {} @Override public void mouseEntered(MouseEvent e) {} @Override public void mouseExited(MouseEvent e) {} @Override public void mousePressed(MouseEvent e) {} @Override public void mouseReleased(MouseEvent evt) { currentChooser = renderer.type.getValueChooser(); if (currentChooser == null) return; currentChooser.setValue(renderer.value); BorderLayout layout = (BorderLayout)popup.getLayout(); Component cur = layout.getLayoutComponent(BorderLayout.CENTER); if (cur != currentChooser.getComponent()) { if (cur != null) popup.remove(cur); popup.add(currentChooser.getComponent(), BorderLayout.CENTER); } popup.show(renderer, 0, renderer.getHeight()); } } private static abstract class ValueChooser { abstract JComponent getComponent(); abstract void setValue(Object value); abstract Object getValue(); } private static class BooleanChooser extends ValueChooser { @SuppressWarnings("unused") BooleanChooser() { tru = new JRadioButton(Boolean.TRUE.toString()); tru.setFont(UIDefaultsRenderer.BOOLEAN_FONT); fal = new JRadioButton(Boolean.FALSE.toString()); fal.setFont(UIDefaultsRenderer.BOOLEAN_FONT); ButtonGroup group = new ButtonGroup(); group.add(tru); group.add(fal); pane = new JPanel(null); GroupLayout layout = new GroupLayout(pane); pane.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(Alignment.CENTER, true) .addGap(100, 100, Short.MAX_VALUE) .addGroup(layout.createSequentialGroup() .addGap(8) .addGroup(layout.createParallelGroup(Alignment.LEADING, false) .addComponent(tru).addComponent(fal)) .addGap(8))); layout.setVerticalGroup(layout.createSequentialGroup() .addGap(2).addComponent(tru).addComponent(fal).addGap(4)); } JComponent pane; JRadioButton tru; JRadioButton fal; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { if (Boolean.TRUE.equals(value)) { tru.setSelected(true); } else { fal.setSelected(true); } } @Override Object getValue() { return Boolean.valueOf(tru.isSelected()); } } private static class StringChooser extends ValueChooser { @SuppressWarnings("unused") StringChooser() { pane = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 2)); text = new JTextField(40); pane.add(text); } JComponent pane; JTextField text; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { text.setText(value.toString()); } @Override Object getValue() { return text.getText(); } } private static class ColorChooser extends ValueChooser { @SuppressWarnings("unused") ColorChooser() { chooser = new JColorChooser(); } JColorChooser chooser; @Override JComponent getComponent() { return chooser; } @Override void setValue(Object value) { chooser.setColor((Color)value); } @Override Object getValue() { return chooser.getColor(); } } private static class IntegerChooser extends ValueChooser { @SuppressWarnings("unused") IntegerChooser() { chooser = new NumberChooser(null, -10, 100); pane = NumberChooser.createComponent(null, -1, -1, -1, -1, chooser); } JComponent pane; NumberChooser chooser; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { chooser.setValue((Integer)value); } @Override Object getValue() { return chooser.getValue(); } } private static class DimensionChooser extends ValueChooser implements ChangeListener { @SuppressWarnings("unused") DimensionChooser() { width = new NumberChooser("Width:", 0, 2000); height = new NumberChooser("Height:", 0, 2000); renderer = new UIDefaultsRenderer(); renderer.type = Type.Dimension; width.addChangeListener(this); height.addChangeListener(this); pane = NumberChooser.createComponent(renderer, 200, Short.MAX_VALUE, 200, 200, width, height); } JComponent pane; NumberChooser width; NumberChooser height; UIDefaultsRenderer renderer; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { Dimension d = (Dimension)value; renderer.value = null; width.setValue(d.width); height.setValue(d.height); renderer.value = (Dimension)d.clone(); } @Override Object getValue() { return renderer.value; } @Override public void stateChanged(ChangeEvent e) { if (renderer.value != null) { Dimension d = (Dimension)renderer.value; d.width = width.getValue(); d.height = height.getValue(); renderer.repaint(); } } } private static class InsetsChooser extends ValueChooser implements ChangeListener { @SuppressWarnings("unused") InsetsChooser() { top = new NumberChooser("Top:", 0, 20); left = new NumberChooser("Left:", 0, 20); bottom = new NumberChooser("Bottom:", 0, 20); right = new NumberChooser("Right:", 0, 20); renderer = new UIDefaultsRenderer(); renderer.type = Type.Insets; top.addChangeListener(this); left.addChangeListener(this); bottom.addChangeListener(this); right.addChangeListener(this); pane = NumberChooser.createComponent(renderer, 120, 120, 50, 50, top, left, bottom, right); } JComponent pane; NumberChooser top; NumberChooser left; NumberChooser bottom; NumberChooser right; UIDefaultsRenderer renderer; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { Insets i = (Insets)value; renderer.value = null; top.setValue(i.top); left.setValue(i.left); bottom.setValue(i.bottom); right.setValue(i.right); renderer.value = (Insets)i.clone(); renderer.repaint(); } @Override Object getValue() { return renderer.value; } @Override public void stateChanged(ChangeEvent e) { if (renderer.value != null) { Insets in = (Insets)renderer.value; in.top = top.getValue(); in.left = left.getValue(); in.bottom = bottom.getValue(); in.right = right.getValue(); renderer.repaint(); } } } private static class NumberChooser implements ChangeListener { NumberChooser(String nam, int min, int max) { name = nam; spin = new SpinnerNumberModel(min, min, max, 1); spin.addChangeListener(this); slide = new JSlider(min, max); slide.setMinorTickSpacing((max-min)/10); slide.setMajorTickSpacing((max-min)/2); slide.setPaintTicks(true); slide.addChangeListener(this); } String name; SpinnerNumberModel spin; JSlider slide; @Override public void stateChanged(ChangeEvent e) { if (spin.getNumber().intValue() != slide.getValue()) { if (e.getSource() == slide) { spin.setValue(slide.getValue()); } else { slide.setValue(spin.getNumber().intValue()); } } } int getValue() { return slide.getValue(); } void setValue(int value) { slide.setValue(value); } void addChangeListener(ChangeListener l) { slide.addChangeListener(l); } static JComponent createComponent(JComponent preview, int prefW, int maxW, int prefH, int maxH, NumberChooser ... choosers) { JComponent pane = new JPanel(null); GroupLayout layout = new GroupLayout(pane); pane.setLayout(layout); GroupLayout.ParallelGroup labelX = null; GroupLayout.ParallelGroup spinX = layout.createParallelGroup(Alignment.LEADING, false); GroupLayout.ParallelGroup slideX = layout.createParallelGroup(Alignment.LEADING, false); GroupLayout.SequentialGroup y = layout.createSequentialGroup().addGap(2); for (NumberChooser chooser : choosers) { JLabel label = chooser.name == null ? null : new JLabel(chooser.name); JSpinner spin = new JSpinner(chooser.spin); GroupLayout.ParallelGroup baseline = layout.createBaselineGroup(false, true); y.addGroup(baseline); if (label != null) { if (labelX == null) labelX = layout.createParallelGroup(Alignment.TRAILING, false); labelX.addComponent(label); baseline.addComponent(label); } spinX.addComponent(spin); slideX.addComponent(chooser.slide); baseline.addComponent(spin).addComponent(chooser.slide); } GroupLayout.Group x = layout.createSequentialGroup().addGap(8); if (labelX != null) x.addGroup(labelX).addGap(2); x.addGroup(spinX).addGap(2).addGroup(slideX).addGap(8); y.addGap(4); if (preview != null) { y.addComponent(preview, prefH, prefH, maxH); y.addGap(4); x = layout.createParallelGroup(Alignment.CENTER, false) .addGroup(x).addComponent(preview, prefW, prefW, maxW); } layout.setHorizontalGroup(x); layout.setVerticalGroup(y); return pane; } } private static class FontChooser extends ValueChooser implements ChangeListener { @SuppressWarnings("unused") FontChooser() { family = new SpinnerListModel(new Object[]{ Font.DIALOG, Font.DIALOG_INPUT, Font.MONOSPACED, Font.SANS_SERIF, Font.SERIF }); family.addChangeListener(this); JSpinner familySpin = new JSpinner(family); size = new SpinnerNumberModel(32f, 8f, 32f, 2f); size.addChangeListener(this); JSpinner sizeSpin = new JSpinner(size); bold = new JToggleButton("b"); bold.addChangeListener(this); bold.setFont(bold.getFont().deriveFont(Font.BOLD)); italic = new JToggleButton("i"); italic.addChangeListener(this); italic.setFont(italic.getFont().deriveFont(Font.ITALIC)); renderer = new UIDefaultsRenderer(); renderer.type = Type.Font; pane = new JPanel(null); GroupLayout layout = new GroupLayout(pane); pane.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup(GroupLayout.Alignment.CENTER, true) .addGroup(layout.createSequentialGroup() .addGap(8).addComponent(familySpin, 150, 150, 150).addGap(2) .addComponent(sizeSpin).addGap(2).addComponent(bold) .addGap(2).addComponent(italic).addGap(12)) .addComponent(renderer)); layout.setVerticalGroup(layout.createSequentialGroup() .addGap(2) .addGroup(layout.createBaselineGroup(false, true) .addComponent(familySpin).addComponent(sizeSpin) .addComponent(bold).addComponent(italic)) .addComponent(renderer, 50, 50, 50)); } JComponent pane; SpinnerListModel family; SpinnerNumberModel size; JToggleButton bold; JToggleButton italic; UIDefaultsRenderer renderer; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { Font font = (Font)value; renderer.value = null; family.setValue(font.getFamily()); size.setValue(font.getSize2D()); bold.setSelected(font.isBold()); italic.setSelected(font.isItalic()); renderer.value = value; } @Override Object getValue() { return renderer.value; } @Override public void stateChanged(ChangeEvent e) { Font font = (Font)renderer.value; if (font != null) { if (e.getSource() == size) { renderer.value = font.deriveFont(size.getNumber().floatValue()); } else if (e.getSource() == bold) { renderer.value = font.deriveFont(bold.isSelected() ? font.getStyle() | Font.BOLD : font.getStyle() & ~Font.BOLD); } else if (e.getSource() == italic) { renderer.value = font.deriveFont(italic.isSelected() ? font.getStyle() | Font.ITALIC : font.getStyle() & ~Font.ITALIC); } else if (e.getSource() == family) { font = Font.decode(family.getValue().toString()+' '+size.getNumber().intValue()); int style = 0; if (bold.isSelected()) style |= Font.BOLD; if (italic.isSelected()) style |= Font.ITALIC; if (style != 0) font = font.deriveFont(style); renderer.value = font; } renderer.repaint(); } } } private static class PainterChooser extends ValueChooser implements ActionListener, ListSelectionListener, ChangeListener { @SuppressWarnings("unused") PainterChooser() { tablePane = new JScrollPane(); renderer = new UIDefaultsRenderer(); renderer.type = Type.Painter; editor = new JTextArea(20, 80); editor.setText("Not Implemented"); editor.setEnabled(false); editor.setFont(Font.decode(Font.MONOSPACED+' '+12)); JScrollPane scroller = new JScrollPane(editor); JButton update = new JButton("Update"); update.addActionListener(this); update.setEnabled(false); JButton toDialog = new JButton("Switch to Dialog"); toDialog.addActionListener(this); JPanel custom = new JPanel(null); GroupLayout layout = new GroupLayout(custom); custom.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup() .addComponent(scroller) .addGroup(layout.createSequentialGroup() .addComponent(update).addGap(10, 100, Short.MAX_VALUE).addComponent(toDialog))); layout.setVerticalGroup(layout.createSequentialGroup() .addComponent(scroller) .addGroup(layout.createBaselineGroup(false, true) .addComponent(update).addComponent(toDialog))); tabs = new JTabbedPane(); pane = new JPanel(null); layout = new GroupLayout(pane); pane.setLayout(layout); layout.setHorizontalGroup(layout.createParallelGroup() .addComponent(tabs) .addComponent(renderer, Alignment.CENTER, 100, 100, Short.MAX_VALUE)); layout.setVerticalGroup(layout.createSequentialGroup() .addComponent(tabs).addComponent(renderer, 25, 25, 25)); tabs.add("Custom", custom); tabs.add("Nimbus Painters", tablePane); tabs.addChangeListener(this); } JComponent pane; JTabbedPane tabs; JScrollPane tablePane; JTable table; JTextArea editor; UIDefaultsRenderer renderer; Object value; JDialog dialog; @Override JComponent getComponent() { return pane; } @Override void setValue(Object value) { this.value = null; if (table != null) table.changeSelection(-1, -1, false, false); this.value = value; renderer.value = value; } @Override Object getValue() { return value; } @Override public void valueChanged(ListSelectionEvent e) { if (value == null || e.getValueIsAdjusting()) return; int row = table.getSelectedRow(); renderer.value = row < 0 ? value : UIManager.getLookAndFeelDefaults().get( table.getValueAt(row, 0)); renderer.repaint(); } @Override public void stateChanged(ChangeEvent e) { if (tabs.getSelectedComponent() == tablePane && table == null) { DefaultTableColumnModel columns = new DefaultTableColumnModel(); TableColumn column = new TableColumn(0, 400); column.setHeaderValue("Key"); columns.addColumn(column); column = new TableColumn(2, 50, new UIDefaultsRenderer(), null); columns.addColumn(column); column.setHeaderValue(Type.Painter.name()); table = new Table(new UITypeTableModel(painterKeys, Type.Painter, false), columns); table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF); table.setRowHeight(25); table.setPreferredScrollableViewportSize(new Dimension(500, table.getRowHeight()*10)); table.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); table.getSelectionModel().addListSelectionListener(this); tablePane.getViewport().setView(table); tablePane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS); } } @Override public void actionPerformed(ActionEvent e) { if (e.getActionCommand() == "Update") { } else if (e.getActionCommand() == "Switch to Dialog") { if (dialog == null) { dialog = new JDialog((JFrame)null, true); } dialog.add(pane, BorderLayout.CENTER); dialog.pack(); dialog.setVisible(true); } } } }
Creativa3d/box3d
paquetesUtilidades/src/LOOKANDFEEL/NimbusThemeCreator.java
Java
gpl-2.0
117,156
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> <title>Íþº£Ô¶º½ÓÎÏ·ÖÐÐĹÙÍø½éÉÜ</title> <meta name="keywords" content="Íþº£Ô¶º½ÓÎÏ·ÖÐÐĹٷ½ÏÂÔØ¿Í»§¶Ë£¬Íþº£Ô¶º½ÓÎÏ·ÖÐÐÄÏÂÔØ" /> <meta name="description" content="Íþº£Ô¶º½ÓÎÏ·ÖÐÐĹÙÍø½éÉÜÁËÍþº£Ô¶º½ÓÎÏ·ÖÐÐĹٷ½ÏÂÔØ¿Í»§¶ËµÄ·½·¨£¬¹©´ó¼Ò²ÎÔÄ¡£" /> <link rel=stylesheet type=text/css href="/qipai/templets/default/style/style.css"> <link rel=stylesheet type=text/css href="/qipai/templets/default/style/p.css"> <link rel=stylesheet type=text/css href="/qipai/templets/default/style/common.css"> <script tyep="text/javascript" src="/qipai/templets/default/js/jquery-1.8.3.min.js"></script> </head> <body> <DIV class=top> <DIV class=c_960> <DIV class=top-nav><SPAN>Hi£¬»¶Ó­À´µ½789ÓÎÏ·ÖÐÐÄ£¡</SPAN></DIV> <DIV><!-- logo --> <DIV style="POSITION: relative" class=logo><A href="http://www.789game.com"></A></DIV> <DIV class=nav> <UL> <LI><a href="http://www.789game.com/" target="_blank">ÍøÕ¾Ê×Ò³</a></LI> <li><a href='/qipai/qipaiyouxipingtai/' target="_blank" >ÆåÅÆÓÎϷƽ̨</a></li> <li><a href='http://www.789game.com/GameIntroduction.aspx' target="_blank" >ÓÎÏ·½éÉÜ</a></li> <li><a href='http://www.789game.com/NewsList.aspx' target="_blank" >ÐÂÎŹ«¸æ</a></li> <li><a href='http://shuihu.789game.com/' target="_blank" >½Ö»úˮ䰴«</a></li> <li><a href='http://www.789game.com/xinshoubangzhu.html' target="_blank" >ÐÂÊÖ°ïÖú</a></li> <li><a href='http://buyu.789game.com/' target="_blank" >½Ö»úǧÅÚ²¶Óã</a></li> </UL> </DIV> <!-- µ¼º½À¸½áÊø --> </DIV> </DIV> </DIV> <div style="BORDER: #cdcdcd 1px solid; margin-top:10px; width:960px; margin:5px auto"> <div id="lunbobg"> <ul> <li><a href="http://www.789game.com/NewsShow.aspx?XID=439"> <img src="/qipai/templets/default/images/1-1.jpg" width="960" height="424"></a></a></li> <li><a href="http://down.789game.net/tgdownload/1272461/789GameCenter.exe"> <img src="/qipai/templets/default/images/2-1.jpg" width="960" height="424"></a></a></li> <li><a href="http://www.789game.com/NewsShow.aspx?XID=2006"> <img src="/qipai/templets/default/images/3-1.jpg" width="960" height="424"></a></a></li> </ul> </div> </div> <div class="main"> <div id=p_con><!--Ò³Ãæ×ó²à²¿·Ö ¿ªÊ¼ --> <div class=p_l> <div class=location> <img src="/qipai/templets/default/images/flag.png" width=16 height=16> µ±Ç°Î»ÖÃ:</strong><a href='/qipai'>ÆåÅÆÓÎÏ·</a> > <a href='/qipai/qipaiyouxipingtai/'>ÆåÅÆÓÎϷƽ̨</a> > </div> <div id=pnlContent> <h1 class=que-title>Íþº£Ô¶º½ÓÎÏ·ÖÐÐĹÙÍø½éÉÜ</h1> <div class="articelinfo"><span>×÷Õߣºadmin</span><span>·¢²¼Ê±¼ä£º2014-12-03</span></div> <div class=que-content> <div> &nbsp;</div> <div> <strong><span style="font-size: 12px;">Íþº£Ô¶º½ÓÎÏ·ÖÐÐĹÙÍø</span></strong><span style="font-size: 12px;">Ö÷Òª¾ÍÊÇÍþº£µØÇøÄDZßÓÎÏ·µÄÒ»¸öÍøÕ¾£¬Ö®ËùÒÔ½Ð×öÔ¶º½£¬ÊÇÒòΪÄDZ߿¿º££¬ÓæÃñÊǷdz£µÄ¶àµÄ£¬´¬Ò²ºÜ¶à£¬ËùÒÔÕâ<a href="http://www.789game.com">¸öÍøÕ¾µÄÓÎ</a>Ï·Ò²ÊǺÍÍþº£µ±µØµÄ·çÍÁÈËÇé·Ö²»¿ªµÄ¡£</span></div> <div> &nbsp;</div> <div> &nbsp;</div> <div> <strong>Íþº£Ô¶º½ÓÎÏ·ÖÐÐĹÙÍø</strong>µÄÓÎÏ··þÎñÆ÷ÊǷdz£µÄÀ÷º¦µÄ£¬ÓÎÏ·ÍŶÓΪÁ˱£Ö¤ÓÎÏ·µÄÕý³£µÄÔË×÷£¬ËùÒÔ¿ªÍ¨ÁË´ó¸ÅÁùÊ®¶ą̀µÄ·þÎñÆ÷£¬ËùÒÔÔÚÓÎÏ·µÄÎȶ¨ÐÔÕâÒ»µãÉÏÊDz»»á³öÏÖÈκεÄÎÊÌâµÄ£¬²»»á¿¨Ò²²»»á³öʲô¹ÊÕÏ£¬¸ÃÓÎϷƽ̨µÄºÜ¶àµÄÓÎÏ·¶¼ÉêÇëÁ˹ú¼ÒרÀû£¬ËùÒÔ±ðµÄÓÎÏ·ÖÐÐÄÊDz»¿ÉÒÔËæ±ã¾Í½è¼øÊ¹Óõģ¬ÕâÒ²ÊDZ£»¤µØ·½ÎÄ»¯µÄÒ»¸öÌåÏÖ£¬É½¶«±£»Ê¾ÍÊÇ×îºÃÍæµÄÒ»¿îÓÎÏ·ÁË£¬ËüÈÚºÏÁËɽ¶«ÈËÃñµÄֱˬºÍÖÇ»ÛÔÚÀïÃæ£¬ÄúÈç¹ûÍæÒ»ÍæµÄ»°£¬¿Ï¶¨»áÉîÓÐÌå»á¡£³ýÁËÕâÒ»¿î£¬Ò²ÊÇÓкܶà±ðµÄÓÎÏ·ÁË£¬±ÈÈçн®¹ØÅÆ£¬Ë®¾§Ö®ÁµµÈµÈ£¬ÔÚ²»¾ÃÒԺ󣬻¹»áÓÐÒ»¿îÐÂÓÎÏ·ÉÏÏߣ¬´ó¼Ò¾Í¾¡ÇéÆÚ´ý°É¡£</div> <div> &nbsp;</div> </div> <div class=pre-nex>ÉÏһƪ£º<a href='/qipai/qipaiyouxipingtai/1134.html'>ÖйúÓÎÏ·ÖÐÐÄ´óÌü¹Ù·½ÏÂÔØÁ´½Ó-ÖйúÆåÅÆÓÎÏ·ÖÐÐĹÙÍø</a> &nbsp;&nbsp;&nbsp;&nbsp;ÏÂһƪ£º<a href='/qipai/qipaiyouxipingtai/1144.html'>ÈýÏ¿ÓÎÏ·ÖÐÐĹٷ½ÏÂÔØ´óÌüµÄ²½Öè</a> </div> </div> </div> <!--ÓÒ²àÏÂÔØ begin--> <DIV class=p_r_xiazai> <DIV class=r_ad> <DIV class=dl_client_v2> <A style="BACKGROUND-POSITION: 22px -536px" href="http://down.789game.net/tgdownload/1272461/789GameCenter.exe" class=client_dl title=ÏÂÔØ¿Í»§¶Ë rel=nofollow></A> </DIV> </DIV> </div> <div class="ewmDown"> <div class="anzhuoDown"> <a href="http://download.6513.com/phoneGame/590145BY.apk" class="dowmForA" rel="nofollow"></a> </div> <div class="appleDown"> <a href="https://itunes.apple.com/us/app/jie-ji-jin-chan-bu-yu-mian/id1022745046?l=zh&ls=1&mt=8" class="dowmForI" target='_blank' rel="nofollow"></a> </div> </div> <DIV class=p_r> <DIV class=tags> <DL class=box_dl> <DT>ÓÎÏ·½éÉÜ</DT> <DIV class=tags> <A href="http://www.789game.com/GameRulesShow.aspx?XID=610" target="_blnak">½ð󸲶Óã</A> <A href="http://shuihu.789game.com/" target="_blnak">°ÙÒ×ˮ䰴«</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=601" target="_blnak">´óÊ¥ÄÖº£</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=203" target="_blnak">ˮ䰴«</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=2040" target="_blank">нð󸲶Óã</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=6" target="_blank">789Ó®ÈýÕÅ</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=361" target="_blank">¶þÈËÂ齫</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=102" target="_blank">¶þÈ˶·Å£</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=27" target="_blank">ËÄÈ˶·Å£</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=200" target="_blank">¶·µØÖ÷</A> <A href="http://www.789game.com/GameRulesShow.aspx?XID=5501" target="_blank">ÀîåÓÅüÓã</A> <A href="http://www.789game.com/" target="_blank">ÆåÅÆÆ½Ì¨</A> <A href="http://www.789game.com/NewsShow.aspx?XID=130" target="_blank">ÓÎÏ·Ìü²¶Óã´ïÈË</A> <A href="http://buyu.789game.com/" target="_blank">½Ö»úǧÅÚ²¶Óã¹ÙÍø</A> </DIV> </DL> </DIV> <DL class=box_dl> <DT>ÍÆ¼öÎÄÕÂ</DT> <DD><a href="/qipai/qipaiyouxipingtai/2781.html">ÐÂÀËÆåÅÆÖÐÐÄÏÂÔØ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2780.html">½¨µÂÓÎÏ·ÖÐÐÄ_¿ÉÒÔÊÍ·ÅѹÁ¦µÄÆå</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2779.html">çÆÔÆÓÎÏ·ÖÐÐÄ_×îºÃµÄÆåÅÆÓÎϷƽ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2778.html">¼Ñľ˹ÁúÓòÓÎÏ·ÖÐÐÄÏÂÔØ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2777.html">1368ÆåÅÆÓÎϷƽ̨</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2776.html">°®ÆåÅÆÓÎÏ·ÖÐÐÄ£¬ÆåÅÆÀàÓÎÏ·°®ºÃ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2775.html">½¨µÂÓÎÏ·ÖÐÐÄÊÖ»ú°æÏÂÔØ¸üºÃÍæ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2774.html">789ÆåÅÆÓÎÏ·ÊÖ»ú°æÏÂÔØ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2773.html">ÓÎÏ·Ìü²¶Óã´ïÈËÊÖ»ú°æ£¬°®²»ÊÍÊÖ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2772.html">½Ö»úǧÅÚ²¶Óã¹Ù·½°æ×¢²á£¬ºÃÀñÏà</a> </DD> </DL> <DL class=box_dl> <DT>×îÈÈÎÄÕÂ</DT> <DD><a href="/qipai/qipaiyouxipingtai/17.html">°²»Õ±ß·æÓÎÏ·¶·µØÖ÷</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/365.html">»ªÏÄÆåÅÆÓÎÏ·</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/1156.html">Öйú»¥¶¯ÓÎÏ·ÖÐÐÄÓÎϷƽ̨-Öйú</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/1199.html">çÆÔÆÓÎÏ·ÖÐÐĵÄÓÎÏ·Íæ·¨</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/1240.html">psp¶·µØÖ÷µÄÌØµã</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/1834.html">¿ªÐĶ·µØÖ÷ÏÂÔØÊ±Òª×¢ÒâµÄÎÊÌâ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/1926.html">ÁªÖÚ¶·µØÖ÷ÓÎÏ·ÄÜÓÐЧ»º½âѹÁ¦</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/1932.html">173ÓÎÏ·Íø£¬¸øÄã×îºÃµÄÓÎÏ·ÌåÑé</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2071.html">Ãæ¶ÔÃæµÄÊÓÆµ¶·µØÖ÷ÈÃÈËÃÇÓкõÄ</a> </DD> <DD><a href="/qipai/qipaiyouxipingtai/2092.html">ºÃÍæµÄ²¶Óã´ïÈË3ÄÚ¹º1.0.7°æ±¾</a> </DD> </DL> </DIV> </div> <!--Ò³ÃæÓҲಿ·Ö ½áÊø --> </div> </div> <DIV class=footer> µÖÖÆ²»Á¼ÓÎÏ·&nbsp;&nbsp;¾Ü¾øµÁ°æÓÎÏ·&nbsp;&nbsp;×¢Òâ×ÔÎÒ±£»¤&nbsp;&nbsp;½÷·ÀÊÜÆ­Éϵ±&nbsp;&nbsp;ÊʶÈÓÎÏ·ÒæÄÔ&nbsp;&nbsp;³ÁÃÔÓÎÏ·ÉËÉí&nbsp;&nbsp;ºÏÀí°²ÅÅʱ¼ä&nbsp;&nbsp;ÏíÊܽ¡¿µÉú»î <BR> <a href="http://www.789game.com">789ÓÎÏ·ÖÐÐÄ</a>http://www.789game.com/ Ô¥ICP±¸12014032ºÅ-1 ±¸°¸ÎĺÅ:ÎÄÍøÓα¸×Ö[2011]C-CBG002ºÅ<BR>¿Í·þQQ£º4000371814 ¿Í·þÈÈÏߣº4000371814 <script type="text/javascript"> var _bdhmProtocol = (("https:" == document.location.protocol) ? " https://" : " http://"); document.write(unescape("%3Cscript src='" + _bdhmProtocol + "hm.baidu.com/h.js%3Fde6684532de22a1b45cd44b14141ff07' type='text/javascript'%3E%3C/script%3E")); </script> </DIV> <style> #banners {margin-top:-50px;} #banners .hd {margin-top:-15px;width:100%;float:left;} #banners .hd ul {width: 555px;z-index: 100; position: absolute; left: 45%; } #banners .hd ul li {float: left; width: 11px; height: 11px; background-color: #fff; overflow: hidden; text-indent: -9999px; border-radius:6px;cursor:pointer; opacity: 0.5;filter: alpha(opacity=50); cursor: pointer;} #banners .hd ul li.on {opacity: 1;filter: alpha(opacity=100);} </style> <div style="position:absolute;width:200px;top:340px;"> <div id="ad_right" style="position:fixed;width:142px;height:327px;z-index:8886;"> <a style="float:right;position:absolute;left:145px;margin-left:-20px;width:17px;height:17px;background:url(/qipai/templets/default/images/close1.png) no-repeat;z-index:8888;" id="closeleftbar" href="javascript:void(0);"></a> <div class="leftLoops leftLoop1" style="z-index:8887" id="banners"> <div class="bd bd3"> <ul class="picLists"> <li> <a href="http://www.789game.com/NewsShow.aspx?XID=439" target="_blank" style="width:100%;float:left;text-align:center;margin-top:50px;"> <img src="/qipai/templets/default/images/001leftQP.jpg" width="142" height="327" alt="" title="" /></a> </a> </li> <li> <a href="http://www.789game.com/NewsShow.aspx?XID=2006" target="_blank" style="width:100%;float:left;text-align:center;margin-top:50px;"> <img src="/qipai/templets/default/images/sh.jpg" width="142" height="327" alt="" title="" /></a> </a> </li> </ul> </div> <div class="hd"> <ul></ul> </div> </div> </div> <script type="text/javascript" src="/qipai/templets/default/js/jquery.SuperSlide.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#closeleftbar").click(function(){ $("#ad_right").css("display","none"); }); }); jQuery("#banners").slide({titCell:".hd ul",mainCell:".bd3 ul",effect:"leftLoop",autoPlay:true,autoPage:true,vis:1,scroll:1,trigger:"click",interTime:3000});</script> <script type="text/javascript"> $(function() { var sWidth = $("#lunbobg").width(); //»ñÈ¡½¹µãͼµÄ¿í¶È£¨ÏÔÊ¾Ãæ»ý£© var len = $("#lunbobg ul li").length; //»ñÈ¡½¹µãͼ¸öÊý var index = 0; var picTimer; //ÒÔÏ´úÂëÌí¼ÓÊý×Ö°´Å¥ºÍ°´Å¥ºóµÄ°ë͸Ã÷Ìõ£¬»¹ÓÐÉÏÒ»Ò³¡¢ÏÂÒ»Ò³Á½¸ö°´Å¥ var btn = "<div class='btnBg'></div><div class='btn'>"; for(var i=0; i < len; i++) { btn += "<span></span>"; } btn += "</div><div class='preNext pre'></div><div class='preNext next'></div>"; $("#lunbobg").append(btn); $("#lunbobg .btnBg").css("opacity",0); //ΪС°´Å¥Ìí¼ÓÊó±ê»¬Èëʼþ£¬ÒÔÏÔʾÏàÓ¦µÄÄÚÈÝ $("#lunbobg .btn span").css("opacity",0.4).mouseover(function() { index = $("#lunbobg .btn span").index(this); showPics(index); }).eq(0).trigger("mouseover"); //ÉÏÒ»Ò³¡¢ÏÂÒ»Ò³°´Å¥Í¸Ã÷¶È´¦Àí $("#lunbobg .preNext").css("opacity",0.08).hover(function() { $(this).stop(true,false).animate({"opacity":"0.5"},300); },function() { $(this).stop(true,false).animate({"opacity":"0.08"},300); }); //ÉÏÒ»Ò³°´Å¥ $("#lunbobg .pre").click(function() { index -= 1; if(index == -1) {index = len - 1;} showPics(index); }); //ÏÂÒ»Ò³°´Å¥ $("#lunbobg .next").click(function() { index += 1; if(index == len) {index = 0;} showPics(index); }); //±¾ÀýΪ×óÓÒ¹ö¶¯£¬¼´ËùÓÐliÔªËØ¶¼ÊÇÔÚͬһÅÅÏò×󸡶¯£¬ËùÒÔÕâÀïÐèÒª¼ÆËã³öÍâΧulÔªËØµÄ¿í¶È $("#lunbobg ul").css("width",sWidth * (len)); //Êó±ê»¬ÉϽ¹µãͼʱֹͣ×Ô¶¯²¥·Å£¬»¬³öʱ¿ªÊ¼×Ô¶¯²¥·Å $("#lunbobg").hover(function() { clearInterval(picTimer); },function() { picTimer = setInterval(function() { showPics(index); index++; if(index == len) {index = 0;} },3000); //´Ë4000´ú±í×Ô¶¯²¥·ÅµÄ¼ä¸ô£¬µ¥Î»£ººÁÃë }).trigger("mouseleave"); //ÏÔʾͼƬº¯Êý£¬¸ù¾Ý½ÓÊÕµÄindexÖµÏÔʾÏàÓ¦µÄÄÚÈÝ function showPics(index) { //ÆÕͨÇл» var nowLeft = -index*sWidth; //¸ù¾ÝindexÖµ¼ÆËãulÔªËØµÄleftÖµ $("#lunbobg ul").stop(true,false).animate({"left":nowLeft},300); //ͨ¹ýanimate()µ÷ÕûulÔªËØ¹ö¶¯µ½¼ÆËã³öµÄposition $("#lunbobg .btn span").stop(true,false).animate({"opacity":"0.2"},300).eq(index).stop(true,false).animate({"opacity":"1"},300); //Ϊµ±Ç°µÄ°´Å¥Çл»µ½Ñ¡ÖеÄЧ¹û } }); </script> </body> </HTML>
bylu/Test
wulu/2015.11.23/qipai/qipaiyouxipingtai/1143.html
HTML
gpl-2.0
13,516
/* Company : Nequeo Pty Ltd, http://www.nequeo.com.au/ * Copyright : Copyright © Nequeo Pty Ltd 2015 http://www.nequeo.com.au/ * * File : SdpSession.h * Purpose : SIP SdpSession class. * */ /* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #pragma once #ifndef _SDPSESSION_H #define _SDPSESSION_H #include "stdafx.h" #include "Call.h" #include "CallInfo.h" #include "SipEventType.h" #include "pjsua2.hpp" using namespace System; using namespace System::Collections; using namespace System::Collections::Generic; namespace Nequeo { namespace Net { namespace PjSip { /// <summary> /// This structure describes SDP session description. /// </summary> public ref class SdpSession sealed { public: /// <summary> /// This structure describes SDP session description. /// </summary> SdpSession(); /// <summary> /// Gets or sets the whole SDP as a string. /// </summary> property String^ WholeSdp { String^ get(); void set(String^ value); } private: String^ _wholeSdp; }; } } } #endif
drazenzadravec/nequeo
Source/Components/Net/Nequeo.Sip/Nequeo.PjSip/Nequeo.PjSip/SdpSession.h
C
gpl-2.0
2,160
import "bootstrap/js/dist/button"; import "bootstrap/js/dist/collapse"; import "bootstrap/js/dist/dropdown"; import "bootstrap/js/dist/modal"; import "bootstrap/js/dist/tab"; import "bootstrap/js/dist/tooltip";
bmybbs/bmybbs
web/src/plugins/bootstrap.js
JavaScript
gpl-2.0
212
/***************************************************************************** Copyright (C) 2013, 2014 Facebook, Inc. All Rights Reserved. Copyright (C) 2014, 2020, MariaDB Corporation. 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 of the License. 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-1335 USA *****************************************************************************/ #ifndef btr0defragment_h #define btr0defragment_h #include "btr0pcur.h" /* Max number of pages to consider at once during defragmentation. */ #define BTR_DEFRAGMENT_MAX_N_PAGES 32 /** stats in btr_defragment */ extern Atomic_counter<ulint> btr_defragment_compression_failures; extern Atomic_counter<ulint> btr_defragment_failures; extern Atomic_counter<ulint> btr_defragment_count; /******************************************************************//** Initialize defragmentation. */ void btr_defragment_init(void); /******************************************************************//** Shutdown defragmentation. */ void btr_defragment_shutdown(); /******************************************************************//** Check whether the given index is in btr_defragment_wq. */ bool btr_defragment_find_index( dict_index_t* index); /*!< Index to find. */ /******************************************************************//** Add an index to btr_defragment_wq. Return a pointer to os_event if this is a synchronized defragmentation. */ os_event_t btr_defragment_add_index( dict_index_t* index, /*!< index to be added */ dberr_t* err); /*!< out: error code */ /******************************************************************//** When table is dropped, this function is called to mark a table as removed in btr_efragment_wq. The difference between this function and the remove_index function is this will not NULL the event. */ void btr_defragment_remove_table( dict_table_t* table); /*!< Index to be removed. */ /******************************************************************//** Mark an index as removed from btr_defragment_wq. */ void btr_defragment_remove_index( dict_index_t* index); /*!< Index to be removed. */ /*********************************************************************//** Check whether we should save defragmentation statistics to persistent storage.*/ UNIV_INTERN void btr_defragment_save_defrag_stats_if_needed( dict_index_t* index); /*!< in: index */ /* Stop defragmentation.*/ void btr_defragment_end(); extern bool btr_defragment_active; #endif
tempesta-tech/mariadb
storage/innobase/include/btr0defragment.h
C
gpl-2.0
2,993
/*************************************************************************** PStartupHandler_SV.cpp Author: Andreas Suter e-mail: andreas.suter@psi.ch ***************************************************************************/ /*************************************************************************** * Copyright (C) 2013 by Andreas Suter * * andreas.suter@psi.ch * * * * 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 <cmath> #include <iostream> #include <fstream> using namespace std; #include "PStartupHandler_SV.h" ClassImpQ(PStartupHandler_SV) //-------------------------------------------------------------------------- // Constructor //-------------------------------------------------------------------------- /** * */ PStartupHandler_SV::PStartupHandler_SV() { fIsValid = true; fStartupFileFound = false; fStartupFilePath = ""; // get default path (for the moment only linux like) char startup_path_name[128]; // check if the startup file is found in the current directory strcpy(startup_path_name, "./spinValve_startup.xml"); if (StartupFileExists(startup_path_name)) { fStartupFileFound = true; fStartupFilePath = TString(startup_path_name); } else { // startup file is not found in the current directory cout << endl << ">> PStartupHandler_SV(): **WARNING** Couldn't find skewedLorentzian_startup.xml in the current directory, will try default one." << endl; strncpy(startup_path_name, "/home/nemu/analysis/musrfit/src/external/libSpinValve/test/spinValve_startup.xml", sizeof(startup_path_name)); if (StartupFileExists(startup_path_name)) { fStartupFileFound = true; fStartupFilePath = TString(startup_path_name); } } // init rest fNoOfFields = 0; fRange = 0.0; } //-------------------------------------------------------------------------- // OnStartDocument //-------------------------------------------------------------------------- /** * <p> */ void PStartupHandler_SV::OnStartDocument() { fKey = eEmpty; } //-------------------------------------------------------------------------- // OnEndDocument //-------------------------------------------------------------------------- /** * <p> */ void PStartupHandler_SV::OnEndDocument() { // nothing to be done for now } //-------------------------------------------------------------------------- // OnStartElement //-------------------------------------------------------------------------- /** * <p> * * \param str * \param attributes */ void PStartupHandler_SV::OnStartElement(const char *str, const TList *attributes) { if (!strcmp(str, "number_of_fields")) { fKey = eNoOfFields; } else if (!strcmp(str, "range")) { fKey = eRange; } } //-------------------------------------------------------------------------- // OnEndElement //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnEndElement(const char *str) { fKey = eEmpty; } //-------------------------------------------------------------------------- // OnCharacters //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnCharacters(const char *str) { TString tstr; switch (fKey) { case eNoOfFields: tstr = str; if (tstr.IsDigit()) { fNoOfFields = tstr.Atoi(); } else { cout << endl << "PStartupHandler_SV::OnCharacters: **ERROR** when finding number_of_fields:"; cout << endl << "\"" << str << "\" is not a number, will ignore it and use the default value."; cout << endl; } break; case eRange: tstr = str; if (tstr.IsFloat()) { fRange = tstr.Atof(); } else { cout << endl << "PStartupHandler_SV::OnCharacters: **ERROR** when finding range:"; cout << endl << "\"" << str << "\" is not a floating point number, will ignore it and use the default value."; cout << endl; } break; default: break; } } //-------------------------------------------------------------------------- // OnComment //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnComment(const char *str) { // nothing to be done for now } //-------------------------------------------------------------------------- // OnWarning //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnWarning(const char *str) { cout << endl << "PStartupHandler_SV **WARNING** " << str; cout << endl; } //-------------------------------------------------------------------------- // OnError //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnError(const char *str) { cout << endl << "PStartupHandler_SV **ERROR** " << str; cout << endl; } //-------------------------------------------------------------------------- // OnFatalError //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnFatalError(const char *str) { cout << endl << "PStartupHandler_SV **FATAL ERROR** " << str; cout << endl; } //-------------------------------------------------------------------------- // OnCdataBlock //-------------------------------------------------------------------------- /** * <p> * * \param str */ void PStartupHandler_SV::OnCdataBlock(const char *str, Int_t len) { // nothing to be done for now } //-------------------------------------------------------------------------- // StartupFileExists //-------------------------------------------------------------------------- /** * <p> * */ bool PStartupHandler_SV::StartupFileExists(char *fln) { bool result = false; ifstream ifile(fln); if (ifile.fail()) { result = false; } else { result = true; ifile.close(); } return result; } // ------------------------------------------------------------------------- // end // -------------------------------------------------------------------------
zaher-salman/musrfit
src/external/libSpinValve/classes/PStartupHandler_SV.cpp
C++
gpl-2.0
7,498
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # This file is part of overview archive. # Copyright © 2015 seamus tuohy, <stuohy@internews.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 included LICENSE file for details. # identification from os import path from os.path import abspath from urllib.parse import urlparse from urllib.request import urlopen import magic from urllib.error import HTTPError # logging import logging log = logging.getLogger("oa.{0}".format(__name__)) def filetype(file_path): if path.exists(file_path) and path.isfile(file_path): try: file_type = magic.from_file(abspath(file_path), mime=True) except IOError: log.error("{0} is not a valid file".format(file_path)) raise IOError("{0} is not a valid file".format(file_path)) else: log.error("{0} is not a valid path to a file".format(file_path)) raise IOError("{0} is not a valid path to a file".format(file_path)) log.debug("filetype for {0} identified as {1}".format(file_path, file_type)) return file_type def is_url(link): try: site = urlopen(link) return True except (ValueError, HTTPError): return False return False def is_archive(link): try: parsed_url = urlparse(link) if parsed_url.netloc == 'web.archive.org': return True except ValueError: return False return False
elationfoundation/overview_archive
overview_archive/utils/identify.py
Python
gpl-2.0
1,836
//-------------------------------------------------------------------------- // Copyright (C) 2014-2016 Cisco and/or its affiliates. All rights reserved. // Copyright (C) 2002-2013 Sourcefire, Inc. // Copyright (C) 1998-2002 Martin Roesch <roesch@sourcefire.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. You may not use, modify or distribute // this program under any other version of the GNU General Public License. // // 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 "treenodes.h" #include "framework/ips_option.h" #include "main/snort_types.h" #include "main/snort_debug.h" #include "utils/util.h" #include "detect.h" /**************************************************************************** * * Function: AddOptFuncToList(int (*func)(), OptTreeNode *) * * Purpose: Links the option detection module to the OTN * * Arguments: (*func)() => function pointer to the detection module * otn => pointer to the current OptTreeNode * * Returns: void function * ***************************************************************************/ OptFpList* AddOptFuncToList(RuleOptEvalFunc ro_eval_func, OptTreeNode* otn) { OptFpList* ofp = (OptFpList*)SnortAlloc(sizeof(OptFpList)); DebugMessage(DEBUG_CONFIGRULES,"Adding new rule to list\n"); /* if there are no nodes on the function list... */ if (otn->opt_func == NULL) { otn->opt_func = ofp; } else { OptFpList* tmp = otn->opt_func; /* walk to the end of the list */ while ( tmp->next ) tmp = tmp->next; tmp->next = ofp; } DebugFormat(DEBUG_CONFIGRULES,"Set OptTestFunc to %p\n", ro_eval_func); ofp->OptTestFunc = ro_eval_func; return ofp; } bool otn_set_agent(OptTreeNode* otn, IpsOption* opt) { if ( otn->agent ) return false; otn->agent = opt; return true; } void otn_trigger_actions(const OptTreeNode* otn, Packet* p) { if ( otn->agent ) otn->agent->action(p); } //------------------------------------------------------------------------- // rule FOO //------------------------------------------------------------------------- void* get_rule_type_data(OptTreeNode* otn, option_type_t type) { OptFpList* fpl = otn->opt_func; while ( fpl ) { if ( fpl->type == type ) return fpl->ips_opt; fpl = fpl->next; } return nullptr; } void* get_rule_type_data(OptTreeNode* otn, const char* name) { OptFpList* fpl = otn->opt_func; while ( fpl ) { if ( fpl->ips_opt ) { if ( !strcmp(fpl->ips_opt->get_name(), name) ) return fpl->ips_opt; } fpl = fpl->next; } return nullptr; } bool otn_has_plugin(OptTreeNode* otn, const char* name) { OptFpList* fpl = otn->opt_func; while ( fpl ) { if ( !fpl->ips_opt ) continue; if ( !strcmp(fpl->ips_opt->get_name(), name) ) return true; fpl = fpl->next; } return false; }
Ghorbani-Roozbahan-Gholipoor-Dashti/Snort
src/detection/treenodes.cc
C++
gpl-2.0
3,672
// +------------------------------------------------------------------+ // | ____ _ _ __ __ _ __ | // | / ___| |__ ___ ___| | __ | \/ | |/ / | // | | | | '_ \ / _ \/ __| |/ / | |\/| | ' / | // | | |___| | | | __/ (__| < | | | | . \ | // | \____|_| |_|\___|\___|_|\_\___|_| |_|_|\_\ | // | | // | Copyright Mathias Kettner 2014 mk@mathias-kettner.de | // +------------------------------------------------------------------+ // // This file is part of Check_MK. // The official homepage is at http://mathias-kettner.de/check_mk. // // check_mk 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 in version 2. check_mk is distributed // in the hope that it will be useful, but WITHOUT ANY WARRANTY; with- // out even the implied warranty of MERCHANTABILITY or FITNESS FOR A // PARTICULAR PURPOSE. See the GNU General Public License for more de- // tails. You should have received a copy of the GNU General Public // License along with GNU Make; see the file COPYING. If not, write // to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, // Boston, MA 02110-1301 USA. #ifndef HostServiceState_h #define HostServiceState_h #include "config.h" // IWYU pragma: keep #include <cstring> #include <ctime> #include <vector> #include "nagios.h" // IWYU pragma: keep class HostServiceState; typedef std::vector<HostServiceState *> HostServices; typedef void *HostServiceKey; class HostServiceState { public: bool _is_host; time_t _time; int _lineno; time_t _from; time_t _until; time_t _duration; double _duration_part; // Do not change order within this block! // These durations will be bzero'd time_t _duration_state_UNMONITORED; double _duration_part_UNMONITORED; time_t _duration_state_OK; double _duration_part_OK; time_t _duration_state_WARNING; double _duration_part_WARNING; time_t _duration_state_CRITICAL; double _duration_part_CRITICAL; time_t _duration_state_UNKNOWN; double _duration_part_UNKNOWN; // State information int _host_down; // used if service int _state; // -1/0/1/2/3 int _in_notification_period; int _in_service_period; int _in_downtime; int _in_host_downtime; int _is_flapping; // Service information HostServices _services; // Absent state handling bool _may_no_longer_exist; bool _has_vanished; time_t _last_known_time; const char *_debug_info; // NOTE: _log_output is the *only* pointer in this class to an object we // own, all other pointers are to foreign objects. This ownership is // unfortunate and complicates things quite a lot, see the corresponding // TODO in TableStateHistory::updateHostServiceState. char *_log_output; const char *_notification_period; // may be "": -> no period known, we // assume "always" const char *_service_period; // may be "": -> no period known, we assume "always" host *_host; service *_service; const char *_host_name; // Fallback if host no longer exists const char *_service_description; // Fallback if service no longer exists HostServiceState() { bzero(this, sizeof(HostServiceState)); } ~HostServiceState(); #ifdef CMC void computePerStateDurations(); #endif }; #endif // HostServiceState_h
ypid-bot/check_mk
livestatus/src/HostServiceState.h
C
gpl-2.0
3,701
// // Copyright (C) 2011 David Eckhoff <eckhoff@cs.fau.de> // // Documentation for these modules is at http://veins.car2x.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 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 // /* * Based on Decider80211.h from Karl Wessel * and modifications by Christopher Saloman */ #ifndef DECIDER80211_H_ #define DECIDER80211_H_ #include <BaseDecider.h> #include <Consts80211p.h> #include <Mac80211pToPhy11pInterface.h> #include <Decider80211pToPhy80211pInterface.h> #ifndef DBG_D11P #define DBG_D11P EV #endif //#define DBG_D11P std::cerr << "[" << simTime().raw() << "] " << myPath << ".Dec " class Decider80211p: public BaseDecider { public: enum Decider80211ControlKinds { NOTHING = 22100, BITERROR, //the phy has recognized a bit error in the packet LAST_DECIDER_80211_CONTROL_KIND, RECWHILESEND }; protected: // threshold value for checking a SNR-map (SNR-threshold) double snrThreshold; /** @brief The center frequency on which the decider listens for signals */ double centerFrequency; double myBusyTime; double myStartTime; std::string myPath; Decider80211pToPhy80211pInterface* phy11p; std::map<AirFrame*,int> signalStates; protected: /** * @brief Checks a mapping against a specific threshold (element-wise). * * @return true , if every entry of the mapping is above threshold * false , otherwise * * */ virtual DeciderResult* checkIfSignalOk(AirFrame* frame); virtual simtime_t processNewSignal(AirFrame* frame); /** * @brief Processes a received AirFrame. * * The SNR-mapping for the Signal is created and checked against the Deciders * SNR-threshold. Depending on that the received AirFrame is either sent up * to the MAC-Layer or dropped. * * @return usually return a value for: 'do not pass it again' */ virtual simtime_t processSignalEnd(AirFrame* frame); /** @brief computes if packet is ok or has errors*/ bool packetOk(double snirMin, int lengthMPDU, double bitrate); /** * @brief Calculates the RSSI value for the passed ChannelSenseRequest. * * This method is called by BaseDecider when it answers a ChannelSenseRequest * and can be overridden by sub classing Deciders. * * Returns the maximum RSSI value inside the ChannelSenseRequest time * interval and the channel the Decider currently listens to. */ virtual double calcChannelSenseRSSI(simtime_t_cref min, simtime_t_cref max); public: /** * @brief Initializes the Decider with a pointer to its PhyLayer and * specific values for threshold and sensitivity */ Decider80211p(DeciderToPhyInterface* phy, double sensitivity, double centerFrequency, int myIndex = -1, bool debug = false): BaseDecider(phy, sensitivity, myIndex, debug), centerFrequency(centerFrequency), myBusyTime(0), myStartTime(simTime().dbl()) { phy11p = dynamic_cast<Decider80211pToPhy80211pInterface*>(phy); assert(phy11p); } void setPath(std::string myPath) { this->myPath = myPath; } bool cca(simtime_t_cref, AirFrame*); int getSignalState(AirFrame* frame); virtual ~Decider80211p(); void changeFrequency(double freq); void setChannelIdleStatus(bool isIdle); }; #endif /* DECIDER80211_H_ */
mnobrega/EMoS
src/modules/phy/Decider80211p.h
C
gpl-2.0
3,966
<?php /** * Layout for the shopping cart * * @package VirtueMart * @subpackage Cart * @author Max Milbers * * @link https://virtuemart.net * @copyright Copyright (c) 2004 - 2016 VirtueMart Team. All rights reserved. * @license http://www.gnu.org/copyleft/gpl.html GNU/GPL * @version $Id: cart.php 2551 2010-09-30 18:52:40Z milbo $ */ // Check to ensure this file is included in Joomla! defined ('_JEXEC') or die('Restricted access'); ?> <fieldset class="vm-fieldset-pricelist"> <table class="cart-summary" cellspacing="0" cellpadding="0" border="0" width="100%"> <tr> <th class="vm-cart-item-name" ><?php echo vmText::_ ('COM_VIRTUEMART_CART_NAME') ?></th> <th class="vm-cart-item-sku" ><?php echo vmText::_ ('COM_VIRTUEMART_CART_SKU') ?></th> <th class="vm-cart-item-basicprice" ><?php echo vmText::_ ('COM_VIRTUEMART_CART_PRICE') ?></th> <th class="vm-cart-item-quantity" ><?php echo vmText::_ ('COM_VIRTUEMART_CART_QUANTITY') ?></th> <?php if (VmConfig::get ('show_tax')) { $tax = vmText::_ ('COM_VIRTUEMART_CART_SUBTOTAL_TAX_AMOUNT'); if(!empty($this->cart->cartData['VatTax'])){ if(count($this->cart->cartData['VatTax']) < 2) { reset($this->cart->cartData['VatTax']); $taxd = current($this->cart->cartData['VatTax']); $tax = shopFunctionsF::getTaxNameWithValue($taxd['calc_name'],$taxd['calc_value']); } } ?> <th class="vm-cart-item-tax" ><?php echo "<span class='priceColor2'>" . $tax . '</span>' ?></th> <?php } ?> <th class="vm-cart-item-discount" ><?php echo "<span class='priceColor2'>" . vmText::_ ('COM_VIRTUEMART_CART_SUBTOTAL_DISCOUNT_AMOUNT') . '</span>' ?></th> <th class="vm-cart-item-total" ><?php echo vmText::_ ('COM_VIRTUEMART_CART_TOTAL') ?></th> </tr> <?php $i = 1; foreach ($this->cart->products as $pkey => $prow) { $prow->prices = array_merge($prow->prices,$this->cart->cartPrices[$pkey]); ?> <tr style="vertical-align: top" class="sectiontableentry<?php echo $i ?>"> <td class="vm-cart-item-name" > <input type="hidden" name="cartpos[]" value="<?php echo $pkey ?>"> <?php if ($prow->virtuemart_media_id) { ?> <span class="cart-images"> <?php if (!empty($prow->images[0])) { echo $prow->images[0]->displayMediaThumb ('', FALSE); } ?> </span> <?php } ?> <?php echo JHtml::link ($prow->url, $prow->product_name); echo $this->customfieldsModel->CustomsFieldCartDisplay ($prow); ?> </td> <td class="vm-cart-item-sku" ><?php echo $prow->product_sku ?></td> <td class="vm-cart-item-basicprice" > <?php if (VmConfig::get ('checkout_show_origprice', 1) && $prow->prices['discountedPriceWithoutTax'] != $prow->prices['priceWithoutTax']) { echo '<span class="line-through">' . $this->currencyDisplay->createPriceDiv ('basePriceVariant', '', $prow->prices, TRUE, FALSE) . '</span><br />'; } if ($prow->prices['discountedPriceWithoutTax']) { echo $this->currencyDisplay->createPriceDiv ('discountedPriceWithoutTax', '', $prow->prices, FALSE, FALSE, 1.0, false, true); } else { echo $this->currencyDisplay->createPriceDiv ('basePriceVariant', '', $prow->prices, FALSE, FALSE, 1.0, false, true); } ?> </td> <td class="vm-cart-item-quantity" ><?php if ($prow->step_order_level) $step=$prow->step_order_level; else $step=1; if($step==0) $step=1; ?> <input type="text" onblur="Virtuemart.checkQuantity(this,<?php echo $step?>,'<?php echo vmText::_ ('COM_VIRTUEMART_WRONG_AMOUNT_ADDED',true)?>');" onclick="Virtuemart.checkQuantity(this,<?php echo $step?>,'<?php echo vmText::_ ('COM_VIRTUEMART_WRONG_AMOUNT_ADDED',true)?>');" onchange="Virtuemart.checkQuantity(this,<?php echo $step?>,'<?php echo vmText::_ ('COM_VIRTUEMART_WRONG_AMOUNT_ADDED',true)?>');" onsubmit="Virtuemart.checkQuantity(this,<?php echo $step?>,'<?php echo vmText::_ ('COM_VIRTUEMART_WRONG_AMOUNT_ADDED',true)?>');" title="<?php echo vmText::_('COM_VIRTUEMART_CART_UPDATE') ?>" class="quantity-input js-recalculate" size="3" maxlength="4" name="quantity[<?php echo $pkey; ?>]" value="<?php echo $prow->quantity ?>" /> <button type="submit" class="vmicon vm2-add_quantity_cart" name="updatecart.<?php echo $pkey ?>" title="<?php echo vmText::_ ('COM_VIRTUEMART_CART_UPDATE') ?>" data-dynamic-update="1" ></button> <button type="submit" class="vmicon vm2-remove_from_cart" name="delete.<?php echo $pkey ?>" title="<?php echo vmText::_ ('COM_VIRTUEMART_CART_DELETE') ?>" ></button> </td> <?php if (VmConfig::get ('show_tax')) { ?> <td class="vm-cart-item-tax" ><?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('taxAmount', '', $prow->prices, FALSE, FALSE, $prow->quantity, false, true) . "</span>" ?></td> <?php } ?> <td class="vm-cart-item-discount" ><?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('discountAmount', '', $prow->prices, FALSE, FALSE, $prow->quantity, false, true) . "</span>" ?></td> <td class="vm-cart-item-total"> <?php if (VmConfig::get ('checkout_show_origprice', 1) && !empty($prow->prices['basePriceWithTax']) && $prow->prices['basePriceWithTax'] != $prow->prices['salesPrice']) { echo '<span class="line-through">' . $this->currencyDisplay->createPriceDiv ('basePriceWithTax', '', $prow->prices, TRUE, FALSE, $prow->quantity) . '</span><br />'; } elseif (VmConfig::get ('checkout_show_origprice', 1) && empty($prow->prices['basePriceWithTax']) && !empty($prow->prices['basePriceVariant']) && $prow->prices['basePriceVariant'] != $prow->prices['salesPrice']) { echo '<span class="line-through">' . $this->currencyDisplay->createPriceDiv ('basePriceVariant', '', $prow->prices, TRUE, FALSE, $prow->quantity) . '</span><br />'; } echo $this->currencyDisplay->createPriceDiv ('salesPrice', '', $prow->prices, FALSE, FALSE, $prow->quantity) ?></td> </tr> <?php $i = ($i==1) ? 2 : 1; } ?> <!--Begin of SubTotal, Tax, Shipment, Coupon Discount and Total listing --> <?php if (VmConfig::get ('show_tax')) { $colspan = 3; } else { $colspan = 2; } ?> <tr> <td colspan="4">&nbsp;</td> <td colspan="<?php echo $colspan ?>"> <hr/> </td> </tr> <tr class="sectiontableentry1"> <td colspan="4" style="text-align: right;"><?php echo vmText::_ ('COM_VIRTUEMART_ORDER_PRINT_PRODUCT_PRICES_TOTAL'); ?></td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"><?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('taxAmount', '', $this->cart->cartPrices, FALSE, false, true) . "</span>" ?></td> <?php } ?> <td style="text-align: right;"><?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('discountAmount', '', $this->cart->cartPrices, FALSE) . "</span>" ?></td> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ('salesPrice', '', $this->cart->cartPrices, FALSE) ?></td> </tr> <?php if (VmConfig::get ('coupons_enable')) { ?> <tr class="sectiontableentry2"> <td colspan="4" style="text-align: left;"> <?php if (!empty($this->layoutName) && $this->layoutName == $this->cart->layout) { echo $this->loadTemplate ('coupon'); } ?> <?php if (!empty($this->cart->cartData['couponCode'])) { ?> <?php echo $this->cart->cartData['couponCode']; echo $this->cart->cartData['couponDescr'] ? (' (' . $this->cart->cartData['couponDescr'] . ')') : ''; ?> </td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ('couponTax', '', $this->cart->cartPrices['couponTax'], FALSE); ?> </td> <?php } ?> <td style="text-align: right;">&nbsp;</td> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ('salesPriceCoupon', '', $this->cart->cartPrices['salesPriceCoupon'], FALSE); ?> </td> <?php } else { ?> &nbsp;</td> <td colspan="<?php echo $colspan ?>" style="text-align: left;">&nbsp;</td> <?php } ?> </tr> <?php } ?> <?php foreach ($this->cart->cartData['DBTaxRulesBill'] as $rule) { ?> <tr class="sectiontableentry<?php echo $i ?>"> <td colspan="4" style="text-align: right;"><?php echo $rule['calc_name'] ?> </td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"></td> <?php } ?> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ($rule['virtuemart_calc_id'] . 'Diff', '', $this->cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], FALSE); ?>&nbsp;</td> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ($rule['virtuemart_calc_id'] . 'Diff', '', $this->cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], FALSE); ?>&nbsp;</td> </tr> <?php if ($i) { $i = 1; } else { $i = 0; } } ?> <?php foreach ($this->cart->cartData['taxRulesBill'] as $rule) { if($rule['calc_value_mathop']=='avalara') continue; ?> <tr class="sectiontableentry<?php echo $i ?>"> <td colspan="4" style="text-align: right;"><?php echo $rule['calc_name'] ?> </td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ($rule['virtuemart_calc_id'] . 'Diff', '', $this->cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], FALSE); ?>&nbsp;</td> <?php } ?> <td style="text-align: right;"><?php ?> </td> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ($rule['virtuemart_calc_id'] . 'Diff', '', $this->cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], FALSE); ?>&nbsp;</td> </tr> <?php if ($i) { $i = 1; } else { $i = 0; } } foreach ($this->cart->cartData['DATaxRulesBill'] as $rule) { ?> <tr class="sectiontableentry<?php echo $i ?>"> <td colspan="4" style="text-align: right;"><?php echo $rule['calc_name'] ?> </td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;">&nbsp;</td> <?php } ?> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ($rule['virtuemart_calc_id'] . 'Diff', '', $this->cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], FALSE); ?> </td> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ($rule['virtuemart_calc_id'] . 'Diff', '', $this->cart->cartPrices[$rule['virtuemart_calc_id'] . 'Diff'], FALSE); ?> </td> </tr> <?php if ($i) { $i = 1; } else { $i = 0; } } if (VmConfig::get('oncheckout_opc',true) or !VmConfig::get('oncheckout_show_steps',false) or (!VmConfig::get('oncheckout_opc',true) and VmConfig::get('oncheckout_show_steps',false) and !empty($this->cart->virtuemart_shipmentmethod_id) ) ) { ?> <tr class="sectiontableentry1" style="vertical-align:top;"> <?php if (!$this->cart->automaticSelectedShipment) { ?> <td colspan="4" style="align:left;vertical-align:top;"> <?php echo '<h3>'.vmText::_ ('COM_VIRTUEMART_CART_SELECTED_SHIPMENT').'</h3>'; echo $this->cart->cartData['shipmentName'].'<br/>'; if (!empty($this->layoutName) and $this->layoutName == $this->cart->layout) { if (VmConfig::get('oncheckout_opc', 0)) { $previouslayout = $this->setLayout('select'); echo $this->loadTemplate('shipment'); $this->setLayout($previouslayout); } else { echo JHtml::_('link', JRoute::_('index.php?option=com_virtuemart&view=cart&task=edit_shipment', $this->useXHTML, $this->useSSL), $this->select_shipment_text, 'class=""'); } } else { echo vmText::_ ('COM_VIRTUEMART_CART_SHIPPING'); } echo '</td>'; } else { ?> <td colspan="4" style="align:left;vertical-align:top;"> <?php echo '<h4>'.vmText::_ ('COM_VIRTUEMART_CART_SELECTED_SHIPMENT').'</h4>'; ?> <?php echo $this->cart->cartData['shipmentName']; echo '<span class="floatright">' . $this->currencyDisplay->createPriceDiv ('shipmentValue', '', $this->cart->cartPrices['shipmentValue'], FALSE) . '</span>'; ?> </td> <?php } ?> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"><?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('shipmentTax', '', $this->cart->cartPrices['shipmentTax'], FALSE) . "</span>"; ?> </td> <?php } ?> <td style="text-align: right;"><?php if($this->cart->cartPrices['salesPriceShipment'] < 0) echo $this->currencyDisplay->createPriceDiv ('salesPriceShipment', '', $this->cart->cartPrices['salesPriceShipment'], FALSE); ?></td> <td style="text-align: right;"><?php echo $this->currencyDisplay->createPriceDiv ('salesPriceShipment', '', $this->cart->cartPrices['salesPriceShipment'], FALSE); ?> </td> </tr> <?php } ?> <?php if ($this->cart->pricesUnformatted['salesPrice']>0.0 and (VmConfig::get('oncheckout_opc',true) or !VmConfig::get('oncheckout_show_steps',false) or ( (!VmConfig::get('oncheckout_opc',true) and VmConfig::get('oncheckout_show_steps',false) ) and !empty($this->cart->virtuemart_paymentmethod_id)) ) ) { ?> <tr class="sectiontableentry1" style="vertical-align:top;"> <?php if (!$this->cart->automaticSelectedPayment) { ?> <td colspan="4" style="align:left;vertical-align:top;"> <?php echo '<h3>'.vmText::_ ('COM_VIRTUEMART_CART_SELECTED_PAYMENT').'</h3>'; echo $this->cart->cartData['paymentName'].'<br/>'; if (!empty($this->layoutName) && $this->layoutName == $this->cart->layout) { if (VmConfig::get('oncheckout_opc', 0)) { $previouslayout = $this->setLayout('select'); echo $this->loadTemplate('payment'); $this->setLayout($previouslayout); } else { echo JHtml::_('link', JRoute::_('index.php?option=com_virtuemart&view=cart&task=editpayment', $this->useXHTML, $this->useSSL), $this->select_payment_text, 'class=""'); } } else { echo vmText::_ ('COM_VIRTUEMART_CART_PAYMENT'); } ?></td> <?php } else { ?> <td colspan="4" style="align:left;vertical-align:top;" > <?php echo '<h4>'.vmText::_ ('COM_VIRTUEMART_CART_SELECTED_PAYMENT').'</h4>'; ?> <?php echo $this->cart->cartData['paymentName']; ?> </td> <?php } ?> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"><?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('paymentTax', '', $this->cart->cartPrices['paymentTax'], FALSE) . "</span>"; ?> </td> <?php } ?> <td style="text-align: right;" ><?php if($this->cart->cartPrices['salesPricePayment'] < 0) echo $this->currencyDisplay->createPriceDiv ('salesPricePayment', '', $this->cart->cartPrices['salesPricePayment'], FALSE); ?></td> <td style="text-align: right;" ><?php echo $this->currencyDisplay->createPriceDiv ('salesPricePayment', '', $this->cart->cartPrices['salesPricePayment'], FALSE); ?> </td> </tr> <?php } ?> <tr> <td colspan="4">&nbsp;</td> <td colspan="<?php echo $colspan ?>"> <hr/> </td> </tr> <tr class="sectiontableentry2"> <td colspan="4" style="text-align: right;"><?php echo vmText::_ ('COM_VIRTUEMART_CART_TOTAL') ?>:</td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;"> <?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('billTaxAmount', '', $this->cart->cartPrices['billTaxAmount'], FALSE) . "</span>" ?> </td> <?php } ?> <td style="text-align: right;"> <?php echo "<span class='priceColor2'>" . $this->currencyDisplay->createPriceDiv ('billDiscountAmount', '', $this->cart->cartPrices['billDiscountAmount'], FALSE) . "</span>" ?> </td> <td style="text-align: right;"><strong><?php echo $this->currencyDisplay->createPriceDiv ('billTotal', '', $this->cart->cartPrices['billTotal'], FALSE); ?></strong></td> </tr> <?php if ($this->totalInPaymentCurrency) { ?> <tr class="sectiontableentry2"> <td colspan="4" style="text-align: right;"><?php echo vmText::_ ('COM_VIRTUEMART_CART_TOTAL_PAYMENT') ?>:</td> <?php if (VmConfig::get ('show_tax')) { ?> <td style="text-align: right;">&nbsp;</td> <?php } ?> <td style="text-align: right;">&nbsp;</td> <td style="text-align: right;"><strong><?php echo $this->totalInPaymentCurrency; ?></strong></td> </tr> <?php } //Show VAT tax separated if(!empty($this->cart->cartData)){ if(!empty($this->cart->cartData['VatTax'])){ $c = count($this->cart->cartData['VatTax']); if (!VmConfig::get ('show_tax') or $c>1) { if($c>0){ ?> <tr class="sectiontableentry2"> <td colspan="3">&nbsp;</td> <td colspan="2" style="text-align: left;border-bottom: 1px solid #333;"><?php echo vmText::_ ('COM_VIRTUEMART_TOTAL_INCL_TAX') ?></td> <?php if (VmConfig::get ('show_tax')) { ?> <td>&nbsp;</td> <?php } ?> <td>&nbsp;</td> </tr> <?php } foreach( $this->cart->cartData['VatTax'] as $vatTax ) { if(!empty($vatTax['result'])) { ?> <tr class="sectiontableentry<?php echo $i ?>"> <td colspan="3">&nbsp;</td> <td style="text-align: right;"><?php echo shopFunctionsF::getTaxNameWithValue($vatTax['calc_name'],$vatTax['calc_value']) ?></td> <td style="text-align: right;"><span class="priceColor2"><?php echo $this->currencyDisplay->createPriceDiv( 'taxAmount', '', $vatTax['result'], FALSE, false, 1.0,false,true ) ?></span></td> <?php if (VmConfig::get ('show_tax')) { ?> <td >&nbsp;</td> <?php } ?> <td>&nbsp;</td> </tr> <?php } } } } } ?> </table> </fieldset>
hoangyen201201/TrienLamOnline
components/com_virtuemart/views/cart/tmpl/default_pricelist.php
PHP
gpl-2.0
16,973
/* * linux/include/asm-arm/arch-omap/cpu.h * * OMAP cpu type detection * * Copyright (C) 2004 Nokia Corporation * * Written by Tony Lindgren <tony.lindgren@nokia.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; version 2 of the License. * * * 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 * */ #ifndef __ASM_ARCH_OMAP_CPU_H #define __ASM_ARCH_OMAP_CPU_H extern unsigned int system_rev; extern unsigned int scalability_status; #define omap2_cpu_rev() ((system_rev >> 12) & 0x0f) /* * Test if multicore OMAP support is needed */ #undef MULTI_OMAP1 #undef MULTI_OMAP2 #undef MULTI_OMAP3 #undef OMAP_NAME #ifdef CONFIG_ARCH_OMAP730 # ifdef OMAP_NAME # undef MULTI_OMAP1 # define MULTI_OMAP1 # else # define OMAP_NAME omap730 # endif #endif #ifdef CONFIG_ARCH_OMAP15XX # ifdef OMAP_NAME # undef MULTI_OMAP1 # define MULTI_OMAP1 # else # define OMAP_NAME omap1510 # endif #endif #ifdef CONFIG_ARCH_OMAP16XX # ifdef OMAP_NAME # undef MULTI_OMAP1 # define MULTI_OMAP1 # else # define OMAP_NAME omap16xx # endif #endif #ifdef CONFIG_ARCH_OMAP24XX # if (defined(OMAP_NAME) || defined(MULTI_OMAP1)) # error "OMAP1 and OMAP2 can't be selected at the same time" # else # undef MULTI_OMAP2 # define OMAP_NAME omap24xx # endif #endif #ifdef CONFIG_ARCH_OMAP34XX # if (defined(OMAP_NAME) || defined(MULTI_OMAP1) || defined(MULTI_OMAP2)) # error "OMAP1 / OMAP2 / OMAP3 can't be selected at the same time" # else # undef MULTI_OMAP3 # define OMAP_NAME omap34xx # endif #endif /* * Macros to group OMAP into cpu classes. * These can be used in most places. * cpu_is_omap7xx(): True for OMAP730 * cpu_is_omap15xx(): True for OMAP1510, OMAP5910 and OMAP310 * cpu_is_omap16xx(): True for OMAP1610, OMAP5912 and OMAP1710 * cpu_is_omap24xx(): True for OMAP2420, OMAP2422, OMAP2423, OMAP2430 * cpu_is_omap242x(): True for OMAP2420, OMAP2422, OMAP2423 * cpu_is_omap243x(): True for OMAP2430 * cpu_is_omap343x(): True for OMAP3430 */ #define GET_OMAP_CLASS ((system_rev >> 24) & 0xff) #define IS_OMAP_CLASS(class, id) \ static inline int is_omap ##class (void) \ { \ return (GET_OMAP_CLASS == (id)) ? 1 : 0; \ } #define GET_OMAP_SUBCLASS ((system_rev >> 20) & 0x0fff) #define IS_OMAP_SUBCLASS(subclass, id) \ static inline int is_omap ##subclass (void) \ { \ return (GET_OMAP_SUBCLASS == (id)) ? 1 : 0; \ } IS_OMAP_CLASS(7xx, 0x07) IS_OMAP_CLASS(15xx, 0x15) IS_OMAP_CLASS(16xx, 0x16) IS_OMAP_CLASS(24xx, 0x24) IS_OMAP_CLASS(34xx, 0x34) IS_OMAP_SUBCLASS(242x, 0x242) IS_OMAP_SUBCLASS(243x, 0x243) IS_OMAP_SUBCLASS(343x, 0x343) #define cpu_is_omap7xx() 0 #define cpu_is_omap15xx() 0 #define cpu_is_omap16xx() 0 #define cpu_is_omap24xx() 0 #define cpu_is_omap242x() 0 #define cpu_is_omap243x() 0 #define cpu_is_omap343x() 0 #if defined(MULTI_OMAP1) # if defined(CONFIG_ARCH_OMAP730) # undef cpu_is_omap7xx # define cpu_is_omap7xx() is_omap7xx() # endif # if defined(CONFIG_ARCH_OMAP15XX) # undef cpu_is_omap15xx # define cpu_is_omap15xx() is_omap15xx() # endif # if defined(CONFIG_ARCH_OMAP16XX) # undef cpu_is_omap16xx # define cpu_is_omap16xx() is_omap16xx() # endif #else # if defined(CONFIG_ARCH_OMAP730) # undef cpu_is_omap7xx # define cpu_is_omap7xx() 1 # endif # if defined(CONFIG_ARCH_OMAP15XX) # undef cpu_is_omap15xx # define cpu_is_omap15xx() 1 # endif # if defined(CONFIG_ARCH_OMAP16XX) # undef cpu_is_omap16xx # define cpu_is_omap16xx() 1 # endif # if defined(CONFIG_ARCH_OMAP24XX) # undef cpu_is_omap24xx # undef cpu_is_omap242x # undef cpu_is_omap243x # define cpu_is_omap24xx() 1 # define cpu_is_omap242x() is_omap242x() # define cpu_is_omap243x() is_omap243x() # endif # if defined(CONFIG_ARCH_OMAP34XX) # undef cpu_is_omap34xx # define cpu_is_omap34xx() 1 # else # define cpu_is_omap34xx() 0 # endif #endif /* * Macros to detect individual cpu types. * These are only rarely needed. * cpu_is_omap330(): True for OMAP330 * cpu_is_omap730(): True for OMAP730 * cpu_is_omap1510(): True for OMAP1510 * cpu_is_omap1610(): True for OMAP1610 * cpu_is_omap1611(): True for OMAP1611 * cpu_is_omap5912(): True for OMAP5912 * cpu_is_omap1621(): True for OMAP1621 * cpu_is_omap1710(): True for OMAP1710 * cpu_is_omap2420(): True for OMAP2420 * cpu_is_omap2422(): True for OMAP2422 * cpu_is_omap2423(): True for OMAP2423 * cpu_is_omap2430(): True for OMAP2430 * cpu_is_omap3430(): True for OMAP3430 */ #define GET_OMAP_TYPE ((system_rev >> 16) & 0xffff) #define IS_OMAP_TYPE(type, id) \ static inline int is_omap ##type (void) \ { \ return (GET_OMAP_TYPE == (id)) ? 1 : 0; \ } IS_OMAP_TYPE(310, 0x0310) IS_OMAP_TYPE(730, 0x0730) IS_OMAP_TYPE(1510, 0x1510) IS_OMAP_TYPE(1610, 0x1610) IS_OMAP_TYPE(1611, 0x1611) IS_OMAP_TYPE(5912, 0x1611) IS_OMAP_TYPE(1621, 0x1621) IS_OMAP_TYPE(1710, 0x1710) IS_OMAP_TYPE(2420, 0x2420) IS_OMAP_TYPE(2422, 0x2422) IS_OMAP_TYPE(2423, 0x2423) IS_OMAP_TYPE(2430, 0x2430) IS_OMAP_TYPE(3430, 0x3430) #define cpu_is_omap310() 0 #define cpu_is_omap730() 0 #define cpu_is_omap1510() 0 #define cpu_is_omap1610() 0 #define cpu_is_omap5912() 0 #define cpu_is_omap1611() 0 #define cpu_is_omap1621() 0 #define cpu_is_omap1710() 0 #define cpu_is_omap2420() 0 #define cpu_is_omap2422() 0 #define cpu_is_omap2423() 0 #define cpu_is_omap2430() 0 #define cpu_is_omap3430() 0 #define cpu_is_omap3410() 0 #if defined(MULTI_OMAP1) # if defined(CONFIG_ARCH_OMAP730) # undef cpu_is_omap730 # define cpu_is_omap730() is_omap730() # endif #else # if defined(CONFIG_ARCH_OMAP730) # undef cpu_is_omap730 # define cpu_is_omap730() 1 # endif #endif /* * Whether we have MULTI_OMAP1 or not, we still need to distinguish * between 330 vs. 1510 and 1611B/5912 vs. 1710. */ #if defined(CONFIG_ARCH_OMAP15XX) # undef cpu_is_omap310 # undef cpu_is_omap1510 # define cpu_is_omap310() is_omap310() # define cpu_is_omap1510() is_omap1510() #endif #if defined(CONFIG_ARCH_OMAP16XX) # undef cpu_is_omap1610 # undef cpu_is_omap1611 # undef cpu_is_omap5912 # undef cpu_is_omap1621 # undef cpu_is_omap1710 # define cpu_is_omap1610() is_omap1610() # define cpu_is_omap1611() is_omap1611() # define cpu_is_omap5912() is_omap5912() # define cpu_is_omap1621() is_omap1621() # define cpu_is_omap1710() is_omap1710() #endif #if defined(CONFIG_ARCH_OMAP24XX) # undef cpu_is_omap2420 # undef cpu_is_omap2422 # undef cpu_is_omap2423 # undef cpu_is_omap2430 # define cpu_is_omap2420() is_omap2420() # define cpu_is_omap2422() is_omap2422() # define cpu_is_omap2423() is_omap2423() # define cpu_is_omap2430() is_omap2430() #endif #if defined(CONFIG_ARCH_OMAP34XX) # undef cpu_is_omap3430 #define cpu_is_omap3430() is_omap3430() #endif /* Macros to detect if we have OMAP1 or OMAP2 */ #define cpu_class_is_omap1() (cpu_is_omap730() || cpu_is_omap15xx() || \ cpu_is_omap16xx()) #define cpu_class_is_omap2() (cpu_is_omap24xx() || cpu_is_omap34xx()) #if defined(CONFIG_ARCH_OMAP2) || defined(CONFIG_ARCH_OMAP3) /* * Macros to detect silicon revision of OMAP2/3 processors. * is_sil_rev_greater_than: true if passed cpu type & its rev is greater. * is_sil_rev_lesser_than: true if passed cpu type & its rev is lesser. * is_sil_rev_equal_to: true if passed cpu type & its rev is equal. * get_sil_rev: return the silicon rev value. */ #define is_sil_rev_greater_than(rev) \ (((((system_rev & 0xffff0000) >> 16) == \ ((rev & 0xffff0000) >> 16))) && \ (((system_rev & 0xf000) >> 12) > ((rev & 0xf000) >> 12))) #define is_sil_rev_less_than(rev) \ (((((system_rev & 0xffff0000) >> 16) == \ ((rev & 0xffff0000) >> 16))) && \ (((system_rev & 0xf000) >> 12) < ((rev & 0xf000) >> 12))) #define is_sil_rev_equal_to(rev) \ (((((system_rev & 0xffff0000) >> 16) == \ ((rev & 0xffff0000) >> 16))) && \ (((system_rev & 0xf000) >> 12) == ((rev & 0xf000) >> 12))) #define get_sil_rev() \ ((system_rev & 0xf000) >> 12) /* Various silicon macros defined here */ #define OMAP242X_CLASS 0x24200000 #define OMAP2420_REV_ES1_0 0x24200000 #define OMAP2420_REV_ES2_0 0x24201000 #define OMAP243X_CLASS 0x24300000 #define OMAP2430_REV_ES1_0 0x24300000 #define OMAP2430_REV_ES2_0 0x24301000 #define OMAP2430_REV_ES2_1 0x24302000 #define OMAP343X_CLASS 0x34300000 #define OMAP3430_REV_ES1_0 0x34300000 #define OMAP3430_REV_ES2_0 0x34301000 #define OMAP3430_REV_ES2_1 0x34302000 #define OMAP3430_REV_ES3_0 0x34303000 #define OMAP3430_REV_ES3_1 0x34304000 #define OMAP3410 0x34100000 #define OMAP3420 0x34200000 /* since 3410 is a scalable mode of 3430 itself, it doesnt have a separate * entry in system_rev. For scalable silicon we use scalability_status */ #define get_scalable_cpu (scalability_status & 0xFFFF0000) #undef cpu_is_omap3410 #define cpu_is_omap3410() (get_scalable_cpu == OMAP3410) #define cpu_is_omap3420() (get_scalable_cpu == OMAP3420) /* * Macro to detect device type i.e. EMU/HS/TST/GP/BAD */ #define DEVICE_TYPE_TEST 0 #define DEVICE_TYPE_EMU 1 #define DEVICE_TYPE_SEC 2 #define DEVICE_TYPE_GP 3 #define DEVICE_TYPE_BAD 4 #define is_device_type_test() \ (((system_rev & 0x700) >> 8) == DEVICE_TYPE_TEST) #define is_device_type_emu() \ (((system_rev & 0x700) >> 8) == DEVICE_TYPE_EMU) #define is_device_type_sec() \ (((system_rev & 0x700) >> 8) == DEVICE_TYPE_SEC) #define is_device_type_gp() \ (((system_rev & 0x700) >> 8) == DEVICE_TYPE_GP) #define is_device_type_bad() \ (((system_rev & 0x700) >> 8) == DEVICE_TYPE_BAD) #define get_device_type() \ ((system_rev & 0x700) >> 8) #endif #endif
mozyg/kernel
include/asm-arm/arch-omap/cpu.h
C
gpl-2.0
10,058
<?php namespace Drupal\Tests\paragraphs\Functional\Experimental; use Drupal\Core\Entity\Entity\EntityFormDisplay; use Drupal\Tests\paragraphs\Functional\Classic\ParagraphsTestBase; use Drupal\Tests\paragraphs\FunctionalJavascript\ParagraphsTestBaseTrait; /** * Base class for tests. */ abstract class ParagraphsExperimentalTestBase extends ParagraphsTestBase { use ParagraphsTestBaseTrait; /** * Sets the Paragraphs widget add mode. * * @param string $content_type * Content type name where to set the widget mode. * @param string $paragraphs_field * Paragraphs field to change the mode. * @param string $mode * Mode to be set. ('dropdown', 'select' or 'button'). */ protected function setAddMode($content_type, $paragraphs_field, $mode) { $form_display = EntityFormDisplay::load('node.' . $content_type . '.default') ->setComponent($paragraphs_field, [ 'type' => 'paragraphs', 'settings' => ['add_mode' => $mode] ]); $form_display->save(); } /** * Removes the default paragraph type. * * @param $content_type * Content type name that contains the paragraphs field. */ protected function removeDefaultParagraphType($content_type) { $this->drupalGet('node/add/' . $content_type); $this->drupalPostForm(NULL, [], 'Remove'); $this->assertNoText('No paragraphs added yet.'); } }
marteenzh/d1
modules/paragraphs/tests/src/Functional/Experimental/ParagraphsExperimentalTestBase.php
PHP
gpl-2.0
1,396
/* * Seven Kingdoms: Ancient Adversaries * * Copyright 1997,1998 Enlight Software Ltd. * * 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/>. * */ //Filename : OTOWNAI.CPP //Description : Object Town AI #include <OWORLD.h> #include <OUNIT.h> #include <OCONFIG.h> #include <OSITE.h> #include <ONEWS.h> #include <OTECHRES.h> #include <OWALLRES.h> #include <ORACERES.h> #include <OGODRES.h> #include <OSPY.h> #include <OTOWN.h> #include <ONATION.h> #include <OINFO.h> #include <OFIRMALL.h> #include <OLOG.h> //--------- Begin of function Town::process_ai ----------// // void Town::process_ai() { Nation* ownNation = nation_array[nation_recno]; #if defined(DEBUG) && defined(ENABLE_LOG) String logStr; logStr = "begin Town::process_ai, town_recno="; logStr += town_recno; logStr += " nation_recno="; logStr += nation_recno; LOG_MSG(logStr); #endif //---- think about cancelling the base town status ----// if( info.game_date%30==town_recno%30 ) { LOG_MSG(" update_base_town_status"); update_base_town_status(); LOG_MSG(m.get_random_seed()); } //------ think about granting villagers ---// if( info.game_date%30==town_recno%30 ) { LOG_MSG(" think_reward"); think_reward(); LOG_MSG(m.get_random_seed()); } //----- if this town should migrate now -----// if( should_ai_migrate() ) { if( info.game_date%30==town_recno%30 ) { LOG_MSG(" think_ai_migrate"); think_ai_migrate(); LOG_MSG(m.get_random_seed()); } return; // don't do anything else if the town is about to migrate } //------ think about building camps first -------// if( info.game_date%30==town_recno%30 && !no_neighbor_space && // if there is no space in the neighbor area for building a new firm. population > 1 ) { LOG_MSG(" think_build_camp"); if( think_build_camp() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); } //----- the following are base town only functions ----// if( !is_base_town ) return; //------ think about collecting tax ---// if( info.game_date%30==(town_recno+15)%30 ) { LOG_MSG("think_collect_tax"); think_collect_tax(); LOG_MSG(m.get_random_seed()); } //---- think about scouting in an unexplored map ----// if( info.game_date%30==(town_recno+20)%30 ) { think_scout(); } //---- think about splitting the town ---// if( info.game_date%30==town_recno%30 ) { LOG_MSG("think_split_town"); think_split_town(); LOG_MSG(m.get_random_seed() ); LOG_MSG("think_move_between_town"); think_move_between_town(); LOG_MSG(m.get_random_seed() ); } //---- think about attacking firms/units nearby ---// if( info.game_date%30==town_recno%30 ) { LOG_MSG(" think_attack_nearby_enemy"); if( think_attack_nearby_enemy() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); LOG_MSG(" think_attack_linked_enemy"); if( think_attack_linked_enemy() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); } //---- think about capturing linked enemy firms ----// if( info.game_date%60==town_recno%60 ) { LOG_MSG(" think_capture_linked_firm"); think_capture_linked_firm(); LOG_MSG(m.get_random_seed()); } //---- think about capturing enemy towns ----// if( info.game_date%120==town_recno%120 ) { LOG_MSG(" think_capture_enemy_town"); think_capture_enemy_town(); LOG_MSG(m.get_random_seed()); } //---- think about using spies on enemies ----// if( info.game_date%60==(town_recno+10)%60 ) { LOG_MSG(" think_spying_town"); if( think_spying_town() ) { LOG_MSG(m.get_random_seed()); return; } } //---- think about anti-spies activities ----// if( info.game_date%60==(town_recno+20)%60 ) { LOG_MSG(" think_counter_spy"); if( think_counter_spy() ) { LOG_MSG(m.get_random_seed()); return; } } //--- think about setting up firms next to this town ---// if( info.game_date%30==town_recno%30 && !no_neighbor_space && // if there is no space in the neighbor area for building a new firm. population >= 5 ) { LOG_MSG(" think_build_market"); if( think_build_market() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); //--- the following functions will only be called when the nation has at least a mine ---// if( site_array.untapped_raw_count > 0 && ownNation->ai_mine_count==0 && // don't build other structures if there are untapped raw sites and our nation still doesn't have any ownNation->true_profit_365days() < 0 ) { return; } //---- only build the following if we have enough food ----// if( ownNation->ai_has_enough_food() ) { LOG_MSG(" think_build_research"); if( think_build_research() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); LOG_MSG(" think_build_war_factory"); if( think_build_war_factory() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); LOG_MSG(" think_build_base"); if( think_build_base() ) { LOG_MSG(m.get_random_seed()); return; } LOG_MSG(m.get_random_seed()); } //-------- think build inn ---------// LOG_MSG(" think_build_inn"); think_build_inn(); LOG_MSG(m.get_random_seed()); } } //--------- End of function Town::process_ai ----------// //--------- Begin of function Town::think_defense ----------// // void Town::think_defense() { int enemyUnitRecno = detect_enemy(3); // only when 3 units are detected, we consider them as enemy if( !enemyUnitRecno ) return; Unit* enemyUnit = unit_array[enemyUnitRecno]; int enemyXLoc = enemyUnit->cur_x_loc(); int enemyYLoc = enemyUnit->cur_y_loc(); //----- get our unit that is closet to it to attack it -------// int i, closestUnitRecno=0, curDis, minDis=0x7FFF; Unit* unitPtr; for( i=unit_array.size() ; i>0 ; i-- ) { if( unit_array.is_deleted(i) ) continue; unitPtr = unit_array[i]; if( unitPtr->nation_recno == nation_recno ) { curDis = MAX( abs(unitPtr->cur_x_loc()-enemyXLoc), abs(unitPtr->cur_y_loc()-enemyYLoc) ); if( curDis < minDis ) { minDis = curDis; closestUnitRecno = i; } } } //-------- attack the enemy now ----------// if( closestUnitRecno ) unit_array[closestUnitRecno]->attack_unit(enemyUnit->sprite_recno); } //--------- End of function Town::think_defense ----------// //--------- Begin of function Town::detect_enemy ----------// // // Detect if there is any enemy in the town. (within the city // wall area.) // // <int> alertNum - only alert when this number of units are detected. // int Town::detect_enemy(int alertNum) { //------ check if any enemies have entered in the city -----// int xLoc1 = MAX(0, loc_x1-WALL_SPACE_LOC); int yLoc1 = MAX(0, loc_y1-WALL_SPACE_LOC); int xLoc2 = MIN(MAX_WORLD_X_LOC-1, loc_x2+WALL_SPACE_LOC); int yLoc2 = MIN(MAX_WORLD_Y_LOC-1, loc_y2+WALL_SPACE_LOC); int xLoc, yLoc, unitRecno; int enemyCount=0; Location* locPtr; Unit* unitPtr; for( yLoc=yLoc1 ; yLoc<=yLoc2 ; yLoc++ ) { locPtr = world.get_loc(xLoc1, yLoc); for( xLoc=xLoc1 ; xLoc<=xLoc2 ; xLoc++, locPtr++ ) { if( locPtr->has_unit(UNIT_LAND) ) { unitRecno = locPtr->unit_recno(UNIT_LAND); //------- if any enemy detected -------// unitPtr = unit_array[unitRecno]; if( unitPtr->nation_recno != nation_recno && unitPtr->nation_recno > 0 ) { if( ++enemyCount >= alertNum ) return unitRecno; } } } } return 0; } //--------- End of function Town::detect_enemy ----------// //------- Begin of function Town::think_build_firm --------// // // Think about building a specific type of firm next to this town. // // <int> firmId - id. of the firm to be built. // <int> maxFirm - MAX. no. of firm of this type to be built next to this town. // int Town::think_build_firm(int firmId, int maxFirm) { Nation* nationPtr = nation_array[nation_recno]; //--- check whether the AI can build a new firm next this firm ---// if( !nationPtr->can_ai_build(firmId) ) return 0; //-- only build one market place next to this town, check if there is any existing one --// Firm* firmPtr; int firmCount=0; for(int i=0; i<linked_firm_count; i++) { err_when(!linked_firm_array[i] || firm_array.is_deleted(linked_firm_array[i])); firmPtr = firm_array[linked_firm_array[i]]; //---- if there is one firm of this type near the town already ----// if( firmPtr->firm_id == firmId && firmPtr->nation_recno == nation_recno ) { if( ++firmCount >= maxFirm ) return 0; } } //------ queue building a new firm -------// return ai_build_neighbor_firm(firmId); } //-------- End of function Town::think_build_firm ---------// //------- Begin of function Town::think_collect_tax --------// // // Think about collecting tax. // void Town::think_collect_tax() { if( !has_linked_own_camp ) return; if( should_ai_migrate() ) // if the town should migrate, do collect tax, otherwise the loyalty will be too low for mobilizing the peasants. return; if( accumulated_collect_tax_penalty > 0 ) return; //--- collect tax if the loyalty of all the races >= minLoyalty (55-85) ---// int yearProfit = (int) nation_array[nation_recno]->profit_365days(); int minLoyalty = 55 + 30 * nation_array[nation_recno]->pref_loyalty_concern / 100; if( yearProfit < 0 ) // we are losing money now minLoyalty -= (-yearProfit) / 100; // more aggressive in collecting tax if we are losing a lot of money minLoyalty = MAX( 55, minLoyalty ); //---------------------------------------------// int achievableLoyalty = average_target_loyalty()-10; // -10 because it's an average, -10 will be safer if( achievableLoyalty > minLoyalty ) // if the achievable loyalty is higher, then use it minLoyalty = achievableLoyalty; if( average_loyalty() < minLoyalty ) return; //---------- collect tax now ----------// collect_tax( COMMAND_AI ); } //-------- End of function Town::think_collect_tax ---------// //------- Begin of function Town::think_reward --------// // // Think about granting the villagers. // void Town::think_reward() { if( !has_linked_own_camp ) return; if( accumulated_reward_penalty > 0 ) return; //---- if accumulated_reward_penalty>0, don't grant unless the villagers are near the rebel level ----// Nation* ownNation = nation_array[nation_recno]; int averageLoyalty = average_loyalty(); if( averageLoyalty < REBEL_LOYALTY + 5 + ownNation->pref_loyalty_concern/10 ) // 35 to 45 { int importanceRating; if( averageLoyalty < REBEL_LOYALTY+5 ) importanceRating = 40+population; else importanceRating = population; if( ownNation->ai_should_spend(importanceRating) ) reward( COMMAND_AI ); } } //-------- End of function Town::think_reward ---------// //------- Begin of function Town::think_ai_migrate --------// // // Think about migrating to another town. // int Town::think_ai_migrate() { if( info.game_date < setup_date+90 ) // don't move if this town has just been set up for less than 90 days. It may be a town set up by think_split_town() return 0; Nation* nationPtr = nation_array[nation_recno]; //-- the higher the loyalty, the higher the chance all the unit can be migrated --// int averageLoyalty = average_loyalty(); int minMigrateLoyalty = 35 + nationPtr->pref_loyalty_concern/10; // 35 to 45 if( averageLoyalty < minMigrateLoyalty ) { //-- if the total population is low (we need people) and the cash is high (we have money), then grant to increase loyalty for migration --// if( accumulated_reward_penalty==0 && average_target_loyalty() < minMigrateLoyalty+5 ) // if the average target loyalty is also lower than { if( nationPtr->ai_should_spend( 20+nationPtr->pref_territorial_cohesiveness/2 ) ) // 20 to 70 reward( COMMAND_AI ); } if( average_loyalty() < minMigrateLoyalty ) return 0; } if( !should_ai_migrate() ) return 0; //------ think about which town to migrate to ------// int bestTownRecno = think_ai_migrate_to_town(); if( !bestTownRecno ) return 0; //--- check if there are already units currently migrating to the destination town ---// Town* destTownPtr = town_array[bestTownRecno]; if( nationPtr->is_action_exist( destTownPtr->loc_x1, destTownPtr->loc_y1, loc_x1, loc_y1, ACTION_AI_SETTLE_TO_OTHER_TOWN, 0, 0, 1 ) ) // last 1-check duplication on the destination town only { return 0; } //--------- queue for migration now ---------// int migrateCount = (average_loyalty() - MIN_RECRUIT_LOYALTY) / 5; migrateCount = MIN( migrateCount, jobless_population ); if( migrateCount <= 0 ) return 0; nationPtr->add_action( destTownPtr->loc_x1, destTownPtr->loc_y1, loc_x1, loc_y1, ACTION_AI_SETTLE_TO_OTHER_TOWN, 0, migrateCount); return 1; } //-------- End of function Town::think_ai_migrate ---------// //------- Begin of function Town::think_ai_migrate_to_town --------// // // Think about the town to migrate to. // int Town::think_ai_migrate_to_town() { //------ think about which town to migrate to ------// Nation* nationPtr = nation_array[nation_recno]; int curRating, bestRating=0, bestTownRecno=0; short *aiTownPtr = nationPtr->ai_town_array; int majorityRace = majority_race(); Town *townPtr; for(int i=0; i<nationPtr->ai_town_count; i++, aiTownPtr++) { if( town_recno == *aiTownPtr ) continue; townPtr = town_array[*aiTownPtr]; err_when( townPtr->nation_recno != nation_recno ); if( !townPtr->is_base_town ) // only migrate to base towns continue; if( townPtr->region_id != region_id ) continue; if( population > MAX_TOWN_POPULATION-townPtr->population ) // if the town does not have enough space for the migration continue; //--------- compare the ratings ---------// curRating = 1000 * townPtr->race_pop_array[majorityRace-1] / townPtr->population; // *1000 so that this will have a much bigger weight than the distance rating curRating += world.distance_rating( center_x, center_y, townPtr->center_x, townPtr->center_y ); if( curRating > bestRating ) { //--- if there is a considerable population of this race, then must migrate to a town with the same race ---// if( race_pop_array[majorityRace-1] >= 6 ) { if( townPtr->majority_race() != majorityRace ) // must be commented out otherwise low population town will never be optimized continue; } bestRating = curRating; bestTownRecno = townPtr->town_recno; } } return bestTownRecno; } //-------- End of function Town::think_ai_migrate_to_town ---------// //------- Begin of function Town::should_ai_migrate --------// // // Whether this town should think about migration or not. // int Town::should_ai_migrate() { //--- if this town is the base town of the nation's territory, don't migrate ---// Nation* nationPtr = nation_array[nation_recno]; if( is_base_town || nationPtr->ai_base_town_count==0 ) // don't migrate if this is a base town or there is no base town in this nation return 0; if( population-jobless_population>0 ) // if there are workers in this town, don't migrate the town people return 0; return 1; } //-------- End of function Town::should_ai_migrate ---------// //-------- Begin of function Town::protection_needed ------// // // Return an index from 0 to 100 indicating the military // protection needed for this town. // int Town::protection_needed() { int protectionNeeded = population * 10; Firm* firmPtr; for( int i=linked_firm_count-1 ; i>=0 ; i-- ) { firmPtr = firm_array[ linked_firm_array[i] ]; if( firmPtr->nation_recno != nation_recno ) continue; //----- if this is a camp, add combat level points -----// if( firmPtr->firm_id == FIRM_MARKET ) { protectionNeeded += ((FirmMarket*)firmPtr)->stock_value_index()*2; } else { protectionNeeded += (int) firmPtr->productivity*2; if( firmPtr->firm_id == FIRM_MINE ) // more protection for mines protectionNeeded += 200; } } return protectionNeeded; } //---------- End of function Town::protection_needed ------// //-------- Begin of function Town::protection_available ------// // // Return an index from 0 to 100 indicating the military // protection currently available for this town. // int Town::protection_available() { int protectionLevel=0; Firm* firmPtr; for( int i=linked_firm_count-1 ; i>=0 ; i-- ) { firmPtr = firm_array[ linked_firm_array[i] ]; if( firmPtr->nation_recno != nation_recno ) continue; //----- if this is a camp, add combat level points -----// if( firmPtr->firm_id == FIRM_CAMP ) protectionLevel += 10 + ((FirmCamp*)firmPtr)->total_combat_level(); // +10 for the existence of the camp structure } return protectionLevel; } //---------- End of function Town::protection_available ------// //-------- Begin of function Town::think_build_market ------// // int Town::think_build_market() { if( info.game_date < setup_date + 90 ) // don't build the market too soon, as it may need to migrate to other town return 0; Nation* ownNation = nation_array[nation_recno]; if( population < 10 + (100-ownNation->pref_trading_tendency)/20 ) return 0; if( no_neighbor_space ) // if there is no space in the neighbor area for building a new firm. return 0; //--- check whether the AI can build a new firm next this firm ---// if( !ownNation->can_ai_build(FIRM_MARKET) ) return 0; //----------------------------------------------------// // If there is already a firm queued for building with // a building location that is within the effective range // of the this firm. //----------------------------------------------------// if( ownNation->is_build_action_exist(FIRM_MARKET, center_x, center_y) ) return 0; //-- only build one market place next to this mine, check if there is any existing one --// FirmMarket* firmPtr; for(int i=0; i<linked_firm_count; i++) { firmPtr = (FirmMarket*) firm_array[linked_firm_array[i]]; if(firmPtr->firm_id!=FIRM_MARKET) continue; //------ if this market is our own one ------// if( firmPtr->nation_recno == nation_recno && ((FirmMarket*)firmPtr)->is_retail_market ) { return 0; } } //------ queue building a new market -------// short buildXLoc, buildYLoc; if( !ownNation->find_best_firm_loc(FIRM_MARKET, loc_x1, loc_y1, buildXLoc, buildYLoc) ) { no_neighbor_space = 1; return 0; } ownNation->add_action(buildXLoc, buildYLoc, loc_x1, loc_y1, ACTION_AI_BUILD_FIRM, FIRM_MARKET); return 1; } //-------- End of function Town::think_build_market ------// //-------- Begin of function Town::think_build_camp ------// // // Think about building military camps for protecting this town. // int Town::think_build_camp() { //----- check if any of the other camps protecting this town is still recruiting soldiers, if so, wait until their recruitment is finished. So we can measure the protection available accurately. Nation* ownNation = nation_array[nation_recno]; FirmCamp* firmCamp; Firm* firmPtr; int campCount=0; for(int i=linked_firm_count-1; i>=0; --i) { err_when(firm_array.is_deleted(linked_firm_array[i])); firmPtr = firm_array[linked_firm_array[i]]; if(firmPtr->firm_id!=FIRM_CAMP) continue; firmCamp = (FirmCamp*) firmPtr; if( firmCamp->nation_recno != nation_recno ) continue; if( firmCamp->under_construction || firmCamp->ai_recruiting_soldier ) // if this camp is still trying to recruit soldiers return 0; campCount++; } //--- this is one of the few base towns the nation has, then a camp must be built ---// if( campCount==0 && is_base_town && ownNation->ai_base_town_count<=2 ) { return ai_build_neighbor_firm(FIRM_CAMP); } //---- only build camp if we have enough cash and profit ----// if( !ownNation->ai_should_spend(70+ownNation->pref_military_development/4) ) // 70 to 95 return 0; //---- only build camp if we need more protection than it is currently available ----// int protectionNeeded = protection_needed(); int protectionAvailable = protection_available(); if( protectionAvailable >= protectionNeeded ) return 0; Nation* nationPtr = nation_array[nation_recno]; if( !(protectionNeeded>0 && protectionAvailable==0) ) // if protection needed > 0, and protection available is 0, we must build a camp now { int needUrgency = 100 * (protectionNeeded-protectionAvailable) / protectionNeeded; if( nationPtr->total_jobless_population-MAX_WORKER < (100-needUrgency) * (200 - nationPtr->pref_military_development) / 200 ) { return 0; } } //--- check if we have enough people to recruit ---// int buildFlag = 0; if( nationPtr->total_jobless_population >= 16 ) { buildFlag = 1; } if( nationPtr->total_jobless_population >= 8 && is_base_town ) { buildFlag = 1; } else if( nationPtr->ai_has_should_close_camp(region_id) ) // there is camp that can be closed { buildFlag = 1; } if( !buildFlag ) return 0; return ai_build_neighbor_firm(FIRM_CAMP); } //---------- End of function Town::think_build_camp ------// //-------- Begin of function Town::update_product_supply ------// // void Town::update_product_supply() { FirmMarket* firmPtr; int productId; memset( has_product_supply, 0, sizeof(has_product_supply) ); //----- scan for linked market place -----// for( int i=linked_firm_count-1 ; i>=0 ; i-- ) { firmPtr = (FirmMarket*) firm_array[ linked_firm_array[i] ]; if( firmPtr->nation_recno != nation_recno || firmPtr->firm_id != FIRM_MARKET ) { continue; } //---- check what type of products they are selling ----// for( int j=0 ; j<MAX_MARKET_GOODS ; j++ ) { productId = firmPtr->market_goods_array[j].product_raw_id; has_product_supply[productId-1]++; } } } //---------- End of function Town::update_product_supply ------// //------- Begin of function Town::think_build_research -------// int Town::think_build_research() { Nation* nationPtr = nation_array[nation_recno]; if( !is_base_town ) return 0; if( jobless_population < MAX_WORKER || nationPtr->total_jobless_population < MAX_WORKER*2 ) { return 0; } if( nationPtr->true_profit_365days() < 0 ) return 0; if( !nationPtr->ai_should_spend( 25 + nationPtr->pref_use_weapon/2 - nationPtr->ai_research_count*10 ) ) return 0; int totalTechLevel = nationPtr->total_tech_level(); if( totalTechLevel == tech_res.total_tech_level ) // all technology have been researched return 0; //--------------------------------------------// int maxResearch = 2 * (50+nationPtr->pref_use_weapon) / 50; maxResearch = MIN(nationPtr->ai_town_count, maxResearch); if( nationPtr->ai_research_count >= maxResearch ) return 0; //---- if any of the existing ones are not full employed ----// FirmResearch* firmResearch; for( int i=0 ; i<nationPtr->ai_research_count ; i++ ) { firmResearch = (FirmResearch*) firm_array[ nationPtr->ai_research_array[i] ]; if( firmResearch->region_id != region_id ) continue; if( firmResearch->worker_count < MAX_WORKER ) return 0; } //------- queue building a war factory -------// return ai_build_neighbor_firm(FIRM_RESEARCH); } //-------- End of function Town::think_build_research -------// //------- Begin of function Town::think_build_war_factory -------// int Town::think_build_war_factory() { Nation* nationPtr = nation_array[nation_recno]; if( !is_base_town ) return 0; if( jobless_population < MAX_WORKER || nationPtr->total_jobless_population < MAX_WORKER*2 ) { return 0; } int totalWeaponTechLevel = nationPtr->total_tech_level(UNIT_CLASS_WEAPON); if( totalWeaponTechLevel==0 ) return 0; //----- see if we have enough money to build & support the weapon ----// if( nationPtr->true_profit_365days() < 0 && nationPtr->ai_war_count > 0 ) // if we don't have any war factory, we may want to build one despite that we are losing money return 0; if( !nationPtr->ai_should_spend( nationPtr->pref_use_weapon/2 ) ) return 0; //--------------------------------------------// int maxWarFactory = (1+totalWeaponTechLevel) * nationPtr->pref_use_weapon / 100; maxWarFactory = MIN(nationPtr->ai_town_count, maxWarFactory); if( nationPtr->ai_war_count >= maxWarFactory ) return 0; //---- if any of the existing ones are not full employed or under capacity ----// FirmWar* firmWar; for( int i=0 ; i<nationPtr->ai_war_count ; i++ ) { firmWar = (FirmWar*) firm_array[ nationPtr->ai_war_array[i] ]; if( firmWar->region_id != region_id ) continue; if( firmWar->worker_count < MAX_WORKER || !firmWar->build_unit_id ) return 0; } //------- queue building a war factory -------// return ai_build_neighbor_firm(FIRM_WAR_FACTORY); } //-------- End of function Town::think_build_war_factory -------// //------- Begin of function Town::think_build_base -------// // // Think about building seats of powre. // int Town::think_build_base() { Nation* nationPtr = nation_array[nation_recno]; if( !is_base_town ) return 0; //----- see if we have enough money to build & support the weapon ----// if( !nationPtr->ai_should_spend(50) ) return 0; if( jobless_population < MAX_BASE_PRAYER/2 || nationPtr->total_jobless_population < MAX_BASE_PRAYER ) { return 0; } //------ do a scan on the existing bases first ------// static short buildRatingArray[MAX_RACE]; memset( buildRatingArray, 0, sizeof(buildRatingArray) ); //--- increase build rating for the seats that this nation knows how to build ---// GodInfo* godInfo; int i; for( i=1 ; i<=god_res.god_count ; i++ ) { godInfo = god_res[i]; if( godInfo->is_nation_know(nation_recno) ) buildRatingArray[godInfo->race_id-1] += 100; } //--- decrease build rating for the seats that the nation currently has ---// FirmBase* firmBase; for( i=0 ; i<nationPtr->ai_base_count ; i++ ) { firmBase = (FirmBase*) firm_array[ nationPtr->ai_base_array[i] ]; buildRatingArray[ god_res[firmBase->god_id]->race_id-1 ] = 0; // only build one /* if( firmBase->prayer_count < MAX_BASE_PRAYER ) buildRatingArray[ god_res[firmBase->god_id]->race_id-1 ] = 0; else buildRatingArray[ god_res[firmBase->god_id]->race_id-1 ] -= 10; // -10 for one existing instance */ } //------ decide which is the best to build -------// int bestRating=0, bestRaceId=0; for( i=0 ; i<MAX_RACE ; i++ ) { if( buildRatingArray[i] > bestRating ) { bestRating = buildRatingArray[i]; bestRaceId = i+1; } } //------- queue building a seat of power ------// if( bestRaceId ) return ai_build_neighbor_firm(FIRM_BASE, bestRaceId); return 0; } //-------- End of function Town::think_build_base -------// //------- Begin of function Town::think_build_inn -------// // int Town::think_build_inn() { Nation* ownNation = nation_array[nation_recno]; if( ownNation->ai_inn_count < ownNation->ai_supported_inn_count() ) { return think_build_firm( FIRM_INN, 1 ); } return 0; } //-------- End of function Town::think_build_inn -------// //------- Begin of function Town::ai_build_neighbor_firm -------// // // Build a specific firm next to this town. // int Town::ai_build_neighbor_firm(int firmId, int firmRaceId) { short buildXLoc, buildYLoc; Nation* nationPtr = nation_array[nation_recno]; if( !nationPtr->find_best_firm_loc(firmId, loc_x1, loc_y1, buildXLoc, buildYLoc) ) { no_neighbor_space = 1; return 0; } nationPtr->add_action(buildXLoc, buildYLoc, loc_x1, loc_y1, ACTION_AI_BUILD_FIRM, firmId, 1, 0, firmRaceId); return 1; } //-------- End of function Town::ai_build_neighbor_firm -------// //------- Begin of function Town::think_split_town -------// // // Split the town into two, migrating some population to the new // town. // int Town::think_split_town() { if( jobless_population==0 ) // cannot move if we don't have any mobilizable unit return 0; //--- split when the population is close to its limit ----// Nation* nationPtr = nation_array[nation_recno]; if( population < 45 + nationPtr->pref_territorial_cohesiveness / 10 ) return 0; //-------- think about which race to move --------// int mostRaceId1, mostRaceId2, raceId=0; get_most_populated_race(mostRaceId1, mostRaceId2); if( mostRaceId2 && jobless_race_pop_array[mostRaceId2-1] > 0 && can_recruit(mostRaceId2) ) raceId = mostRaceId2; else if( mostRaceId1 && jobless_race_pop_array[mostRaceId1-1] > 0 && can_recruit(mostRaceId1) ) raceId = mostRaceId1; else raceId = pick_random_race(0, 1); // 0-recruitable only, 1-also pick spy. if( !raceId ) { //---- if the racial mix favors a split of town -----// // // This is when there are two major races, both of significant // population in the town. This is a good time for us to move // the second major race to a new town. // //---------------------------------------------------// if( mostRaceId2 && jobless_race_pop_array[mostRaceId2] > 0 && race_pop_array[mostRaceId2] >= population/3 && // the race's has at least 1/3 of the town's total population can_recruit(mostRaceId2) ) { raceId = mostRaceId2; } } if( !raceId ) return 0; //---- check if there is already a town of this race with low population linked to this town, then don't split a new one ---// Town* townPtr; for( int i=0 ; i<linked_town_count ; i++ ) { townPtr = town_array[ linked_town_array[i] ]; if( townPtr->nation_recno == nation_recno && townPtr->population < 20 && townPtr->majority_race() == raceId ) { return 0; } } //-------- settle to a new town ---------// return ai_settle_new(raceId); } //-------- End of function Town::think_split_town -------// //------- Begin of function Town::think_move_between_town -------// // void Town::think_move_between_town() { //------ move people between linked towns ------// int ourMajorityRace = majority_race(); int raceId, rc, loopCount; Town* townPtr; for( int i=0 ; i<linked_town_count ; i++ ) { townPtr = town_array[ linked_town_array[i] ]; if( townPtr->nation_recno != nation_recno ) continue; loopCount=0; //--- migrate people to the new town ---// while(1) { err_when( ++loopCount > 100 ); rc = 0; raceId = townPtr->majority_race(); // get the linked town's major race if( ourMajorityRace != raceId ) // if our major race is not this race, then move the person to the target town { rc = 1; } else //-- if this town's major race is the same as the target town --// { if( population - townPtr->population > 10 ) // if this town's population is larger than the target town by 10 people, then move rc = 1; } if( rc ) { if( !migrate_to(townPtr->town_recno, COMMAND_AI, raceId) ) break; } else break; } } } //-------- End of function Town::think_move_between_town -------// //------- Begin of function Town::ai_settle_new -------// // int Town::ai_settle_new(int raceId) { //-------- locate space for the new town --------// int xLoc=loc_x1, yLoc=loc_y1; // xLoc & yLoc are used for returning results if( !world.locate_space( xLoc, yLoc, loc_x2, loc_y2, STD_TOWN_LOC_WIDTH+2, // STD_TOWN_LOC_WIDTH+2 for space around the town STD_TOWN_LOC_HEIGHT+2, UNIT_LAND, region_id, 1 ) ) { return 0; } //------- it must be within the effective town-to-town distance ---// if( m.points_distance( center_x, center_y, xLoc+(STD_TOWN_LOC_WIDTH-1)/2, yLoc+(STD_TOWN_LOC_HEIGHT-1)/2 ) > EFFECTIVE_TOWN_TOWN_DISTANCE ) { return 0; } //--- recruit a unit from the town and order it to settle a new town ---// int unitRecno = recruit(-1, raceId, COMMAND_AI); if( !unitRecno || !unit_array[unitRecno]->is_visible() ) return 0; unit_array[unitRecno]->settle( xLoc+1, yLoc+1 ); return 1; } //-------- End of function Town::ai_settle_new -------// //------- Begin of function Town::think_attack_nearby_enemy -------// // // Think about attacking enemies near the town. // int Town::think_attack_nearby_enemy() { enum { SCAN_X_RANGE = 6, SCAN_Y_RANGE = 6 }; int xLoc1 = loc_x1 - SCAN_X_RANGE; int yLoc1 = loc_y1 - SCAN_Y_RANGE; int xLoc2 = loc_x2 + SCAN_X_RANGE; int yLoc2 = loc_y2 + SCAN_Y_RANGE; xLoc1 = MAX( xLoc1, 0 ); yLoc1 = MAX( yLoc1, 0 ); xLoc2 = MIN( xLoc2, MAX_WORLD_X_LOC-1 ); yLoc2 = MIN( yLoc2, MAX_WORLD_Y_LOC-1 ); //------------------------------------------// int enemyCombatLevel=0; // the higher the rating, the easier we can attack the target town. int xLoc, yLoc; int enemyXLoc= -1, enemyYLoc; Unit* unitPtr; Nation* nationPtr = nation_array[nation_recno]; Firm* firmPtr; Location* locPtr; for( yLoc=yLoc1 ; yLoc<=yLoc2 ; yLoc++ ) { locPtr = world.get_loc(xLoc1, yLoc); for( xLoc=xLoc1 ; xLoc<=xLoc2 ; xLoc++, locPtr++ ) { //--- if there is an enemy unit here ---// if( locPtr->has_unit(UNIT_LAND) ) { unitPtr = unit_array[ locPtr->unit_recno(UNIT_LAND) ]; if( !unitPtr->nation_recno ) continue; //--- if the unit is idle and he is our enemy ---// if( unitPtr->cur_action == SPRITE_IDLE && nationPtr->get_relation_status(unitPtr->nation_recno) == NATION_HOSTILE ) { err_when( unitPtr->nation_recno == nation_recno ); enemyCombatLevel += (int) unitPtr->hit_points; if( enemyXLoc == -1 || m.random(5)==0 ) { enemyXLoc = xLoc; enemyYLoc = yLoc; } } } //--- if there is an enemy firm here ---// else if( locPtr->is_firm() ) { firmPtr = firm_array[locPtr->firm_recno()]; //------- if this is a monster firm ------// if( firmPtr->firm_id == FIRM_MONSTER ) // don't attack monster here, OAI_MONS.CPP will handle that continue; //------- if this is a firm of our enemy -------// if( nationPtr->get_relation_status(firmPtr->nation_recno) == NATION_HOSTILE ) { err_when( firmPtr->nation_recno == nation_recno ); if( firmPtr->worker_count == 0 ) enemyCombatLevel += 50; // empty firm else { Worker* workerPtr = firmPtr->worker_array; for( int i=firmPtr->worker_count ; i>0 ; i--, workerPtr++ ) enemyCombatLevel += workerPtr->hit_points; } if( enemyXLoc == -1 || m.random(5)==0 ) { enemyXLoc = firmPtr->loc_x1; enemyYLoc = firmPtr->loc_y1; } } } } } //--------- attack the target now -----------// if( enemyCombatLevel > 0 ) { err_when( enemyXLoc < 0 ); nationPtr->ai_attack_target( enemyXLoc, enemyYLoc, enemyCombatLevel ); return 1; } return 0; } //-------- End of function Town::think_attack_nearby_enemy -------// //------- Begin of function Town::think_attack_linked_enemy -------// // // Think about attacking enemy camps that are linked to this town. // int Town::think_attack_linked_enemy() { Firm* firmPtr; Nation* ownNation = nation_array[nation_recno]; int targetCombatLevel; for(int i=0; i<linked_firm_count; i++) { if( linked_firm_enable_array[i] != LINK_EE ) // don't attack if the link is not enabled continue; firmPtr = firm_array[ linked_firm_array[i] ]; if( firmPtr->nation_recno == nation_recno ) continue; if( firmPtr->should_close_flag ) // if this camp is about to close continue; //--- only attack AI firms when they belong to a hostile nation ---// if( firmPtr->firm_ai && ownNation->get_relation_status(firmPtr->nation_recno) != NATION_HOSTILE ) { continue; } //---- if this is a camp -----// if( firmPtr->firm_id == FIRM_CAMP ) { //----- if we are friendly with the target nation ------// int nationStatus = ownNation->get_relation_status(firmPtr->nation_recno); if( nationStatus >= NATION_FRIENDLY ) { if( !ownNation->ai_should_attack_friendly(firmPtr->nation_recno, 100) ) continue; ownNation->ai_end_treaty(firmPtr->nation_recno); } else if( nationStatus == NATION_NEUTRAL ) { //-- if the link is off and the nation's miliary strength is bigger than us, don't attack --// if( nation_array[firmPtr->nation_recno]->military_rank_rating() > ownNation->military_rank_rating() ) { continue; } } //--- don't attack when the trade rating is high ----// int tradeRating = ownNation->trade_rating(firmPtr->nation_recno); if( tradeRating > 50 || tradeRating + ownNation->ai_trade_with_rating(firmPtr->nation_recno) > 100 ) { continue; } targetCombatLevel = ((FirmCamp*)firmPtr)->total_combat_level(); } else //--- if this is another type of firm ----// { //--- only attack other types of firm when the status is hostile ---// if( ownNation->get_relation_status(firmPtr->nation_recno) != NATION_HOSTILE ) continue; targetCombatLevel = 50; } //--------- attack now ----------// ownNation->ai_attack_target( firmPtr->loc_x1, firmPtr->loc_y1, targetCombatLevel ); return 1; } return 0; } //-------- End of function Town::think_attack_linked_enemy -------// //-------- Begin of function Town::think_capture_linked_firm --------// // // Try to capture firms linked to this town if all the workers in firms // resident in this town. // void Town::think_capture_linked_firm() { Firm* firmPtr; //----- scan for linked firms -----// for( int i=linked_firm_count-1 ; i>=0 ; i-- ) { firmPtr = firm_array[ linked_firm_array[i] ]; if( firmPtr->nation_recno == nation_recno ) // this is our own firm continue; if( firmPtr->can_worker_capture(nation_recno) ) // if we can capture this firm, capture it now { firmPtr->capture_firm(nation_recno); } } } //-------- End of function Town::think_capture_linked_firm --------// //-------- Begin of function Town::think_capture_enemy_town --------// // // Think about sending troops from this town to capture enemy towns. // int Town::think_capture_enemy_town() { if( !is_base_town ) return 0; Nation* nationPtr = nation_array[nation_recno]; if( nationPtr->ai_capture_enemy_town_recno ) // a capturing action is already in process return 0; int surplusProtection = protection_available() - protection_needed(); //-- only attack enemy town if we have enough military protection surplus ---// if( surplusProtection < 300 - nationPtr->pref_military_courage*2 ) return 0; return nationPtr->think_capture_new_enemy_town(this); } //-------- End of function Town::think_capture_enemy_town --------// //-------- Begin of function Town::think_counter_spy --------// // // Think about planting anti-spy units in this town. // int Town::think_counter_spy() { if( population >= MAX_TOWN_POPULATION ) return 0; Nation* ownNation = nation_array[nation_recno]; if( ownNation->total_spy_count > ownNation->total_population * (10+ownNation->pref_spy/5) / 100 ) // 10% to 30% return 0; if( !ownNation->ai_should_spend(ownNation->pref_counter_spy/2) ) // 0 to 50 return 0; //--- the expense of spies should not be too large ---// if( ownNation->expense_365days(EXPENSE_SPY) > ownNation->expense_365days() * (50+ownNation->pref_counter_spy) / 400 ) { return 0; } //------- check if we need additional spies ------// int spyCount; int curSpyLevel = spy_array.total_spy_skill_level( SPY_TOWN, town_recno, nation_recno, spyCount ); if( spyCount >= 1+ownNation->pref_counter_spy/40 ) // 1 to 3 spies at MAX in each town return 0; //---- if the spy skill needed is more than the current skill level ----// int neededSpyLevel = needed_anti_spy_level(); if( neededSpyLevel > curSpyLevel+30 ) { return ownNation->ai_assign_spy_to_town(town_recno); } else return 0; } //-------- End of function Town::think_counter_spy --------// //-------- Begin of function Town::needed_anti_spy_level --------// // // Return the total needed spy level for anti-spying in this town. // int Town::needed_anti_spy_level() { return ( linked_firm_count*10 + 100 * population / MAX_TOWN_POPULATION ) * nation_array[nation_recno]->pref_counter_spy / 100; } //-------- End of function Town::needed_anti_spy_level --------// //-------- Begin of function Town::think_spying_town --------// // // Think about planting spies into independent towns and enemy towns. // int Town::think_spying_town() { int majorityRace = majority_race(); //---- don't recruit spy if we are low in cash or losing money ----// Nation* ownNation = nation_array[nation_recno]; if( ownNation->total_population < 30-ownNation->pref_spy/10 ) // don't use spies if the population is too low, we need to use have people to grow population return 0; if( ownNation->total_spy_count > ownNation->total_population * (10+ownNation->pref_spy/5) / 100 ) // 10% to 30% return 0; if( !ownNation->ai_should_spend(ownNation->pref_spy/2) ) // 0 to 50 return 0; //--- pick minority units first (also for increasing town harmony) ---// for( int raceId=1 ; raceId<=MAX_RACE ; raceId++ ) { if( race_pop_array[raceId-1]==0 || raceId==majorityRace ) continue; if( !can_recruit(raceId) ) continue; if( think_spying_town_assign_to(raceId) ) return 1; } //---- then think about assign spies of majority race ----// if( ownNation->pref_spy > 50 ) // only if pref_spy is > 50, it will consider using spies of majority race { if( can_recruit(majorityRace) ) { if( think_spying_town_assign_to(majorityRace) ) return 1; } } return 0; } //-------- End of function Town::think_spying_town --------// //-------- Begin of function Town::think_spying_town_assign_to --------// // // Think about planting spies into independent towns and enemy towns. // int Town::think_spying_town_assign_to(int raceId) { Nation* ownNation = nation_array[nation_recno]; int targetTownRecno = ownNation->think_assign_spy_target_town(race_id, region_id); if( !targetTownRecno ) return 0; //------- assign the spy now -------// int unitRecno = recruit(SKILL_SPYING, raceId, COMMAND_AI); if( !unitRecno ) return 0; Town* targetTown = town_array[targetTownRecno]; int actionRecno = ownNation->add_action( targetTown->loc_x1, targetTown->loc_y1, -1, -1, ACTION_AI_ASSIGN_SPY, targetTown->nation_recno, 1, unitRecno ); if( !actionRecno ) return 0; train_unit_action_id = ownNation->get_action(actionRecno)->action_id; return 1; } //-------- End of function Town::think_spying_town_assign_to --------// //-------- Begin of function Town::update_base_town_status --------// // void Town::update_base_town_status() { int newBaseTownStatus = new_base_town_status(); if( newBaseTownStatus == is_base_town ) return; Nation* ownNation = nation_array[nation_recno]; if( is_base_town ) ownNation->ai_base_town_count--; if( newBaseTownStatus ) ownNation->ai_base_town_count++; is_base_town = newBaseTownStatus; } //-------- End of function Town::update_base_town_status --------// //-------- Begin of function Town::new_base_town_status --------// // int Town::new_base_town_status() { Nation* ownNation = nation_array[nation_recno]; if( population > 20 + ownNation->pref_territorial_cohesiveness/10 ) return 1; //---- if there is only 1 town, then it must be the base town ---// if( ownNation->ai_town_count==1 ) return 1; //---- if there is only 1 town in this region, then it must be the base town ---// AIRegion* aiRegion = ownNation->get_ai_region(region_id); if( aiRegion && aiRegion->town_count==1 ) return 1; //--- don't drop if there are employed villagers ---// if( jobless_population != population ) return 1; //---- if this town is linked to a base town, also don't drop it ----// Town* townPtr; for( int i=linked_town_count-1 ; i>=0 ; i-- ) { townPtr = town_array[ linked_town_array[i] ]; if( townPtr->nation_recno == nation_recno && townPtr->is_base_town ) { return 1; } } /* //---- if there is not a single town meeting the above criteria, then set the town with the largest population to be the base town. ----// if( ownNation->ai_base_town_count <= 1 ) { for( i=ownNation->ai_town_count-1 ; i>=0 ; i-- ) { townPtr = town_array[ ownNation->ai_town_array[i] ]; if( townPtr->population > population ) // if this town is not the largest town return 0. return 0; } return 1; // return 1 if this town is the largest town. } */ return 0; } //-------- End of function Town::new_base_town_status --------// //-------- Begin of function Town::think_scout --------// // int Town::think_scout() { Nation* ownNation = nation_array[nation_recno]; if( config.explore_whole_map ) return 0; if( info.game_date > info.game_start_date + 50 + ownNation->pref_scout ) // only in the first half year of the game return 0; if( ownNation->ai_town_count > 1 ) // only when there is only one town return 0; //-------------------------------------------// int destX, destY; if( m.random(2)==0 ) destX = center_x + 50 + m.random(50); else destX = center_x - 50 - m.random(50); if( m.random(2)==0 ) destY = center_y + 50 + m.random(50); else destY = center_y - 50 - m.random(50); destX = MAX(0, destX); destX = MIN(MAX_WORLD_X_LOC-1, destX); destY = MAX(0, destY); destY = MIN(MAX_WORLD_Y_LOC-1, destY); ownNation->add_action( destX, destY, loc_x1, loc_y1, ACTION_AI_SCOUT, 0); return 1; } //-------- End of function Town::think_scout --------//
brianV/7kaa
src/client/OTOWNAI.cpp
C++
gpl-2.0
45,862
// // // Solution: PartDesk // Project: PartDesk.Web // File: OrdersListModel.cs // // Created by: ykors_000 at 25.11.2013 15:54 // // Property of SoftGears // // ======== using PartDesk.Domain.Entities; using PartDesk.Web.Models.Manage; namespace PartDesk.Web.Models.Orders { /// <summary> /// Модель списка заказов /// </summary> public class OrdersListModel: GenericListModel<Order> { /// <summary> /// Заголовок списка заказов /// </summary> public string Title { get; set; } } }
softgears/PartDesk
PartDesk.Web/Models/Orders/OrdersListModel.cs
C#
gpl-2.0
590
/* * tcluser.c -- handles: * Tcl stubs for the user-record-oriented commands */ /* * Copyright (C) 1997 Robey Pointer * Copyright (C) 1999 - 2016 Eggheads Development 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 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 "main.h" #include "users.h" #include "chan.h" #include "tandem.h" #include "modules.h" extern Tcl_Interp *interp; extern struct userrec *userlist; extern int default_flags, dcc_total, ignore_time; extern struct dcc_t *dcc; extern char botnetnick[]; extern time_t now; static int tcl_countusers STDVAR { BADARGS(1, 1, ""); Tcl_AppendResult(irp, int_to_base10(count_users(userlist)), NULL); return TCL_OK; } static int tcl_validuser STDVAR { BADARGS(2, 2, " handle"); Tcl_AppendResult(irp, get_user_by_handle(userlist, argv[1]) ? "1" : "0", NULL); return TCL_OK; } static int tcl_finduser STDVAR { struct userrec *u; BADARGS(2, 2, " nick!user@host"); u = get_user_by_host(argv[1]); Tcl_AppendResult(irp, u ? u->handle : "*", NULL); return TCL_OK; } static int tcl_passwdOk STDVAR { struct userrec *u; BADARGS(3, 3, " handle passwd"); Tcl_AppendResult(irp, ((u = get_user_by_handle(userlist, argv[1])) && u_pass_match(u, argv[2])) ? "1" : "0", NULL); return TCL_OK; } static int tcl_chattr STDVAR { int of, ocf = 0; char *chan, *chg, work[100]; struct flag_record pls, mns, user; struct userrec *u; BADARGS(2, 4, " handle ?changes? ?channel?"); if ((argv[1][0] == '*') || !(u = get_user_by_handle(userlist, argv[1]))) { Tcl_AppendResult(irp, "*", NULL); return TCL_OK; } if (argc == 4) { user.match = FR_GLOBAL | FR_CHAN; chan = argv[3]; chg = argv[2]; } else if (argc == 3 && argv[2][0]) { int ischan = (findchan_by_dname(argv[2]) != NULL); if (strchr(CHANMETA, argv[2][0]) && !ischan && argv[2][0] != '+' && argv[2][0] != '-') { Tcl_AppendResult(irp, "no such channel", NULL); return TCL_ERROR; } else if (ischan) { /* Channel exists */ user.match = FR_GLOBAL | FR_CHAN; chan = argv[2]; chg = NULL; } else { /* 3rd possibility... channel doesnt exist, does start with a +. * In this case we assume the string is flags. */ user.match = FR_GLOBAL; chan = NULL; chg = argv[2]; } } else { user.match = FR_GLOBAL; chan = NULL; chg = NULL; } if (chan && !findchan_by_dname(chan)) { Tcl_AppendResult(irp, "no such channel", NULL); return TCL_ERROR; } /* Retrieve current flags */ get_user_flagrec(u, &user, chan); /* Make changes */ if (chg) { of = user.global; pls.match = user.match; break_down_flags(chg, &pls, &mns); /* No-one can change these flags on-the-fly */ pls.global &=~(USER_BOT); mns.global &=~(USER_BOT); if (chan) { pls.chan &= ~(BOT_SHARE); mns.chan &= ~(BOT_SHARE); } user.global = sanity_check((user.global |pls.global) &~mns.global); user.udef_global = (user.udef_global | pls.udef_global) & ~mns.udef_global; if (chan) { ocf = user.chan; user.chan = chan_sanity_check((user.chan | pls.chan) & ~mns.chan, user.global); user.udef_chan = (user.udef_chan | pls.udef_chan) & ~mns.udef_chan; } set_user_flagrec(u, &user, chan); check_dcc_attrs(u, of); if (chan) check_dcc_chanattrs(u, chan, user.chan, ocf); } user.chan &= ~BOT_SHARE; /* actually not a user flag, hide it */ /* Build flag string */ build_flags(work, &user, NULL); Tcl_AppendResult(irp, work, NULL); return TCL_OK; } static int tcl_botattr STDVAR { char *chan, *chg, work[100]; struct flag_record pls, mns, user; struct userrec *u; BADARGS(2, 4, " bot-handle ?changes? ?channel?"); u = get_user_by_handle(userlist, argv[1]); if ((argv[1][0] == '*') || !u || !(u->flags & USER_BOT)) { Tcl_AppendResult(irp, "*", NULL); return TCL_OK; } if (argc == 4) { user.match = FR_BOT | FR_CHAN; chan = argv[3]; chg = argv[2]; } else if (argc == 3 && argv[2][0] && strchr(CHANMETA, argv[2][0]) != NULL) { /* We need todo extra checking here to stop us mixing up +channel's * with flags. <cybah> */ if (!findchan_by_dname(argv[2]) && argv[2][0] != '+') { /* Channel doesnt exist, and it cant possibly be flags as there * is no + at the start of the string. */ Tcl_AppendResult(irp, "no such channel", NULL); return TCL_ERROR; } else if (findchan_by_dname(argv[2])) { /* Channel exists */ user.match = FR_BOT | FR_CHAN; chan = argv[2]; chg = NULL; } else { /* 3rd possibility... channel doesnt exist, does start with a +. * In this case we assume the string is flags. */ user.match = FR_BOT; chan = NULL; chg = argv[2]; } } else { user.match = FR_BOT; chan = NULL; if (argc < 3) chg = NULL; else chg = argv[2]; } if (chan && !findchan_by_dname(chan)) { Tcl_AppendResult(irp, "no such channel", NULL); return TCL_ERROR; } /* Retrieve current flags */ get_user_flagrec(u, &user, chan); /* Make changes */ if (chg) { pls.match = user.match; break_down_flags(chg, &pls, &mns); /* No-one can change these flags on-the-fly */ if (chan) { pls.chan &= BOT_SHARE; mns.chan &= BOT_SHARE; } user.bot = sanity_check((user.bot | pls.bot) & ~mns.bot); if (chan) { user.chan = (user.chan | pls.chan) & ~mns.chan; user.udef_chan = (user.udef_chan | pls.udef_chan) & ~mns.udef_chan; } set_user_flagrec(u, &user, chan); } /* Only user flags can be set per channel, not bot ones, so BOT_SHARE is a hack to allow botattr |+s */ user.chan &= BOT_SHARE; user.udef_chan = 0; /* User definable bot flags are global only, anything here is a regular flag, so hide it. */ /* Build flag string */ build_flags(work, &user, NULL); Tcl_AppendResult(irp, work, NULL); return TCL_OK; } static int tcl_matchattr STDVAR { struct userrec *u; struct flag_record plus, minus, user; int ok = 0, f; BADARGS(3, 4, " handle flags ?channel?"); if ((u = get_user_by_handle(userlist, argv[1]))) { user.match = FR_GLOBAL | (argc == 4 ? FR_CHAN : 0) | FR_BOT; get_user_flagrec(u, &user, argv[3]); plus.match = user.match; break_down_flags(argv[2], &plus, &minus); f = (minus.global || minus.udef_global || minus.chan || minus.udef_chan || minus.bot); if (flagrec_eq(&plus, &user)) { if (!f) ok = 1; else { minus.match = plus.match ^ (FR_AND | FR_OR); if (!flagrec_eq(&minus, &user)) ok = 1; } } } Tcl_AppendResult(irp, ok ? "1" : "0", NULL); return TCL_OK; } static int tcl_adduser STDVAR { unsigned char *p; BADARGS(2, 3, " handle ?hostmask?"); if (strlen(argv[1]) > HANDLEN) argv[1][HANDLEN] = 0; for (p = (unsigned char *) argv[1]; *p; p++) if (*p <= 32 || *p == '@') *p = '?'; if ((argv[1][0] == '*') || strchr(BADHANDCHARS, argv[1][0]) || get_user_by_handle(userlist, argv[1])) Tcl_AppendResult(irp, "0", NULL); else { userlist = adduser(userlist, argv[1], argv[2], "-", default_flags); Tcl_AppendResult(irp, "1", NULL); } return TCL_OK; } static int tcl_addbot STDVAR { struct bot_addr *bi; char *p, *q; BADARGS(3, 3, " handle address"); if (strlen(argv[1]) > HANDLEN) argv[1][HANDLEN] = 0; for (p = argv[1]; *p; p++) if ((unsigned char) *p <= 32 || *p == '@') *p = '?'; if ((argv[1][0] == '*') || strchr(BADHANDCHARS, argv[1][0]) || get_user_by_handle(userlist, argv[1])) Tcl_AppendResult(irp, "0", NULL); else { userlist = adduser(userlist, argv[1], "none", "-", USER_BOT); bi = user_malloc(sizeof(struct bot_addr)); #ifdef IPV6 if ((q = strchr(argv[2], '/'))) { if (!q[1]) { *q = 0; q = 0; } } else #endif q = strchr(argv[2], ':'); if (!q) { bi->address = user_malloc(strlen(argv[2]) + 1); strcpy(bi->address, argv[2]); bi->telnet_port = 3333; bi->relay_port = 3333; } else { bi->address = user_malloc(q - argv[2] + 1); strncpy(bi->address, argv[2], q - argv[2]); bi->address[q - argv[2]] = 0; p = q + 1; bi->telnet_port = atoi(p); q = strchr(p, '/'); if (!q) bi->relay_port = bi->telnet_port; else bi->relay_port = atoi(q + 1); } set_user(&USERENTRY_BOTADDR, get_user_by_handle(userlist, argv[1]), bi); Tcl_AppendResult(irp, "1", NULL); } return TCL_OK; } static int tcl_deluser STDVAR { BADARGS(2, 2, " handle"); Tcl_AppendResult(irp, (argv[1][0] == '*') ? "0" : int_to_base10(deluser(argv[1])), NULL); return TCL_OK; } static int tcl_delhost STDVAR { BADARGS(3, 3, " handle hostmask"); if ((!get_user_by_handle(userlist, argv[1])) || (argv[1][0] == '*')) { Tcl_AppendResult(irp, "non-existent user", NULL); return TCL_ERROR; } Tcl_AppendResult(irp, delhost_by_handle(argv[1], argv[2]) ? "1" : "0", NULL); return TCL_OK; } static int tcl_userlist STDVAR { struct userrec *u; struct flag_record user, plus, minus; int ok = 1, f = 0; BADARGS(1, 3, " ?flags ?channel??"); if (argc == 3 && !findchan_by_dname(argv[2])) { Tcl_AppendResult(irp, "Invalid channel: ", argv[2], NULL); return TCL_ERROR; } if (argc >= 2) { plus.match = FR_GLOBAL | FR_CHAN | FR_BOT; break_down_flags(argv[1], &plus, &minus); f = (minus.global ||minus.udef_global || minus.chan || minus.udef_chan || minus.bot); } minus.match = plus.match ^ (FR_AND | FR_OR); for (u = userlist; u; u = u->next) { if (argc >= 2) { user.match = FR_GLOBAL | FR_CHAN | FR_BOT | (argc == 3 ? 0 : FR_ANYWH); if (argc == 3) get_user_flagrec(u, &user, argv[2]); else get_user_flagrec(u, &user, NULL); if (flagrec_eq(&plus, &user) && !(f && flagrec_eq(&minus, &user))) ok = 1; else ok = 0; } if (ok) Tcl_AppendElement(interp, u->handle); } return TCL_OK; } static int tcl_save STDVAR { write_userfile(-1); return TCL_OK; } static int tcl_reload STDVAR { reload(); return TCL_OK; } static int tcl_chhandle STDVAR { struct userrec *u; char newhand[HANDLEN + 1]; int x = 1, i; BADARGS(3, 3, " oldnick newnick"); u = get_user_by_handle(userlist, argv[1]); if (!u) x = 0; else { strncpyz(newhand, argv[2], sizeof newhand); for (i = 0; i < strlen(newhand); i++) if (((unsigned char) newhand[i] <= 32) || (newhand[i] == '@')) newhand[i] = '?'; if (strchr(BADHANDCHARS, newhand[0]) != NULL) x = 0; else if (strlen(newhand) < 1) x = 0; else if (get_user_by_handle(userlist, newhand)) x = 0; else if (!egg_strcasecmp(botnetnick, newhand) && (!(u->flags & USER_BOT) || nextbot(argv[1]) != -1)) x = 0; else if (newhand[0] == '*') x = 0; } if (x) x = change_handle(u, newhand); Tcl_AppendResult(irp, x ? "1" : "0", NULL); return TCL_OK; } static int tcl_getting_users STDVAR { int i; BADARGS(1, 1, ""); for (i = 0; i < dcc_total; i++) { if (dcc[i].type == &DCC_BOT && dcc[i].status & STAT_GETTING) { Tcl_AppendResult(irp, "1", NULL); return TCL_OK; } } Tcl_AppendResult(irp, "0", NULL); return TCL_OK; } static int tcl_isignore STDVAR { BADARGS(2, 2, " nick!user@host"); Tcl_AppendResult(irp, match_ignore(argv[1]) ? "1" : "0", NULL); return TCL_OK; } static int tcl_newignore STDVAR { time_t expire_time; char ign[UHOSTLEN], cmt[66], from[HANDLEN + 1]; BADARGS(4, 5, " hostmask creator comment ?lifetime?"); strncpyz(ign, argv[1], sizeof ign); strncpyz(from, argv[2], sizeof from); strncpyz(cmt, argv[3], sizeof cmt); if (argc == 4) expire_time = now + (60 * ignore_time); else { if (argc == 5 && atol(argv[4]) == 0) expire_time = 0L; else expire_time = now + (60 * atol(argv[4])); /* This is a potential crash. FIXME -poptix */ } addignore(ign, from, cmt, expire_time); return TCL_OK; } static int tcl_killignore STDVAR { BADARGS(2, 2, " hostmask"); Tcl_AppendResult(irp, delignore(argv[1]) ? "1" : "0", NULL); return TCL_OK; } static int tcl_ignorelist STDVAR { char expire[11], added[11], *p; long tv; EGG_CONST char *list[5]; struct igrec *i; BADARGS(1, 1, ""); for (i = global_ign; i; i = i->next) { list[0] = i->igmask; list[1] = i->msg; tv = i->expire; egg_snprintf(expire, sizeof expire, "%lu", tv); list[2] = expire; tv = i->added; egg_snprintf(added, sizeof added, "%lu", tv); list[3] = added; list[4] = i->user; p = Tcl_Merge(5, list); Tcl_AppendElement(irp, p); Tcl_Free((char *) p); } return TCL_OK; } static int tcl_getuser STDVAR { struct user_entry_type *et; struct userrec *u; struct user_entry *e; BADARGS(3, -1, " handle type"); if (!(et = find_entry_type(argv[2])) && egg_strcasecmp(argv[2], "HANDLE")) { Tcl_AppendResult(irp, "No such info type: ", argv[2], NULL); return TCL_ERROR; } if (!(u = get_user_by_handle(userlist, argv[1]))) { if (argv[1][0] != '*') { Tcl_AppendResult(irp, "No such user.", NULL); return TCL_ERROR; } else return TCL_OK; /* silently ignore user */ } if (!egg_strcasecmp(argv[2], "HANDLE")) Tcl_AppendResult(irp, u->handle, NULL); else { e = find_user_entry(et, u); if (e) return et->tcl_get(irp, u, e, argc, argv); } return TCL_OK; } static int tcl_setuser STDVAR { struct user_entry_type *et; struct userrec *u; struct user_entry *e; int r; module_entry *me; BADARGS(3, -1, " handle type ?setting....?"); if (!(et = find_entry_type(argv[2]))) { Tcl_AppendResult(irp, "No such info type: ", argv[2], NULL); return TCL_ERROR; } if (!(u = get_user_by_handle(userlist, argv[1]))) { if (argv[1][0] != '*') { Tcl_AppendResult(irp, "No such user.", NULL); return TCL_ERROR; } else return TCL_OK; /* Silently ignore user * */ } me = module_find("irc", 0, 0); if (me && !strcasecmp(argv[2], "hosts") && argc == 3) { Function *func = me->funcs; (func[IRC_CHECK_THIS_USER]) (argv[1], 1, NULL); } if (!(e = find_user_entry(et, u))) { e = user_malloc(sizeof(struct user_entry)); e->type = et; e->name = NULL; e->u.list = NULL; list_insert((&(u->entries)), e); } r = et->tcl_set(irp, u, e, argc, argv); /* Yeah... e is freed, and we read it... (tcl: setuser hand HOSTS none) */ if ((!e->u.list) && (egg_list_delete((struct list_type **) &(u->entries), (struct list_type *) e))) nfree(e); /* else maybe already freed... (entry_type==HOSTS) <drummer> */ if (me && !strcasecmp(argv[2], "hosts") && argc == 4) { Function *func = me->funcs; (func[IRC_CHECK_THIS_USER]) (argv[1], 0, NULL); } return r; } tcl_cmds tcluser_cmds[] = { {"countusers", tcl_countusers}, {"validuser", tcl_validuser}, {"finduser", tcl_finduser}, {"passwdok", tcl_passwdOk}, {"chattr", tcl_chattr}, {"botattr", tcl_botattr}, {"matchattr", tcl_matchattr}, {"matchchanattr", tcl_matchattr}, {"adduser", tcl_adduser}, {"addbot", tcl_addbot}, {"deluser", tcl_deluser}, {"delhost", tcl_delhost}, {"userlist", tcl_userlist}, {"save", tcl_save}, {"reload", tcl_reload}, {"chhandle", tcl_chhandle}, {"chnick", tcl_chhandle}, {"getting-users", tcl_getting_users}, {"isignore", tcl_isignore}, {"newignore", tcl_newignore}, {"killignore", tcl_killignore}, {"ignorelist", tcl_ignorelist}, {"getuser", tcl_getuser}, {"setuser", tcl_setuser}, {NULL, NULL} };
poppabear8883/ViperBot
src/tcluser.c
C
gpl-2.0
16,828
/* [Discuz!] (C)2001-2099 Comsenz Inc. This is NOT a freeware, use is subject to license terms $Id: portal_upload.js 32590 2013-02-22 09:42:48Z monkey $ */ var nowid = 0; var extensions = ''; function addAttach() { var newnode = $('upload').cloneNode(true); var id = nowid; var tags; newnode.id = 'upload_' + id; tags = newnode.getElementsByTagName('input'); for(i = 0;i < tags.length;i++) { if(tags[i].name == 'attach') { tags[i].id = 'attach_' + id; tags[i].name = 'attach'; tags[i].onchange = function() {this.form.action = this.form.action.replace(/catid\=\d/, 'catid='+$('catid').value);insertAttach(id)}; tags[i].unselectable = 'on'; } } tags = newnode.getElementsByTagName('span'); for(i = 0;i < tags.length;i++) { if(tags[i].id == 'localfile') { tags[i].id = 'localfile_' + id; } } nowid++; $('attachbody').appendChild(newnode); } function insertAttach(id) { var path = $('attach_' + id).value; if(path == '') { return; } var ext = path.lastIndexOf('.') == -1 ? '' : path.substr(path.lastIndexOf('.') + 1, path.length).toLowerCase(); var re = new RegExp("(^|\\s|,)" + ext + "($|\\s|,)", "ig"); if(extensions != '' && (re.exec(extensions) == null || ext == '')) { alert('¹ï¤£°_¡A¤£¤ä«ù¤W¶Ç¦¹Ãþ¤å¥ó'); return; } var localfile = $('attach_' + id).value.substr($('attach_' + id).value.replace(/\\/g, '/').lastIndexOf('/') + 1); $('localfile_' + id).innerHTML = localfile + ' ¤W¶Ç¤¤...'; $('attach_' + id).style.display = 'none'; $('upload_' + id).action += '&attach_target_id=' + id; $('upload_' + id).submit(); addAttach(); } function deleteAttach(attachid, url) { ajaxget(url); $('attach_list_' + attachid).style.display = 'none'; } function setConver(attach) { $('conver').value = attach; } addAttach();
Shallmay14/Qiandynasty
forum/static/js/portal_upload.js
JavaScript
gpl-2.0
1,782
/* * linux/fs/compat.c * * Kernel compatibililty routines for e.g. 32 bit syscall support * on 64 bit kernels. * * Copyright (C) 2002 Stephen Rothwell, IBM Corporation * Copyright (C) 1997-2000 Jakub Jelinek (jakub@redhat.com) * Copyright (C) 1998 Eddie C. Dost (ecd@skynet.be) * Copyright (C) 2001,2002 Andi Kleen, SuSE Labs * Copyright (C) 2003 Pavel Machek (pavel@suse.cz) * * 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. */ #include <linux/kernel.h> #include <linux/linkage.h> #include <linux/compat.h> #include <linux/errno.h> #include <linux/time.h> #include <linux/fs.h> #include <linux/fcntl.h> #include <linux/namei.h> #include <linux/file.h> #include <linux/fdtable.h> #include <linux/vfs.h> #include <linux/ioctl.h> #include <linux/init.h> #include <linux/smb.h> #include <linux/smb_mount.h> #include <linux/ncp_mount.h> #include <linux/nfs4_mount.h> #include <linux/syscalls.h> #include <linux/ctype.h> #include <linux/module.h> #include <linux/dirent.h> #include <linux/fsnotify.h> #include <linux/highuid.h> #include <linux/sunrpc/svc.h> #include <linux/nfsd/nfsd.h> #include <linux/nfsd/syscall.h> #include <linux/personality.h> #include <linux/rwsem.h> #include <linux/tsacct_kern.h> #include <linux/security.h> #include <linux/highmem.h> #include <linux/signal.h> #include <linux/poll.h> #include <linux/mm.h> #include <linux/eventpoll.h> #include <linux/fs_struct.h> #include <asm/uaccess.h> #include <asm/mmu_context.h> #include <asm/ioctls.h> #include "internal.h" int compat_log = 1; int compat_printk(const char *fmt, ...) { va_list ap; int ret; if (!compat_log) return 0; va_start(ap, fmt); ret = vprintk(fmt, ap); va_end(ap); return ret; } #include "read_write.h" /* * Not all architectures have sys_utime, so implement this in terms * of sys_utimes. */ asmlinkage long compat_sys_utime(char __user *filename, struct compat_utimbuf __user *t) { struct timespec tv[2]; if (t) { if (get_user(tv[0].tv_sec, &t->actime) || get_user(tv[1].tv_sec, &t->modtime)) return -EFAULT; tv[0].tv_nsec = 0; tv[1].tv_nsec = 0; } return do_utimes(AT_FDCWD, filename, t ? tv : NULL, 0); } asmlinkage long compat_sys_utimensat(unsigned int dfd, char __user *filename, struct compat_timespec __user *t, int flags) { struct timespec tv[2]; if (t) { if (get_compat_timespec(&tv[0], &t[0]) || get_compat_timespec(&tv[1], &t[1])) return -EFAULT; if ((tv[0].tv_nsec == UTIME_OMIT || tv[0].tv_nsec == UTIME_NOW) && tv[0].tv_sec != 0) return -EINVAL; if ((tv[1].tv_nsec == UTIME_OMIT || tv[1].tv_nsec == UTIME_NOW) && tv[1].tv_sec != 0) return -EINVAL; if (tv[0].tv_nsec == UTIME_OMIT && tv[1].tv_nsec == UTIME_OMIT) return 0; } return do_utimes(dfd, filename, t ? tv : NULL, flags); } asmlinkage long compat_sys_futimesat(unsigned int dfd, char __user *filename, struct compat_timeval __user *t) { struct timespec tv[2]; if (t) { if (get_user(tv[0].tv_sec, &t[0].tv_sec) || get_user(tv[0].tv_nsec, &t[0].tv_usec) || get_user(tv[1].tv_sec, &t[1].tv_sec) || get_user(tv[1].tv_nsec, &t[1].tv_usec)) return -EFAULT; if (tv[0].tv_nsec >= 1000000 || tv[0].tv_nsec < 0 || tv[1].tv_nsec >= 1000000 || tv[1].tv_nsec < 0) return -EINVAL; tv[0].tv_nsec *= 1000; tv[1].tv_nsec *= 1000; } return do_utimes(dfd, filename, t ? tv : NULL, 0); } asmlinkage long compat_sys_utimes(char __user *filename, struct compat_timeval __user *t) { return compat_sys_futimesat(AT_FDCWD, filename, t); } static int cp_compat_stat(struct kstat *stat, struct compat_stat __user *ubuf) { compat_ino_t ino = stat->ino; typeof(ubuf->st_uid) uid = 0; typeof(ubuf->st_gid) gid = 0; int err; SET_UID(uid, stat->uid); SET_GID(gid, stat->gid); if ((u64) stat->size > MAX_NON_LFS || !old_valid_dev(stat->dev) || !old_valid_dev(stat->rdev)) return -EOVERFLOW; if (sizeof(ino) < sizeof(stat->ino) && ino != stat->ino) return -EOVERFLOW; if (clear_user(ubuf, sizeof(*ubuf))) return -EFAULT; err = __put_user(old_encode_dev(stat->dev), &ubuf->st_dev); err |= __put_user(ino, &ubuf->st_ino); err |= __put_user(stat->mode, &ubuf->st_mode); err |= __put_user(stat->nlink, &ubuf->st_nlink); err |= __put_user(uid, &ubuf->st_uid); err |= __put_user(gid, &ubuf->st_gid); err |= __put_user(old_encode_dev(stat->rdev), &ubuf->st_rdev); err |= __put_user(stat->size, &ubuf->st_size); err |= __put_user(stat->atime.tv_sec, &ubuf->st_atime); err |= __put_user(stat->atime.tv_nsec, &ubuf->st_atime_nsec); err |= __put_user(stat->mtime.tv_sec, &ubuf->st_mtime); err |= __put_user(stat->mtime.tv_nsec, &ubuf->st_mtime_nsec); err |= __put_user(stat->ctime.tv_sec, &ubuf->st_ctime); err |= __put_user(stat->ctime.tv_nsec, &ubuf->st_ctime_nsec); err |= __put_user(stat->blksize, &ubuf->st_blksize); err |= __put_user(stat->blocks, &ubuf->st_blocks); return err; } asmlinkage long compat_sys_newstat(char __user * filename, struct compat_stat __user *statbuf) { struct kstat stat; int error; error = vfs_stat(filename, &stat); if (error) return error; return cp_compat_stat(&stat, statbuf); } asmlinkage long compat_sys_newlstat(char __user * filename, struct compat_stat __user *statbuf) { struct kstat stat; int error; error = vfs_lstat(filename, &stat); if (error) return error; return cp_compat_stat(&stat, statbuf); } #ifndef __ARCH_WANT_STAT64 asmlinkage long compat_sys_newfstatat(unsigned int dfd, char __user *filename, struct compat_stat __user *statbuf, int flag) { struct kstat stat; int error; error = vfs_fstatat(dfd, filename, &stat, flag); if (error) return error; return cp_compat_stat(&stat, statbuf); } #endif asmlinkage long compat_sys_newfstat(unsigned int fd, struct compat_stat __user * statbuf) { struct kstat stat; int error = vfs_fstat(fd, &stat); if (!error) error = cp_compat_stat(&stat, statbuf); return error; } static int put_compat_statfs(struct compat_statfs __user *ubuf, struct kstatfs *kbuf) { if (sizeof ubuf->f_blocks == 4) { if ((kbuf->f_blocks | kbuf->f_bfree | kbuf->f_bavail | kbuf->f_bsize | kbuf->f_frsize) & 0xffffffff00000000ULL) return -EOVERFLOW; /* f_files and f_ffree may be -1; it's okay * to stuff that into 32 bits */ if (kbuf->f_files != 0xffffffffffffffffULL && (kbuf->f_files & 0xffffffff00000000ULL)) return -EOVERFLOW; if (kbuf->f_ffree != 0xffffffffffffffffULL && (kbuf->f_ffree & 0xffffffff00000000ULL)) return -EOVERFLOW; } if (!access_ok(VERIFY_WRITE, ubuf, sizeof(*ubuf)) || __put_user(kbuf->f_type, &ubuf->f_type) || __put_user(kbuf->f_bsize, &ubuf->f_bsize) || __put_user(kbuf->f_blocks, &ubuf->f_blocks) || __put_user(kbuf->f_bfree, &ubuf->f_bfree) || __put_user(kbuf->f_bavail, &ubuf->f_bavail) || __put_user(kbuf->f_files, &ubuf->f_files) || __put_user(kbuf->f_ffree, &ubuf->f_ffree) || __put_user(kbuf->f_namelen, &ubuf->f_namelen) || __put_user(kbuf->f_fsid.val[0], &ubuf->f_fsid.val[0]) || __put_user(kbuf->f_fsid.val[1], &ubuf->f_fsid.val[1]) || __put_user(kbuf->f_frsize, &ubuf->f_frsize) || __put_user(0, &ubuf->f_spare[0]) || __put_user(0, &ubuf->f_spare[1]) || __put_user(0, &ubuf->f_spare[2]) || __put_user(0, &ubuf->f_spare[3]) || __put_user(0, &ubuf->f_spare[4])) return -EFAULT; return 0; } /* * The following statfs calls are copies of code from fs/open.c and * should be checked against those from time to time */ asmlinkage long compat_sys_statfs(const char __user *pathname, struct compat_statfs __user *buf) { struct path path; int error; error = user_path(pathname, &path); if (!error) { struct kstatfs tmp; error = vfs_statfs(path.dentry, &tmp); if (!error) error = put_compat_statfs(buf, &tmp); path_put(&path); } return error; } asmlinkage long compat_sys_fstatfs(unsigned int fd, struct compat_statfs __user *buf) { struct file * file; struct kstatfs tmp; int error; error = -EBADF; file = fget(fd); if (!file) goto out; error = vfs_statfs(file->f_path.dentry, &tmp); if (!error) error = put_compat_statfs(buf, &tmp); fput(file); out: return error; } static int put_compat_statfs64(struct compat_statfs64 __user *ubuf, struct kstatfs *kbuf) { if (sizeof ubuf->f_blocks == 4) { if ((kbuf->f_blocks | kbuf->f_bfree | kbuf->f_bavail | kbuf->f_bsize | kbuf->f_frsize) & 0xffffffff00000000ULL) return -EOVERFLOW; /* f_files and f_ffree may be -1; it's okay * to stuff that into 32 bits */ if (kbuf->f_files != 0xffffffffffffffffULL && (kbuf->f_files & 0xffffffff00000000ULL)) return -EOVERFLOW; if (kbuf->f_ffree != 0xffffffffffffffffULL && (kbuf->f_ffree & 0xffffffff00000000ULL)) return -EOVERFLOW; } if (!access_ok(VERIFY_WRITE, ubuf, sizeof(*ubuf)) || __put_user(kbuf->f_type, &ubuf->f_type) || __put_user(kbuf->f_bsize, &ubuf->f_bsize) || __put_user(kbuf->f_blocks, &ubuf->f_blocks) || __put_user(kbuf->f_bfree, &ubuf->f_bfree) || __put_user(kbuf->f_bavail, &ubuf->f_bavail) || __put_user(kbuf->f_files, &ubuf->f_files) || __put_user(kbuf->f_ffree, &ubuf->f_ffree) || __put_user(kbuf->f_namelen, &ubuf->f_namelen) || __put_user(kbuf->f_fsid.val[0], &ubuf->f_fsid.val[0]) || __put_user(kbuf->f_fsid.val[1], &ubuf->f_fsid.val[1]) || __put_user(kbuf->f_frsize, &ubuf->f_frsize)) return -EFAULT; return 0; } asmlinkage long compat_sys_statfs64(const char __user *pathname, compat_size_t sz, struct compat_statfs64 __user *buf) { struct path path; int error; if (sz != sizeof(*buf)) return -EINVAL; error = user_path(pathname, &path); if (!error) { struct kstatfs tmp; error = vfs_statfs(path.dentry, &tmp); if (!error) error = put_compat_statfs64(buf, &tmp); path_put(&path); } return error; } asmlinkage long compat_sys_fstatfs64(unsigned int fd, compat_size_t sz, struct compat_statfs64 __user *buf) { struct file * file; struct kstatfs tmp; int error; if (sz != sizeof(*buf)) return -EINVAL; error = -EBADF; file = fget(fd); if (!file) goto out; error = vfs_statfs(file->f_path.dentry, &tmp); if (!error) error = put_compat_statfs64(buf, &tmp); fput(file); out: return error; } /* * This is a copy of sys_ustat, just dealing with a structure layout. * Given how simple this syscall is that apporach is more maintainable * than the various conversion hacks. */ asmlinkage long compat_sys_ustat(unsigned dev, struct compat_ustat __user *u) { struct super_block *sb; struct compat_ustat tmp; struct kstatfs sbuf; int err; sb = user_get_super(new_decode_dev(dev)); if (!sb) return -EINVAL; err = vfs_statfs(sb->s_root, &sbuf); drop_super(sb); if (err) return err; memset(&tmp, 0, sizeof(struct compat_ustat)); tmp.f_tfree = sbuf.f_bfree; tmp.f_tinode = sbuf.f_ffree; if (copy_to_user(u, &tmp, sizeof(struct compat_ustat))) return -EFAULT; return 0; } static int get_compat_flock(struct flock *kfl, struct compat_flock __user *ufl) { if (!access_ok(VERIFY_READ, ufl, sizeof(*ufl)) || __get_user(kfl->l_type, &ufl->l_type) || __get_user(kfl->l_whence, &ufl->l_whence) || __get_user(kfl->l_start, &ufl->l_start) || __get_user(kfl->l_len, &ufl->l_len) || __get_user(kfl->l_pid, &ufl->l_pid)) return -EFAULT; return 0; } static int put_compat_flock(struct flock *kfl, struct compat_flock __user *ufl) { if (!access_ok(VERIFY_WRITE, ufl, sizeof(*ufl)) || __put_user(kfl->l_type, &ufl->l_type) || __put_user(kfl->l_whence, &ufl->l_whence) || __put_user(kfl->l_start, &ufl->l_start) || __put_user(kfl->l_len, &ufl->l_len) || __put_user(kfl->l_pid, &ufl->l_pid)) return -EFAULT; return 0; } #ifndef HAVE_ARCH_GET_COMPAT_FLOCK64 static int get_compat_flock64(struct flock *kfl, struct compat_flock64 __user *ufl) { if (!access_ok(VERIFY_READ, ufl, sizeof(*ufl)) || __get_user(kfl->l_type, &ufl->l_type) || __get_user(kfl->l_whence, &ufl->l_whence) || __get_user(kfl->l_start, &ufl->l_start) || __get_user(kfl->l_len, &ufl->l_len) || __get_user(kfl->l_pid, &ufl->l_pid)) return -EFAULT; return 0; } #endif #ifndef HAVE_ARCH_PUT_COMPAT_FLOCK64 static int put_compat_flock64(struct flock *kfl, struct compat_flock64 __user *ufl) { if (!access_ok(VERIFY_WRITE, ufl, sizeof(*ufl)) || __put_user(kfl->l_type, &ufl->l_type) || __put_user(kfl->l_whence, &ufl->l_whence) || __put_user(kfl->l_start, &ufl->l_start) || __put_user(kfl->l_len, &ufl->l_len) || __put_user(kfl->l_pid, &ufl->l_pid)) return -EFAULT; return 0; } #endif asmlinkage long compat_sys_fcntl64(unsigned int fd, unsigned int cmd, unsigned long arg) { mm_segment_t old_fs; struct flock f; long ret; switch (cmd) { case F_GETLK: case F_SETLK: case F_SETLKW: ret = get_compat_flock(&f, compat_ptr(arg)); if (ret != 0) break; old_fs = get_fs(); set_fs(KERNEL_DS); ret = sys_fcntl(fd, cmd, (unsigned long)&f); set_fs(old_fs); if (cmd == F_GETLK && ret == 0) { /* GETLK was successful and we need to return the data... * but it needs to fit in the compat structure. * l_start shouldn't be too big, unless the original * start + end is greater than COMPAT_OFF_T_MAX, in which * case the app was asking for trouble, so we return * -EOVERFLOW in that case. * l_len could be too big, in which case we just truncate it, * and only allow the app to see that part of the conflicting * lock that might make sense to it anyway */ if (f.l_start > COMPAT_OFF_T_MAX) ret = -EOVERFLOW; if (f.l_len > COMPAT_OFF_T_MAX) f.l_len = COMPAT_OFF_T_MAX; if (ret == 0) ret = put_compat_flock(&f, compat_ptr(arg)); } break; case F_GETLK64: case F_SETLK64: case F_SETLKW64: ret = get_compat_flock64(&f, compat_ptr(arg)); if (ret != 0) break; old_fs = get_fs(); set_fs(KERNEL_DS); ret = sys_fcntl(fd, (cmd == F_GETLK64) ? F_GETLK : ((cmd == F_SETLK64) ? F_SETLK : F_SETLKW), (unsigned long)&f); set_fs(old_fs); if (cmd == F_GETLK64 && ret == 0) { /* need to return lock information - see above for commentary */ if (f.l_start > COMPAT_LOFF_T_MAX) ret = -EOVERFLOW; if (f.l_len > COMPAT_LOFF_T_MAX) f.l_len = COMPAT_LOFF_T_MAX; if (ret == 0) ret = put_compat_flock64(&f, compat_ptr(arg)); } break; default: ret = sys_fcntl(fd, cmd, arg); break; } return ret; } asmlinkage long compat_sys_fcntl(unsigned int fd, unsigned int cmd, unsigned long arg) { if ((cmd == F_GETLK64) || (cmd == F_SETLK64) || (cmd == F_SETLKW64)) return -EINVAL; return compat_sys_fcntl64(fd, cmd, arg); } asmlinkage long compat_sys_io_setup(unsigned nr_reqs, u32 __user *ctx32p) { long ret; aio_context_t ctx64; mm_segment_t oldfs = get_fs(); if (unlikely(get_user(ctx64, ctx32p))) return -EFAULT; set_fs(KERNEL_DS); /* The __user pointer cast is valid because of the set_fs() */ ret = sys_io_setup(nr_reqs, (aio_context_t __user *) &ctx64); set_fs(oldfs); /* truncating is ok because it's a user address */ if (!ret) ret = put_user((u32) ctx64, ctx32p); return ret; } asmlinkage long compat_sys_io_getevents(aio_context_t ctx_id, unsigned long min_nr, unsigned long nr, struct io_event __user *events, struct compat_timespec __user *timeout) { long ret; struct timespec t; struct timespec __user *ut = NULL; ret = -EFAULT; if (unlikely(!access_ok(VERIFY_WRITE, events, nr * sizeof(struct io_event)))) goto out; if (timeout) { if (get_compat_timespec(&t, timeout)) goto out; ut = compat_alloc_user_space(sizeof(*ut)); if (copy_to_user(ut, &t, sizeof(t)) ) goto out; } ret = sys_io_getevents(ctx_id, min_nr, nr, events, ut); out: return ret; } static inline long copy_iocb(long nr, u32 __user *ptr32, struct iocb __user * __user *ptr64) { compat_uptr_t uptr; int i; for (i = 0; i < nr; ++i) { if (get_user(uptr, ptr32 + i)) return -EFAULT; if (put_user(compat_ptr(uptr), ptr64 + i)) return -EFAULT; } return 0; } #define MAX_AIO_SUBMITS (PAGE_SIZE/sizeof(struct iocb *)) asmlinkage long compat_sys_io_submit(aio_context_t ctx_id, int nr, u32 __user *iocb) { struct iocb __user * __user *iocb64; long ret; if (unlikely(nr < 0)) return -EINVAL; if (nr > MAX_AIO_SUBMITS) nr = MAX_AIO_SUBMITS; iocb64 = compat_alloc_user_space(nr * sizeof(*iocb64)); ret = copy_iocb(nr, iocb, iocb64); if (!ret) ret = sys_io_submit(ctx_id, nr, iocb64); return ret; } struct compat_ncp_mount_data { compat_int_t version; compat_uint_t ncp_fd; __compat_uid_t mounted_uid; compat_pid_t wdog_pid; unsigned char mounted_vol[NCP_VOLNAME_LEN + 1]; compat_uint_t time_out; compat_uint_t retry_count; compat_uint_t flags; __compat_uid_t uid; __compat_gid_t gid; compat_mode_t file_mode; compat_mode_t dir_mode; }; struct compat_ncp_mount_data_v4 { compat_int_t version; compat_ulong_t flags; compat_ulong_t mounted_uid; compat_long_t wdog_pid; compat_uint_t ncp_fd; compat_uint_t time_out; compat_uint_t retry_count; compat_ulong_t uid; compat_ulong_t gid; compat_ulong_t file_mode; compat_ulong_t dir_mode; }; static void *do_ncp_super_data_conv(void *raw_data) { int version = *(unsigned int *)raw_data; if (version == 3) { struct compat_ncp_mount_data *c_n = raw_data; struct ncp_mount_data *n = raw_data; n->dir_mode = c_n->dir_mode; n->file_mode = c_n->file_mode; n->gid = c_n->gid; n->uid = c_n->uid; memmove (n->mounted_vol, c_n->mounted_vol, (sizeof (c_n->mounted_vol) + 3 * sizeof (unsigned int))); n->wdog_pid = c_n->wdog_pid; n->mounted_uid = c_n->mounted_uid; } else if (version == 4) { struct compat_ncp_mount_data_v4 *c_n = raw_data; struct ncp_mount_data_v4 *n = raw_data; n->dir_mode = c_n->dir_mode; n->file_mode = c_n->file_mode; n->gid = c_n->gid; n->uid = c_n->uid; n->retry_count = c_n->retry_count; n->time_out = c_n->time_out; n->ncp_fd = c_n->ncp_fd; n->wdog_pid = c_n->wdog_pid; n->mounted_uid = c_n->mounted_uid; n->flags = c_n->flags; } else if (version != 5) { return NULL; } return raw_data; } struct compat_smb_mount_data { compat_int_t version; __compat_uid_t mounted_uid; __compat_uid_t uid; __compat_gid_t gid; compat_mode_t file_mode; compat_mode_t dir_mode; }; static void *do_smb_super_data_conv(void *raw_data) { struct smb_mount_data *s = raw_data; struct compat_smb_mount_data *c_s = raw_data; if (c_s->version != SMB_MOUNT_OLDVERSION) goto out; s->dir_mode = c_s->dir_mode; s->file_mode = c_s->file_mode; s->gid = c_s->gid; s->uid = c_s->uid; s->mounted_uid = c_s->mounted_uid; out: return raw_data; } struct compat_nfs_string { compat_uint_t len; compat_uptr_t data; }; static inline void compat_nfs_string(struct nfs_string *dst, struct compat_nfs_string *src) { dst->data = compat_ptr(src->data); dst->len = src->len; } struct compat_nfs4_mount_data_v1 { compat_int_t version; compat_int_t flags; compat_int_t rsize; compat_int_t wsize; compat_int_t timeo; compat_int_t retrans; compat_int_t acregmin; compat_int_t acregmax; compat_int_t acdirmin; compat_int_t acdirmax; struct compat_nfs_string client_addr; struct compat_nfs_string mnt_path; struct compat_nfs_string hostname; compat_uint_t host_addrlen; compat_uptr_t host_addr; compat_int_t proto; compat_int_t auth_flavourlen; compat_uptr_t auth_flavours; }; static int do_nfs4_super_data_conv(void *raw_data) { int version = *(compat_uint_t *) raw_data; if (version == 1) { struct compat_nfs4_mount_data_v1 *raw = raw_data; struct nfs4_mount_data *real = raw_data; /* copy the fields backwards */ real->auth_flavours = compat_ptr(raw->auth_flavours); real->auth_flavourlen = raw->auth_flavourlen; real->proto = raw->proto; real->host_addr = compat_ptr(raw->host_addr); real->host_addrlen = raw->host_addrlen; compat_nfs_string(&real->hostname, &raw->hostname); compat_nfs_string(&real->mnt_path, &raw->mnt_path); compat_nfs_string(&real->client_addr, &raw->client_addr); real->acdirmax = raw->acdirmax; real->acdirmin = raw->acdirmin; real->acregmax = raw->acregmax; real->acregmin = raw->acregmin; real->retrans = raw->retrans; real->timeo = raw->timeo; real->wsize = raw->wsize; real->rsize = raw->rsize; real->flags = raw->flags; real->version = raw->version; } return 0; } #define SMBFS_NAME "smbfs" #define NCPFS_NAME "ncpfs" #define NFS4_NAME "nfs4" asmlinkage long compat_sys_mount(char __user * dev_name, char __user * dir_name, char __user * type, unsigned long flags, void __user * data) { unsigned long type_page; unsigned long data_page; unsigned long dev_page; char *dir_page; int retval; retval = copy_mount_options (type, &type_page); if (retval < 0) goto out; dir_page = getname(dir_name); retval = PTR_ERR(dir_page); if (IS_ERR(dir_page)) goto out1; retval = copy_mount_options (dev_name, &dev_page); if (retval < 0) goto out2; retval = copy_mount_options (data, &data_page); if (retval < 0) goto out3; retval = -EINVAL; if (type_page && data_page) { if (!strcmp((char *)type_page, SMBFS_NAME)) { do_smb_super_data_conv((void *)data_page); } else if (!strcmp((char *)type_page, NCPFS_NAME)) { do_ncp_super_data_conv((void *)data_page); } else if (!strcmp((char *)type_page, NFS4_NAME)) { if (do_nfs4_super_data_conv((void *) data_page)) goto out4; } } retval = do_mount((char*)dev_page, dir_page, (char*)type_page, flags, (void*)data_page); out4: free_page(data_page); out3: free_page(dev_page); out2: putname(dir_page); out1: free_page(type_page); out: return retval; } #define NAME_OFFSET(de) ((int) ((de)->d_name - (char __user *) (de))) struct compat_old_linux_dirent { compat_ulong_t d_ino; compat_ulong_t d_offset; unsigned short d_namlen; char d_name[1]; }; struct compat_readdir_callback { struct compat_old_linux_dirent __user *dirent; int result; }; static int compat_fillonedir(void *__buf, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { struct compat_readdir_callback *buf = __buf; struct compat_old_linux_dirent __user *dirent; compat_ulong_t d_ino; if (buf->result) return -EINVAL; d_ino = ino; if (sizeof(d_ino) < sizeof(ino) && d_ino != ino) { buf->result = -EOVERFLOW; return -EOVERFLOW; } buf->result++; dirent = buf->dirent; if (!access_ok(VERIFY_WRITE, dirent, (unsigned long)(dirent->d_name + namlen + 1) - (unsigned long)dirent)) goto efault; if ( __put_user(d_ino, &dirent->d_ino) || __put_user(offset, &dirent->d_offset) || __put_user(namlen, &dirent->d_namlen) || __copy_to_user(dirent->d_name, name, namlen) || __put_user(0, dirent->d_name + namlen)) goto efault; return 0; efault: buf->result = -EFAULT; return -EFAULT; } asmlinkage long compat_sys_old_readdir(unsigned int fd, struct compat_old_linux_dirent __user *dirent, unsigned int count) { int error; struct file *file; struct compat_readdir_callback buf; error = -EBADF; file = fget(fd); if (!file) goto out; buf.result = 0; buf.dirent = dirent; error = vfs_readdir(file, compat_fillonedir, &buf); if (buf.result) error = buf.result; fput(file); out: return error; } struct compat_linux_dirent { compat_ulong_t d_ino; compat_ulong_t d_off; unsigned short d_reclen; char d_name[1]; }; struct compat_getdents_callback { struct compat_linux_dirent __user *current_dir; struct compat_linux_dirent __user *previous; int count; int error; }; static int compat_filldir(void *__buf, const char *name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { struct compat_linux_dirent __user * dirent; struct compat_getdents_callback *buf = __buf; compat_ulong_t d_ino; int reclen = ALIGN(NAME_OFFSET(dirent) + namlen + 2, sizeof(compat_long_t)); buf->error = -EINVAL; /* only used if we fail.. */ if (reclen > buf->count) return -EINVAL; d_ino = ino; if (sizeof(d_ino) < sizeof(ino) && d_ino != ino) { buf->error = -EOVERFLOW; return -EOVERFLOW; } dirent = buf->previous; if (dirent) { if (__put_user(offset, &dirent->d_off)) goto efault; } dirent = buf->current_dir; if (__put_user(d_ino, &dirent->d_ino)) goto efault; if (__put_user(reclen, &dirent->d_reclen)) goto efault; if (copy_to_user(dirent->d_name, name, namlen)) goto efault; if (__put_user(0, dirent->d_name + namlen)) goto efault; if (__put_user(d_type, (char __user *) dirent + reclen - 1)) goto efault; buf->previous = dirent; dirent = (void __user *)dirent + reclen; buf->current_dir = dirent; buf->count -= reclen; return 0; efault: buf->error = -EFAULT; return -EFAULT; } asmlinkage long compat_sys_getdents(unsigned int fd, struct compat_linux_dirent __user *dirent, unsigned int count) { struct file * file; struct compat_linux_dirent __user * lastdirent; struct compat_getdents_callback buf; int error; error = -EFAULT; if (!access_ok(VERIFY_WRITE, dirent, count)) goto out; error = -EBADF; file = fget(fd); if (!file) goto out; buf.current_dir = dirent; buf.previous = NULL; buf.count = count; buf.error = 0; error = vfs_readdir(file, compat_filldir, &buf); if (error >= 0) error = buf.error; lastdirent = buf.previous; if (lastdirent) { if (put_user(file->f_pos, &lastdirent->d_off)) error = -EFAULT; else error = count - buf.count; } fput(file); out: return error; } #ifndef __ARCH_OMIT_COMPAT_SYS_GETDENTS64 struct compat_getdents_callback64 { struct linux_dirent64 __user *current_dir; struct linux_dirent64 __user *previous; int count; int error; }; static int compat_filldir64(void * __buf, const char * name, int namlen, loff_t offset, u64 ino, unsigned int d_type) { struct linux_dirent64 __user *dirent; struct compat_getdents_callback64 *buf = __buf; int jj = NAME_OFFSET(dirent); int reclen = ALIGN(jj + namlen + 1, sizeof(u64)); u64 off; buf->error = -EINVAL; /* only used if we fail.. */ if (reclen > buf->count) return -EINVAL; dirent = buf->previous; if (dirent) { if (__put_user_unaligned(offset, &dirent->d_off)) goto efault; } dirent = buf->current_dir; if (__put_user_unaligned(ino, &dirent->d_ino)) goto efault; off = 0; if (__put_user_unaligned(off, &dirent->d_off)) goto efault; if (__put_user(reclen, &dirent->d_reclen)) goto efault; if (__put_user(d_type, &dirent->d_type)) goto efault; if (copy_to_user(dirent->d_name, name, namlen)) goto efault; if (__put_user(0, dirent->d_name + namlen)) goto efault; buf->previous = dirent; dirent = (void __user *)dirent + reclen; buf->current_dir = dirent; buf->count -= reclen; return 0; efault: buf->error = -EFAULT; return -EFAULT; } asmlinkage long compat_sys_getdents64(unsigned int fd, struct linux_dirent64 __user * dirent, unsigned int count) { struct file * file; struct linux_dirent64 __user * lastdirent; struct compat_getdents_callback64 buf; int error; error = -EFAULT; if (!access_ok(VERIFY_WRITE, dirent, count)) goto out; error = -EBADF; file = fget(fd); if (!file) goto out; buf.current_dir = dirent; buf.previous = NULL; buf.count = count; buf.error = 0; error = vfs_readdir(file, compat_filldir64, &buf); if (error >= 0) error = buf.error; lastdirent = buf.previous; if (lastdirent) { typeof(lastdirent->d_off) d_off = file->f_pos; if (__put_user_unaligned(d_off, &lastdirent->d_off)) error = -EFAULT; else error = count - buf.count; } fput(file); out: return error; } #endif /* ! __ARCH_OMIT_COMPAT_SYS_GETDENTS64 */ static ssize_t compat_do_readv_writev(int type, struct file *file, const struct compat_iovec __user *uvector, unsigned long nr_segs, loff_t *pos) { compat_ssize_t tot_len; struct iovec iovstack[UIO_FASTIOV]; struct iovec *iov=iovstack, *vector; ssize_t ret; int seg; io_fn_t fn; iov_fn_t fnv; /* * SuS says "The readv() function *may* fail if the iovcnt argument * was less than or equal to 0, or greater than {IOV_MAX}. Linux has * traditionally returned zero for zero segments, so... */ ret = 0; if (nr_segs == 0) goto out; /* * First get the "struct iovec" from user memory and * verify all the pointers */ ret = -EINVAL; if ((nr_segs > UIO_MAXIOV) || (nr_segs <= 0)) goto out; if (!file->f_op) goto out; if (nr_segs > UIO_FASTIOV) { ret = -ENOMEM; iov = kmalloc(nr_segs*sizeof(struct iovec), GFP_KERNEL); if (!iov) goto out; } ret = -EFAULT; if (!access_ok(VERIFY_READ, uvector, nr_segs*sizeof(*uvector))) goto out; /* * Single unix specification: * We should -EINVAL if an element length is not >= 0 and fitting an * ssize_t. The total length is fitting an ssize_t * * Be careful here because iov_len is a size_t not an ssize_t */ tot_len = 0; vector = iov; ret = -EINVAL; for (seg = 0 ; seg < nr_segs; seg++) { compat_ssize_t tmp = tot_len; compat_ssize_t len; compat_uptr_t buf; if (__get_user(len, &uvector->iov_len) || __get_user(buf, &uvector->iov_base)) { ret = -EFAULT; goto out; } if (len < 0) /* size_t not fitting an compat_ssize_t .. */ goto out; tot_len += len; if (tot_len < tmp) /* maths overflow on the compat_ssize_t */ goto out; vector->iov_base = compat_ptr(buf); vector->iov_len = (compat_size_t) len; uvector++; vector++; } if (tot_len == 0) { ret = 0; goto out; } ret = rw_verify_area(type, file, pos, tot_len); if (ret < 0) goto out; fnv = NULL; if (type == READ) { fn = file->f_op->read; fnv = file->f_op->aio_read; } else { fn = (io_fn_t)file->f_op->write; fnv = file->f_op->aio_write; } if (fnv) ret = do_sync_readv_writev(file, iov, nr_segs, tot_len, pos, fnv); else ret = do_loop_readv_writev(file, iov, nr_segs, pos, fn); out: if (iov != iovstack) kfree(iov); if ((ret + (type == READ)) > 0) { struct dentry *dentry = file->f_path.dentry; if (type == READ) fsnotify_access(dentry); else fsnotify_modify(dentry); } return ret; } static size_t compat_readv(struct file *file, const struct compat_iovec __user *vec, unsigned long vlen, loff_t *pos) { ssize_t ret = -EBADF; if (!(file->f_mode & FMODE_READ)) goto out; ret = -EINVAL; if (!file->f_op || (!file->f_op->aio_read && !file->f_op->read)) goto out; ret = compat_do_readv_writev(READ, file, vec, vlen, pos); out: if (ret > 0) add_rchar(current, ret); inc_syscr(current); return ret; } asmlinkage ssize_t compat_sys_readv(unsigned long fd, const struct compat_iovec __user *vec, unsigned long vlen) { struct file *file; int fput_needed; ssize_t ret; file = fget_light(fd, &fput_needed); if (!file) return -EBADF; ret = compat_readv(file, vec, vlen, &file->f_pos); fput_light(file, fput_needed); return ret; } asmlinkage ssize_t compat_sys_preadv(unsigned long fd, const struct compat_iovec __user *vec, unsigned long vlen, u32 pos_low, u32 pos_high) { loff_t pos = ((loff_t)pos_high << 32) | pos_low; struct file *file; int fput_needed; ssize_t ret; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (!file) return -EBADF; ret = compat_readv(file, vec, vlen, &pos); fput_light(file, fput_needed); return ret; } static size_t compat_writev(struct file *file, const struct compat_iovec __user *vec, unsigned long vlen, loff_t *pos) { ssize_t ret = -EBADF; if (!(file->f_mode & FMODE_WRITE)) goto out; ret = -EINVAL; if (!file->f_op || (!file->f_op->aio_write && !file->f_op->write)) goto out; ret = compat_do_readv_writev(WRITE, file, vec, vlen, pos); out: if (ret > 0) add_wchar(current, ret); inc_syscw(current); return ret; } asmlinkage ssize_t compat_sys_writev(unsigned long fd, const struct compat_iovec __user *vec, unsigned long vlen) { struct file *file; int fput_needed; ssize_t ret; file = fget_light(fd, &fput_needed); if (!file) return -EBADF; ret = compat_writev(file, vec, vlen, &file->f_pos); fput_light(file, fput_needed); return ret; } asmlinkage ssize_t compat_sys_pwritev(unsigned long fd, const struct compat_iovec __user *vec, unsigned long vlen, u32 pos_low, u32 pos_high) { loff_t pos = ((loff_t)pos_high << 32) | pos_low; struct file *file; int fput_needed; ssize_t ret; if (pos < 0) return -EINVAL; file = fget_light(fd, &fput_needed); if (!file) return -EBADF; ret = compat_writev(file, vec, vlen, &pos); fput_light(file, fput_needed); return ret; } asmlinkage long compat_sys_vmsplice(int fd, const struct compat_iovec __user *iov32, unsigned int nr_segs, unsigned int flags) { unsigned i; struct iovec __user *iov; if (nr_segs > UIO_MAXIOV) return -EINVAL; iov = compat_alloc_user_space(nr_segs * sizeof(struct iovec)); for (i = 0; i < nr_segs; i++) { struct compat_iovec v; if (get_user(v.iov_base, &iov32[i].iov_base) || get_user(v.iov_len, &iov32[i].iov_len) || put_user(compat_ptr(v.iov_base), &iov[i].iov_base) || put_user(v.iov_len, &iov[i].iov_len)) return -EFAULT; } return sys_vmsplice(fd, iov, nr_segs, flags); } /* * Exactly like fs/open.c:sys_open(), except that it doesn't set the * O_LARGEFILE flag. */ asmlinkage long compat_sys_open(const char __user *filename, int flags, int mode) { return do_sys_open(AT_FDCWD, filename, flags, mode); } /* * Exactly like fs/open.c:sys_openat(), except that it doesn't set the * O_LARGEFILE flag. */ asmlinkage long compat_sys_openat(unsigned int dfd, const char __user *filename, int flags, int mode) { return do_sys_open(dfd, filename, flags, mode); } /* * compat_count() counts the number of arguments/envelopes. It is basically * a copy of count() from fs/exec.c, except that it works with 32 bit argv * and envp pointers. */ static int compat_count(compat_uptr_t __user *argv, int max) { int i = 0; if (argv != NULL) { for (;;) { compat_uptr_t p; if (get_user(p, argv)) return -EFAULT; if (!p) break; argv++; if (i++ >= max) return -E2BIG; } } return i; } /* * compat_copy_strings() is basically a copy of copy_strings() from fs/exec.c * except that it works with 32 bit argv and envp pointers. */ static int compat_copy_strings(int argc, compat_uptr_t __user *argv, struct linux_binprm *bprm) { struct page *kmapped_page = NULL; char *kaddr = NULL; unsigned long kpos = 0; int ret; while (argc-- > 0) { compat_uptr_t str; int len; unsigned long pos; if (get_user(str, argv+argc) || !(len = strnlen_user(compat_ptr(str), MAX_ARG_STRLEN))) { ret = -EFAULT; goto out; } if (len > MAX_ARG_STRLEN) { ret = -E2BIG; goto out; } /* We're going to work our way backwords. */ pos = bprm->p; str += len; bprm->p -= len; while (len > 0) { int offset, bytes_to_copy; offset = pos % PAGE_SIZE; if (offset == 0) offset = PAGE_SIZE; bytes_to_copy = offset; if (bytes_to_copy > len) bytes_to_copy = len; offset -= bytes_to_copy; pos -= bytes_to_copy; str -= bytes_to_copy; len -= bytes_to_copy; if (!kmapped_page || kpos != (pos & PAGE_MASK)) { struct page *page; #ifdef CONFIG_STACK_GROWSUP ret = expand_stack_downwards(bprm->vma, pos); if (ret < 0) { /* We've exceed the stack rlimit. */ ret = -E2BIG; goto out; } #endif ret = get_user_pages(current, bprm->mm, pos, 1, 1, 1, &page, NULL); if (ret <= 0) { /* We've exceed the stack rlimit. */ ret = -E2BIG; goto out; } if (kmapped_page) { flush_kernel_dcache_page(kmapped_page); kunmap(kmapped_page); put_page(kmapped_page); } kmapped_page = page; kaddr = kmap(kmapped_page); kpos = pos & PAGE_MASK; flush_cache_page(bprm->vma, kpos, page_to_pfn(kmapped_page)); } if (copy_from_user(kaddr+offset, compat_ptr(str), bytes_to_copy)) { ret = -EFAULT; goto out; } } } ret = 0; out: if (kmapped_page) { flush_kernel_dcache_page(kmapped_page); kunmap(kmapped_page); put_page(kmapped_page); } return ret; } /* * compat_do_execve() is mostly a copy of do_execve(), with the exception * that it processes 32 bit argv and envp pointers. */ int compat_do_execve(char * filename, compat_uptr_t __user *argv, compat_uptr_t __user *envp, struct pt_regs * regs) { struct linux_binprm *bprm; struct file *file; struct files_struct *displaced; bool clear_in_exec; int retval; retval = unshare_files(&displaced); if (retval) goto out_ret; retval = -ENOMEM; bprm = kzalloc(sizeof(*bprm), GFP_KERNEL); if (!bprm) goto out_files; retval = -ERESTARTNOINTR; if (mutex_lock_interruptible(&current->cred_guard_mutex)) goto out_free; current->in_execve = 1; retval = -ENOMEM; bprm->cred = prepare_exec_creds(); if (!bprm->cred) goto out_unlock; retval = check_unsafe_exec(bprm); if (retval < 0) goto out_unlock; clear_in_exec = retval; file = open_exec(filename); retval = PTR_ERR(file); if (IS_ERR(file)) goto out_unmark; sched_exec(); bprm->file = file; bprm->filename = filename; bprm->interp = filename; retval = bprm_mm_init(bprm); if (retval) goto out_file; bprm->argc = compat_count(argv, MAX_ARG_STRINGS); if ((retval = bprm->argc) < 0) goto out; bprm->envc = compat_count(envp, MAX_ARG_STRINGS); if ((retval = bprm->envc) < 0) goto out; retval = prepare_binprm(bprm); if (retval < 0) goto out; retval = copy_strings_kernel(1, &bprm->filename, bprm); if (retval < 0) goto out; bprm->exec = bprm->p; retval = compat_copy_strings(bprm->envc, envp, bprm); if (retval < 0) goto out; retval = compat_copy_strings(bprm->argc, argv, bprm); if (retval < 0) goto out; retval = search_binary_handler(bprm, regs); if (retval < 0) goto out; /* execve succeeded */ current->fs->in_exec = 0; current->in_execve = 0; mutex_unlock(&current->cred_guard_mutex); acct_update_integrals(current); free_bprm(bprm); if (displaced) put_files_struct(displaced); return retval; out: if (bprm->mm) mmput(bprm->mm); out_file: if (bprm->file) { allow_write_access(bprm->file); fput(bprm->file); } out_unmark: if (clear_in_exec) current->fs->in_exec = 0; out_unlock: current->in_execve = 0; mutex_unlock(&current->cred_guard_mutex); out_free: free_bprm(bprm); out_files: if (displaced) reset_files_struct(displaced); out_ret: return retval; } #define __COMPAT_NFDBITS (8 * sizeof(compat_ulong_t)) static int poll_select_copy_remaining(struct timespec *end_time, void __user *p, int timeval, int ret) { struct timespec ts; if (!p) return ret; if (current->personality & STICKY_TIMEOUTS) goto sticky; /* No update for zero timeout */ if (!end_time->tv_sec && !end_time->tv_nsec) return ret; ktime_get_ts(&ts); ts = timespec_sub(*end_time, ts); if (ts.tv_sec < 0) ts.tv_sec = ts.tv_nsec = 0; if (timeval) { struct compat_timeval rtv; rtv.tv_sec = ts.tv_sec; rtv.tv_usec = ts.tv_nsec / NSEC_PER_USEC; if (!copy_to_user(p, &rtv, sizeof(rtv))) return ret; } else { struct compat_timespec rts; rts.tv_sec = ts.tv_sec; rts.tv_nsec = ts.tv_nsec; if (!copy_to_user(p, &rts, sizeof(rts))) return ret; } /* * If an application puts its timeval in read-only memory, we * don't want the Linux-specific update to the timeval to * cause a fault after the select has completed * successfully. However, because we're not updating the * timeval, we can't restart the system call. */ sticky: if (ret == -ERESTARTNOHAND) ret = -EINTR; return ret; } /* * Ooo, nasty. We need here to frob 32-bit unsigned longs to * 64-bit unsigned longs. */ static int compat_get_fd_set(unsigned long nr, compat_ulong_t __user *ufdset, unsigned long *fdset) { nr = DIV_ROUND_UP(nr, __COMPAT_NFDBITS); if (ufdset) { unsigned long odd; if (!access_ok(VERIFY_WRITE, ufdset, nr*sizeof(compat_ulong_t))) return -EFAULT; odd = nr & 1UL; nr &= ~1UL; while (nr) { unsigned long h, l; if (__get_user(l, ufdset) || __get_user(h, ufdset+1)) return -EFAULT; ufdset += 2; *fdset++ = h << 32 | l; nr -= 2; } if (odd && __get_user(*fdset, ufdset)) return -EFAULT; } else { /* Tricky, must clear full unsigned long in the * kernel fdset at the end, this makes sure that * actually happens. */ memset(fdset, 0, ((nr + 1) & ~1)*sizeof(compat_ulong_t)); } return 0; } static int compat_set_fd_set(unsigned long nr, compat_ulong_t __user *ufdset, unsigned long *fdset) { unsigned long odd; nr = DIV_ROUND_UP(nr, __COMPAT_NFDBITS); if (!ufdset) return 0; odd = nr & 1UL; nr &= ~1UL; while (nr) { unsigned long h, l; l = *fdset++; h = l >> 32; if (__put_user(l, ufdset) || __put_user(h, ufdset+1)) return -EFAULT; ufdset += 2; nr -= 2; } if (odd && __put_user(*fdset, ufdset)) return -EFAULT; return 0; } /* * This is a virtual copy of sys_select from fs/select.c and probably * should be compared to it from time to time */ /* * We can actually return ERESTARTSYS instead of EINTR, but I'd * like to be certain this leads to no problems. So I return * EINTR just for safety. * * Update: ERESTARTSYS breaks at least the xview clock binary, so * I'm trying ERESTARTNOHAND which restart only when you want to. */ #define MAX_SELECT_SECONDS \ ((unsigned long) (MAX_SCHEDULE_TIMEOUT / HZ)-1) int compat_core_sys_select(int n, compat_ulong_t __user *inp, compat_ulong_t __user *outp, compat_ulong_t __user *exp, struct timespec *end_time) { fd_set_bits fds; void *bits; int size, max_fds, ret = -EINVAL; struct fdtable *fdt; long stack_fds[SELECT_STACK_ALLOC/sizeof(long)]; if (n < 0) goto out_nofds; /* max_fds can increase, so grab it once to avoid race */ rcu_read_lock(); fdt = files_fdtable(current->files); max_fds = fdt->max_fds; rcu_read_unlock(); if (n > max_fds) n = max_fds; /* * We need 6 bitmaps (in/out/ex for both incoming and outgoing), * since we used fdset we need to allocate memory in units of * long-words. */ size = FDS_BYTES(n); bits = stack_fds; if (size > sizeof(stack_fds) / 6) { bits = kmalloc(6 * size, GFP_KERNEL); ret = -ENOMEM; if (!bits) goto out_nofds; } fds.in = (unsigned long *) bits; fds.out = (unsigned long *) (bits + size); fds.ex = (unsigned long *) (bits + 2*size); fds.res_in = (unsigned long *) (bits + 3*size); fds.res_out = (unsigned long *) (bits + 4*size); fds.res_ex = (unsigned long *) (bits + 5*size); if ((ret = compat_get_fd_set(n, inp, fds.in)) || (ret = compat_get_fd_set(n, outp, fds.out)) || (ret = compat_get_fd_set(n, exp, fds.ex))) goto out; zero_fd_set(n, fds.res_in); zero_fd_set(n, fds.res_out); zero_fd_set(n, fds.res_ex); ret = do_select(n, &fds, end_time); if (ret < 0) goto out; if (!ret) { ret = -ERESTARTNOHAND; if (signal_pending(current)) goto out; ret = 0; } if (compat_set_fd_set(n, inp, fds.res_in) || compat_set_fd_set(n, outp, fds.res_out) || compat_set_fd_set(n, exp, fds.res_ex)) ret = -EFAULT; out: if (bits != stack_fds) kfree(bits); out_nofds: return ret; } asmlinkage long compat_sys_select(int n, compat_ulong_t __user *inp, compat_ulong_t __user *outp, compat_ulong_t __user *exp, struct compat_timeval __user *tvp) { struct timespec end_time, *to = NULL; struct compat_timeval tv; int ret; if (tvp) { if (copy_from_user(&tv, tvp, sizeof(tv))) return -EFAULT; to = &end_time; if (poll_select_set_timeout(to, tv.tv_sec + (tv.tv_usec / USEC_PER_SEC), (tv.tv_usec % USEC_PER_SEC) * NSEC_PER_USEC)) return -EINVAL; } ret = compat_core_sys_select(n, inp, outp, exp, to); ret = poll_select_copy_remaining(&end_time, tvp, 1, ret); return ret; } #ifdef HAVE_SET_RESTORE_SIGMASK static long do_compat_pselect(int n, compat_ulong_t __user *inp, compat_ulong_t __user *outp, compat_ulong_t __user *exp, struct compat_timespec __user *tsp, compat_sigset_t __user *sigmask, compat_size_t sigsetsize) { compat_sigset_t ss32; sigset_t ksigmask, sigsaved; struct compat_timespec ts; struct timespec end_time, *to = NULL; int ret; if (tsp) { if (copy_from_user(&ts, tsp, sizeof(ts))) return -EFAULT; to = &end_time; if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec)) return -EINVAL; } if (sigmask) { if (sigsetsize != sizeof(compat_sigset_t)) return -EINVAL; if (copy_from_user(&ss32, sigmask, sizeof(ss32))) return -EFAULT; sigset_from_compat(&ksigmask, &ss32); sigdelsetmask(&ksigmask, sigmask(SIGKILL)|sigmask(SIGSTOP)); sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved); } ret = compat_core_sys_select(n, inp, outp, exp, to); ret = poll_select_copy_remaining(&end_time, tsp, 0, ret); if (ret == -ERESTARTNOHAND) { /* * Don't restore the signal mask yet. Let do_signal() deliver * the signal on the way back to userspace, before the signal * mask is restored. */ if (sigmask) { memcpy(&current->saved_sigmask, &sigsaved, sizeof(sigsaved)); set_restore_sigmask(); } } else if (sigmask) sigprocmask(SIG_SETMASK, &sigsaved, NULL); return ret; } asmlinkage long compat_sys_pselect6(int n, compat_ulong_t __user *inp, compat_ulong_t __user *outp, compat_ulong_t __user *exp, struct compat_timespec __user *tsp, void __user *sig) { compat_size_t sigsetsize = 0; compat_uptr_t up = 0; if (sig) { if (!access_ok(VERIFY_READ, sig, sizeof(compat_uptr_t)+sizeof(compat_size_t)) || __get_user(up, (compat_uptr_t __user *)sig) || __get_user(sigsetsize, (compat_size_t __user *)(sig+sizeof(up)))) return -EFAULT; } return do_compat_pselect(n, inp, outp, exp, tsp, compat_ptr(up), sigsetsize); } asmlinkage long compat_sys_ppoll(struct pollfd __user *ufds, unsigned int nfds, struct compat_timespec __user *tsp, const compat_sigset_t __user *sigmask, compat_size_t sigsetsize) { compat_sigset_t ss32; sigset_t ksigmask, sigsaved; struct compat_timespec ts; struct timespec end_time, *to = NULL; int ret; if (tsp) { if (copy_from_user(&ts, tsp, sizeof(ts))) return -EFAULT; to = &end_time; if (poll_select_set_timeout(to, ts.tv_sec, ts.tv_nsec)) return -EINVAL; } if (sigmask) { if (sigsetsize != sizeof(compat_sigset_t)) return -EINVAL; if (copy_from_user(&ss32, sigmask, sizeof(ss32))) return -EFAULT; sigset_from_compat(&ksigmask, &ss32); sigdelsetmask(&ksigmask, sigmask(SIGKILL)|sigmask(SIGSTOP)); sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved); } ret = do_sys_poll(ufds, nfds, to); /* We can restart this syscall, usually */ if (ret == -EINTR) { /* * Don't restore the signal mask yet. Let do_signal() deliver * the signal on the way back to userspace, before the signal * mask is restored. */ if (sigmask) { memcpy(&current->saved_sigmask, &sigsaved, sizeof(sigsaved)); set_restore_sigmask(); } ret = -ERESTARTNOHAND; } else if (sigmask) sigprocmask(SIG_SETMASK, &sigsaved, NULL); ret = poll_select_copy_remaining(&end_time, tsp, 0, ret); return ret; } #endif /* HAVE_SET_RESTORE_SIGMASK */ #if defined(CONFIG_NFSD) || defined(CONFIG_NFSD_MODULE) /* Stuff for NFS server syscalls... */ struct compat_nfsctl_svc { u16 svc32_port; s32 svc32_nthreads; }; struct compat_nfsctl_client { s8 cl32_ident[NFSCLNT_IDMAX+1]; s32 cl32_naddr; struct in_addr cl32_addrlist[NFSCLNT_ADDRMAX]; s32 cl32_fhkeytype; s32 cl32_fhkeylen; u8 cl32_fhkey[NFSCLNT_KEYMAX]; }; struct compat_nfsctl_export { char ex32_client[NFSCLNT_IDMAX+1]; char ex32_path[NFS_MAXPATHLEN+1]; compat_dev_t ex32_dev; compat_ino_t ex32_ino; compat_int_t ex32_flags; __compat_uid_t ex32_anon_uid; __compat_gid_t ex32_anon_gid; }; struct compat_nfsctl_fdparm { struct sockaddr gd32_addr; s8 gd32_path[NFS_MAXPATHLEN+1]; compat_int_t gd32_version; }; struct compat_nfsctl_fsparm { struct sockaddr gd32_addr; s8 gd32_path[NFS_MAXPATHLEN+1]; compat_int_t gd32_maxlen; }; struct compat_nfsctl_arg { compat_int_t ca32_version; /* safeguard */ union { struct compat_nfsctl_svc u32_svc; struct compat_nfsctl_client u32_client; struct compat_nfsctl_export u32_export; struct compat_nfsctl_fdparm u32_getfd; struct compat_nfsctl_fsparm u32_getfs; } u; #define ca32_svc u.u32_svc #define ca32_client u.u32_client #define ca32_export u.u32_export #define ca32_getfd u.u32_getfd #define ca32_getfs u.u32_getfs }; union compat_nfsctl_res { __u8 cr32_getfh[NFS_FHSIZE]; struct knfsd_fh cr32_getfs; }; static int compat_nfs_svc_trans(struct nfsctl_arg *karg, struct compat_nfsctl_arg __user *arg) { if (!access_ok(VERIFY_READ, &arg->ca32_svc, sizeof(arg->ca32_svc)) || get_user(karg->ca_version, &arg->ca32_version) || __get_user(karg->ca_svc.svc_port, &arg->ca32_svc.svc32_port) || __get_user(karg->ca_svc.svc_nthreads, &arg->ca32_svc.svc32_nthreads)) return -EFAULT; return 0; } static int compat_nfs_clnt_trans(struct nfsctl_arg *karg, struct compat_nfsctl_arg __user *arg) { if (!access_ok(VERIFY_READ, &arg->ca32_client, sizeof(arg->ca32_client)) || get_user(karg->ca_version, &arg->ca32_version) || __copy_from_user(&karg->ca_client.cl_ident[0], &arg->ca32_client.cl32_ident[0], NFSCLNT_IDMAX) || __get_user(karg->ca_client.cl_naddr, &arg->ca32_client.cl32_naddr) || __copy_from_user(&karg->ca_client.cl_addrlist[0], &arg->ca32_client.cl32_addrlist[0], (sizeof(struct in_addr) * NFSCLNT_ADDRMAX)) || __get_user(karg->ca_client.cl_fhkeytype, &arg->ca32_client.cl32_fhkeytype) || __get_user(karg->ca_client.cl_fhkeylen, &arg->ca32_client.cl32_fhkeylen) || __copy_from_user(&karg->ca_client.cl_fhkey[0], &arg->ca32_client.cl32_fhkey[0], NFSCLNT_KEYMAX)) return -EFAULT; return 0; } static int compat_nfs_exp_trans(struct nfsctl_arg *karg, struct compat_nfsctl_arg __user *arg) { if (!access_ok(VERIFY_READ, &arg->ca32_export, sizeof(arg->ca32_export)) || get_user(karg->ca_version, &arg->ca32_version) || __copy_from_user(&karg->ca_export.ex_client[0], &arg->ca32_export.ex32_client[0], NFSCLNT_IDMAX) || __copy_from_user(&karg->ca_export.ex_path[0], &arg->ca32_export.ex32_path[0], NFS_MAXPATHLEN) || __get_user(karg->ca_export.ex_dev, &arg->ca32_export.ex32_dev) || __get_user(karg->ca_export.ex_ino, &arg->ca32_export.ex32_ino) || __get_user(karg->ca_export.ex_flags, &arg->ca32_export.ex32_flags) || __get_user(karg->ca_export.ex_anon_uid, &arg->ca32_export.ex32_anon_uid) || __get_user(karg->ca_export.ex_anon_gid, &arg->ca32_export.ex32_anon_gid)) return -EFAULT; SET_UID(karg->ca_export.ex_anon_uid, karg->ca_export.ex_anon_uid); SET_GID(karg->ca_export.ex_anon_gid, karg->ca_export.ex_anon_gid); return 0; } static int compat_nfs_getfd_trans(struct nfsctl_arg *karg, struct compat_nfsctl_arg __user *arg) { if (!access_ok(VERIFY_READ, &arg->ca32_getfd, sizeof(arg->ca32_getfd)) || get_user(karg->ca_version, &arg->ca32_version) || __copy_from_user(&karg->ca_getfd.gd_addr, &arg->ca32_getfd.gd32_addr, (sizeof(struct sockaddr))) || __copy_from_user(&karg->ca_getfd.gd_path, &arg->ca32_getfd.gd32_path, (NFS_MAXPATHLEN+1)) || __get_user(karg->ca_getfd.gd_version, &arg->ca32_getfd.gd32_version)) return -EFAULT; return 0; } static int compat_nfs_getfs_trans(struct nfsctl_arg *karg, struct compat_nfsctl_arg __user *arg) { if (!access_ok(VERIFY_READ,&arg->ca32_getfs,sizeof(arg->ca32_getfs)) || get_user(karg->ca_version, &arg->ca32_version) || __copy_from_user(&karg->ca_getfs.gd_addr, &arg->ca32_getfs.gd32_addr, (sizeof(struct sockaddr))) || __copy_from_user(&karg->ca_getfs.gd_path, &arg->ca32_getfs.gd32_path, (NFS_MAXPATHLEN+1)) || __get_user(karg->ca_getfs.gd_maxlen, &arg->ca32_getfs.gd32_maxlen)) return -EFAULT; return 0; } /* This really doesn't need translations, we are only passing * back a union which contains opaque nfs file handle data. */ static int compat_nfs_getfh_res_trans(union nfsctl_res *kres, union compat_nfsctl_res __user *res) { int err; err = copy_to_user(res, kres, sizeof(*res)); return (err) ? -EFAULT : 0; } asmlinkage long compat_sys_nfsservctl(int cmd, struct compat_nfsctl_arg __user *arg, union compat_nfsctl_res __user *res) { struct nfsctl_arg *karg; union nfsctl_res *kres; mm_segment_t oldfs; int err; karg = kmalloc(sizeof(*karg), GFP_USER); kres = kmalloc(sizeof(*kres), GFP_USER); if(!karg || !kres) { err = -ENOMEM; goto done; } switch(cmd) { case NFSCTL_SVC: err = compat_nfs_svc_trans(karg, arg); break; case NFSCTL_ADDCLIENT: err = compat_nfs_clnt_trans(karg, arg); break; case NFSCTL_DELCLIENT: err = compat_nfs_clnt_trans(karg, arg); break; case NFSCTL_EXPORT: case NFSCTL_UNEXPORT: err = compat_nfs_exp_trans(karg, arg); break; case NFSCTL_GETFD: err = compat_nfs_getfd_trans(karg, arg); break; case NFSCTL_GETFS: err = compat_nfs_getfs_trans(karg, arg); break; default: err = -EINVAL; break; } if (err) goto done; oldfs = get_fs(); set_fs(KERNEL_DS); /* The __user pointer casts are valid because of the set_fs() */ err = sys_nfsservctl(cmd, (void __user *) karg, (void __user *) kres); set_fs(oldfs); if (err) goto done; if((cmd == NFSCTL_GETFD) || (cmd == NFSCTL_GETFS)) err = compat_nfs_getfh_res_trans(kres, res); done: kfree(karg); kfree(kres); return err; } #else /* !NFSD */ long asmlinkage compat_sys_nfsservctl(int cmd, void *notused, void *notused2) { return sys_ni_syscall(); } #endif #ifdef CONFIG_EPOLL #ifdef HAVE_SET_RESTORE_SIGMASK asmlinkage long compat_sys_epoll_pwait(int epfd, struct compat_epoll_event __user *events, int maxevents, int timeout, const compat_sigset_t __user *sigmask, compat_size_t sigsetsize) { long err; compat_sigset_t csigmask; sigset_t ksigmask, sigsaved; /* * If the caller wants a certain signal mask to be set during the wait, * we apply it here. */ if (sigmask) { if (sigsetsize != sizeof(compat_sigset_t)) return -EINVAL; if (copy_from_user(&csigmask, sigmask, sizeof(csigmask))) return -EFAULT; sigset_from_compat(&ksigmask, &csigmask); sigdelsetmask(&ksigmask, sigmask(SIGKILL) | sigmask(SIGSTOP)); sigprocmask(SIG_SETMASK, &ksigmask, &sigsaved); } err = sys_epoll_wait(epfd, events, maxevents, timeout); /* * If we changed the signal mask, we need to restore the original one. * In case we've got a signal while waiting, we do not restore the * signal mask yet, and we allow do_signal() to deliver the signal on * the way back to userspace, before the signal mask is restored. */ if (sigmask) { if (err == -EINTR) { memcpy(&current->saved_sigmask, &sigsaved, sizeof(sigsaved)); set_restore_sigmask(); } else sigprocmask(SIG_SETMASK, &sigsaved, NULL); } return err; } #endif /* HAVE_SET_RESTORE_SIGMASK */ #endif /* CONFIG_EPOLL */ #ifdef CONFIG_SIGNALFD asmlinkage long compat_sys_signalfd4(int ufd, const compat_sigset_t __user *sigmask, compat_size_t sigsetsize, int flags) { compat_sigset_t ss32; sigset_t tmp; sigset_t __user *ksigmask; if (sigsetsize != sizeof(compat_sigset_t)) return -EINVAL; if (copy_from_user(&ss32, sigmask, sizeof(ss32))) return -EFAULT; sigset_from_compat(&tmp, &ss32); ksigmask = compat_alloc_user_space(sizeof(sigset_t)); if (copy_to_user(ksigmask, &tmp, sizeof(sigset_t))) return -EFAULT; return sys_signalfd4(ufd, ksigmask, sizeof(sigset_t), flags); } asmlinkage long compat_sys_signalfd(int ufd, const compat_sigset_t __user *sigmask, compat_size_t sigsetsize) { return compat_sys_signalfd4(ufd, sigmask, sigsetsize, 0); } #endif /* CONFIG_SIGNALFD */ #ifdef CONFIG_TIMERFD asmlinkage long compat_sys_timerfd_settime(int ufd, int flags, const struct compat_itimerspec __user *utmr, struct compat_itimerspec __user *otmr) { int error; struct itimerspec t; struct itimerspec __user *ut; if (get_compat_itimerspec(&t, utmr)) return -EFAULT; ut = compat_alloc_user_space(2 * sizeof(struct itimerspec)); if (copy_to_user(&ut[0], &t, sizeof(t))) return -EFAULT; error = sys_timerfd_settime(ufd, flags, &ut[0], &ut[1]); if (!error && otmr) error = (copy_from_user(&t, &ut[1], sizeof(struct itimerspec)) || put_compat_itimerspec(otmr, &t)) ? -EFAULT: 0; return error; } asmlinkage long compat_sys_timerfd_gettime(int ufd, struct compat_itimerspec __user *otmr) { int error; struct itimerspec t; struct itimerspec __user *ut; ut = compat_alloc_user_space(sizeof(struct itimerspec)); error = sys_timerfd_gettime(ufd, ut); if (!error) error = (copy_from_user(&t, ut, sizeof(struct itimerspec)) || put_compat_itimerspec(otmr, &t)) ? -EFAULT: 0; return error; } #endif /* CONFIG_TIMERFD */
jonsmirl/mpc5200
fs/compat.c
C
gpl-2.0
57,092
<?php /*------------------------------------------------------------------------ # com_guru # ------------------------------------------------------------------------ # author iJoomla # copyright Copyright (C) 2013 ijoomla.com. All Rights Reserved. # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # Websites: http://www.ijoomla.com # Technical Support: Forum - http://www.ijoomla.com.com/forum/index/ -------------------------------------------------------------------------*/ defined( '_JEXEC' ) or die( 'Restricted access' ); $db = JFactory::getDBO(); $id = $_REQUEST["id"]; $task = $_REQUEST["task"]; if($task == 'addcourse_ajax'){ $sql = "select `published` from #__guru_program where id =".$id; $db->setQuery($sql); $db->query(); $published = $db->loadColumn(); $published = $published["0"]; if($published){ $sql = "update #__guru_program set published='0' where id =".$id; $ret = 'unpublish'; } else{ $ret = 'publish'; $sql = "update #__guru_program set published='1' where id =".$id; } } else{ $sql = "select `published` from #__guru_media where id =".$id; $db->setQuery($sql); $db->query(); $published = $db->loadColumn(); $published = $published["0"]; if($published){ $sql = "update #__guru_media set published='0' where id =".$id; $ret = 'unpublish'; } else{ $ret = 'publish'; $sql = "update #__guru_media set published='1' where id =".$id; } } $db->setQuery($sql); if (!$db->query() ){ $this->setError($db->getErrorMsg()); return false; } echo $ret; die(); ?>
JozefAB/neoacu
administrator/components/com_guru/js/ajaxExercices.php
PHP
gpl-2.0
1,591
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("LiftSensorTest")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("LiftSensorTest")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: ComVisible(false)]
nickajohnson/WinDT
WinDT/LiftSensorTest/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,048
/* * Mp3Splt -- Utility for mp3/ogg splitting without decoding * * Copyright (c) 2002-2004 M. Trotta - <matteo.trotta@lib.unimib.it> * * http://mp3splt.sourceforge.net * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Library General Public License for more details. * * You should have received a copy of the GNU Library 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. * * Tested on: GNU/Linux 2.4.20 #2 Mon Mar 17 22:02:15 PST 2003 i686 */ /* * NOTE: The major part of the code below is original from: * * vcut 1.6 - (c) 2000-2001 Michael Smith <msmith@labyrinth.net.au> * * included in vorbis tools (http://www.xiph.org) */ #ifndef NO_OGG #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <stdio.h> #include <stdlib.h> #include <time.h> #include <errno.h> #include <string.h> #include <math.h> #include <ogg/ogg.h> #include <vorbis/codec.h> #include <vorbis/vorbisfile.h> #include <locale.h> #include "ogg.h" #include "mp3.h" #include "splt.h" #if !HAVE_FSEEKO #define fseeko fseek #define ftello ftell #endif #include <values.h> static v_packet *save_packet(ogg_packet *packet) { v_packet *p = malloc(sizeof(v_packet)); p->length = packet->bytes; p->packet = malloc(p->length); memcpy(p->packet, packet->packet, p->length); return p; } static void free_packet(v_packet *p) { if(p) { if(p->packet) free(p->packet); free(p); } } static long get_blocksize(ogg_state *s, vorbis_info *vi, ogg_packet *op) { int this = vorbis_packet_blocksize(vi, op); int ret = (this+s->prevW)/4; s->prevW = this; return ret; } static int update_sync(ogg_sync_state *sync_in, FILE *f) { unsigned char *buffer = ogg_sync_buffer(sync_in, BUFSIZE); int bytes = fread(buffer,1,BUFSIZE,f); ogg_sync_wrote(sync_in, bytes); return bytes; } /* Returns 0 for success, or -1 on failure. */ static int write_pages_to_file(ogg_stream_state *stream, FILE *file, int flush) { ogg_page page; if(flush) { while(ogg_stream_flush(stream, &page)) { if(fwrite(page.header,1,page.header_len, file) != page.header_len) return -1; if(fwrite(page.body,1,page.body_len, file) != page.body_len) return -1; } } else { while(ogg_stream_pageout(stream, &page)) { if(fwrite(page.header,1,page.header_len, file) != page.header_len) return -1; if(fwrite(page.body,1,page.body_len, file) != page.body_len) return -1; } } return 0; } /* Read stream until we get to the appropriate cut point. * * We need to do the following: * - Save the final two packets in the stream to temporary buffers. * These two packets then become the first two packets in the 2nd stream * (we need two packets because of the overlap-add nature of vorbis). * - For each packet, buffer it (it could be the 2nd last packet, we don't * know yet (but we could optimise this decision based on known maximum * block sizes, and call get_blocksize(), because this updates internal * state needed for sample-accurate block size calculations. */ static int find_begin_cutpoint(ogg_state *s, FILE *in, ogg_int64_t cutpoint) { int eos=0; ogg_page page; ogg_packet packet; ogg_int64_t granpos, prevgranpos; int result; granpos = prevgranpos = 0; while(!eos) { while(!eos) { int result = ogg_sync_pageout(s->sync_in, &page); if(result==0) break; else if(result>0) { granpos = ogg_page_granulepos(&page); ogg_stream_pagein(s->stream_in, &page); if(granpos < cutpoint) { while(1) { result=ogg_stream_packetout(s->stream_in, &packet); /* throw away result, but update state */ get_blocksize(s,s->vd->vi,&packet); if(result==0) break; else if(result!=-1) { /* We need to save the last packet in the first * stream - but we don't know when we're going * to get there. So we have to keep every packet * just in case. */ if(s->packets[0]) free_packet(s->packets[0]); s->packets[0] = save_packet(&packet); } } prevgranpos = granpos; } else eos=1; /* First stream ends somewhere in this page. We break of out this loop here. */ if(ogg_page_eos(&page)) { eos=1; } } } if(!eos) { if(update_sync(s->sync_in, in)==0) { eos=1; } } } /* Now, check to see if we reached a real EOS */ if(granpos < cutpoint) return -1; // Cutpoint is out of file while((result = ogg_stream_packetout(s->stream_in, &packet))!=0) { int bs; bs = get_blocksize(s, s->vd->vi, &packet); prevgranpos += bs; if(prevgranpos > cutpoint) { s->packets[1] = save_packet(&packet); break; } if(s->packets[0]) free_packet(s->packets[0]); s->packets[0] = save_packet(&packet); } /* Remaining samples in first packet */ s->initialgranpos = prevgranpos - cutpoint; s->cutpoint_begin = cutpoint; return 0; } /* Process second stream. * * We need to do more packet manipulation here, because we need to calculate * a new granulepos for every packet, since the old ones are now invalid. * Start by placing the modified first and second packets into the stream. * Then just proceed through the stream modifying packno and granulepos for * each packet, using the granulepos which we track block-by-block. */ static int find_end_cutpoint(ogg_state *s, ogg_stream_state *stream, FILE *in, FILE *f, ogg_int64_t cutpoint, short adjust, float threshold) { ogg_packet packet; ogg_page page; int eos=0; int result; ogg_int64_t page_granpos = 0, current_granpos = 0, prev_granpos = 0; ogg_int64_t packetnum=0; /* Should this start from 0 or 3 ? */ if(s->packets[0] && s->packets[1]) { // Check if we have the 2 packet, begin can be 0! packet.bytes = s->packets[0]->length; packet.packet = s->packets[0]->packet; packet.b_o_s = 0; packet.e_o_s = 0; packet.granulepos = 0; packet.packetno = packetnum++; ogg_stream_packetin(stream,&packet); packet.bytes = s->packets[1]->length; packet.packet = s->packets[1]->packet; packet.b_o_s = 0; packet.e_o_s = 0; packet.granulepos = s->initialgranpos; packet.packetno = packetnum++; ogg_stream_packetin(stream,&packet); if(ogg_stream_flush(stream, &page)!=0) { fwrite(page.header,1,page.header_len,f); fwrite(page.body,1,page.body_len,f); } while(ogg_stream_flush(stream, &page)!=0) { /* Might this happen for _really_ high bitrate modes, if we're * spectacularly unlucky? Doubt it, but let's check for it just * in case. */ fprintf(stderr, _("Warning: First audio packet didn't fit into page. File may not decode correctly\n")); fwrite(page.header,1,page.header_len,f); fwrite(page.body,1,page.body_len,f); } } else s->initialgranpos = 0; current_granpos = s->initialgranpos; while(!eos) { while(!eos) { result=ogg_sync_pageout(s->sync_in, &page); if(result==0) break; else if(result!=-1) { page_granpos = ogg_page_granulepos(&page) - s->cutpoint_begin; if(ogg_page_eos(&page)) eos=1; ogg_stream_pagein(s->stream_in, &page); if ((cutpoint == 0) || (page_granpos < cutpoint)) { while(1) { result = ogg_stream_packetout(s->stream_in, &packet); if(result==0) break; else if(result!=-1) { int bs = get_blocksize(s, s->vd->vi, &packet); current_granpos += bs; if(s->packets[0]) /* We need to save packet to optimize following split process */ free_packet(s->packets[0]); s->packets[0] = save_packet(&packet); if(current_granpos > page_granpos) current_granpos = page_granpos; packet.granulepos = current_granpos; packet.packetno = packetnum++; ogg_stream_packetin(stream, &packet); if(write_pages_to_file(stream,f, 0)) return -1; } } prev_granpos = page_granpos; } else { if (adjust) { if (ogg_scan_silence(s, (2 * adjust), threshold, 0.f, 0, &page, current_granpos) > 0) cutpoint = (ogg_int64_t) (silence_position(s->silence_list, s->off) * s->vd->vi->rate); else cutpoint = (ogg_int64_t) (cutpoint + (adjust * s->vd->vi->rate)); ssplit_free(&s->silence_list); adjust=0; } else eos=1; /* We reached the second cutpoint */ } if(ogg_page_eos(&page)) { eos=1; } } } if(!eos) { if(update_sync(s->sync_in, in)==0) { eos=1; } } } if ((cutpoint == 0) || (page_granpos < cutpoint)) // End of file. We stop here { if(write_pages_to_file(stream,f, 0)) return -1; s->end = -1; // No more data available. Next processes aborted return 0; } while((result = ogg_stream_packetout(s->stream_in, &packet))!=0) { int bs; bs = get_blocksize(s, s->vd->vi, &packet); prev_granpos += bs; if(prev_granpos >= cutpoint) { s->packets[1] = save_packet(&packet); packet.granulepos = cutpoint; /* Set it! This 'truncates' the final packet, as needed. */ packet.e_o_s = 1; ogg_stream_packetin(stream, &packet); break; } if(s->packets[0]) free_packet(s->packets[0]); s->packets[0] = save_packet(&packet); ogg_stream_packetin(stream, &packet); if(write_pages_to_file(stream,f, 0)) return -1; } if(write_pages_to_file(stream,f, 0)) return -1; s->initialgranpos = prev_granpos - cutpoint; s->end = 1; s->cutpoint_begin += cutpoint; return 0; } static void submit_headers_to_stream(ogg_stream_state *stream, ogg_state *s) { int i; for(i=0;i<3;i++) { ogg_packet p; p.bytes = s->headers[i]->length; p.packet = s->headers[i]->packet; p.b_o_s = ((i==0)?1:0); p.e_o_s = 0; p.granulepos=0; ogg_stream_packetin(stream, &p); } } /* Pull out and save the 3 header packets from the input file. */ static int process_headers(ogg_state *s) { ogg_page page; ogg_packet packet; int bytes; int i; unsigned char *buffer; ogg_sync_init(s->sync_in); vorbis_info_init(s->vd->vi); vorbis_comment_init(&s->vc); while (ogg_sync_pageout(s->sync_in, &page)!=1) { buffer = ogg_sync_buffer(s->sync_in, BUFSIZE); bytes = fread(buffer, 1, BUFSIZE, s->in); if (bytes <= 0) { return -1; } ogg_sync_wrote(s->sync_in, bytes); } s->serial = ogg_page_serialno(&page); ogg_stream_init(s->stream_in, s->serial); if(ogg_stream_pagein(s->stream_in, &page) <0) { return -1; } if(ogg_stream_packetout(s->stream_in, &packet)!=1){ return -1; } if(vorbis_synthesis_headerin(s->vd->vi, &s->vc, &packet)<0) { return -1; } s->headers[0] = save_packet(&packet); i=0; while(i<2) { while(i<2) { int res = ogg_sync_pageout(s->sync_in, &page); if(res==0)break; if(res==1) { ogg_stream_pagein(s->stream_in, &page); while(i<2) { res = ogg_stream_packetout(s->stream_in, &packet); if(res==0)break; if(res<0) { return -1; } s->headers[i+1] = save_packet(&packet); vorbis_synthesis_headerin(s->vd->vi,&s->vc,&packet); i++; } } } buffer=ogg_sync_buffer(s->sync_in, BUFSIZE); bytes=fread(buffer,1,BUFSIZE,s->in); if(bytes==0 && i<2) { return -1; } ogg_sync_wrote(s->sync_in, bytes); } return 0; } ogg_state *ogginfo(FILE *in, ogg_state *state) { setlocale(LC_ALL, ""); bindtextdomain(PACKAGE, LOCALEDIR); textdomain(PACKAGE); state = v_new(); if (state == NULL) { perror("malloc"); exit(1); } state->in = in; state->end = 0; if (state->in != stdin) { if(ov_open(state->in, &state->vf, NULL, 0) < 0) return NULL; rewind(state->in); } /* Read headers in, and save them */ if(process_headers(state)) return NULL; if (state->in != stdin) state->len = (ogg_int64_t) ((state->vd->vi->rate)*(ov_time_total(&state->vf, -1))); state->cutpoint_begin = 0; vorbis_synthesis_init(state->vd,state->vd->vi); vorbis_block_init(state->vd,state->vb); srand(time(NULL)); return state; } int oggsplit(unsigned char *filename, ogg_state *state, float sec_begin, float sec_end, short seekable, short adjust, float threshold) { ogg_stream_state stream_out; ogg_packet header_comm; ogg_int64_t begin, end = 0, cutpoint = 0; begin = (ogg_int64_t) (sec_begin * state->vd->vi->rate); if (sec_end != -1.f) { if (sec_begin >= sec_end) return -1; if (adjust) { if (sec_end != -1) { float gap = (float) adjust; if (sec_end > gap) sec_end -= gap; if (sec_end < sec_begin) sec_end = sec_begin; } else adjust = 0; } end = (ogg_int64_t) (sec_end * state->vd->vi->rate); cutpoint = end - begin; } if (state->end == 0) { // First time we run this, no packets already saved. if(find_begin_cutpoint(state, state->in, begin)) // We must do this before. If an error occurs, we don't want to create empty files! return -1; } if (strcmp(filename, "-")==0) state->out = stdout; else if (!(state->out=fopen(filename, "wb"))) { fprintf (stderr, "\n"); perror(filename); exit(1); } ogg_stream_init(&stream_out, rand()); /* gets random serial number*/ vorbis_commentheader_out(&state->vc, &header_comm); if (state->headers[1]) free_packet(state->headers[1]); state->headers[1] = save_packet(&header_comm); submit_headers_to_stream(&stream_out, state); if(write_pages_to_file(&stream_out, state->out, 1)) return -1; if(find_end_cutpoint(state, &stream_out, state->in, state->out, cutpoint, adjust, threshold)) return -1; ogg_stream_clear(&stream_out); fclose(state->out); if (state->end == -1) return -3; // End of file, no more data available return 0; } int ogg_silence(ogg_state *state, vorbis_dsp_state *vd, float threshold) { float **pcm, sample; int samples, silence = 1; while((samples=vorbis_synthesis_pcmout(vd,&pcm))>0) { if (silence) { int i, j; for (i=0; i < state->vd->vi->channels; i++) { float *mono=pcm[i]; if (!silence) break; for(j=0; j<samples; j++) { sample = fabs(mono[j]); state->temp_level = state->temp_level *0.999 + sample*0.001; if (sample > threshold) silence = 0; } } } vorbis_synthesis_read(vd, samples); } return silence; } int ogg_scan_silence (ogg_state *state, short seconds, float threshold, float min, short output, ogg_page *page, ogg_int64_t granpos) { ogg_page og; ogg_packet op; ogg_sync_state oy; ogg_stream_state os; vorbis_dsp_state vd; vorbis_block vb; ogg_int64_t end_position, begin_position, pos, end, begin, page_granpos; int eos=0, found = 0, shot, result = 0, len = 0 ; short first, flush = 0; unsigned long count = 0; off_t position = ftello(state->in); // Some backups int saveW = state->prevW; float th = convertfromdB(threshold); ogg_sync_init(&oy); ogg_stream_init(&os, state->serial); if (page){ // We still have a page to process memcpy(&og, page, sizeof(ogg_page)); result = 1; } end_position = begin_position = pos = granpos; vorbis_synthesis_init(&vd, state->vd->vi); vorbis_block_init(&vd, &vb); if (seconds > 0) end = (ogg_int64_t) (seconds * state->vd->vi->rate); else end = 0; begin = 0; first = output; shot = DEFAULTSHOT; state->temp_level = 0.0; state->avg_level = 0.0; state->n_stat = 0.0; if (output) fprintf(stderr, "[ 0 %%] S: 00 Level: -0.0 dB\r"); while (!eos) { while(!eos) { if (result==0) break; if(result>0) { if (ogg_page_eos(&og)) eos=1; page_granpos = ogg_page_granulepos(&og) - state->cutpoint_begin; if (pos == 0) pos = page_granpos; ogg_stream_pagein(&os, &og); while(1) { result=ogg_stream_packetout(&os, &op); if(result==0) break; /* need more data */ if(result>0) { int bs = get_blocksize(state, state->vd->vi, &op); pos += bs; if (pos > page_granpos) pos = page_granpos; begin += bs; if(vorbis_synthesis(&vb, &op)==0) { vorbis_synthesis_blockin(&vd, &vb); if ((!flush) && (ogg_silence(state, &vd, th))) { if (len == 0) begin_position = pos; if (first == 0) len++; if (shot < DEFAULTSHOT) shot+=2; end_position = pos; } else { if (len > DEFAULTSILLEN) { if ((flush) || (shot <= 0)) { float b_position, e_position; double temp; temp = (double) begin_position; temp /= state->vd->vi->rate; b_position = (float) temp; temp = (double) end_position; temp /= state->vd->vi->rate; e_position = (float) temp; if ((e_position - b_position - min) >= 0.f) { ssplit_new(&state->silence_list, b_position, e_position, len); found++; } len = 0; shot = DEFAULTSHOT; } } else len = 0; if (flush) { eos = 1; break; } if ((first) && (shot <= 0)) first = 0; if (shot > 0) shot--; } } } if (end) if (begin > end) flush = 1; if (found >= MAXTRACKS) eos = 1; } } result=ogg_sync_pageout(&oy, &og); } if(!eos){ if(update_sync(&oy, state->in)==0) { eos=1; } result=ogg_sync_pageout(&oy, &og); if ((output) && ((count++ > OGG_STAT) && (state->len > 0))) { float level = convert2dB(state->temp_level); state->avg_level += level; state->n_stat++; fprintf(stderr, "[%3d %%] S: %02d Level: %+.1f\r", (int)(pos/(state->len/100)), found, level); count = 0; } } } if (output) fprintf(stderr, "[100 %%]\n"); ogg_stream_clear(&os); vorbis_block_clear(&vb); vorbis_dsp_clear(&vd); ogg_sync_clear(&oy); state->prevW = saveW; fseeko(state->in, position, SEEK_SET); return found; } ogg_state *v_new(void) { ogg_state *s; if ((s = (ogg_state *) malloc(sizeof(ogg_state)))==NULL) return NULL; memset(s, 0, sizeof(ogg_state)); if ((s->sync_in = (ogg_sync_state *) malloc(sizeof(ogg_sync_state)))==NULL) return NULL; if ((s->stream_in = (ogg_stream_state *) malloc(sizeof(ogg_stream_state)))==NULL) return NULL; if ((s->vd = (vorbis_dsp_state *) malloc(sizeof(vorbis_dsp_state)))==NULL) return NULL; if ((s->vd->vi = (vorbis_info *) malloc(sizeof(vorbis_info)))==NULL) return NULL; if ((s->vb = (vorbis_block *) malloc(sizeof(vorbis_block)))==NULL) return NULL; if ((s->headers = malloc(sizeof(v_packet)*3))==NULL) return NULL; memset(s->headers, 0, sizeof(v_packet)*3); if ((s->packets = malloc(sizeof(v_packet)*2))==NULL) return NULL; memset(s->packets, 0, sizeof(v_packet)*2); return s; } /* Full cleanup of internal state and vorbis/ogg structures */ void v_free(ogg_state *s) { if(s) { if(s->packets) { if(s->packets[0]) free_packet(s->packets[0]); if(s->packets[1]) free_packet(s->packets[1]); free(s->packets); } if(s->headers) { int i; for(i=0; i < 3; i++) if(s->headers[i]) free_packet(s->headers[i]); free(s->headers); } if(s->vb) { vorbis_block_clear(s->vb); free(s->vb); } if(s->vd) { vorbis_dsp_clear(s->vd); free(s->vd); } if(s->stream_in) { ogg_stream_clear(s->stream_in); free(s->stream_in); } if(s->sync_in) { ogg_sync_clear(s->sync_in); free(s->sync_in); } ssplit_free(&s->silence_list); free(s); } } static char *checkutf(unsigned char *s) // For the moment we only omit invalid character { int i, j=0; for (i=0; i < strlen(s); i++) { if (s[i]<0x7F) s[j++] = s[i]; } s[j] = '\0'; return s; } vorbis_comment *v_comment (vorbis_comment *vc, char *artist, char *album, char *title, char *tracknum, char *date, char *genre, char *comment) { if (title!=NULL) vorbis_comment_add_tag(vc, "title", checkutf(title)); if (artist!=NULL) vorbis_comment_add_tag(vc, "artist", checkutf(artist)); if (album!=NULL) vorbis_comment_add_tag(vc, "album", checkutf(album)); if (date!=NULL) if (strlen(date)>0) vorbis_comment_add_tag(vc, "date", date); if (genre!=NULL) vorbis_comment_add_tag(vc, "genre", genre); if (tracknum!=NULL) vorbis_comment_add_tag(vc, "tracknumber", tracknum); if (comment!=NULL) vorbis_comment_add_tag(vc, "", comment); return vc; } #endif
OS2World/MM-SOUND-Mp3Splt
sources/ogg.c
C
gpl-2.0
20,654
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: t; c-basic-offset: 8 -*- * * Copyright (C) 2013 Richard Hughes <richard@hughsie.com> * * Licensed under the GNU General Public License Version 2 * * Most of this code was taken from Zif, libzif/zif-transaction.c * * 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. */ #ifdef HAVE_CONFIG_H # include <config.h> #endif #include <glib.h> #include <rpm/rpmlib.h> #include <rpm/rpmlog.h> #include <rpm/rpmdb.h> #include "hif-rpmts.h" #include "hif-utils.h" /** * hif_rpmts_add_install_filename: **/ gboolean hif_rpmts_add_install_filename (rpmts ts, const gchar *filename, gboolean allow_untrusted, gboolean is_update, GError **error) { gint res; Header hdr; FD_t fd; gboolean ret = FALSE; /* open this */ fd = Fopen (filename, "r.ufdio"); res = rpmReadPackageFile (ts, fd, filename, &hdr); Fclose (fd); /* be less strict when we're allowing untrusted transactions */ if (allow_untrusted) { switch (res) { case RPMRC_NOKEY: case RPMRC_NOTFOUND: case RPMRC_NOTTRUSTED: case RPMRC_OK: break; case RPMRC_FAIL: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "signature does not verify for %s", filename); goto out; default: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "failed to open (generic error): %s", filename); goto out; } } else { switch (res) { case RPMRC_OK: break; case RPMRC_NOTTRUSTED: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "failed to verify key for %s", filename); goto out; case RPMRC_NOKEY: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "public key unavailable for %s", filename); goto out; case RPMRC_NOTFOUND: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "signature not found for %s", filename); goto out; case RPMRC_FAIL: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "signature does not verify for %s", filename); goto out; default: g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "failed to open (generic error): %s", filename); goto out; } } /* add to the transaction */ res = rpmtsAddInstallElement (ts, hdr, (fnpyKey) filename, is_update, NULL); if (res != 0) { g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "failed to add install element: %s [%i]", filename, res); goto out; } ret = TRUE; out: return ret; } /** * hif_rpmts_get_problem_str: **/ static gchar * hif_rpmts_get_problem_str (rpmProblem prob) { const char *generic_str; const char *pkg_nevr; const char *pkg_nevr_alt; goffset diskspace; rpmProblemType type; gchar *str = NULL; /* get data from the problem object */ type = rpmProblemGetType (prob); pkg_nevr = rpmProblemGetPkgNEVR (prob); pkg_nevr_alt = rpmProblemGetAltNEVR (prob); generic_str = rpmProblemGetStr (prob); switch (type) { case RPMPROB_BADARCH: str = g_strdup_printf ("package %s is for a different architecture", pkg_nevr); break; case RPMPROB_BADOS: str = g_strdup_printf ("package %s is for a different operating system", pkg_nevr); break; case RPMPROB_PKG_INSTALLED: str = g_strdup_printf ("package %s is already installed", pkg_nevr); break; case RPMPROB_BADRELOCATE: str = g_strdup_printf ("path %s is not relocatable for package %s", generic_str, pkg_nevr); break; case RPMPROB_REQUIRES: str = g_strdup_printf ("package %s has unsatisfied Requires: %s", pkg_nevr, generic_str); break; case RPMPROB_CONFLICT: str = g_strdup_printf ("package %s has unsatisfied Conflicts: %s", pkg_nevr, generic_str); break; case RPMPROB_NEW_FILE_CONFLICT: str = g_strdup_printf ("file %s conflicts between attemped installs of %s", generic_str, pkg_nevr); break; case RPMPROB_FILE_CONFLICT: str = g_strdup_printf ("file %s from install of %s conflicts with file from %s", generic_str, pkg_nevr, pkg_nevr_alt); break; case RPMPROB_OLDPACKAGE: str = g_strdup_printf ("package %s (newer than %s) is already installed", pkg_nevr, pkg_nevr_alt); break; case RPMPROB_DISKSPACE: case RPMPROB_DISKNODES: diskspace = rpmProblemGetDiskNeed (prob); str = g_strdup_printf ("installing package %s needs %" G_GOFFSET_FORMAT " on the %s filesystem", pkg_nevr, diskspace, generic_str); break; case RPMPROB_OBSOLETES: str = g_strdup_printf ("package %s is obsoleted by %s", pkg_nevr, pkg_nevr_alt); break; } return str; } /** * hif_rpmts_look_for_problems: **/ gboolean hif_rpmts_look_for_problems (rpmts ts, GError **error) { gboolean ret = TRUE; GString *string = NULL; rpmProblem prob; rpmpsi psi; rpmps probs = NULL; gchar *msg; /* get a list of problems */ probs = rpmtsProblems (ts); if (rpmpsNumProblems (probs) == 0) goto out; /* parse problems */ string = g_string_new (""); psi = rpmpsInitIterator (probs); while (rpmpsNextIterator (psi) >= 0) { prob = rpmpsGetProblem (psi); msg = hif_rpmts_get_problem_str (prob); g_string_append (string, msg); g_string_append (string, "\n"); g_free (msg); } rpmpsFreeIterator (psi); /* set error */ ret = FALSE; /* we failed, and got a reason to report */ if (string->len > 0) { g_string_set_size (string, string->len - 1); g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "Error running transaction: %s", string->str); goto out; } /* we failed, and got no reason why */ g_set_error_literal (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "Error running transaction and no problems were reported!"); out: if (string != NULL) g_string_free (string, TRUE); rpmpsFree (probs); return ret; } /** * hif_rpmts_log_handler_cb: **/ static int hif_rpmts_log_handler_cb (rpmlogRec rec, rpmlogCallbackData data) { GString **string = (GString **) data; /* only log errors */ if (rpmlogRecPriority (rec) != RPMLOG_ERR) return RPMLOG_DEFAULT; /* do not log internal BDB errors */ if (g_strstr_len (rpmlogRecMessage (rec), -1, "BDB") != NULL) return 0; /* create string if required */ if (*string == NULL) *string = g_string_new (""); /* if text already exists, join them */ if ((*string)->len > 0) g_string_append (*string, ": "); g_string_append (*string, rpmlogRecMessage (rec)); /* remove the trailing /n which rpm does */ if ((*string)->len > 0) g_string_truncate (*string, (*string)->len - 1); return 0; } /** * hif_rpmts_find_package: **/ static Header hif_rpmts_find_package (rpmts ts, HyPackage pkg, GError **error) { GString *rpm_error = NULL; Header hdr = NULL; rpmdbMatchIterator iter; unsigned int recOffset; /* find package by db-id */ recOffset = hy_package_get_rpmdbid (pkg); rpmlogSetCallback (hif_rpmts_log_handler_cb, &rpm_error); iter = rpmtsInitIterator(ts, RPMDBI_PACKAGES, &recOffset, sizeof(recOffset)); if (iter == NULL) { if (rpm_error != NULL) { g_set_error_literal (error, HIF_ERROR, PK_ERROR_ENUM_UNFINISHED_TRANSACTION, rpm_error->str); } else { g_set_error_literal (error, HIF_ERROR, PK_ERROR_ENUM_UNFINISHED_TRANSACTION, "Fatal error, run database recovery"); } goto out; } hdr = rpmdbNextIterator (iter); if (hdr == NULL) { g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_FILE_NOT_FOUND, "failed to find package %s", hy_package_get_name (pkg)); goto out; } /* success */ headerLink (hdr); out: rpmlogSetCallback (NULL, NULL); if (rpm_error != NULL) g_string_free (rpm_error, TRUE); if (iter != NULL) rpmdbFreeIterator (iter); return hdr; } /** * hif_rpmts_add_remove_pkg: **/ gboolean hif_rpmts_add_remove_pkg (rpmts ts, HyPackage pkg, GError **error) { gboolean ret = TRUE; gint retval; Header hdr; hdr = hif_rpmts_find_package (ts, pkg, error); if (hdr == NULL) { ret = FALSE; goto out; } /* remove it */ retval = rpmtsAddEraseElement (ts, hdr, -1); if (retval != 0) { ret = FALSE; g_set_error (error, HIF_ERROR, PK_ERROR_ENUM_INTERNAL_ERROR, "could not add erase element %s (%i)", hy_package_get_name (pkg), retval); goto out; } out: if (hdr != NULL) headerFree (hdr); return ret; }
axaxs/PackageKit-0.8.17
backends/hawkey/hif-rpmts.c
C
gpl-2.0
9,457
<?php /** * @package Komento * @copyright Copyright (C) 2012 Stack Ideas Private Limited. All rights reserved. * @license GNU/GPL, see LICENSE.php * Komento is free software. This version may have been modified pursuant * to the GNU General Public License, and as distributed it includes or * is derivative of works licensed under the GNU General Public License or * other free or open source software licenses. * See COPYRIGHT.php for copyright notices and details. */ defined('_JEXEC') or die('Restricted access'); $componentHelper = Komento::getHelper( 'components' ); if( $componentHelper->isInstalled( 'com_jcomments' ) ) { $components = $this->getModel()->getMigrator( 'jcomments' )->getUniqueComponents(); $selection = array(); foreach ( $components as $component ) { $selection[] = JHtml::_('select.option', $component, JText::_( 'COM_KOMENTO_' . strtoupper( $component ) ) ); } $componentSelect = JHTML::_( 'select.genericlist' , $selection , 'components' , 'multiple="multiple" size="10" style="height: auto !important;"' , 'value' , 'text' ); ?> <table id="migrator-jcomments" migrator-type="jcomments" migration-type="component" class="noshow migratorTable"> <tr> <td width="50%" valign="top"> <fieldset class="adminform"> <legend><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_LAYOUT_MAIN' ); ?></legend> <table class="migrator-options admintable"> <tr> <td class="key"><span><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_SELECT_COMPONENTS' ); ?></span></td> <td><?php echo $componentSelect; ?></td> </tr> <tr> <td class="key"><span><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_SELECT_PUBLISHING_STATE' ); ?></span></td> <td> <select id="publishingState"> <option value="inherit"><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_PUBLISHING_STATE_INHERIT' ); ?></option> <option value="1"><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_PUBLISHING_STATE_PUBLISHED' ); ?></option> <option value="0"><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_PUBLISHING_STATE_UNPUBLISHED' ); ?></option> </select> </td> </tr> <tr> <td class="key"><span><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_MIGRATE_LIKES' ); ?></span></td> <td><input id="migrateLikes" type="checkbox" checked="checked" /></td> </tr> </table> <a href="javascript:void(0);" class="migrateButton button"><?php echo JText::_( 'COM_KOMENTO_MIGRATORS_START_MIGRATE' ); ?></a> </fieldset> </td> <td width="50%" valign="top" class="migratorProgress"> <?php echo $this->loadTemplate( 'progress' ); ?> </td> </tr> </table> <?php } else { ?> <table id="migrator-jcomments" class="noshow adminlist"> <tr> <td><?php echo JText::_( 'COM_KOMENTO_JCOMMENTS_NOT_INSTALLED' ); ?></td> </tr> </table> <?php } ?>
atweb-project/in-case-of.com
administrator/components/com_komento/views/migrators/tmpl/default_jcomments.php
PHP
gpl-2.0
2,803
<?php echo showSectionHead($spTextKeyword['New Keyword']); ?> <form id="newKeyword"> <input type="hidden" name="sec" value="create"/> <table width="100%" border="0" cellspacing="0" cellpadding="0" class="list"> <tr class="listHead"> <td class="left" width='30%'><?=$spTextKeyword['New Keyword']?></td> <td class="right">&nbsp;</td> </tr> <tr class="white_row"> <td class="td_left_col"><?=$spText['common']['Name']?>:</td> <td class="td_right_col"><input type="text" name="name" value="<?=$post['name']?>" class="long"><?=$errMsg['name']?></td> </tr> <tr class="blue_row"> <td class="td_left_col"><?=$spText['common']['Website']?>:</td> <td class="td_right_col"> <select name="website_id"> <?php foreach($websiteList as $websiteInfo){?> <?php if($websiteInfo['id'] == $post['website_id']){?> <option value="<?=$websiteInfo['id']?>" selected><?=$websiteInfo['name']?></option> <?php }else{?> <option value="<?=$websiteInfo['id']?>"><?=$websiteInfo['name']?></option> <?php }?> <?php }?> </select> <?=$errMsg['website_id']?> </td> </tr> <tr class="white_row"> <td class="td_left_col"><?=$spText['common']['lang']?>:</td> <td class="td_right_col"> <?php echo $this->render('language/languageselectbox', 'ajax'); ?> </td> </tr> <tr class="blue_row"> <td class="td_left_col"><?=$spText['common']['Country']?>:</td> <td class="td_right_col"> <?php echo $this->render('country/countryselectbox', 'ajax'); ?> </td> </tr> <?php $post['searchengines'] = is_array($post['searchengines']) ? $post['searchengines'] : array(); ?> <tr class="white_row"> <td class="td_left_col"><?=$spText['common']['Search Engine']?>:</td> <td class="td_right_col"> <select name="searchengines[]" class="multi" multiple="multiple" id="searchengines"> <?php foreach($seList as $seInfo){?> <?php $selected = in_array($seInfo['id'], $post['searchengines']) ? "selected" : ""?> <option value="<?=$seInfo['id']?>" <?=$selected?>><?=$seInfo['domain']?></option> <?php }?> </select> <?=$errMsg['searchengines']?> <br> <input type="checkbox" id="select_all" onclick="selectAllOptions('searchengines', true); $('clear_all').checked=false;"> <?=$spText['label']['Select All']?> &nbsp;&nbsp; <input type="checkbox" id="clear_all" onclick="selectAllOptions('searchengines', false); $('select_all').checked=false;"> <?=$spText['label']['Clear All']?> </td> </tr> <tr class="blue_row"> <td class="tab_left_bot_noborder"></td> <td class="tab_right_bot"></td> </tr> <tr class="listBot"> <td class="left" colspan="1"></td> <td class="right"></td> </tr> </table> <table width="100%" cellspacing="0" cellpadding="0" border="0" class="actionSec"> <tr> <td style="padding-top: 6px;text-align:right;"> <a onclick="scriptDoLoad('keywords.php', 'content')" href="javascript:void(0);" class="actionbut"> <?=$spText['button']['Cancel']?> </a>&nbsp; <?php $actFun = SP_DEMO ? "alertDemoMsg()" : "scriptDoLoadPost('keywords.php', 'newKeyword', 'content')"; ?> <a onclick="<?=$actFun?>" href="javascript:void(0);" class="actionbut"> <?=$spText['button']['Proceed']?> </a> </td> </tr> </table> </form>
szepeviktor/Seo-Panel
themes/szepe/views/keyword/new.ctp.php
PHP
gpl-2.0
3,262
<?php /** * Date: 05/02/14 * Time: 12:30 * Author: Jean-Christophe Cuvelier <jcc@morris-chapman.com> */ if(!cmsms()) exit; $IP = $_SERVER['REMOTE_ADDR']; echo IPRange::getCountryISOFromIP($IP);
atomseeds/cmsms-ip2country
action.get_country_iso.php
PHP
gpl-2.0
200
#ifndef FASTDISCRETEFOURIERTRANSFORM_HPP_INCLUDED #define FASTDISCRETEFOURIERTRANSFORM_HPP_INCLUDED #include <vector> #include <complex> template < class Type > class FDFT { private: std::vector < std::complex < Type > > Signal; std::vector < std::complex < Type > > Fourier; Type PI(void) { return 3.14159265358979; } void fdft_slow(std::vector < std::complex < Type > > &a, bool invert = false) { size_t n = (int) a.size(); if (n == 1) return; std::vector < std::complex < Type > > a0(n/2); std::vector < std::complex < Type > > a1(n/2); for (size_t i = 0, j = 0; i < n; i += 2, j++) { a0[j] = a[i]; a1[j] = a[i+1]; } fdft_slow(a0, invert); fdft_slow(a1, invert); Type ang = 2*PI()/n * (invert ? -1 : 1); std::complex < Type > w(1); std::complex < Type > wn(cos(ang), sin(ang)); for (size_t i = 0; i < n/2; i++) { a[i] = a0[i] + w*a1[i]; a[i + n/2] = a0[i] - w*a1[i]; if (invert) { a[i] /= 2; a[i + n/2] /= 2; } w *= wn; } } void fdft(std::vector < std::complex < Type > > &a, bool invert = false) { fdft_slow(a, invert); return; } public: FDFT() { Signal.clear(); Fourier.clear(); } ~FDFT() { Signal.clear(); Fourier.clear(); } void Set_Signal(const std::vector < std::complex < Type > > &_Signal) { Signal = _Signal; return; } std::vector < std::complex < Type > > Get_Signal(void) const{ return std::vector < std::complex < Type > > (Signal); } void Set_Fourier(const std::vector < std::complex < Type > > &_Fourier) { Fourier = _Fourier; return; } std::vector < std::complex < Type > > Get_Fourier(void) const { return std::vector < std::complex < Type > > (Fourier); } bool Run_FDFT(void) { if (!Signal.size()) return false; Fourier = Signal; fdft(Fourier, false); return true; } bool Run_IFDFT(void) { if(!Fourier.size()) return false; Signal = Fourier; fdft(Signal, true); return true; } void Fourier_test(void) { double twopi = 2*PI(); std::complex < Type > ci (0, 1); int nx; std::cout << "Nx = "; std::cin >> nx; std::complex < Type > w0 = exp(-ci*twopi/std::complex < Type > (nx, 0)); std::complex < Type > q = 1.01 + ci*0.02; std::vector < std::complex < Type > > y, fy, _y, _fy; y.resize(nx); fy.resize(nx); for (int m = 0; m < nx; m++) { y[m] = pow(q, m); fy[m] = (pow(q, nx) - 1.0) / (q*pow(w0, m) - 1.0) / std::complex < Type > (nx, 0); } for (int m = 0; m < 4; m++) std::cout << "m = " << m << ", y = " << y[m] << ", fy = " << fy[m] << std::endl; Set_Signal(y); Run_FDFT(); _fy = Get_Fourier(); Run_IFDFT(); _y = Get_Signal(); std::cout << "Calculated:" << std::endl; for (int m = 0; m < 4; m++) std::cout << "m = " << m << ", y = " << y[m] << ", fy = " << fy[m] << std::endl; } }; #endif // FASTDISCRETEFOURIERTRANSFORM_HPP_INCLUDED
VulpesCorsac/Mathematical-Modelling-DPQE-MIPT
Task7/FastDiscreteFourierTransform.hpp
C++
gpl-2.0
3,415
# generator-angular-ts [![Build Status](https://secure.travis-ci.org/travissimon/generator-angular-ts.png?branch=master)](https://travis-ci.org/travissimon/generator-angular-ts) > [Yeoman](http://yeoman.io) generator ## Getting Started ### What is Yeoman? Trick question. It's not a thing. It's this guy: ![](http://i.imgur.com/JHaAlBJ.png) Basically, he wears a top hat, lives in your computer, and waits for you to tell him what kind of application you wish to create. Not every new computer comes with a Yeoman pre-installed. He lives in the [npm](https://npmjs.org) package repository. You only have to ask for him once, then he packs up and moves into your hard drive. *Make sure you clean up, he likes new and shiny things.* ```bash npm install -g yo ``` ### Yeoman Generators Yeoman travels light. He didn't pack any generators when he moved in. You can think of a generator like a plug-in. You get to choose what type of application you wish to create, such as a Backbone application or even a Chrome extension. To install generator-angular-ts from npm, run: ```bash npm install -g generator-angular-ts ``` Finally, initiate the generator: ```bash yo angular ts ``` ### Getting To Know Yeoman Yeoman has a heart of gold. He's a person with feelings and opinions, but he's very easy to work with. If you think he's too opinionated, he can be easily convinced. If you'd like to get to know Yeoman better and meet some of his friends, [Grunt](http://gruntjs.com) and [Bower](http://bower.io), check out the complete [Getting Started Guide](https://github.com/yeoman/yeoman/wiki/Getting-Started). ## License MIT
travissimon/generator-angular-ts
README.md
Markdown
gpl-2.0
1,637
package com.gtss.douban; import kg.gtss.utils.Log; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteDatabase.CursorFactory; import android.database.sqlite.SQLiteOpenHelper; import android.provider.BaseColumns; //import android.util.Log; /** * * database.At first i wanna creat serveral dbs for * DouBan,Google,Amazon.But...uh..Db is shared within all parts in a apk.So...i * create a dozen of tables. A good way to organize a contract class is to put * definitions that are global to your whole database in the root level of the * class. Then create an inner class for each table that enumerates its * columns.<b>http * ://developer.android.com/training/basics/data-storage/databases.html</b> * */ public class DatabaseSQLiteOpenHelper extends SQLiteOpenHelper { // private final static String this = "DatabaseSQLiteOpenHelper"; // database name public static final String DB_NAME = "pba.db"; // database version public static final int DATABASE_VERSION = 9; // table name public final static String TableName = "douban"; // create table.INTEGER PRIMARY KEY, private static String TABLE_CREATE = "create table " + TableName + "(" + DatabaseBookInterface._ID + " integer default '1' not null primary key autoincrement," + DatabaseBookInterface.COLUMN_NAME_FAVORITE + " integer not null," + DatabaseBookInterface.COLUMN_NAME_ISBN + " integer not null," + DatabaseBookInterface.COLUMN_NAME_TITLE + " text not null," + DatabaseBookInterface.COLUMN_NAME_AUTHOR + " text not null," + DatabaseBookInterface.COLUMN_NAME_DATE + " text not null," + DatabaseBookInterface.COLUMN_NAME_IMGURI + " text not null," + DatabaseBookInterface.COLUMN_NAME_SUMMARY + " text not null)"; // + DatabaseBookInterface.COLUMN_NAME_DATE + // " timestamp not null default(datetime('now','localtime')))"; // + DatabaseBookInterface.COLUMN_NAME_DATE + // " timestamp not null default current_timestamp)"; public static String[] PROJECTION = { DatabaseBookInterface._ID, DatabaseBookInterface.COLUMN_NAME_FAVORITE, DatabaseBookInterface.COLUMN_NAME_ISBN, DatabaseBookInterface.COLUMN_NAME_TITLE, DatabaseBookInterface.COLUMN_NAME_AUTHOR, DatabaseBookInterface.COLUMN_NAME_DATE, DatabaseBookInterface.COLUMN_NAME_SUMMARY, DatabaseBookInterface.COLUMN_NAME_IMGURI }; // delete table private static String TABLE_DELETE = "DROP TABLE IF EXISTS " + TableName; public DatabaseSQLiteOpenHelper(Context context) { super(context, DB_NAME, null, DATABASE_VERSION); // mTableName = tableName; } // public DatabaseSQLiteOpenHelper(Context context, String name, // CursorFactory factory, int version) { // super(context, name, factory, version); // // TODO Auto-generated constructor stub // } @Override public void onCreate(SQLiteDatabase db) { // TODO Auto-generated method stub Log.v(this, "onCreate--->>> " + TABLE_CREATE); db.execSQL(TABLE_CREATE); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub Log.v(this, "onUpgrade "); // This database is only a cache for online data, so its upgrade policy // is // to simply to discard the data and start over db.execSQL(TABLE_DELETE); onCreate(db); } @Override public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) { // TODO Auto-generated method stub onUpgrade(db, oldVersion, newVersion); } @Override public void onOpen(SQLiteDatabase db) { // TODO Auto-generated method stub super.onOpen(db); } }
gongtingshisi/pba
src/com/gtss/douban/DatabaseSQLiteOpenHelper.java
Java
gpl-2.0
3,710
/*----------------------------------------------------------------------------------*/ //This code is part of a larger project whose main purpose is to entretain either // //by helping making it better or by playing it in its actual state. // // // //Copyright (C) 2011 Three Legged Studio // // // // 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, 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. // // // // You can contact us at projectpgz.blogspot.com // /*----------------------------------------------------------------------------------*/ #include "Stamp.h" //Construye un Stamp a partir de un nombre de imagen Stamp::Stamp(string fname, GfxEngine* gfxEngine) : Graphic() { //Crea una imagen a partir del nombre que le pasan y el subsistema grafico this->image = new Image(fname,gfxEngine); // Se indica que se ha cargado aquí loaded = true; //Apunta a su subsistema grafico this->gfxEngine = gfxEngine; // se toma el ancho y alto de la imagen. w = image->getWidth(); h = image->getHeigth(); }; //Construye un Stamp a partir de una imagen Stamp::Stamp(Image* image, GfxEngine* gfxEngine) { //Toma la imagen y el subsistema grafico que le proporcionan this->image = image; this->gfxEngine = gfxEngine; // Indicando que la imagen no se ha cargado aquí loaded = false; // Si la imagen que nos han pasado es inválida // establecemos dimensiones por defecto if (image == NULL) { w = 0; h = 0; } else { // se toma el ancho y alto de la imagen. w = image->getWidth(); h = image->getHeigth(); } }; //Destructora Stamp::~Stamp() { // se libera la memoria reservada para la imagen. // si se ha cargado aquí if (image != NULL && loaded) delete image; }; //Devuelve en encho de la imagen int Stamp::getWidth() { return w; }; //Devuelve el alto de la imagen int Stamp::getHeight() { return h; }; //Metodo de renderizado del Stamp, que hace que el subsistema grafico lo pinte en el lugar indicado void Stamp::render(int x, int y) { gfxEngine->renderExt(image,x+originX,y+originY, *color, alpha, scaleH, scaleV, rotation, NULL, originX, originY); };
rafadelahoz/pgz-engine
pgz-engine/source/src/Stamp.cpp
C++
gpl-2.0
3,023
/*BEGIN_LEGAL Intel Open Source License Copyright (c) 2002-2013 Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the Intel Corporation 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 INTEL OR ITS 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. END_LEGAL */ #ifndef TIME_WARP_H #define TIME_WARP_H namespace INSTLIB { /*! @defgroup TIME_WARPER It is often desirable to use instrumentation to change behavior of program in certain ways so that different runs of the program (with the same input) are same. Time_warper allows uses to modify non-repitative constructs such as instructions reading the cycle counters and system calls reading time of the day. */ /*! @defgroup TIME_WARPER_RDTSC @ingroup TIME_WARPER Modify the behaviors of RDTSC instruction on IA-32 and Intel(R) 64 architectures. */ /*! @ingroup TIME_WARPER_RDTSC */ class TIME_WARP_RDTSC { public: TIME_WARP_RDTSC():_enableKnob(KNOB_MODE_WRITEONCE, "pintool", "rdtsc_warp", "0", "Modify the behavior of RDTSC") { _edx_eax = 1ULL; _eax= 0; _edx= 0; } bool IsActive() { return (_enableKnob); } /*! @ingroup TIME_WARPER_RDTSC Activate the controller if the -length knob is provided @return 1 if controller can start an interval, otherwise 0 */ INT32 CheckKnobs(VOID * val) { if (_enableKnob==0) return 0; #if defined(TARGET_IA32) || defined(TARGET_IA32E) // Register Instruction to be called to instrument instructions TRACE_AddInstrumentFunction(ProcessRDTSC, this); #endif return 1; } private: KNOB<BOOL> _enableKnob; UINT64 _edx_eax; UINT32 _eax; UINT32 _edx; static UINT32 SwizzleEdx(TIME_WARP_RDTSC *rd) { rd->_edx = (rd->_edx_eax & 0xffffffff00000000ULL) >> 32; // cerr << "SwizzleEdx() returning 0x"<< hex << edx << endl; return rd->_edx; } static UINT32 SwizzleEax(TIME_WARP_RDTSC *rd) { rd->_eax = rd->_edx_eax & 0x00000000ffffffffULL; rd->_edx_eax+=100; // cerr << "SwizzleEax() edx_eax= 0x"<< hex << edx_eax << endl; // cerr << "SwizzleEax() returning 0x"<< hex << eax << endl; return rd->_eax; } static VOID PrintEaxEdx(ADDRINT reax, ADDRINT redx) { cerr << "PrintEaxEdx():reg eax = 0x"<< hex << reax << endl; cerr << "PrintEaxEdx():reg edx = 0x"<< hex << redx << endl; } #if defined(TARGET_IA32) || defined(TARGET_IA32E) // Pin calls this function every time a new trace is encountered // Goal: Make rdtsc repeatable across runs // NOTE: We are using TRACE instrumentation because it has higher // precedence than INS instrumentation. static VOID ProcessRDTSC(TRACE trace, VOID *v) { for (BBL bbl = TRACE_BblHead(trace); BBL_Valid(bbl); bbl = BBL_Next(bbl)) { for (INS ins = BBL_InsHead(bbl); INS_Valid(ins); ins = INS_Next(ins)) { if(INS_IsRDTSC(ins)) { INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)SwizzleEdx,IARG_PTR, v, IARG_RETURN_REGS, REG_GDX, IARG_END); INS_InsertCall(ins, IPOINT_AFTER, (AFUNPTR)SwizzleEax,IARG_PTR, v, IARG_RETURN_REGS, REG_GAX, IARG_END); } } } } #endif }; /*! @ingroup TIME_WARPER_MULTI */ class TIME_WARP { public: /*! @ingroup TIME_WARPER_MULTI */ /*! @ingroup TIME_WARPER_MULTI Activate all the component controllers */ INT32 CheckKnobs(VOID * val) { _val = val; INT32 start = 0; start = start + _rdtsc.CheckKnobs(this); return start; } bool RDTSC_modified() { return _rdtsc.IsActive(); }; private: VOID * _val; TIME_WARP_RDTSC _rdtsc; }; } #endif
cyjseagull/SHMA
zsim-nvmain/pin_kit/source/tools/InstLib/time_warp.H
C++
gpl-2.0
5,202
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.6 | +--------------------------------------------------------------------+ | Copyright Tech To The People http:tttp.eu (c) 2011 | +--------------------------------------------------------------------+ | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * Delete records passed in via a csv file. You must have the record * id defined in the csv file. * * Usage: * php bin/csv/delete.php -e <entity> --file /path/to/csv/file [ -s site.org ] * e.g.: php bin/csv/delete.php -e Contact --file /tmp/delete.csv * */ require_once dirname(__DIR__) . '/cli.class.php'; $entityImporter = new civicrm_cli_csv_deleter(); $entityImporter->run();
acappellamaniac/eva_website
sites/all/modules/civicrm/bin/csv/delete.php
PHP
gpl-2.0
2,032
/* Copyright (C) Hongsen Liao Institute of Computer Graphics and Computer Aided Design School of Software, Tsinghua University Contact: liaohs082@gmail.com All rights reserved. */ #ifndef DENSITY_RENDERING_WIDGET_H_ #define DENSITY_RENDERING_WIDGET_H_ #include <vtk3DWidget.h> #include <vector> using namespace std; class vtkActor; class vtkPolyDataMapper; class vtkPolyData; class DensityRenderingWidget : public vtk3DWidget { public: static DensityRenderingWidget* New(); vtkTypeMacro(DensityRenderingWidget, vtk3DWidget); void SetData(vector<vector<float>>& pos, vector<int>& cluster_index); virtual void SetEnabled(int enabled); virtual void PlaceWidget(double bounds[6]) {} protected: DensityRenderingWidget(); ~DensityRenderingWidget(); private: vtkActor* actor_ = NULL; vtkPolyDataMapper* data_mapper_ = NULL; vtkPolyData* polydata_ = NULL; vector<vector<float>> point_pos_; vector<int> cluster_index_; vector<float> adaptive_rate_; void BuildRepresentation(); }; #endif
Edgar324/ScatterPointGlyph
ScatterPointGlyph/density_rendering_widget.h
C
gpl-2.0
1,051
// // Diese Datei wurde mit der JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.11 generiert // Siehe <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Änderungen an dieser Datei gehen bei einer Neukompilierung des Quellschemas verloren. // Generiert: 2014.11.06 um 02:47:13 AM CET // package de.idealo.offers.imports.offermanager.ebay.api.binding.jaxb.trading; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * * Validates the user response to a <b class="con">GetChallengeToken</b> * botblock challenge. * * * <p>Java-Klasse für ValidateChallengeInputRequestType complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="ValidateChallengeInputRequestType"&gt; * &lt;complexContent&gt; * &lt;extension base="{urn:ebay:apis:eBLBaseComponents}AbstractRequestType"&gt; * &lt;sequence&gt; * &lt;element name="ChallengeToken" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="UserInput" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/&gt; * &lt;element name="KeepTokenValid" type="{http://www.w3.org/2001/XMLSchema}boolean" minOccurs="0"/&gt; * &lt;/sequence&gt; * &lt;/extension&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "ValidateChallengeInputRequestType", propOrder = { "challengeToken", "userInput", "keepTokenValid" }) public class ValidateChallengeInputRequestType extends AbstractRequestType { @XmlElement(name = "ChallengeToken") protected String challengeToken; @XmlElement(name = "UserInput") protected String userInput; @XmlElement(name = "KeepTokenValid") protected Boolean keepTokenValid; /** * Ruft den Wert der challengeToken-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getChallengeToken() { return challengeToken; } /** * Legt den Wert der challengeToken-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setChallengeToken(String value) { this.challengeToken = value; } /** * Ruft den Wert der userInput-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getUserInput() { return userInput; } /** * Legt den Wert der userInput-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setUserInput(String value) { this.userInput = value; } /** * Ruft den Wert der keepTokenValid-Eigenschaft ab. * * @return * possible object is * {@link Boolean } * */ public Boolean getKeepTokenValid() { return keepTokenValid; } /** * Legt den Wert der keepTokenValid-Eigenschaft fest. * * @param value * allowed object is * {@link Boolean } * */ public void setKeepTokenValid(Boolean value) { this.keepTokenValid = value; } }
Team-OfferManager/ebay-jaxb-bindings
src/main/java/de/idealo/offers/imports/offermanager/ebay/api/binding/jaxb/trading/ValidateChallengeInputRequestType.java
Java
gpl-2.0
3,553
<!DOCTYPE HTML> <html> <head> <title>Whose Opinion?</title> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="description" content="Site created to express public sentiment and the peoples voice on topics and issues today" /> <meta name="author" content="Ethan Eldridge"> <meta name="keywords" content="Public,Opinion,Voice,Democracy,Ethan,Eldridge"/> <meta name="robots" content="index, follow" /> <meta name="revisit-after" content="1 month" /> <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon" /> <link rel="icon" href="/favicon.ico" type="image/ico"> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel='stylesheet' href="/style/main.css" /> <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/tooltipster/3.0.5/css/tooltipster.css"> <link rel="stylesheet" type="text/css" href="//cdnjs.cloudflare.com/ajax/libs/tooltipster/3.0.5/css/themes/tooltipster-light.min.css"> </head> <body id=""> <header> <h1>Your Opinion Matters</h1> </header> <nav> <span name="vote-help" title="Click for Help">(?)</span> <h3 name="category-header">Category</h3> <ul> <li><a href="/">Popular</a></li> <li><a href="/category/?c=politics">Politics</a> <li><a href="/category/?c=religion">Religion</a> <li><a href="/category/?c=technology">Technology</a> <li><a href="/category/?c=environment">Environment</a> <li><a href="/category/?c=international">International</a> </ul> <footer> <ul> <li><a href="http://www.ethanjoachimeldridge.info">Created By E.J. Eldridge</a> <li><a href="http://github.com/EJEHardenberg/whoseopinion.com">Source Code</a> <li><a href="https://github.com/EJEHardenberg/whoseopinion.com/blob/master/LICENSE">License</a> <li><a href="/privacy-data-policy">Privacy &amp; Data Policy</a> </ul> </footer> </nav> <section> <h3>Privacy and Data Policy</h3> <h4>Are your vote&#39;s confidential?</h4> <p>Yes, we do not associate your opinions with your account. Visualizations and reports using user data is always in an aggregated form and cannot be traced to a single individual. </p> </section> <div id="tutorial-dialogs" style="display: none;"> <div id="welcome"> <p> Welcome! Is this your first time? </p> <ul> <li><a name="yes" href="#yes">Yes</a> <li><a name="no" href="#no">No</a> </ul> </div> <div id="vote-help"> <h4>Guide to voting</h4> Do you think this statement <dl> <dt>is horribly wrong? Or out of touch with reality?</dt> <dd>Outraged</dd> <dt>is wrong, but would agree to disagree?</dt> <dd>Disagree</dd> <dt>is correct, but could agree to disagree with someone?</dt> <dd>Agree</dd> <dt>is true, and would try to change other people's minds if they didn't?</dt> <dd>Support</dd> </dl> </div> </div> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.4.33/jquery.colorbox-min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/tooltipster/3.0.5/js/jquery.tooltipster.min.js"></script> <script type="text/javascript" src="/js/question.js"></script> <script type="text/javascript" src="/js/tutorial.js"></script> <link rel="stylesheet" type="text/css" href="/style/tutorial.css"> </body> </html>
EdgeCaseBerg/whoseopinion.com
www/privacy-data-policy.html
HTML
gpl-2.0
3,459
'use strict'; var wallas = angular.module('wallasApp'); wallas.factory('PercentSpendingService', ['$http', function($http) { var percentSpendingService = {}; percentSpendingService.getPercents = function(login, startDate, endDate) { var startDateUTC = startDate.getUTCFullYear() + '-' + (startDate.getUTCMonth() + 1)+ '-' + startDate.getUTCDate()+'T'+startDate.getUTCHours()+':'+startDate.getUTCMinutes()+'Z'; var endDateUTC = endDate.getUTCFullYear() + '-' + (endDate.getUTCMonth() + 1)+ '-' + endDate.getUTCDate()+'T'+endDate.getUTCHours()+':'+endDate.getUTCMinutes()+'Z'; return $http.get('rest/percents/'.concat(login) + '?startDate=' + startDateUTC + '&endDate=' + endDateUTC); }; return percentSpendingService; }]);
adri229/wallas
assets/js/PercentSpendingService.js
JavaScript
gpl-2.0
748
# -*- coding: utf-8 -*- # # # TheVirtualBrain-Framework Package. This package holds all Data Management, and # Web-UI helpful to run brain-simulations. To use it, you also need do download # TheVirtualBrain-Scientific Package (for simulators). See content of the # documentation-folder for more details. See also http://www.thevirtualbrain.org # # (c) 2012-2013, Baycrest Centre for Geriatric Care ("Baycrest") # # 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. 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, you can download it here # http://www.gnu.org/licenses/old-licenses/gpl-2.0 # # # CITATION: # When using The Virtual Brain for scientific publications, please cite it as follows: # # Paula Sanz Leon, Stuart A. Knock, M. Marmaduke Woodman, Lia Domide, # Jochen Mersmann, Anthony R. McIntosh, Viktor Jirsa (2013) # The Virtual Brain: a simulator of primate brain network dynamics. # Frontiers in Neuroinformatics (7:10. doi: 10.3389/fninf.2013.00010) # # """ .. moduleauthor:: Calin Pavel <calin.pavel@codemart.ro> """ import os import logging from logging.handlers import MemoryHandler from tvb.basic.profile import TvbProfile from tvb.basic.logger.simple_handler import SimpleTimedRotatingFileHandler class ClusterTimedRotatingFileHandler(MemoryHandler): """ This is a custom rotating file handler which computes the name of the file depending on the execution environment (web node or cluster node) """ # Name of the log file where code from Web application will be stored WEB_LOG_FILE = "web_application.log" # Name of the file where to write logs from the code executed on cluster nodes CLUSTER_NODES_LOG_FILE = "operations_executions.log" # Size of the buffer which store log entries in memory # in number of lines BUFFER_CAPACITY = 20 def __init__(self, when='h', interval=1, backupCount=0): """ Constructor for logging formatter. """ # Formatting string format_str = '%(asctime)s - %(levelname)s' if TvbProfile.current.cluster.IN_OPERATION_EXECUTION_PROCESS: log_file = self.CLUSTER_NODES_LOG_FILE if TvbProfile.current.cluster.IS_RUNNING_ON_CLUSTER_NODE: node_name = TvbProfile.current.cluster.CLUSTER_NODE_NAME if node_name is not None: format_str += ' [node:' + str(node_name) + '] ' else: format_str += ' [proc:' + str(os.getpid()) + '] ' else: log_file = self.WEB_LOG_FILE format_str += ' - %(name)s - %(message)s' rotating_file_handler = SimpleTimedRotatingFileHandler(log_file, when, interval, backupCount) rotating_file_handler.setFormatter(logging.Formatter(format_str)) MemoryHandler.__init__(self, capacity=self.BUFFER_CAPACITY, target=rotating_file_handler)
rajul/tvb-framework
tvb/config/logger/cluster_handler.py
Python
gpl-2.0
3,331
using System; using System.Collections.Generic; using System.Text; using System.Windows.Forms; using System.Drawing; using System.ComponentModel; namespace CSharpWin_JD.CaptureImage { /* 作者:Starts_2000 * (涂剑凯修改 http://www.cnblogs.com/bdstjk/) * 日期:2009-09-08 * 网站:http://www.csharpwin.com CS 程序员之窗。 * 你可以免费使用或修改以下代码,但请保留版权信息。 * 具体请查看 CS程序员之窗开源协议(http://www.csharpwin.com/csol.html)。 */ public class ColorLabel : Control { #region Fields private Color _borderColor = Color.FromArgb(65, 173, 236); #endregion #region Constructors public ColorLabel() : base() { SetStyles(); } #endregion #region Properties [DefaultValue(typeof(Color),"65, 173, 236")] public Color BorderColor { get { return _borderColor; } set { _borderColor = value; base.Invalidate(); } } protected override Size DefaultSize { get { return new Size(16, 16); } } #endregion #region Private Methods private void SetStyles() { base.SetStyle( ControlStyles.UserPaint | ControlStyles.OptimizedDoubleBuffer | ControlStyles.AllPaintingInWmPaint | ControlStyles.ResizeRedraw, true); base.UpdateStyles(); } #endregion #region OverideMethods protected override void OnPaint(PaintEventArgs e) { base.OnPaint(e); Graphics g = e.Graphics; Rectangle rect = ClientRectangle; using (SolidBrush brush = new SolidBrush(base.BackColor)) { g.FillRectangle( brush, rect); } ControlPaint.DrawBorder( g, rect, _borderColor, ButtonBorderStyle.Solid); rect.Inflate(-1, -1); ControlPaint.DrawBorder( g, rect, Color.White, ButtonBorderStyle.Solid); } #endregion } }
ioilala/desktoponline
CaptureImageTool/ColorLabel.cs
C#
gpl-2.0
2,418
/**************************************************************************** ** Meta object code from reading C++ file 'qlcoutplugin.h' ** ** Created: Fri Sep 2 17:15:15 2011 ** by: The Qt Meta Object Compiler version 62 (Qt 4.7.4) ** ** WARNING! All changes made in this file will be lost! *****************************************************************************/ #include "../../interfaces/qlcoutplugin.h" #if !defined(Q_MOC_OUTPUT_REVISION) #error "The header file 'qlcoutplugin.h' doesn't include <QObject>." #elif Q_MOC_OUTPUT_REVISION != 62 #error "This file was generated using the moc from 4.7.4. It" #error "cannot be used with the include files from this version of Qt." #error "(The moc has changed too much.)" #endif QT_BEGIN_MOC_NAMESPACE static const uint qt_meta_data_QLCOutPlugin[] = { // content: 5, // revision 0, // classname 0, 0, // classinfo 1, 14, // methods 0, 0, // properties 0, 0, // enums/sets 0, 0, // constructors 0, // flags 1, // signalCount // signals: signature, parameters, type, tag, flags 14, 13, 13, 13, 0x05, 0 // eod }; static const char qt_meta_stringdata_QLCOutPlugin[] = { "QLCOutPlugin\0\0configurationChanged()\0" }; const QMetaObject QLCOutPlugin::staticMetaObject = { { &QObject::staticMetaObject, qt_meta_stringdata_QLCOutPlugin, qt_meta_data_QLCOutPlugin, 0 } }; #ifdef Q_NO_DATA_RELOCATION const QMetaObject &QLCOutPlugin::getStaticMetaObject() { return staticMetaObject; } #endif //Q_NO_DATA_RELOCATION const QMetaObject *QLCOutPlugin::metaObject() const { return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject; } void *QLCOutPlugin::qt_metacast(const char *_clname) { if (!_clname) return 0; if (!strcmp(_clname, qt_meta_stringdata_QLCOutPlugin)) return static_cast<void*>(const_cast< QLCOutPlugin*>(this)); return QObject::qt_metacast(_clname); } int QLCOutPlugin::qt_metacall(QMetaObject::Call _c, int _id, void **_a) { _id = QObject::qt_metacall(_c, _id, _a); if (_id < 0) return _id; if (_c == QMetaObject::InvokeMetaMethod) { switch (_id) { case 0: configurationChanged(); break; default: ; } _id -= 1; } return _id; } // SIGNAL 0 void QLCOutPlugin::configurationChanged() { QMetaObject::activate(this, &staticMetaObject, 0, 0); } QT_END_MOC_NAMESPACE
alexpaulzor/qlc
plugins/enttecdmxusbout/src/moc_qlcoutplugin.cpp
C++
gpl-2.0
2,500
<!DOCTYPE TS><TS> <context> <name>Board</name> <message> <source>Blanks: </source> <translation>Blanco:</translation> </message> <message> <source>OK</source> <translation>OK</translation> </message> <message> <source>Cancel</source> <translation>Annuleer</translation> </message> <message> <source>Unknown word</source> <translation>Onbekend woord</translation> </message> <message> <source>&lt;p&gt;The word &quot;%1&quot; is not in the dictionary.</source> <translation>&lt;p&gt;Het woord &quot;%1&quot; staat niet in het woordenboek.</translation> </message> <message> <source>Add</source> <translation>Voeg toe</translation> </message> <message> <source>Ignore</source> <translation>Negeer</translation> </message> </context> <context> <name>NewGameBase</name> <message> <source>Players</source> <translation>Spelers</translation> </message> <message> <source>AI3: Smart AI player</source> <translation>AI3: Slimme AI speler</translation> </message> <message> <source>Rules</source> <translation>Regels</translation> </message> <message> <source>&amp;Start</source> <translation>&amp;Start</translation> </message> </context> <context> <name>RulesBase</name> <message> <source>Game Rules</source> <translation>Spelregels</translation> </message> <message> <source>Name:</source> <translation>Naam:</translation> </message> <message> <source>Board</source> <translation>Bord</translation> </message> <message> <source>Size:</source> <translation>Grootte:</translation> </message> <message> <source>Edit...</source> <translation>Wijzig...</translation> </message> <message> <source>Delete</source> <translation>Verwijder</translation> </message> <message> <source>&amp;OK</source> <translation>&amp;OK</translation> </message> <message> <source>&amp;Cancel</source> <translation>&amp;Annuleer</translation> </message> </context> <context> <name>ScoreInfo</name> <message> <source>&lt;P&gt;Invalid move</source> <translation>&lt;p&gt;Foute zet</translation> </message> <message> <source>&lt;P&gt;Score: </source> <translation>&lt;p&gt;Score:</translation> </message> </context> <context> <name>WordGame</name> <message> <source>Word Game</source> <translation>Woordspel</translation> </message> <message> <source>Back</source> <translation>Terug</translation> </message> <message> <source>Done</source> <translation>Klaar</translation> </message> <message> <source>Close</source> <translation>Sluit</translation> </message> <message> <source>End game</source> <translation>Einde spel</translation> </message> <message> <source>Do you want to end the game early?</source> <translation>Wil je tijdens het spel stoppen?</translation> </message> <message> <source>Yes</source> <translation>Ja</translation> </message> <message> <source>No</source> <translation>Nee</translation> </message> </context> </TS>
opieproject/opie
i18n/nl/wordgame.ts
TypeScript
gpl-2.0
3,521
<?php /** * Class AMP_Validated_URL_Post_Type * * @package AMP */ use AmpProject\AmpWP\Admin\OptionsMenu; use AmpProject\AmpWP\Admin\ValidationCounts; use AmpProject\AmpWP\Icon; use AmpProject\AmpWP\Option; use AmpProject\AmpWP\QueryVar; use AmpProject\AmpWP\Services; /** * Class AMP_Validated_URL_Post_Type * * @since 1.0 * @internal */ class AMP_Validated_URL_Post_Type { /** * The slug of the post type to store URLs that have AMP errors. * * @var string */ const POST_TYPE_SLUG = 'amp_validated_url'; /** * Postmeta key for storing stylesheet data. * * @var string */ const STYLESHEETS_POST_META_KEY = '_amp_stylesheets'; /** * Postmeta key for storing queried object data. * * @var string */ const QUERIED_OBJECT_POST_META_KEY = '_amp_queried_object'; /** * Postmeta key for storing validated environment data. * * @var string */ const VALIDATED_ENVIRONMENT_POST_META_KEY = '_amp_validated_environment'; /** * Postmeta key for storing PHP fatal error data. * * @var string */ const PHP_FATAL_ERROR_POST_META_KEY = '_amp_php_fatal_error'; /** * The action to recheck URLs for AMP validity. * * @var string */ const VALIDATE_ACTION = 'amp_validate'; /** * The action to bulk recheck URLs for AMP validity. * * @var string */ const BULK_VALIDATE_ACTION = 'amp_bulk_validate'; /** * Action to update the status of AMP validation errors. * * @var string */ const UPDATE_POST_TERM_STATUS_ACTION = 'amp_update_validation_error_status'; /** * The query arg for whether there are remaining errors after rechecking URLs. * * @var string */ const REMAINING_ERRORS = 'amp_remaining_errors'; /** * The handle for the post edit screen script. * * @var string */ const EDIT_POST_SCRIPT_HANDLE = 'amp-validated-url-post-edit-screen'; /** * The query arg for the number of URLs tested. * * @var string */ const URLS_TESTED = 'amp_urls_tested'; /** * The nonce action for rechecking a URL. * * @var string */ const NONCE_ACTION = 'amp_recheck_'; /** * The name of the side meta box on the CPT post.php page. * * @var string */ const STATUS_META_BOX = 'amp_validation_status'; /** * The transient key to use for caching the number of URLs with new validation errors. * * @var string */ const NEW_VALIDATION_ERROR_URLS_COUNT_TRANSIENT = 'amp_new_validation_error_urls_count'; /** * The name of the input that captures the current state of validation errors. * * @var string */ const VALIDATION_ERRORS_INPUT_KEY = 'validation_errors'; /** * The total number of errors associated with a URL, regardless of the maximum that can display. * * @var int */ public static $total_errors_for_url; /** * Registers the post type to store URLs with validation errors. * * @return void */ public static function register() { add_action( 'amp_plugin_update', [ __CLASS__, 'handle_plugin_update' ] ); $dev_tools_user_access = Services::get( 'dev_tools.user_access' ); // Show in the admin menu if dev tools are enabled for the user or if the user is on any dev tools screen. $show_in_menu = ( $dev_tools_user_access->is_user_enabled() || ( isset( $_GET['post_type'] ) && self::POST_TYPE_SLUG === $_GET['post_type'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended || ( isset( $_GET['post'], $_GET['action'] ) && 'edit' === $_GET['action'] && self::POST_TYPE_SLUG === get_post_type( (int) $_GET['post'] ) ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended || ( isset( $_GET['taxonomy'] ) && AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG === $_GET['taxonomy'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended ); if ( $show_in_menu && current_user_can( 'manage_options' ) ) { $show_in_menu = AMP_Options_Manager::OPTION_NAME; } register_post_type( self::POST_TYPE_SLUG, [ 'labels' => [ 'all_items' => __( 'All Validated URLs', 'amp' ), 'name' => _x( 'AMP Validated URLs', 'post type general name', 'amp' ), 'menu_name' => __( 'Validated URLs', 'amp' ), 'singular_name' => __( 'Validated URL', 'amp' ), 'not_found' => __( 'No validated URLs found', 'amp' ), 'not_found_in_trash' => __( 'No forgotten validated URLs', 'amp' ), 'search_items' => __( 'Search validated URLs', 'amp' ), 'edit_item' => '', // Overwritten in JS, so this prevents the page header from appearing and changing. ], 'supports' => false, 'public' => false, 'show_ui' => true, 'show_in_menu' => $show_in_menu, 'map_meta_cap' => false, 'capabilities' => array_merge( array_fill_keys( [ 'edit_post', 'read_post', 'delete_post', 'edit_posts', 'edit_others_posts', 'delete_posts', 'publish_posts', 'read_private_posts', ], AMP_Validation_Manager::VALIDATE_CAPABILITY ), [ // Hide the add new post link, as new posts are created programmatically. 'create_posts' => 'do_not_allow', ] ), // @todo Show in rest. ] ); if ( $show_in_menu ) { add_action( 'admin_menu', [ __CLASS__, 'update_validated_url_menu_item' ] ); } // Rename the top-level menu from "Validated URLs" to "AMP DevTools" when the user does not have access to the AMP settings screen. if ( $show_in_menu && ! current_user_can( 'manage_options' ) ) { add_action( 'admin_menu', static function () { global $menu; foreach ( $menu as &$menu_item ) { if ( 'edit.php?post_type=' . self::POST_TYPE_SLUG === $menu_item[2] ) { $menu_item[0] = esc_html__( 'AMP DevTools', 'amp' ); $menu_item[6] = OptionsMenu::ICON_BASE64_SVG; break; } } } ); } // Ensure cached count of URLs with new validation errors is flushed whenever a URL is updated, trashed, or deleted. $handle_delete = static function ( $post_id ) { if ( static::POST_TYPE_SLUG === get_post_type( $post_id ) ) { delete_transient( static::NEW_VALIDATION_ERROR_URLS_COUNT_TRANSIENT ); delete_transient( AMP_Validation_Error_Taxonomy::TRANSIENT_KEY_ERROR_INDEX_COUNTS ); } }; add_action( 'save_post_' . self::POST_TYPE_SLUG, $handle_delete ); add_action( 'trash_post', $handle_delete ); add_action( 'delete_post', $handle_delete ); if ( is_admin() ) { self::add_admin_hooks(); } } /** * Handle update to plugin. * * @param string $old_version Old version. */ public static function handle_plugin_update( $old_version ) { // Update the old post type slug from amp_invalid_url to amp_validated_url. if ( '1.0-' === substr( $old_version, 0, 4 ) || version_compare( $old_version, '1.0', '<' ) ) { global $wpdb; $post_ids = get_posts( [ 'post_type' => 'amp_invalid_url', 'fields' => 'ids', 'posts_per_page' => -1, ] ); foreach ( $post_ids as $post_id ) { // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery $wpdb->update( $wpdb->posts, [ 'post_type' => self::POST_TYPE_SLUG ], [ 'ID' => $post_id ] ); clean_post_cache( $post_id ); } } } /** * Add admin hooks. */ public static function add_admin_hooks() { add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_post_list_screen_scripts' ] ); // Edit post screen hooks. add_action( 'admin_enqueue_scripts', [ __CLASS__, 'enqueue_edit_post_screen_scripts' ] ); add_action( 'add_meta_boxes', [ __CLASS__, 'add_meta_boxes' ], PHP_INT_MAX ); add_action( 'edit_form_after_title', [ __CLASS__, 'render_single_url_list_table' ] ); add_filter( 'edit_' . AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG . '_per_page', [ __CLASS__, 'get_terms_per_page' ] ); add_action( 'admin_init', [ __CLASS__, 'add_taxonomy' ] ); add_action( 'edit_form_top', [ __CLASS__, 'print_url_as_title' ] ); // Post list screen hooks. add_filter( 'view_mode_post_types', static function( $post_types ) { return array_diff( $post_types, [ AMP_Validated_URL_Post_Type::POST_TYPE_SLUG ] ); } ); add_action( 'load-edit.php', static function() { if ( 'edit-' . AMP_Validated_URL_Post_Type::POST_TYPE_SLUG !== get_current_screen()->id ) { return; } add_action( 'admin_head-edit.php', static function() { global $mode; $mode = 'list'; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited } ); } ); add_action( 'admin_notices', [ __CLASS__, 'render_link_to_error_index_screen' ] ); add_filter( 'the_title', [ __CLASS__, 'filter_the_title_in_post_list_table' ], 10, 2 ); add_action( 'restrict_manage_posts', [ __CLASS__, 'render_post_filters' ], 10, 2 ); add_filter( 'manage_' . self::POST_TYPE_SLUG . '_posts_columns', [ __CLASS__, 'add_post_columns' ] ); add_filter( 'manage_' . self::POST_TYPE_SLUG . '_columns', [ __CLASS__, 'add_single_post_columns' ] ); add_action( 'manage_posts_custom_column', [ __CLASS__, 'output_custom_column' ], 10, 2 ); add_filter( 'bulk_actions-edit-' . self::POST_TYPE_SLUG, [ __CLASS__, 'filter_bulk_actions' ], 10, 2 ); add_filter( 'bulk_actions-' . self::POST_TYPE_SLUG, '__return_false' ); add_filter( 'handle_bulk_actions-edit-' . self::POST_TYPE_SLUG, [ __CLASS__, 'handle_bulk_action' ], 10, 3 ); add_action( 'admin_notices', [ __CLASS__, 'print_admin_notice' ] ); add_action( 'admin_action_' . self::VALIDATE_ACTION, [ __CLASS__, 'handle_validate_request' ] ); add_action( 'post_action_' . self::UPDATE_POST_TERM_STATUS_ACTION, [ __CLASS__, 'handle_validation_error_status_update' ] ); add_filter( 'post_row_actions', [ __CLASS__, 'filter_post_row_actions' ], PHP_INT_MAX - 1, 2 ); add_filter( sprintf( 'views_edit-%s', self::POST_TYPE_SLUG ), [ __CLASS__, 'filter_table_views' ] ); add_filter( 'bulk_post_updated_messages', [ __CLASS__, 'filter_bulk_post_updated_messages' ], 10, 2 ); add_filter( 'admin_title', [ __CLASS__, 'filter_admin_title' ] ); // Hide irrelevant "published" label in the AMP Validated URLs post list. add_filter( 'post_date_column_status', static function ( $status, $post ) { if ( AMP_Validated_URL_Post_Type::POST_TYPE_SLUG === get_post_type( $post ) ) { $status = ''; } return $status; }, 10, 2 ); // Prevent query vars from persisting after redirect. add_filter( 'removable_query_args', static function ( $query_vars ) { $query_vars[] = 'amp_actioned'; $query_vars[] = 'amp_taxonomy_terms_updated'; $query_vars[] = AMP_Validated_URL_Post_Type::REMAINING_ERRORS; $query_vars[] = 'amp_urls_tested'; $query_vars[] = 'amp_validate_error'; return $query_vars; } ); } /** * Enqueue style. */ public static function enqueue_post_list_screen_scripts() { $screen = get_current_screen(); if ( ! $screen instanceof \WP_Screen ) { return; } // Enqueue this on both the 'AMP Validated URLs' page and the single URL page. if ( 'edit-' . self::POST_TYPE_SLUG === $screen->id || self::POST_TYPE_SLUG === $screen->id ) { wp_enqueue_style( 'amp-admin-tables', amp_get_asset_url( 'css/admin-tables.css' ), [ 'amp-icons' ], AMP__VERSION ); wp_styles()->add_data( 'amp-admin-tables', 'rtl', 'replace' ); } if ( 'edit-' . self::POST_TYPE_SLUG !== $screen->id ) { return; } wp_register_style( 'amp-validation-tooltips', amp_get_asset_url( 'css/amp-validation-tooltips.css' ), [ 'wp-pointer' ], AMP__VERSION ); wp_styles()->add_data( 'amp-validation-tooltips', 'rtl', 'replace' ); $asset_file = AMP__DIR__ . '/assets/js/amp-validation-tooltips.asset.php'; $asset = require $asset_file; $dependencies = $asset['dependencies']; $version = $asset['version']; wp_register_script( 'amp-validation-tooltips', amp_get_asset_url( 'js/amp-validation-tooltips.js' ), $dependencies, $version, true ); wp_enqueue_style( 'amp-validation-error-taxonomy', amp_get_asset_url( 'css/amp-validation-error-taxonomy.css' ), [ 'common', 'amp-validation-tooltips', 'amp-icons' ], AMP__VERSION ); wp_styles()->add_data( 'amp-validation-error-taxonomy', 'rtl', 'replace' ); wp_enqueue_script( 'amp-validation-detail-toggle', amp_get_asset_url( 'js/amp-validation-detail-toggle.js' ), [ 'wp-dom-ready', 'wp-i18n', 'amp-validation-tooltips' ], AMP__VERSION, true ); } /** * On the 'AMP Validated URLs' screen, renders a link to the 'Error Index' page. * * @see AMP_Validation_Error_Taxonomy::render_link_to_invalid_urls_screen() */ public static function render_link_to_error_index_screen() { if ( ! ( get_current_screen() && 'edit' === get_current_screen()->base && self::POST_TYPE_SLUG === get_current_screen()->post_type ) ) { return; } $taxonomy_object = get_taxonomy( AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ); if ( ! current_user_can( $taxonomy_object->cap->manage_terms ) ) { return; } $id = 'link-errors-index'; printf( '<a href="%s" hidden class="page-title-action" id="%s" style="margin-left: 1rem;">%s</a>', esc_url( get_admin_url( null, 'edit-tags.php?taxonomy=' . AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG . '&post_type=' . self::POST_TYPE_SLUG ) ), esc_attr( $id ), esc_html__( 'View Error Index', 'amp' ) ); ?> <script> jQuery( function( $ ) { // Move the link to after the heading, as it also looks like there's no action for this. $( <?php echo wp_json_encode( '#' . $id ); ?> ).removeAttr( 'hidden' ).insertAfter( $( '.wp-heading-inline' ) ); } ); </script> <?php } /** * Update the "Validated URLs" menu item label and append a count of how many validation error posts there are * next to it. * * @global array $submenu */ public static function update_validated_url_menu_item() { global $submenu; $post_type_menu_slug = 'edit.php?post_type=' . self::POST_TYPE_SLUG; $parent_menu_slug = current_user_can( 'manage_options' ) ? AMP_Options_Manager::OPTION_NAME : $post_type_menu_slug; if ( ! isset( $submenu[ $parent_menu_slug ] ) ) { return; } foreach ( $submenu[ $parent_menu_slug ] as &$submenu_item ) { if ( $post_type_menu_slug === $submenu_item[2] ) { // Use the `menu_name` label as the submenu label instead of the `all_items` label. $menu_name_label = get_post_type_object( self::POST_TYPE_SLUG )->labels->menu_name; $submenu_item[0] = $menu_name_label; if ( ValidationCounts::is_needed() ) { // Append markup to display a loading spinner while the unreviewed count is being fetched. $submenu_item[0] .= ' <span id="amp-new-validation-url-count"></span>'; } break; } } } /** * Get the count of URLs that have new validation errors. * * @since 1.3 * * @return int Count of new validation error URLs. */ public static function get_validation_error_urls_count() { $count = get_transient( static::NEW_VALIDATION_ERROR_URLS_COUNT_TRANSIENT ); if ( false !== $count ) { // Handle case where integer stored in transient gets returned as string when persistent object cache is not // used. This is due to wp_options.option_value being a string. return (int) $count; } // Make sure filter is added in REST API context which is otherwise only added via AMP_Validation_Error_Taxonomy::add_admin_hooks(). $callback = [ AMP_Validation_Error_Taxonomy::class, 'filter_posts_where_for_validation_error_status' ]; $priority = 10; $has_filter = has_filter( 'posts_where', $callback ); if ( false === $has_filter ) { add_filter( 'posts_where', $callback, $priority, 2 ); } $query = new WP_Query( [ 'post_type' => self::POST_TYPE_SLUG, AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_STATUS_QUERY_VAR => [ AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS, AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS, ], 'update_post_meta_cache' => false, 'update_post_term_cache' => false, ] ); // Remove filter if we added it in this method. if ( false === $has_filter ) { remove_filter( 'posts_where', $callback, $priority ); } $count = $query->found_posts; set_transient( static::NEW_VALIDATION_ERROR_URLS_COUNT_TRANSIENT, $count, DAY_IN_SECONDS ); return $count; } /** * Gets validation errors for a given validated URL post. * * @param string|int|WP_Post $url Either the URL string or a post (ID or WP_Post) of amp_validated_url type. * @param array $args { * Args. * * @type bool $ignore_accepted Exclude validation errors that are accepted (invalid markup removed). Default false. * } * @return array List of errors, with keys for term, data, status, and (sanitization) forced. */ public static function get_invalid_url_validation_errors( $url, $args = [] ) { $args = array_merge( [ 'ignore_accepted' => false, ], $args ); // Look up post by URL or ensure the amp_validated_url object. if ( is_string( $url ) ) { $post = self::get_invalid_url_post( $url ); } else { $post = get_post( $url ); } if ( ! $post || self::POST_TYPE_SLUG !== $post->post_type ) { return []; } // Skip when parse error. $stored_validation_errors = json_decode( $post->post_content, true ); if ( ! is_array( $stored_validation_errors ) ) { return []; } $errors = []; foreach ( $stored_validation_errors as $stored_validation_error ) { if ( ! isset( $stored_validation_error['term_slug'] ) ) { continue; } $term = AMP_Validation_Error_Taxonomy::get_term( $stored_validation_error['term_slug'] ); if ( ! $term ) { continue; } $sanitization = AMP_Validation_Error_Taxonomy::get_validation_error_sanitization( $stored_validation_error['data'] ); if ( $args['ignore_accepted'] && ( AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS === $sanitization['status'] || AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS === $sanitization['status'] ) ) { continue; } $errors[] = array_merge( [ 'term' => $term, 'data' => $stored_validation_error['data'], ], $sanitization ); } return $errors; } /** * Display summary of the validation error counts for a given post. * * @param int|WP_Post $post Post of amp_validated_url type. */ public static function display_invalid_url_validation_error_counts_summary( $post ) { $validation_errors = self::get_invalid_url_validation_errors( $post ); $counts = self::count_invalid_url_validation_errors( $validation_errors ); $removed_count = ( $counts['new_accepted'] + $counts['ack_accepted'] ); $kept_count = ( $counts['new_rejected'] + $counts['ack_rejected'] ); $result = []; if ( $kept_count ) { $title = ''; if ( $counts['new_rejected'] > 0 && $counts['ack_rejected'] > 0 ) { $title = sprintf( /* translators: %s is the count of new validation errors */ _n( '%s validation error with kept markup is new', '%s validation errors with kept markup are new', $counts['new_rejected'], 'amp' ), $counts['new_rejected'] ); } $result[] = sprintf( '<span class="status-text %s" title="%s">%s %s: %s</span>', esc_attr( $counts['new_rejected'] > 0 ? 'has-new' : '' ), esc_attr( $title ), Icon::invalid()->to_html(), esc_html__( 'Invalid markup kept', 'amp' ), number_format_i18n( $kept_count ) ); } if ( $removed_count ) { $title = ''; if ( $counts['new_accepted'] > 0 && $counts['ack_accepted'] > 0 ) { $title = sprintf( /* translators: %s is the count of new validation errors */ _n( '%s validation error with removed markup is new', '%s validation errors with removed markup are new', $counts['new_rejected'], 'amp' ), $counts['new_accepted'] ); } $icon = ( $counts['new_accepted'] + $counts['new_rejected'] ) > 0 ? Icon::removed() : Icon::valid(); $result[] = sprintf( '<span class="status-text %s" title="%s">%s %s: %s</span>', esc_attr( $counts['new_accepted'] > 0 ? 'has-new' : '' ), esc_attr( $title ), $icon->to_html(), esc_html__( 'Invalid markup removed', 'amp' ), number_format_i18n( $removed_count ) ); } if ( 0 === $removed_count && 0 === $kept_count ) { $result[] = sprintf( '<span class="status-text">%s %s</span>', Icon::valid()->to_html(), esc_html__( 'All markup valid', 'amp' ) ); } echo implode( '', $result ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped printf( '<input class="amp-validation-error-new" type="hidden" value="%d">', (int) ( $counts['new_accepted'] + $counts['new_rejected'] > 0 ) ); } /** * Gets the existing custom post that stores errors for the $url, if it exists. * * @param string $url The (in)valid URL. * @param array $options { * Options. * * @type bool $normalize Whether to normalize the URL. * @type bool $include_trashed Include trashed. * } * @return WP_Post|null The post of the existing custom post, or null. */ public static function get_invalid_url_post( $url, $options = [] ) { $default = [ 'normalize' => true, 'include_trashed' => false, ]; $options = wp_parse_args( $options, $default ); if ( $options['normalize'] ) { $url = self::normalize_url_for_storage( $url ); } $slug = md5( $url ); $post = get_page_by_path( $slug, OBJECT, self::POST_TYPE_SLUG ); if ( $post instanceof WP_Post ) { return $post; } if ( $options['include_trashed'] ) { $post = get_page_by_path( $slug . '__trashed', OBJECT, self::POST_TYPE_SLUG ); if ( $post instanceof WP_Post ) { return $post; } } return null; } /** * Get the URL from a given amp_validated_url post. * * The URL will be returned with the amp query var added to it if the site is not canonical. The post_title * is always stored using the canonical AMP-less URL. * * @param int|WP_Post $post Post. * @return string|null The URL stored for the post or null if post does not exist or it is not the right type. */ public static function get_url_from_post( $post ) { $post = get_post( $post ); if ( ! $post || self::POST_TYPE_SLUG !== $post->post_type ) { return null; } $url = $post->post_title; // Add AMP query var if in transitional mode. if ( ! amp_is_canonical() ) { $url = amp_add_paired_endpoint( $url ); } // Set URL scheme based on whether HTTPS is current. $url = set_url_scheme( $url, ( 'http' === wp_parse_url( home_url(), PHP_URL_SCHEME ) ) ? 'http' : 'https' ); return $url; } /** * Get the markup status preview URL. * * Adds a _wpnonce query param for the markup status preview action. * * @since 1.5.0 * * @param string $url Frontend URL to preview markup status changes. * @return string Preview URL. */ protected static function get_markup_status_preview_url( $url ) { return add_query_arg( '_wpnonce', wp_create_nonce( AMP_Validation_Manager::MARKUP_STATUS_PREVIEW_ACTION ), $url ); } /** * Normalize a URL for storage. * * The AMP query param is removed to facilitate switching between standard and transitional. * The URL scheme is also normalized to HTTPS to help with transition from HTTP to HTTPS. * * @param string $url URL. * @return string Normalized URL. */ public static function normalize_url_for_storage( $url ) { // Only ever store the canonical version. if ( ! amp_is_canonical() ) { $url = amp_remove_paired_endpoint( $url ); } // Remove fragment identifier in the rare case it could be provided. It is irrelevant for validation. $url = strtok( $url, '#' ); // Query args to be removed from validated URLs. $removable_query_vars = array_merge( wp_removable_query_args(), [ 'preview_id', 'preview_nonce', 'preview', QueryVar::NOAMP, AMP_Validation_Manager::VALIDATE_QUERY_VAR ] ); // Normalize query args, removing all that are not recognized or which are removable. $url_parts = explode( '?', $url, 2 ); if ( 2 === count( $url_parts ) ) { $args = wp_parse_args( $url_parts[1] ); foreach ( $removable_query_vars as $removable_query_arg ) { unset( $args[ $removable_query_arg ] ); } $url = $url_parts[0]; if ( ! empty( $args ) ) { $url = $url_parts[0] . '?' . build_query( $args ); } } // Normalize the scheme as HTTPS. $url = set_url_scheme( $url, 'https' ); return $url; } /** * Stores the validation errors. * * If there are no validation errors provided, then any existing amp_validated_url post is deleted. * * @param array $validation_errors Validation errors. * @param string $url URL on which the validation errors occurred. Will be normalized to non-AMP version. * @param array $args { * Args. * * @type int|WP_Post $invalid_url_post Post to update. Optional. If empty, then post is looked up by URL. * @type array $queried_object Queried object, including keys for type and id. May be empty. * @type array $stylesheets Stylesheet data. May be empty. * @type array $php_fatal_error PHP Fatal Error. May be empty. * } * @return int|WP_Error $post_id The post ID of the custom post type used, or WP_Error on failure. * @global WP $wp */ public static function store_validation_errors( $validation_errors, $url, $args = [] ) { $url = self::normalize_url_for_storage( $url ); $slug = md5( $url ); $post = null; if ( ! empty( $args['invalid_url_post'] ) ) { $post = get_post( $args['invalid_url_post'] ); } if ( ! $post ) { $post = self::get_invalid_url_post( $url, [ 'include_trashed' => true, 'normalize' => false, // Since already normalized. ] ); } /* * The details for individual validation errors is stored in the amp_validation_error taxonomy terms. * The post content just contains the slugs for these terms and the sources for the given instance of * the validation error. */ $stored_validation_errors = []; // Prevent Kses from corrupting JSON in description. $pre_term_description_filters = [ 'wp_filter_kses' => has_filter( 'pre_term_description', 'wp_filter_kses' ), 'wp_targeted_link_rel' => has_filter( 'pre_term_description', 'wp_targeted_link_rel' ), ]; foreach ( $pre_term_description_filters as $callback => $priority ) { if ( false !== $priority ) { remove_filter( 'pre_term_description', $callback, $priority ); } } $terms = []; foreach ( $validation_errors as $data ) { $term_data = AMP_Validation_Error_Taxonomy::prepare_validation_error_taxonomy_term( $data ); $term_slug = $term_data['slug']; if ( ! isset( $terms[ $term_slug ] ) ) { // Not using WP_Term_Query since more likely individual terms are cached and wp_insert_term() will itself look at this cache anyway. $term = AMP_Validation_Error_Taxonomy::get_term( $term_slug ); if ( ! ( $term instanceof WP_Term ) ) { /* * The default term_group is 0 so that is AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS. * If sanitization auto-acceptance is enabled, then the term_group will be updated below. */ $r = wp_insert_term( $term_slug, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, wp_slash( $term_data ) ); if ( is_wp_error( $r ) ) { continue; } $term_id = $r['term_id']; update_term_meta( $term_id, 'created_date_gmt', current_time( 'mysql', true ) ); /* * When sanitization is forced by filter, make sure the term is created with the filtered status. * For some reason, the wp_insert_term() function doesn't work with the term_group being passed in. */ $sanitization = AMP_Validation_Error_Taxonomy::get_validation_error_sanitization( $data ); if ( 'with_filter' === $sanitization['forced'] ) { $term_data['term_group'] = $sanitization['status']; wp_update_term( $term_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, [ 'term_group' => $sanitization['status'], ] ); } elseif ( AMP_Validation_Manager::is_sanitization_auto_accepted( $data ) ) { $term_data['term_group'] = AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS; wp_update_term( $term_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, [ 'term_group' => $term_data['term_group'], ] ); } $term = get_term( $term_id ); } $terms[ $term_slug ] = $term; } $stored_validation_errors[] = compact( 'term_slug', 'data' ); } // Finish preventing Kses from corrupting JSON in description. foreach ( $pre_term_description_filters as $callback => $priority ) { if ( false !== $priority ) { add_filter( 'pre_term_description', $callback, $priority ); } } $post_content = wp_json_encode( $stored_validation_errors ); $placeholder = 'amp_validated_url_content_placeholder' . wp_rand(); // Guard against Kses from corrupting content by adding post_content after content_save_pre filter applies. $insert_post_content = static function( $post_data ) use ( $placeholder, $post_content ) { $should_supply_post_content = ( isset( $post_data['post_content'], $post_data['post_type'] ) && $placeholder === $post_data['post_content'] && AMP_Validated_URL_Post_Type::POST_TYPE_SLUG === $post_data['post_type'] ); if ( $should_supply_post_content ) { $post_data['post_content'] = wp_slash( $post_content ); } return $post_data; }; add_filter( 'wp_insert_post_data', $insert_post_content ); // Create a new invalid AMP URL post, or update the existing one. $r = wp_insert_post( wp_slash( [ 'ID' => $post ? $post->ID : null, 'post_type' => self::POST_TYPE_SLUG, 'post_title' => $url, 'post_name' => $slug, 'post_content' => $placeholder, // Content is provided via wp_insert_post_data filter above to guard against Kses-corruption. 'post_status' => 'publish', ] ), true ); remove_filter( 'wp_insert_post_data', $insert_post_content ); if ( is_wp_error( $r ) ) { return $r; } $post_id = $r; wp_set_object_terms( $post_id, wp_list_pluck( $terms, 'term_id' ), AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ); update_post_meta( $post_id, self::VALIDATED_ENVIRONMENT_POST_META_KEY, self::get_validated_environment() ); if ( isset( $args['queried_object'] ) ) { update_post_meta( $post_id, self::QUERIED_OBJECT_POST_META_KEY, $args['queried_object'] ); } if ( isset( $args['stylesheets'] ) ) { // Note that json_encode() is being used here because wp_slash() will coerce scalar values to strings. update_post_meta( $post_id, self::STYLESHEETS_POST_META_KEY, wp_slash( wp_json_encode( $args['stylesheets'] ) ) ); } if ( isset( $args['php_fatal_error'] ) ) { if ( empty( $args['php_fatal_error'] ) ) { delete_post_meta( $post_id, self::PHP_FATAL_ERROR_POST_META_KEY ); } else { // Note that json_encode() is being used here because wp_slash() will coerce scalar values to strings. update_post_meta( $post_id, self::PHP_FATAL_ERROR_POST_META_KEY, wp_slash( wp_json_encode( $args['php_fatal_error'] ) ) ); } } delete_transient( static::NEW_VALIDATION_ERROR_URLS_COUNT_TRANSIENT ); return $post_id; } /** * Delete batch of stylesheets postmeta. * * Given that parsed CSS can be quite large (250KB+) and is not de-duplicated across each validated URL, it is important * to not store the stylesheet data indefinitely in order to not excessively bloat the database. The reality is that * keeping around the parsed stylesheet data is of little value given that it will quickly go stale as themes and * plugins are updated. * * @since 2.0 * * @param int $count Count of batch size to delete. * @param string|array $before Date before which to find amp_validated_url posts to delete. * Accepts strtotime()-compatible string, or array of 'year', 'month', 'day' values. * @return int Count of postmeta that were deleted. */ public static function delete_stylesheets_postmeta_batch( $count, $before ) { $deleted = 0; $query = new WP_Query( [ 'post_type' => self::POST_TYPE_SLUG, 'meta_key' => self::STYLESHEETS_POST_META_KEY, 'date_query' => [ [ 'before' => $before, ], ], 'fields' => 'ids', 'orderby' => 'date', 'order' => 'ASC', 'posts_per_page' => $count, ] ); foreach ( $query->get_posts() as $post_id ) { if ( delete_post_meta( $post_id, self::STYLESHEETS_POST_META_KEY ) ) { $deleted++; } } return $deleted; } /** * Garbage-collect validated URL posts. * * Now with Site Scanning in v2.2, the most recently published post will be validated on a weekly basis. If the user * never sees the list of Validated URLs--such as when the user doesn't have DevTools turned on--the end result is * a perpetual increase in the number of validated URLs. Over time this will result in validation data taking up * more and more of the database. When all of the validation errors associated with a validated URL are unreviewed, * or if all of the validation errors are related to other validated URLs as well, then there is no need to keep * the old validated URLs in perpetuity. They should be garbage-collected. * * @since 2.2 * * @param int $count Count of batch size to delete. Default is 100. * @param string|array $before Date before which to find amp_validated_url posts to delete. * Accepts strtotime()-compatible string, or array of 'year', 'month', 'day' values. * @return int Count of deleted posts. */ public static function garbage_collect_validated_urls( $count = 100, $before = '1 week ago' ) { $deleted = 0; // The random order in this query is needed in case the oldest 100 URLs end up not being eligible for garbage- // collection. In that case, garbage collection would get stuck. So by getting a random set of validated URLs // we can prevent the garbage collection from ceasing to function. $query = new WP_Query( [ 'post_type' => self::POST_TYPE_SLUG, 'orderby' => 'rand', // phpcs:ignore WordPressVIPMinimum.Performance.OrderByRand.orderby_orderby -- Due to garbage collection, there should not be more than a dozen posts. 'posts_per_page' => $count, 'date_query' => [ [ 'before' => $before, ], ], ] ); foreach ( $query->get_posts() as $post ) { if ( ! self::is_post_safe_to_garbage_collect( $post ) ) { continue; } if ( wp_delete_post( $post->ID ) ) { $deleted++; } } return $deleted; } /** * Check whether an amp_validated_url post is safe to garbage-collect. * * @since 2.2 * * @param WP_Post $validated_url_post Validated URL post. * @return bool Whether safe to garbage-collect. */ public static function is_post_safe_to_garbage_collect( WP_Post $validated_url_post ) { // Check sanity. if ( self::POST_TYPE_SLUG !== $validated_url_post->post_type ) { return false; } // Skip non-stale validated URLs. if ( count( self::get_post_staleness( $validated_url_post ) ) === 0 ) { return false; } $validation_error_terms = wp_get_post_terms( $validated_url_post->ID, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ); if ( ! is_array( $validation_error_terms ) ) { return false; } /** @var WP_Term[] $validation_error_terms */ foreach ( $validation_error_terms as $validation_error_term ) { // If this error is associated with other URL(s), the reference count will remain non-zero if this validated // URL is garbage-collected, and thus the term will not be removed as part of the Clear Empty operation. if ( $validation_error_term->count > 1 ) { continue; } // If the validation error has been reviewed (aka acknowledged), then check to make sure that the // validation error is associated with at least one other URL. This is so that when a user clicks // Clear Empty they won't inadvertently clear out the reviewed validation error terms. This is only // relevant when the user has DevTools turned on, as this is the way that a term could have the // reviewed state in the first place. if ( in_array( $validation_error_term->term_group, [ AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS, ], true ) ) { // This URL is the only one that is associated with the term, so it's not safe to garbage collect. return false; } // If the term's removal status is not the same as the default removed status for the validation // error, and this is the only instance of that validation error for a URL, then skip removing the URL. $is_sanitized = in_array( $validation_error_term->term_group, [ AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS, AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS, ], true ); $error_data = json_decode( $validation_error_term->description, true ); if ( is_array( $error_data ) && AMP_Validation_Manager::is_sanitization_auto_accepted( $error_data ) !== $is_sanitized ) { return false; } } return true; } /** * Get recent validation errors by source. * * @since 2.0 * @todo This can be stored in object cache, invalidated whenever a validated URL post is inserted/updated/deleted. * * @param int $count Maximum count of validated URLs to gather validation errors from. * @return array Multidimensional array where root keys are source types, sub-keys are source names, and leaf arrays are the validation error terms, data, and the post IDs the error occurs on. */ public static function get_recent_validation_errors_by_source( $count = 100 ) { $posts = get_posts( [ 'post_type' => self::POST_TYPE_SLUG, 'posts_per_page' => $count, 'orderby' => 'date', 'order' => 'desc', ] ); $errors_by_source = []; foreach ( $posts as $post ) { // Skip validated URLs which are stale since results will be misleading. if ( self::get_post_staleness( $post ) ) { continue; } $validation_errors = self::get_invalid_url_validation_errors( $post ); if ( empty( $validation_errors ) ) { continue; } foreach ( $validation_errors as $validation_error ) { if ( empty( $validation_error['data']['sources'] ) || ! $validation_error['term'] instanceof WP_Term ) { continue; } foreach ( $validation_error['data']['sources'] as $source ) { if ( ! isset( $source['type'], $source['name'] ) ) { continue; } $data = json_decode( $validation_error['term']->description, true ); if ( ! is_array( $data ) ) { continue; } if ( ! isset( $errors_by_source[ $source['type'] ][ $source['name'] ][ $validation_error['term']->slug ] ) ) { $errors_by_source[ $source['type'] ][ $source['name'] ][ $validation_error['term']->slug ] = [ 'term' => $validation_error['term'], 'data' => $data, 'post_ids' => [], ]; } $errors_by_source[ $source['type'] ][ $source['name'] ][ $validation_error['term']->slug ]['post_ids'][] = $post->ID; } } } return $errors_by_source; } /** * Get the environment properties which will likely effect whether validation results are stale. * * @return array Environment. */ public static function get_validated_environment() { $plugin_registry = Services::get( 'plugin_registry' ); $theme = []; $theme_obj = null; if ( Services::get( 'reader_theme_loader' )->is_enabled() ) { $theme_obj = Services::get( 'reader_theme_loader' )->get_reader_theme(); } if ( ! $theme_obj instanceof WP_Theme ) { $theme_obj = wp_get_theme(); } if ( ! $theme_obj->errors() ) { $theme[ $theme_obj->get_stylesheet() ] = $theme_obj->get( 'Version' ); $parent_theme_obj = $theme_obj->parent(); if ( $parent_theme_obj ) { $theme[ $parent_theme_obj->get_stylesheet() ] = $parent_theme_obj->get( 'Version' ); } } return [ 'theme' => $theme, 'plugins' => wp_list_pluck( $plugin_registry->get_plugins( true, false ), 'Version' ), // @todo What about multiple plugins being in the same directory? 'options' => wp_array_slice_assoc( AMP_Options_Manager::get_options(), [ Option::ALL_TEMPLATES_SUPPORTED, Option::READER_THEME, Option::SUPPORTED_POST_TYPES, Option::SUPPORTED_TEMPLATES, Option::THEME_SUPPORT, ] ), ]; } /** * Get the differences between the current themes, plugins, and relevant options when amp_validated_url post was last updated and now. * * @param int|WP_Post $post Post of amp_validated_url type. * @return array { * Staleness of the validation results. An empty array if the results are fresh. * * @type string $theme The theme that was active but is no longer. Absent if theme is the same. * @type array $plugins Plugins that used to be active but are no longer, or which are active now but weren't. Also includes plugins that have version updates. Absent if the plugins were the same. * @type array $options Options that used to be set. Absent if the options were the same. * } */ public static function get_post_staleness( $post ) { $post = get_post( $post ); if ( empty( $post ) || self::POST_TYPE_SLUG !== $post->post_type ) { return []; } $old_validated_environment = get_post_meta( $post->ID, self::VALIDATED_ENVIRONMENT_POST_META_KEY, true ); $new_validated_environment = self::get_validated_environment(); $staleness = []; // Theme difference. if ( isset( $old_validated_environment['theme'] ) && $new_validated_environment['theme'] !== $old_validated_environment['theme'] ) { if ( is_string( $old_validated_environment['theme'] ) ) { $old_validated_environment['theme'] = [ $old_validated_environment['theme'] => null, ]; } $new_active_theme = array_diff_assoc( $new_validated_environment['theme'], $old_validated_environment['theme'] ); if ( ! empty( $new_active_theme ) ) { $staleness['theme']['new'] = array_keys( $new_active_theme ); } $old_active_theme = array_diff_assoc( $old_validated_environment['theme'], $new_validated_environment['theme'] ); if ( ! empty( $old_active_theme ) ) { $staleness['theme']['old'] = array_keys( $old_active_theme ); } } // Plugin difference. if ( isset( $old_validated_environment['plugins'] ) ) { $new_active_plugins = array_diff_assoc( $new_validated_environment['plugins'], $old_validated_environment['plugins'] ); if ( ! empty( $new_active_plugins ) ) { $staleness['plugins']['new'] = array_keys( $new_active_plugins ); } $old_active_plugins = array_diff_assoc( $old_validated_environment['plugins'], $new_validated_environment['plugins'] ); if ( ! empty( $old_active_plugins ) ) { $staleness['plugins']['old'] = array_keys( $old_active_plugins ); } } // Options difference. if ( isset( $old_validated_environment['options'] ) ) { $old_options = $old_validated_environment['options']; } else { $old_options = []; } $option_differences = []; foreach ( $new_validated_environment['options'] as $option => $value ) { if ( ! isset( $old_options[ $option ] ) ) { $option_differences[ $option ] = null; } elseif ( $old_options[ $option ] !== $value ) { $option_differences[ $option ] = $old_options[ $option ]; } } if ( ! empty( $option_differences ) ) { $staleness['options'] = $option_differences; } return $staleness; } /** * Adds post columns to the UI for the validation errors. * * @param array $columns The post columns. * @return array $columns The new post columns. */ public static function add_post_columns( $columns ) { $columns = array_merge( $columns, [ AMP_Validation_Error_Taxonomy::ERROR_STATUS => sprintf( '%s<span class="dashicons dashicons-editor-help tooltip-button" tabindex="0"></span><div class="tooltip" hidden data-content="%s"></div>', esc_html__( 'Markup Status', 'amp' ), esc_attr( sprintf( '<h3>%s</h3><p>%s</p>', __( 'Markup Status', 'amp' ), __( 'When invalid markup is removed it will not block a URL from being served as AMP; the validation error will be sanitized, where the offending markup is stripped from the response to ensure AMP validity. If invalid AMP markup is kept, then URLs is occurs on will not be served as AMP pages.', 'amp' ) ) ) ), AMP_Validation_Error_Taxonomy::FOUND_ELEMENTS_AND_ATTRIBUTES => esc_html__( 'Invalid Markup', 'amp' ), AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT => esc_html__( 'Sources', 'amp' ), 'css_usage' => esc_html__( 'CSS Usage', 'amp' ), ] ); if ( isset( $columns['title'] ) ) { $columns['title'] = esc_html__( 'URL', 'amp' ); } // Move date to end. if ( isset( $columns['date'] ) ) { unset( $columns['date'] ); $columns['date'] = esc_html__( 'Last Checked', 'amp' ); } if ( ! empty( $_GET[ AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended unset( $columns['error_status'], $columns[ AMP_Validation_Error_Taxonomy::REMOVED_ELEMENTS ], $columns[ AMP_Validation_Error_Taxonomy::REMOVED_ATTRIBUTES ] ); $columns[ AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT ] = esc_html__( 'Sources', 'amp' ); $columns['date'] = esc_html__( 'Last Checked', 'amp' ); $columns['title'] = esc_html__( 'URL', 'amp' ); } return $columns; } /** * Adds post columns to the /wp-admin/post.php page for amp_validated_url. * * @return array The filtered post columns. */ public static function add_single_post_columns() { return [ 'cb' => '<input type="checkbox" />', 'error_code' => __( 'Error', 'amp' ), 'error_type' => __( 'Type', 'amp' ), 'details' => sprintf( '%s<span class="dashicons dashicons-editor-help tooltip-button" tabindex="0"></span><div class="tooltip" hidden data-content="%s"></div>', esc_html__( 'Context', 'amp' ), esc_attr( sprintf( '<h3>%s</h3><p>%s</p>', esc_html__( 'Context', 'amp' ), esc_html__( 'The parent element of where the error occurred.', 'amp' ) ) ) ), 'sources_with_invalid_output' => __( 'Sources', 'amp' ), 'status' => sprintf( '%s<span class="dashicons dashicons-editor-help tooltip-button" tabindex="0"></span><div class="tooltip" hidden data-content="%s"></div>', esc_html__( 'Markup Status', 'amp' ), esc_attr( sprintf( '<h3>%s</h3><p>%s</p>', esc_html__( 'Markup Status', 'amp' ), esc_html__( 'When invalid markup is removed it will not block a URL from being served as AMP; the validation error will be sanitized, where the offending markup is stripped from the response to ensure AMP validity. If invalid AMP markup is kept, then URLs is occurs on will not be served as AMP pages.', 'amp' ) ) ) ), 'reviewed' => sprintf( '%s<span class="dashicons dashicons-editor-help tooltip-button" tabindex="0"></span><div class="tooltip" hidden data-content="%s"></div>', esc_html__( 'Reviewed', 'amp' ), esc_attr( sprintf( '<h3>%s</h3><p>%s</p>', esc_html__( 'Reviewed', 'amp' ), esc_html__( 'Confirm that the action being taken on the invalid markup (causing a validation error) has been seen and approved.', 'amp' ) ) ) ), ]; } /** * Outputs custom columns in the /wp-admin UI for the AMP validation errors. * * @param string $column_name The name of the column. * @param int $post_id The ID of the post for the column. * @return void */ public static function output_custom_column( $column_name, $post_id ) { $post = get_post( $post_id ); if ( self::POST_TYPE_SLUG !== $post->post_type ) { return; } $validation_errors = self::get_invalid_url_validation_errors( $post_id ); $error_summary = AMP_Validation_Error_Taxonomy::summarize_validation_errors( wp_list_pluck( $validation_errors, 'data' ) ); switch ( $column_name ) { case 'error_status': $staleness = self::get_post_staleness( $post_id ); if ( ! empty( $staleness ) ) { echo '<p><strong><em>' . esc_html__( 'Stale results', 'amp' ) . '</em></strong></p>'; } self::display_invalid_url_validation_error_counts_summary( $post_id ); break; case AMP_Validation_Error_Taxonomy::FOUND_ELEMENTS_AND_ATTRIBUTES: $items = []; if ( ! empty( $error_summary[ AMP_Validation_Error_Taxonomy::REMOVED_ELEMENTS ] ) ) { foreach ( $error_summary[ AMP_Validation_Error_Taxonomy::REMOVED_ELEMENTS ] as $name => $count ) { if ( 1 === (int) $count ) { $items[] = sprintf( '<code>&lt;%s&gt;</code>', esc_html( $name ) ); } else { $items[] = sprintf( '<code>&lt;%s&gt;</code> (%d)', esc_html( $name ), $count ); } } } if ( ! empty( $error_summary[ AMP_Validation_Error_Taxonomy::REMOVED_ATTRIBUTES ] ) ) { foreach ( $error_summary[ AMP_Validation_Error_Taxonomy::REMOVED_ATTRIBUTES ] as $name => $count ) { if ( 1 === (int) $count ) { $items[] = sprintf( '<code>%s</code>', esc_html( $name ) ); } else { $items[] = sprintf( '<code>%s</code> (%d)', esc_html( $name ), $count ); } } } if ( ! empty( $error_summary['removed_pis'] ) ) { foreach ( $error_summary['removed_pis'] as $name => $count ) { if ( 1 === (int) $count ) { $items[] = sprintf( '<code>&lt;?%s&hellip;?&gt;</code>', esc_html( $name ) ); } else { $items[] = sprintf( '<code>&lt;?%s&hellip;?&gt;</code> (%d)', esc_html( $name ), $count ); } } } if ( ! empty( $items ) ) { $imploded_items = implode( ',</div><div>', $items ); echo sprintf( '<div>%s</div>', $imploded_items ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } else { esc_html_e( '--', 'amp' ); } break; case 'css_usage': $style_custom_cdata_spec = null; foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'style' ) as $spec_rule ) { if ( isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) && AMP_Style_Sanitizer::STYLE_AMP_CUSTOM_SPEC_NAME === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) { $style_custom_cdata_spec = $spec_rule[ AMP_Rule_Spec::CDATA ]; } } $stylesheets = json_decode( get_post_meta( $post->ID, self::STYLESHEETS_POST_META_KEY, true ), true ); if ( ! is_array( $stylesheets ) || ! $style_custom_cdata_spec ) { echo esc_html( _x( 'n/a', 'CSS usage not available', 'amp' ) ); } else { $total_size = 0; foreach ( $stylesheets as $stylesheet ) { if ( ! isset( $stylesheet['group'] ) || 'amp-custom' !== $stylesheet['group'] || ! empty( $stylesheet['duplicate'] ) ) { continue; } $total_size += $stylesheet['final_size']; } $css_usage_percentage = ( $total_size / $style_custom_cdata_spec['max_bytes'] ) * 100; if ( $css_usage_percentage > 100 ) { $color = '#a00'; // Red. } elseif ( $css_usage_percentage >= AMP_Style_Sanitizer::CSS_BUDGET_WARNING_PERCENTAGE ) { $color = '#d98500'; // Orange. } else { $color = '#006505'; // Green. } printf( '<span style="color:%s">%s%%</span>', esc_attr( $color ), esc_html( number_format_i18n( ceil( $css_usage_percentage ) ) ) ); } break; case AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT: if ( 0 === count( array_filter( $error_summary ) ) || empty( $error_summary[ AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT ] ) ) { esc_html_e( '--', 'amp' ); } else { self::render_sources_column( $error_summary[ AMP_Validation_Error_Taxonomy::SOURCES_INVALID_OUTPUT ], $post_id ); } break; } } /** * Renders the sources column on the the single error URL page and the 'AMP Validated URLs' page. * * @param array $sources The summary of errors. * @param int $post_id The ID of the amp_validated_url post. */ public static function render_sources_column( $sources, $post_id ) { $active_theme = null; $validated_environment = get_post_meta( $post_id, self::VALIDATED_ENVIRONMENT_POST_META_KEY, true ); if ( isset( $validated_environment['theme'] ) ) { $active_theme = $validated_environment['theme']; } $output = []; $plugin_registry = Services::get( 'plugin_registry' ); foreach ( wp_array_slice_assoc( $sources, [ 'plugin', 'mu-plugin' ] ) as $type => $slugs ) { $plugin_names = []; $plugin_slugs = array_unique( $slugs ); foreach ( $plugin_slugs as $plugin_slug ) { if ( 'mu-plugin' === $type ) { $plugin_names[] = $plugin_slug; } else { // Skip including Gutenberg in the summary if there is another plugin, since Gutenberg is like core. if ( 'gutenberg' === $plugin_slug && count( $slugs ) > 1 ) { continue; } $plugin_name = $plugin_slug; $plugin = $plugin_registry->get_plugin_from_slug( $plugin_slug ); if ( $plugin ) { $plugin_name = $plugin['data']['Name']; } $plugin_names[] = $plugin_name; } } $count = count( $plugin_names ); if ( 1 === $count ) { $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-admin-plugins"></span>%s</strong>', esc_html( $plugin_names[0] ) ); } else { $output[] = '<details class="source">'; $output[] = sprintf( '<summary class="details-attributes__summary"><strong class="source"><span class="dashicons dashicons-admin-plugins"></span>%s (%d)</strong></summary>', 'mu-plugin' === $type ? esc_html__( 'Must-Use Plugins', 'amp' ) : esc_html__( 'Plugins', 'amp' ), $count ); $output[] = '<div>'; $output[] = implode( '<br/>', array_unique( $plugin_names ) ); $output[] = '</div>'; $output[] = '</details>'; } } if ( isset( $sources['theme'] ) && empty( $sources['embed'] ) ) { foreach ( array_unique( $sources['theme'] ) as $theme_slug ) { $theme_obj = wp_get_theme( $theme_slug ); if ( ! $theme_obj->errors() ) { $theme_name = $theme_obj->get( 'Name' ); } else { $theme_name = $theme_slug; } $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-admin-appearance"></span>%s</strong>', esc_html( $theme_name ) ); } } if ( isset( $sources['core'] ) ) { $core_sources = array_unique( $sources['core'] ); $count = count( $core_sources ); if ( 1 === $count ) { $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-wordpress-alt"></span>%s</strong>', esc_html( $core_sources[0] ) ); } else { $output[] = '<details class="source">'; $output[] = sprintf( '<summary class="details-attributes__summary"><strong class="source"><span class="dashicons dashicons-wordpress-alt"></span>%s (%d)</strong></summary>', esc_html__( 'Other', 'amp' ), $count ); $output[] = '<div>'; $output[] = implode( '<br/>', array_unique( $sources['core'] ) ); $output[] = '</div>'; $output[] = '</details>'; } } if ( empty( $output ) && ! empty( $sources['embed'] ) ) { $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-wordpress-alt"></span>%s</strong>', esc_html__( 'Embed', 'amp' ) ); } if ( empty( $output ) && ! empty( $sources['blocks'] ) ) { foreach ( array_unique( $sources['blocks'] ) as $block ) { $block_title = AMP_Validation_Error_Taxonomy::get_block_title( $block ); if ( $block_title ) { $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-edit"></span>%s</strong>', esc_html( $block_title ) ); } else { $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-edit"></span><code>%s</code></strong>', esc_html( $block ) ); } } } if ( empty( $output ) && ! empty( $sources['hook'] ) ) { switch ( $sources['hook'] ) { case 'the_content': $dashicon = 'edit'; $source_name = __( 'Content', 'amp' ); break; case 'the_excerpt': $dashicon = 'edit'; $source_name = __( 'Excerpt', 'amp' ); break; default: $dashicon = 'wordpress-alt'; $source_name = sprintf( /* translators: %s is the hook name */ __( 'Hook: %s', 'amp' ), $sources['hook'] ); } $output[] = sprintf( '<strong class="source"><span class="dashicons dashicons-%s"></span>%s</strong>', esc_attr( $dashicon ), esc_html( $source_name ) ); } if ( empty( $sources ) && $active_theme ) { $theme_obj = wp_get_theme( $active_theme ); if ( ! $theme_obj->errors() ) { $theme_name = $theme_obj->get( 'Name' ); } else { $theme_name = $active_theme; } $output[] = '<div class="source">'; $output[] = '<span class="dashicons dashicons-admin-appearance"></span>'; /* translators: %s is the guessed theme as the source for the error */ $output[] = esc_html( sprintf( __( '%s (?)', 'amp' ), $theme_name ) ); $output[] = '</div>'; } echo implode( '', $output ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } /** * Adds a 'Recheck' bulk action to the edit.php page and modifies the 'Move to Trash' text. * * Ensure only delete action is present, not trash. * * @param array $actions The bulk actions in the edit.php page. * @return array $actions The filtered bulk actions. */ public static function filter_bulk_actions( $actions ) { $has_delete = ( isset( $actions['trash'] ) || isset( $actions['delete'] ) ); unset( $actions['trash'], $actions['delete'] ); if ( $has_delete ) { $actions['delete'] = esc_html__( 'Forget', 'amp' ); } unset( $actions['edit'] ); $actions[ self::BULK_VALIDATE_ACTION ] = esc_html__( 'Recheck', 'amp' ); return $actions; } /** * Handles the 'Recheck' bulk action on the edit.php page. * * @param string $redirect The URL of the redirect. * @param string $action The action. * @param array $items The items on which to take the action. * @return string $redirect The filtered URL of the redirect. */ public static function handle_bulk_action( $redirect, $action, $items ) { if ( self::BULK_VALIDATE_ACTION !== $action ) { return $redirect; } $remaining_invalid_urls = []; $errors = []; foreach ( $items as $item ) { $post = get_post( $item ); if ( empty( $post ) || ! current_user_can( 'edit_post', $post->ID ) ) { continue; } $url = self::get_url_from_post( $post ); if ( empty( $url ) ) { continue; } $validity = AMP_Validation_Manager::validate_url_and_store( $url ); if ( is_wp_error( $validity ) ) { $errors[] = AMP_Validation_Manager::get_validate_url_error_message( $validity->get_error_code(), $validity->get_error_message() ); continue; } $validation_errors = wp_list_pluck( $validity['results'], 'error' ); $unaccepted_error_count = count( array_filter( $validation_errors, static function( $error ) { return ! AMP_Validation_Error_Taxonomy::is_validation_error_sanitized( $error ); } ) ); if ( $unaccepted_error_count > 0 ) { $remaining_invalid_urls[] = $validity['url']; } } // Get the URLs that still have errors after rechecking. $args = [ self::URLS_TESTED => count( $items ), ]; if ( ! empty( $errors ) ) { $args['amp_validate_error'] = AMP_Validation_Manager::serialize_validation_error_messages( $errors ); } else { $args[ self::REMAINING_ERRORS ] = count( $remaining_invalid_urls ); } $redirect = remove_query_arg( wp_removable_query_args(), $redirect ); return add_query_arg( rawurlencode_deep( $args ), $redirect ); } /** * Outputs an admin notice after rechecking URL(s) on the custom post page. * * @return void */ public static function print_admin_notice() { if ( ! get_current_screen() || self::POST_TYPE_SLUG !== get_current_screen()->post_type ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } if ( isset( $_GET['amp_validate_error'] ) && is_string( $_GET['amp_validate_error'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- The input var is validated by the unserialize_validation_error_messages method. $errors = AMP_Validation_Manager::unserialize_validation_error_messages( wp_unslash( $_GET['amp_validate_error'] ) ); if ( $errors ) { foreach ( array_unique( $errors ) as $error_message ) { printf( '<div class="notice is-dismissible error"><p>%s</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">%s</span></button></div>', wp_kses( $error_message, [ 'a' => array_fill_keys( [ 'href', 'target' ], true ), 'code' => [], ] ), esc_html__( 'Dismiss this notice.', 'amp' ) ); } } } if ( isset( $_GET[ self::REMAINING_ERRORS ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $count_urls_tested = isset( $_GET[ self::URLS_TESTED ] ) ? (int) $_GET[ self::URLS_TESTED ] : 1; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $errors_remain = ! empty( $_GET[ self::REMAINING_ERRORS ] ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( $errors_remain ) { $message = _n( 'The rechecked URL still has remaining invalid markup kept.', 'The rechecked URLs still have remaining invalid markup kept.', $count_urls_tested, 'amp' ); $class = 'notice-warning'; } else { $message = _n( 'The rechecked URL is free of non-removed invalid markup.', 'The rechecked URLs are free of non-removed invalid markup.', $count_urls_tested, 'amp' ); $class = 'updated'; } printf( '<div class="notice is-dismissible %s"><p>%s</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">%s</span></button></div>', esc_attr( $class ), esc_html( $message ), esc_html__( 'Dismiss this notice.', 'amp' ) ); } if ( isset( $_GET['amp_taxonomy_terms_updated'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $count = (int) $_GET['amp_taxonomy_terms_updated']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended $class = 'updated'; printf( '<div class="notice is-dismissible %s"><p>%s</p><button type="button" class="notice-dismiss"><span class="screen-reader-text">%s</span></button></div>', esc_attr( $class ), esc_html( sprintf( /* translators: %s is count of validation errors updated */ _n( 'Updated %s validation error.', 'Updated %s validation errors.', $count, 'amp' ), number_format_i18n( $count ) ) ), esc_html__( 'Dismiss this notice.', 'amp' ) ); } // Add notice for PHP fatal error during validation request. $post = get_post(); if ( $post instanceof WP_Post && 'post' === get_current_screen()->base && self::POST_TYPE_SLUG === get_current_screen()->post_type ) { self::render_php_fatal_error_admin_notice( $post ); } /** * Adds notices to the single error page. * 1. If the error does not occur in any validated URL: Notice with button to delete the error. * 2. Notice with detailed error information in an expanding box. */ if ( ! empty( $_GET[ AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ] ) && isset( $_GET['post_type'] ) && self::POST_TYPE_SLUG === $_GET['post_type'] ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended $error_id = sanitize_key( wp_unslash( $_GET[ AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG ] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended $error = AMP_Validation_Error_Taxonomy::get_term( $error_id ); if ( ! $error ) { return; } // @todo Update this to use the method which will be developed in PR #1429 AMP_Validation_Error_Taxonomy::get_term_error() . $validation_error = json_decode( $error->description, true ); if ( ! is_array( $validation_error ) ) { $validation_error = []; } $sanitization = AMP_Validation_Error_Taxonomy::get_validation_error_sanitization( $validation_error ); $error_title = AMP_Validation_Error_Taxonomy::get_error_title_from_code( $validation_error ); if ( 0 === $error->count ) { echo '<div class="notice accept-reject-error"><p>'; esc_html_e( 'There are no validated URLs with this validation error. Would you like to delete it?', 'amp' ); $delete_url = wp_nonce_url( add_query_arg( [ 'action' => 'delete', 'term_id' => $error->term_id, ] ), 'delete' ); printf( ' <a class="button button-small button-primary reject" href="%s">%s</a> ', esc_url( $delete_url ), esc_html__( 'Delete', 'amp' ) ); echo '</p></div>'; } $status_text = AMP_Validation_Error_Taxonomy::get_status_text_with_icon( $sanitization, true ); $status_detail = sprintf( '<dt>%s</dt><dd>%s</dd>', esc_html__( 'Status', 'amp' ), wp_kses_post( $status_text ) ); $error_details = AMP_Validation_Error_Taxonomy::render_single_url_error_details( $validation_error, $error, false, false ); $error_details = str_replace( '<dl class="detailed">', '<dl class="detailed">' . $status_detail, $error_details ); $class = 'notice error-details'; if ( ! ( $sanitization['term_status'] & AMP_Validation_Error_Taxonomy::ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK ) ) { $class .= ' unreviewed'; } ?> <div class="<?php echo esc_attr( $class ); ?>"> <ul> <?php echo $error_details; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> </ul> </div> <?php $heading = wp_kses_post( $error_title ); ?> <script type="text/javascript"> jQuery( function( $ ) { $( 'h1.wp-heading-inline' ).html( <?php echo wp_json_encode( $heading ); ?> ); }); </script> <?php } } /** * Render PHP fatal error admin notice. * * @param WP_Post $post Post. */ private static function render_php_fatal_error_admin_notice( WP_Post $post ) { $error = get_post_meta( $post->ID, self::PHP_FATAL_ERROR_POST_META_KEY, true ); if ( empty( $error ) ) { return; } $error_data = json_decode( $error, true ); if ( ! is_array( $error_data ) || ! isset( $error_data['message'], $error_data['file'], $error_data['line'] ) ) { return; } ?> <div class="notice notice-error"> <p><?php echo AMP_Validation_Manager::get_validate_url_error_message( 'fatal_error_during_validation' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></p> <?php if ( defined( 'WP_DEBUG_DISPLAY' ) && WP_DEBUG_DISPLAY ) : ?> <blockquote> <pre><?php echo esc_html( $error_data['message'] ); ?></pre> </blockquote> <p> <?php esc_html_e( 'Location:', 'amp' ); ?> <code><?php echo esc_html( sprintf( '%s:%d', $error_data['file'], $error_data['line'] ) ); ?></code> </p> <?php endif; ?> </div> <?php } /** * Handles clicking 'recheck' on the inline post actions and in the admin bar on the frontend. * * @throws Exception But it is caught. This is here for a PHPCS bug. */ public static function handle_validate_request() { check_admin_referer( self::NONCE_ACTION ); if ( ! AMP_Validation_Manager::has_cap() ) { wp_die( esc_html__( 'You do not have permissions to validate an AMP URL. Did you get logged out?', 'amp' ) ); } $post = null; $url = null; $args = []; try { if ( isset( $_GET['post'] ) ) { $post = (int) $_GET['post']; if ( $post <= 0 ) { throw new Exception( 'unknown_post' ); } $post = get_post( $post ); if ( ! $post || self::POST_TYPE_SLUG !== $post->post_type ) { throw new Exception( 'invalid_post' ); } if ( ! current_user_can( 'edit_post', $post->ID ) ) { throw new Exception( 'unauthorized' ); } $url = self::get_url_from_post( $post ); } elseif ( isset( $_GET['url'] ) ) { $url = wp_validate_redirect( esc_url_raw( wp_unslash( $_GET['url'] ) ), null ); if ( ! $url ) { throw new Exception( 'illegal_url' ); } // Don't let non-admins create new amp_validated_url posts. if ( ! AMP_Validation_Manager::has_cap() ) { throw new Exception( 'unauthorized' ); } } if ( ! $url ) { throw new Exception( 'missing_url' ); } $validity = AMP_Validation_Manager::validate_url_and_store( $url ); if ( is_wp_error( $validity ) ) { throw new Exception( AMP_Validation_Manager::get_validate_url_error_message( $validity->get_error_code(), $validity->get_error_message() ) ); } $errors = wp_list_pluck( $validity['results'], 'error' ); $redirect = get_edit_post_link( $validity['post_id'], 'raw' ); $error_count = count( array_filter( $errors, static function ( $error ) { return ! AMP_Validation_Error_Taxonomy::is_validation_error_sanitized( $error ); } ) ); $args[ self::URLS_TESTED ] = '1'; $args[ self::REMAINING_ERRORS ] = $error_count; } catch ( Exception $e ) { $args['amp_validate_error'] = AMP_Validation_Manager::serialize_validation_error_messages( [ $e->getMessage() ] ); $args[ self::URLS_TESTED ] = '0'; if ( $post && self::POST_TYPE_SLUG === $post->post_type ) { $redirect = get_edit_post_link( $post->ID, 'raw' ); } else { $redirect = admin_url( add_query_arg( [ 'post_type' => self::POST_TYPE_SLUG ], 'edit.php' ) ); } } wp_safe_redirect( add_query_arg( rawurlencode_deep( $args ), $redirect ) ); exit(); } /** * Re-check validated URL post for whether it has blocking validation errors. * * @param int|WP_Post $post Post. * @return array|WP_Error List of blocking validation results, or a WP_Error in the case of failure. */ public static function recheck_post( $post ) { if ( ! $post ) { return new WP_Error( 'missing_post' ); } $post = get_post( $post ); if ( ! $post ) { return new WP_Error( 'missing_post' ); } $url = self::get_url_from_post( $post ); if ( ! $url ) { return new WP_Error( 'missing_url' ); } $validity = AMP_Validation_Manager::validate_url_and_store( $url, $post ); if ( is_wp_error( $validity ) ) { return $validity; } $validation_errors = wp_list_pluck( $validity['results'], 'error' ); $validation_results = []; foreach ( $validation_errors as $error ) { $sanitized = AMP_Validation_Error_Taxonomy::is_validation_error_sanitized( $error ); // @todo Consider re-using $validity['results'][x]['sanitized'], unless auto-sanitize is causing problem. $validation_results[] = compact( 'error', 'sanitized' ); } return $validation_results; } /** * Handle validation error status update. * * @see AMP_Validation_Error_Taxonomy::handle_validation_error_update() * @todo This is duplicated with logic in AMP_Validation_Error_Taxonomy. All of the term updating needs to be refactored to make use of the REST API. */ public static function handle_validation_error_status_update() { check_admin_referer( self::UPDATE_POST_TERM_STATUS_ACTION, self::UPDATE_POST_TERM_STATUS_ACTION . '_nonce' ); if ( empty( $_POST[ self::VALIDATION_ERRORS_INPUT_KEY ] ) || ! is_array( $_POST[ self::VALIDATION_ERRORS_INPUT_KEY ] ) ) { return; } $post = get_post(); if ( ! $post || self::POST_TYPE_SLUG !== $post->post_type ) { return; } if ( ! AMP_Validation_Manager::has_cap() || ! current_user_can( 'edit_post', $post->ID ) ) { wp_die( esc_html__( 'You do not have permissions to validate an AMP URL. Did you get logged out?', 'amp' ) ); } $updated_count = 0; $has_pre_term_description_filter = has_filter( 'pre_term_description', 'wp_filter_kses' ); if ( false !== $has_pre_term_description_filter ) { remove_filter( 'pre_term_description', 'wp_filter_kses', $has_pre_term_description_filter ); } // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Sanitization performed in loop. foreach ( $_POST[ self::VALIDATION_ERRORS_INPUT_KEY ] as $term_slug => $data ) { if ( ! is_array( $data ) ) { continue; } $status = isset( $data[ AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ] ) ? $data[ AMP_Validation_Manager::VALIDATION_ERROR_TERM_STATUS_QUERY_VAR ] : null; $status_acknowledged = isset( $data[ AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACKNOWLEDGE_ACTION ] ); if ( ! is_numeric( $status ) ) { continue; } $term_slug = sanitize_key( $term_slug ); $term = AMP_Validation_Error_Taxonomy::get_term( $term_slug ); if ( ! $term ) { continue; } $term_group = AMP_Validation_Error_Taxonomy::sanitize_term_status( $status ); if ( null === $term_group ) { continue; } $term_group = $status_acknowledged ? $term_group | AMP_Validation_Error_Taxonomy::ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK : $term_group & ~ AMP_Validation_Error_Taxonomy::ACKNOWLEDGED_VALIDATION_ERROR_BIT_MASK; if ( $term_group !== $term->term_group ) { $updated_count++; wp_update_term( $term->term_id, AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG, compact( 'term_group' ) ); } } if ( false !== $has_pre_term_description_filter ) { add_filter( 'pre_term_description', 'wp_filter_kses', $has_pre_term_description_filter ); } $args = [ 'amp_taxonomy_terms_updated' => $updated_count, ]; // Re-check the post after the validation status change. if ( $updated_count > 0 ) { $validation_results = self::recheck_post( $post->ID ); if ( ! is_wp_error( $validation_results ) ) { $args[ self::REMAINING_ERRORS ] = count( array_filter( $validation_results, static function( $result ) { return ! $result['sanitized']; } ) ); } delete_transient( static::NEW_VALIDATION_ERROR_URLS_COUNT_TRANSIENT ); } $redirect = wp_get_referer(); if ( ! $redirect ) { $redirect = get_edit_post_link( $post->ID, 'raw' ); } $redirect = remove_query_arg( wp_removable_query_args(), $redirect ); wp_safe_redirect( add_query_arg( $args, $redirect ) ); exit(); } /** * Enqueue scripts for the edit post screen. */ public static function enqueue_edit_post_screen_scripts() { $current_screen = get_current_screen(); if ( 'post' !== $current_screen->base || self::POST_TYPE_SLUG !== $current_screen->post_type ) { return; } // Eliminate autosave since it is only relevant for the content editor. wp_dequeue_script( 'autosave' ); $asset_file = AMP__DIR__ . '/assets/js/' . self::EDIT_POST_SCRIPT_HANDLE . '.asset.php'; $asset = require $asset_file; $dependencies = $asset['dependencies']; $version = $asset['version']; wp_enqueue_script( self::EDIT_POST_SCRIPT_HANDLE, amp_get_asset_url( 'js/' . self::EDIT_POST_SCRIPT_HANDLE . '.js' ), $dependencies, $version, true ); // @todo This is likely dead code. $current_screen = get_current_screen(); $post = get_post(); if ( $post && $current_screen && 'post' === $current_screen->base && self::POST_TYPE_SLUG === $current_screen->post_type ) { $data = [ 'amp_enabled' => self::is_amp_enabled_on_post( $post ), ]; wp_localize_script( self::EDIT_POST_SCRIPT_HANDLE, 'ampValidation', $data ); } if ( function_exists( 'wp_set_script_translations' ) ) { wp_set_script_translations( self::EDIT_POST_SCRIPT_HANDLE, 'amp' ); } elseif ( function_exists( 'wp_get_jed_locale_data' ) || function_exists( 'gutenberg_get_jed_locale_data' ) ) { $locale_data = function_exists( 'wp_get_jed_locale_data' ) ? wp_get_jed_locale_data( 'amp' ) : gutenberg_get_jed_locale_data( 'amp' ); $translations = wp_json_encode( $locale_data ); wp_add_inline_script( self::EDIT_POST_SCRIPT_HANDLE, 'wp.i18n.setLocaleData( ' . $translations . ', "amp" );', 'after' ); } } /** * Adds the meta boxes to the CPT post.php page. * * @global array $wp_meta_boxes * @return void */ public static function add_meta_boxes() { global $wp_meta_boxes; $stylesheets_metabox_id = 'amp_stylesheets'; remove_meta_box( 'submitdiv', self::POST_TYPE_SLUG, 'side' ); remove_meta_box( 'slugdiv', self::POST_TYPE_SLUG, 'normal' ); add_meta_box( self::STATUS_META_BOX, __( 'Status', 'amp' ), [ __CLASS__, 'print_status_meta_box' ], self::POST_TYPE_SLUG, 'side', 'default', [ '__back_compat_meta_box' => true ] ); add_meta_box( $stylesheets_metabox_id, __( 'Stylesheets', 'amp' ), [ __CLASS__, 'print_stylesheets_meta_box' ], self::POST_TYPE_SLUG, 'normal', 'default', [ '__back_compat_meta_box' => true ] ); // Ensure only the expected metaboxes are shown on this screen. // Note the O(n^3) complexity here is not a concern because each nested array has only a few items. $allowed_metaboxes = [ 'slugdiv', 'submitdiv', self::STATUS_META_BOX, $stylesheets_metabox_id ]; foreach ( $wp_meta_boxes[ self::POST_TYPE_SLUG ] as $context => $metabox_contexts ) { foreach ( $metabox_contexts as $metabox_priorities ) { foreach ( array_keys( $metabox_priorities ) as $id ) { if ( ! in_array( $id, $allowed_metaboxes, true ) ) { remove_meta_box( $id, self::POST_TYPE_SLUG, $context ); } } } } } /** * Outputs the markup of the side meta box in the CPT post.php page. * * This is partially copied from meta-boxes.php. * Adds 'Published on,' and links to move to trash and recheck. * * @param WP_Post $post The post for which to output the box. * @return void */ public static function print_status_meta_box( WP_Post $post ) { ?> <style> #amp_validation_status .inside { margin: 0; padding: 0; } #re-check-action { float: left; } </style> <div id="submitpost" class="submitbox"> <?php wp_nonce_field( self::UPDATE_POST_TERM_STATUS_ACTION, self::UPDATE_POST_TERM_STATUS_ACTION . '_nonce', false ); ?> <div id="minor-publishing"> <div class="curtime misc-pub-section"> <span id="timestamp"> <?php printf( /* translators: %s: The date this was published */ wp_kses_post( __( 'Last checked: <b>%s</b>', 'amp' ) ), /* translators: Meta box date format */ esc_html( date_i18n( __( 'M j, Y @ H:i', 'amp' ), strtotime( $post->post_date ) ) ) ); ?> </span> </div> <div id="minor-publishing-actions"> <div id="re-check-action"> <a class="button button-secondary" href="<?php echo esc_url( self::get_recheck_url( $post ) ); ?>"> <?php esc_html_e( 'Recheck', 'amp' ); ?> </a> </div> <div id="preview-action"> <button type="button" name="action" class="preview button" id="preview_validation_errors"><?php esc_html_e( 'Preview Changes', 'amp' ); ?></button> </div> <div class="clear"></div> </div> <div id="misc-publishing-actions"> <div class="misc-pub-section"> <?php $staleness = self::get_post_staleness( $post ); if ( ! empty( $staleness ) ) { echo '<div class="notice notice-info notice-alt inline"><p>'; echo '<b>'; esc_html_e( 'Stale results', 'amp' ); echo '</b>'; echo '<br>'; if ( ! empty( $staleness['theme'] ) && ! empty( $staleness['plugins'] ) ) { esc_html_e( 'The theme and plugins have changed since these results were obtained.', 'amp' ); echo ' '; } elseif ( ! empty( $staleness['theme'] ) ) { esc_html_e( 'The theme has changed since these results were obtained.', 'amp' ); echo ' '; } elseif ( ! empty( $staleness['plugins'] ) ) { esc_html_e( 'Plugins have been updated since these results were obtained.', 'amp' ); echo ' '; } esc_html_e( 'Please recheck.', 'amp' ); echo '</p></div>'; } ?> <?php $counts = self::count_invalid_url_validation_errors( self::get_invalid_url_validation_errors( $post ) ); if ( 0 < ( $counts['new_rejected'] + $counts['new_accepted'] ) ) { ?> <strong id="amp-invalid-markup" class="status-text"> <span class="amp-icon amp-invalid"></span> <?php esc_html_e( 'Invalid markup not reviewed', 'amp' ); ?> </strong> <?php esc_html_e( 'For each instance of invalid markup, determine whether it can be safely removed or it needs to be kept. You can change the Markup Status (Removed or Kept) and click the Preview Changes button to see its impact on the page. Once the proper action has been taken (Remove or Keep), you can toggle the checkbox the instance as Reviewed.', 'amp' ); echo '<br><br>'; } ?> <?php $is_amp_enabled = self::is_amp_enabled_on_post( $post ); $class = $is_amp_enabled ? 'amp-enabled' : 'amp-disabled'; ?> <strong id="amp-enabled-icon" class="status-text <?php echo esc_attr( $class ); ?>"> <?php if ( $is_amp_enabled ) { esc_html_e( 'AMP enabled', 'amp' ); } else { esc_html_e( 'AMP disabled', 'amp' ); } ?> </strong> <?php if ( $is_amp_enabled && count( array_filter( $counts ) ) > 0 ) : ?> <?php esc_html_e( 'AMP is enabled because no invalid markup is being kept.', 'amp' ); ?> <?php elseif ( ! $is_amp_enabled ) : ?> <?php esc_html_e( 'AMP is disabled because some invalid markup has been kept. To enable AMP to be served, either mark the invalid markup as &#8220;removed&#8221; or provide an AMP-compatible fix that eliminates the invalid markup from being generated in the first place.', 'amp' ); ?> <?php endif; ?> </div> <div class="misc-pub-section"> <?php $actions = []; ob_start(); $view_label = __( 'View URL', 'amp' ); $queried_object = get_post_meta( $post->ID, self::QUERIED_OBJECT_POST_META_KEY, true ); if ( isset( $queried_object['id'], $queried_object['type'] ) ) { if ( 'post' === $queried_object['type'] && get_post( $queried_object['id'] ) && post_type_exists( get_post( $queried_object['id'] )->post_type ) ) { $post_type_object = get_post_type_object( get_post( $queried_object['id'] )->post_type ); edit_post_link( $post_type_object->labels->edit_item, '', '', $queried_object['id'] ); $view_label = $post_type_object->labels->view_item; } elseif ( 'term' === $queried_object['type'] && get_term( $queried_object['id'] ) && taxonomy_exists( get_term( $queried_object['id'] )->taxonomy ) ) { $taxonomy_object = get_taxonomy( get_term( $queried_object['id'] )->taxonomy ); edit_term_link( $taxonomy_object->labels->edit_item, '', '', get_term( $queried_object['id'] ) ); $view_label = $taxonomy_object->labels->view_item; } elseif ( 'user' === $queried_object['type'] ) { $link = get_edit_user_link( $queried_object['id'] ); if ( $link ) { printf( '<a href="%s">%s</a>', esc_url( $link ), esc_html__( 'Edit User', 'amp' ) ); } $view_label = __( 'View User', 'amp' ); } } $actions['edit'] = ob_get_clean(); $actions['view'] = sprintf( '<a href="%s">%s</a>', esc_url( self::get_url_from_post( $post ) ), esc_html( $view_label ) ); /** * Filters the array of action links shown in the status metabox. * * @since 2.1 * @internal * * @param string[] $actions Action links. * @param WP_Post $post Validated URL post. */ $actions = apply_filters( 'amp_validated_url_status_actions', $actions, $post ); echo wp_kses( implode( ' | ', array_filter( $actions ) ), [ 'a' => array_fill_keys( [ 'href' ], true ), ] ); ?> </div> </div> </div> <div id="major-publishing-actions"> <div id="delete-action"> <a class="submitdelete deletion" href="<?php echo esc_url( get_delete_post_link( $post->ID, '', true ) ); ?>"> <?php esc_html_e( 'Forget', 'amp' ); ?> </a> </div> <div id="publishing-action"> <button type="submit" name="action" class="button button-primary" value="<?php echo esc_attr( self::UPDATE_POST_TERM_STATUS_ACTION ); ?>"><?php esc_html_e( 'Update', 'amp' ); ?></button> </div> <div class="clear"></div> </div> </div><!-- /submitpost --> <script> jQuery( function( $ ) { var validateUrl, postId; validateUrl = <?php echo wp_json_encode( self::get_markup_status_preview_url( self::get_url_from_post( $post ) ) ); ?>; postId = <?php echo wp_json_encode( $post->ID ); ?>; $( '#preview_validation_errors' ).on( 'click', function() { var params = {}, validatePreviewUrl = validateUrl; params.preview = '1'; $( '.amp-validation-error-status' ).each( function() { if ( this.value && ! this.options[ this.selectedIndex ].defaultSelected ) { params[ this.name ] = this.value; } } ); validatePreviewUrl += '&' + $.param( params ); validatePreviewUrl += '#development=1'; window.open( validatePreviewUrl, 'amp-validation-error-term-status-preview-' + String( postId ) ); } ); } ); </script> <?php } /** * Renders stylesheet info for the validated URL. * * @param WP_Post $post The post for the meta box. * @return void */ public static function print_stylesheets_meta_box( $post ) { $stylesheets = get_post_meta( $post->ID, self::STYLESHEETS_POST_META_KEY, true ); if ( empty( $stylesheets ) ) { printf( '<p><em>%s</em></p>', wp_kses_post( sprintf( /* translators: placeholder is URL to recheck the post */ __( 'Stylesheet information for this URL is no longer available. Such data is automatically deleted after a week to reduce database storage. It is of little value to store long-term given that it becomes stale as themes and plugins are updated. To obtain the latest stylesheet information, <a href="%s">recheck this URL</a>.', 'amp' ), esc_url( self::get_recheck_url( $post ) . '#amp_stylesheets' ) ) ) ); return; } $stylesheets = json_decode( $stylesheets, true ); if ( ! is_array( $stylesheets ) ) { printf( '<p><em>%s</em></p>', esc_html__( 'Unable to retrieve data for stylesheets.', 'amp' ) ); return; } $style_custom_cdata_spec = null; foreach ( AMP_Allowed_Tags_Generated::get_allowed_tag( 'style' ) as $spec_rule ) { if ( isset( $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) && AMP_Style_Sanitizer::STYLE_AMP_CUSTOM_SPEC_NAME === $spec_rule[ AMP_Rule_Spec::TAG_SPEC ]['spec_name'] ) { $style_custom_cdata_spec = $spec_rule[ AMP_Rule_Spec::CDATA ]; } } $included_final_size = 0; $included_original_size = 0; $excluded_final_size = 0; $excluded_original_size = 0; $excluded_stylesheets = 0; $max_final_size = 0; $included_status = 1; $excessive_status = 2; $excluded_status = 3; // Determine which stylesheets are included based on their priorities. $pending_stylesheet_indices = array_keys( $stylesheets ); usort( $pending_stylesheet_indices, static function ( $a, $b ) use ( $stylesheets ) { return $stylesheets[ $a ]['priority'] - $stylesheets[ $b ]['priority']; } ); foreach ( $pending_stylesheet_indices as $i ) { // @todo Add information about amp-keyframes as well. if ( ! isset( $stylesheets[ $i ]['group'] ) || 'amp-custom' !== $stylesheets[ $i ]['group'] || ! empty( $stylesheets[ $i ]['duplicate'] ) ) { continue; } $max_final_size = max( $max_final_size, $stylesheets[ $i ]['final_size'] ); if ( $stylesheets[ $i ]['included'] ) { $included_final_size += $stylesheets[ $i ]['final_size']; $included_original_size += $stylesheets[ $i ]['original_size']; if ( $included_final_size >= $style_custom_cdata_spec['max_bytes'] && $stylesheets[ $i ]['final_size'] > 0 ) { $stylesheets[ $i ]['status'] = $excessive_status; } else { $stylesheets[ $i ]['status'] = $included_status; } } else { $excluded_final_size += $stylesheets[ $i ]['final_size']; $excluded_original_size += $stylesheets[ $i ]['original_size']; $excluded_stylesheets++; $stylesheets[ $i ]['status'] = $excluded_status; } } ?> <?php if ( ! AMP_Style_Sanitizer::has_required_php_css_parser() ) : ?> <div class="notice notice-alt notice-warning inline"> <p> <?php esc_html_e( 'AMP CSS processing is limited because a conflicting version of PHP-CSS-Parser has been loaded by another plugin or theme. Tree shaking is not available.', 'amp' ); ?> </p> </div> <?php endif; ?> <table class="amp-stylesheet-summary"> <tr> <th> <?php esc_html_e( 'Total CSS size prior to minification:', 'amp' ); ?> </th> <td> <?php echo esc_html( number_format_i18n( $included_original_size + $excluded_original_size ) ); ?> <abbr title="<?php esc_attr_e( 'bytes', 'amp' ); ?>"><?php echo esc_html_x( 'B', 'abbreviation for bytes', 'amp' ); ?></abbr> </td> </tr> <tr> <th> <?php esc_html_e( 'Total CSS size after minification:', 'amp' ); ?> </th> <td> <?php echo esc_html( number_format_i18n( $included_final_size + $excluded_final_size ) ); ?> <abbr title="<?php esc_attr_e( 'bytes', 'amp' ); ?>"><?php echo esc_html_x( 'B', 'abbreviation for bytes', 'amp' ); ?></abbr> </td> </tr> <tr> <th> <?php echo esc_html( sprintf( /* translators: %s is max kilobytes */ __( 'Percentage of used CSS budget (%sKB):', 'amp' ), number_format_i18n( $style_custom_cdata_spec['max_bytes'] / 1000 ) ) ); ?> </th> <td> <?php $percentage_budget_used = ( ( $included_final_size + $excluded_final_size ) / $style_custom_cdata_spec['max_bytes'] ) * 100; printf( '%.1f%% ', $percentage_budget_used ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped if ( $percentage_budget_used > 100 ) { $icon = Icon::invalid(); } elseif ( $percentage_budget_used >= AMP_Style_Sanitizer::CSS_BUDGET_WARNING_PERCENTAGE ) { $icon = Icon::warning(); } else { $icon = Icon::valid(); } echo $icon->to_html(); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?> </td> </tr> <tr> <th> <?php echo esc_html( sprintf( /* translators: %s is the number of stylesheets excluded */ _n( 'Excluded minified CSS (%s stylesheet):', 'Excluded minified CSS size (%s stylesheets):', $excluded_stylesheets, 'amp' ), number_format_i18n( $excluded_stylesheets ) ) ); ?> </th> <td> <?php echo esc_html( number_format_i18n( $excluded_final_size ) ); ?> <abbr title="<?php esc_attr_e( 'bytes', 'amp' ); ?>"><?php echo esc_html_x( 'B', 'abbreviation for bytes', 'amp' ); ?></abbr> </td> </tr> </table> <?php if ( $percentage_budget_used > 100 ) : ?> <div class="notice notice-alt notice-error inline"> <p> <?php if ( 0 === $excluded_stylesheets ) : ?> <?php esc_html_e( 'You have exceeded the CSS budget. The page will not be served as a valid AMP page.', 'amp' ); ?> <?php else : ?> <?php esc_html_e( 'You have exceeded the CSS budget. Stylesheets deemed of lesser priority have been excluded from the page.', 'amp' ); ?> <?php endif; ?> <?php esc_html_e( 'Please review the flagged stylesheets below and determine if the current theme or a particular plugin is including excessive CSS.', 'amp' ); ?> </p> </div> <?php elseif ( $percentage_budget_used >= AMP_Style_Sanitizer::CSS_BUDGET_WARNING_PERCENTAGE ) : ?> <div class="notice notice-alt notice-warning inline"> <p> <?php esc_html_e( 'You are nearing the limit of the CSS budget. Once this limit is reached, stylesheets deemed of lesser priority will be excluded from the page. Please review the stylesheets below and determine if the current theme or a particular plugin is including excessive CSS.', 'amp' ); ?> </p> </div> <?php endif; ?> <table class="amp-stylesheet-list wp-list-table widefat fixed striped"> <thead> <tr> <th class="column-stylesheet_expand"></th> <th class="column-stylesheet_order"><?php esc_html_e( 'Order', 'amp' ); ?></th> <th class="column-original_size"> <?php esc_html_e( 'Original', 'amp' ); ?> (<abbr title="<?php esc_attr_e( 'bytes', 'amp' ); ?>"><?php echo esc_html_x( 'B', 'abbreviation for bytes', 'amp' ); ?></abbr>) </th> <th class="column-minified"><?php esc_html_e( 'Minified', 'amp' ); ?></th> <th class="column-final_size"> <?php esc_html_e( 'Final', 'amp' ); ?> (<abbr title="<?php esc_attr_e( 'bytes', 'amp' ); ?>"><?php echo esc_html_x( 'B', 'abbreviation for bytes', 'amp' ); ?></abbr>) </th> <th class="column-percentage"><?php esc_html_e( 'Percent', 'amp' ); ?></th> <th class="column-priority"><?php esc_html_e( 'Priority', 'amp' ); ?></th> <th class="column-stylesheet_included"><?php esc_html_e( 'Included', 'amp' ); ?></th> <th class="column-markup"><?php esc_html_e( 'Markup', 'amp' ); ?></th> <th class="column-sources_with_invalid_output"><?php esc_html_e( 'Sources', 'amp' ); ?></th> </tr> </thead> <tbody> <?php $row = 1; ?> <?php foreach ( $stylesheets as $stylesheet ) : ?> <?php // @todo Add information about amp-keyframes as well. if ( ! isset( $stylesheet['group'] ) || 'amp-custom' !== $stylesheet['group'] || ! empty( $stylesheet['duplicate'] ) ) { continue; } $origin_html = '<' . $stylesheet['element']['name']; if ( ! empty( $stylesheet['element']['attributes'] ) ) { $attributes = $stylesheet['element']['attributes']; if ( ! empty( $attributes['class'] ) ) { $attributes['class'] = trim( preg_replace( '/(^|\s)amp-wp-\w+(\s|$)/', ' ', $attributes['class'] ) ); if ( empty( $attributes['class'] ) ) { unset( $attributes['class'] ); } } if ( isset( $attributes[ AMP_Style_Sanitizer::ORIGINAL_STYLE_ATTRIBUTE_NAME ] ) ) { $attributes['style'] = $attributes[ AMP_Style_Sanitizer::ORIGINAL_STYLE_ATTRIBUTE_NAME ]; unset( $attributes[ AMP_Style_Sanitizer::ORIGINAL_STYLE_ATTRIBUTE_NAME ] ); } if ( ! empty( $attributes ) ) { foreach ( $attributes as $name => $value ) { if ( '' === $value ) { $origin_html .= ' ' . sprintf( '%s', esc_html( $name ) ); } else { $origin_html .= ' ' . sprintf( '%s="%s"', esc_html( $name ), esc_attr( $value ) ); } } } } $origin_html .= '>'; if ( 0 === $stylesheet['original_size'] ) { $ratio = 1; } else { $ratio = $stylesheet['final_size'] / $stylesheet['original_size']; } ?> <tr class="<?php echo esc_attr( sprintf( 'stylesheet level-0 %s', 0 === $row % 2 ? 'even' : 'odd' ) ); ?>"> <td class="column-stylesheet_expand"> <button class="toggle-stylesheet-details" type="button"> <span class="screen-reader-text"><?php esc_html_e( 'Expand/collapse', 'amp' ); ?></span> </button> </td> <td class="column-stylesheet_order"> <?php echo (int) $row; ?> </td> <td class="column-original_size"> <?php echo esc_html( number_format_i18n( $stylesheet['original_size'] ) ); ?> </td> <td class="column-minified"> <?php if ( $ratio <= 1 ) { echo esc_html( sprintf( '-%.1f%%', ( 1.0 - $ratio ) * 100 ) ); } else { echo esc_html( sprintf( '+%.1f%%', -1 * ( 1.0 - $ratio ) * 100 ) ); } ?> </td> <td class="column-final_size"> <?php echo esc_html( number_format_i18n( $stylesheet['final_size'] ) ); ?> </td> <td class="column-percentage"> <?php $percentage = $stylesheet['final_size'] / ( $included_final_size + $excluded_final_size ); ?> <meter value="<?php echo esc_attr( $stylesheet['final_size'] ); ?>" min="0" max="<?php echo esc_attr( $included_final_size + $excluded_final_size ); ?>" title="<?php esc_attr_e( 'Stylesheet bytes of total CSS added to page', 'amp' ); ?>"> <?php echo esc_html( round( ( $percentage ) * 100 ) ) . '%'; ?> </meter> </td> <td class="column-priority"> <?php echo esc_html( $stylesheet['priority'] ); ?> </td> <td class="column-stylesheet_included"> <?php switch ( $stylesheet['status'] ) { case $included_status: printf( '<span title="%s" class="amp-icon amp-valid"></span>', esc_attr__( 'Stylesheet included', 'amp' ) ); break; case $excessive_status: printf( '<span title="%s" class="amp-icon amp-warning"></span>', esc_attr__( 'Stylesheet overruns CSS budget yet it is still included on page', 'amp' ) ); break; case $excluded_status: printf( '<span title="%s" class="amp-icon amp-invalid"></span>', esc_attr__( 'Stylesheet excluded due to exceeding CSS budget', 'amp' ) ); break; } ?> </td> <td class="column-markup"> <?php $origin_abbr_text = '?'; if ( 'link_element' === $stylesheet['origin'] ) { $origin_abbr_text = '<link&nbsp;&hellip;>'; // @todo Consider adding the basename of the CSS file. } elseif ( 'style_element' === $stylesheet['origin'] ) { $origin_abbr_text = '<style>'; } elseif ( 'style_attribute' === $stylesheet['origin'] ) { $origin_abbr_text = 'style="&hellip;"'; } $needs_abbr = $origin_abbr_text !== $origin_html; if ( $needs_abbr ) { printf( '<abbr title="%s">', esc_attr( $origin_html ) ); } printf( '<code>%s</code>', esc_html( $origin_abbr_text ) ); if ( $needs_abbr ) { echo '</abbr>'; } echo '</code>'; ?> </td> <td class="column-sources_with_invalid_output"> <?php if ( empty( $stylesheet['sources'] ) ) { esc_html_e( '--', 'amp' ); } else { self::render_sources_column( AMP_Validation_Error_Taxonomy::summarize_sources( $stylesheet['sources'] ), $post->ID ); } ?> </td> </tr> <tr class="<?php echo esc_attr( sprintf( 'stylesheet-details level-0 %s', 0 === $row % 2 ? 'even' : 'odd' ) ); ?>"> <td colspan="10"> <dl class="detailed"> <dt><?php esc_html_e( 'Original Markup', 'amp' ); ?></dt> <dd><code class="stylesheet-origin-markup"><?php echo esc_html( $origin_html ); ?></code></dd> <?php if ( isset( $stylesheet['element']['attributes']['href'] ) ) : ?> <dt><?php esc_html_e( 'Stylesheet URL', 'amp' ); ?></dt> <dd> <?php printf( '<a href="%s" target="_blank">%s</a>', esc_url( $stylesheet['element']['attributes']['href'] ), esc_html( $stylesheet['element']['attributes']['href'] ) ); ?> </dd> <?php endif; ?> <dt><?php esc_html_e( 'Sources', 'amp' ); ?></dt> <dd> <?php AMP_Validation_Error_Taxonomy::render_sources( $stylesheet['sources'] ); ?> </dd> <dt><?php esc_html_e( 'CSS Code', 'amp' ); ?></dt> <dd> <?php ob_start(); echo '<code class="shaken-stylesheet">'; $open_parens = 0; $ins_count = 0; $del_count = 0; foreach ( $stylesheet['shaken_tokens'] as $shaken_token ) { if ( $shaken_token[0] ) { $ins_count++; } else { $del_count++; } if ( is_array( $shaken_token[1] ) ) { echo '<span class="declaration-block">'; $selector_count = count( $shaken_token[1] ); foreach ( array_keys( $shaken_token[1] ) as $i => $selector ) { $included = $shaken_token[1][ $selector ]; echo $included ? '<ins class="selector">' : '<del class="selector">'; echo str_repeat( "\t", $open_parens ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped $selector_html = preg_replace( '/(:root|html)(:not\(#_\))+/', sprintf( '<abbr title="%s">$0</abbr>', esc_attr( 'style_attribute' === $stylesheet['origin'] ? __( 'Selector generated to increase specificity so the cascade is preserved for properties moved from style attribute to CSS rules in style[amp-custom].', 'amp' ) : __( 'Selector generated to increase specificity for important properties so that the CSS cascade is preserved. AMP does not allow important properties.', 'amp' ) ) ), esc_html( $selector ) ); if ( 'style_attribute' === $stylesheet['origin'] ) { $selector_html = preg_replace( '/\.amp-wp-\w+/', sprintf( '<abbr title="%s">$0</abbr>', esc_attr__( 'Class name generated during extraction of inline style to style[amp-custom].', 'amp' ) ), $selector_html ); } $selector_html = preg_replace( '/:not\((#_)+\)/', sprintf( '<abbr title="%s">$0</abbr>', esc_attr__( 'Pseudo-class selector used to increase specificity for rule extracted from inline styles and/or properties with !important qualifiers.', 'amp' ) ), $selector_html ); echo $selector_html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped if ( $i + 1 < $selector_count ) { echo ','; } echo $included ? '</ins>' : '</del>'; } echo $shaken_token[0] ? '<ins>' : '<del>'; echo str_repeat( "\t", $open_parens + 1 ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped echo '{ ' . esc_html( implode( '; ', $shaken_token[2] ) ) . '; }'; echo $shaken_token[0] ? '</ins>' : '</del>'; echo '</span>'; } elseif ( is_string( $shaken_token[1] ) ) { echo $shaken_token[0] ? '<ins class="">' : '<del class="">'; $parent_count_diff = substr_count( $shaken_token[1], '{' ) - substr_count( $shaken_token[1], '}' ); if ( $parent_count_diff >= 0 ) { echo str_repeat( "\t", $open_parens ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } else { echo str_repeat( "\t", $open_parens + $parent_count_diff ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } $open_parens += $parent_count_diff; echo esc_html( $shaken_token[1] ); echo $shaken_token[0] ? '</ins>' : '</del>'; } } echo '</code>'; $html = trim( ob_get_clean() ); if ( 0 === $ins_count && 0 === $del_count ) { printf( '<p><em>%s</em></p>', esc_html__( 'The stylesheet was empty after minification (removal of comments and whitespace).', 'amp' ) ); } elseif ( 0 === $ins_count ) { printf( '<p><em>%s</em></p>', esc_html__( 'All of the stylesheet was removed during tree-shaking.', 'amp' ) ); } if ( 0 !== $ins_count || 0 !== $del_count ) { if ( $del_count > 0 ) { printf( '<p><label><input type="checkbox" class="show-removed-styles"> %s</label></p>', esc_html__( 'Show styles removed during tree-shaking', 'amp' ) ); } echo $html; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped } ?> </dd> </dl> </td> </tr> <?php $row++; ?> <?php endforeach; ?> </tbody> </table> <?php } /** * Renders the single URL list table. * * Mainly copied from edit-tags.php. * This is output on the post.php page for amp_validated_url, * where the editor normally would be. * But it's really more similar to /wp-admin/edit-tags.php than a post.php page, * as this outputs a WP_Terms_List_Table of amp_validation_error terms. * * @todo: complete this, as it may need to use more logic from edit-tags.php. * @param WP_Post $post The post for the meta box. * @return void */ public static function render_single_url_list_table( $post ) { if ( self::POST_TYPE_SLUG !== $post->post_type ) { return; } $taxonomy = AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG; $taxonomy_object = get_taxonomy( $taxonomy ); if ( ! $taxonomy_object ) { wp_die( esc_html__( 'Invalid taxonomy.', 'amp' ) ); } /** * Set the order of the terms in the order of occurrence. * * Note that this function will call \AMP_Validation_Error_Taxonomy::get_term() repeatedly, and the * object cache will be pre-populated with terms due to the term query in the term list table. * * @return WP_Term[] */ $override_terms_in_occurrence_order = static function() use ( $post ) { return wp_list_pluck( AMP_Validated_URL_Post_Type::get_invalid_url_validation_errors( $post ), 'term' ); }; add_filter( 'get_terms', $override_terms_in_occurrence_order ); $wp_list_table = _get_list_table( 'WP_Terms_List_Table' ); get_current_screen()->set_screen_reader_content( [ 'heading_pagination' => $taxonomy_object->labels->items_list_navigation, 'heading_list' => $taxonomy_object->labels->items_list, ] ); $wp_list_table->prepare_items(); $wp_list_table->views(); // The inline script depends on data from the list table. self::$total_errors_for_url = $wp_list_table->get_pagination_arg( 'total_items' ); ?> <form class="search-form wp-clearfix" method="get"> <input type="hidden" name="taxonomy" value="<?php echo esc_attr( $taxonomy ); ?>" /> <input type="hidden" name="post_type" value="<?php echo esc_attr( $post->post_type ); ?>" /> <?php $wp_list_table->search_box( esc_html__( 'Search Errors', 'amp' ), 'invalid-url-search' ); ?> </form> <div id="remove-keep-buttons" class="hidden"> <button type="button" class="button action remove"><?php esc_html_e( 'Remove', 'amp' ); ?></button> <button type="button" class="button action keep"><?php esc_html_e( 'Keep', 'amp' ); ?></button> <button type="button" class="button action reviewed-toggle reviewed"><?php esc_html_e( 'Mark reviewed', 'amp' ); ?></button> <button type="button" class="button action reviewed-toggle unreviewed"><?php esc_html_e( 'Mark unreviewed', 'amp' ); ?></button> <button type="button" class="button action copy-all"><?php esc_html_e( 'Copy to clipboard', 'amp' ); ?></button> <div id="vertical-divider"></div> </div> <div id="url-post-filter" class="alignleft actions"> <?php AMP_Validation_Error_Taxonomy::render_error_type_filter(); ?> </div> <?php AMP_Validation_Error_Taxonomy::reset_validation_error_row_index(); $wp_list_table->display(); ?> <?php remove_filter( 'get_terms', $override_terms_in_occurrence_order ); } /** * Gets the number of amp_validation_error terms that should appear on the single amp_validated_url /wp-admin/post.php page. * * @param int $terms_per_page The number of terms on a page. * @return int The number of terms on the page. */ public static function get_terms_per_page( $terms_per_page ) { global $pagenow; if ( 'post.php' === $pagenow ) { return PHP_INT_MAX; } return $terms_per_page; } /** * Adds the taxonomy to the $_REQUEST, so that it is available in WP_Screen and WP_Terms_List_Table. * * It would be ideal to do this in render_single_url_list_table(), * but set_current_screen() looks to run before that, and that needs access to the 'taxonomy'. */ public static function add_taxonomy() { global $pagenow; if ( 'post.php' !== $pagenow || ! isset( $_REQUEST['post'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended return; } $post_id = (int) $_REQUEST['post']; // phpcs:ignore WordPress.Security.NonceVerification.Recommended if ( ! empty( $post_id ) && self::POST_TYPE_SLUG === get_post_type( $post_id ) ) { $_REQUEST['taxonomy'] = AMP_Validation_Error_Taxonomy::TAXONOMY_SLUG; } } /** * Show URL at the top of the edit form in place of the title (since title support is not present). * * @param WP_Post $post Post. */ public static function print_url_as_title( $post ) { if ( self::POST_TYPE_SLUG !== $post->post_type ) { return; } $url = self::get_url_from_post( $post ); if ( ! $url ) { return; } // @todo For URLs without a queried object, this should eventually be augmented to indicate the query type (e.g. Homepage, Search Results, Date Archive, etc) $entity_title = self::get_validated_url_title(); ?> <?php if ( $entity_title ) : ?> <h2><em><?php echo esc_html( $entity_title ); ?></em></h2> <?php endif; ?> <h2 class="amp-validated-url"> <a href="<?php echo esc_url( $url ); ?>"> <span class="dashicons dashicons-admin-links"></span> <?php echo esc_html( $url ); ?> </a> </h2> <?php } /** * Strip host name from AMP validated URL being printed. * * @param string $title Title. * @param int $id Post ID. * * @return string Title. */ public static function filter_the_title_in_post_list_table( $title, $id = null ) { if ( function_exists( 'get_current_screen' ) && get_current_screen() && get_current_screen()->base === 'edit' && get_current_screen()->post_type === self::POST_TYPE_SLUG && self::POST_TYPE_SLUG === get_post_type( $id ) ) { $title = preg_replace( '#^(\w+:)?//[^/]+#', '', $title ); } return $title; } /** * Renders the filters on the validated URL post type edit.php page. * * @param string $post_type The slug of the post type. * @param string $which The location for the markup, either 'top' or 'bottom'. */ public static function render_post_filters( $post_type, $which ) { if ( self::POST_TYPE_SLUG === $post_type && 'top' === $which ) { AMP_Validation_Error_Taxonomy::render_error_status_filter(); AMP_Validation_Error_Taxonomy::render_error_type_filter(); } } /** * Gets the URL to recheck the post for AMP validity. * * Appends a query var to $redirect_url. * On clicking the link, it checks if errors still exist for $post. * * @param string|WP_Post $url_or_post The post storing the validation error or the URL to check. * @return string The URL to recheck the post. */ public static function get_recheck_url( $url_or_post ) { $args = [ 'action' => self::VALIDATE_ACTION, ]; if ( is_string( $url_or_post ) ) { $args['url'] = $url_or_post; } elseif ( $url_or_post instanceof WP_Post && self::POST_TYPE_SLUG === $url_or_post->post_type ) { $args['post'] = $url_or_post->ID; } return wp_nonce_url( add_query_arg( rawurlencode_deep( $args ), admin_url() ), self::NONCE_ACTION ); } /** * Filters the document title on the single URL page at /wp-admin/post.php. * * @global string $title * * @param string $admin_title Document title. * @return string Filtered document title. */ public static function filter_admin_title( $admin_title ) { global $title; if ( self::is_validated_url_admin_screen() ) { // This is not ideal to set this in a filter, but it's the only apparent way to set the variable for admin-header.php. $title = __( 'AMP Validated URL', 'amp' ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited /* translators: Admin screen title. %s: Admin screen name */ $admin_title = sprintf( __( '%s &#8212; WordPress', 'default' ), $title ); } return $admin_title; } /** * Determines whether the current screen is for a validated URL. * * @return bool Is screen. */ private static function is_validated_url_admin_screen() { global $pagenow; return ! ( 'post.php' !== $pagenow || ! isset( $_GET['post'], $_GET['action'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended || self::POST_TYPE_SLUG !== get_post_type( $_GET['post'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized ); } /** * Gets the title for validated URL, corresponding with the title for the queried object. * * @param int|WP_Post $post Post for the validated URL. * @return string|null Title, or null if none is available. */ public static function get_validated_url_title( $post = null ) { $name = null; $post = get_post( $post ); if ( ! $post ) { return null; } // Mainly uses the same conditionals as print_status_meta_box(). $queried_object = get_post_meta( $post->ID, self::QUERIED_OBJECT_POST_META_KEY, true ); if ( isset( $queried_object['type'], $queried_object['id'] ) ) { $name = null; if ( 'post' === $queried_object['type'] && get_post( $queried_object['id'] ) ) { $name = html_entity_decode( get_the_title( $queried_object['id'] ), ENT_QUOTES ); } elseif ( 'term' === $queried_object['type'] && get_term( $queried_object['id'] ) ) { $name = get_term( $queried_object['id'] )->name; } elseif ( 'user' === $queried_object['type'] && get_user_by( 'ID', $queried_object['id'] ) ) { $name = get_user_by( 'ID', $queried_object['id'] )->display_name; } } return $name; } /** * Filters post row actions. * * Manages links for details, recheck, view, forget, and forget permanently. * * @param array $actions Row action links. * @param WP_Post $post Current WP post. * * @return array Filtered action links. */ public static function filter_post_row_actions( $actions, $post ) { if ( ! is_object( $post ) || self::POST_TYPE_SLUG !== $post->post_type ) { return $actions; } // Inline edits are not relevant. unset( $actions['inline hide-if-no-js'] ); if ( isset( $actions['edit'] ) ) { $actions['edit'] = sprintf( '<a href="%s">%s</a>', esc_url( get_edit_post_link( $post ) ), esc_html__( 'Details', 'amp' ) ); } if ( 'trash' !== $post->post_status && current_user_can( 'edit_post', $post->ID ) ) { $url = self::get_url_from_post( $post ); if ( $url ) { $actions['view'] = sprintf( '<a href="%s">%s</a>', esc_url( $url ), esc_html__( 'View', 'amp' ) ); } $actions[ self::VALIDATE_ACTION ] = sprintf( '<a href="%s">%s</a>', esc_url( self::get_recheck_url( $post ) ), esc_html__( 'Recheck', 'amp' ) ); if ( self::get_post_staleness( $post ) ) { $actions[ self::VALIDATE_ACTION ] = sprintf( '<em>%s</em>', $actions[ self::VALIDATE_ACTION ] ); } } // Replace 'Trash' with 'Forget' (which permanently deletes). $has_delete = ( isset( $actions['trash'] ) || isset( $actions['delete'] ) ); unset( $actions['trash'], $actions['delete'] ); if ( $has_delete ) { $actions['delete'] = sprintf( '<a href="%s" class="submitdelete" aria-label="%s">%s</a>', get_delete_post_link( $post->ID, '', true ), /* translators: %s: post title */ esc_attr( sprintf( __( 'Forget &#8220;%s&#8221;', 'amp' ), self::get_url_from_post( $post ) ) ), esc_html__( 'Forget', 'amp' ) ); } $actions = wp_array_slice_assoc( $actions, [ 'edit', self::VALIDATE_ACTION, 'view', 'delete' ] ); return $actions; } /** * Filters table views for the post type. * * @param array $views Array of table view links keyed by status slug. * @return array Filtered views. */ public static function filter_table_views( $views ) { // Replace 'Trash' text with 'Forgotten'. if ( isset( $views['trash'] ) ) { $status = get_post_status_object( 'trash' ); $views['trash'] = str_replace( $status->label, esc_html__( 'Forgotten', 'amp' ), $views['trash'] ); } return $views; } /** * Filters messages displayed after bulk updates. * * Note that trashing is replaced with deletion whenever possible, so the trashed and untrashed messages will not be used in practice. * * @param array $messages Bulk message text. * @param array $bulk_counts Post numbers for the current message. * @return array Filtered messages. */ public static function filter_bulk_post_updated_messages( $messages, $bulk_counts ) { if ( get_current_screen()->id === sprintf( 'edit-%s', self::POST_TYPE_SLUG ) ) { $messages['post'] = array_merge( $messages['post'], [ /* translators: %s is the number of posts forgotten */ 'deleted' => _n( '%s validated URL forgotten.', '%s validated URLs forgotten.', $bulk_counts['deleted'], 'amp' ), /* translators: %s is the number of posts forgotten */ 'trashed' => _n( '%s validated URL forgotten.', '%s validated URLs forgotten.', $bulk_counts['trashed'], 'amp' ), /* translators: %s is the number of posts restored from trash. */ 'untrashed' => _n( '%s validated URL unforgotten.', '%s validated URLs unforgotten.', $bulk_counts['untrashed'], 'amp' ), ] ); } return $messages; } /** * Is AMP Enabled on Post * * @param WP_Post $post Post object to check. * * @return bool Whether enabled. */ public static function is_amp_enabled_on_post( WP_Post $post ) { $validation_errors = self::get_invalid_url_validation_errors( $post ); $counts = self::count_invalid_url_validation_errors( $validation_errors ); return 0 === ( $counts['new_rejected'] + $counts['ack_rejected'] ); } /** * Count URL Validation Errors * * @param array $validation_errors Validation errors. * * @return int[] */ protected static function count_invalid_url_validation_errors( $validation_errors ) { $counts = array_fill_keys( [ 'new_accepted', 'ack_accepted', 'new_rejected', 'ack_rejected' ], 0 ); foreach ( $validation_errors as $error ) { switch ( $error['term']->term_group ) { case AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_REJECTED_STATUS: $counts['new_rejected']++; break; case AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_NEW_ACCEPTED_STATUS: $counts['new_accepted']++; break; case AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_ACCEPTED_STATUS: $counts['ack_accepted']++; break; case AMP_Validation_Error_Taxonomy::VALIDATION_ERROR_ACK_REJECTED_STATUS: $counts['ack_rejected']++; break; } } return $counts; } }
ampproject/amp-wp
includes/validation/class-amp-validated-url-post-type.php
PHP
gpl-2.0
119,270
<?php die("Access Denied"); ?>#x#a:2:{s:6:"output";s:0:"";s:6:"result";s:7:"1566593";}
jolay/ayansa
cache/mod_vvisit_counter/860aea6b5aac75573e8d7d8ebc839c97-cache-mod_vvisit_counter-e137663a3d8c1ae370185bf16afaea30.php
PHP
gpl-2.0
86
<?php /** * Error handler * * CustomException extension to the Exception classes in PHP5 * * PHP version 5 * * 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. * * @category Chisimba * @package errors * @author Paul Scott <pscott@uwc.ac.za> * @copyright 2007 Paul Scott * @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License * @version $Id$ * @link http://avoir.uwc.ac.za * @see core */ // security check - must be included in all scripts if (! /** * Description for $GLOBALS * @global string $GLOBALS['kewl_entry_point_run'] * @name $kewl_entry_point_run */ $GLOBALS['kewl_entry_point_run']) { die("You cannot view this page directly"); } // end security check /** * Error handler * * CustomException extension to the Exception classes in PHP5 * * @category Chisimba * @package errors * @author Paul Scott <pscott@uwc.ac.za> * @copyright 2007 Paul Scott * @license http://www.gnu.org/licenses/gpl-2.0.txt The GNU General Public License * @version Release: @package_version@ * @link http://avoir.uwc.ac.za * @see core */ class errors extends controller { /** * Logging object * @var unknown * @access public */ public $objLog; /** * Config object * @var mixed * @access public */ public $objConfig; /** * Language Object * @var object * @access public */ public $objLanguage; /** * Mail Object * @var unknown * @access public */ public $objMail; /** * Users Object * @var object * @access public */ public $objUser; /** * Constructor method to instantiate objects and get variables */ public function init() { try { $this->objConfig = $this->getObject('altconfig','config'); $this->objLanguage = $this->getObject('language','language'); $this->objUser = $this->getObject('user', 'security'); } catch (customException $e) { customException::cleanUp(); } } /** * login override * * Overrides the parent login function requirement * * @return boolean Return * @access public */ public function requiresLogin() { return FALSE; } /** * Method to process actions to be taken * * @param string $action String indicating action to be taken */ public function dispatch($action=Null) { switch ($action) { default: return 'noaction_tpl.php'; break; case 'dberror': //check for a dead database as well //$dsn = KEWL_DB_DSN; //$dsn = $this->parseDSN($dsn); // Connect to the database //require_once 'MDB2.php'; //MDB2 has a factory method, so lets use it now... //$checkdb = &MDB2::connect($dsn); //Check for errors on the connect method //if (PEAR::isError($checkdb)) { // $devmsg = $checkdb->getMessage(); // $usrmsg = $checkdb->getUserInfo(); // $this->setVarByRef('devmsg',$devmsg); // $this->setVarByRef('usrmsg',$usrmsg); // return 'dberror_tpl.php'; // break; // } $devmsg = $this->getParam('devmsg'); $usrmsg = $this->getParam('usrmsg'); $this->setVarByRef('devmsg',$devmsg); $this->setVarByRef('usrmsg',$usrmsg); return 'dberror_tpl.php'; break; case 'errormail': $hidmsg = $this->getParam('error'); $captcha = $this->getParam('request_captcha'); if(empty($hidmsg)) { //possible spam usage!!! return 'spam_tpl.php'; exit(); } $text = $this->getParam('comments'); try { //load up the mail class $this->objMail = $this->newObject('email', 'mail'); //set up the mailer $objMailer = $this->getObject('mailer', 'mail'); $objMailer->setValue('to', array($this->objConfig->getsiteEmail(), 'chisimba-dev@googlegroups.com')); $objMailer->setValue('from', $this->objUser->email()); $objMailer->setValue('fromName', $this->objUser->fullname()); $objMailer->setValue('subject', $this->objLanguage->languageText("mod_errors_errsubject", "errors")); $objMailer->setValue('body', $text . " " . $hidmsg . " " . $this->objConfig->getSiteName() . " " . $this->objConfig->getSiteRoot()); if (md5(strtoupper($captcha)) != $this->getParam('captcha') || empty($captcha)) { return 'spam_tpl.php'; break; } else { $objMailer->send(); return 'thanks_tpl.php'; break; } } catch (customException $e) { customException::cleanUp(); exit; } //$this->objMail-> //echo $hidmsg . "<br /><br />" . $text; break; case 'syserr': $mess = $this->getParam('msg'); $mess = urldecode(htmlentities($mess)); $this->setVarByRef('mess', $mess); return "syserror_tpl.php"; break; } } /** * Method to parse the DSN from a string style DSN to an array for portability reasons * * @access public * @param string $dsn * @return void * @TODO get the port settings too! */ public function parseDSN($dsn) { $parsed = NULL; $arr = NULL; if (is_array($dsn)) { $dsn = array_merge($parsed, $dsn); return $dsn; } //find the protocol if (($pos = strpos($dsn, '://')) !== false) { $str = substr($dsn, 0, $pos); $dsn = substr($dsn, $pos + 3); } else { $str = $dsn; $dsn = null; } if (preg_match('|^(.+?)\((.*?)\)$|', $str, $arr)) { $parsed['phptype'] = $arr[1]; $parsed['phptype'] = !$arr[2] ? $arr[1] : $arr[2]; } else { $parsed['phptype'] = $str; $parsed['phptype'] = $str; } if (!count($dsn)) { return $parsed; } // Get (if found): username and password if (($at = strrpos($dsn,'@')) !== false) { $str = substr($dsn, 0, $at); $dsn = substr($dsn, $at + 1); if (($pos = strpos($str, ':')) !== false) { $parsed['username'] = rawurldecode(substr($str, 0, $pos)); $parsed['password'] = rawurldecode(substr($str, $pos + 1)); } else { $parsed['username'] = rawurldecode($str); } } //server if (($col = strrpos($dsn,':')) !== false) { $strcol = substr($dsn, 0, $col); $dsn = substr($dsn, $col + 1); if (($pos = strpos($strcol, '+')) !== false) { $parsed['hostspec'] = rawurldecode(substr($strcol, 0, $pos)); } else { $parsed['hostspec'] = rawurldecode($strcol); } } //now we are left with the port and databsource so we can just explode the string and clobber the arrays together $pm = explode("/",$dsn); $parsed['hostspec'] = $pm[0]; $parsed['database'] = $pm[1]; $dsn = NULL; $parsed['hostspec'] = str_replace("+","/",$parsed['hostspec']); return $parsed; } } ?>
chisimba/chisimba
app/core_modules/errors/controller.php
PHP
gpl-2.0
8,815
<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title>ActiveRecord::Migration::CheckPending</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <link rel="stylesheet" href="../../../css/reset.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../css/main.css" type="text/css" media="screen" /> <link rel="stylesheet" href="../../../css/github.css" type="text/css" media="screen" /> <script src="../../../js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/jquery-effect.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/main.js" type="text/javascript" charset="utf-8"></script> <script src="../../../js/highlight.pack.js" type="text/javascript" charset="utf-8"></script> </head> <body> <div class="banner"> <span>Ruby on Rails 4.0.0</span><br /> <h1> <span class="type">Class</span> ActiveRecord::Migration::CheckPending <span class="parent">&lt; <a href="../../Object.html">Object</a> </span> </h1> <ul class="files"> <li><a href="../../../files/Users/aaron/_rvm/gems/ruby-2_0_0-head/gems/activerecord-4_0_0/lib/active_record/migration_rb.html">/Users/aaron/.rvm/gems/ruby-2.0.0-head/gems/activerecord-4.0.0/lib/active_record/migration.rb</a></li> </ul> </div> <div id="bodyContent"> <div id="content"> <div class="description"> <p>This class is used to verify that all migrations have been run before loading a web page if config.active_record.migration_error is set to :page_load</p> </div> <!-- Method ref --> <div class="sectiontitle">Methods</div> <dl class="methods"> <dt>C</dt> <dd> <ul> <li> <a href="#method-i-call">call</a> </li> </ul> </dd> <dt>N</dt> <dd> <ul> <li> <a href="#method-c-new">new</a> </li> </ul> </dd> </dl> <!-- Methods --> <div class="sectiontitle">Class Public methods</div> <div class="method"> <div class="title method-title" id="method-c-new"> <b>new</b>(app) <a href="../../../classes/ActiveRecord/Migration/CheckPending.html#method-c-new" name="method-c-new" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-c-new_source')" id="l_method-c-new_source">show</a> </p> <div id="method-c-new_source" class="dyn-source"> <pre><span class="ruby-comment"># File /Users/aaron/.rvm/gems/ruby-2.0.0-head/gems/activerecord-4.0.0/lib/active_record/migration.rb, line 358</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">initialize</span>(<span class="ruby-identifier">app</span>) <span class="ruby-ivar">@app</span> = <span class="ruby-identifier">app</span> <span class="ruby-ivar">@last_check</span> = <span class="ruby-number">0</span> <span class="ruby-keyword">end</span></pre> </div> </div> </div> <div class="sectiontitle">Instance Public methods</div> <div class="method"> <div class="title method-title" id="method-i-call"> <b>call</b>(env) <a href="../../../classes/ActiveRecord/Migration/CheckPending.html#method-i-call" name="method-i-call" class="permalink">Link</a> </div> <div class="description"> </div> <div class="sourcecode"> <p class="source-link"> Source: <a href="javascript:toggleSource('method-i-call_source')" id="l_method-i-call_source">show</a> </p> <div id="method-i-call_source" class="dyn-source"> <pre><span class="ruby-comment"># File /Users/aaron/.rvm/gems/ruby-2.0.0-head/gems/activerecord-4.0.0/lib/active_record/migration.rb, line 363</span> <span class="ruby-keyword">def</span> <span class="ruby-keyword ruby-title">call</span>(<span class="ruby-identifier">env</span>) <span class="ruby-identifier">mtime</span> = <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Migrator</span>.<span class="ruby-identifier">last_migration</span>.<span class="ruby-identifier">mtime</span>.<span class="ruby-identifier">to_i</span> <span class="ruby-keyword">if</span> <span class="ruby-ivar">@last_check</span> <span class="ruby-operator">&lt;</span> <span class="ruby-identifier">mtime</span> <span class="ruby-constant">ActiveRecord</span><span class="ruby-operator">::</span><span class="ruby-constant">Migration</span>.<span class="ruby-identifier">check_pending!</span> <span class="ruby-ivar">@last_check</span> = <span class="ruby-identifier">mtime</span> <span class="ruby-keyword">end</span> <span class="ruby-ivar">@app</span>.<span class="ruby-identifier">call</span>(<span class="ruby-identifier">env</span>) <span class="ruby-keyword">end</span></pre> </div> </div> </div> </div> </div> </body> </html>
aaronfi/chess-es6-demo
doc/api/classes/ActiveRecord/Migration/CheckPending.html
HTML
gpl-2.0
6,347
<?php use Wikimedia\IPUtils; class SpecialCheckUserLog extends SpecialPage { /** * @var string */ protected $target; public function __construct() { parent::__construct( 'CheckUserLog', 'checkuser-log' ); } public function execute( $par ) { $this->setHeaders(); $this->addHelpLink( 'Extension:CheckUser' ); $this->checkPermissions(); // Blocked users are not allowed to run checkuser queries (bug T157883) $block = $this->getUser()->getBlock(); if ( $block && $block->isSitewide() ) { throw new UserBlockedError( $block ); } $out = $this->getOutput(); $request = $this->getRequest(); $this->target = trim( $request->getVal( 'cuSearch', $par ) ); if ( $this->getUser()->isAllowed( 'checkuser' ) ) { $subtitleLink = $this->getLinkRenderer()->makeKnownLink( SpecialPage::getTitleFor( 'CheckUser' ), $this->msg( 'checkuser-showmain' )->text() ); if ( !$this->target === false ) { $subtitleLink .= ' | ' . $this->getLinkRenderer()->makeKnownLink( SpecialPage::getTitleFor( 'CheckUser', $this->target ), $this->msg( 'checkuser-check-this-user' )->text() ); } $out->addSubtitle( $subtitleLink ); } $type = $request->getVal( 'cuSearchType', 'target' ); $this->displaySearchForm(); // Default to all log entries - we'll add conditions below if a target was provided $searchConds = []; if ( $this->target !== '' ) { $searchConds = ( $type === 'initiator' ) ? $this->getPerformerSearchConds() : $this->getTargetSearchConds(); } if ( $searchConds === null ) { // Invalid target was input so show an error message and stop from here $out->wrapWikiMsg( "<div class='errorbox'>\n$1\n</div>", 'checkuser-user-nonexistent' ); return; } $pager = new CheckUserLogPager( $this->getContext(), [ 'queryConds' => $searchConds, 'year' => $request->getInt( 'year' ), 'month' => $request->getInt( 'month' ), ] ); $out->addHTML( $pager->getNavigationBar() . $pager->getBody() . $pager->getNavigationBar() ); } /** * Use an HTMLForm to create and output the search form used on this page. */ protected function displaySearchForm() { $request = $this->getRequest(); $fields = [ 'target' => [ 'type' => 'user', // validation in execute() currently 'exists' => false, 'ipallowed' => true, 'name' => 'cuSearch', 'size' => 40, 'label-message' => 'checkuser-log-search-target', 'default' => $this->target, ], 'type' => [ 'type' => 'radio', 'name' => 'cuSearchType', 'label-message' => 'checkuser-log-search-type', 'options-messages' => [ 'checkuser-search-target' => 'target', 'checkuser-search-initiator' => 'initiator', ], 'flatlist' => true, 'default' => 'target', ], // @todo hack until HTMLFormField has a proper date selector 'monthyear' => [ 'type' => 'info', 'default' => Xml::dateMenu( $request->getInt( 'year' ), $request->getInt( 'month' ) ), 'raw' => true, ], ]; $form = HTMLForm::factory( 'table', $fields, $this->getContext() ); $form->setMethod( 'get' ) ->setWrapperLegendMsg( 'checkuser-search' ) ->setSubmitTextMsg( 'checkuser-search-submit' ) ->prepareForm() ->displayForm( false ); } /** * Get DB search conditions depending on the CU performer/initiator * Use this only for searches by 'initiator' type * * @return array|null array if valid target, null if invalid */ protected function getPerformerSearchConds() { $initiator = User::newFromName( $this->target ); if ( $initiator && $initiator->getId() ) { return [ 'cul_user' => $initiator->getId() ]; } return null; } /** * Get DB search conditions according to the CU target given. * * @return array|null array if valid target, null if invalid target given */ protected function getTargetSearchConds() { list( $start, $end ) = IPUtils::parseRange( $this->target ); $conds = null; if ( $start !== false ) { $dbr = wfGetDB( DB_REPLICA ); if ( $start === $end ) { // Single IP address $conds = [ 'cul_target_hex = ' . $dbr->addQuotes( $start ) . ' OR ' . '(cul_range_end >= ' . $dbr->addQuotes( $start ) . ' AND ' . 'cul_range_start <= ' . $dbr->addQuotes( $start ) . ')' ]; } else { // IP range $conds = [ '(cul_target_hex >= ' . $dbr->addQuotes( $start ) . ' AND ' . 'cul_target_hex <= ' . $dbr->addQuotes( $end ) . ') OR ' . '(cul_range_end >= ' . $dbr->addQuotes( $start ) . ' AND ' . 'cul_range_start <= ' . $dbr->addQuotes( $end ) . ')' ]; } } else { $user = User::newFromName( $this->target ); if ( $user && $user->getId() ) { // Registered user $conds = [ 'cul_type' => [ 'userips', 'useredits' ], 'cul_target_id' => $user->getId(), ]; } } return $conds; } protected function getGroupName() { return 'changes'; } }
skizzerz/thetestwiki-checkuser
includes/specials/SpecialCheckUserLog.php
PHP
gpl-2.0
4,918
#pragma once // "Immediate mode"-lookalike buffered drawing. Very fast way to draw 2D. #include <vector> #include "base/basictypes.h" #include "base/colorutil.h" #include "gfx/gl_lost_manager.h" #include "gfx/texture_atlas.h" #include "math/geom2d.h" #include "math/lin/matrix4x4.h" #include "thin3d/thin3d.h" #undef DrawText struct Atlas; enum { ALIGN_LEFT = 0, ALIGN_RIGHT = 16, ALIGN_TOP = 0, ALIGN_BOTTOM = 1, ALIGN_HCENTER = 4, ALIGN_VCENTER = 8, ALIGN_VBASELINE = 32, // text only, possibly not yet working ALIGN_CENTER = ALIGN_HCENTER | ALIGN_VCENTER, ALIGN_TOPLEFT = ALIGN_TOP | ALIGN_LEFT, ALIGN_TOPRIGHT = ALIGN_TOP | ALIGN_RIGHT, ALIGN_BOTTOMLEFT = ALIGN_BOTTOM | ALIGN_LEFT, ALIGN_BOTTOMRIGHT = ALIGN_BOTTOM | ALIGN_RIGHT, // Only for text drawing ROTATE_90DEG_LEFT = 256, ROTATE_90DEG_RIGHT = 512, ROTATE_180DEG = 1024, // For "uncachable" text like debug log. // Avoids using system font drawing as it's too slow. // Not actually used here but is reserved for whatever system wraps DrawBuffer. FLAG_DYNAMIC_ASCII = 2048, FLAG_NO_PREFIX = 4096, // means to not process ampersands FLAG_WRAP_TEXT = 8192, }; namespace Draw { class Pipeline; } enum DrawBufferPrimitiveMode { DBMODE_NORMAL = 0, DBMODE_LINES = 1 }; struct GradientStop { float t; uint32_t color; }; class TextDrawer; class DrawBuffer { public: DrawBuffer(); ~DrawBuffer(); void Begin(Draw::Pipeline *pipeline); void End(); // TODO: Enforce these. Now Init is autocalled and shutdown not called. void Init(Draw::DrawContext *t3d, Draw::Pipeline *pipeline); void Shutdown(); // So that callers can create appropriate pipelines. Draw::InputLayout *CreateInputLayout(Draw::DrawContext *t3d); int Count() const { return count_; } void Flush(bool set_blend_state = true); void Rect(float x, float y, float w, float h, uint32_t color, int align = ALIGN_TOPLEFT); void hLine(float x1, float y, float x2, uint32_t color); void vLine(float x, float y1, float y2, uint32_t color); void vLineAlpha50(float x, float y1, float y2, uint32_t color); void Line(int atlas_image, float x1, float y1, float x2, float y2, float thickness, uint32_t color); void RectOutline(float x, float y, float w, float h, uint32_t color, int align = ALIGN_TOPLEFT); void RectVGradient(float x, float y, float w, float h, uint32_t colorTop, uint32_t colorBottom); void RectVDarkFaded(float x, float y, float w, float h, uint32_t colorTop) { RectVGradient(x, y, w, h, colorTop, darkenColor(colorTop)); } void MultiVGradient(float x, float y, float w, float h, GradientStop *stops, int numStops); void RectCenter(float x, float y, float w, float h, uint32_t color) { Rect(x - w/2, y - h/2, w, h, color); } void Rect(float x, float y, float w, float h, float u, float v, float uw, float uh, uint32_t color); void V(float x, float y, float z, uint32_t color, float u, float v); void V(float x, float y, uint32_t color, float u, float v) { V(x, y, 0.0f, color, u, v); } void Circle(float x, float y, float radius, float thickness, int segments, float startAngle, uint32_t color, float u_mul); // New drawing APIs // Must call this before you use any functions with atlas_image etc. void SetAtlas(const Atlas *_atlas) { atlas = _atlas; } const Atlas *GetAtlas() const { return atlas; } void MeasureImage(ImageID atlas_image, float *w, float *h); void DrawImage(ImageID atlas_image, float x, float y, float scale, Color color = COLOR(0xFFFFFF), int align = ALIGN_TOPLEFT); void DrawImageStretch(ImageID atlas_image, float x1, float y1, float x2, float y2, Color color = COLOR(0xFFFFFF)); void DrawImageStretch(ImageID atlas_image, const Bounds &bounds, Color color = COLOR(0xFFFFFF)) { DrawImageStretch(atlas_image, bounds.x, bounds.y, bounds.x2(), bounds.y2(), color); } void DrawImageRotated(ImageID atlas_image, float x, float y, float scale, float angle, Color color = COLOR(0xFFFFFF), bool mirror_h = false); // Always centers void DrawTexRect(float x1, float y1, float x2, float y2, float u1, float v1, float u2, float v2, Color color); void DrawTexRect(const Bounds &bounds, float u1, float v1, float u2, float v2, Color color) { DrawTexRect(bounds.x, bounds.y, bounds.x2(), bounds.y2(), u1, v1, u2, v2, color); } // Results in 18 triangles. Kind of expensive for a button. void DrawImage4Grid(ImageID atlas_image, float x1, float y1, float x2, float y2, Color color = COLOR(0xFFFFFF), float corner_scale = 1.0); // This is only 6 triangles, much cheaper. void DrawImage2GridH(ImageID atlas_image, float x1, float y1, float x2, Color color = COLOR(0xFFFFFF), float scale = 1.0); void MeasureText(int font, const char *text, float *w, float *h); // NOTE: Count is in plain chars not utf-8 chars! void MeasureTextCount(int font, const char *text, int count, float *w, float *h); void MeasureTextRect(int font, const char *text, int count, const Bounds &bounds, float *w, float *h, int align = 0); void DrawTextRect(int font, const char *text, float x, float y, float w, float h, Color color = 0xFFFFFFFF, int align = 0); void DrawText(int font, const char *text, float x, float y, Color color = 0xFFFFFFFF, int align = 0); void DrawTextShadow(int font, const char *text, float x, float y, Color color = 0xFFFFFFFF, int align = 0); void SetFontScale(float xs, float ys) { fontscalex = xs; fontscaley = ys; } static void DoAlign(int flags, float *x, float *y, float *w, float *h); void PushDrawMatrix(const Matrix4x4 &m) { drawMatrixStack_.push_back(drawMatrix_); drawMatrix_ = m; } void PopDrawMatrix() { drawMatrix_ = drawMatrixStack_.back(); drawMatrixStack_.pop_back(); } Matrix4x4 GetDrawMatrix() { return drawMatrix_; } void PushAlpha(float a) { alphaStack_.push_back(alpha_); alpha_ *= a; } void PopAlpha() { alpha_ = alphaStack_.back(); alphaStack_.pop_back(); } private: struct Vertex { float x, y, z; float u, v; uint32_t rgba; }; Matrix4x4 drawMatrix_; std::vector<Matrix4x4> drawMatrixStack_; float alpha_ = 1.0f; std::vector<float> alphaStack_; Draw::DrawContext *draw_; Draw::Buffer *vbuf_; Draw::Pipeline *pipeline_; Vertex *verts_; int count_; DrawBufferPrimitiveMode mode_; const Atlas *atlas; bool inited_; float fontscalex; float fontscaley; };
Orphis/ppsspp
ext/native/gfx_es2/draw_buffer.h
C
gpl-2.0
6,296
<?php /** * Fabrik List Template: AdminModule CSS * * @package Joomla * @subpackage Fabrik * @copyright Copyright (C) 2005-2015 fabrikar.com - All rights reserved. * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ header('Content-type: text/css'); $c = $_REQUEST['c']; echo " #listform_$c .fabrik_buttons{ height:2.5em; text-align:right; } #listform_$c a, #listform_$c .fabrikDataContainer a:hover{ border:0; background:transparent; } #listform_$c td.decimal, #listform_$c td.integer{ text-align:right; } #listform_$c .list-footer{ display:-moz-box; display:-webkit-box; display:box; } #listform_$c .list-footer div{ margin-top:8px; margin-left:10px; } #listform_$c .list-footer .pagination{ margin-left:20px; } #listform_$c .fabrik_ordercell a{ text-decoration:none; color:#333; } #listform_$c .fabrik_ordercell a:hover{ color:#333; } #listform_$c .fabrikElementContainer{ /** for inline edit **/ position:relative; } #listform_$c table.fabrikList, .advancedSearch_$c table { border-collapse: collapse; margin-top: 10px; } #listform_$c table.fabrikList td,table.fabrikList th, .advancedSearch_$c td, .advancedSearch_$c th { padding: 5px; border-bottom: 2px solid #e6e8e9; vertical-align:top; } /** bump calendar above mocha window in mootools 1.2**/ div.calendar{ z-index:115 !important; } /** autocomplete container inject in doc body not iin #forn_$c */ .auto-complete-container{ overflow-y: hidden; border:1px solid #ddd; } .auto-complete-container ul{ list-style:none; background-color:#fff; margin:0; padding:0; } .auto-complete-container li{ text-align:left; padding:2px 10px !important; background:#fff; margin:0 !important; border-top:1px solid #ddd; cursor:hand; } .auto-complete-container li:hover, .auto-complete-container li.selected{ background-color:#DFFAFF !important; cursor:pointer; } #listform_$c .fabrikForm { margin-top: 15px; } #listform_$c .fabrikNav{ border-top: 1px solid #333; } #listform_$c .fabrik_groupheading a{ color: #777777; text-decoration:none; } #listform_$c .firstPage,.previousPage,.aPage,.nextPage,.lastPage { display: inline; padding: 3px; } #listform_$c table.filtertable { width: 50%; float: right; } #listform_$c .fabrikHover, #advancedSearchContainer tr:hover { background-color: #ffffff; } /** highlight the last row that was clicked */ #listform_$c .fabrikRowClick { background-color: #ffffff; } /** highlight the loaded row - package only */ #listform_$c .activeRow { background-color: #FFFFCC; } #listform_$c .emptyDataMessage { background-color: #EFE7B8; border-color: #EFD859; border-width: 2px 0; border-style: solid; padding: 5px; margin: 10px 0; font-size: 1em; color: #CC0000; font-weight: bold; } #listform_$c .fabrikButtons { text-align: right; padding-top: 10px; } #listform_$c ul.fabrikRepeatData { padding: 0; margin: 0; list-style: none; } #listform_$c ul.fabrikRepeatData li { background-image: none; padding: 0; margin: 0; } #listform_$c .filtertitle{ border-bottom:1px dotted #fff; cursor:pointer; } #listform_$c .fabrikFilterContainer { background-color: #1A80B2; color: #FFFFFF; padding: 10px 15px; position: absolute; display:none; border-radius: 0 0 6px 6px; } #listform_$c .fabrikFilterContainer a{ color:#fff; padding-right:5px; } /*****************************************************/ /********** default action formatting ****************/ /*****************************************************/ #listform_$c .fabrik_row ul.fabrik_action, #listform_$c ul.fabrik_action, .advancedSearch_$c ul.fabrik_action{ list-style:none !important; border:1px solid #999; padding:0; text-align:left; font-weight: bold; font-size: 11px; -moz-border-radius: 6px; -webkit-border-radius: 6px; border-radius: 6px; height:23px; margin:5px; filter: progid : DXImageTransform.Microsoft.gradient ( startColorstr = '#cccccc', endColorstr = '#666666' ); /* for IE */ background: -webkit-gradient(linear, left top, left bottom, from(#eee), to(#ccc) ); /* for webkit browsers */ background: -moz-linear-gradient(top, #eee, #ccc); background-image: -ms-linear-gradient(top, #eee, #ccc); display:-moz-box; /* chrome: causes images in menu not to be displayed display:-webkit-box;*/ display:box; float:right; } #listform_$c .fabrik_row ul.fabrik_action span, #listform_$c ul.fabrik_action span{ display:none; } #listform_$c ul.fabrik_action.fabrik_keeptext span{ display:inline; } #listform_$c .fabrik_row .fabrik_action li, #listform_$c .fabrik_action li, .advancedSearch_$c .fabrik_action li{ float:left; padding:2px 6px 0 6px; border-left:1px solid #999; min-height:17px; margin-top:2px; margin-bottom:2px; } #listform_$c .fabrik_row .fabrik_action li:first-child, #listform_$c .fabrik_action li:first-child, .advancedSearch_$c .fabrik_action li:first-child{ -moz-border-radius: 6px 0 0 6px; -webkit-border-radius: 6px 0 0 6px; border-radius: 6px 0 0 6px; border:0; } #listform_$c .fabrik_row .fabrik_action li:last-child, #listform_$c .fabrik_action li:last-child, .advancedSearch_$c .fabrik_action li:last-child{ -moz-border-radius: 0 6px 6px 0; -webkit-border-radius: 0 6px 6px 0; border-radius: 0 6px 6px 0; } ";?>
rodhoff/cdn1
components/com_fabrik/views/list/tmpl25/adminmodule/template_css.php
PHP
gpl-2.0
5,247
angular.module('bhima.controllers') .controller('StockSettingsController', StockSettingsController); StockSettingsController.$inject = [ 'StockSettingsService', 'EnterpriseService', 'util', 'NotifyService', 'SessionService', 'bhConstants', ]; /** * Stock Settings Controller * This module is a for getting/updating the parameters/settings related to Stock */ function StockSettingsController( StockSettings, Enterprises, util, Notify, Session, bhConstants, ) { const vm = this; vm.enterprise = {}; vm.settings = {}; let $touched = false; // bind methods vm.submit = submit; vm.onSelectCostCenter = onSelectCostCenter; // fired on startup function startup() { // load enterprises Enterprises.read() .then(enterprises => { // Assume the enterprise data has been created already [vm.enterprise] = enterprises; const params = { enterprise_id : vm.enterprise.id }; // Now look up the stock settings // (assume they have already been created ) return StockSettings.read(null, params); }) .then(settings => { if (settings.length > 0) { [vm.settings] = settings; } }) .catch(Notify.handleError); // load algorithms for Average Consumption vm.algorithms = bhConstants.average_consumption_algo; } function onSelectCostCenter(cc) { const ccKey = 'default_cost_center_for_loss'; vm.settings[ccKey] = cc.id; } // form submission function submit(form) { if (form.$invalid) { Notify.danger('FORM.ERRORS.HAS_ERRORS'); return 0; } // make sure only fresh data is sent to the server. if (form.$pristine && !$touched) { Notify.warn('FORM.WARNINGS.NO_CHANGES'); return 0; } const changes = util.filterFormElements(form, true); Object.keys(vm.settings).forEach(key => { delete changes[key]; }); changes.settings = angular.copy(vm.settings); const promise = StockSettings.update(vm.enterprise.id, changes); return promise .then(() => Notify.success('FORM.INFO.UPDATE_SUCCESS')) .then(() => Session.reload()) // Should we just refresh the stock settings in the Session? .catch(Notify.handleError); } /** * @function proxy * * @description * Proxies requests for different stock settings. * * @returns {function} */ function proxy(key) { return (enabled) => { vm.settings[key] = enabled; $touched = true; }; } vm.enableAutoStockAccounting = proxy('enable_auto_stock_accounting'); vm.enableAutoPurchaseOrderConfirmation = proxy('enable_auto_purchase_order_confirmation'); vm.enableStrictDepotPermission = proxy('enable_strict_depot_permission'); vm.enableSupplierCredit = proxy('enable_supplier_credit'); vm.enableStrictDepotDistribution = proxy('enable_strict_depot_distribution'); vm.enableExpiredStockOut = proxy('enable_expired_stock_out'); vm.setMonthAverage = function setMonthAverage() { $touched = true; }; vm.setDefaultMinMonthsSecurityStock = function setDefaultMinMonthsSecurityStock() { $touched = true; }; vm.setMinDelay = () => { $touched = true; }; vm.setPurchaseInterval = () => { $touched = true; }; startup(); }
IMA-WorldHealth/bhima
client/src/modules/stock/settings/stock-settings.js
JavaScript
gpl-2.0
3,282
/* Copyright (C) 2003-2007 Tensilica, Inc. All Rights Reserved. Revised to support Tensilica processors and to improve overall performance */ /* Front-end tree definitions for GNU compiler. Copyright (C) 1989, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000 Free Software Foundation, Inc. This file is part of GNU CC. GNU CC 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, or (at your option) any later version. GNU CC 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 GNU CC; see the file COPYING. If not, write to the Free Software Foundation, 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #include "machmode.h" #include "version.h" #ifndef RTX_CODE struct rtx_def; #endif /* Codes of tree nodes */ #define DEFTREECODE(SYM, STRING, TYPE, NARGS) SYM, enum tree_code { #include "tree.def" LAST_AND_UNUSED_TREE_CODE /* A convenient way to get a value for NUM_TREE_CODE. */ }; #undef DEFTREECODE /* Number of language-independent tree codes. */ #define NUM_TREE_CODES ((int) LAST_AND_UNUSED_TREE_CODE) /* Indexed by enum tree_code, contains a character which is `<' for a comparison expression, `1', for a unary arithmetic expression, `2' for a binary arithmetic expression, `e' for other types of expressions, `r' for a reference, `c' for a constant, `d' for a decl, `t' for a type, `s' for a statement, and `x' for anything else (TREE_LIST, IDENTIFIER, etc). */ #define MAX_TREE_CODES 256 extern char tree_code_type[MAX_TREE_CODES]; #define TREE_CODE_CLASS(CODE) tree_code_type[(int) (CODE)] /* Returns non-zero iff CLASS is the tree-code class of an expression. */ #define IS_EXPR_CODE_CLASS(CLASS) \ (CLASS == '<' || CLASS == '1' || CLASS == '2' || CLASS == 'e') /* Number of argument-words in each kind of tree-node. */ extern int tree_code_length[MAX_TREE_CODES]; #define TREE_CODE_LENGTH(CODE) tree_code_length[(int) (CODE)] /* Names of tree components. */ extern const char *tree_code_name[MAX_TREE_CODES]; /* Classify which part of the compiler has defined a given builtin function. Note that we assume below that this is no more than two bits. */ enum built_in_class { NOT_BUILT_IN = 0, BUILT_IN_FRONTEND, BUILT_IN_MD, BUILT_IN_NORMAL }; /* Names for the above. */ extern const char *const built_in_class_names[4]; /* Codes that identify the various built in functions so that expand_call can identify them quickly. */ #define DEF_BUILTIN(x) x, enum built_in_function { #include "builtins.def" /* Upper bound on non-language-specific builtins. */ END_BUILTINS }; #undef DEF_BUILTIN /* Names for the above. */ extern const char *const built_in_names[(int) END_BUILTINS]; /* The definition of tree nodes fills the next several pages. */ /* A tree node can represent a data type, a variable, an expression or a statement. Each node has a TREE_CODE which says what kind of thing it represents. Some common codes are: INTEGER_TYPE -- represents a type of integers. ARRAY_TYPE -- represents a type of pointer. VAR_DECL -- represents a declared variable. INTEGER_CST -- represents a constant integer value. PLUS_EXPR -- represents a sum (an expression). As for the contents of a tree node: there are some fields that all nodes share. Each TREE_CODE has various special-purpose fields as well. The fields of a node are never accessed directly, always through accessor macros. */ /* This type is used everywhere to refer to a tree node. */ typedef union tree_node *tree; /* Every kind of tree node starts with this structure, so all nodes have these fields. See the accessor macros, defined below, for documentation of the fields. */ struct tree_common { union tree_node *chain; union tree_node *type; ENUM_BITFIELD(tree_code) code : 8; unsigned side_effects_flag : 1; unsigned constant_flag : 1; unsigned permanent_flag : 1; unsigned addressable_flag : 1; unsigned volatile_flag : 1; unsigned readonly_flag : 1; unsigned unsigned_flag : 1; unsigned asm_written_flag: 1; unsigned used_flag : 1; unsigned nothrow_flag : 1; unsigned static_flag : 1; unsigned public_flag : 1; unsigned private_flag : 1; unsigned protected_flag : 1; unsigned bounded_flag : 1; unsigned lang_flag_0 : 1; unsigned lang_flag_1 : 1; unsigned lang_flag_2 : 1; unsigned lang_flag_3 : 1; unsigned lang_flag_4 : 1; unsigned lang_flag_5 : 1; unsigned lang_flag_6 : 1; }; /* The following table lists the uses of each of the above flags and for which types of nodes they are defined. Note that expressions include decls. addressable_flag: TREE_ADDRESSABLE in VAR_DECL, FUNCTION_DECL, FIELD_DECL, CONSTRUCTOR, LABEL_DECL, ..._TYPE, IDENTIFIER_NODE static_flag: TREE_STATIC in VAR_DECL, FUNCTION_DECL, CONSTRUCTOR, ADDR_EXPR TREE_NO_UNUSED_WARNING in CONVERT_EXPR, NOP_EXPR, COMPOUND_EXPR TREE_VIA_VIRTUAL in TREE_LIST or TREE_VEC TREE_CONSTANT_OVERFLOW in INTEGER_CST, REAL_CST, COMPLEX_CST TREE_SYMBOL_REFERENCED in IDENTIFIER_NODE public_flag: TREE_OVERFLOW in INTEGER_CST, REAL_CST, COMPLEX_CST TREE_PUBLIC in VAR_DECL or FUNCTION_DECL TREE_VIA_PUBLIC in TREE_LIST or TREE_VEC EXPR_WFL_EMIT_LINE_NOTE in EXPR_WITH_FILE_LOCATION private_flag: TREE_VIA_PRIVATE in TREE_LIST or TREE_VEC TREE_PRIVATE in ??? unspecified nodes protected_flag: TREE_VIA_PROTECTED in TREE_LIST TREE_PROTECTED in BLOCK ??? unspecified nodes side_effects_flag: TREE_SIDE_EFFECTS in all expressions volatile_flag: TREE_THIS_VOLATILE in all expressions TYPE_VOLATILE in ..._TYPE readonly_flag: TREE_READONLY in all expressions ITERATOR_BOUND_P in VAR_DECL if iterator (C) TYPE_READONLY in ..._TYPE constant_flag: TREE_CONSTANT in all expressions permanent_flag: TREE_PERMANENT in all nodes unsigned_flag: TREE_UNSIGNED in INTEGER_TYPE, ENUMERAL_TYPE, FIELD_DECL DECL_BUILT_IN_NONANSI in FUNCTION_DECL TREE_PARMLIST in TREE_PARMLIST (C++) SAVE_EXPR_NOPLACEHOLDER in SAVE_EXPR asm_written_flag: TREE_ASM_WRITTEN in VAR_DECL, FUNCTION_DECL, RECORD_TYPE, UNION_TYPE, QUAL_UNION_TYPE BLOCK used_flag: TREE_USED in expressions, IDENTIFIER_NODE nothrow_flag: TREE_NOTHROW in CALL_EXPR, FUNCTION_DECL bounded_flag: TREE_BOUNDED in expressions, VAR_DECL, PARM_DECL, FIELD_DECL, FUNCTION_DECL TYPE_BOUNDED in ..._TYPE */ /* Define accessors for the fields that all tree nodes have (though some fields are not used for all kinds of nodes). */ /* The tree-code says what kind of node it is. Codes are defined in tree.def. */ #define TREE_CODE(NODE) ((enum tree_code) (NODE)->common.code) #define TREE_SET_CODE(NODE, VALUE) ((NODE)->common.code = (int) (VALUE)) /* When checking is enabled, errors will be generated if a tree node is accessed incorrectly. The macros abort with a fatal error. */ #if defined ENABLE_TREE_CHECKING && (GCC_VERSION >= 2007) #define TREE_CHECK(t, code) __extension__ \ ({ const tree __t = t; \ if (TREE_CODE(__t) != (code)) \ tree_check_failed (__t, code, __FILE__, \ __LINE__, __PRETTY_FUNCTION__); \ __t; }) #define TREE_CLASS_CHECK(t, class) __extension__ \ ({ const tree __t = t; \ if (TREE_CODE_CLASS(TREE_CODE(__t)) != (class)) \ tree_class_check_failed (__t, class, __FILE__, \ __LINE__, __PRETTY_FUNCTION__); \ __t; }) /* These checks have to be special cased. */ #define CST_OR_CONSTRUCTOR_CHECK(t) __extension__ \ ({ const tree __t = t; \ enum tree_code __c = TREE_CODE(__t); \ if (__c != CONSTRUCTOR && TREE_CODE_CLASS(__c) != 'c') \ tree_check_failed (__t, CONSTRUCTOR, __FILE__, \ __LINE__, __PRETTY_FUNCTION__); \ __t; }) #define EXPR_CHECK(t) __extension__ \ ({ const tree __t = t; \ char __c = TREE_CODE_CLASS(TREE_CODE(__t)); \ if (__c != 'r' && __c != 's' && __c != '<' \ && __c != '1' && __c != '2' && __c != 'e') \ tree_class_check_failed(__t, 'e', __FILE__, \ __LINE__, __PRETTY_FUNCTION__); \ __t; }) extern void tree_check_failed PARAMS ((const tree, enum tree_code, const char *, int, const char *)) ATTRIBUTE_NORETURN; extern void tree_class_check_failed PARAMS ((const tree, char, const char *, int, const char *)) ATTRIBUTE_NORETURN; #else /* not ENABLE_TREE_CHECKING, or not gcc */ #define TREE_CHECK(t, code) (t) #define TREE_CLASS_CHECK(t, code) (t) #define CST_OR_CONSTRUCTOR_CHECK(t) (t) #define EXPR_CHECK(t) (t) #endif #include "tree-check.h" #define TYPE_CHECK(tree) TREE_CLASS_CHECK (tree, 't') #define DECL_CHECK(tree) TREE_CLASS_CHECK (tree, 'd') #define CST_CHECK(tree) TREE_CLASS_CHECK (tree, 'c') /* In all nodes that are expressions, this is the data type of the expression. In POINTER_TYPE nodes, this is the type that the pointer points to. In ARRAY_TYPE nodes, this is the type of the elements. */ #define TREE_TYPE(NODE) ((NODE)->common.type) /* Nodes are chained together for many purposes. Types are chained together to record them for being output to the debugger (see the function `chain_type'). Decls in the same scope are chained together to record the contents of the scope. Statement nodes for successive statements used to be chained together. Often lists of things are represented by TREE_LIST nodes that are chained together. */ #define TREE_CHAIN(NODE) ((NODE)->common.chain) /* Given an expression as a tree, strip any NON_LVALUE_EXPRs and NOP_EXPRs that don't change the machine mode. */ #define STRIP_NOPS(EXP) \ while ((TREE_CODE (EXP) == NOP_EXPR \ || TREE_CODE (EXP) == CONVERT_EXPR \ || TREE_CODE (EXP) == NON_LVALUE_EXPR) \ && (TYPE_MODE (TREE_TYPE (EXP)) \ == TYPE_MODE (TREE_TYPE (TREE_OPERAND (EXP, 0))))) \ (EXP) = TREE_OPERAND (EXP, 0); /* Like STRIP_NOPS, but don't let the signedness change either. */ #define STRIP_SIGN_NOPS(EXP) \ while ((TREE_CODE (EXP) == NOP_EXPR \ || TREE_CODE (EXP) == CONVERT_EXPR \ || TREE_CODE (EXP) == NON_LVALUE_EXPR) \ && (TYPE_MODE (TREE_TYPE (EXP)) \ == TYPE_MODE (TREE_TYPE (TREE_OPERAND (EXP, 0)))) \ && (TREE_UNSIGNED (TREE_TYPE (EXP)) \ == TREE_UNSIGNED (TREE_TYPE (TREE_OPERAND (EXP, 0))))) \ (EXP) = TREE_OPERAND (EXP, 0); /* Like STRIP_NOPS, but don't alter the TREE_TYPE either. */ #define STRIP_TYPE_NOPS(EXP) \ while ((TREE_CODE (EXP) == NOP_EXPR \ || TREE_CODE (EXP) == CONVERT_EXPR \ || TREE_CODE (EXP) == NON_LVALUE_EXPR) \ && (TREE_TYPE (EXP) \ == TREE_TYPE (TREE_OPERAND (EXP, 0)))) \ (EXP) = TREE_OPERAND (EXP, 0); /* Nonzero if TYPE represents an integral type. Note that we do not include COMPLEX types here. */ #define INTEGRAL_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == INTEGER_TYPE || TREE_CODE (TYPE) == ENUMERAL_TYPE \ || TREE_CODE (TYPE) == BOOLEAN_TYPE || TREE_CODE (TYPE) == CHAR_TYPE) /* Nonzero if TYPE represents a floating-point type, including complex floating-point types. */ #define FLOAT_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == REAL_TYPE \ || (TREE_CODE (TYPE) == COMPLEX_TYPE \ && TREE_CODE (TREE_TYPE (TYPE)) == REAL_TYPE)) /* Nonzero if TYPE represents an aggregate (multi-component) type. */ #define AGGREGATE_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == ARRAY_TYPE || TREE_CODE (TYPE) == RECORD_TYPE \ || TREE_CODE (TYPE) == UNION_TYPE || TREE_CODE (TYPE) == QUAL_UNION_TYPE \ || TREE_CODE (TYPE) == SET_TYPE) /* Nonzero if TYPE represents an unbounded pointer or unbounded reference type. (It should be renamed to INDIRECT_TYPE_P.) */ #define POINTER_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == POINTER_TYPE || TREE_CODE (TYPE) == REFERENCE_TYPE) /* Nonzero if TYPE represents a bounded pointer or bounded reference type. */ #define BOUNDED_INDIRECT_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == RECORD_TYPE && TREE_TYPE (TYPE)) /* Nonzero if TYPE represents a bounded pointer type. */ #define BOUNDED_POINTER_TYPE_P(TYPE) \ (BOUNDED_INDIRECT_TYPE_P (TYPE) \ && TREE_CODE (TYPE_BOUNDED_SUBTYPE (TYPE)) == POINTER_TYPE) /* Nonzero if TYPE represents a bounded reference type. Bounded reference types have two specific uses: (1) When a reference is seated to a variable-length RECORD_TYPE that has an array of indeterminate length as its final field. For all other objects, it is sufficient to check bounds at the time the reference is seated, and assume that all future uses of the reference are safe, since the address of references cannot change. (2) When a reference supertype is seated to an subtype object. The bounds "remember" the true size of the complete object, so that subsequent upcasts of the address of the reference will be checked properly (is such a thing valid C++?). */ #define BOUNDED_REFERENCE_TYPE_P(TYPE) \ (BOUNDED_INDIRECT_TYPE_P (TYPE) \ && TREE_CODE (TYPE_BOUNDED_SUBTYPE (TYPE)) == REFERENCE_TYPE) /* Nonzero if TYPE represents a pointer or reference type, either bounded or unbounded. */ #define MAYBE_BOUNDED_INDIRECT_TYPE_P(TYPE) \ (POINTER_TYPE_P (TYPE) || BOUNDED_INDIRECT_TYPE_P (TYPE)) /* Nonzero if TYPE represents a pointer type, either bounded or unbounded. */ #define MAYBE_BOUNDED_POINTER_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == POINTER_TYPE || BOUNDED_POINTER_TYPE_P (TYPE)) /* Nonzero if TYPE represents a reference type, either bounded or unbounded. */ #define MAYBE_BOUNDED_REFERENCE_TYPE_P(TYPE) \ (TREE_CODE (TYPE) == REFERENCE_TYPE || BOUNDED_REFERENCE_TYPE_P (TYPE)) /* Nonzero if this type is a complete type. */ #define COMPLETE_TYPE_P(NODE) (TYPE_SIZE (NODE) != NULL_TREE) /* Nonzero if this type is the (possibly qualified) void type. */ #define VOID_TYPE_P(NODE) (TYPE_MAIN_VARIANT (NODE) == void_type_node) /* Nonzero if this type is complete or is cv void. */ #define COMPLETE_OR_VOID_TYPE_P(NODE) \ (COMPLETE_TYPE_P (NODE) || VOID_TYPE_P (NODE)) /* Nonzero if this type is complete or is an array with unspecified bound. */ #define COMPLETE_OR_UNBOUND_ARRAY_TYPE_P(NODE) \ (COMPLETE_TYPE_P (TREE_CODE (NODE) == ARRAY_TYPE ? TREE_TYPE (NODE) : NODE)) /* Nonzero if TYPE represents a type. */ #define TYPE_P(TYPE) (TREE_CODE_CLASS (TREE_CODE (TYPE)) == 't') /* Define many boolean fields that all tree nodes have. */ /* In VAR_DECL nodes, nonzero means address of this is needed. So it cannot be in a register. In a FUNCTION_DECL, nonzero means its address is needed. So it must be compiled even if it is an inline function. In a FIELD_DECL node, it means that the programmer is permitted to construct the address of this field. This is used for aliasing purposes: see record_component_aliases. In CONSTRUCTOR nodes, it means object constructed must be in memory. In LABEL_DECL nodes, it means a goto for this label has been seen from a place outside all binding contours that restore stack levels. In ..._TYPE nodes, it means that objects of this type must be fully addressable. This means that pieces of this object cannot go into register parameters, for example. In IDENTIFIER_NODEs, this means that some extern decl for this name had its address taken. That matters for inline functions. */ #define TREE_ADDRESSABLE(NODE) ((NODE)->common.addressable_flag) /* In a VAR_DECL, nonzero means allocate static storage. In a FUNCTION_DECL, nonzero if function has been defined. In a CONSTRUCTOR, nonzero means allocate static storage. */ #define TREE_STATIC(NODE) ((NODE)->common.static_flag) /* In a CONVERT_EXPR, NOP_EXPR or COMPOUND_EXPR, this means the node was made implicitly and should not lead to an "unused value" warning. */ #define TREE_NO_UNUSED_WARNING(NODE) ((NODE)->common.static_flag) /* Nonzero for a TREE_LIST or TREE_VEC node means that the derivation chain is via a `virtual' declaration. */ #define TREE_VIA_VIRTUAL(NODE) ((NODE)->common.static_flag) /* In an INTEGER_CST, REAL_CST, or COMPLEX_CST, this means there was an overflow in folding. This is distinct from TREE_OVERFLOW because ANSI C requires a diagnostic when overflows occur in constant expressions. */ #define TREE_CONSTANT_OVERFLOW(NODE) ((NODE)->common.static_flag) /* In an IDENTIFIER_NODE, this means that assemble_name was called with this string as an argument. */ #define TREE_SYMBOL_REFERENCED(NODE) ((NODE)->common.static_flag) /* In an INTEGER_CST, REAL_CST, of COMPLEX_CST, this means there was an overflow in folding, and no warning has been issued for this subexpression. TREE_OVERFLOW implies TREE_CONSTANT_OVERFLOW, but not vice versa. */ #define TREE_OVERFLOW(NODE) ((NODE)->common.public_flag) /* In a VAR_DECL or FUNCTION_DECL, nonzero means name is to be accessible from outside this module. In an identifier node, nonzero means an external declaration accessible from outside this module was previously seen for this name in an inner scope. */ #define TREE_PUBLIC(NODE) ((NODE)->common.public_flag) /* Nonzero for TREE_LIST or TREE_VEC node means that the path to the base class is via a `public' declaration, which preserves public fields from the base class as public. */ #define TREE_VIA_PUBLIC(NODE) ((NODE)->common.public_flag) /* Ditto, for `private' declarations. */ #define TREE_VIA_PRIVATE(NODE) ((NODE)->common.private_flag) /* Nonzero for TREE_LIST node means that the path to the base class is via a `protected' declaration, which preserves protected fields from the base class as protected. OVERLOADED. */ #define TREE_VIA_PROTECTED(NODE) ((NODE)->common.protected_flag) /* In any expression, nonzero means it has side effects or reevaluation of the whole expression could produce a different value. This is set if any subexpression is a function call, a side effect or a reference to a volatile variable. In a ..._DECL, this is set only if the declaration said `volatile'. */ #define TREE_SIDE_EFFECTS(NODE) ((NODE)->common.side_effects_flag) /* Nonzero means this expression is volatile in the C sense: its address should be of type `volatile WHATEVER *'. In other words, the declared item is volatile qualified. This is used in _DECL nodes and _REF nodes. In a ..._TYPE node, means this type is volatile-qualified. But use TYPE_VOLATILE instead of this macro when the node is a type, because eventually we may make that a different bit. If this bit is set in an expression, so is TREE_SIDE_EFFECTS. */ #define TREE_THIS_VOLATILE(NODE) ((NODE)->common.volatile_flag) /* In a VAR_DECL, PARM_DECL or FIELD_DECL, or any kind of ..._REF node, nonzero means it may not be the lhs of an assignment. In a ..._TYPE node, means this type is const-qualified (but the macro TYPE_READONLY should be used instead of this macro when the node is a type). */ #define TREE_READONLY(NODE) ((NODE)->common.readonly_flag) /* Value of expression is constant. Always appears in all ..._CST nodes. May also appear in an arithmetic expression, an ADDR_EXPR or a CONSTRUCTOR if the value is constant. */ #define TREE_CONSTANT(NODE) ((NODE)->common.constant_flag) /* Nonzero means permanent node; node will continue to exist for the entire compiler run. Otherwise it will be recycled at the end of the function. This flag is always zero if garbage collection is in use. Try not to use this. Only set it with TREE_SET_PERMANENT. */ #define TREE_PERMANENT(NODE) ((NODE)->common.permanent_flag) #define TREE_SET_PERMANENT(NODE) do { \ if (!ggc_p && current_obstack == &permanent_obstack) \ TREE_PERMANENT(NODE) = 1; \ } while (0) /* In INTEGER_TYPE or ENUMERAL_TYPE nodes, means an unsigned type. In FIELD_DECL nodes, means an unsigned bit field. The same bit is used in functions as DECL_BUILT_IN_NONANSI. */ #define TREE_UNSIGNED(NODE) ((NODE)->common.unsigned_flag) /* Nonzero in a VAR_DECL means assembler code has been written. Nonzero in a FUNCTION_DECL means that the function has been compiled. This is interesting in an inline function, since it might not need to be compiled separately. Nonzero in a RECORD_TYPE, UNION_TYPE, QUAL_UNION_TYPE or ENUMERAL_TYPE if the sdb debugging info for the type has been written. In a BLOCK node, nonzero if reorder_blocks has already seen this block. */ #define TREE_ASM_WRITTEN(NODE) ((NODE)->common.asm_written_flag) /* Nonzero in a _DECL if the name is used in its scope. Nonzero in an expr node means inhibit warning if value is unused. In IDENTIFIER_NODEs, this means that some extern decl for this name was used. */ #define TREE_USED(NODE) ((NODE)->common.used_flag) /* In a FUNCTION_DECL, nonzero means a call to the function cannot throw an exception. In a CALL_EXPR, nonzero means the call cannot throw. */ #define TREE_NOTHROW(NODE) ((NODE)->common.nothrow_flag) /* Used in classes in C++. */ #define TREE_PRIVATE(NODE) ((NODE)->common.private_flag) /* Used in classes in C++. In a BLOCK node, this is BLOCK_HANDLER_BLOCK. */ #define TREE_PROTECTED(NODE) ((NODE)->common.protected_flag) /* In a ..._TYPE node, nonzero means that the type's size and layout, (or the size and layout of its arguments and/or return value in the case of a FUNCTION_TYPE or METHOD_TYPE) was changed by the presence of pointer bounds. Use TYPE_BOUNDED instead of this macro when the node is a type, because eventually we may make that a different bit. TYPE_BOUNDED doesn't mean that this type is a bounded indirect type--use BOUNDED_POINTER_TYPE_P, BOUNDED_REFERENCE_TYPE_P, BOUNDED_INDIRECT_TYPE_P to test for that. In a FUNCTION_DECL, nonzero means that the size and layout of one of its arguments and/or return value was changed by the presence of pointer bounds. This value can differ from the value of TYPE_BOUNDED (TREE_TYPE (fundecl)) if the function was implicitly declared, then later called with pointer args, or was declared with a variable argument list and is later called with pointer values in the variable argument list. In a VAR_DECL, PARM_DECL or FIELD_DECL, TREE_BOUNDED matches the value of the decl's type's BOUNDED_POINTER_TYPE_P. In a CONSTRUCTOR or other expression, nonzero means the value is a bounded pointer. It is insufficient to determine the boundedness of an expression EXP with BOUNDED_POINTER_TYPE_P (TREE_TYPE (EXP)), since we allow pointer to be temporarily cast to integer for rounding up to an alignment boudary in a way that preserves the pointer's bounds. In an IDENTIFIER_NODE, nonzero means that the name is prefixed with BP_PREFIX (see varasm.c). This occurs for the DECL_ASSEMBLER_NAME of a function that has bounded pointer(s) for its return type and/or argument type(s). */ #define TREE_BOUNDED(NODE) ((NODE)->common.bounded_flag) /* These flags are available for each language front end to use internally. */ #define TREE_LANG_FLAG_0(NODE) ((NODE)->common.lang_flag_0) #define TREE_LANG_FLAG_1(NODE) ((NODE)->common.lang_flag_1) #define TREE_LANG_FLAG_2(NODE) ((NODE)->common.lang_flag_2) #define TREE_LANG_FLAG_3(NODE) ((NODE)->common.lang_flag_3) #define TREE_LANG_FLAG_4(NODE) ((NODE)->common.lang_flag_4) #define TREE_LANG_FLAG_5(NODE) ((NODE)->common.lang_flag_5) #define TREE_LANG_FLAG_6(NODE) ((NODE)->common.lang_flag_6) /* Define additional fields and accessors for nodes representing constants. */ /* In an INTEGER_CST node. These two together make a 2-word integer. If the data type is signed, the value is sign-extended to 2 words even though not all of them may really be in use. In an unsigned constant shorter than 2 words, the extra bits are 0. */ #define TREE_INT_CST_LOW(NODE) (INTEGER_CST_CHECK (NODE)->int_cst.int_cst_low) #define TREE_INT_CST_HIGH(NODE) (INTEGER_CST_CHECK (NODE)->int_cst.int_cst_high) #define INT_CST_LT(A, B) \ (TREE_INT_CST_HIGH (A) < TREE_INT_CST_HIGH (B) \ || (TREE_INT_CST_HIGH (A) == TREE_INT_CST_HIGH (B) \ && TREE_INT_CST_LOW (A) < TREE_INT_CST_LOW (B))) #define INT_CST_LT_UNSIGNED(A, B) \ (((unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (A) \ < (unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (B)) \ || (((unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (A) \ == (unsigned HOST_WIDE_INT) TREE_INT_CST_HIGH (B)) \ && TREE_INT_CST_LOW (A) < TREE_INT_CST_LOW (B))) struct tree_int_cst { struct tree_common common; struct rtx_def *rtl; /* acts as link to register transfer language (rtl) info */ unsigned HOST_WIDE_INT int_cst_low; HOST_WIDE_INT int_cst_high; }; /* In REAL_CST, STRING_CST, COMPLEX_CST nodes, and CONSTRUCTOR nodes, and generally in all kinds of constants that could be given labels (rather than being immediate). */ #define TREE_CST_RTL(NODE) (CST_OR_CONSTRUCTOR_CHECK (NODE)->real_cst.rtl) /* In a REAL_CST node. */ /* We can represent a real value as either a `double' or a string. Strings don't allow for any optimization, but they do allow for cross-compilation. */ #define TREE_REAL_CST(NODE) (REAL_CST_CHECK (NODE)->real_cst.real_cst) #include "real.h" struct tree_real_cst { struct tree_common common; struct rtx_def *rtl; /* acts as link to register transfer language (rtl) info */ REAL_VALUE_TYPE real_cst; }; /* In a STRING_CST */ #define TREE_STRING_LENGTH(NODE) (STRING_CST_CHECK (NODE)->string.length) #define TREE_STRING_POINTER(NODE) (STRING_CST_CHECK (NODE)->string.pointer) struct tree_string { struct tree_common common; struct rtx_def *rtl; /* acts as link to register transfer language (rtl) info */ int length; char *pointer; }; /* In a COMPLEX_CST node. */ #define TREE_REALPART(NODE) (COMPLEX_CST_CHECK (NODE)->complex.real) #define TREE_IMAGPART(NODE) (COMPLEX_CST_CHECK (NODE)->complex.imag) struct tree_complex { struct tree_common common; struct rtx_def *rtl; /* acts as link to register transfer language (rtl) info */ union tree_node *real; union tree_node *imag; }; /* Define fields and accessors for some special-purpose tree nodes. */ #define IDENTIFIER_LENGTH(NODE) (IDENTIFIER_NODE_CHECK (NODE)->identifier.length) #define IDENTIFIER_POINTER(NODE) (IDENTIFIER_NODE_CHECK (NODE)->identifier.pointer) struct tree_identifier { struct tree_common common; int length; char *pointer; }; /* In a TREE_LIST node. */ #define TREE_PURPOSE(NODE) (TREE_LIST_CHECK (NODE)->list.purpose) #define TREE_VALUE(NODE) (TREE_LIST_CHECK (NODE)->list.value) struct tree_list { struct tree_common common; union tree_node *purpose; union tree_node *value; }; /* In a TREE_VEC node. */ #define TREE_VEC_LENGTH(NODE) (TREE_VEC_CHECK (NODE)->vec.length) #define TREE_VEC_ELT(NODE,I) (TREE_VEC_CHECK (NODE)->vec.a[I]) #define TREE_VEC_END(NODE) ((void) TREE_VEC_CHECK (NODE),&((NODE)->vec.a[(NODE)->vec.length])) struct tree_vec { struct tree_common common; int length; union tree_node *a[1]; }; /* Define fields and accessors for some nodes that represent expressions. */ /* In a SAVE_EXPR node. */ #define SAVE_EXPR_CONTEXT(NODE) TREE_OPERAND(NODE, 1) #define SAVE_EXPR_RTL(NODE) (*(struct rtx_def **) &EXPR_CHECK (NODE)->exp.operands[2]) #define SAVE_EXPR_NOPLACEHOLDER(NODE) TREE_UNSIGNED (NODE) /* Nonzero if the SAVE_EXPRs value should be kept, even if it occurs both in normal code and in a handler. (Normally, in a handler, all SAVE_EXPRs are unsaved, meaning that there values are recalculated.) */ #define SAVE_EXPR_PERSISTENT_P(NODE) TREE_ASM_WRITTEN (NODE) /* In a RTL_EXPR node. */ #define RTL_EXPR_SEQUENCE(NODE) (*(struct rtx_def **) &EXPR_CHECK (NODE)->exp.operands[0]) #define RTL_EXPR_RTL(NODE) (*(struct rtx_def **) &EXPR_CHECK (NODE)->exp.operands[1]) /* In a CALL_EXPR node. */ #define CALL_EXPR_RTL(NODE) (*(struct rtx_def **) &EXPR_CHECK (NODE)->exp.operands[2]) /* In a CONSTRUCTOR node. */ #define CONSTRUCTOR_ELTS(NODE) TREE_OPERAND (NODE, 1) /* In ordinary expression nodes. */ #define TREE_OPERAND(NODE, I) (EXPR_CHECK (NODE)->exp.operands[I]) #define TREE_COMPLEXITY(NODE) (EXPR_CHECK (NODE)->exp.complexity) /* In a LABELED_BLOCK_EXPR node. */ #define LABELED_BLOCK_LABEL(NODE) TREE_OPERAND (NODE, 0) #define LABELED_BLOCK_BODY(NODE) TREE_OPERAND (NODE, 1) /* In a EXIT_BLOCK_EXPR node. */ #define EXIT_BLOCK_LABELED_BLOCK(NODE) TREE_OPERAND (NODE, 0) #define EXIT_BLOCK_RETURN(NODE) TREE_OPERAND (NODE, 1) /* In a LOOP_EXPR node. */ #define LOOP_EXPR_BODY(NODE) TREE_OPERAND (NODE, 0) /* In a EXPR_WITH_FILE_LOCATION node. */ #define EXPR_WFL_NODE(NODE) TREE_OPERAND((NODE), 0) #define EXPR_WFL_FILENAME(NODE) \ (IDENTIFIER_POINTER (EXPR_WFL_FILENAME_NODE ((NODE)))) #define EXPR_WFL_FILENAME_NODE(NODE) TREE_OPERAND((NODE), 1) #define EXPR_WFL_LINENO(NODE) (EXPR_CHECK (NODE)->exp.complexity >> 12) #define EXPR_WFL_COLNO(NODE) (EXPR_CHECK (NODE)->exp.complexity & 0xfff) #define EXPR_WFL_LINECOL(NODE) (EXPR_CHECK (NODE)->exp.complexity) #define EXPR_WFL_SET_LINECOL(NODE, LINE, COL) \ (EXPR_WFL_LINECOL(NODE) = ((LINE) << 12) | ((COL) & 0xfff)) #define EXPR_WFL_EMIT_LINE_NOTE(NODE) ((NODE)->common.public_flag) struct tree_exp { struct tree_common common; int complexity; union tree_node *operands[1]; }; /* In a BLOCK node. */ #define BLOCK_VARS(NODE) (BLOCK_CHECK (NODE)->block.vars) #define BLOCK_SUBBLOCKS(NODE) (BLOCK_CHECK (NODE)->block.subblocks) #define BLOCK_SUPERCONTEXT(NODE) (BLOCK_CHECK (NODE)->block.supercontext) /* Note: when changing this, make sure to find the places that use chainon or nreverse. */ #define BLOCK_CHAIN(NODE) TREE_CHAIN (NODE) #define BLOCK_ABSTRACT_ORIGIN(NODE) (BLOCK_CHECK (NODE)->block.abstract_origin) #define BLOCK_ABSTRACT(NODE) (BLOCK_CHECK (NODE)->block.abstract_flag) /* Nonzero means that this block is prepared to handle exceptions listed in the BLOCK_VARS slot. */ #define BLOCK_HANDLER_BLOCK(NODE) (BLOCK_CHECK (NODE)->block.handler_block_flag) /* An index number for this block. These values are not guaranteed to be unique across functions -- whether or not they are depends on the debugging output format in use. */ #define BLOCK_NUMBER(NODE) (BLOCK_CHECK (NODE)->block.block_num) struct tree_block { struct tree_common common; unsigned handler_block_flag : 1; unsigned abstract_flag : 1; unsigned block_num : 30; union tree_node *vars; union tree_node *subblocks; union tree_node *supercontext; union tree_node *abstract_origin; }; /* Define fields and accessors for nodes representing data types. */ /* See tree.def for documentation of the use of these fields. Look at the documentation of the various ..._TYPE tree codes. */ #define TYPE_UID(NODE) (TYPE_CHECK (NODE)->type.uid) #define TYPE_SIZE(NODE) (TYPE_CHECK (NODE)->type.size) #define TYPE_SIZE_UNIT(NODE) (TYPE_CHECK (NODE)->type.size_unit) #define TYPE_MODE(NODE) (TYPE_CHECK (NODE)->type.mode) #define TYPE_VALUES(NODE) (TYPE_CHECK (NODE)->type.values) #define TYPE_DOMAIN(NODE) (TYPE_CHECK (NODE)->type.values) #define TYPE_FIELDS(NODE) (TYPE_CHECK (NODE)->type.values) #define TYPE_METHODS(NODE) (TYPE_CHECK (NODE)->type.maxval) #define TYPE_VFIELD(NODE) (TYPE_CHECK (NODE)->type.minval) #define TYPE_ARG_TYPES(NODE) (TYPE_CHECK (NODE)->type.values) #define TYPE_METHOD_BASETYPE(NODE) (TYPE_CHECK (NODE)->type.maxval) #define TYPE_OFFSET_BASETYPE(NODE) (TYPE_CHECK (NODE)->type.maxval) #define TYPE_POINTER_TO(NODE) (TYPE_CHECK (NODE)->type.pointer_to) #define TYPE_REFERENCE_TO(NODE) (TYPE_CHECK (NODE)->type.reference_to) #define TYPE_MIN_VALUE(NODE) (TYPE_CHECK (NODE)->type.minval) #define TYPE_MAX_VALUE(NODE) (TYPE_CHECK (NODE)->type.maxval) #define TYPE_PRECISION(NODE) (TYPE_CHECK (NODE)->type.precision) #define TYPE_SYMTAB_ADDRESS(NODE) (TYPE_CHECK (NODE)->type.symtab.address) #define TYPE_SYMTAB_POINTER(NODE) (TYPE_CHECK (NODE)->type.symtab.pointer) #define TYPE_NAME(NODE) (TYPE_CHECK (NODE)->type.name) #define TYPE_NEXT_VARIANT(NODE) (TYPE_CHECK (NODE)->type.next_variant) #define TYPE_MAIN_VARIANT(NODE) (TYPE_CHECK (NODE)->type.main_variant) #define TYPE_NONCOPIED_PARTS(NODE) (TYPE_CHECK (NODE)->type.noncopied_parts) #define TYPE_CONTEXT(NODE) (TYPE_CHECK (NODE)->type.context) #define TYPE_OBSTACK(NODE) (TYPE_CHECK (NODE)->type.obstack) #define TYPE_LANG_SPECIFIC(NODE) (TYPE_CHECK (NODE)->type.lang_specific) /* Indirect types present difficulties because they may be represented as either POINTER_TYPE/REFERENCE_TYPE nodes (unbounded) or as RECORD_TYPE nodes (bounded). Bounded and unbounded pointers might be logically equivalent, but physically different. Simple comparison of the main variant only tells if the types are logically equivalent. Use this predicate to compare for physical equivalency. */ /* Types have the same main variant, and have the same boundedness. */ #define TYPE_MAIN_VARIANTS_PHYSICALLY_EQUAL_P(TYPE1, TYPE2) \ (TYPE_MAIN_VARIANT (TYPE1) == TYPE_MAIN_VARIANT (TYPE2) \ && TREE_CODE (TYPE1) == TREE_CODE (TYPE2)) /* Return the type variant that has no qualifiers (i.e., the main variant), except that the boundedness qualifier is preserved. */ #define TYPE_MAIN_PHYSICAL_VARIANT(TYPE) \ (BOUNDED_POINTER_TYPE_P (TYPE) \ ? build_qualified_type (TYPE, TYPE_QUAL_BOUNDED) \ : TYPE_MAIN_VARIANT (TYPE)) /* For aggregate types, information about this type, as a base type for itself. Used in a language-dependent way for types that are neither a RECORD_TYPE, QUAL_UNION_TYPE, nor a UNION_TYPE. */ #define TYPE_BINFO(NODE) (TYPE_CHECK (NODE)->type.binfo) /* The (language-specific) typed-based alias set for this type. Objects whose TYPE_ALIAS_SETs are different cannot alias each other. If the TYPE_ALIAS_SET is -1, no alias set has yet been assigned to this type. If the TYPE_ALIAS_SET is 0, objects of this type can alias objects of any type. */ #define TYPE_ALIAS_SET(NODE) (TYPE_CHECK (NODE)->type.alias_set) /* Nonzero iff the typed-based alias set for this type has been calculated. */ #define TYPE_ALIAS_SET_KNOWN_P(NODE) \ (TYPE_CHECK (NODE)->type.alias_set != -1) /* A TREE_LIST of IDENTIFIER nodes of the attributes that apply to this type. */ #define TYPE_ATTRIBUTES(NODE) (TYPE_CHECK (NODE)->type.attributes) /* The alignment necessary for objects of this type. The value is an int, measured in bits. */ #define TYPE_ALIGN(NODE) (TYPE_CHECK (NODE)->type.align) #define TYPE_ATTR_ALIGN(NODE) (TYPE_CHECK (NODE)->type.attr_align) /* The alignment for NODE, in bytes. */ #define TYPE_ALIGN_UNIT(NODE) \ (TYPE_ALIGN (NODE) / BITS_PER_UNIT) #define TYPE_STUB_DECL(NODE) (TREE_CHAIN (NODE)) /* In a RECORD_TYPE, UNION_TYPE or QUAL_UNION_TYPE, it means the type has BLKmode only because it lacks the alignment requirement for its size. */ #define TYPE_NO_FORCE_BLK(NODE) (TYPE_CHECK (NODE)->type.no_force_blk_flag) /* In an INTEGER_TYPE, it means the type represents a size. We use this both for validity checking and to permit optimziations that are unsafe for other types. */ #define TYPE_IS_SIZETYPE(NODE) (TYPE_CHECK (NODE)->type.no_force_blk_flag) /* Nonzero in a type considered volatile as a whole. */ #define TYPE_VOLATILE(NODE) ((NODE)->common.volatile_flag) /* Means this type is const-qualified. */ #define TYPE_READONLY(NODE) ((NODE)->common.readonly_flag) /* If nonzero, this type is `restrict'-qualified, in the C sense of the term. */ #define TYPE_RESTRICT(NODE) (TYPE_CHECK (NODE)->type.restrict_flag) /* If nonzero, this type's size and layout, (or the size and layout of its arguments and/or return value in the case of a FUNCTION_TYPE or METHOD_TYPE) was changed by the presence of pointer bounds. */ #define TYPE_BOUNDED(NODE) (TYPE_CHECK (NODE)->common.bounded_flag) /* There is a TYPE_QUAL value for each type qualifier. They can be combined by bitwise-or to form the complete set of qualifiers for a type. */ #define TYPE_UNQUALIFIED 0x0 #define TYPE_QUAL_CONST 0x1 #define TYPE_QUAL_VOLATILE 0x2 #define TYPE_QUAL_RESTRICT 0x4 #define TYPE_QUAL_BOUNDED 0x8 /* The set of type qualifiers for this type. */ #define TYPE_QUALS(NODE) \ ((TYPE_READONLY (NODE) * TYPE_QUAL_CONST) \ | (TYPE_VOLATILE (NODE) * TYPE_QUAL_VOLATILE) \ | (TYPE_RESTRICT (NODE) * TYPE_QUAL_RESTRICT) \ | (BOUNDED_INDIRECT_TYPE_P (NODE) * TYPE_QUAL_BOUNDED)) /* The set of qualifiers pertinent to an expression node. */ #define TREE_EXPR_QUALS(NODE) \ ((TREE_READONLY (NODE) * TYPE_QUAL_CONST) \ | (TREE_THIS_VOLATILE (NODE) * TYPE_QUAL_VOLATILE) \ | (TREE_BOUNDED (NODE) * TYPE_QUAL_BOUNDED)) /* The set of qualifiers pertinent to a FUNCTION_DECL node. */ #define TREE_FUNC_QUALS(NODE) \ ((TREE_READONLY (NODE) * TYPE_QUAL_CONST) \ | (TREE_THIS_VOLATILE (NODE) * TYPE_QUAL_VOLATILE)) /* These flags are available for each language front end to use internally. */ #define TYPE_LANG_FLAG_0(NODE) (TYPE_CHECK (NODE)->type.lang_flag_0) #define TYPE_LANG_FLAG_1(NODE) (TYPE_CHECK (NODE)->type.lang_flag_1) #define TYPE_LANG_FLAG_2(NODE) (TYPE_CHECK (NODE)->type.lang_flag_2) #define TYPE_LANG_FLAG_3(NODE) (TYPE_CHECK (NODE)->type.lang_flag_3) #define TYPE_LANG_FLAG_4(NODE) (TYPE_CHECK (NODE)->type.lang_flag_4) #define TYPE_LANG_FLAG_5(NODE) (TYPE_CHECK (NODE)->type.lang_flag_5) #define TYPE_LANG_FLAG_6(NODE) (TYPE_CHECK (NODE)->type.lang_flag_6) /* If set in an ARRAY_TYPE, indicates a string type (for languages that distinguish string from array of char). If set in a SET_TYPE, indicates a bitstring type. */ #define TYPE_STRING_FLAG(NODE) (TYPE_CHECK (NODE)->type.string_flag) /* If non-NULL, this is a upper bound of the size (in bytes) of an object of the given ARRAY_TYPE. This allows temporaries to be allocated. */ #define TYPE_ARRAY_MAX_SIZE(ARRAY_TYPE) TYPE_MAX_VALUE (ARRAY_TYPE) /* Indicates that objects of this type must be initialized by calling a function when they are created. */ #define TYPE_NEEDS_CONSTRUCTING(NODE) \ (TYPE_CHECK (NODE)->type.needs_constructing_flag) /* Indicates that objects of this type (a UNION_TYPE), should be passed the same way that the first union alternative would be passed. */ #define TYPE_TRANSPARENT_UNION(NODE) \ (UNION_TYPE_CHECK (NODE)->type.transparent_union_flag) /* For an ARRAY_TYPE, indicates that it is not permitted to take the address of a component of the type. */ #define TYPE_NONALIASED_COMPONENT(NODE) \ (ARRAY_TYPE_CHECK (NODE)->type.transparent_union_flag) /* Indicated that objects of this type should be laid out in as compact a way as possible. */ #define TYPE_PACKED(NODE) (TYPE_CHECK (NODE)->type.packed_flag) /* A bounded pointer or bounded reference type (collectively called indirect types) is represented as a RECORD_TYPE node containing three pointer fields whose type is the corresponding unbounded POINTER_TYPE or REFERENCE_TYPE. A RECORD_TYPE node that represents a bounded indirect type differs from a normal RECORD_TYPE node in that its TREE_TYPE is non-NULL and has the pointed-to type just as a POINTER_TYPE or REFERENCE_TYPE node has. The bounded RECORD_TYPE nodes are stored on the same type variant chain alongside the variants of the underlaying indirect types nodes. The main variant of such chains is always the unbounded type. */ /* Access the field decls of a bounded-pointer type. */ #define TYPE_BOUNDED_VALUE(TYPE) TYPE_FIELDS (TYPE) #define TYPE_BOUNDED_BASE(TYPE) TREE_CHAIN (TYPE_BOUNDED_VALUE (TYPE)) #define TYPE_BOUNDED_EXTENT(TYPE) TREE_CHAIN (TYPE_BOUNDED_BASE (TYPE)) /* Access the simple-pointer subtype of a bounded-pointer type. */ #define TYPE_BOUNDED_SUBTYPE(TYPE) TREE_TYPE (TYPE_BOUNDED_VALUE (TYPE)) /* Find the unbounded counterpart to a type, or return TYPE if it is already unbounded. */ #define TYPE_UNBOUNDED_VARIANT(TYPE) \ (BOUNDED_POINTER_TYPE_P (TYPE) ? TYPE_BOUNDED_SUBTYPE (TYPE) : (TYPE)) /* This field comprises two bits, for values in the range 0..3: depth=0 means that type is a scalar, or an aggregate that contains only depth=0 types, or a function that has only depth=0 types for its return value and argument types. depth=1 means that type is a pointer to a depth=0 type, or an aggregate that contains only depth=0 and depth=1 types, or a function that has only depth=0 and depth=1 types for its return value and argument types. The meanings of depth=2 and depth=3 are obvious by induction. Varargs functions are depth=3. The type `va_list' is depth=3. The purpose of measuring pointer depth of a type is to determine the eligibility of a function for an automatically-generated bounded-pointer thunk. A depth=0 functions needs no thunk. A depth=1 function is eligible for an automatic thunk. Functions with depth 2 or more are too complex to get automatic thunks. Function decls also have a pointer_depth field, since we also consider the actual argument types for functions. */ #define TYPE_POINTER_DEPTH(TYPE) (TYPE_CHECK (TYPE)->type.pointer_depth) /* In a FUNCTION_TYPE node, this bit stores the value of default_pointer_boundedness at the time TYPE was created. It is useful for choosing default boundedness of function arguments for non-prototype function decls and for varargs/stdarg lists. */ #define TYPE_AMBIENT_BOUNDEDNESS(TYPE) \ (FUNCTION_TYPE_CHECK (TYPE)->type.transparent_union_flag) #define MAX_POINTER_DEPTH 2 #define VA_LIST_POINTER_DEPTH 3 struct tree_type { struct tree_common common; union tree_node *values; union tree_node *size; union tree_node *size_unit; union tree_node *attributes; unsigned int uid; unsigned int precision : 9; ENUM_BITFIELD(machine_mode) mode : 7; unsigned string_flag : 1; unsigned no_force_blk_flag : 1; unsigned needs_constructing_flag : 1; unsigned transparent_union_flag : 1; unsigned packed_flag : 1; unsigned restrict_flag : 1; unsigned pointer_depth : 2; unsigned lang_flag_0 : 1; unsigned lang_flag_1 : 1; unsigned lang_flag_2 : 1; unsigned lang_flag_3 : 1; unsigned lang_flag_4 : 1; unsigned lang_flag_5 : 1; unsigned lang_flag_6 : 1; unsigned int attr_align : 5; unsigned int align; union tree_node *pointer_to; union tree_node *reference_to; union {int address; char *pointer; } symtab; union tree_node *name; union tree_node *minval; union tree_node *maxval; union tree_node *next_variant; union tree_node *main_variant; union tree_node *binfo; union tree_node *noncopied_parts; union tree_node *context; struct obstack *obstack; HOST_WIDE_INT alias_set; /* Points to a structure whose details depend on the language in use. */ struct lang_type *lang_specific; unsigned int attr_fill; /* attribute fill amount*/ }; /* Define accessor macros for information about type inheritance and basetypes. A "basetype" means a particular usage of a data type for inheritance in another type. Each such basetype usage has its own "binfo" object to describe it. The binfo object is a TREE_VEC node. Inheritance is represented by the binfo nodes allocated for a given type. For example, given types C and D, such that D is inherited by C, 3 binfo nodes will be allocated: one for describing the binfo properties of C, similarly one for D, and one for describing the binfo properties of D as a base type for C. Thus, given a pointer to class C, one can get a pointer to the binfo of D acting as a basetype for C by looking at C's binfo's basetypes. */ /* The actual data type node being inherited in this basetype. */ #define BINFO_TYPE(NODE) TREE_TYPE (NODE) /* The offset where this basetype appears in its containing type. BINFO_OFFSET slot holds the offset (in bytes) from the base of the complete object to the base of the part of the object that is allocated on behalf of this `type'. This is always 0 except when there is multiple inheritance. */ #define BINFO_OFFSET(NODE) TREE_VEC_ELT ((NODE), 1) #define TYPE_BINFO_OFFSET(NODE) BINFO_OFFSET (TYPE_BINFO (NODE)) #define BINFO_OFFSET_ZEROP(NODE) (integer_zerop (BINFO_OFFSET (NODE))) /* The virtual function table belonging to this basetype. Virtual function tables provide a mechanism for run-time method dispatching. The entries of a virtual function table are language-dependent. */ #define BINFO_VTABLE(NODE) TREE_VEC_ELT ((NODE), 2) #define TYPE_BINFO_VTABLE(NODE) BINFO_VTABLE (TYPE_BINFO (NODE)) /* The virtual functions in the virtual function table. This is a TREE_LIST that is used as an initial approximation for building a virtual function table for this basetype. */ #define BINFO_VIRTUALS(NODE) TREE_VEC_ELT ((NODE), 3) #define TYPE_BINFO_VIRTUALS(NODE) BINFO_VIRTUALS (TYPE_BINFO (NODE)) /* A vector of binfos for the direct basetypes inherited by this basetype. If this basetype describes type D as inherited in C, and if the basetypes of D are E and F, then this vector contains binfos for inheritance of E and F by C. ??? This could probably be done by just allocating the base types at the end of this TREE_VEC (instead of using another TREE_VEC). This would simplify the calculation of how many basetypes a given type had. */ #define BINFO_BASETYPES(NODE) TREE_VEC_ELT ((NODE), 4) #define TYPE_BINFO_BASETYPES(NODE) TREE_VEC_ELT (TYPE_BINFO (NODE), 4) /* The number of basetypes for NODE. */ #define BINFO_N_BASETYPES(NODE) \ (BINFO_BASETYPES (NODE) ? TREE_VEC_LENGTH (BINFO_BASETYPES (NODE)) : 0) /* Accessor macro to get to the Nth basetype of this basetype. */ #define BINFO_BASETYPE(NODE,N) TREE_VEC_ELT (BINFO_BASETYPES (NODE), (N)) #define TYPE_BINFO_BASETYPE(NODE,N) BINFO_TYPE (TREE_VEC_ELT (BINFO_BASETYPES (TYPE_BINFO (NODE)), (N))) /* For a BINFO record describing a virtual base class, i.e., one where TREE_VIA_VIRTUAL is set, this field assists in locating the virtual base. The actual contents are language-dependent. Under the old ABI, the C++ front-end uses a FIELD_DECL whose contents are a pointer to the virtual base; under the new ABI this field is instead a INTEGER_CST giving an offset into the vtable where the offset to the virtual base can be found. */ #define BINFO_VPTR_FIELD(NODE) TREE_VEC_ELT ((NODE), 5) /* The size of a base class subobject of this type. Not all frontends currently allocate the space for these fields. */ #define BINFO_SIZE(NODE) TREE_VEC_ELT ((NODE), 6) #define BINFO_SIZE_UNIT(NODE) TREE_VEC_ELT ((NODE), 7) #define TYPE_BINFO_SIZE(NODE) BINFO_SIZE (TYPE_BINFO (NODE)) #define TYPE_BINFO_SIZE_UNIT(NODE) BINFO_SIZE_UNIT (TYPE_BINFO (NODE)) /* Slot used to build a chain that represents a use of inheritance. For example, if X is derived from Y, and Y is derived from Z, then this field can be used to link the binfo node for X to the binfo node for X's Y to represent the use of inheritance from X to Y. Similarly, this slot of the binfo node for X's Y can point to the Z from which Y is inherited (in X's inheritance hierarchy). In this fashion, one can represent and traverse specific uses of inheritance using the binfo nodes themselves (instead of consing new space pointing to binfo nodes). It is up to the language-dependent front-ends to maintain this information as necessary. */ #define BINFO_INHERITANCE_CHAIN(NODE) TREE_VEC_ELT ((NODE), 0) /* Define fields and accessors for nodes representing declared names. */ /* Nonzero if DECL represents a decl. */ #define DECL_P(DECL) (TREE_CODE_CLASS (TREE_CODE (DECL)) == 'd') /* This is the name of the object as written by the user. It is an IDENTIFIER_NODE. */ #define DECL_NAME(NODE) (DECL_CHECK (NODE)->decl.name) /* This is the name of the object as the assembler will see it (but before any translations made by ASM_OUTPUT_LABELREF). Often this is the same as DECL_NAME. It is an IDENTIFIER_NODE. */ #define DECL_ASSEMBLER_NAME(NODE) (DECL_CHECK (NODE)->decl.assembler_name) /* Records the section name in a section attribute. Used to pass the name from decl_attributes to make_function_rtl and make_decl_rtl. */ #define DECL_SECTION_NAME(NODE) (DECL_CHECK (NODE)->decl.section_name) /* Records the rodata section name in a section attribute. Used to pass the name from decl_attributes to make_function_rtl and make_decl_rtl. */ #define DECL_ROSECTION_NAME(NODE) (DECL_CHECK (NODE)->decl.ro_section_name) /* For FIELD_DECLs, this is the RECORD_TYPE, UNION_TYPE, or QUAL_UNION_TYPE node that the field is a member of. For VAR_DECL, PARM_DECL, FUNCTION_DECL, LABEL_DECL, and CONST_DECL nodes, this points to either the FUNCTION_DECL for the containing function, the RECORD_TYPE or UNION_TYPE for the containing type, or NULL_TREE if the given decl has "file scope". */ #define DECL_CONTEXT(NODE) (DECL_CHECK (NODE)->decl.context) #define DECL_FIELD_CONTEXT(NODE) (FIELD_DECL_CHECK (NODE)->decl.context) /* In a DECL this is the field where configuration dependent machine attributes are store */ #define DECL_MACHINE_ATTRIBUTES(NODE) (DECL_CHECK (NODE)->decl.machine_attributes) /* In a FIELD_DECL, this is the field position, counting in bytes, of the byte containing the bit closest to the beginning of the structure. */ #define DECL_FIELD_OFFSET(NODE) (FIELD_DECL_CHECK (NODE)->decl.arguments) /* In a FIELD_DECL, this is the offset, in bits, of the first bit of the field from DECL_FIELD_OFFSET. */ #define DECL_FIELD_BIT_OFFSET(NODE) (FIELD_DECL_CHECK (NODE)->decl.u2.t) /* In a FIELD_DECL, this indicates whether the field was a bit-field and if so, the type that was originally specified for it. TREE_TYPE may have been modified (in finish_struct). */ #define DECL_BIT_FIELD_TYPE(NODE) (FIELD_DECL_CHECK (NODE)->decl.result) /* In FUNCTION_DECL, a chain of ..._DECL nodes. */ /* VAR_DECL and PARM_DECL reserve the arguments slot for language-specific uses. */ #define DECL_ARGUMENTS(NODE) (DECL_CHECK (NODE)->decl.arguments) /* This field is used to reference anything in decl.result and is meant only for use by the garbage collector. */ #define DECL_RESULT_FLD(NODE) (DECL_CHECK (NODE)->decl.result) /* In FUNCTION_DECL, holds the decl for the return value. */ #define DECL_RESULT(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.result) /* For a TYPE_DECL, holds the "original" type. (TREE_TYPE has the copy.) */ #define DECL_ORIGINAL_TYPE(NODE) (TYPE_DECL_CHECK (NODE)->decl.result) /* In PARM_DECL, holds the type as written (perhaps a function or array). */ #define DECL_ARG_TYPE_AS_WRITTEN(NODE) (PARM_DECL_CHECK (NODE)->decl.result) /* For a FUNCTION_DECL, holds the tree of BINDINGs. For a VAR_DECL, holds the initial value. For a PARM_DECL, not used--default values for parameters are encoded in the type of the function, not in the PARM_DECL slot. */ #define DECL_INITIAL(NODE) (DECL_CHECK (NODE)->decl.initial) /* For a PARM_DECL, records the data type used to pass the argument, which may be different from the type seen in the program. */ #define DECL_ARG_TYPE(NODE) (PARM_DECL_CHECK (NODE)->decl.initial) /* For a FIELD_DECL in a QUAL_UNION_TYPE, records the expression, which if nonzero, indicates that the field occupies the type. */ #define DECL_QUALIFIER(NODE) (FIELD_DECL_CHECK (NODE)->decl.initial) /* These two fields describe where in the source code the declaration was. */ #define DECL_SOURCE_FILE(NODE) (DECL_CHECK (NODE)->decl.filename) #define DECL_SOURCE_LINE(NODE) (DECL_CHECK (NODE)->decl.linenum) /* Holds the size of the datum, in bits, as a tree expression. Need not be constant. */ #define DECL_SIZE(NODE) (DECL_CHECK (NODE)->decl.size) /* Likewise for the size in bytes. */ #define DECL_SIZE_UNIT(NODE) (DECL_CHECK (NODE)->decl.size_unit) /* Restricted pointers. */ #define DECL_RESTRICT(NODE) (DECL_CHECK (NODE)->decl.restrict_flag) /* Holds the alignment required for the datum. */ #define DECL_ALIGN(NODE) (DECL_CHECK (NODE)->decl.u1.a.align) #define DECL_FILL(NODE) (DECL_CHECK (NODE)->decl.attr_fill) #define DECL_ATTR_ALIGN(NODE) (DECL_CHECK (NODE)->decl.attr_align) /* For FIELD_DECLs, holds the alignment that DECL_FIELD_OFFSET has. */ #define DECL_OFFSET_ALIGN(NODE) (FIELD_DECL_CHECK (NODE)->decl.u1.a.off_align) /* Holds the machine mode corresponding to the declaration of a variable or field. Always equal to TYPE_MODE (TREE_TYPE (decl)) except for a FIELD_DECL. */ #define DECL_MODE(NODE) (DECL_CHECK (NODE)->decl.mode) /* Holds the RTL expression for the value of a variable or function. If PROMOTED_MODE is defined, the mode of this expression may not be same as DECL_MODE. In that case, DECL_MODE contains the mode corresponding to the variable's data type, while the mode of DECL_RTL is the mode actually used to contain the data. */ #define DECL_RTL(NODE) (DECL_CHECK (NODE)->decl.rtl) /* Holds an INSN_LIST of all of the live ranges in which the variable has been moved to a possibly different register. */ #define DECL_LIVE_RANGE_RTL(NODE) (DECL_CHECK (NODE)->decl.live_range_rtl) /* For PARM_DECL, holds an RTL for the stack slot or register where the data was actually passed. */ #define DECL_INCOMING_RTL(NODE) (PARM_DECL_CHECK (NODE)->decl.u2.r) /* For FUNCTION_DECL, if it is inline, holds the saved insn chain. */ #define DECL_SAVED_INSNS(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.u2.f) /* For FUNCTION_DECL, if it is inline, holds the size of the stack frame, as an integer. */ #define DECL_FRAME_SIZE(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.u1.i) /* For FUNCTION_DECL, if it is built-in, this identifies which built-in operation it is. */ #define DECL_FUNCTION_CODE(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.u1.f) /* The DECL_VINDEX is used for FUNCTION_DECLS in two different ways. Before the struct containing the FUNCTION_DECL is laid out, DECL_VINDEX may point to a FUNCTION_DECL in a base class which is the FUNCTION_DECL which this FUNCTION_DECL will replace as a virtual function. When the class is laid out, this pointer is changed to an INTEGER_CST node which is suitable for use as an index into the virtual function table. */ #define DECL_VINDEX(NODE) (DECL_CHECK (NODE)->decl.vindex) /* For FIELD_DECLS, DECL_FCONTEXT is the *first* baseclass in which this FIELD_DECL is defined. This information is needed when writing debugging information about vfield and vbase decls for C++. */ #define DECL_FCONTEXT(NODE) (FIELD_DECL_CHECK (NODE)->decl.vindex) /* Every ..._DECL node gets a unique number. */ #define DECL_UID(NODE) (DECL_CHECK (NODE)->decl.uid) /* For any sort of a ..._DECL node, this points to the original (abstract) decl node which this decl is an instance of, or else it is NULL indicating that this decl is not an instance of some other decl. For example, in a nested declaration of an inline function, this points back to the definition. */ #define DECL_ABSTRACT_ORIGIN(NODE) (DECL_CHECK (NODE)->decl.abstract_origin) /* Like DECL_ABSTRACT_ORIGIN, but returns NODE if there's no abstract origin. This is useful when setting the DECL_ABSTRACT_ORIGIN. */ #define DECL_ORIGIN(NODE) \ (DECL_ABSTRACT_ORIGIN (NODE) ? DECL_ABSTRACT_ORIGIN (NODE) : NODE) /* Nonzero for any sort of ..._DECL node means this decl node represents an inline instance of some original (abstract) decl from an inline function; suppress any warnings about shadowing some other variable. FUNCTION_DECL nodes can also have their abstract origin set to themselves (see save_for_inline_copying). */ #define DECL_FROM_INLINE(NODE) (DECL_ABSTRACT_ORIGIN (NODE) != (tree) 0 \ && DECL_ABSTRACT_ORIGIN (NODE) != (NODE)) /* Nonzero if a _DECL means that the name of this decl should be ignored for symbolic debug purposes. */ #define DECL_IGNORED_P(NODE) (DECL_CHECK (NODE)->decl.ignored_flag) /* Nonzero for a given ..._DECL node means that this node represents an "abstract instance" of the given declaration (e.g. in the original declaration of an inline function). When generating symbolic debugging information, we mustn't try to generate any address information for nodes marked as "abstract instances" because we don't actually generate any code or allocate any data space for such instances. */ #define DECL_ABSTRACT(NODE) (DECL_CHECK (NODE)->decl.abstract_flag) /* Nonzero if a _DECL means that no warnings should be generated just because this decl is unused. */ #define DECL_IN_SYSTEM_HEADER(NODE) (DECL_CHECK (NODE)->decl.in_system_header_flag) /* Nonzero for a given ..._DECL node means that this node should be put in .common, if possible. If a DECL_INITIAL is given, and it is not error_mark_node, then the decl cannot be put in .common. */ #define DECL_COMMON(NODE) (DECL_CHECK (NODE)->decl.common_flag) /* Language-specific decl information. */ #define DECL_LANG_SPECIFIC(NODE) (DECL_CHECK (NODE)->decl.lang_specific) /* In a VAR_DECL or FUNCTION_DECL, nonzero means external reference: do not allocate storage, and refer to a definition elsewhere. */ #define DECL_EXTERNAL(NODE) (DECL_CHECK (NODE)->decl.external_flag) /* In a VAR_DECL for a RECORD_TYPE, sets number for non-init_priority initializatons. */ #define DEFAULT_INIT_PRIORITY 65535 #define MAX_INIT_PRIORITY 65535 #define MAX_RESERVED_INIT_PRIORITY 100 /* In a TYPE_DECL nonzero means the detail info about this type is not dumped into stabs. Instead it will generate cross reference ('x') of names. This uses the same flag as DECL_EXTERNAL. */ #define TYPE_DECL_SUPPRESS_DEBUG(NODE) \ (TYPE_DECL_CHECK (NODE)->decl.external_flag) /* In VAR_DECL and PARM_DECL nodes, nonzero means declared `register'. */ #define DECL_REGISTER(NODE) (DECL_CHECK (NODE)->decl.regdecl_flag) /* In LABEL_DECL nodes, nonzero means that an error message about jumping into such a binding contour has been printed for this label. */ #define DECL_ERROR_ISSUED(NODE) (LABEL_DECL_CHECK (NODE)->decl.regdecl_flag) /* In a FIELD_DECL, indicates this field should be bit-packed. */ #define DECL_PACKED(NODE) (FIELD_DECL_CHECK (NODE)->decl.regdecl_flag) /* In a FUNCTION_DECL with a non-zero DECL_CONTEXT, indicates that a static chain is not needed. */ #define DECL_NO_STATIC_CHAIN(NODE) \ (FUNCTION_DECL_CHECK (NODE)->decl.regdecl_flag) /* Nonzero in a ..._DECL means this variable is ref'd from a nested function. For VAR_DECL nodes, PARM_DECL nodes, and FUNCTION_DECL nodes. For LABEL_DECL nodes, nonzero if nonlocal gotos to the label are permitted. Also set in some languages for variables, etc., outside the normal lexical scope, such as class instance variables. */ #define DECL_NONLOCAL(NODE) (DECL_CHECK (NODE)->decl.nonlocal_flag) /* Nonzero in a FUNCTION_DECL means this function can be substituted where it is called. */ #define DECL_INLINE(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.inline_flag) /* In a FUNCTION_DECL, nonzero if the function cannot be inlined. */ #define DECL_UNINLINABLE_ATTRIBUTE(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.uninlinable_attribute) #define DECL_ALWAYS_INLINE(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.always_inline) #define DECL_NORETURN(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.noreturn) /* Nonzero in a FUNCTION_DECL means this is a built-in function that is not specified by ansi C and that users are supposed to be allowed to redefine for any purpose whatever. */ #define DECL_BUILT_IN_NONANSI(NODE) \ (FUNCTION_DECL_CHECK (NODE)->common.unsigned_flag) /* Nonzero in a FUNCTION_DECL means this function should be treated as if it were a malloc, meaning it returns a pointer that is not an alias. */ #define DECL_IS_MALLOC(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.malloc_flag) /* Nonzero in a FUNCTION_DECL means this function should be treated as "pure" function (like const function, but may read global memory). */ #define DECL_IS_PURE(NODE) (FUNCTION_DECL_CHECK (NODE)->decl.pure_flag) /* Nonzero in a FIELD_DECL means it is a bit field, and must be accessed specially. */ #define DECL_BIT_FIELD(NODE) (FIELD_DECL_CHECK (NODE)->decl.bit_field_flag) /* In a LABEL_DECL, nonzero means label was defined inside a binding contour that restored a stack level and which is now exited. */ #define DECL_TOO_LATE(NODE) (LABEL_DECL_CHECK (NODE)->decl.bit_field_flag) /* Unused in FUNCTION_DECL. */ /* In a VAR_DECL that's static, nonzero if the space is in the text section. */ #define DECL_IN_TEXT_SECTION(NODE) (VAR_DECL_CHECK (NODE)->decl.bit_field_flag) /* In a FUNCTION_DECL, nonzero means a built in function. */ #define DECL_BUILT_IN(NODE) (DECL_BUILT_IN_CLASS (NODE) != NOT_BUILT_IN) /* For a builtin function, identify which part of the compiler defined it. */ #define DECL_BUILT_IN_CLASS(NODE) \ ((enum built_in_class)(FUNCTION_DECL_CHECK (NODE)->decl.built_in_class)) /* Used in VAR_DECLs to indicate that the variable is a vtable. Used in FIELD_DECLs for vtable pointers. Used in FUNCTION_DECLs to indicate that the function is virtual. */ #define DECL_VIRTUAL_P(NODE) (DECL_CHECK (NODE)->decl.virtual_flag) /* Used to indicate that the linkage status of this DECL is not yet known, so it should not be output now. */ #define DECL_DEFER_OUTPUT(NODE) (DECL_CHECK (NODE)->decl.defer_output) /* Used in PARM_DECLs whose type are unions to indicate that the argument should be passed in the same way that the first union alternative would be passed. */ #define DECL_TRANSPARENT_UNION(NODE) \ (PARM_DECL_CHECK (NODE)->decl.transparent_union) /* Used in FUNCTION_DECLs to indicate that they should be run automatically at the beginning or end of execution. */ #define DECL_STATIC_CONSTRUCTOR(NODE) \ (FUNCTION_DECL_CHECK (NODE)->decl.static_ctor_flag) #define DECL_STATIC_DESTRUCTOR(NODE) \ (FUNCTION_DECL_CHECK (NODE)->decl.static_dtor_flag) /* Used to indicate that this DECL represents a compiler-generated entity. */ #define DECL_ARTIFICIAL(NODE) (DECL_CHECK (NODE)->decl.artificial_flag) /* Used to indicate that this DECL has weak linkage. */ #define DECL_WEAK(NODE) (DECL_CHECK (NODE)->decl.weak_flag) /* Used to indicate that this DECL has asmspec */ #define DECL_HAS_ASMSPEC(NODE) (DECL_CHECK (NODE)->decl.has_asmspec_flag) /* Used in TREE_PUBLIC decls to indicate that copies of this DECL in multiple translation units should be merged. */ #define DECL_ONE_ONLY(NODE) (DECL_CHECK (NODE)->decl.transparent_union) /* Used in a DECL to indicate that, even if it TREE_PUBLIC, it need not be put out unless it is needed in this translation unit. Entities like this are shared across translation units (like weak entities), but are guaranteed to be generated by any translation unit that needs them, and therefore need not be put out anywhere where they are not needed. DECL_COMDAT is just a hint to the back-end; it is up to front-ends which set this flag to ensure that there will never be any harm, other than bloat, in putting out something which is DECL_COMDAT. */ #define DECL_COMDAT(NODE) (DECL_CHECK (NODE)->decl.comdat_flag) /* Used in FUNCTION_DECLs to indicate that function entry and exit should be instrumented with calls to support routines. */ #define DECL_NO_INSTRUMENT_FUNCTION_ENTRY_EXIT(NODE) \ (FUNCTION_DECL_CHECK (NODE)->decl.no_instrument_function_entry_exit) /* Used in FUNCTION_DECLs to indicate that check-memory-usage should be disabled in this function. */ #define DECL_NO_CHECK_MEMORY_USAGE(NODE) \ (FUNCTION_DECL_CHECK (NODE)->decl.no_check_memory_usage) /* Used in FUNCTION_DECLs to indicate that limit-stack-* should be disabled in this function. */ #define DECL_NO_LIMIT_STACK(NODE) \ (FUNCTION_DECL_CHECK (NODE)->decl.no_limit_stack) /* Additional flags for language-specific uses. */ #define DECL_LANG_FLAG_0(NODE) (DECL_CHECK (NODE)->decl.lang_flag_0) #define DECL_LANG_FLAG_1(NODE) (DECL_CHECK (NODE)->decl.lang_flag_1) #define DECL_LANG_FLAG_2(NODE) (DECL_CHECK (NODE)->decl.lang_flag_2) #define DECL_LANG_FLAG_3(NODE) (DECL_CHECK (NODE)->decl.lang_flag_3) #define DECL_LANG_FLAG_4(NODE) (DECL_CHECK (NODE)->decl.lang_flag_4) #define DECL_LANG_FLAG_5(NODE) (DECL_CHECK (NODE)->decl.lang_flag_5) #define DECL_LANG_FLAG_6(NODE) (DECL_CHECK (NODE)->decl.lang_flag_6) #define DECL_LANG_FLAG_7(NODE) (DECL_CHECK (NODE)->decl.lang_flag_7) /* Used to indicate that the pointer to this DECL cannot be treated as an address constant. */ #define DECL_NON_ADDR_CONST_P(NODE) (DECL_CHECK (NODE)->decl.non_addr_const_p) /* Used in a FIELD_DECL to indicate that we cannot form the address of this component. */ #define DECL_NONADDRESSABLE_P(NODE) \ (FIELD_DECL_CHECK (NODE)->decl.non_addressable) /* Used to indicate an alias set for the memory pointed to by this particular FIELD_DECL, PARM_DECL, or VAR_DECL, which must have pointer (or reference) type. */ #define DECL_POINTER_ALIAS_SET(NODE) \ (DECL_CHECK (NODE)->decl.pointer_alias_set) /* Nonzero if an alias set has been assigned to this declaration. */ #define DECL_POINTER_ALIAS_SET_KNOWN_P(NODE) \ (DECL_POINTER_ALIAS_SET (NODE) != - 1) /* The pointer_depth field comprises two bits for values in the range 0..3. The value is normally equal to TYPE_POINTER_DEPTH of decl's type node, but for functions it migth be greater. For example, this can happen when the function is declared to accept a parameter of type void* (depth=1), but is actually called with an argument of type foo** (depth=2). The function type will get the formal parameter's depth, but the function decl will get the actual argument's depth. */ #define DECL_POINTER_DEPTH(DECL) (DECL_CHECK (DECL)->decl.pointer_depth) /* WARNING: Do not add tree pointer fields without updating ggc-common.c */ struct tree_decl { struct tree_common common; const char *filename; int linenum; unsigned int uid; union tree_node *size; ENUM_BITFIELD(machine_mode) mode : 8; unsigned external_flag : 1; unsigned nonlocal_flag : 1; unsigned regdecl_flag : 1; unsigned inline_flag : 1; unsigned bit_field_flag : 1; unsigned virtual_flag : 1; unsigned ignored_flag : 1; unsigned abstract_flag : 1; unsigned in_system_header_flag : 1; unsigned common_flag : 1; unsigned defer_output : 1; unsigned transparent_union : 1; unsigned static_ctor_flag : 1; unsigned static_dtor_flag : 1; unsigned artificial_flag : 1; unsigned has_asmspec_flag : 1; unsigned weak_flag : 1; unsigned non_addr_const_p : 1; unsigned no_instrument_function_entry_exit : 1; unsigned no_check_memory_usage : 1; unsigned comdat_flag : 1; unsigned malloc_flag : 1; unsigned no_limit_stack : 1; ENUM_BITFIELD(built_in_class) built_in_class : 2; unsigned pure_flag : 1; unsigned uninlinable_attribute : 1; unsigned always_inline : 1; unsigned noreturn : 1; unsigned pointer_depth : 2; unsigned non_addressable : 1; unsigned restrict_flag : 1; unsigned attr_align : 5; unsigned lang_flag_0 : 1; unsigned lang_flag_1 : 1; unsigned lang_flag_2 : 1; unsigned lang_flag_3 : 1; unsigned lang_flag_4 : 1; unsigned lang_flag_5 : 1; unsigned lang_flag_6 : 1; unsigned lang_flag_7 : 1; /* For a FUNCTION_DECL, if inline, this is the size of frame needed. If built-in, this is the code for which built-in function. For other kinds of decls, this is DECL_ALIGN and DECL_OFFSET_ALIGN. */ union { HOST_WIDE_INT i; enum built_in_function f; struct {unsigned int align : 24; unsigned int off_align : 8;} a; } u1; union tree_node *size_unit; union tree_node *name; union tree_node *context; union tree_node *arguments; /* Also used for DECL_FIELD_OFFSET */ union tree_node *result; /* Also used for DECL_BIT_FIELD_TYPE */ union tree_node *initial; /* Also used for DECL_QUALIFIER */ union tree_node *abstract_origin; union tree_node *assembler_name; union tree_node *section_name; union tree_node *ro_section_name; union tree_node *machine_attributes; struct rtx_def *rtl; /* RTL representation for object. */ struct rtx_def *live_range_rtl; /* In FUNCTION_DECL, if it is inline, holds the saved insn chain. In FIELD_DECL, is DECL_FIELD_BIT_OFFSET. In PARM_DECL, holds an RTL for the stack slot of register where the data was actually passed. Used by Chill and Java in LABEL_DECL and by C++ and Java in VAR_DECL. */ union { struct function *f; struct rtx_def *r; union tree_node *t; int i; } u2; union tree_node *vindex; HOST_WIDE_INT pointer_alias_set; /* Points to a structure whose details depend on the language in use. */ struct lang_decl *lang_specific; unsigned used_attribute : 1; /* was a used attribute used on a function declaration */ unsigned int attr_fill; /* for attribute fill */ }; /* Define the overall contents of a tree node. It may be any of the structures declared above for various types of node. */ union tree_node { struct tree_common common; struct tree_int_cst int_cst; struct tree_real_cst real_cst; struct tree_string string; struct tree_complex complex; struct tree_identifier identifier; struct tree_decl decl; struct tree_type type; struct tree_list list; struct tree_vec vec; struct tree_exp exp; struct tree_block block; }; /* Standard named or nameless data types of the C compiler. */ enum tree_index { TI_ERROR_MARK, TI_INTQI_TYPE, TI_INTHI_TYPE, TI_INTSI_TYPE, TI_INTDI_TYPE, TI_INTTI_TYPE, TI_UINTQI_TYPE, TI_UINTHI_TYPE, TI_UINTSI_TYPE, TI_UINTDI_TYPE, TI_UINTTI_TYPE, TI_INTEGER_ZERO, TI_INTEGER_ONE, TI_NULL_POINTER, TI_SIZE_ZERO, TI_SIZE_ONE, TI_BITSIZE_ZERO, TI_BITSIZE_ONE, TI_BITSIZE_UNIT, TI_COMPLEX_INTEGER_TYPE, TI_COMPLEX_FLOAT_TYPE, TI_COMPLEX_DOUBLE_TYPE, TI_COMPLEX_LONG_DOUBLE_TYPE, TI_FLOAT_TYPE, TI_DOUBLE_TYPE, TI_LONG_DOUBLE_TYPE, TI_VOID_TYPE, TI_PTR_TYPE, TI_CONST_PTR_TYPE, TI_PTRDIFF_TYPE, TI_VA_LIST_TYPE, #ifdef TENSILICA_CHANGES TI_FIRST_TIE_TYPE, TI_LAST_TIE_TYPE = TI_FIRST_TIE_TYPE + 127, TI_MAX = TI_LAST_TIE_TYPE #else TI_MAX #endif /* TENSILICA_CHANGES */ }; extern tree global_trees[TI_MAX]; #ifdef TENSILICA_CHANGES #define tie_type_node(i) global_trees[TI_FIRST_TIE_TYPE+(i)] #endif /* TENSILICA_CHANGES */ #define error_mark_node global_trees[TI_ERROR_MARK] #define intQI_type_node global_trees[TI_INTQI_TYPE] #define intHI_type_node global_trees[TI_INTHI_TYPE] #define intSI_type_node global_trees[TI_INTSI_TYPE] #define intDI_type_node global_trees[TI_INTDI_TYPE] #define intTI_type_node global_trees[TI_INTTI_TYPE] #define unsigned_intQI_type_node global_trees[TI_UINTQI_TYPE] #define unsigned_intHI_type_node global_trees[TI_UINTHI_TYPE] #define unsigned_intSI_type_node global_trees[TI_UINTSI_TYPE] #define unsigned_intDI_type_node global_trees[TI_UINTDI_TYPE] #define unsigned_intTI_type_node global_trees[TI_UINTTI_TYPE] #define integer_zero_node global_trees[TI_INTEGER_ZERO] #define integer_one_node global_trees[TI_INTEGER_ONE] #define size_zero_node global_trees[TI_SIZE_ZERO] #define size_one_node global_trees[TI_SIZE_ONE] #define bitsize_zero_node global_trees[TI_BITSIZE_ZERO] #define bitsize_one_node global_trees[TI_BITSIZE_ONE] #define bitsize_unit_node global_trees[TI_BITSIZE_UNIT] #define null_pointer_node global_trees[TI_NULL_POINTER] #define float_type_node global_trees[TI_FLOAT_TYPE] #define double_type_node global_trees[TI_DOUBLE_TYPE] #define long_double_type_node global_trees[TI_LONG_DOUBLE_TYPE] #define complex_integer_type_node global_trees[TI_COMPLEX_INTEGER_TYPE] #define complex_float_type_node global_trees[TI_COMPLEX_FLOAT_TYPE] #define complex_double_type_node global_trees[TI_COMPLEX_DOUBLE_TYPE] #define complex_long_double_type_node global_trees[TI_COMPLEX_LONG_DOUBLE_TYPE] #define void_type_node global_trees[TI_VOID_TYPE] /* The C type `void *'. */ #define ptr_type_node global_trees[TI_PTR_TYPE] /* The C type `const void *'. */ #define const_ptr_type_node global_trees[TI_CONST_PTR_TYPE] #define ptrdiff_type_node global_trees[TI_PTRDIFF_TYPE] #define va_list_type_node global_trees[TI_VA_LIST_TYPE] /* An enumeration of the standard C integer types. These must be ordered so that shorter types appear before longer ones. */ enum integer_type_kind { itk_char, itk_signed_char, itk_unsigned_char, itk_short, itk_unsigned_short, itk_int, itk_unsigned_int, itk_long, itk_unsigned_long, itk_long_long, itk_unsigned_long_long, itk_none }; typedef enum integer_type_kind integer_type_kind; /* The standard C integer types. Use integer_type_kind to index into this array. */ extern tree integer_types[itk_none]; #define char_type_node integer_types[itk_char] #define signed_char_type_node integer_types[itk_signed_char] #define unsigned_char_type_node integer_types[itk_unsigned_char] #define short_integer_type_node integer_types[itk_short] #define short_unsigned_type_node integer_types[itk_unsigned_short] #define integer_type_node integer_types[itk_int] #define unsigned_type_node integer_types[itk_unsigned_int] #define long_integer_type_node integer_types[itk_long] #define long_unsigned_type_node integer_types[itk_unsigned_long] #define long_long_integer_type_node integer_types[itk_long_long] #define long_long_unsigned_type_node integer_types[itk_unsigned_long_long] #define NULL_TREE (tree) NULL /* The following functions accept a wide integer argument. Rather than having to cast on every function call, we use a macro instead, that is defined here and in rtl.h. */ #ifndef exact_log2 #define exact_log2(N) exact_log2_wide ((unsigned HOST_WIDE_INT) (N)) #define floor_log2(N) floor_log2_wide ((unsigned HOST_WIDE_INT) (N)) #endif extern int exact_log2_wide PARAMS ((unsigned HOST_WIDE_INT)); extern int floor_log2_wide PARAMS ((unsigned HOST_WIDE_INT)); extern char *oballoc PARAMS ((int)); extern char *permalloc PARAMS ((int)); extern char *savealloc PARAMS ((int)); extern char *expralloc PARAMS ((int)); /* Lowest level primitive for allocating a node. The TREE_CODE is the only argument. Contents are initialized to zero except for a few of the common fields. */ extern tree make_node PARAMS ((enum tree_code)); extern tree make_lang_type PARAMS ((enum tree_code)); extern tree (*make_lang_type_fn) PARAMS ((enum tree_code)); /* Make a copy of a node, with all the same contents except for TREE_PERMANENT. (The copy is permanent iff nodes being made now are permanent.) */ extern tree copy_node PARAMS ((tree)); /* Make a copy of a chain of TREE_LIST nodes. */ extern tree copy_list PARAMS ((tree)); /* Make a TREE_VEC. */ extern tree make_tree_vec PARAMS ((int)); /* Return the (unique) IDENTIFIER_NODE node for a given name. The name is supplied as a char *. */ extern tree get_identifier PARAMS ((const char *)); /* If an identifier with the name TEXT (a null-terminated string) has previously been referred to, return that node; otherwise return NULL_TREE. */ extern tree maybe_get_identifier PARAMS ((const char *)); /* Construct various types of nodes. */ #define build_int_2(LO,HI) \ build_int_2_wide ((unsigned HOST_WIDE_INT) (LO), (HOST_WIDE_INT) (HI)) extern tree build PARAMS ((enum tree_code, tree, ...)); extern tree build_nt PARAMS ((enum tree_code, ...)); extern tree build_parse_node PARAMS ((enum tree_code, ...)); extern tree build_int_2_wide PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT)); extern tree build_real PARAMS ((tree, REAL_VALUE_TYPE)); extern tree build_real_from_int_cst PARAMS ((tree, tree)); extern tree build_complex PARAMS ((tree, tree, tree)); extern tree build_string PARAMS ((int, const char *)); extern tree build1 PARAMS ((enum tree_code, tree, tree)); extern tree build_tree_list PARAMS ((tree, tree)); extern tree build_decl_list PARAMS ((tree, tree)); extern tree build_expr_list PARAMS ((tree, tree)); extern tree build_decl PARAMS ((enum tree_code, tree, tree)); extern tree build_block PARAMS ((tree, tree, tree, tree, tree)); extern tree build_expr_wfl PARAMS ((tree, const char *, int, int)); /* Construct various nodes representing data types. */ extern tree make_signed_type PARAMS ((int)); extern tree make_unsigned_type PARAMS ((int)); #ifdef TENSILICA_CHANGES extern tree make_tie_type PARAMS ((int, int)); #endif /* TENSILICA_CHANGES */ extern void initialize_sizetypes PARAMS ((void)); extern void set_sizetype PARAMS ((tree)); extern tree signed_or_unsigned_type PARAMS ((int, tree)); extern void fixup_unsigned_type PARAMS ((tree)); extern tree build_pointer_type PARAMS ((tree)); extern tree build_reference_type PARAMS ((tree)); extern tree build_index_type PARAMS ((tree)); extern tree build_index_2_type PARAMS ((tree, tree)); extern tree build_array_type PARAMS ((tree, tree)); extern tree build_function_type PARAMS ((tree, tree)); extern tree build_method_type PARAMS ((tree, tree)); extern tree build_offset_type PARAMS ((tree, tree)); extern tree build_complex_type PARAMS ((tree)); extern tree array_type_nelts PARAMS ((tree)); extern tree value_member PARAMS ((tree, tree)); extern tree purpose_member PARAMS ((tree, tree)); extern tree binfo_member PARAMS ((tree, tree)); extern unsigned int attribute_hash_list PARAMS ((tree)); extern int attribute_list_equal PARAMS ((tree, tree)); extern int attribute_list_contained PARAMS ((tree, tree)); extern int tree_int_cst_equal PARAMS ((tree, tree)); extern int tree_int_cst_lt PARAMS ((tree, tree)); extern int host_integerp PARAMS ((tree, int)); extern HOST_WIDE_INT tree_low_cst PARAMS ((tree, int)); extern int tree_int_cst_msb PARAMS ((tree)); extern int tree_int_cst_sgn PARAMS ((tree)); extern int tree_expr_nonnegative_p PARAMS ((tree)); extern int index_type_equal PARAMS ((tree, tree)); extern tree get_inner_array_type PARAMS ((tree)); /* From expmed.c. Since rtl.h is included after tree.h, we can't put the prototype here. Rtl.h does declare the prototype if tree.h had been included. */ extern tree make_tree PARAMS ((tree, struct rtx_def *)); /* Return a type like TTYPE except that its TYPE_ATTRIBUTES is ATTRIBUTE. Such modified types already made are recorded so that duplicates are not made. */ extern tree build_type_attribute_variant PARAMS ((tree, tree)); extern tree build_decl_attribute_variant PARAMS ((tree, tree)); extern tree merge_machine_decl_attributes PARAMS ((tree, tree)); extern tree merge_machine_type_attributes PARAMS ((tree, tree)); /* Split a list of declspecs and attributes into two. */ extern void split_specs_attrs PARAMS ((tree, tree *, tree *)); /* Strip attributes from a list of combined specs and attrs. */ extern tree strip_attrs PARAMS ((tree)); /* Return 1 if an attribute and its arguments are valid for a decl or type. */ extern int valid_machine_attribute PARAMS ((tree, tree, tree, tree)); /* Given a tree node and a string, return non-zero if the tree node is a valid attribute name for the string. */ extern int is_attribute_p PARAMS ((const char *, tree)); /* Given an attribute name and a list of attributes, return the list element of the attribute or NULL_TREE if not found. */ extern tree lookup_attribute PARAMS ((const char *, tree)); /* Given two attributes lists, return a list of their union. */ extern tree merge_attributes PARAMS ((tree, tree)); /* Given a type node TYPE and a TYPE_QUALIFIER_SET, return a type for the same kind of data as TYPE describes. Variants point to the "main variant" (which has no qualifiers set) via TYPE_MAIN_VARIANT, and it points to a chain of other variants so that duplicate variants are never made. Only main variants should ever appear as types of expressions. */ extern tree build_qualified_type PARAMS ((tree, int)); /* Like build_qualified_type, but only deals with the `const' and `volatile' qualifiers. This interface is retained for backwards compatiblity with the various front-ends; new code should use build_qualified_type instead. */ #define build_type_variant(TYPE, CONST_P, VOLATILE_P) \ build_qualified_type (TYPE, \ ((CONST_P) ? TYPE_QUAL_CONST : 0) \ | ((VOLATILE_P) ? TYPE_QUAL_VOLATILE : 0)) /* Make a copy of a type node. */ extern tree build_type_copy PARAMS ((tree)); /* Given a ..._TYPE node, calculate the TYPE_SIZE, TYPE_SIZE_UNIT, TYPE_ALIGN and TYPE_MODE fields. If called more than once on one node, does nothing except for the first time. */ extern void layout_type PARAMS ((tree)); /* These functions allow a front-end to perform a manual layout of a RECORD_TYPE. (For instance, if the placement of subsequent fields depends on the placement of fields so far.) Begin by calling start_record_layout. Then, call place_field for each of the fields. Then, call finish_record_layout. See layout_type for the default way in which these functions are used. */ typedef struct record_layout_info_s { /* The RECORD_TYPE that we are laying out. */ tree t; /* The offset into the record so far, in bytes, not including bits in BITPOS. */ tree offset; /* The last known alignment of SIZE. */ unsigned int offset_align; /* The bit position within the last OFFSET_ALIGN bits, in bits. */ tree bitpos; /* The alignment of the record so far, in bits. */ unsigned int record_align; /* The alignment of the record so far, not including padding, in bits. */ unsigned int unpacked_align; /* The static variables (i.e., class variables, as opposed to instance variables) encountered in T. */ tree pending_statics; int packed_maybe_necessary; } *record_layout_info; extern record_layout_info start_record_layout PARAMS ((tree)); extern tree bit_from_pos PARAMS ((tree, tree)); extern tree byte_from_pos PARAMS ((tree, tree)); extern void pos_from_byte PARAMS ((tree *, tree *, unsigned int, tree)); extern void pos_from_bit PARAMS ((tree *, tree *, unsigned int, tree)); extern void normalize_offset PARAMS ((tree *, tree *, unsigned int)); extern tree rli_size_unit_so_far PARAMS ((record_layout_info)); extern tree rli_size_so_far PARAMS ((record_layout_info)); extern void normalize_rli PARAMS ((record_layout_info)); extern void place_field PARAMS ((record_layout_info, tree)); extern void compute_record_mode PARAMS ((tree)); extern void finish_record_layout PARAMS ((record_layout_info)); /* Given a hashcode and a ..._TYPE node (for which the hashcode was made), return a canonicalized ..._TYPE node, so that duplicates are not made. How the hash code is computed is up to the caller, as long as any two callers that could hash identical-looking type nodes agree. */ extern tree type_hash_canon PARAMS ((unsigned int, tree)); /* Given a VAR_DECL, PARM_DECL, RESULT_DECL or FIELD_DECL node, calculates the DECL_SIZE, DECL_SIZE_UNIT, DECL_ALIGN and DECL_MODE fields. Call this only once for any given decl node. Second argument is the boundary that this field can be assumed to be starting at (in bits). Zero means it can be assumed aligned on any boundary that may be needed. */ extern void layout_decl PARAMS ((tree, unsigned)); /* Return the mode for data of a given size SIZE and mode class CLASS. If LIMIT is nonzero, then don't use modes bigger than MAX_FIXED_MODE_SIZE. The value is BLKmode if no other mode is found. This is like mode_for_size, but is passed a tree. */ extern enum machine_mode mode_for_size_tree PARAMS ((tree, enum mode_class, int)); /* Return an expr equal to X but certainly not valid as an lvalue. */ extern tree non_lvalue PARAMS ((tree)); extern tree pedantic_non_lvalue PARAMS ((tree)); extern tree convert PARAMS ((tree, tree)); extern unsigned int expr_align PARAMS ((tree)); extern tree size_in_bytes PARAMS ((tree)); extern HOST_WIDE_INT int_size_in_bytes PARAMS ((tree)); extern tree bit_position PARAMS ((tree)); extern HOST_WIDE_INT int_bit_position PARAMS ((tree)); extern tree byte_position PARAMS ((tree)); extern HOST_WIDE_INT int_byte_position PARAMS ((tree)); /* Define data structures, macros, and functions for handling sizes and the various types used to represent sizes. */ enum size_type_kind { SIZETYPE, /* Normal representation of sizes in bytes. */ SSIZETYPE, /* Signed representation of sizes in bytes. */ USIZETYPE, /* Unsigned representation of sizes in bytes. */ BITSIZETYPE, /* Normal representation of sizes in bits. */ SBITSIZETYPE, /* Signed representation of sizes in bits. */ UBITSIZETYPE, /* Unsifgned representation of sizes in bits. */ TYPE_KIND_LAST}; extern tree sizetype_tab[(int) TYPE_KIND_LAST]; #define sizetype sizetype_tab[(int) SIZETYPE] #define bitsizetype sizetype_tab[(int) BITSIZETYPE] #define ssizetype sizetype_tab[(int) SSIZETYPE] #define usizetype sizetype_tab[(int) USIZETYPE] #define sbitsizetype sizetype_tab[(int) SBITSIZETYPE] #define ubitsizetype sizetype_tab[(int) UBITSIZETYPE] extern tree size_binop PARAMS ((enum tree_code, tree, tree)); extern tree size_diffop PARAMS ((tree, tree)); extern tree size_int_wide PARAMS ((HOST_WIDE_INT, enum size_type_kind)); extern tree size_int_type_wide PARAMS ((HOST_WIDE_INT, tree)); #define size_int_type(L, T) size_int_type_wide ((HOST_WIDE_INT) (L), T) #define size_int(L) size_int_wide ((HOST_WIDE_INT) (L), SIZETYPE) #define ssize_int(L) size_int_wide ((HOST_WIDE_INT) (L), SSIZETYPE) #define bitsize_int(L) size_int_wide ((HOST_WIDE_INT) (L), BITSIZETYPE) #define sbitsize_int(L) size_int_wide ((HOST_WIDE_INT) (L), SBITSIZETYPE) extern tree round_up PARAMS ((tree, int)); extern tree round_down PARAMS ((tree, int)); extern tree get_pending_sizes PARAMS ((void)); extern void put_pending_sizes PARAMS ((tree)); /* Type for sizes of data-type. */ #define BITS_PER_UNIT_LOG \ ((BITS_PER_UNIT > 1) + (BITS_PER_UNIT > 2) + (BITS_PER_UNIT > 4) \ + (BITS_PER_UNIT > 8) + (BITS_PER_UNIT > 16) + (BITS_PER_UNIT > 32) \ + (BITS_PER_UNIT > 64) + (BITS_PER_UNIT > 128) + (BITS_PER_UNIT > 256)) /* If nonzero, an upper limit on alignment of structure fields, in bits. */ extern unsigned int maximum_field_alignment; /* If non-zero, the alignment of a bitstring or (power-)set value, in bits. */ extern unsigned int set_alignment; /* Concatenate two lists (chains of TREE_LIST nodes) X and Y by making the last node in X point to Y. Returns X, except if X is 0 returns Y. */ extern tree chainon PARAMS ((tree, tree)); /* Make a new TREE_LIST node from specified PURPOSE, VALUE and CHAIN. */ extern tree tree_cons PARAMS ((tree, tree, tree)); extern tree perm_tree_cons PARAMS ((tree, tree, tree)); extern tree temp_tree_cons PARAMS ((tree, tree, tree)); extern tree saveable_tree_cons PARAMS ((tree, tree, tree)); extern tree decl_tree_cons PARAMS ((tree, tree, tree)); extern tree expr_tree_cons PARAMS ((tree, tree, tree)); /* Return the last tree node in a chain. */ extern tree tree_last PARAMS ((tree)); /* Reverse the order of elements in a chain, and return the new head. */ extern tree nreverse PARAMS ((tree)); /* Returns the length of a chain of nodes (number of chain pointers to follow before reaching a null pointer). */ extern int list_length PARAMS ((tree)); /* Returns the number of FIELD_DECLs in a type. */ extern int fields_length PARAMS ((tree)); /* integer_zerop (tree x) is nonzero if X is an integer constant of value 0 */ extern int integer_zerop PARAMS ((tree)); /* integer_onep (tree x) is nonzero if X is an integer constant of value 1 */ extern int integer_onep PARAMS ((tree)); /* integer_all_onesp (tree x) is nonzero if X is an integer constant all of whose significant bits are 1. */ extern int integer_all_onesp PARAMS ((tree)); /* integer_pow2p (tree x) is nonzero is X is an integer constant with exactly one bit 1. */ extern int integer_pow2p PARAMS ((tree)); /* staticp (tree x) is nonzero if X is a reference to data allocated at a fixed address in memory. */ extern int staticp PARAMS ((tree)); /* Gets an error if argument X is not an lvalue. Also returns 1 if X is an lvalue, 0 if not. */ extern int lvalue_or_else PARAMS ((tree, const char *)); /* save_expr (EXP) returns an expression equivalent to EXP but it can be used multiple times within context CTX and only evaluate EXP once. */ extern tree save_expr PARAMS ((tree)); /* Returns the index of the first non-tree operand for CODE, or the number of operands if all are trees. */ extern int first_rtl_op PARAMS ((enum tree_code)); /* unsave_expr (EXP) returns an expression equivalent to EXP but it can be used multiple times and will evaluate EXP in its entirety each time. */ extern tree unsave_expr PARAMS ((tree)); /* Reset EXP in place so that it can be expaned again. Does not recurse into subtrees. */ extern void unsave_expr_1 PARAMS ((tree)); /* Like unsave_expr_1, but recurses into all subtrees. */ extern tree unsave_expr_now PARAMS ((tree)); /* If non-null, these are language-specific helper functions for unsave_expr_now. If present, LANG_UNSAVE is called before its argument (an UNSAVE_EXPR) is to be unsaved, and all other processing in unsave_expr_now is aborted. LANG_UNSAVE_EXPR_NOW is called from unsave_expr_1 for language-specific tree codes. */ extern void (*lang_unsave) PARAMS ((tree *)); extern void (*lang_unsave_expr_now) PARAMS ((tree)); /* Return 0 if it is safe to evaluate EXPR multiple times, return 1 if it is safe if EXPR is unsaved afterward, or return 2 if it is completely unsafe. */ extern int unsafe_for_reeval PARAMS ((tree)); /* Return 1 if EXP contains a PLACEHOLDER_EXPR; i.e., if it represents a size or offset that depends on a field within a record. Note that we only allow such expressions within simple arithmetic or a COND_EXPR. */ extern int contains_placeholder_p PARAMS ((tree)); /* Return 1 if EXP contains any expressions that produce cleanups for an outer scope to deal with. Used by fold. */ extern int has_cleanups PARAMS ((tree)); /* Given a tree EXP, a FIELD_DECL F, and a replacement value R, return a tree with all occurrences of references to F in a PLACEHOLDER_EXPR replaced by R. Note that we assume here that EXP contains only arithmetic expressions. */ extern tree substitute_in_expr PARAMS ((tree, tree, tree)); /* variable_size (EXP) is like save_expr (EXP) except that it is for the special case of something that is part of a variable size for a data type. It makes special arrangements to compute the value at the right time when the data type belongs to a function parameter. */ extern tree variable_size PARAMS ((tree)); /* stabilize_reference (EXP) returns an reference equivalent to EXP but it can be used multiple times and only evaluate the subexpressions once. */ extern tree stabilize_reference PARAMS ((tree)); /* Subroutine of stabilize_reference; this is called for subtrees of references. Any expression with side-effects must be put in a SAVE_EXPR to ensure that it is only evaluated once. */ extern tree stabilize_reference_1 PARAMS ((tree)); /* Return EXP, stripped of any conversions to wider types in such a way that the result of converting to type FOR_TYPE is the same as if EXP were converted to FOR_TYPE. If FOR_TYPE is 0, it signifies EXP's type. */ extern tree get_unwidened PARAMS ((tree, tree)); /* Return OP or a simpler expression for a narrower value which can be sign-extended or zero-extended to give back OP. Store in *UNSIGNEDP_PTR either 1 if the value should be zero-extended or 0 if the value should be sign-extended. */ extern tree get_narrower PARAMS ((tree, int *)); /* Given MODE and UNSIGNEDP, return a suitable type-tree with that mode. The definition of this resides in language-specific code as the repertoire of available types may vary. */ extern tree type_for_mode PARAMS ((enum machine_mode, int)); /* Given PRECISION and UNSIGNEDP, return a suitable type-tree for an integer type with at least that precision. The definition of this resides in language-specific code as the repertoire of available types may vary. */ extern tree type_for_size PARAMS ((unsigned, int)); /* Given an integer type T, return a type like T but unsigned. If T is unsigned, the value is T. The definition of this resides in language-specific code as the repertoire of available types may vary. */ extern tree unsigned_type PARAMS ((tree)); /* Given an integer type T, return a type like T but signed. If T is signed, the value is T. The definition of this resides in language-specific code as the repertoire of available types may vary. */ extern tree signed_type PARAMS ((tree)); /* This function must be defined in the language-specific files. expand_expr calls it to build the cleanup-expression for a TARGET_EXPR. This is defined in a language-specific file. */ extern tree maybe_build_cleanup PARAMS ((tree)); /* Given an expression EXP that may be a COMPONENT_REF or an ARRAY_REF, look for nested component-refs or array-refs at constant positions and find the ultimate containing object, which is returned. */ extern tree get_inner_reference PARAMS ((tree, HOST_WIDE_INT *, HOST_WIDE_INT *, tree *, enum machine_mode *, int *, int *, unsigned int *)); /* Given a DECL or TYPE, return the scope in which it was declared, or NUL_TREE if there is no containing scope. */ extern tree get_containing_scope PARAMS ((tree)); /* Return the FUNCTION_DECL which provides this _DECL with its context, or zero if none. */ extern tree decl_function_context PARAMS ((tree)); /* Return the RECORD_TYPE, UNION_TYPE, or QUAL_UNION_TYPE which provides this _DECL with its context, or zero if none. */ extern tree decl_type_context PARAMS ((tree)); /* Given the FUNCTION_DECL for the current function, return zero if it is ok for this function to be inline. Otherwise return a warning message with a single %s for the function's name. */ extern const char *function_cannot_inline_p PARAMS ((tree)); /* Return 1 if EXPR is the real constant zero. */ extern int real_zerop PARAMS ((tree)); /* Declare commonly used variables for tree structure. */ /* Points to the name of the input file from which the current input being parsed originally came (before it went into cpp). */ extern const char *input_filename; /* Current line number in input file. */ extern int lineno; /* Nonzero for -pedantic switch: warn about anything that standard C forbids. */ extern int pedantic; /* Nonzero means lvalues are limited to those valid in pedantic ANSI C. Zero means allow extended lvalues. */ extern int pedantic_lvalues; /* Nonzero means can safely call expand_expr now; otherwise layout_type puts variable sizes onto `pending_sizes' instead. */ extern int immediate_size_expand; /* Points to the FUNCTION_DECL of the function whose body we are reading. */ extern tree current_function_decl; /* Nonzero means a FUNC_BEGIN label was emitted. */ extern tree current_function_func_begin_label; /* Nonzero means all ..._TYPE nodes should be allocated permanently. */ extern int all_types_permanent; /* Pointer to function to compute the name to use to print a declaration. DECL is the declaration in question. VERBOSITY determines what information will be printed: 0: DECL_NAME, demangled as necessary. 1: and scope information. 2: and any other information that might be interesting, such as function parameter types in C++. */ extern const char *(*decl_printable_name) PARAMS ((tree, int)); /* Pointer to function to finish handling an incomplete decl at the end of compilation. */ extern void (*incomplete_decl_finalize_hook) PARAMS ((tree)); extern const char *init_parse PARAMS ((const char *)); extern void finish_parse PARAMS ((void)); extern const char * const language_string; /* Declare a predefined function. Return the declaration. This function is provided by each language frontend. */ extern tree builtin_function PARAMS ((const char *, tree, int, enum built_in_class, const char *)); /* In tree.c */ extern char *perm_calloc PARAMS ((int, long)); extern tree get_file_function_name PARAMS ((int)); extern tree get_file_function_name_long PARAMS ((const char *)); extern tree get_set_constructor_bits PARAMS ((tree, char *, int)); extern tree get_set_constructor_bytes PARAMS ((tree, unsigned char *, int)); extern tree get_callee_fndecl PARAMS ((tree)); /* In stmt.c */ extern int in_control_zone_p PARAMS ((void)); extern void expand_fixups PARAMS ((struct rtx_def *)); extern tree expand_start_stmt_expr PARAMS ((void)); extern tree expand_end_stmt_expr PARAMS ((tree)); extern void expand_expr_stmt PARAMS ((tree)); extern int warn_if_unused_value PARAMS ((tree)); extern void expand_decl_init PARAMS ((tree)); extern void clear_last_expr PARAMS ((void)); extern void expand_label PARAMS ((tree)); extern void expand_goto PARAMS ((tree)); extern void expand_asm PARAMS ((tree)); extern void expand_start_cond PARAMS ((tree, int)); extern void expand_end_cond PARAMS ((void)); extern void expand_start_else PARAMS ((void)); extern void expand_start_elseif PARAMS ((tree)); extern struct nesting *expand_start_loop PARAMS ((int)); extern struct nesting *expand_start_loop_continue_elsewhere PARAMS ((int)); extern void expand_loop_continue_here PARAMS ((void)); extern void expand_end_loop PARAMS ((void)); extern int expand_continue_loop PARAMS ((struct nesting *)); extern int expand_exit_loop PARAMS ((struct nesting *)); extern int expand_exit_loop_if_false PARAMS ((struct nesting *, tree)); extern int expand_exit_something PARAMS ((void)); extern void expand_null_return PARAMS ((void)); extern void expand_return PARAMS ((tree)); extern int optimize_tail_recursion PARAMS ((tree, struct rtx_def *)); extern void expand_start_bindings_and_block PARAMS ((int, tree)); #define expand_start_bindings(flags) \ expand_start_bindings_and_block(flags, NULL_TREE) extern void expand_end_bindings PARAMS ((tree, int, int)); extern void warn_about_unused_variables PARAMS ((tree)); extern void start_cleanup_deferral PARAMS ((void)); extern void end_cleanup_deferral PARAMS ((void)); extern int is_body_block PARAMS ((tree)); extern void mark_block_as_eh_region PARAMS ((void)); extern void mark_block_as_not_eh_region PARAMS ((void)); extern int is_eh_region PARAMS ((void)); extern int conditional_context PARAMS ((void)); extern tree last_cleanup_this_contour PARAMS ((void)); extern int expand_dhc_cleanup PARAMS ((tree)); extern int expand_dcc_cleanup PARAMS ((tree)); extern void expand_start_case PARAMS ((int, tree, tree, const char *)); extern void expand_end_case PARAMS ((tree)); extern int pushcase PARAMS ((tree, tree (*) (tree, tree), tree, tree *)); extern int pushcase_range PARAMS ((tree, tree, tree (*) (tree, tree), tree, tree *)); extern void using_eh_for_cleanups PARAMS ((void)); extern int stmt_loop_nest_empty PARAMS ((void)); /* In fold-const.c */ /* Fold constants as much as possible in an expression. Returns the simplified expression. Acts only on the top level of the expression; if the argument itself cannot be simplified, its subexpressions are not changed. */ extern tree fold PARAMS ((tree)); extern int force_fit_type PARAMS ((tree, int)); extern int add_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *)); extern int neg_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *)); extern int mul_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *)); extern void lshift_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, HOST_WIDE_INT, unsigned int, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *, int)); extern void rshift_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, HOST_WIDE_INT, unsigned int, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *, int)); extern void lrotate_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, HOST_WIDE_INT, unsigned int, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *)); extern void rrotate_double PARAMS ((unsigned HOST_WIDE_INT, HOST_WIDE_INT, HOST_WIDE_INT, unsigned int, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *)); extern int operand_equal_p PARAMS ((tree, tree, int)); extern tree invert_truthvalue PARAMS ((tree)); /* In builtins.c. Given a type, apply default promotions wrt unnamed function arguments and return the new type. Return NULL_TREE if no change. Required by any language that supports variadic arguments. */ extern tree (*lang_type_promotes_to) PARAMS ((tree)); /* Interface of the DWARF2 unwind info support. */ /* Decide whether we want to emit frame unwind information for the current translation unit. */ extern int dwarf2out_do_frame PARAMS ((void)); /* Generate a new label for the CFI info to refer to. */ extern char *dwarf2out_cfi_label PARAMS ((void)); /* Entry point to update the canonical frame address (CFA). */ extern void dwarf2out_def_cfa PARAMS ((const char *, unsigned, long)); /* Add the CFI for saving a register window. */ extern void dwarf2out_window_save PARAMS ((const char *)); /* Add a CFI to update the running total of the size of arguments pushed onto the stack. */ extern void dwarf2out_args_size PARAMS ((const char *, long)); /* Entry point for saving a register to the stack. */ extern void dwarf2out_reg_save PARAMS ((const char *, unsigned, long)); /* Entry point for saving the return address in the stack. */ extern void dwarf2out_return_save PARAMS ((const char *, long)); /* Entry point for saving the return address in a register. */ extern void dwarf2out_return_reg PARAMS ((const char *, unsigned)); /* Output a marker (i.e. a label) for the beginning of a function, before the prologue. */ extern void dwarf2out_begin_prologue PARAMS ((void)); /* Output a marker (i.e. a label) for the absolute end of the generated code for a function definition. */ extern void dwarf2out_end_epilogue PARAMS ((void)); /* The language front-end must define these functions. */ /* Function of no arguments for initializing options. */ extern void lang_init_options PARAMS ((void)); /* Function of no arguments for initializing lexical scanning. */ extern void init_lex PARAMS ((void)); /* Function of no arguments for initializing the symbol table. */ extern void init_decl_processing PARAMS ((void)); /* Functions called with no arguments at the beginning and end or processing the input source file. */ extern void lang_init PARAMS ((void)); extern void lang_finish PARAMS ((void)); /* Function to identify which front-end produced the output file. */ extern const char *lang_identify PARAMS ((void)); /* Called by report_error_function to print out function name. * Default may be overridden by language front-ends. */ extern void (*print_error_function) PARAMS ((const char *)); /* Function to replace the DECL_LANG_SPECIFIC field of a DECL with a copy. */ extern void copy_lang_decl PARAMS ((tree)); /* Function called with no arguments to parse and compile the input. */ extern int yyparse PARAMS ((void)); /* Function called with option as argument to decode options starting with -f or -W or +. It should return nonzero if it handles the option. */ extern int lang_decode_option PARAMS ((int, char **)); /* Functions for processing symbol declarations. */ /* Function to enter a new lexical scope. Takes one argument: always zero when called from outside the front end. */ extern void pushlevel PARAMS ((int)); /* Function to exit a lexical scope. It returns a BINDING for that scope. Takes three arguments: KEEP -- nonzero if there were declarations in this scope. REVERSE -- reverse the order of decls before returning them. FUNCTIONBODY -- nonzero if this level is the body of a function. */ extern tree poplevel PARAMS ((int, int, int)); /* Set the BLOCK node for the current scope level. */ extern void set_block PARAMS ((tree)); /* Function to add a decl to the current scope level. Takes one argument, a decl to add. Returns that decl, or, if the same symbol is already declared, may return a different decl for that name. */ extern tree pushdecl PARAMS ((tree)); /* Function to return the chain of decls so far in the current scope level. */ extern tree getdecls PARAMS ((void)); /* Function to return the chain of structure tags in the current scope level. */ extern tree gettags PARAMS ((void)); extern tree build_range_type PARAMS ((tree, tree, tree)); /* Call when starting to parse a declaration: make expressions in the declaration last the length of the function. Returns an argument that should be passed to resume_momentary later. */ extern int suspend_momentary PARAMS ((void)); extern int allocation_temporary_p PARAMS ((void)); /* Call when finished parsing a declaration: restore the treatment of node-allocation that was in effect before the suspension. YES should be the value previously returned by suspend_momentary. */ extern void resume_momentary PARAMS ((int)); /* Called after finishing a record, union or enumeral type. */ extern void rest_of_type_compilation PARAMS ((tree, int)); /* Save the current set of obstacks, but don't change them. */ extern void push_obstacks_nochange PARAMS ((void)); extern void permanent_allocation PARAMS ((int)); extern void push_momentary PARAMS ((void)); extern void clear_momentary PARAMS ((void)); extern void pop_momentary PARAMS ((void)); extern void end_temporary_allocation PARAMS ((void)); /* Pop the obstack selection stack. */ extern void pop_obstacks PARAMS ((void)); /* In alias.c */ void record_component_aliases PARAMS ((tree)); /* In tree.c */ extern int really_constant_p PARAMS ((tree)); extern void push_obstacks PARAMS ((struct obstack *, struct obstack *)); extern void pop_momentary_nofree PARAMS ((void)); extern void preserve_momentary PARAMS ((void)); extern void saveable_allocation PARAMS ((void)); extern void temporary_allocation PARAMS ((void)); extern void resume_temporary_allocation PARAMS ((void)); extern tree get_file_function_name PARAMS ((int)); extern void set_identifier_size PARAMS ((int)); extern int int_fits_type_p PARAMS ((tree, tree)); extern int tree_log2 PARAMS ((tree)); extern int tree_floor_log2 PARAMS ((tree)); extern void preserve_initializer PARAMS ((void)); extern void preserve_data PARAMS ((void)); extern int object_permanent_p PARAMS ((tree)); extern int type_precision PARAMS ((tree)); extern int simple_cst_equal PARAMS ((tree, tree)); extern int compare_tree_int PARAMS ((tree, unsigned int)); extern int type_list_equal PARAMS ((tree, tree)); extern int chain_member PARAMS ((tree, tree)); extern int chain_member_purpose PARAMS ((tree, tree)); extern int chain_member_value PARAMS ((tree, tree)); extern tree listify PARAMS ((tree)); extern tree type_hash_lookup PARAMS ((unsigned int, tree)); extern void type_hash_add PARAMS ((unsigned int, tree)); extern unsigned int type_hash_list PARAMS ((tree)); extern int simple_cst_list_equal PARAMS ((tree, tree)); extern void debug_obstack PARAMS ((char *)); extern void rtl_in_current_obstack PARAMS ((void)); extern void rtl_in_saveable_obstack PARAMS ((void)); extern void init_tree_codes PARAMS ((void)); extern void dump_tree_statistics PARAMS ((void)); extern void print_obstack_statistics PARAMS ((const char *, struct obstack *)); #ifdef BUFSIZ extern void print_obstack_name PARAMS ((char *, FILE *, const char *)); #endif extern void expand_function_end PARAMS ((const char *, int, int)); extern void expand_function_start PARAMS ((tree, int)); extern int real_onep PARAMS ((tree)); extern int real_twop PARAMS ((tree)); extern void start_identifier_warnings PARAMS ((void)); extern void gcc_obstack_init PARAMS ((struct obstack *)); extern void init_obstacks PARAMS ((void)); extern void obfree PARAMS ((char *)); extern void build_common_tree_nodes PARAMS ((int)); extern void build_common_tree_nodes_2 PARAMS ((int)); /* In function.c */ extern void setjmp_protect_args PARAMS ((void)); extern void setjmp_protect PARAMS ((tree)); extern void expand_main_function PARAMS ((void)); extern void mark_varargs PARAMS ((void)); extern void init_dummy_function_start PARAMS ((void)); extern void expand_dummy_function_end PARAMS ((void)); extern void init_function_for_compilation PARAMS ((void)); extern void init_function_start PARAMS ((tree, const char *, int)); extern void assign_parms PARAMS ((tree)); extern void put_var_into_stack PARAMS ((tree)); extern void flush_addressof PARAMS ((tree)); extern void uninitialized_vars_warning PARAMS ((tree)); extern void setjmp_args_warning PARAMS ((void)); extern void mark_all_temps_used PARAMS ((void)); extern void init_temp_slots PARAMS ((void)); extern void combine_temp_slots PARAMS ((void)); extern void free_temp_slots PARAMS ((void)); extern void pop_temp_slots PARAMS ((void)); extern void push_temp_slots PARAMS ((void)); extern void preserve_temp_slots PARAMS ((struct rtx_def *)); extern void preserve_rtl_expr_temps PARAMS ((tree)); extern int aggregate_value_p PARAMS ((tree)); extern void free_temps_for_rtl_expr PARAMS ((tree)); extern void instantiate_virtual_regs PARAMS ((tree, struct rtx_def *)); extern void unshare_all_rtl PARAMS ((tree, struct rtx_def *)); extern int max_parm_reg_num PARAMS ((void)); extern void push_function_context PARAMS ((void)); extern void pop_function_context PARAMS ((void)); extern void push_function_context_to PARAMS ((tree)); extern void pop_function_context_from PARAMS ((tree)); /* In print-rtl.c */ #ifdef BUFSIZ extern void print_rtl PARAMS ((FILE *, struct rtx_def *)); #endif /* In print-tree.c */ extern void debug_tree PARAMS ((tree)); extern void debug_tree_limit PARAMS ((tree, int)); #ifdef BUFSIZ extern void print_node PARAMS ((FILE *, const char *, tree, int)); extern void print_node_brief PARAMS ((FILE *, const char *, tree, int)); extern void indent_to PARAMS ((FILE *, int)); #endif /* In expr.c */ extern void emit_queue PARAMS ((void)); extern int apply_args_register_offset PARAMS ((int)); extern struct rtx_def *expand_builtin_return_addr PARAMS ((enum built_in_function, int, struct rtx_def *)); extern void do_pending_stack_adjust PARAMS ((void)); extern struct rtx_def *expand_assignment PARAMS ((tree, tree, int, int)); extern struct rtx_def *store_expr PARAMS ((tree, struct rtx_def *, int)); extern void check_max_integer_computation_mode PARAMS ((tree)); /* In emit-rtl.c */ extern void start_sequence_for_rtl_expr PARAMS ((tree)); extern struct rtx_def *emit_line_note_after PARAMS ((const char *, int, struct rtx_def *)); extern struct rtx_def *emit_line_note PARAMS ((const char *, int)); extern struct rtx_def *emit_line_note_force PARAMS ((const char *, int)); /* In calls.c */ extern int setjmp_call_p PARAMS ((tree)); /* In front end. */ extern int mark_addressable PARAMS ((tree)); extern void incomplete_type_error PARAMS ((tree, tree)); extern void print_lang_statistics PARAMS ((void)); extern tree truthvalue_conversion PARAMS ((tree)); extern void split_specs_attrs PARAMS ((tree, tree *, tree *)); #ifdef BUFSIZ extern void print_lang_decl PARAMS ((FILE *, tree, int)); extern void print_lang_type PARAMS ((FILE *, tree, int)); extern void print_lang_identifier PARAMS ((FILE *, tree, int)); #endif extern int global_bindings_p PARAMS ((void)); extern void insert_block PARAMS ((tree)); /* In integrate.c */ extern void save_for_inline_nocopy PARAMS ((tree)); extern void save_for_inline_copying PARAMS ((tree)); extern void set_decl_abstract_flags PARAMS ((tree, int)); extern void output_inline_function PARAMS ((tree)); extern void set_decl_origin_self PARAMS ((tree)); /* In front end. */ extern void set_yydebug PARAMS ((int)); /* In stor-layout.c */ extern void fixup_signed_type PARAMS ((tree)); /* varasm.c */ extern void make_decl_rtl PARAMS ((tree, const char *, int)); extern void make_decl_one_only PARAMS ((tree)); extern int supports_one_only PARAMS ((void)); extern void variable_section PARAMS ((tree, int)); /* In fold-const.c */ extern int div_and_round_double PARAMS ((enum tree_code, int, unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT, HOST_WIDE_INT, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *, unsigned HOST_WIDE_INT *, HOST_WIDE_INT *)); /* In stmt.c */ extern void emit_nop PARAMS ((void)); extern void expand_computed_goto PARAMS ((tree)); extern struct rtx_def *label_rtx PARAMS ((tree)); extern void expand_asm_operands PARAMS ((tree, tree, tree, tree, int, const char *, int)); extern int any_pending_cleanups PARAMS ((int)); extern void init_stmt PARAMS ((void)); extern void init_stmt_for_function PARAMS ((void)); extern int drop_through_at_end_p PARAMS ((void)); extern void expand_start_target_temps PARAMS ((void)); extern void expand_end_target_temps PARAMS ((void)); extern void expand_elseif PARAMS ((tree)); extern void expand_decl PARAMS ((tree)); extern int expand_decl_cleanup PARAMS ((tree, tree)); extern void expand_anon_union_decl PARAMS ((tree, tree, tree)); extern void move_cleanups_up PARAMS ((void)); extern void expand_start_case_dummy PARAMS ((void)); extern void expand_end_case_dummy PARAMS ((void)); extern tree case_index_expr_type PARAMS ((void)); extern HOST_WIDE_INT all_cases_count PARAMS ((tree, int *)); extern void check_for_full_enumeration_handling PARAMS ((tree)); extern void declare_nonlocal_label PARAMS ((tree)); #ifdef BUFSIZ extern void lang_print_xnode PARAMS ((FILE *, tree, int)); #endif /* If KIND=='I', return a suitable global initializer (constructor) name. If KIND=='D', return a suitable global clean-up (destructor) name. */ extern tree get_file_function_name PARAMS ((int)); /* Interface of the DWARF2 unwind info support. */ /* Decide whether we want to emit frame unwind information for the current translation unit. */ extern int dwarf2out_do_frame PARAMS ((void)); /* Generate a new label for the CFI info to refer to. */ extern char *dwarf2out_cfi_label PARAMS ((void)); /* Entry point to update the canonical frame address (CFA). */ extern void dwarf2out_def_cfa PARAMS ((const char *, unsigned, long)); /* Add the CFI for saving a register window. */ extern void dwarf2out_window_save PARAMS ((const char *)); /* Add a CFI to update the running total of the size of arguments pushed onto the stack. */ extern void dwarf2out_args_size PARAMS ((const char *, long)); /* Entry point for saving a register to the stack. */ extern void dwarf2out_reg_save PARAMS ((const char *, unsigned, long)); /* Entry point for saving the return address in the stack. */ extern void dwarf2out_return_save PARAMS ((const char *, long)); /* Entry point for saving the return address in a register. */ extern void dwarf2out_return_reg PARAMS ((const char *, unsigned)); /* Output a marker (i.e. a label) for the beginning of a function, before the prologue. */ extern void dwarf2out_begin_prologue PARAMS ((void)); /* Output a marker (i.e. a label) for the absolute end of the generated code for a function definition. */ extern void dwarf2out_end_epilogue PARAMS ((void)); /* Redefine abort to report an internal error w/o coredump, and reporting the location of the error in the source file. This logic is duplicated in rtl.h and tree.h because every file that needs the special abort includes one or both. toplev.h gets too few files, system.h gets too many. */ extern void fancy_abort PARAMS ((const char *, int, const char *)) ATTRIBUTE_NORETURN; #if (GCC_VERSION >= 2007) #define abort() fancy_abort (__FILE__, __LINE__, __PRETTY_FUNCTION__) #else #define abort() fancy_abort (__FILE__, __LINE__, 0) #endif typedef struct linked_list LINKED_LIST; typedef struct pragma_info PRAGMA_INFO; extern LINKED_LIST *new_pragmas; /* new pragmas since last statement */ extern LINKED_LIST *file_pragmas; /* all file pragmas associated with next stmt */ struct linked_list { void *data; LINKED_LIST *next; }; extern void linked_list_push (LINKED_LIST **lla, void *data); extern void *linked_list_pop (LINKED_LIST **lla); extern void linked_list_remove_el (LINKED_LIST **lla); /* pragma_info structure: #pragma name([id[,arg1[,arg2]]]) decl points to the declaration statement of id */ struct pragma_info { char *name; char *id; tree decl; int arg1; int arg2; tree next_stmt; }; extern PRAGMA_INFO *new_pragma_info (); extern void delete_pragma_info (PRAGMA_INFO *pi); extern void pragma_list_push (LINKED_LIST **lla, PRAGMA_INFO *pi); extern PRAGMA_INFO *pragma_list_pop (LINKED_LIST **lla); extern void pragma_list_remove_el (LINKED_LIST **lla);
qiyao/xcc
g++fe/gnu/tree.h
C
gpl-2.0
121,863
/* linux/arch/arm/mach-s5pv310/bootmem-smdkv310.c * * Copyright (c) 2009 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * Bootmem helper functions for smdkv310 * * 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. */ #include <linux/mm.h> #include <linux/bootmem.h> #include <linux/swap.h> #include <asm/setup.h> #include <linux/io.h> #include <mach/memory.h> #include <plat/media.h> #include <mach/media.h> struct s5p_media_device media_devs[] = { #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMD { .id = S5P_MDEV_FIMD, .name = "fimd", .bank = 1, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMD * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_S5P_PMEM_MEMSIZE_PMEM { .id = S5P_MDEV_PMEM, .name = "pmem", .bank = 1, .memsize = CONFIG_S5P_PMEM_MEMSIZE_PMEM * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC0 { .id = S5P_MDEV_FIMC0, .name = "fimc0", .bank = 1, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC0 * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC1 { .id = S5P_MDEV_FIMC1, .name = "fimc1", .bank = 1, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC1 * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC2 { .id = S5P_MDEV_FIMC2, .name = "fimc2", .bank = 1, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC2 * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC3 { .id = S5P_MDEV_FIMC3, .name = "fimc3", .bank = 1, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_FIMC3 * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_JPEG { .id = S5P_MDEV_JPEG, .name = "jpeg", .bank = 0, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_JPEG * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC { .id = S5P_MDEV_MFC, .name = "mfc", .bank = 0, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC0 { .id = S5P_MDEV_MFC, .name = "mfc", .bank = 0, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC0 * SZ_1K, .paddr = 0, }, #endif #ifdef CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC1 { .id = S5P_MDEV_MFC, .name = "mfc", .bank = 1, .memsize = CONFIG_VIDEO_SAMSUNG_MEMSIZE_MFC1 * SZ_1K, .paddr = 0, }, #endif }; int nr_media_devs = (sizeof(media_devs) / sizeof(media_devs[0]));
danguria/linux-kernel-study
arch/arm/mach-s5pv310/bootmem-smdkv310.c
C
gpl-2.0
2,892
/* * Copyright (C) 2010 Pengutronix * Uwe Kleine-Koenig <u.kleine-koenig@pengutronix.de> * * 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. */ #include <linux/dma-mapping.h> #include <mach-imx/hardware.h> #include <mach-imx/devices-common.h> #define imx_mxc_mmc_data_entry_single(soc, _id, _hwid, _size) \ { \ .id = _id, \ .iobase = soc ## _SDHC ## _hwid ## _BASE_ADDR, \ .iosize = _size, \ .irq = soc ## _INT_SDHC ## _hwid, \ .dmareq = soc ## _DMA_REQ_SDHC ## _hwid, \ } #define imx_mxc_mmc_data_entry(soc, _id, _hwid, _size) \ [_id] = imx_mxc_mmc_data_entry_single(soc, _id, _hwid, _size) #ifdef CONFIG_SOC_IMX21 const struct imx_mxc_mmc_data imx21_mxc_mmc_data[] __initconst = { #define imx21_mxc_mmc_data_entry(_id, _hwid) \ imx_mxc_mmc_data_entry(MX21, _id, _hwid, SZ_4K) imx21_mxc_mmc_data_entry(0, 1), imx21_mxc_mmc_data_entry(1, 2), }; #endif /* ifdef CONFIG_SOC_IMX21 */ #ifdef CONFIG_SOC_IMX27 const struct imx_mxc_mmc_data imx27_mxc_mmc_data[] __initconst = { #define imx27_mxc_mmc_data_entry(_id, _hwid) \ imx_mxc_mmc_data_entry(MX27, _id, _hwid, SZ_4K) imx27_mxc_mmc_data_entry(0, 1), imx27_mxc_mmc_data_entry(1, 2), }; #endif /* ifdef CONFIG_SOC_IMX27 */ #ifdef CONFIG_SOC_IMX31 const struct imx_mxc_mmc_data imx31_mxc_mmc_data[] __initconst = { #define imx31_mxc_mmc_data_entry(_id, _hwid) \ imx_mxc_mmc_data_entry(MX31, _id, _hwid, SZ_16K) imx31_mxc_mmc_data_entry(0, 1), imx31_mxc_mmc_data_entry(1, 2), }; #endif /* ifdef CONFIG_SOC_IMX31 */ struct platform_device *__init imx_add_mxc_mmc( const struct imx_mxc_mmc_data *data, const struct imxmmc_platform_data *pdata) { struct resource res[] = { { .start = data->iobase, .end = data->iobase + SZ_4K - 1, .flags = IORESOURCE_MEM, }, { .start = data->irq, .end = data->irq, .flags = IORESOURCE_IRQ, }, { .start = data->dmareq, .end = data->dmareq, .flags = IORESOURCE_DMA, }, }; return imx_add_platform_device_dmamask("mxc-mmc", data->id, res, ARRAY_SIZE(res), pdata, sizeof(*pdata), DMA_BIT_MASK(32)); }
patrikryd/kernel
arch/arm/plat-mxc/devices/platform-mxc-mmc.c
C
gpl-2.0
2,220
using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("SharpUtility.BackgroundWorker.PCL")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("SharpUtility.BackgroundWorker.PCL")] [assembly: AssemblyCopyright("Copyright © 2014")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: NeutralResourcesLanguage("en")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
Knight1988/SharpUtility
tests/BackgroundWorker/SharpUtility.BackgroundWorker.PCL/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,124
package com.yzmoney.common.service.impl; import com.yzmoney.common.constant.PropertyUtils; import com.yzmoney.common.service.SaveQrcodeLogService; import com.yzmoney.common.util.HttpClientUtil; import com.yzmoney.common.util.JDKStackTrace; import com.yzmoney.common.util.JsonUtils; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import java.util.HashMap; import java.util.Map; /** * 保存二维码信息 * */ @Service public class SaveQrcodeLogServiceImpl implements SaveQrcodeLogService{ private static Logger logger = Logger.getLogger(SaveQrcodeLogServiceImpl.class); private String saveQrcodeInfoUrl = PropertyUtils.getValue("add_qrcode_info",""); private boolean sendHttp(String url,Map param){ logger.info("远程保存二维码信息开始,param:" + JsonUtils.toJson(param)+",sendHttp--url:"+ url); if(StringUtils.isNotEmpty(url)){ try { String result = HttpClientUtil.get(url, param, null); if(result!=null){ JSONObject object = JSONObject.fromObject(result); if(object != null && object.getInt("code") == 0){ logger.info("远程保存二维码信息成功,param:" + JsonUtils.toJson(param)+",sendHttp--url:"+ url + ",result:"+result); return true; }else{ logger.info("远程保存二维码信息失败,param:" + JsonUtils.toJson(param)+",sendHttp--url:"+ url + ",result:"+result); } } } catch (Exception e) { logger.info("远程保存二维码信息异常,param:" + JsonUtils.toJson(param)+",sendHttp--url:"+ url + JDKStackTrace.getJDKStrack(e)); return false; } } return false; } @Override public void saveQrcodeInfo(final Map param) { new Thread(new Runnable() { @Override public void run() { sendHttp(saveQrcodeInfoUrl,param); } }).start(); } }
xinbaojian/wechat
src/com/yzmoney/common/service/impl/SaveQrcodeLogServiceImpl.java
Java
gpl-2.0
2,234
#!/usr/bin/env python from distutils.core import setup from DistUtilsExtra.command import * import glob import os setup(name='unattended-upgrades', version='0.1', scripts=['unattended-upgrade'], data_files=[ ('../etc/apt/apt.conf.d/', ["data/50unattended-upgrades"]), ('../etc/logrotate.d/', ["data/logrotate.d/unattended-upgrades"]), ('../usr/share/unattended-upgrades/', ["data/20auto-upgrades", "data/20auto-upgrades-disabled", "unattended-upgrade-shutdown"]), ('../usr/share/man/man8/', ["man/unattended-upgrade.8"]), ('../etc/pm/sleep.d/', ["pm/sleep.d/10_unattended-upgrades-hibernate"]) ], cmdclass = { "build" : build_extra.build_extra, "build_i18n" : build_i18n.build_i18n } )
Jimdo/unattended-upgrades
setup.py
Python
gpl-2.0
968
/*! \file \brief Declaration of library functions Any definitions in this file will be shared among GLUE Layer and internal Driver Stack. */ /******************************************************************************* * C O M P I L E R F L A G S ******************************************************************************** */ /******************************************************************************* * M A C R O S ******************************************************************************** */ #ifdef DFT_TAG #undef DFT_TAG #endif #define DFT_TAG "[WMT-CONSYS-HW]" /******************************************************************************* * E X T E R N A L R E F E R E N C E S ******************************************************************************** */ #include <mach/upmu_common.h> #include "mtk_wcn_consys_hw.h" #include <mach/mt_clkmgr.h> #include <mach/emi_mpu.h> #if CONSYS_PMIC_CTRL_ENABLE #include <mach/mt_pm_ldo.h> #endif #include <mach/mtk_hibernate_dpm.h> #include <asm/memblock.h> /******************************************************************************* * C O N S T A N T S ******************************************************************************** */ /******************************************************************************* * D A T A T Y P E S ******************************************************************************** */ /******************************************************************************* * P U B L I C D A T A ******************************************************************************** */ UINT8 __iomem *pEmibaseaddr = NULL; phys_addr_t gConEmiPhyBase; /******************************************************************************* * P R I V A T E D A T A ******************************************************************************** */ /******************************************************************************* * F U N C T I O N D E C L A R A T I O N S ******************************************************************************** */ extern unsigned int get_CONNSYS_start (void); extern unsigned int get_CONNSYS_size (void); /******************************************************************************* * F U N C T I O N S ******************************************************************************** */ #if CONSYS_ENALBE_SET_JTAG UINT32 gJtagCtrl = 0; #define JTAG_ADDR1_BASE 0x10208000 #define JTAG_ADDR2_BASE 0x10005300 char *jtag_addr1 = (char *)JTAG_ADDR1_BASE; char *jtag_addr2 = (char *)JTAG_ADDR2_BASE; #define JTAG1_REG_WRITE(addr, value) \ writel(value, ((volatile UINT32 *)(jtag_addr1+(addr-JTAG_ADDR1_BASE)))) #define JTAG1_REG_READ(addr) \ readl(((volatile UINT32 *)(jtag_addr1+(addr-JTAG_ADDR1_BASE)))) #define JTAG2_REG_WRITE(addr, value) \ writel(value, ((volatile UINT32 *)(jtag_addr2+(addr-JTAG_ADDR2_BASE)))) #define JTAG2_REG_READ(addr) \ readl(((volatile UINT32 *)(jtag_addr2+(addr-JTAG_ADDR2_BASE)))) static INT32 mtk_wcn_consys_jtag_set_for_mcu(VOID) { int iRet = 0; unsigned int tmp = 0; jtag_addr1 = ioremap(JTAG_ADDR1_BASE, 0x5000); if (jtag_addr1 == 0) { printk("remap jtag_addr1 fail!\n"); return -1; } printk("jtag_addr1 = 0x%p\n", jtag_addr1); jtag_addr2 = ioremap(JTAG_ADDR2_BASE, 0x1000); if (jtag_addr2 == 0) { printk("remap jtag_addr2 fail!\n"); return -1; } printk("jtag_addr2 = 0x%p\n", jtag_addr2); /*Enable IES of all pins*/ JTAG1_REG_WRITE(0x10208004, 0xffffffff); JTAG1_REG_WRITE(0x10208014, 0xffffffff); JTAG1_REG_WRITE(0x10209004, 0xffffffff); JTAG1_REG_WRITE(0x1020A004, 0xffffffff); JTAG1_REG_WRITE(0x1020B004, 0xffffffff); /*JTAG1 mode setting*/ /*set GPIO pull mode*/ /*0x1020A040[6:0]=0x7f*/ tmp = JTAG1_REG_READ(0x1020A040); tmp &= 0xffffff80; tmp |= 0x7f; JTAG1_REG_WRITE(0x1020A040, tmp); #if 0 /*0x1020A060[6:0]=0x31*/ tmp = JTAG1_REG_READ(0x1020A060); tmp &= 0xffffff80; tmp |= 0x31; JTAG1_REG_WRITE(0x1020A060, tmp); /*set CONSYS JTAG mode 0x10005300=0x07777777*/ //DRV_WriteReg32(0x10005300, 0x07777777); /*remove JTAG mode1*/ JTAG2_REG_WRITE(0x10005300, 0x00000000); #endif #if 1 // Chaozhong modified /*0x1020A060[6:0]=0x31*/ tmp = JTAG1_REG_READ(0x1020A060); tmp &= 0xffffff80; tmp |= 0x31; JTAG1_REG_WRITE(0x1020A060, tmp); /*set CONSYS JTAG mode 0x10005300=0x07777777*/ //DRV_WriteReg32(0x10005300, 0x07777777); /*remove JTAG mode1*/ JTAG2_REG_WRITE(0x1000530C, 0x08888888);// Chaozhong modified #endif /*JTAG1 mode setting*/ /*set GPIO pull mode*/ /*0x1020A050[6:0]=0x7f*/ tmp = JTAG1_REG_READ(0x1020A050); tmp &= 0xffffff80; tmp |= 0x7f; JTAG1_REG_WRITE(0x1020A050, tmp); /*0x1020A070[6:0]=0x31*/ tmp = JTAG1_REG_READ(0x1020A070); tmp &= 0xffffff80; tmp |= 0x31; JTAG1_REG_WRITE(0x1020A070, tmp); /*set CONSYS JTAG mode 0x10005310=0x77111111 0x10005320=0x00077777*/ JTAG2_REG_WRITE(0x1000531C, 0xff111111); JTAG2_REG_WRITE(0x1000532C, 0x000fffff); /*set CONSYS debug flag mode*/ JTAG2_REG_WRITE(0x10005410, 0x77700000); /* GPIO141 ~ GPIO143 */ JTAG2_REG_WRITE(0x10005420, 0x00000077); /* GPIO144 ~ GPIO145 */ JTAG2_REG_WRITE(0x10005370, 0x70000000); /* GPIO63 */ JTAG2_REG_WRITE(0x10005380, 0x00000777); /* GPIO64 ~ GPIO66 */ JTAG2_REG_WRITE(0x100053a0, 0x70000000); /* GPIO87 */ JTAG2_REG_WRITE(0x100053b0, 0x00000777); /* GPIO88 ~ GPIO90 */ JTAG2_REG_WRITE(0x100053d0, 0x00777000); /* GPIO107 ~ GPIO109 */ return iRet; } UINT32 mtk_wcn_consys_jtag_flag_ctrl(UINT32 en) { WMT_PLAT_INFO_FUNC("%s jtag set for MCU\n",en ? "enable" : "disable"); gJtagCtrl = en; return 0; } #endif INT32 mtk_wcn_consys_hw_reg_ctrl(UINT32 on,UINT32 co_clock_en) { INT32 iRet = -1; UINT32 retry = 10; UINT32 consysHwChipId = 0; WMT_PLAT_INFO_FUNC("CONSYS-HW-REG-CTRL(0x%08x),start\n",on); if(on) { #if CONSYS_PMIC_CTRL_ENABLE /*need PMIC driver provide new API protocol before 1/18/2013*/ #ifdef MTK_PMIC_MT6397 #ifdef MTK_EXTERNAL_LDO //depends on PCB. In 8127 EVB, the power is always on after VBAT on. //If we need to control, use EINT19. #else //power on VCN18, Use VIO18. In 8127, VIO18 is always on, do nothing. //power on VCN28, Use VIO28. //hwPowerOn(MT65XX_POWER_LDO_VIO28,VOL_DEFAULT,"MOD_WMT"); #endif #else /*1.Power on MT6323 VCN_1V8 LDO<--<VCN_1V8>-->write 0 to 0x512[1], write 1 to 0x512[14]*/ upmu_set_vcn_1v8_lp_mode_set(0); //upmu_set_rg_vcn_1v8_en(1); /*will be replaced by hwpoweron just as below*/ hwPowerOn(MT6323_POWER_LDO_VCN_1V8,VOL_DEFAULT,"MOD_WMT"); udelay(150); if(co_clock_en) { /*2.set VCN_28 to SW control mode<--<VCN28_ON_CTRL>-->write 0 to 0x41C[14]*/ upmu_set_vcn28_on_ctrl(0); } else { /*2.1.switch VCN28 to HW control mode<--<VCN28_ON_CTRL>-->write 1 to 0x41C[14]*/ upmu_set_vcn28_on_ctrl(1); /*2.2.turn on VCN28LDO<--<RG_VCN28_EN>-->write 1 to 0x41C[12]*/ //upmu_set_rg_vcn28_en(1); /*will be replaced by hwpoweron just as below*/ hwPowerOn(MT6323_POWER_LDO_VCN28,VOL_DEFAULT,"MOD_WMT"); } #endif #endif /*mask this action and put it into FW patch for resolve ALPS00544691*/ #if 0 /*1.assert CONSYS CPU SW reset, <CONSYS_CPU_SW_RST_REG>, [12] = 1'b1, [31:24]=8'h88(key)--> CONSYS_CPU_SW_RST_BIT | CONSYS_CPU_SW_RST_CTRL_KEY*/ CONSYS_SET_BIT(CONSYS_CPU_SW_RST_REG, CONSYS_CPU_SW_RST_BIT | CONSYS_CPU_SW_RST_CTRL_KEY); WMT_PLAT_DBG_FUNC("reg uump:CONSYS_CPU_SW_RST_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_CPU_SW_RST_REG)); #endif #if 0 /*turn on top clock gating enable*/ CONSYS_REG_WRITE(CONSYS_TOP_CLKCG_CLR_REG,CONSYS_REG_READ(CONSYS_TOP_CLKCG_CLR_REG) | CONSYS_TOP_CLKCG_BIT); WMT_PLAT_DBG_FUNC("reg dump:CONSYS_TOP_CLKCG_CLR_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_TOP_CLKCG_CLR_REG)); /*turn on SPM clock gating enable*/ CONSYS_REG_WRITE(CONSYS_PWRON_CONFG_EN_REG, CONSYS_PWRON_CONFG_EN_VALUE); WMT_PLAT_DBG_FUNC("reg dump:CONSYS_PWRON_CONFG_EN_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_PWRON_CONFG_EN_REG)); #endif /*use colck manger API to control MTCMOS*/ conn_power_on(); WMT_PLAT_INFO_FUNC("reg dump:CONSYS_PWR_CONN_ACK_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_PWR_CONN_ACK_REG)); WMT_PLAT_INFO_FUNC("reg dump:CONSYS_PWR_CONN_ACK_S_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_PWR_CONN_ACK_S_REG)); WMT_PLAT_INFO_FUNC("reg dump:CONSYS_TOP1_PWR_CTRL_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_TOP1_PWR_CTRL_REG)); /*11.delay 10us, 26M is ready*/ udelay(10); enable_clock(MT_CG_INFRA_CONNMCU, "WMT_MOD"); /*12.poll CONSYS CHIP until MT6582/MT6572 is returned, <CONSYS_CHIP_ID_REG>, 32'h6582/32'h6572 */ /*what does HW do, why we need to polling this register?*/ while (retry-- > 0) { WMT_PLAT_DBG_FUNC("CONSYS_CHIP_ID_REG(0x%08x)",CONSYS_REG_READ(CONSYS_CHIP_ID_REG)); consysHwChipId = CONSYS_REG_READ(CONSYS_CHIP_ID_REG); if((consysHwChipId == 0x6582) || (consysHwChipId == 0x6572) || (consysHwChipId == 0x8127)) { WMT_PLAT_INFO_FUNC("retry(%d)consys chipId(0x%08x)\n", retry,consysHwChipId); break; } msleep(20); } /*mask this action and put it into FW patch for resolve ALPS00544691*/ #if 0 /*13.{default no need}update ROMDEL/PATCH RAM DELSEL if needed, <CONSYS_ROM_RAM_DELSEL_REG>*/ /*14.write 1 to conn_mcu_config ACR[1] if real speed MBIST (default write "1"), <CONSYS_MCU_CFG_ACR_REG>,[18]1'b1-->CONSYS_MCU_CFG_ACR_MBIST_BIT*/ /*if this bit is 0, HW will do memory auto test under low CPU frequence (26M Hz)*/ /*if this bit is 0, HW will do memory auto test under high CPU frequence(138M Hz) inclulding low CPU frequence*/ CONSYS_SET_BIT(CONSYS_MCU_CFG_ACR_REG, CONSYS_MCU_CFG_ACR_MBIST_BIT); /*15.{default no need, Analog HW will inform if this need to be update or not 1 week after IC sample back} update ANA_WBG(AFE) CR if needed, CONSYS_AFE_REG */ CONSYS_REG_WRITE(CONSYS_AFE_REG_DIG_RCK_01,CONSYS_AFE_REG_DIG_RCK_01_VALUE); CONSYS_REG_WRITE(CONSYS_AFE_REG_WBG_PLL_02,CONSYS_AFE_REG_WBG_PLL_02_VALUE); CONSYS_REG_WRITE(CONSYS_AFE_REG_WBG_WB_TX_01,CONSYS_AFE_REG_WBG_WB_TX_01_VALUE); /*16.deassert CONSYS CPU SW reset, <CONSYS_CPU_SW_RST_REG>, [12] = 1'b0, [31:24]=8'h88(key)*/ CONSYS_CLR_BIT_WITH_KEY(CONSYS_CPU_SW_RST_REG, CONSYS_CPU_SW_RST_BIT , CONSYS_CPU_SW_RST_CTRL_KEY); #endif msleep(5); iRet = 0; }else{ disable_clock(MT_CG_INFRA_CONNMCU, "WMT_MOD"); /*New: use colck manger API to control MTCMOS*/ conn_power_off(); #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #ifdef MTK_EXTERNAL_LDO //depends on PCB. In 8127 EVB, the power is always on after VBAT on. //If we need to control, use EINT19. #else //power down VCN28, Use VIO28. //hwPowerDown(MT65XX_POWER_LDO_VIO28,"MOD_WMT"); //power down VCN18. Use VIO28. In 8127, VIO18 can not be power down so do nothing #endif #else /*set VCN_28 to SW control mode*/ upmu_set_vcn28_on_ctrl(0); /*turn off VCN28 LDO*/ //upmu_set_rg_vcn28_en(0); /*will be replaced by hwPowerOff*/ hwPowerDown(MT6323_POWER_LDO_VCN28,"MOD_WMT"); /*power off MT6627 VWCN_1V8 LDO*/ upmu_set_vcn_1v8_lp_mode_set(0); //upmu_set_rg_vcn_1v8_en(0); /*will be replaced by hwPowerOff*/ hwPowerDown(MT6323_POWER_LDO_VCN_1V8,"MOD_WMT"); #endif #endif iRet = 0; } WMT_PLAT_INFO_FUNC("CONSYS-HW-REG-CTRL(0x%08x),finish\n",on); return iRet; } INT32 mtk_wcn_consys_hw_gpio_ctrl (UINT32 on) { INT32 iRet = 0; WMT_PLAT_INFO_FUNC("CONSYS-HW-GPIO-CTRL(0x%08x), start\n",on); if(on) { /*if external modem used,GPS_SYNC still needed to control*/ iRet += wmt_plat_gpio_ctrl(PIN_GPS_SYNC, PIN_STA_INIT); iRet += wmt_plat_gpio_ctrl(PIN_GPS_LNA, PIN_STA_INIT); iRet += wmt_plat_gpio_ctrl(PIN_I2S_GRP,PIN_STA_INIT); /*set EINT< -ommited-> move this to WMT-IC module, where common sdio interface will be identified and do proper operation*/ // TODO: [FixMe][GeorgeKuo] double check if BGF_INT is implemented ok //iRet += wmt_plat_gpio_ctrl(PIN_BGF_EINT, PIN_STA_MUX); #if CFG_WMT_DUMP_INT_STATUS wmt_plat_BGF_irq_dump_status(); #endif iRet += wmt_plat_eirq_ctrl(PIN_BGF_EINT, PIN_STA_INIT); #if CFG_WMT_DUMP_INT_STATUS wmt_plat_BGF_irq_dump_status(); #endif iRet += wmt_plat_eirq_ctrl(PIN_BGF_EINT, PIN_STA_EINT_DIS); #if CFG_WMT_DUMP_INT_STATUS wmt_plat_BGF_irq_dump_status(); #endif WMT_PLAT_INFO_FUNC("CONSYS-HW, BGF IRQ registered and disabled \n"); }else{ /* set bgf eint/all eint to deinit state, namely input low state*/ iRet += wmt_plat_eirq_ctrl(PIN_BGF_EINT, PIN_STA_EINT_DIS); iRet += wmt_plat_eirq_ctrl(PIN_BGF_EINT, PIN_STA_DEINIT); #if CFG_WMT_DUMP_INT_STATUS wmt_plat_BGF_irq_dump_status(); #endif WMT_PLAT_INFO_FUNC("CONSYS-HW, BGF IRQ unregistered and disabled\n"); //iRet += wmt_plat_gpio_ctrl(PIN_BGF_EINT, PIN_STA_DEINIT); /*if external modem used,GPS_SYNC still needed to control*/ iRet += wmt_plat_gpio_ctrl(PIN_GPS_SYNC, PIN_STA_DEINIT); iRet += wmt_plat_gpio_ctrl(PIN_I2S_GRP,PIN_STA_DEINIT); /* deinit gps_lna*/ iRet += wmt_plat_gpio_ctrl(PIN_GPS_LNA, PIN_STA_DEINIT); } WMT_PLAT_INFO_FUNC("CONSYS-HW-GPIO-CTRL(0x%08x), finish\n",on); return iRet; } INT32 mtk_wcn_consys_hw_pwr_on(UINT32 co_clock_en) { INT32 iRet = 0; WMT_PLAT_INFO_FUNC("CONSYS-HW-PWR-ON, start\n"); iRet += mtk_wcn_consys_hw_reg_ctrl(1,co_clock_en); iRet += mtk_wcn_consys_hw_gpio_ctrl(1); #if CONSYS_ENALBE_SET_JTAG if(gJtagCtrl) { mtk_wcn_consys_jtag_set_for_mcu(); } #endif WMT_PLAT_INFO_FUNC("CONSYS-HW-PWR-ON, finish(%d)\n",iRet); return iRet; } INT32 mtk_wcn_consys_hw_pwr_off (VOID) { INT32 iRet = 0; WMT_PLAT_INFO_FUNC("CONSYS-HW-PWR-OFF, start\n"); iRet += mtk_wcn_consys_hw_reg_ctrl(0,0); iRet += mtk_wcn_consys_hw_gpio_ctrl(0); WMT_PLAT_INFO_FUNC("CONSYS-HW-PWR-OFF, finish(%d)\n",iRet); return iRet; } INT32 mtk_wcn_consys_hw_rst (UINT32 co_clock_en) { INT32 iRet = 0; WMT_PLAT_INFO_FUNC("CONSYS-HW, hw_rst start, eirq should be disabled before this step\n"); /*1. do whole hw power off flow*/ iRet += mtk_wcn_consys_hw_reg_ctrl(0,co_clock_en); /*2. do whole hw power on flow*/ iRet += mtk_wcn_consys_hw_reg_ctrl(1,co_clock_en); WMT_PLAT_INFO_FUNC("CONSYS-HW, hw_rst finish, eirq should be enabled after this step\n"); return iRet; } INT32 mtk_wcn_consys_hw_bt_paldo_ctrl(UINT32 enable) { if(enable){ /*do BT PMIC on,depenency PMIC API ready*/ /*switch BT PALDO control from SW mode to HW mode:0x416[5]-->0x1*/ #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #ifdef MTK_EXTERNAL_LDO #else hwPowerOn(MT65XX_POWER_LDO_VGP4,VOL_3300,"MOD_WMT"); // upmu_set_vcn33_on_ctrl_bt(1); #endif #else hwPowerOn(MT6323_POWER_LDO_VCN33_BT,VOL_3300,"MOD_WMT"); upmu_set_vcn33_on_ctrl_bt(1); #endif #endif WMT_PLAT_INFO_FUNC("WMT do BT PMIC on\n"); }else{ /*do BT PMIC off*/ /*switch BT PALDO control from HW mode to SW mode:0x416[5]-->0x0*/ #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #ifdef MTK_EXTERNAL_LDO #else // upmu_set_vcn33_on_ctrl_bt(0); hwPowerDown(MT65XX_POWER_LDO_VGP4,"MOD_WMT"); #endif #else upmu_set_vcn33_on_ctrl_bt(0); hwPowerDown(MT6323_POWER_LDO_VCN33_BT,"MOD_WMT"); #endif #endif WMT_PLAT_INFO_FUNC("WMT do BT PMIC off\n"); } return 0; } INT32 mtk_wcn_consys_hw_wifi_paldo_ctrl(UINT32 enable) { if(enable){ /*do WIFI PMIC on,depenency PMIC API ready*/ /*switch WIFI PALDO control from SW mode to HW mode:0x418[14]-->0x1*/ #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #ifdef MTK_EXTERNAL_LDO //depends on PCB. In 8127 EVB, the power is always on after VBAT on. //If we need to control, use EINT19. #else //power on VCN33, Use VGP4. hwPowerOn(MT65XX_POWER_LDO_VGP4,VOL_3300,"MOD_WMT"); #endif #else hwPowerOn(MT6323_POWER_LDO_VCN33_WIFI,VOL_3300,"MOD_WMT"); //upmu_set_vcn33_on_ctrl_wifi(1); #endif #endif WMT_PLAT_INFO_FUNC("WMT do WIFI PMIC on\n"); }else{ /*do WIFI PMIC off*/ /*switch WIFI PALDO control from HW mode to SW mode:0x418[14]-->0x0*/ #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #ifdef MTK_EXTERNAL_LDO //depends on PCB. In 8127 EVB, the power is always on after VBAT on. //If we need to control, use EINT19. #else //power down VCN33, Use VGP4. hwPowerDown(MT65XX_POWER_LDO_VGP4,"MOD_WMT"); #endif #else //upmu_set_vcn33_on_ctrl_wifi(0); hwPowerDown(MT6323_POWER_LDO_VCN33_WIFI,"MOD_WMT"); #endif #endif WMT_PLAT_INFO_FUNC("WMT do WIFI PMIC off\n"); } return 0; } INT32 mtk_wcn_consys_hw_vcn28_ctrl(UINT32 enable) { if(enable){ /*in co-clock mode,need to turn on vcn28 when fm on*/ #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #else hwPowerOn(MT6323_POWER_LDO_VCN28,VOL_DEFAULT,"MOD_WMT"); #endif #endif WMT_PLAT_INFO_FUNC("turn on vcn28 for fm/gps usage in co-clock mode\n"); }else{ /*in co-clock mode,need to turn off vcn28 when fm off*/ #if CONSYS_PMIC_CTRL_ENABLE #ifdef MTK_PMIC_MT6397 #else hwPowerDown(MT6323_POWER_LDO_VCN28,"MOD_WMT"); #endif #endif WMT_PLAT_INFO_FUNC("turn off vcn28 for fm/gps usage in co-clock mode\n"); } return 0; } INT32 mtk_wcn_consys_hw_state_show(VOID) { return 0; } #if CONSYS_WMT_REG_SUSPEND_CB_ENABLE UINT32 mtk_wcn_consys_hw_osc_en_ctrl(UINT32 en) { if(en) { WMT_PLAT_INFO_FUNC("enable consys sleep mode(turn off 26M)\n"); CONSYS_REG_WRITE(CONSYS_AP2CONN_OSC_EN_REG, CONSYS_REG_READ(CONSYS_AP2CONN_OSC_EN_REG) & ~CONSYS_AP2CONN_OSC_EN_BIT); }else { WMT_PLAT_INFO_FUNC("disable consys sleep mode\n"); CONSYS_REG_WRITE(CONSYS_AP2CONN_OSC_EN_REG, CONSYS_REG_READ(CONSYS_AP2CONN_OSC_EN_REG) | CONSYS_AP2CONN_OSC_EN_BIT); } WMT_PLAT_INFO_FUNC("dump CONSYS_AP2CONN_OSC_EN_REG(0x%x)\n",CONSYS_REG_READ(CONSYS_AP2CONN_OSC_EN_REG)); return 0; } #endif INT32 mtk_wcn_consys_hw_restore(struct device *device) { INT32 iRet = -1; UINT32 addrPhy = 0; /*set MPU for EMI share Memory*/ WMT_PLAT_INFO_FUNC("setting MPU for EMI share memory\n"); emi_mpu_set_region_protection(gConEmiPhyBase + SZ_1M/2, gConEmiPhyBase + SZ_1M, 5, SET_ACCESS_PERMISSON(FORBIDDEN,NO_PROTECTION,FORBIDDEN,NO_PROTECTION)); WMT_PLAT_INFO_FUNC("get consys start phy address(0x%x)\n",gConEmiPhyBase); /*consys to ap emi remapping register:10001310, cal remapping address*/ addrPhy = (gConEmiPhyBase & 0xFFF00000) >> 20; /*enable consys to ap emi remapping bit12*/ addrPhy = addrPhy | 0x1000; CONSYS_REG_WRITE(CONSYS_EMI_MAPPING,CONSYS_REG_READ(CONSYS_EMI_MAPPING) | addrPhy); WMT_PLAT_INFO_FUNC("CONSYS_EMI_MAPPING dump(0x%08x)\n",CONSYS_REG_READ(CONSYS_EMI_MAPPING)); #if 1 pEmibaseaddr = ioremap_nocache(gConEmiPhyBase + CONSYS_EMI_AP_PHY_OFFSET,CONSYS_EMI_MEM_SIZE); #else pEmibaseaddr = ioremap_nocache(CONSYS_EMI_AP_PHY_BASE,CONSYS_EMI_MEM_SIZE); #endif //pEmibaseaddr = ioremap_nocache(0x80090400,270*KBYTE); if(pEmibaseaddr) { WMT_PLAT_INFO_FUNC("EMI mapping OK(0x%p)\n",pEmibaseaddr); memset(pEmibaseaddr,0,CONSYS_EMI_MEM_SIZE); iRet = 0; }else{ WMT_PLAT_ERR_FUNC("EMI mapping fail\n"); } return iRet; } VOID __init mtk_wcn_consys_memory_reserve(VOID) { gConEmiPhyBase = arm_memblock_steal(SZ_1M,SZ_1M); if(gConEmiPhyBase) { WMT_PLAT_INFO_FUNC("memblock done: 0x%x\n",gConEmiPhyBase); }else { WMT_PLAT_ERR_FUNC("memblock fail\n"); } } INT32 mtk_wcn_consys_hw_init() { INT32 iRet = -1; UINT32 addrPhy = 0; /*set MPU for EMI share Memory*/ WMT_PLAT_INFO_FUNC("setting MPU for EMI share memory\n"); emi_mpu_set_region_protection(gConEmiPhyBase + SZ_1M/2, gConEmiPhyBase + SZ_1M, 5, SET_ACCESS_PERMISSON(FORBIDDEN,NO_PROTECTION,FORBIDDEN,NO_PROTECTION)); WMT_PLAT_INFO_FUNC("get consys start phy address(0x%x)\n",gConEmiPhyBase); /*consys to ap emi remapping register:10001310, cal remapping address*/ addrPhy = (gConEmiPhyBase & 0xFFF00000) >> 20; /*enable consys to ap emi remapping bit12*/ addrPhy = addrPhy | 0x1000; CONSYS_REG_WRITE(CONSYS_EMI_MAPPING,CONSYS_REG_READ(CONSYS_EMI_MAPPING) | addrPhy); WMT_PLAT_INFO_FUNC("CONSYS_EMI_MAPPING dump(0x%08x)\n",CONSYS_REG_READ(CONSYS_EMI_MAPPING)); #if 1 pEmibaseaddr = ioremap_nocache(gConEmiPhyBase + CONSYS_EMI_AP_PHY_OFFSET,CONSYS_EMI_MEM_SIZE); #else pEmibaseaddr = ioremap_nocache(CONSYS_EMI_AP_PHY_BASE,CONSYS_EMI_MEM_SIZE); #endif //pEmibaseaddr = ioremap_nocache(0x80090400,270*KBYTE); if(pEmibaseaddr) { WMT_PLAT_INFO_FUNC("EMI mapping OK(0x%p)\n",pEmibaseaddr); memset(pEmibaseaddr,0,CONSYS_EMI_MEM_SIZE); iRet = 0; }else{ WMT_PLAT_ERR_FUNC("EMI mapping fail\n"); } WMT_PLAT_INFO_FUNC("register connsys restore cb for complying with IPOH function\n"); register_swsusp_restore_noirq_func(ID_M_CONNSYS,mtk_wcn_consys_hw_restore,NULL); return iRet; } INT32 mtk_wcn_consys_hw_deinit() { if(pEmibaseaddr) { iounmap(pEmibaseaddr); pEmibaseaddr = NULL; } unregister_swsusp_restore_noirq_func(ID_M_CONNSYS); return 0; } UINT8 *mtk_wcn_consys_emi_virt_addr_get(UINT32 ctrl_state_offset) { UINT8 *p_virtual_addr = NULL; if(!pEmibaseaddr) { WMT_PLAT_ERR_FUNC("EMI base address is NULL\n"); return NULL; } WMT_PLAT_DBG_FUNC("ctrl_state_offset(%08x)\n",ctrl_state_offset); p_virtual_addr = pEmibaseaddr + ctrl_state_offset; return p_virtual_addr; } UINT32 mtk_wcn_consys_soc_chipid() { return PLATFORM_SOC_CHIP; }
HB72K/android_kernel_lgk10_mt6582
drivers/misc/mediatek/connectivity/conn_soc/common/mt8127/mtk_wcn_consys_hw.c
C
gpl-2.0
22,082
// -------------------------------------------------------------------------- // Name: sndpcm.cpp // Purpose: // Date: 08/11/1999 // Author: Guilhem Lavaux <lavaux@easynet.fr> (C) 1999 // CVSID: $Id: sndpcm.cpp 35650 2005-09-23 12:56:45Z MR $ // wxWindows licence // -------------------------------------------------------------------------- #include "wx/wxprec.h" #ifndef WX_PRECOMP #include "wx/defs.h" #endif #ifdef __BORLANDC__ #pragma hdrstop #endif #include "wx/mmedia/sndbase.h" #include "wx/mmedia/sndpcm.h" wxSoundFormatPcm::wxSoundFormatPcm(wxUint32 srate, wxUint8 bps, wxUint16 nchannels, bool sign, int order) : m_srate(srate), m_bps(bps), m_nchan(nchannels), m_order(order), m_signed(sign) { } wxSoundFormatPcm::~wxSoundFormatPcm() { } void wxSoundFormatPcm::SetSampleRate(wxUint32 srate) { m_srate = srate; } void wxSoundFormatPcm::SetBPS(wxUint8 bps) { m_bps = bps; } void wxSoundFormatPcm::SetChannels(wxUint16 nchannels) { m_nchan = nchannels; } void wxSoundFormatPcm::SetOrder(int order) { m_order = order; } void wxSoundFormatPcm::Signed(bool sign) { m_signed = sign; } wxSoundFormatBase *wxSoundFormatPcm::Clone() const { wxSoundFormatPcm *new_pcm; new_pcm = new wxSoundFormatPcm(); new_pcm->m_srate = m_srate; new_pcm->m_bps = m_bps; new_pcm->m_nchan = m_nchan; new_pcm->m_order = m_order; new_pcm->m_signed= m_signed; return new_pcm; } wxUint32 wxSoundFormatPcm::GetTimeFromBytes(wxUint32 bytes) const { return (bytes / (m_srate * (m_bps / 8) * m_nchan)); } wxUint32 wxSoundFormatPcm::GetBytesFromTime(wxUint32 time) const { return (time * (m_srate * (m_bps / 8) * m_nchan)); } bool wxSoundFormatPcm::operator!=(const wxSoundFormatBase& format) const { wxSoundFormatPcm *format2 = (wxSoundFormatPcm *)&format; if (format.GetType() != wxSOUND_PCM) return true; return ( (m_srate != format2->m_srate) || (m_bps != format2->m_bps) || (m_nchan != format2->m_nchan) || (m_order != format2->m_order) || (m_signed != format2->m_signed) ); }
hajuuk/R7000
ap/gpl/amule/wxWidgets-2.8.12/contrib/src/mmedia/sndpcm.cpp
C++
gpl-2.0
2,145
<?php /** * Template Name: Page - Post - Index * The template used for displaying page content in page.php * * @author Matt Peternell| http://stoemper.com * @package stoemper 2.0 */ //*/ ?> <?php //wp_nav_menu(); ?> <?php get_header() ?> <div id="container"> <div id="content" class="index bikes-bground"> <div id="nav-above" class="row navigation"> <div class="col-md-6 nav-previous"><?php next_posts_link(__('<span class="meta-nav">&laquo;</span> Older Posts', 'sandbox')) ?> </div> <div class="col-md-6 nav-next"><?php previous_posts_link(__('Newer Posts <span class="meta-nav">&raquo;</span>', 'sandbox')) ?></div> </div> <?php while ( have_posts() ) : the_post() ?> <article id="post-<?php the_ID() ?>" class=" <?php sandbox_post_class() ?>"> <header class="row"> <div class="col-md-8"> <h2 class="entry-title"><a href="<?php the_permalink() ?>" title="<?php printf(__('Permalink to %s', 'sandbox'), wp_specialchars(get_the_title(), 1)) ?>" rel="bookmark"><?php the_title() ?></a></h2> <?php if(function_exists('the_subtitle')) the_subtitle( '<h2 class="subtitle">', '</h2>'); ?> </div> <div class="col-md-4 entry-date"> <time class="published" title="<?php the_time('Y-m-d\TH:i:sO') ?>"><?php the_time('d M'); ?></time> </div> </header> <div class="row"> <div class="col-md-8 entry-content"> <?php the_content(''.__('Read More <span class="meta-nav">&raquo;</span>', 'sandbox').''); ?> <?php wp_link_pages('before=<div class="page-link">' .__('Pages:', 'sandbox') . '&after=</div>') ?> </div> </div> <footer class="col-md-4 entry-meta"> <span class="author vcard"><?php printf(__('By %s', 'sandbox'), '<a class="url fn n" href="'.get_author_link(false, $authordata->ID, $authordata->user_nicename).'" title="' . sprintf(__('View all posts by %s', 'sandbox'), $authordata->display_name) . '">'.get_the_author().'</a>') ?></span> <span class="cat-links"><?php printf(__('Posted in %s', 'sandbox'), get_the_category_list(', ')) ?></span> <?php the_tags(__('<span class="tag-links">Tagged ', 'sandbox'), ", ", "</span>\n\t\t\t\t\t\n") ?> <span class="comments-link"><?php comments_popup_link(__('Comments (0)', 'sandbox'), __('Comments (1)', 'sandbox'), __('Comments (%)', 'sandbox')) ?></span> <?php edit_post_link(__('Edit', 'sandbox'), "\t\t\t\t\t<br/><br/><span class=\"edit-link btn btn-danger btn-xs\">", "</span>\n\t\t\t\t\t\n"); ?> </footer> </article><!-- .post --> <?php comments_template() ?> <?php endwhile ?> <div id="nav-below" class="row navigation"> <div class="col-md-6 nav-previous"><?php next_posts_link(__('<span class="meta-nav">&laquo;</span> Older Posts', 'sandbox')) ?></div> <div class="col-md-6 nav-next"><?php previous_posts_link(__('Newer Posts <span class="meta-nav">&raquo;</span>', 'sandbox')) ?></div> </div> </div><!-- #content --> </div><!-- #container --> <?php //get_sidebar() ?> <?php get_footer() ?>
peternem/stmpr-wp
wp-content/themes/Stoemper-autofocus-5.0/page-templates/post-index.php
PHP
gpl-2.0
3,019
# Configuration Files ![Let's configure them ALL!](https://github.com/gabrsar/dotfiles/blob/master/imgs/meme.jpg?raw=true) These are my `.files`. Here I will keep my favorite configurations so others can learn or tell-me how to improve my configurations too ;) Here you will find configuration for the following: ## ![VIM](https://github.com/gabrsar/dotfiles/blob/master/imgs/Vimlogo.png?raw=true) VIM - The most awesome text editor, ever. ## ![ZSH](https://github.com/gabrsar/dotfiles/blob/master/imgs/zsh.jpg?raw=true) ZSH - The most awesome shell, ever ## ![i3wm](https://github.com/gabrsar/dotfiles/blob/master/imgs/i3wm.png?raw=true) I3WM - The most awesome window manager, ever. ## ![ROFI](https://github.com/gabrsar/dotfiles/blob/master/imgs/rofi-large.png?raw=true) ROFI - The most awesome app launcher, ever.
gabrsar/dotfiles
README.md
Markdown
gpl-2.0
827
<?php /** * The template for displaying the footer. * * Contains the closing of the #content div and all content after * * @package Quail Forever */ ?> </div><!-- #content --> <footer id="colophon" class="site-footer" role="contentinfo"> <div class="site-info"> <a href="<?php echo esc_url( __( 'http://wordpress.org/', 'quail-forever' ) ); ?>"><?php printf( __( 'Proudly powered by %s', 'quail-forever' ), 'WordPress' ); ?></a> <span class="sep"> | </span> <?php printf( __( 'Theme: %1$s by %2$s.', 'quail-forever' ), 'Quail Forever', '<a href="http://underscores.me/" rel="designer">Mitchell Barron</a>' ); ?> </div><!-- .site-info --> </footer><!-- #colophon --> </div><!-- #page --> <?php wp_footer(); ?> </body> </html>
mtchllbrrn/quail_forever
wp-content/themes/quail-forever/footer.php
PHP
gpl-2.0
751
/* DWARF 2 location expression support for GDB. Copyright (C) 2003-2013 Free Software Foundation, Inc. Contributed by Daniel Jacobowitz, MontaVista Software, Inc. This file is part of GDB. 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 "defs.h" #include "ui-out.h" #include "value.h" #include "frame.h" #include "gdbcore.h" #include "target.h" #include "inferior.h" #include "ax.h" #include "ax-gdb.h" #include "regcache.h" #include "objfiles.h" #include "exceptions.h" #include "block.h" #include "gdbcmd.h" #include "dwarf2.h" #include "dwarf2expr.h" #include "dwarf2loc.h" #include "dwarf2-frame.h" #include <string.h> #include "gdb_assert.h" extern int dwarf2_always_disassemble; static void dwarf_expr_frame_base_1 (struct symbol *framefunc, CORE_ADDR pc, const gdb_byte **start, size_t *length); static const struct dwarf_expr_context_funcs dwarf_expr_ctx_funcs; static struct value *dwarf2_evaluate_loc_desc_full (struct type *type, struct frame_info *frame, const gdb_byte *data, size_t size, struct dwarf2_per_cu_data *per_cu, LONGEST byte_offset); /* Until these have formal names, we define these here. ref: http://gcc.gnu.org/wiki/DebugFission Each entry in .debug_loc.dwo begins with a byte that describes the entry, and is then followed by data specific to that entry. */ enum debug_loc_kind { /* Indicates the end of the list of entries. */ DEBUG_LOC_END_OF_LIST = 0, /* This is followed by an unsigned LEB128 number that is an index into .debug_addr and specifies the base address for all following entries. */ DEBUG_LOC_BASE_ADDRESS = 1, /* This is followed by two unsigned LEB128 numbers that are indices into .debug_addr and specify the beginning and ending addresses, and then a normal location expression as in .debug_loc. */ DEBUG_LOC_START_END = 2, /* This is followed by an unsigned LEB128 number that is an index into .debug_addr and specifies the beginning address, and a 4 byte unsigned number that specifies the length, and then a normal location expression as in .debug_loc. */ DEBUG_LOC_START_LENGTH = 3, /* An internal value indicating there is insufficient data. */ DEBUG_LOC_BUFFER_OVERFLOW = -1, /* An internal value indicating an invalid kind of entry was found. */ DEBUG_LOC_INVALID_ENTRY = -2 }; /* Helper function which throws an error if a synthetic pointer is invalid. */ static void invalid_synthetic_pointer (void) { error (_("access outside bounds of object " "referenced via synthetic pointer")); } /* Decode the addresses in a non-dwo .debug_loc entry. A pointer to the next byte to examine is returned in *NEW_PTR. The encoded low,high addresses are return in *LOW,*HIGH. The result indicates the kind of entry found. */ static enum debug_loc_kind decode_debug_loc_addresses (const gdb_byte *loc_ptr, const gdb_byte *buf_end, const gdb_byte **new_ptr, CORE_ADDR *low, CORE_ADDR *high, enum bfd_endian byte_order, unsigned int addr_size, int signed_addr_p) { CORE_ADDR base_mask = ~(~(CORE_ADDR)1 << (addr_size * 8 - 1)); if (buf_end - loc_ptr < 2 * addr_size) return DEBUG_LOC_BUFFER_OVERFLOW; if (signed_addr_p) *low = extract_signed_integer (loc_ptr, addr_size, byte_order); else *low = extract_unsigned_integer (loc_ptr, addr_size, byte_order); loc_ptr += addr_size; if (signed_addr_p) *high = extract_signed_integer (loc_ptr, addr_size, byte_order); else *high = extract_unsigned_integer (loc_ptr, addr_size, byte_order); loc_ptr += addr_size; *new_ptr = loc_ptr; /* A base-address-selection entry. */ if ((*low & base_mask) == base_mask) return DEBUG_LOC_BASE_ADDRESS; /* An end-of-list entry. */ if (*low == 0 && *high == 0) return DEBUG_LOC_END_OF_LIST; return DEBUG_LOC_START_END; } /* Decode the addresses in .debug_loc.dwo entry. A pointer to the next byte to examine is returned in *NEW_PTR. The encoded low,high addresses are return in *LOW,*HIGH. The result indicates the kind of entry found. */ static enum debug_loc_kind decode_debug_loc_dwo_addresses (struct dwarf2_per_cu_data *per_cu, const gdb_byte *loc_ptr, const gdb_byte *buf_end, const gdb_byte **new_ptr, CORE_ADDR *low, CORE_ADDR *high, enum bfd_endian byte_order) { uint64_t low_index, high_index; if (loc_ptr == buf_end) return DEBUG_LOC_BUFFER_OVERFLOW; switch (*loc_ptr++) { case DEBUG_LOC_END_OF_LIST: *new_ptr = loc_ptr; return DEBUG_LOC_END_OF_LIST; case DEBUG_LOC_BASE_ADDRESS: *low = 0; loc_ptr = gdb_read_uleb128 (loc_ptr, buf_end, &high_index); if (loc_ptr == NULL) return DEBUG_LOC_BUFFER_OVERFLOW; *high = dwarf2_read_addr_index (per_cu, high_index); *new_ptr = loc_ptr; return DEBUG_LOC_BASE_ADDRESS; case DEBUG_LOC_START_END: loc_ptr = gdb_read_uleb128 (loc_ptr, buf_end, &low_index); if (loc_ptr == NULL) return DEBUG_LOC_BUFFER_OVERFLOW; *low = dwarf2_read_addr_index (per_cu, low_index); loc_ptr = gdb_read_uleb128 (loc_ptr, buf_end, &high_index); if (loc_ptr == NULL) return DEBUG_LOC_BUFFER_OVERFLOW; *high = dwarf2_read_addr_index (per_cu, high_index); *new_ptr = loc_ptr; return DEBUG_LOC_START_END; case DEBUG_LOC_START_LENGTH: loc_ptr = gdb_read_uleb128 (loc_ptr, buf_end, &low_index); if (loc_ptr == NULL) return DEBUG_LOC_BUFFER_OVERFLOW; *low = dwarf2_read_addr_index (per_cu, low_index); if (loc_ptr + 4 > buf_end) return DEBUG_LOC_BUFFER_OVERFLOW; *high = *low; *high += extract_unsigned_integer (loc_ptr, 4, byte_order); *new_ptr = loc_ptr + 4; return DEBUG_LOC_START_LENGTH; default: return DEBUG_LOC_INVALID_ENTRY; } } /* A function for dealing with location lists. Given a symbol baton (BATON) and a pc value (PC), find the appropriate location expression, set *LOCEXPR_LENGTH, and return a pointer to the beginning of the expression. Returns NULL on failure. For now, only return the first matching location expression; there can be more than one in the list. */ const gdb_byte * dwarf2_find_location_expression (struct dwarf2_loclist_baton *baton, size_t *locexpr_length, CORE_ADDR pc) { struct objfile *objfile = dwarf2_per_cu_objfile (baton->per_cu); struct gdbarch *gdbarch = get_objfile_arch (objfile); enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); unsigned int addr_size = dwarf2_per_cu_addr_size (baton->per_cu); int signed_addr_p = bfd_get_sign_extend_vma (objfile->obfd); /* Adjust base_address for relocatable objects. */ CORE_ADDR base_offset = dwarf2_per_cu_text_offset (baton->per_cu); CORE_ADDR base_address = baton->base_address + base_offset; const gdb_byte *loc_ptr, *buf_end; loc_ptr = baton->data; buf_end = baton->data + baton->size; while (1) { CORE_ADDR low = 0, high = 0; /* init for gcc -Wall */ int length; enum debug_loc_kind kind; const gdb_byte *new_ptr = NULL; /* init for gcc -Wall */ if (baton->from_dwo) kind = decode_debug_loc_dwo_addresses (baton->per_cu, loc_ptr, buf_end, &new_ptr, &low, &high, byte_order); else kind = decode_debug_loc_addresses (loc_ptr, buf_end, &new_ptr, &low, &high, byte_order, addr_size, signed_addr_p); loc_ptr = new_ptr; switch (kind) { case DEBUG_LOC_END_OF_LIST: *locexpr_length = 0; return NULL; case DEBUG_LOC_BASE_ADDRESS: base_address = high + base_offset; continue; case DEBUG_LOC_START_END: case DEBUG_LOC_START_LENGTH: break; case DEBUG_LOC_BUFFER_OVERFLOW: case DEBUG_LOC_INVALID_ENTRY: error (_("dwarf2_find_location_expression: " "Corrupted DWARF expression.")); default: gdb_assert_not_reached ("bad debug_loc_kind"); } /* Otherwise, a location expression entry. If the entry is from a DWO, don't add base address: the entry is from .debug_addr which has absolute addresses. */ if (! baton->from_dwo) { low += base_address; high += base_address; } length = extract_unsigned_integer (loc_ptr, 2, byte_order); loc_ptr += 2; if (low == high && pc == low) { /* This is entry PC record present only at entry point of a function. Verify it is really the function entry point. */ struct block *pc_block = block_for_pc (pc); struct symbol *pc_func = NULL; if (pc_block) pc_func = block_linkage_function (pc_block); if (pc_func && pc == BLOCK_START (SYMBOL_BLOCK_VALUE (pc_func))) { *locexpr_length = length; return loc_ptr; } } if (pc >= low && pc < high) { *locexpr_length = length; return loc_ptr; } loc_ptr += length; } } /* This is the baton used when performing dwarf2 expression evaluation. */ struct dwarf_expr_baton { struct frame_info *frame; struct dwarf2_per_cu_data *per_cu; }; /* Helper functions for dwarf2_evaluate_loc_desc. */ /* Using the frame specified in BATON, return the value of register REGNUM, treated as a pointer. */ static CORE_ADDR dwarf_expr_read_addr_from_reg (void *baton, int dwarf_regnum) { struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; struct gdbarch *gdbarch = get_frame_arch (debaton->frame); CORE_ADDR result; int regnum; regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, dwarf_regnum); result = address_from_register (builtin_type (gdbarch)->builtin_data_ptr, regnum, debaton->frame); return result; } /* Implement struct dwarf_expr_context_funcs' "get_reg_value" callback. */ static struct value * dwarf_expr_get_reg_value (void *baton, struct type *type, int dwarf_regnum) { struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; struct gdbarch *gdbarch = get_frame_arch (debaton->frame); int regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, dwarf_regnum); return value_from_register (type, regnum, debaton->frame); } /* Read memory at ADDR (length LEN) into BUF. */ static void dwarf_expr_read_mem (void *baton, gdb_byte *buf, CORE_ADDR addr, size_t len) { read_memory (addr, buf, len); } /* Using the frame specified in BATON, find the location expression describing the frame base. Return a pointer to it in START and its length in LENGTH. */ static void dwarf_expr_frame_base (void *baton, const gdb_byte **start, size_t * length) { /* FIXME: cagney/2003-03-26: This code should be using get_frame_base_address(), and then implement a dwarf2 specific this_base method. */ struct symbol *framefunc; struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; struct block *bl = get_frame_block (debaton->frame, NULL); if (bl == NULL) error (_("frame address is not available.")); /* Use block_linkage_function, which returns a real (not inlined) function, instead of get_frame_function, which may return an inlined function. */ framefunc = block_linkage_function (bl); /* If we found a frame-relative symbol then it was certainly within some function associated with a frame. If we can't find the frame, something has gone wrong. */ gdb_assert (framefunc != NULL); dwarf_expr_frame_base_1 (framefunc, get_frame_address_in_block (debaton->frame), start, length); } /* Implement find_frame_base_location method for LOC_BLOCK functions using DWARF expression for its DW_AT_frame_base. */ static void locexpr_find_frame_base_location (struct symbol *framefunc, CORE_ADDR pc, const gdb_byte **start, size_t *length) { struct dwarf2_locexpr_baton *symbaton = SYMBOL_LOCATION_BATON (framefunc); *length = symbaton->size; *start = symbaton->data; } /* Vector for inferior functions as represented by LOC_BLOCK, if the inferior function uses DWARF expression for its DW_AT_frame_base. */ const struct symbol_block_ops dwarf2_block_frame_base_locexpr_funcs = { locexpr_find_frame_base_location }; /* Implement find_frame_base_location method for LOC_BLOCK functions using DWARF location list for its DW_AT_frame_base. */ static void loclist_find_frame_base_location (struct symbol *framefunc, CORE_ADDR pc, const gdb_byte **start, size_t *length) { struct dwarf2_loclist_baton *symbaton = SYMBOL_LOCATION_BATON (framefunc); *start = dwarf2_find_location_expression (symbaton, length, pc); } /* Vector for inferior functions as represented by LOC_BLOCK, if the inferior function uses DWARF location list for its DW_AT_frame_base. */ const struct symbol_block_ops dwarf2_block_frame_base_loclist_funcs = { loclist_find_frame_base_location }; static void dwarf_expr_frame_base_1 (struct symbol *framefunc, CORE_ADDR pc, const gdb_byte **start, size_t *length) { if (SYMBOL_BLOCK_OPS (framefunc) != NULL) { const struct symbol_block_ops *ops_block = SYMBOL_BLOCK_OPS (framefunc); ops_block->find_frame_base_location (framefunc, pc, start, length); } else *length = 0; if (*length == 0) error (_("Could not find the frame base for \"%s\"."), SYMBOL_NATURAL_NAME (framefunc)); } /* Helper function for dwarf2_evaluate_loc_desc. Computes the CFA for the frame in BATON. */ static CORE_ADDR dwarf_expr_frame_cfa (void *baton) { struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; return dwarf2_frame_cfa (debaton->frame); } /* Helper function for dwarf2_evaluate_loc_desc. Computes the PC for the frame in BATON. */ static CORE_ADDR dwarf_expr_frame_pc (void *baton) { struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; return get_frame_address_in_block (debaton->frame); } /* Using the objfile specified in BATON, find the address for the current thread's thread-local storage with offset OFFSET. */ static CORE_ADDR dwarf_expr_tls_address (void *baton, CORE_ADDR offset) { struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; struct objfile *objfile = dwarf2_per_cu_objfile (debaton->per_cu); return target_translate_tls_address (objfile, offset); } /* Call DWARF subroutine from DW_AT_location of DIE at DIE_OFFSET in current CU (as is PER_CU). State of the CTX is not affected by the call and return. */ static void per_cu_dwarf_call (struct dwarf_expr_context *ctx, cu_offset die_offset, struct dwarf2_per_cu_data *per_cu, CORE_ADDR (*get_frame_pc) (void *baton), void *baton) { struct dwarf2_locexpr_baton block; block = dwarf2_fetch_die_loc_cu_off (die_offset, per_cu, get_frame_pc, baton); /* DW_OP_call_ref is currently not supported. */ gdb_assert (block.per_cu == per_cu); dwarf_expr_eval (ctx, block.data, block.size); } /* Helper interface of per_cu_dwarf_call for dwarf2_evaluate_loc_desc. */ static void dwarf_expr_dwarf_call (struct dwarf_expr_context *ctx, cu_offset die_offset) { struct dwarf_expr_baton *debaton = ctx->baton; per_cu_dwarf_call (ctx, die_offset, debaton->per_cu, ctx->funcs->get_frame_pc, ctx->baton); } /* Callback function for dwarf2_evaluate_loc_desc. */ static struct type * dwarf_expr_get_base_type (struct dwarf_expr_context *ctx, cu_offset die_offset) { struct dwarf_expr_baton *debaton = ctx->baton; return dwarf2_get_die_type (die_offset, debaton->per_cu); } /* See dwarf2loc.h. */ unsigned int entry_values_debug = 0; /* Helper to set entry_values_debug. */ static void show_entry_values_debug (struct ui_file *file, int from_tty, struct cmd_list_element *c, const char *value) { fprintf_filtered (file, _("Entry values and tail call frames debugging is %s.\n"), value); } /* Find DW_TAG_GNU_call_site's DW_AT_GNU_call_site_target address. CALLER_FRAME (for registers) can be NULL if it is not known. This function always returns valid address or it throws NO_ENTRY_VALUE_ERROR. */ static CORE_ADDR call_site_to_target_addr (struct gdbarch *call_site_gdbarch, struct call_site *call_site, struct frame_info *caller_frame) { switch (FIELD_LOC_KIND (call_site->target)) { case FIELD_LOC_KIND_DWARF_BLOCK: { struct dwarf2_locexpr_baton *dwarf_block; struct value *val; struct type *caller_core_addr_type; struct gdbarch *caller_arch; dwarf_block = FIELD_DWARF_BLOCK (call_site->target); if (dwarf_block == NULL) { struct bound_minimal_symbol msym; msym = lookup_minimal_symbol_by_pc (call_site->pc - 1); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_AT_GNU_call_site_target is not specified " "at %s in %s"), paddress (call_site_gdbarch, call_site->pc), (msym.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym.minsym))); } if (caller_frame == NULL) { struct bound_minimal_symbol msym; msym = lookup_minimal_symbol_by_pc (call_site->pc - 1); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_AT_GNU_call_site_target DWARF block resolving " "requires known frame which is currently not " "available at %s in %s"), paddress (call_site_gdbarch, call_site->pc), (msym.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym.minsym))); } caller_arch = get_frame_arch (caller_frame); caller_core_addr_type = builtin_type (caller_arch)->builtin_func_ptr; val = dwarf2_evaluate_loc_desc (caller_core_addr_type, caller_frame, dwarf_block->data, dwarf_block->size, dwarf_block->per_cu); /* DW_AT_GNU_call_site_target is a DWARF expression, not a DWARF location. */ if (VALUE_LVAL (val) == lval_memory) return value_address (val); else return value_as_address (val); } case FIELD_LOC_KIND_PHYSNAME: { const char *physname; struct minimal_symbol *msym; physname = FIELD_STATIC_PHYSNAME (call_site->target); /* Handle both the mangled and demangled PHYSNAME. */ msym = lookup_minimal_symbol (physname, NULL, NULL); if (msym == NULL) { msym = lookup_minimal_symbol_by_pc (call_site->pc - 1).minsym; throw_error (NO_ENTRY_VALUE_ERROR, _("Cannot find function \"%s\" for a call site target " "at %s in %s"), physname, paddress (call_site_gdbarch, call_site->pc), msym == NULL ? "???" : SYMBOL_PRINT_NAME (msym)); } return SYMBOL_VALUE_ADDRESS (msym); } case FIELD_LOC_KIND_PHYSADDR: return FIELD_STATIC_PHYSADDR (call_site->target); default: internal_error (__FILE__, __LINE__, _("invalid call site target kind")); } } /* Convert function entry point exact address ADDR to the function which is compliant with TAIL_CALL_LIST_COMPLETE condition. Throw NO_ENTRY_VALUE_ERROR otherwise. */ static struct symbol * func_addr_to_tail_call_list (struct gdbarch *gdbarch, CORE_ADDR addr) { struct symbol *sym = find_pc_function (addr); struct type *type; if (sym == NULL || BLOCK_START (SYMBOL_BLOCK_VALUE (sym)) != addr) throw_error (NO_ENTRY_VALUE_ERROR, _("DW_TAG_GNU_call_site resolving failed to find function " "name for address %s"), paddress (gdbarch, addr)); type = SYMBOL_TYPE (sym); gdb_assert (TYPE_CODE (type) == TYPE_CODE_FUNC); gdb_assert (TYPE_SPECIFIC_FIELD (type) == TYPE_SPECIFIC_FUNC); return sym; } /* Verify function with entry point exact address ADDR can never call itself via its tail calls (incl. transitively). Throw NO_ENTRY_VALUE_ERROR if it can call itself via tail calls. If a funtion can tail call itself its entry value based parameters are unreliable. There is no verification whether the value of some/all parameters is unchanged through the self tail call, we expect if there is a self tail call all the parameters can be modified. */ static void func_verify_no_selftailcall (struct gdbarch *gdbarch, CORE_ADDR verify_addr) { struct obstack addr_obstack; struct cleanup *old_chain; CORE_ADDR addr; /* Track here CORE_ADDRs which were already visited. */ htab_t addr_hash; /* The verification is completely unordered. Track here function addresses which still need to be iterated. */ VEC (CORE_ADDR) *todo = NULL; obstack_init (&addr_obstack); old_chain = make_cleanup_obstack_free (&addr_obstack); addr_hash = htab_create_alloc_ex (64, core_addr_hash, core_addr_eq, NULL, &addr_obstack, hashtab_obstack_allocate, NULL); make_cleanup_htab_delete (addr_hash); make_cleanup (VEC_cleanup (CORE_ADDR), &todo); VEC_safe_push (CORE_ADDR, todo, verify_addr); while (!VEC_empty (CORE_ADDR, todo)) { struct symbol *func_sym; struct call_site *call_site; addr = VEC_pop (CORE_ADDR, todo); func_sym = func_addr_to_tail_call_list (gdbarch, addr); for (call_site = TYPE_TAIL_CALL_LIST (SYMBOL_TYPE (func_sym)); call_site; call_site = call_site->tail_call_next) { CORE_ADDR target_addr; void **slot; /* CALLER_FRAME with registers is not available for tail-call jumped frames. */ target_addr = call_site_to_target_addr (gdbarch, call_site, NULL); if (target_addr == verify_addr) { struct bound_minimal_symbol msym; msym = lookup_minimal_symbol_by_pc (verify_addr); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_OP_GNU_entry_value resolving has found " "function \"%s\" at %s can call itself via tail " "calls"), (msym.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym.minsym)), paddress (gdbarch, verify_addr)); } slot = htab_find_slot (addr_hash, &target_addr, INSERT); if (*slot == NULL) { *slot = obstack_copy (&addr_obstack, &target_addr, sizeof (target_addr)); VEC_safe_push (CORE_ADDR, todo, target_addr); } } } do_cleanups (old_chain); } /* Print user readable form of CALL_SITE->PC to gdb_stdlog. Used only for ENTRY_VALUES_DEBUG. */ static void tailcall_dump (struct gdbarch *gdbarch, const struct call_site *call_site) { CORE_ADDR addr = call_site->pc; struct bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (addr - 1); fprintf_unfiltered (gdb_stdlog, " %s(%s)", paddress (gdbarch, addr), (msym.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym.minsym))); } /* vec.h needs single word type name, typedef it. */ typedef struct call_site *call_sitep; /* Define VEC (call_sitep) functions. */ DEF_VEC_P (call_sitep); /* Intersect RESULTP with CHAIN to keep RESULTP unambiguous, keep in RESULTP only top callers and bottom callees which are present in both. GDBARCH is used only for ENTRY_VALUES_DEBUG. RESULTP is NULL after return if there are no remaining possibilities to provide unambiguous non-trivial result. RESULTP should point to NULL on the first (initialization) call. Caller is responsible for xfree of any RESULTP data. */ static void chain_candidate (struct gdbarch *gdbarch, struct call_site_chain **resultp, VEC (call_sitep) *chain) { struct call_site_chain *result = *resultp; long length = VEC_length (call_sitep, chain); int callers, callees, idx; if (result == NULL) { /* Create the initial chain containing all the passed PCs. */ result = xmalloc (sizeof (*result) + sizeof (*result->call_site) * (length - 1)); result->length = length; result->callers = result->callees = length; if (!VEC_empty (call_sitep, chain)) memcpy (result->call_site, VEC_address (call_sitep, chain), sizeof (*result->call_site) * length); *resultp = result; if (entry_values_debug) { fprintf_unfiltered (gdb_stdlog, "tailcall: initial:"); for (idx = 0; idx < length; idx++) tailcall_dump (gdbarch, result->call_site[idx]); fputc_unfiltered ('\n', gdb_stdlog); } return; } if (entry_values_debug) { fprintf_unfiltered (gdb_stdlog, "tailcall: compare:"); for (idx = 0; idx < length; idx++) tailcall_dump (gdbarch, VEC_index (call_sitep, chain, idx)); fputc_unfiltered ('\n', gdb_stdlog); } /* Intersect callers. */ callers = min (result->callers, length); for (idx = 0; idx < callers; idx++) if (result->call_site[idx] != VEC_index (call_sitep, chain, idx)) { result->callers = idx; break; } /* Intersect callees. */ callees = min (result->callees, length); for (idx = 0; idx < callees; idx++) if (result->call_site[result->length - 1 - idx] != VEC_index (call_sitep, chain, length - 1 - idx)) { result->callees = idx; break; } if (entry_values_debug) { fprintf_unfiltered (gdb_stdlog, "tailcall: reduced:"); for (idx = 0; idx < result->callers; idx++) tailcall_dump (gdbarch, result->call_site[idx]); fputs_unfiltered (" |", gdb_stdlog); for (idx = 0; idx < result->callees; idx++) tailcall_dump (gdbarch, result->call_site[result->length - result->callees + idx]); fputc_unfiltered ('\n', gdb_stdlog); } if (result->callers == 0 && result->callees == 0) { /* There are no common callers or callees. It could be also a direct call (which has length 0) with ambiguous possibility of an indirect call - CALLERS == CALLEES == 0 is valid during the first allocation but any subsequence processing of such entry means ambiguity. */ xfree (result); *resultp = NULL; return; } /* See call_site_find_chain_1 why there is no way to reach the bottom callee PC again. In such case there must be two different code paths to reach it, therefore some of the former determined intermediate PCs must differ and the unambiguous chain gets shortened. */ gdb_assert (result->callers + result->callees < result->length); } /* Create and return call_site_chain for CALLER_PC and CALLEE_PC. All the assumed frames between them use GDBARCH. Use depth first search so we can keep single CHAIN of call_site's back to CALLER_PC. Function recursion would have needless GDB stack overhead. Caller is responsible for xfree of the returned result. Any unreliability results in thrown NO_ENTRY_VALUE_ERROR. */ static struct call_site_chain * call_site_find_chain_1 (struct gdbarch *gdbarch, CORE_ADDR caller_pc, CORE_ADDR callee_pc) { CORE_ADDR save_callee_pc = callee_pc; struct obstack addr_obstack; struct cleanup *back_to_retval, *back_to_workdata; struct call_site_chain *retval = NULL; struct call_site *call_site; /* Mark CALL_SITEs so we do not visit the same ones twice. */ htab_t addr_hash; /* CHAIN contains only the intermediate CALL_SITEs. Neither CALLER_PC's call_site nor any possible call_site at CALLEE_PC's function is there. Any CALL_SITE in CHAIN will be iterated to its siblings - via TAIL_CALL_NEXT. This is inappropriate for CALLER_PC's call_site. */ VEC (call_sitep) *chain = NULL; /* We are not interested in the specific PC inside the callee function. */ callee_pc = get_pc_function_start (callee_pc); if (callee_pc == 0) throw_error (NO_ENTRY_VALUE_ERROR, _("Unable to find function for PC %s"), paddress (gdbarch, save_callee_pc)); back_to_retval = make_cleanup (free_current_contents, &retval); obstack_init (&addr_obstack); back_to_workdata = make_cleanup_obstack_free (&addr_obstack); addr_hash = htab_create_alloc_ex (64, core_addr_hash, core_addr_eq, NULL, &addr_obstack, hashtab_obstack_allocate, NULL); make_cleanup_htab_delete (addr_hash); make_cleanup (VEC_cleanup (call_sitep), &chain); /* Do not push CALL_SITE to CHAIN. Push there only the first tail call site at the target's function. All the possible tail call sites in the target's function will get iterated as already pushed into CHAIN via their TAIL_CALL_NEXT. */ call_site = call_site_for_pc (gdbarch, caller_pc); while (call_site) { CORE_ADDR target_func_addr; struct call_site *target_call_site; /* CALLER_FRAME with registers is not available for tail-call jumped frames. */ target_func_addr = call_site_to_target_addr (gdbarch, call_site, NULL); if (target_func_addr == callee_pc) { chain_candidate (gdbarch, &retval, chain); if (retval == NULL) break; /* There is no way to reach CALLEE_PC again as we would prevent entering it twice as being already marked in ADDR_HASH. */ target_call_site = NULL; } else { struct symbol *target_func; target_func = func_addr_to_tail_call_list (gdbarch, target_func_addr); target_call_site = TYPE_TAIL_CALL_LIST (SYMBOL_TYPE (target_func)); } do { /* Attempt to visit TARGET_CALL_SITE. */ if (target_call_site) { void **slot; slot = htab_find_slot (addr_hash, &target_call_site->pc, INSERT); if (*slot == NULL) { /* Successfully entered TARGET_CALL_SITE. */ *slot = &target_call_site->pc; VEC_safe_push (call_sitep, chain, target_call_site); break; } } /* Backtrack (without revisiting the originating call_site). Try the callers's sibling; if there isn't any try the callers's callers's sibling etc. */ target_call_site = NULL; while (!VEC_empty (call_sitep, chain)) { call_site = VEC_pop (call_sitep, chain); gdb_assert (htab_find_slot (addr_hash, &call_site->pc, NO_INSERT) != NULL); htab_remove_elt (addr_hash, &call_site->pc); target_call_site = call_site->tail_call_next; if (target_call_site) break; } } while (target_call_site); if (VEC_empty (call_sitep, chain)) call_site = NULL; else call_site = VEC_last (call_sitep, chain); } if (retval == NULL) { struct bound_minimal_symbol msym_caller, msym_callee; msym_caller = lookup_minimal_symbol_by_pc (caller_pc); msym_callee = lookup_minimal_symbol_by_pc (callee_pc); throw_error (NO_ENTRY_VALUE_ERROR, _("There are no unambiguously determinable intermediate " "callers or callees between caller function \"%s\" at %s " "and callee function \"%s\" at %s"), (msym_caller.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym_caller.minsym)), paddress (gdbarch, caller_pc), (msym_callee.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym_callee.minsym)), paddress (gdbarch, callee_pc)); } do_cleanups (back_to_workdata); discard_cleanups (back_to_retval); return retval; } /* Create and return call_site_chain for CALLER_PC and CALLEE_PC. All the assumed frames between them use GDBARCH. If valid call_site_chain cannot be constructed return NULL. Caller is responsible for xfree of the returned result. */ struct call_site_chain * call_site_find_chain (struct gdbarch *gdbarch, CORE_ADDR caller_pc, CORE_ADDR callee_pc) { volatile struct gdb_exception e; struct call_site_chain *retval = NULL; TRY_CATCH (e, RETURN_MASK_ERROR) { retval = call_site_find_chain_1 (gdbarch, caller_pc, callee_pc); } if (e.reason < 0) { if (e.error == NO_ENTRY_VALUE_ERROR) { if (entry_values_debug) exception_print (gdb_stdout, e); return NULL; } else throw_exception (e); } return retval; } /* Return 1 if KIND and KIND_U match PARAMETER. Return 0 otherwise. */ static int call_site_parameter_matches (struct call_site_parameter *parameter, enum call_site_parameter_kind kind, union call_site_parameter_u kind_u) { if (kind == parameter->kind) switch (kind) { case CALL_SITE_PARAMETER_DWARF_REG: return kind_u.dwarf_reg == parameter->u.dwarf_reg; case CALL_SITE_PARAMETER_FB_OFFSET: return kind_u.fb_offset == parameter->u.fb_offset; case CALL_SITE_PARAMETER_PARAM_OFFSET: return kind_u.param_offset.cu_off == parameter->u.param_offset.cu_off; } return 0; } /* Fetch call_site_parameter from caller matching KIND and KIND_U. FRAME is for callee. Function always returns non-NULL, it throws NO_ENTRY_VALUE_ERROR otherwise. */ static struct call_site_parameter * dwarf_expr_reg_to_entry_parameter (struct frame_info *frame, enum call_site_parameter_kind kind, union call_site_parameter_u kind_u, struct dwarf2_per_cu_data **per_cu_return) { CORE_ADDR func_addr, caller_pc; struct gdbarch *gdbarch; struct frame_info *caller_frame; struct call_site *call_site; int iparams; /* Initialize it just to avoid a GCC false warning. */ struct call_site_parameter *parameter = NULL; CORE_ADDR target_addr; while (get_frame_type (frame) == INLINE_FRAME) { frame = get_prev_frame (frame); gdb_assert (frame != NULL); } func_addr = get_frame_func (frame); gdbarch = get_frame_arch (frame); caller_frame = get_prev_frame (frame); if (gdbarch != frame_unwind_arch (frame)) { struct bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (func_addr); struct gdbarch *caller_gdbarch = frame_unwind_arch (frame); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_OP_GNU_entry_value resolving callee gdbarch %s " "(of %s (%s)) does not match caller gdbarch %s"), gdbarch_bfd_arch_info (gdbarch)->printable_name, paddress (gdbarch, func_addr), (msym.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym.minsym)), gdbarch_bfd_arch_info (caller_gdbarch)->printable_name); } if (caller_frame == NULL) { struct bound_minimal_symbol msym = lookup_minimal_symbol_by_pc (func_addr); throw_error (NO_ENTRY_VALUE_ERROR, _("DW_OP_GNU_entry_value resolving " "requires caller of %s (%s)"), paddress (gdbarch, func_addr), (msym.minsym == NULL ? "???" : SYMBOL_PRINT_NAME (msym.minsym))); } caller_pc = get_frame_pc (caller_frame); call_site = call_site_for_pc (gdbarch, caller_pc); target_addr = call_site_to_target_addr (gdbarch, call_site, caller_frame); if (target_addr != func_addr) { struct minimal_symbol *target_msym, *func_msym; target_msym = lookup_minimal_symbol_by_pc (target_addr).minsym; func_msym = lookup_minimal_symbol_by_pc (func_addr).minsym; throw_error (NO_ENTRY_VALUE_ERROR, _("DW_OP_GNU_entry_value resolving expects callee %s at %s " "but the called frame is for %s at %s"), (target_msym == NULL ? "???" : SYMBOL_PRINT_NAME (target_msym)), paddress (gdbarch, target_addr), func_msym == NULL ? "???" : SYMBOL_PRINT_NAME (func_msym), paddress (gdbarch, func_addr)); } /* No entry value based parameters would be reliable if this function can call itself via tail calls. */ func_verify_no_selftailcall (gdbarch, func_addr); for (iparams = 0; iparams < call_site->parameter_count; iparams++) { parameter = &call_site->parameter[iparams]; if (call_site_parameter_matches (parameter, kind, kind_u)) break; } if (iparams == call_site->parameter_count) { struct minimal_symbol *msym = lookup_minimal_symbol_by_pc (caller_pc).minsym; /* DW_TAG_GNU_call_site_parameter will be missing just if GCC could not determine its value. */ throw_error (NO_ENTRY_VALUE_ERROR, _("Cannot find matching parameter " "at DW_TAG_GNU_call_site %s at %s"), paddress (gdbarch, caller_pc), msym == NULL ? "???" : SYMBOL_PRINT_NAME (msym)); } *per_cu_return = call_site->per_cu; return parameter; } /* Return value for PARAMETER matching DEREF_SIZE. If DEREF_SIZE is -1, return the normal DW_AT_GNU_call_site_value block. Otherwise return the DW_AT_GNU_call_site_data_value (dereferenced) block. TYPE and CALLER_FRAME specify how to evaluate the DWARF block into returned struct value. Function always returns non-NULL, non-optimized out value. It throws NO_ENTRY_VALUE_ERROR if it cannot resolve the value for any reason. */ static struct value * dwarf_entry_parameter_to_value (struct call_site_parameter *parameter, CORE_ADDR deref_size, struct type *type, struct frame_info *caller_frame, struct dwarf2_per_cu_data *per_cu) { const gdb_byte *data_src; gdb_byte *data; size_t size; data_src = deref_size == -1 ? parameter->value : parameter->data_value; size = deref_size == -1 ? parameter->value_size : parameter->data_value_size; /* DEREF_SIZE size is not verified here. */ if (data_src == NULL) throw_error (NO_ENTRY_VALUE_ERROR, _("Cannot resolve DW_AT_GNU_call_site_data_value")); /* DW_AT_GNU_call_site_value is a DWARF expression, not a DWARF location. Postprocessing of DWARF_VALUE_MEMORY would lose the type from DWARF block. */ data = alloca (size + 1); memcpy (data, data_src, size); data[size] = DW_OP_stack_value; return dwarf2_evaluate_loc_desc (type, caller_frame, data, size + 1, per_cu); } /* Execute DWARF block of call_site_parameter which matches KIND and KIND_U. Choose DEREF_SIZE value of that parameter. Search caller of the CTX's frame. CTX must be of dwarf_expr_ctx_funcs kind. The CTX caller can be from a different CU - per_cu_dwarf_call implementation can be more simple as it does not support cross-CU DWARF executions. */ static void dwarf_expr_push_dwarf_reg_entry_value (struct dwarf_expr_context *ctx, enum call_site_parameter_kind kind, union call_site_parameter_u kind_u, int deref_size) { struct dwarf_expr_baton *debaton; struct frame_info *frame, *caller_frame; struct dwarf2_per_cu_data *caller_per_cu; struct dwarf_expr_baton baton_local; struct dwarf_expr_context saved_ctx; struct call_site_parameter *parameter; const gdb_byte *data_src; size_t size; gdb_assert (ctx->funcs == &dwarf_expr_ctx_funcs); debaton = ctx->baton; frame = debaton->frame; caller_frame = get_prev_frame (frame); parameter = dwarf_expr_reg_to_entry_parameter (frame, kind, kind_u, &caller_per_cu); data_src = deref_size == -1 ? parameter->value : parameter->data_value; size = deref_size == -1 ? parameter->value_size : parameter->data_value_size; /* DEREF_SIZE size is not verified here. */ if (data_src == NULL) throw_error (NO_ENTRY_VALUE_ERROR, _("Cannot resolve DW_AT_GNU_call_site_data_value")); baton_local.frame = caller_frame; baton_local.per_cu = caller_per_cu; saved_ctx.gdbarch = ctx->gdbarch; saved_ctx.addr_size = ctx->addr_size; saved_ctx.offset = ctx->offset; saved_ctx.baton = ctx->baton; ctx->gdbarch = get_objfile_arch (dwarf2_per_cu_objfile (baton_local.per_cu)); ctx->addr_size = dwarf2_per_cu_addr_size (baton_local.per_cu); ctx->offset = dwarf2_per_cu_text_offset (baton_local.per_cu); ctx->baton = &baton_local; dwarf_expr_eval (ctx, data_src, size); ctx->gdbarch = saved_ctx.gdbarch; ctx->addr_size = saved_ctx.addr_size; ctx->offset = saved_ctx.offset; ctx->baton = saved_ctx.baton; } /* Callback function for dwarf2_evaluate_loc_desc. Fetch the address indexed by DW_OP_GNU_addr_index. */ static CORE_ADDR dwarf_expr_get_addr_index (void *baton, unsigned int index) { struct dwarf_expr_baton *debaton = (struct dwarf_expr_baton *) baton; return dwarf2_read_addr_index (debaton->per_cu, index); } /* VALUE must be of type lval_computed with entry_data_value_funcs. Perform the indirect method on it, that is use its stored target value, the sole purpose of entry_data_value_funcs.. */ static struct value * entry_data_value_coerce_ref (const struct value *value) { struct type *checked_type = check_typedef (value_type (value)); struct value *target_val; if (TYPE_CODE (checked_type) != TYPE_CODE_REF) return NULL; target_val = value_computed_closure (value); value_incref (target_val); return target_val; } /* Implement copy_closure. */ static void * entry_data_value_copy_closure (const struct value *v) { struct value *target_val = value_computed_closure (v); value_incref (target_val); return target_val; } /* Implement free_closure. */ static void entry_data_value_free_closure (struct value *v) { struct value *target_val = value_computed_closure (v); value_free (target_val); } /* Vector for methods for an entry value reference where the referenced value is stored in the caller. On the first dereference use DW_AT_GNU_call_site_data_value in the caller. */ static const struct lval_funcs entry_data_value_funcs = { NULL, /* read */ NULL, /* write */ NULL, /* check_validity */ NULL, /* check_any_valid */ NULL, /* indirect */ entry_data_value_coerce_ref, NULL, /* check_synthetic_pointer */ entry_data_value_copy_closure, entry_data_value_free_closure }; /* Read parameter of TYPE at (callee) FRAME's function entry. KIND and KIND_U are used to match DW_AT_location at the caller's DW_TAG_GNU_call_site_parameter. Function always returns non-NULL value. It throws NO_ENTRY_VALUE_ERROR if it cannot resolve the parameter for any reason. */ static struct value * value_of_dwarf_reg_entry (struct type *type, struct frame_info *frame, enum call_site_parameter_kind kind, union call_site_parameter_u kind_u) { struct type *checked_type = check_typedef (type); struct type *target_type = TYPE_TARGET_TYPE (checked_type); struct frame_info *caller_frame = get_prev_frame (frame); struct value *outer_val, *target_val, *val; struct call_site_parameter *parameter; struct dwarf2_per_cu_data *caller_per_cu; CORE_ADDR addr; parameter = dwarf_expr_reg_to_entry_parameter (frame, kind, kind_u, &caller_per_cu); outer_val = dwarf_entry_parameter_to_value (parameter, -1 /* deref_size */, type, caller_frame, caller_per_cu); /* Check if DW_AT_GNU_call_site_data_value cannot be used. If it should be used and it is not available do not fall back to OUTER_VAL - dereferencing TYPE_CODE_REF with non-entry data value would give current value - not the entry value. */ if (TYPE_CODE (checked_type) != TYPE_CODE_REF || TYPE_TARGET_TYPE (checked_type) == NULL) return outer_val; target_val = dwarf_entry_parameter_to_value (parameter, TYPE_LENGTH (target_type), target_type, caller_frame, caller_per_cu); /* value_as_address dereferences TYPE_CODE_REF. */ addr = extract_typed_address (value_contents (outer_val), checked_type); /* The target entry value has artificial address of the entry value reference. */ VALUE_LVAL (target_val) = lval_memory; set_value_address (target_val, addr); release_value (target_val); val = allocate_computed_value (type, &entry_data_value_funcs, target_val /* closure */); /* Copy the referencing pointer to the new computed value. */ memcpy (value_contents_raw (val), value_contents_raw (outer_val), TYPE_LENGTH (checked_type)); set_value_lazy (val, 0); return val; } /* Read parameter of TYPE at (callee) FRAME's function entry. DATA and SIZE are DWARF block used to match DW_AT_location at the caller's DW_TAG_GNU_call_site_parameter. Function always returns non-NULL value. It throws NO_ENTRY_VALUE_ERROR if it cannot resolve the parameter for any reason. */ static struct value * value_of_dwarf_block_entry (struct type *type, struct frame_info *frame, const gdb_byte *block, size_t block_len) { union call_site_parameter_u kind_u; kind_u.dwarf_reg = dwarf_block_to_dwarf_reg (block, block + block_len); if (kind_u.dwarf_reg != -1) return value_of_dwarf_reg_entry (type, frame, CALL_SITE_PARAMETER_DWARF_REG, kind_u); if (dwarf_block_to_fb_offset (block, block + block_len, &kind_u.fb_offset)) return value_of_dwarf_reg_entry (type, frame, CALL_SITE_PARAMETER_FB_OFFSET, kind_u); /* This can normally happen - throw NO_ENTRY_VALUE_ERROR to get the message suppressed during normal operation. The expression can be arbitrary if there is no caller-callee entry value binding expected. */ throw_error (NO_ENTRY_VALUE_ERROR, _("DWARF-2 expression error: DW_OP_GNU_entry_value is supported " "only for single DW_OP_reg* or for DW_OP_fbreg(*)")); } struct piece_closure { /* Reference count. */ int refc; /* The CU from which this closure's expression came. */ struct dwarf2_per_cu_data *per_cu; /* The number of pieces used to describe this variable. */ int n_pieces; /* The target address size, used only for DWARF_VALUE_STACK. */ int addr_size; /* The pieces themselves. */ struct dwarf_expr_piece *pieces; }; /* Allocate a closure for a value formed from separately-described PIECES. */ static struct piece_closure * allocate_piece_closure (struct dwarf2_per_cu_data *per_cu, int n_pieces, struct dwarf_expr_piece *pieces, int addr_size) { struct piece_closure *c = XZALLOC (struct piece_closure); int i; c->refc = 1; c->per_cu = per_cu; c->n_pieces = n_pieces; c->addr_size = addr_size; c->pieces = XCALLOC (n_pieces, struct dwarf_expr_piece); memcpy (c->pieces, pieces, n_pieces * sizeof (struct dwarf_expr_piece)); for (i = 0; i < n_pieces; ++i) if (c->pieces[i].location == DWARF_VALUE_STACK) value_incref (c->pieces[i].v.value); return c; } /* The lowest-level function to extract bits from a byte buffer. SOURCE is the buffer. It is updated if we read to the end of a byte. SOURCE_OFFSET_BITS is the offset of the first bit to read. It is updated to reflect the number of bits actually read. NBITS is the number of bits we want to read. It is updated to reflect the number of bits actually read. This function may read fewer bits. BITS_BIG_ENDIAN is taken directly from gdbarch. This function returns the extracted bits. */ static unsigned int extract_bits_primitive (const gdb_byte **source, unsigned int *source_offset_bits, int *nbits, int bits_big_endian) { unsigned int avail, mask, datum; gdb_assert (*source_offset_bits < 8); avail = 8 - *source_offset_bits; if (avail > *nbits) avail = *nbits; mask = (1 << avail) - 1; datum = **source; if (bits_big_endian) datum >>= 8 - (*source_offset_bits + *nbits); else datum >>= *source_offset_bits; datum &= mask; *nbits -= avail; *source_offset_bits += avail; if (*source_offset_bits >= 8) { *source_offset_bits -= 8; ++*source; } return datum; } /* Extract some bits from a source buffer and move forward in the buffer. SOURCE is the source buffer. It is updated as bytes are read. SOURCE_OFFSET_BITS is the offset into SOURCE. It is updated as bits are read. NBITS is the number of bits to read. BITS_BIG_ENDIAN is taken directly from gdbarch. This function returns the bits that were read. */ static unsigned int extract_bits (const gdb_byte **source, unsigned int *source_offset_bits, int nbits, int bits_big_endian) { unsigned int datum; gdb_assert (nbits > 0 && nbits <= 8); datum = extract_bits_primitive (source, source_offset_bits, &nbits, bits_big_endian); if (nbits > 0) { unsigned int more; more = extract_bits_primitive (source, source_offset_bits, &nbits, bits_big_endian); if (bits_big_endian) datum <<= nbits; else more <<= nbits; datum |= more; } return datum; } /* Write some bits into a buffer and move forward in the buffer. DATUM is the bits to write. The low-order bits of DATUM are used. DEST is the destination buffer. It is updated as bytes are written. DEST_OFFSET_BITS is the bit offset in DEST at which writing is done. NBITS is the number of valid bits in DATUM. BITS_BIG_ENDIAN is taken directly from gdbarch. */ static void insert_bits (unsigned int datum, gdb_byte *dest, unsigned int dest_offset_bits, int nbits, int bits_big_endian) { unsigned int mask; gdb_assert (dest_offset_bits + nbits <= 8); mask = (1 << nbits) - 1; if (bits_big_endian) { datum <<= 8 - (dest_offset_bits + nbits); mask <<= 8 - (dest_offset_bits + nbits); } else { datum <<= dest_offset_bits; mask <<= dest_offset_bits; } gdb_assert ((datum & ~mask) == 0); *dest = (*dest & ~mask) | datum; } /* Copy bits from a source to a destination. DEST is where the bits should be written. DEST_OFFSET_BITS is the bit offset into DEST. SOURCE is the source of bits. SOURCE_OFFSET_BITS is the bit offset into SOURCE. BIT_COUNT is the number of bits to copy. BITS_BIG_ENDIAN is taken directly from gdbarch. */ static void copy_bitwise (gdb_byte *dest, unsigned int dest_offset_bits, const gdb_byte *source, unsigned int source_offset_bits, unsigned int bit_count, int bits_big_endian) { unsigned int dest_avail; int datum; /* Reduce everything to byte-size pieces. */ dest += dest_offset_bits / 8; dest_offset_bits %= 8; source += source_offset_bits / 8; source_offset_bits %= 8; dest_avail = 8 - dest_offset_bits % 8; /* See if we can fill the first destination byte. */ if (dest_avail < bit_count) { datum = extract_bits (&source, &source_offset_bits, dest_avail, bits_big_endian); insert_bits (datum, dest, dest_offset_bits, dest_avail, bits_big_endian); ++dest; dest_offset_bits = 0; bit_count -= dest_avail; } /* Now, either DEST_OFFSET_BITS is byte-aligned, or we have fewer than 8 bits remaining. */ gdb_assert (dest_offset_bits % 8 == 0 || bit_count < 8); for (; bit_count >= 8; bit_count -= 8) { datum = extract_bits (&source, &source_offset_bits, 8, bits_big_endian); *dest++ = (gdb_byte) datum; } /* Finally, we may have a few leftover bits. */ gdb_assert (bit_count <= 8 - dest_offset_bits % 8); if (bit_count > 0) { datum = extract_bits (&source, &source_offset_bits, bit_count, bits_big_endian); insert_bits (datum, dest, dest_offset_bits, bit_count, bits_big_endian); } } static void read_pieced_value (struct value *v) { int i; long offset = 0; ULONGEST bits_to_skip; gdb_byte *contents; struct piece_closure *c = (struct piece_closure *) value_computed_closure (v); struct frame_info *frame = frame_find_by_id (VALUE_FRAME_ID (v)); size_t type_len; size_t buffer_size = 0; gdb_byte *buffer = NULL; struct cleanup *cleanup; int bits_big_endian = gdbarch_bits_big_endian (get_type_arch (value_type (v))); if (value_type (v) != value_enclosing_type (v)) internal_error (__FILE__, __LINE__, _("Should not be able to create a lazy value with " "an enclosing type")); cleanup = make_cleanup (free_current_contents, &buffer); contents = value_contents_raw (v); bits_to_skip = 8 * value_offset (v); if (value_bitsize (v)) { bits_to_skip += value_bitpos (v); type_len = value_bitsize (v); } else type_len = 8 * TYPE_LENGTH (value_type (v)); for (i = 0; i < c->n_pieces && offset < type_len; i++) { struct dwarf_expr_piece *p = &c->pieces[i]; size_t this_size, this_size_bits; long dest_offset_bits, source_offset_bits, source_offset; const gdb_byte *intermediate_buffer; /* Compute size, source, and destination offsets for copying, in bits. */ this_size_bits = p->size; if (bits_to_skip > 0 && bits_to_skip >= this_size_bits) { bits_to_skip -= this_size_bits; continue; } if (bits_to_skip > 0) { dest_offset_bits = 0; source_offset_bits = bits_to_skip; this_size_bits -= bits_to_skip; bits_to_skip = 0; } else { dest_offset_bits = offset; source_offset_bits = 0; } if (this_size_bits > type_len - offset) this_size_bits = type_len - offset; this_size = (this_size_bits + source_offset_bits % 8 + 7) / 8; source_offset = source_offset_bits / 8; if (buffer_size < this_size) { buffer_size = this_size; buffer = xrealloc (buffer, buffer_size); } intermediate_buffer = buffer; /* Copy from the source to DEST_BUFFER. */ switch (p->location) { case DWARF_VALUE_REGISTER: { struct gdbarch *arch = get_frame_arch (frame); int gdb_regnum = gdbarch_dwarf2_reg_to_regnum (arch, p->v.regno); int reg_offset = source_offset; if (gdbarch_byte_order (arch) == BFD_ENDIAN_BIG && this_size < register_size (arch, gdb_regnum)) { /* Big-endian, and we want less than full size. */ reg_offset = register_size (arch, gdb_regnum) - this_size; /* We want the lower-order THIS_SIZE_BITS of the bytes we extract from the register. */ source_offset_bits += 8 * this_size - this_size_bits; } if (gdb_regnum != -1) { int optim, unavail; if (!get_frame_register_bytes (frame, gdb_regnum, reg_offset, this_size, buffer, &optim, &unavail)) { /* Just so garbage doesn't ever shine through. */ memset (buffer, 0, this_size); if (optim) set_value_optimized_out (v, 1); if (unavail) mark_value_bits_unavailable (v, offset, this_size_bits); } } else { error (_("Unable to access DWARF register number %s"), paddress (arch, p->v.regno)); } } break; case DWARF_VALUE_MEMORY: read_value_memory (v, offset, p->v.mem.in_stack_memory, p->v.mem.addr + source_offset, buffer, this_size); break; case DWARF_VALUE_STACK: { size_t n = this_size; if (n > c->addr_size - source_offset) n = (c->addr_size >= source_offset ? c->addr_size - source_offset : 0); if (n == 0) { /* Nothing. */ } else { const gdb_byte *val_bytes = value_contents_all (p->v.value); intermediate_buffer = val_bytes + source_offset; } } break; case DWARF_VALUE_LITERAL: { size_t n = this_size; if (n > p->v.literal.length - source_offset) n = (p->v.literal.length >= source_offset ? p->v.literal.length - source_offset : 0); if (n != 0) intermediate_buffer = p->v.literal.data + source_offset; } break; /* These bits show up as zeros -- but do not cause the value to be considered optimized-out. */ case DWARF_VALUE_IMPLICIT_POINTER: break; case DWARF_VALUE_OPTIMIZED_OUT: set_value_optimized_out (v, 1); break; default: internal_error (__FILE__, __LINE__, _("invalid location type")); } if (p->location != DWARF_VALUE_OPTIMIZED_OUT && p->location != DWARF_VALUE_IMPLICIT_POINTER) copy_bitwise (contents, dest_offset_bits, intermediate_buffer, source_offset_bits % 8, this_size_bits, bits_big_endian); offset += this_size_bits; } do_cleanups (cleanup); } static void write_pieced_value (struct value *to, struct value *from) { int i; long offset = 0; ULONGEST bits_to_skip; const gdb_byte *contents; struct piece_closure *c = (struct piece_closure *) value_computed_closure (to); struct frame_info *frame = frame_find_by_id (VALUE_FRAME_ID (to)); size_t type_len; size_t buffer_size = 0; gdb_byte *buffer = NULL; struct cleanup *cleanup; int bits_big_endian = gdbarch_bits_big_endian (get_type_arch (value_type (to))); if (frame == NULL) { set_value_optimized_out (to, 1); return; } cleanup = make_cleanup (free_current_contents, &buffer); contents = value_contents (from); bits_to_skip = 8 * value_offset (to); if (value_bitsize (to)) { bits_to_skip += value_bitpos (to); type_len = value_bitsize (to); } else type_len = 8 * TYPE_LENGTH (value_type (to)); for (i = 0; i < c->n_pieces && offset < type_len; i++) { struct dwarf_expr_piece *p = &c->pieces[i]; size_t this_size_bits, this_size; long dest_offset_bits, source_offset_bits, dest_offset, source_offset; int need_bitwise; const gdb_byte *source_buffer; this_size_bits = p->size; if (bits_to_skip > 0 && bits_to_skip >= this_size_bits) { bits_to_skip -= this_size_bits; continue; } if (this_size_bits > type_len - offset) this_size_bits = type_len - offset; if (bits_to_skip > 0) { dest_offset_bits = bits_to_skip; source_offset_bits = 0; this_size_bits -= bits_to_skip; bits_to_skip = 0; } else { dest_offset_bits = 0; source_offset_bits = offset; } this_size = (this_size_bits + source_offset_bits % 8 + 7) / 8; source_offset = source_offset_bits / 8; dest_offset = dest_offset_bits / 8; if (dest_offset_bits % 8 == 0 && source_offset_bits % 8 == 0) { source_buffer = contents + source_offset; need_bitwise = 0; } else { if (buffer_size < this_size) { buffer_size = this_size; buffer = xrealloc (buffer, buffer_size); } source_buffer = buffer; need_bitwise = 1; } switch (p->location) { case DWARF_VALUE_REGISTER: { struct gdbarch *arch = get_frame_arch (frame); int gdb_regnum = gdbarch_dwarf2_reg_to_regnum (arch, p->v.regno); int reg_offset = dest_offset; if (gdbarch_byte_order (arch) == BFD_ENDIAN_BIG && this_size <= register_size (arch, gdb_regnum)) /* Big-endian, and we want less than full size. */ reg_offset = register_size (arch, gdb_regnum) - this_size; if (gdb_regnum != -1) { if (need_bitwise) { int optim, unavail; if (!get_frame_register_bytes (frame, gdb_regnum, reg_offset, this_size, buffer, &optim, &unavail)) { if (optim) throw_error (OPTIMIZED_OUT_ERROR, _("Can't do read-modify-write to " "update bitfield; containing word " "has been optimized out")); if (unavail) throw_error (NOT_AVAILABLE_ERROR, _("Can't do read-modify-write to update " "bitfield; containing word " "is unavailable")); } copy_bitwise (buffer, dest_offset_bits, contents, source_offset_bits, this_size_bits, bits_big_endian); } put_frame_register_bytes (frame, gdb_regnum, reg_offset, this_size, source_buffer); } else { error (_("Unable to write to DWARF register number %s"), paddress (arch, p->v.regno)); } } break; case DWARF_VALUE_MEMORY: if (need_bitwise) { /* Only the first and last bytes can possibly have any bits reused. */ read_memory (p->v.mem.addr + dest_offset, buffer, 1); read_memory (p->v.mem.addr + dest_offset + this_size - 1, buffer + this_size - 1, 1); copy_bitwise (buffer, dest_offset_bits, contents, source_offset_bits, this_size_bits, bits_big_endian); } write_memory (p->v.mem.addr + dest_offset, source_buffer, this_size); break; default: set_value_optimized_out (to, 1); break; } offset += this_size_bits; } do_cleanups (cleanup); } /* A helper function that checks bit validity in a pieced value. CHECK_FOR indicates the kind of validity checking. DWARF_VALUE_MEMORY means to check whether any bit is valid. DWARF_VALUE_OPTIMIZED_OUT means to check whether any bit is optimized out. DWARF_VALUE_IMPLICIT_POINTER means to check whether the bits are an implicit pointer. */ static int check_pieced_value_bits (const struct value *value, int bit_offset, int bit_length, enum dwarf_value_location check_for) { struct piece_closure *c = (struct piece_closure *) value_computed_closure (value); int i; int validity = (check_for == DWARF_VALUE_MEMORY || check_for == DWARF_VALUE_IMPLICIT_POINTER); bit_offset += 8 * value_offset (value); if (value_bitsize (value)) bit_offset += value_bitpos (value); for (i = 0; i < c->n_pieces && bit_length > 0; i++) { struct dwarf_expr_piece *p = &c->pieces[i]; size_t this_size_bits = p->size; if (bit_offset > 0) { if (bit_offset >= this_size_bits) { bit_offset -= this_size_bits; continue; } bit_length -= this_size_bits - bit_offset; bit_offset = 0; } else bit_length -= this_size_bits; if (check_for == DWARF_VALUE_IMPLICIT_POINTER) { if (p->location != DWARF_VALUE_IMPLICIT_POINTER) return 0; } else if (p->location == DWARF_VALUE_OPTIMIZED_OUT || p->location == DWARF_VALUE_IMPLICIT_POINTER) { if (validity) return 0; } else { if (!validity) return 1; } } return validity; } static int check_pieced_value_validity (const struct value *value, int bit_offset, int bit_length) { return check_pieced_value_bits (value, bit_offset, bit_length, DWARF_VALUE_MEMORY); } static int check_pieced_value_invalid (const struct value *value) { return check_pieced_value_bits (value, 0, 8 * TYPE_LENGTH (value_type (value)), DWARF_VALUE_OPTIMIZED_OUT); } /* An implementation of an lval_funcs method to see whether a value is a synthetic pointer. */ static int check_pieced_synthetic_pointer (const struct value *value, int bit_offset, int bit_length) { return check_pieced_value_bits (value, bit_offset, bit_length, DWARF_VALUE_IMPLICIT_POINTER); } /* A wrapper function for get_frame_address_in_block. */ static CORE_ADDR get_frame_address_in_block_wrapper (void *baton) { return get_frame_address_in_block (baton); } /* An implementation of an lval_funcs method to indirect through a pointer. This handles the synthetic pointer case when needed. */ static struct value * indirect_pieced_value (struct value *value) { struct piece_closure *c = (struct piece_closure *) value_computed_closure (value); struct type *type; struct frame_info *frame; struct dwarf2_locexpr_baton baton; int i, bit_offset, bit_length; struct dwarf_expr_piece *piece = NULL; LONGEST byte_offset; type = check_typedef (value_type (value)); if (TYPE_CODE (type) != TYPE_CODE_PTR) return NULL; bit_length = 8 * TYPE_LENGTH (type); bit_offset = 8 * value_offset (value); if (value_bitsize (value)) bit_offset += value_bitpos (value); for (i = 0; i < c->n_pieces && bit_length > 0; i++) { struct dwarf_expr_piece *p = &c->pieces[i]; size_t this_size_bits = p->size; if (bit_offset > 0) { if (bit_offset >= this_size_bits) { bit_offset -= this_size_bits; continue; } bit_length -= this_size_bits - bit_offset; bit_offset = 0; } else bit_length -= this_size_bits; if (p->location != DWARF_VALUE_IMPLICIT_POINTER) return NULL; if (bit_length != 0) error (_("Invalid use of DW_OP_GNU_implicit_pointer")); piece = p; break; } frame = get_selected_frame (_("No frame selected.")); /* This is an offset requested by GDB, such as value subscripts. However, due to how synthetic pointers are implemented, this is always presented to us as a pointer type. This means we have to sign-extend it manually as appropriate. */ byte_offset = value_as_address (value); if (TYPE_LENGTH (value_type (value)) < sizeof (LONGEST)) byte_offset = gdb_sign_extend (byte_offset, 8 * TYPE_LENGTH (value_type (value))); byte_offset += piece->v.ptr.offset; gdb_assert (piece); baton = dwarf2_fetch_die_loc_sect_off (piece->v.ptr.die, c->per_cu, get_frame_address_in_block_wrapper, frame); if (baton.data != NULL) return dwarf2_evaluate_loc_desc_full (TYPE_TARGET_TYPE (type), frame, baton.data, baton.size, baton.per_cu, byte_offset); { struct obstack temp_obstack; struct cleanup *cleanup; const gdb_byte *bytes; LONGEST len; struct value *result; obstack_init (&temp_obstack); cleanup = make_cleanup_obstack_free (&temp_obstack); bytes = dwarf2_fetch_constant_bytes (piece->v.ptr.die, c->per_cu, &temp_obstack, &len); if (bytes == NULL) result = allocate_optimized_out_value (TYPE_TARGET_TYPE (type)); else { if (byte_offset < 0 || byte_offset + TYPE_LENGTH (TYPE_TARGET_TYPE (type)) > len) invalid_synthetic_pointer (); bytes += byte_offset; result = value_from_contents (TYPE_TARGET_TYPE (type), bytes); } do_cleanups (cleanup); return result; } } static void * copy_pieced_value_closure (const struct value *v) { struct piece_closure *c = (struct piece_closure *) value_computed_closure (v); ++c->refc; return c; } static void free_pieced_value_closure (struct value *v) { struct piece_closure *c = (struct piece_closure *) value_computed_closure (v); --c->refc; if (c->refc == 0) { int i; for (i = 0; i < c->n_pieces; ++i) if (c->pieces[i].location == DWARF_VALUE_STACK) value_free (c->pieces[i].v.value); xfree (c->pieces); xfree (c); } } /* Functions for accessing a variable described by DW_OP_piece. */ static const struct lval_funcs pieced_value_funcs = { read_pieced_value, write_pieced_value, check_pieced_value_validity, check_pieced_value_invalid, indirect_pieced_value, NULL, /* coerce_ref */ check_pieced_synthetic_pointer, copy_pieced_value_closure, free_pieced_value_closure }; /* Virtual method table for dwarf2_evaluate_loc_desc_full below. */ static const struct dwarf_expr_context_funcs dwarf_expr_ctx_funcs = { dwarf_expr_read_addr_from_reg, dwarf_expr_get_reg_value, dwarf_expr_read_mem, dwarf_expr_frame_base, dwarf_expr_frame_cfa, dwarf_expr_frame_pc, dwarf_expr_tls_address, dwarf_expr_dwarf_call, dwarf_expr_get_base_type, dwarf_expr_push_dwarf_reg_entry_value, dwarf_expr_get_addr_index }; /* Evaluate a location description, starting at DATA and with length SIZE, to find the current location of variable of TYPE in the context of FRAME. BYTE_OFFSET is applied after the contents are computed. */ static struct value * dwarf2_evaluate_loc_desc_full (struct type *type, struct frame_info *frame, const gdb_byte *data, size_t size, struct dwarf2_per_cu_data *per_cu, LONGEST byte_offset) { struct value *retval; struct dwarf_expr_baton baton; struct dwarf_expr_context *ctx; struct cleanup *old_chain, *value_chain; struct objfile *objfile = dwarf2_per_cu_objfile (per_cu); volatile struct gdb_exception ex; if (byte_offset < 0) invalid_synthetic_pointer (); if (size == 0) return allocate_optimized_out_value (type); baton.frame = frame; baton.per_cu = per_cu; ctx = new_dwarf_expr_context (); old_chain = make_cleanup_free_dwarf_expr_context (ctx); value_chain = make_cleanup_value_free_to_mark (value_mark ()); ctx->gdbarch = get_objfile_arch (objfile); ctx->addr_size = dwarf2_per_cu_addr_size (per_cu); ctx->ref_addr_size = dwarf2_per_cu_ref_addr_size (per_cu); ctx->offset = dwarf2_per_cu_text_offset (per_cu); ctx->baton = &baton; ctx->funcs = &dwarf_expr_ctx_funcs; TRY_CATCH (ex, RETURN_MASK_ERROR) { dwarf_expr_eval (ctx, data, size); } if (ex.reason < 0) { if (ex.error == NOT_AVAILABLE_ERROR) { do_cleanups (old_chain); retval = allocate_value (type); mark_value_bytes_unavailable (retval, 0, TYPE_LENGTH (type)); return retval; } else if (ex.error == NO_ENTRY_VALUE_ERROR) { if (entry_values_debug) exception_print (gdb_stdout, ex); do_cleanups (old_chain); return allocate_optimized_out_value (type); } else throw_exception (ex); } if (ctx->num_pieces > 0) { struct piece_closure *c; struct frame_id frame_id = get_frame_id (frame); ULONGEST bit_size = 0; int i; for (i = 0; i < ctx->num_pieces; ++i) bit_size += ctx->pieces[i].size; if (8 * (byte_offset + TYPE_LENGTH (type)) > bit_size) invalid_synthetic_pointer (); c = allocate_piece_closure (per_cu, ctx->num_pieces, ctx->pieces, ctx->addr_size); /* We must clean up the value chain after creating the piece closure but before allocating the result. */ do_cleanups (value_chain); retval = allocate_computed_value (type, &pieced_value_funcs, c); VALUE_FRAME_ID (retval) = frame_id; set_value_offset (retval, byte_offset); } else { switch (ctx->location) { case DWARF_VALUE_REGISTER: { struct gdbarch *arch = get_frame_arch (frame); int dwarf_regnum = longest_to_int (value_as_long (dwarf_expr_fetch (ctx, 0))); int gdb_regnum = gdbarch_dwarf2_reg_to_regnum (arch, dwarf_regnum); if (byte_offset != 0) error (_("cannot use offset on synthetic pointer to register")); do_cleanups (value_chain); if (gdb_regnum == -1) error (_("Unable to access DWARF register number %d"), dwarf_regnum); retval = value_from_register (type, gdb_regnum, frame); if (value_optimized_out (retval)) { /* This means the register has undefined value / was not saved. As we're computing the location of some variable etc. in the program, not a value for inspecting a register ($pc, $sp, etc.), return a generic optimized out value instead, so that we show <optimized out> instead of <not saved>. */ do_cleanups (value_chain); retval = allocate_optimized_out_value (type); } } break; case DWARF_VALUE_MEMORY: { CORE_ADDR address = dwarf_expr_fetch_address (ctx, 0); int in_stack_memory = dwarf_expr_fetch_in_stack_memory (ctx, 0); do_cleanups (value_chain); retval = value_at_lazy (type, address + byte_offset); if (in_stack_memory) set_value_stack (retval, 1); } break; case DWARF_VALUE_STACK: { struct value *value = dwarf_expr_fetch (ctx, 0); gdb_byte *contents; const gdb_byte *val_bytes; size_t n = TYPE_LENGTH (value_type (value)); if (byte_offset + TYPE_LENGTH (type) > n) invalid_synthetic_pointer (); val_bytes = value_contents_all (value); val_bytes += byte_offset; n -= byte_offset; /* Preserve VALUE because we are going to free values back to the mark, but we still need the value contents below. */ value_incref (value); do_cleanups (value_chain); make_cleanup_value_free (value); retval = allocate_value (type); contents = value_contents_raw (retval); if (n > TYPE_LENGTH (type)) { struct gdbarch *objfile_gdbarch = get_objfile_arch (objfile); if (gdbarch_byte_order (objfile_gdbarch) == BFD_ENDIAN_BIG) val_bytes += n - TYPE_LENGTH (type); n = TYPE_LENGTH (type); } memcpy (contents, val_bytes, n); } break; case DWARF_VALUE_LITERAL: { bfd_byte *contents; const bfd_byte *ldata; size_t n = ctx->len; if (byte_offset + TYPE_LENGTH (type) > n) invalid_synthetic_pointer (); do_cleanups (value_chain); retval = allocate_value (type); contents = value_contents_raw (retval); ldata = ctx->data + byte_offset; n -= byte_offset; if (n > TYPE_LENGTH (type)) { struct gdbarch *objfile_gdbarch = get_objfile_arch (objfile); if (gdbarch_byte_order (objfile_gdbarch) == BFD_ENDIAN_BIG) ldata += n - TYPE_LENGTH (type); n = TYPE_LENGTH (type); } memcpy (contents, ldata, n); } break; case DWARF_VALUE_OPTIMIZED_OUT: do_cleanups (value_chain); retval = allocate_optimized_out_value (type); break; /* DWARF_VALUE_IMPLICIT_POINTER was converted to a pieced operation by execute_stack_op. */ case DWARF_VALUE_IMPLICIT_POINTER: /* DWARF_VALUE_OPTIMIZED_OUT can't occur in this context -- it can only be encountered when making a piece. */ default: internal_error (__FILE__, __LINE__, _("invalid location type")); } } set_value_initialized (retval, ctx->initialized); do_cleanups (old_chain); return retval; } /* The exported interface to dwarf2_evaluate_loc_desc_full; it always passes 0 as the byte_offset. */ struct value * dwarf2_evaluate_loc_desc (struct type *type, struct frame_info *frame, const gdb_byte *data, size_t size, struct dwarf2_per_cu_data *per_cu) { return dwarf2_evaluate_loc_desc_full (type, frame, data, size, per_cu, 0); } /* Helper functions and baton for dwarf2_loc_desc_needs_frame. */ struct needs_frame_baton { int needs_frame; struct dwarf2_per_cu_data *per_cu; }; /* Reads from registers do require a frame. */ static CORE_ADDR needs_frame_read_addr_from_reg (void *baton, int regnum) { struct needs_frame_baton *nf_baton = baton; nf_baton->needs_frame = 1; return 1; } /* struct dwarf_expr_context_funcs' "get_reg_value" callback: Reads from registers do require a frame. */ static struct value * needs_frame_get_reg_value (void *baton, struct type *type, int regnum) { struct needs_frame_baton *nf_baton = baton; nf_baton->needs_frame = 1; return value_zero (type, not_lval); } /* Reads from memory do not require a frame. */ static void needs_frame_read_mem (void *baton, gdb_byte *buf, CORE_ADDR addr, size_t len) { memset (buf, 0, len); } /* Frame-relative accesses do require a frame. */ static void needs_frame_frame_base (void *baton, const gdb_byte **start, size_t * length) { static gdb_byte lit0 = DW_OP_lit0; struct needs_frame_baton *nf_baton = baton; *start = &lit0; *length = 1; nf_baton->needs_frame = 1; } /* CFA accesses require a frame. */ static CORE_ADDR needs_frame_frame_cfa (void *baton) { struct needs_frame_baton *nf_baton = baton; nf_baton->needs_frame = 1; return 1; } /* Thread-local accesses do require a frame. */ static CORE_ADDR needs_frame_tls_address (void *baton, CORE_ADDR offset) { struct needs_frame_baton *nf_baton = baton; nf_baton->needs_frame = 1; return 1; } /* Helper interface of per_cu_dwarf_call for dwarf2_loc_desc_needs_frame. */ static void needs_frame_dwarf_call (struct dwarf_expr_context *ctx, cu_offset die_offset) { struct needs_frame_baton *nf_baton = ctx->baton; per_cu_dwarf_call (ctx, die_offset, nf_baton->per_cu, ctx->funcs->get_frame_pc, ctx->baton); } /* DW_OP_GNU_entry_value accesses require a caller, therefore a frame. */ static void needs_dwarf_reg_entry_value (struct dwarf_expr_context *ctx, enum call_site_parameter_kind kind, union call_site_parameter_u kind_u, int deref_size) { struct needs_frame_baton *nf_baton = ctx->baton; nf_baton->needs_frame = 1; /* The expression may require some stub values on DWARF stack. */ dwarf_expr_push_address (ctx, 0, 0); } /* DW_OP_GNU_addr_index doesn't require a frame. */ static CORE_ADDR needs_get_addr_index (void *baton, unsigned int index) { /* Nothing to do. */ return 1; } /* Virtual method table for dwarf2_loc_desc_needs_frame below. */ static const struct dwarf_expr_context_funcs needs_frame_ctx_funcs = { needs_frame_read_addr_from_reg, needs_frame_get_reg_value, needs_frame_read_mem, needs_frame_frame_base, needs_frame_frame_cfa, needs_frame_frame_cfa, /* get_frame_pc */ needs_frame_tls_address, needs_frame_dwarf_call, NULL, /* get_base_type */ needs_dwarf_reg_entry_value, needs_get_addr_index }; /* Return non-zero iff the location expression at DATA (length SIZE) requires a frame to evaluate. */ static int dwarf2_loc_desc_needs_frame (const gdb_byte *data, size_t size, struct dwarf2_per_cu_data *per_cu) { struct needs_frame_baton baton; struct dwarf_expr_context *ctx; int in_reg; struct cleanup *old_chain; struct objfile *objfile = dwarf2_per_cu_objfile (per_cu); baton.needs_frame = 0; baton.per_cu = per_cu; ctx = new_dwarf_expr_context (); old_chain = make_cleanup_free_dwarf_expr_context (ctx); make_cleanup_value_free_to_mark (value_mark ()); ctx->gdbarch = get_objfile_arch (objfile); ctx->addr_size = dwarf2_per_cu_addr_size (per_cu); ctx->ref_addr_size = dwarf2_per_cu_ref_addr_size (per_cu); ctx->offset = dwarf2_per_cu_text_offset (per_cu); ctx->baton = &baton; ctx->funcs = &needs_frame_ctx_funcs; dwarf_expr_eval (ctx, data, size); in_reg = ctx->location == DWARF_VALUE_REGISTER; if (ctx->num_pieces > 0) { int i; /* If the location has several pieces, and any of them are in registers, then we will need a frame to fetch them from. */ for (i = 0; i < ctx->num_pieces; i++) if (ctx->pieces[i].location == DWARF_VALUE_REGISTER) in_reg = 1; } do_cleanups (old_chain); return baton.needs_frame || in_reg; } /* A helper function that throws an unimplemented error mentioning a given DWARF operator. */ static void unimplemented (unsigned int op) { const char *name = get_DW_OP_name (op); if (name) error (_("DWARF operator %s cannot be translated to an agent expression"), name); else error (_("Unknown DWARF operator 0x%02x cannot be translated " "to an agent expression"), op); } /* A helper function to convert a DWARF register to an arch register. ARCH is the architecture. DWARF_REG is the register. This will throw an exception if the DWARF register cannot be translated to an architecture register. */ static int translate_register (struct gdbarch *arch, int dwarf_reg) { int reg = gdbarch_dwarf2_reg_to_regnum (arch, dwarf_reg); if (reg == -1) error (_("Unable to access DWARF register number %d"), dwarf_reg); return reg; } /* A helper function that emits an access to memory. ARCH is the target architecture. EXPR is the expression which we are building. NBITS is the number of bits we want to read. This emits the opcodes needed to read the memory and then extract the desired bits. */ static void access_memory (struct gdbarch *arch, struct agent_expr *expr, ULONGEST nbits) { ULONGEST nbytes = (nbits + 7) / 8; gdb_assert (nbytes > 0 && nbytes <= sizeof (LONGEST)); if (expr->tracing) ax_trace_quick (expr, nbytes); if (nbits <= 8) ax_simple (expr, aop_ref8); else if (nbits <= 16) ax_simple (expr, aop_ref16); else if (nbits <= 32) ax_simple (expr, aop_ref32); else ax_simple (expr, aop_ref64); /* If we read exactly the number of bytes we wanted, we're done. */ if (8 * nbytes == nbits) return; if (gdbarch_bits_big_endian (arch)) { /* On a bits-big-endian machine, we want the high-order NBITS. */ ax_const_l (expr, 8 * nbytes - nbits); ax_simple (expr, aop_rsh_unsigned); } else { /* On a bits-little-endian box, we want the low-order NBITS. */ ax_zero_ext (expr, nbits); } } /* A helper function to return the frame's PC. */ static CORE_ADDR get_ax_pc (void *baton) { struct agent_expr *expr = baton; return expr->scope; } /* Compile a DWARF location expression to an agent expression. EXPR is the agent expression we are building. LOC is the agent value we modify. ARCH is the architecture. ADDR_SIZE is the size of addresses, in bytes. OP_PTR is the start of the location expression. OP_END is one past the last byte of the location expression. This will throw an exception for various kinds of errors -- for example, if the expression cannot be compiled, or if the expression is invalid. */ void dwarf2_compile_expr_to_ax (struct agent_expr *expr, struct axs_value *loc, struct gdbarch *arch, unsigned int addr_size, const gdb_byte *op_ptr, const gdb_byte *op_end, struct dwarf2_per_cu_data *per_cu) { struct cleanup *cleanups; int i, *offsets; VEC(int) *dw_labels = NULL, *patches = NULL; const gdb_byte * const base = op_ptr; const gdb_byte *previous_piece = op_ptr; enum bfd_endian byte_order = gdbarch_byte_order (arch); ULONGEST bits_collected = 0; unsigned int addr_size_bits = 8 * addr_size; int bits_big_endian = gdbarch_bits_big_endian (arch); offsets = xmalloc ((op_end - op_ptr) * sizeof (int)); cleanups = make_cleanup (xfree, offsets); for (i = 0; i < op_end - op_ptr; ++i) offsets[i] = -1; make_cleanup (VEC_cleanup (int), &dw_labels); make_cleanup (VEC_cleanup (int), &patches); /* By default we are making an address. */ loc->kind = axs_lvalue_memory; while (op_ptr < op_end) { enum dwarf_location_atom op = *op_ptr; uint64_t uoffset, reg; int64_t offset; int i; offsets[op_ptr - base] = expr->len; ++op_ptr; /* Our basic approach to code generation is to map DWARF operations directly to AX operations. However, there are some differences. First, DWARF works on address-sized units, but AX always uses LONGEST. For most operations we simply ignore this difference; instead we generate sign extensions as needed before division and comparison operations. It would be nice to omit the sign extensions, but there is no way to determine the size of the target's LONGEST. (This code uses the size of the host LONGEST in some cases -- that is a bug but it is difficult to fix.) Second, some DWARF operations cannot be translated to AX. For these we simply fail. See http://sourceware.org/bugzilla/show_bug.cgi?id=11662. */ switch (op) { case DW_OP_lit0: case DW_OP_lit1: case DW_OP_lit2: case DW_OP_lit3: case DW_OP_lit4: case DW_OP_lit5: case DW_OP_lit6: case DW_OP_lit7: case DW_OP_lit8: case DW_OP_lit9: case DW_OP_lit10: case DW_OP_lit11: case DW_OP_lit12: case DW_OP_lit13: case DW_OP_lit14: case DW_OP_lit15: case DW_OP_lit16: case DW_OP_lit17: case DW_OP_lit18: case DW_OP_lit19: case DW_OP_lit20: case DW_OP_lit21: case DW_OP_lit22: case DW_OP_lit23: case DW_OP_lit24: case DW_OP_lit25: case DW_OP_lit26: case DW_OP_lit27: case DW_OP_lit28: case DW_OP_lit29: case DW_OP_lit30: case DW_OP_lit31: ax_const_l (expr, op - DW_OP_lit0); break; case DW_OP_addr: uoffset = extract_unsigned_integer (op_ptr, addr_size, byte_order); op_ptr += addr_size; /* Some versions of GCC emit DW_OP_addr before DW_OP_GNU_push_tls_address. In this case the value is an index, not an address. We don't support things like branching between the address and the TLS op. */ if (op_ptr >= op_end || *op_ptr != DW_OP_GNU_push_tls_address) uoffset += dwarf2_per_cu_text_offset (per_cu); ax_const_l (expr, uoffset); break; case DW_OP_const1u: ax_const_l (expr, extract_unsigned_integer (op_ptr, 1, byte_order)); op_ptr += 1; break; case DW_OP_const1s: ax_const_l (expr, extract_signed_integer (op_ptr, 1, byte_order)); op_ptr += 1; break; case DW_OP_const2u: ax_const_l (expr, extract_unsigned_integer (op_ptr, 2, byte_order)); op_ptr += 2; break; case DW_OP_const2s: ax_const_l (expr, extract_signed_integer (op_ptr, 2, byte_order)); op_ptr += 2; break; case DW_OP_const4u: ax_const_l (expr, extract_unsigned_integer (op_ptr, 4, byte_order)); op_ptr += 4; break; case DW_OP_const4s: ax_const_l (expr, extract_signed_integer (op_ptr, 4, byte_order)); op_ptr += 4; break; case DW_OP_const8u: ax_const_l (expr, extract_unsigned_integer (op_ptr, 8, byte_order)); op_ptr += 8; break; case DW_OP_const8s: ax_const_l (expr, extract_signed_integer (op_ptr, 8, byte_order)); op_ptr += 8; break; case DW_OP_constu: op_ptr = safe_read_uleb128 (op_ptr, op_end, &uoffset); ax_const_l (expr, uoffset); break; case DW_OP_consts: op_ptr = safe_read_sleb128 (op_ptr, op_end, &offset); ax_const_l (expr, offset); break; case DW_OP_reg0: case DW_OP_reg1: case DW_OP_reg2: case DW_OP_reg3: case DW_OP_reg4: case DW_OP_reg5: case DW_OP_reg6: case DW_OP_reg7: case DW_OP_reg8: case DW_OP_reg9: case DW_OP_reg10: case DW_OP_reg11: case DW_OP_reg12: case DW_OP_reg13: case DW_OP_reg14: case DW_OP_reg15: case DW_OP_reg16: case DW_OP_reg17: case DW_OP_reg18: case DW_OP_reg19: case DW_OP_reg20: case DW_OP_reg21: case DW_OP_reg22: case DW_OP_reg23: case DW_OP_reg24: case DW_OP_reg25: case DW_OP_reg26: case DW_OP_reg27: case DW_OP_reg28: case DW_OP_reg29: case DW_OP_reg30: case DW_OP_reg31: dwarf_expr_require_composition (op_ptr, op_end, "DW_OP_regx"); loc->u.reg = translate_register (arch, op - DW_OP_reg0); loc->kind = axs_lvalue_register; break; case DW_OP_regx: op_ptr = safe_read_uleb128 (op_ptr, op_end, &reg); dwarf_expr_require_composition (op_ptr, op_end, "DW_OP_regx"); loc->u.reg = translate_register (arch, reg); loc->kind = axs_lvalue_register; break; case DW_OP_implicit_value: { uint64_t len; op_ptr = safe_read_uleb128 (op_ptr, op_end, &len); if (op_ptr + len > op_end) error (_("DW_OP_implicit_value: too few bytes available.")); if (len > sizeof (ULONGEST)) error (_("Cannot translate DW_OP_implicit_value of %d bytes"), (int) len); ax_const_l (expr, extract_unsigned_integer (op_ptr, len, byte_order)); op_ptr += len; dwarf_expr_require_composition (op_ptr, op_end, "DW_OP_implicit_value"); loc->kind = axs_rvalue; } break; case DW_OP_stack_value: dwarf_expr_require_composition (op_ptr, op_end, "DW_OP_stack_value"); loc->kind = axs_rvalue; break; case DW_OP_breg0: case DW_OP_breg1: case DW_OP_breg2: case DW_OP_breg3: case DW_OP_breg4: case DW_OP_breg5: case DW_OP_breg6: case DW_OP_breg7: case DW_OP_breg8: case DW_OP_breg9: case DW_OP_breg10: case DW_OP_breg11: case DW_OP_breg12: case DW_OP_breg13: case DW_OP_breg14: case DW_OP_breg15: case DW_OP_breg16: case DW_OP_breg17: case DW_OP_breg18: case DW_OP_breg19: case DW_OP_breg20: case DW_OP_breg21: case DW_OP_breg22: case DW_OP_breg23: case DW_OP_breg24: case DW_OP_breg25: case DW_OP_breg26: case DW_OP_breg27: case DW_OP_breg28: case DW_OP_breg29: case DW_OP_breg30: case DW_OP_breg31: op_ptr = safe_read_sleb128 (op_ptr, op_end, &offset); i = translate_register (arch, op - DW_OP_breg0); ax_reg (expr, i); if (offset != 0) { ax_const_l (expr, offset); ax_simple (expr, aop_add); } break; case DW_OP_bregx: { op_ptr = safe_read_uleb128 (op_ptr, op_end, &reg); op_ptr = safe_read_sleb128 (op_ptr, op_end, &offset); i = translate_register (arch, reg); ax_reg (expr, i); if (offset != 0) { ax_const_l (expr, offset); ax_simple (expr, aop_add); } } break; case DW_OP_fbreg: { const gdb_byte *datastart; size_t datalen; struct block *b; struct symbol *framefunc; b = block_for_pc (expr->scope); if (!b) error (_("No block found for address")); framefunc = block_linkage_function (b); if (!framefunc) error (_("No function found for block")); dwarf_expr_frame_base_1 (framefunc, expr->scope, &datastart, &datalen); op_ptr = safe_read_sleb128 (op_ptr, op_end, &offset); dwarf2_compile_expr_to_ax (expr, loc, arch, addr_size, datastart, datastart + datalen, per_cu); if (loc->kind == axs_lvalue_register) require_rvalue (expr, loc); if (offset != 0) { ax_const_l (expr, offset); ax_simple (expr, aop_add); } loc->kind = axs_lvalue_memory; } break; case DW_OP_dup: ax_simple (expr, aop_dup); break; case DW_OP_drop: ax_simple (expr, aop_pop); break; case DW_OP_pick: offset = *op_ptr++; ax_pick (expr, offset); break; case DW_OP_swap: ax_simple (expr, aop_swap); break; case DW_OP_over: ax_pick (expr, 1); break; case DW_OP_rot: ax_simple (expr, aop_rot); break; case DW_OP_deref: case DW_OP_deref_size: { int size; if (op == DW_OP_deref_size) size = *op_ptr++; else size = addr_size; if (size != 1 && size != 2 && size != 4 && size != 8) error (_("Unsupported size %d in %s"), size, get_DW_OP_name (op)); access_memory (arch, expr, size * TARGET_CHAR_BIT); } break; case DW_OP_abs: /* Sign extend the operand. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_dup); ax_const_l (expr, 0); ax_simple (expr, aop_less_signed); ax_simple (expr, aop_log_not); i = ax_goto (expr, aop_if_goto); /* We have to emit 0 - X. */ ax_const_l (expr, 0); ax_simple (expr, aop_swap); ax_simple (expr, aop_sub); ax_label (expr, i, expr->len); break; case DW_OP_neg: /* No need to sign extend here. */ ax_const_l (expr, 0); ax_simple (expr, aop_swap); ax_simple (expr, aop_sub); break; case DW_OP_not: /* Sign extend the operand. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_bit_not); break; case DW_OP_plus_uconst: op_ptr = safe_read_uleb128 (op_ptr, op_end, &reg); /* It would be really weird to emit `DW_OP_plus_uconst 0', but we micro-optimize anyhow. */ if (reg != 0) { ax_const_l (expr, reg); ax_simple (expr, aop_add); } break; case DW_OP_and: ax_simple (expr, aop_bit_and); break; case DW_OP_div: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_simple (expr, aop_div_signed); break; case DW_OP_minus: ax_simple (expr, aop_sub); break; case DW_OP_mod: ax_simple (expr, aop_rem_unsigned); break; case DW_OP_mul: ax_simple (expr, aop_mul); break; case DW_OP_or: ax_simple (expr, aop_bit_or); break; case DW_OP_plus: ax_simple (expr, aop_add); break; case DW_OP_shl: ax_simple (expr, aop_lsh); break; case DW_OP_shr: ax_simple (expr, aop_rsh_unsigned); break; case DW_OP_shra: ax_simple (expr, aop_rsh_signed); break; case DW_OP_xor: ax_simple (expr, aop_bit_xor); break; case DW_OP_le: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); /* Note no swap here: A <= B is !(B < A). */ ax_simple (expr, aop_less_signed); ax_simple (expr, aop_log_not); break; case DW_OP_ge: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); /* A >= B is !(A < B). */ ax_simple (expr, aop_less_signed); ax_simple (expr, aop_log_not); break; case DW_OP_eq: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); /* No need for a second swap here. */ ax_simple (expr, aop_equal); break; case DW_OP_lt: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_simple (expr, aop_less_signed); break; case DW_OP_gt: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); /* Note no swap here: A > B is B < A. */ ax_simple (expr, aop_less_signed); break; case DW_OP_ne: /* Sign extend the operands. */ ax_ext (expr, addr_size_bits); ax_simple (expr, aop_swap); ax_ext (expr, addr_size_bits); /* No need for a swap here. */ ax_simple (expr, aop_equal); ax_simple (expr, aop_log_not); break; case DW_OP_call_frame_cfa: dwarf2_compile_cfa_to_ax (expr, loc, arch, expr->scope, per_cu); loc->kind = axs_lvalue_memory; break; case DW_OP_GNU_push_tls_address: unimplemented (op); break; case DW_OP_skip: offset = extract_signed_integer (op_ptr, 2, byte_order); op_ptr += 2; i = ax_goto (expr, aop_goto); VEC_safe_push (int, dw_labels, op_ptr + offset - base); VEC_safe_push (int, patches, i); break; case DW_OP_bra: offset = extract_signed_integer (op_ptr, 2, byte_order); op_ptr += 2; /* Zero extend the operand. */ ax_zero_ext (expr, addr_size_bits); i = ax_goto (expr, aop_if_goto); VEC_safe_push (int, dw_labels, op_ptr + offset - base); VEC_safe_push (int, patches, i); break; case DW_OP_nop: break; case DW_OP_piece: case DW_OP_bit_piece: { uint64_t size, offset; if (op_ptr - 1 == previous_piece) error (_("Cannot translate empty pieces to agent expressions")); previous_piece = op_ptr - 1; op_ptr = safe_read_uleb128 (op_ptr, op_end, &size); if (op == DW_OP_piece) { size *= 8; offset = 0; } else op_ptr = safe_read_uleb128 (op_ptr, op_end, &offset); if (bits_collected + size > 8 * sizeof (LONGEST)) error (_("Expression pieces exceed word size")); /* Access the bits. */ switch (loc->kind) { case axs_lvalue_register: ax_reg (expr, loc->u.reg); break; case axs_lvalue_memory: /* Offset the pointer, if needed. */ if (offset > 8) { ax_const_l (expr, offset / 8); ax_simple (expr, aop_add); offset %= 8; } access_memory (arch, expr, size); break; } /* For a bits-big-endian target, shift up what we already have. For a bits-little-endian target, shift up the new data. Note that there is a potential bug here if the DWARF expression leaves multiple values on the stack. */ if (bits_collected > 0) { if (bits_big_endian) { ax_simple (expr, aop_swap); ax_const_l (expr, size); ax_simple (expr, aop_lsh); /* We don't need a second swap here, because aop_bit_or is symmetric. */ } else { ax_const_l (expr, size); ax_simple (expr, aop_lsh); } ax_simple (expr, aop_bit_or); } bits_collected += size; loc->kind = axs_rvalue; } break; case DW_OP_GNU_uninit: unimplemented (op); case DW_OP_call2: case DW_OP_call4: { struct dwarf2_locexpr_baton block; int size = (op == DW_OP_call2 ? 2 : 4); cu_offset offset; uoffset = extract_unsigned_integer (op_ptr, size, byte_order); op_ptr += size; offset.cu_off = uoffset; block = dwarf2_fetch_die_loc_cu_off (offset, per_cu, get_ax_pc, expr); /* DW_OP_call_ref is currently not supported. */ gdb_assert (block.per_cu == per_cu); dwarf2_compile_expr_to_ax (expr, loc, arch, addr_size, block.data, block.data + block.size, per_cu); } break; case DW_OP_call_ref: unimplemented (op); default: unimplemented (op); } } /* Patch all the branches we emitted. */ for (i = 0; i < VEC_length (int, patches); ++i) { int targ = offsets[VEC_index (int, dw_labels, i)]; if (targ == -1) internal_error (__FILE__, __LINE__, _("invalid label")); ax_label (expr, VEC_index (int, patches, i), targ); } do_cleanups (cleanups); } /* Return the value of SYMBOL in FRAME using the DWARF-2 expression evaluator to calculate the location. */ static struct value * locexpr_read_variable (struct symbol *symbol, struct frame_info *frame) { struct dwarf2_locexpr_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); struct value *val; val = dwarf2_evaluate_loc_desc (SYMBOL_TYPE (symbol), frame, dlbaton->data, dlbaton->size, dlbaton->per_cu); return val; } /* Return the value of SYMBOL in FRAME at (callee) FRAME's function entry. SYMBOL should be a function parameter, otherwise NO_ENTRY_VALUE_ERROR will be thrown. */ static struct value * locexpr_read_variable_at_entry (struct symbol *symbol, struct frame_info *frame) { struct dwarf2_locexpr_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); return value_of_dwarf_block_entry (SYMBOL_TYPE (symbol), frame, dlbaton->data, dlbaton->size); } /* Return non-zero iff we need a frame to evaluate SYMBOL. */ static int locexpr_read_needs_frame (struct symbol *symbol) { struct dwarf2_locexpr_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); return dwarf2_loc_desc_needs_frame (dlbaton->data, dlbaton->size, dlbaton->per_cu); } /* Return true if DATA points to the end of a piece. END is one past the last byte in the expression. */ static int piece_end_p (const gdb_byte *data, const gdb_byte *end) { return data == end || data[0] == DW_OP_piece || data[0] == DW_OP_bit_piece; } /* Helper for locexpr_describe_location_piece that finds the name of a DWARF register. */ static const char * locexpr_regname (struct gdbarch *gdbarch, int dwarf_regnum) { int regnum; regnum = gdbarch_dwarf2_reg_to_regnum (gdbarch, dwarf_regnum); return gdbarch_register_name (gdbarch, regnum); } /* Nicely describe a single piece of a location, returning an updated position in the bytecode sequence. This function cannot recognize all locations; if a location is not recognized, it simply returns DATA. If there is an error during reading, e.g. we run off the end of the buffer, an error is thrown. */ static const gdb_byte * locexpr_describe_location_piece (struct symbol *symbol, struct ui_file *stream, CORE_ADDR addr, struct objfile *objfile, struct dwarf2_per_cu_data *per_cu, const gdb_byte *data, const gdb_byte *end, unsigned int addr_size) { struct gdbarch *gdbarch = get_objfile_arch (objfile); size_t leb128_size; if (data[0] >= DW_OP_reg0 && data[0] <= DW_OP_reg31) { fprintf_filtered (stream, _("a variable in $%s"), locexpr_regname (gdbarch, data[0] - DW_OP_reg0)); data += 1; } else if (data[0] == DW_OP_regx) { uint64_t reg; data = safe_read_uleb128 (data + 1, end, &reg); fprintf_filtered (stream, _("a variable in $%s"), locexpr_regname (gdbarch, reg)); } else if (data[0] == DW_OP_fbreg) { struct block *b; struct symbol *framefunc; int frame_reg = 0; int64_t frame_offset; const gdb_byte *base_data, *new_data, *save_data = data; size_t base_size; int64_t base_offset = 0; new_data = safe_read_sleb128 (data + 1, end, &frame_offset); if (!piece_end_p (new_data, end)) return data; data = new_data; b = block_for_pc (addr); if (!b) error (_("No block found for address for symbol \"%s\"."), SYMBOL_PRINT_NAME (symbol)); framefunc = block_linkage_function (b); if (!framefunc) error (_("No function found for block for symbol \"%s\"."), SYMBOL_PRINT_NAME (symbol)); dwarf_expr_frame_base_1 (framefunc, addr, &base_data, &base_size); if (base_data[0] >= DW_OP_breg0 && base_data[0] <= DW_OP_breg31) { const gdb_byte *buf_end; frame_reg = base_data[0] - DW_OP_breg0; buf_end = safe_read_sleb128 (base_data + 1, base_data + base_size, &base_offset); if (buf_end != base_data + base_size) error (_("Unexpected opcode after " "DW_OP_breg%u for symbol \"%s\"."), frame_reg, SYMBOL_PRINT_NAME (symbol)); } else if (base_data[0] >= DW_OP_reg0 && base_data[0] <= DW_OP_reg31) { /* The frame base is just the register, with no offset. */ frame_reg = base_data[0] - DW_OP_reg0; base_offset = 0; } else { /* We don't know what to do with the frame base expression, so we can't trace this variable; give up. */ return save_data; } fprintf_filtered (stream, _("a variable at frame base reg $%s offset %s+%s"), locexpr_regname (gdbarch, frame_reg), plongest (base_offset), plongest (frame_offset)); } else if (data[0] >= DW_OP_breg0 && data[0] <= DW_OP_breg31 && piece_end_p (data, end)) { int64_t offset; data = safe_read_sleb128 (data + 1, end, &offset); fprintf_filtered (stream, _("a variable at offset %s from base reg $%s"), plongest (offset), locexpr_regname (gdbarch, data[0] - DW_OP_breg0)); } /* The location expression for a TLS variable looks like this (on a 64-bit LE machine): DW_AT_location : 10 byte block: 3 4 0 0 0 0 0 0 0 e0 (DW_OP_addr: 4; DW_OP_GNU_push_tls_address) 0x3 is the encoding for DW_OP_addr, which has an operand as long as the size of an address on the target machine (here is 8 bytes). Note that more recent version of GCC emit DW_OP_const4u or DW_OP_const8u, depending on address size, rather than DW_OP_addr. 0xe0 is the encoding for DW_OP_GNU_push_tls_address. The operand represents the offset at which the variable is within the thread local storage. */ else if (data + 1 + addr_size < end && (data[0] == DW_OP_addr || (addr_size == 4 && data[0] == DW_OP_const4u) || (addr_size == 8 && data[0] == DW_OP_const8u)) && data[1 + addr_size] == DW_OP_GNU_push_tls_address && piece_end_p (data + 2 + addr_size, end)) { ULONGEST offset; offset = extract_unsigned_integer (data + 1, addr_size, gdbarch_byte_order (gdbarch)); fprintf_filtered (stream, _("a thread-local variable at offset 0x%s " "in the thread-local storage for `%s'"), phex_nz (offset, addr_size), objfile_name (objfile)); data += 1 + addr_size + 1; } /* With -gsplit-dwarf a TLS variable can also look like this: DW_AT_location : 3 byte block: fc 4 e0 (DW_OP_GNU_const_index: 4; DW_OP_GNU_push_tls_address) */ else if (data + 3 <= end && data + 1 + (leb128_size = skip_leb128 (data + 1, end)) < end && data[0] == DW_OP_GNU_const_index && leb128_size > 0 && data[1 + leb128_size] == DW_OP_GNU_push_tls_address && piece_end_p (data + 2 + leb128_size, end)) { uint64_t offset; data = safe_read_uleb128 (data + 1, end, &offset); offset = dwarf2_read_addr_index (per_cu, offset); fprintf_filtered (stream, _("a thread-local variable at offset 0x%s " "in the thread-local storage for `%s'"), phex_nz (offset, addr_size), objfile_name (objfile)); ++data; } else if (data[0] >= DW_OP_lit0 && data[0] <= DW_OP_lit31 && data + 1 < end && data[1] == DW_OP_stack_value) { fprintf_filtered (stream, _("the constant %d"), data[0] - DW_OP_lit0); data += 2; } return data; } /* Disassemble an expression, stopping at the end of a piece or at the end of the expression. Returns a pointer to the next unread byte in the input expression. If ALL is nonzero, then this function will keep going until it reaches the end of the expression. If there is an error during reading, e.g. we run off the end of the buffer, an error is thrown. */ static const gdb_byte * disassemble_dwarf_expression (struct ui_file *stream, struct gdbarch *arch, unsigned int addr_size, int offset_size, const gdb_byte *start, const gdb_byte *data, const gdb_byte *end, int indent, int all, struct dwarf2_per_cu_data *per_cu) { while (data < end && (all || (data[0] != DW_OP_piece && data[0] != DW_OP_bit_piece))) { enum dwarf_location_atom op = *data++; uint64_t ul; int64_t l; const char *name; name = get_DW_OP_name (op); if (!name) error (_("Unrecognized DWARF opcode 0x%02x at %ld"), op, (long) (data - 1 - start)); fprintf_filtered (stream, " %*ld: %s", indent + 4, (long) (data - 1 - start), name); switch (op) { case DW_OP_addr: ul = extract_unsigned_integer (data, addr_size, gdbarch_byte_order (arch)); data += addr_size; fprintf_filtered (stream, " 0x%s", phex_nz (ul, addr_size)); break; case DW_OP_const1u: ul = extract_unsigned_integer (data, 1, gdbarch_byte_order (arch)); data += 1; fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_const1s: l = extract_signed_integer (data, 1, gdbarch_byte_order (arch)); data += 1; fprintf_filtered (stream, " %s", plongest (l)); break; case DW_OP_const2u: ul = extract_unsigned_integer (data, 2, gdbarch_byte_order (arch)); data += 2; fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_const2s: l = extract_signed_integer (data, 2, gdbarch_byte_order (arch)); data += 2; fprintf_filtered (stream, " %s", plongest (l)); break; case DW_OP_const4u: ul = extract_unsigned_integer (data, 4, gdbarch_byte_order (arch)); data += 4; fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_const4s: l = extract_signed_integer (data, 4, gdbarch_byte_order (arch)); data += 4; fprintf_filtered (stream, " %s", plongest (l)); break; case DW_OP_const8u: ul = extract_unsigned_integer (data, 8, gdbarch_byte_order (arch)); data += 8; fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_const8s: l = extract_signed_integer (data, 8, gdbarch_byte_order (arch)); data += 8; fprintf_filtered (stream, " %s", plongest (l)); break; case DW_OP_constu: data = safe_read_uleb128 (data, end, &ul); fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_consts: data = safe_read_sleb128 (data, end, &l); fprintf_filtered (stream, " %s", plongest (l)); break; case DW_OP_reg0: case DW_OP_reg1: case DW_OP_reg2: case DW_OP_reg3: case DW_OP_reg4: case DW_OP_reg5: case DW_OP_reg6: case DW_OP_reg7: case DW_OP_reg8: case DW_OP_reg9: case DW_OP_reg10: case DW_OP_reg11: case DW_OP_reg12: case DW_OP_reg13: case DW_OP_reg14: case DW_OP_reg15: case DW_OP_reg16: case DW_OP_reg17: case DW_OP_reg18: case DW_OP_reg19: case DW_OP_reg20: case DW_OP_reg21: case DW_OP_reg22: case DW_OP_reg23: case DW_OP_reg24: case DW_OP_reg25: case DW_OP_reg26: case DW_OP_reg27: case DW_OP_reg28: case DW_OP_reg29: case DW_OP_reg30: case DW_OP_reg31: fprintf_filtered (stream, " [$%s]", locexpr_regname (arch, op - DW_OP_reg0)); break; case DW_OP_regx: data = safe_read_uleb128 (data, end, &ul); fprintf_filtered (stream, " %s [$%s]", pulongest (ul), locexpr_regname (arch, (int) ul)); break; case DW_OP_implicit_value: data = safe_read_uleb128 (data, end, &ul); data += ul; fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_breg0: case DW_OP_breg1: case DW_OP_breg2: case DW_OP_breg3: case DW_OP_breg4: case DW_OP_breg5: case DW_OP_breg6: case DW_OP_breg7: case DW_OP_breg8: case DW_OP_breg9: case DW_OP_breg10: case DW_OP_breg11: case DW_OP_breg12: case DW_OP_breg13: case DW_OP_breg14: case DW_OP_breg15: case DW_OP_breg16: case DW_OP_breg17: case DW_OP_breg18: case DW_OP_breg19: case DW_OP_breg20: case DW_OP_breg21: case DW_OP_breg22: case DW_OP_breg23: case DW_OP_breg24: case DW_OP_breg25: case DW_OP_breg26: case DW_OP_breg27: case DW_OP_breg28: case DW_OP_breg29: case DW_OP_breg30: case DW_OP_breg31: data = safe_read_sleb128 (data, end, &l); fprintf_filtered (stream, " %s [$%s]", plongest (l), locexpr_regname (arch, op - DW_OP_breg0)); break; case DW_OP_bregx: data = safe_read_uleb128 (data, end, &ul); data = safe_read_sleb128 (data, end, &l); fprintf_filtered (stream, " register %s [$%s] offset %s", pulongest (ul), locexpr_regname (arch, (int) ul), plongest (l)); break; case DW_OP_fbreg: data = safe_read_sleb128 (data, end, &l); fprintf_filtered (stream, " %s", plongest (l)); break; case DW_OP_xderef_size: case DW_OP_deref_size: case DW_OP_pick: fprintf_filtered (stream, " %d", *data); ++data; break; case DW_OP_plus_uconst: data = safe_read_uleb128 (data, end, &ul); fprintf_filtered (stream, " %s", pulongest (ul)); break; case DW_OP_skip: l = extract_signed_integer (data, 2, gdbarch_byte_order (arch)); data += 2; fprintf_filtered (stream, " to %ld", (long) (data + l - start)); break; case DW_OP_bra: l = extract_signed_integer (data, 2, gdbarch_byte_order (arch)); data += 2; fprintf_filtered (stream, " %ld", (long) (data + l - start)); break; case DW_OP_call2: ul = extract_unsigned_integer (data, 2, gdbarch_byte_order (arch)); data += 2; fprintf_filtered (stream, " offset %s", phex_nz (ul, 2)); break; case DW_OP_call4: ul = extract_unsigned_integer (data, 4, gdbarch_byte_order (arch)); data += 4; fprintf_filtered (stream, " offset %s", phex_nz (ul, 4)); break; case DW_OP_call_ref: ul = extract_unsigned_integer (data, offset_size, gdbarch_byte_order (arch)); data += offset_size; fprintf_filtered (stream, " offset %s", phex_nz (ul, offset_size)); break; case DW_OP_piece: data = safe_read_uleb128 (data, end, &ul); fprintf_filtered (stream, " %s (bytes)", pulongest (ul)); break; case DW_OP_bit_piece: { uint64_t offset; data = safe_read_uleb128 (data, end, &ul); data = safe_read_uleb128 (data, end, &offset); fprintf_filtered (stream, " size %s offset %s (bits)", pulongest (ul), pulongest (offset)); } break; case DW_OP_GNU_implicit_pointer: { ul = extract_unsigned_integer (data, offset_size, gdbarch_byte_order (arch)); data += offset_size; data = safe_read_sleb128 (data, end, &l); fprintf_filtered (stream, " DIE %s offset %s", phex_nz (ul, offset_size), plongest (l)); } break; case DW_OP_GNU_deref_type: { int addr_size = *data++; cu_offset offset; struct type *type; data = safe_read_uleb128 (data, end, &ul); offset.cu_off = ul; type = dwarf2_get_die_type (offset, per_cu); fprintf_filtered (stream, "<"); type_print (type, "", stream, -1); fprintf_filtered (stream, " [0x%s]> %d", phex_nz (offset.cu_off, 0), addr_size); } break; case DW_OP_GNU_const_type: { cu_offset type_die; struct type *type; data = safe_read_uleb128 (data, end, &ul); type_die.cu_off = ul; type = dwarf2_get_die_type (type_die, per_cu); fprintf_filtered (stream, "<"); type_print (type, "", stream, -1); fprintf_filtered (stream, " [0x%s]>", phex_nz (type_die.cu_off, 0)); } break; case DW_OP_GNU_regval_type: { uint64_t reg; cu_offset type_die; struct type *type; data = safe_read_uleb128 (data, end, &reg); data = safe_read_uleb128 (data, end, &ul); type_die.cu_off = ul; type = dwarf2_get_die_type (type_die, per_cu); fprintf_filtered (stream, "<"); type_print (type, "", stream, -1); fprintf_filtered (stream, " [0x%s]> [$%s]", phex_nz (type_die.cu_off, 0), locexpr_regname (arch, reg)); } break; case DW_OP_GNU_convert: case DW_OP_GNU_reinterpret: { cu_offset type_die; data = safe_read_uleb128 (data, end, &ul); type_die.cu_off = ul; if (type_die.cu_off == 0) fprintf_filtered (stream, "<0>"); else { struct type *type; type = dwarf2_get_die_type (type_die, per_cu); fprintf_filtered (stream, "<"); type_print (type, "", stream, -1); fprintf_filtered (stream, " [0x%s]>", phex_nz (type_die.cu_off, 0)); } } break; case DW_OP_GNU_entry_value: data = safe_read_uleb128 (data, end, &ul); fputc_filtered ('\n', stream); disassemble_dwarf_expression (stream, arch, addr_size, offset_size, start, data, data + ul, indent + 2, all, per_cu); data += ul; continue; case DW_OP_GNU_parameter_ref: ul = extract_unsigned_integer (data, 4, gdbarch_byte_order (arch)); data += 4; fprintf_filtered (stream, " offset %s", phex_nz (ul, 4)); break; case DW_OP_GNU_addr_index: data = safe_read_uleb128 (data, end, &ul); ul = dwarf2_read_addr_index (per_cu, ul); fprintf_filtered (stream, " 0x%s", phex_nz (ul, addr_size)); break; case DW_OP_GNU_const_index: data = safe_read_uleb128 (data, end, &ul); ul = dwarf2_read_addr_index (per_cu, ul); fprintf_filtered (stream, " %s", pulongest (ul)); break; } fprintf_filtered (stream, "\n"); } return data; } /* Describe a single location, which may in turn consist of multiple pieces. */ static void locexpr_describe_location_1 (struct symbol *symbol, CORE_ADDR addr, struct ui_file *stream, const gdb_byte *data, size_t size, struct objfile *objfile, unsigned int addr_size, int offset_size, struct dwarf2_per_cu_data *per_cu) { const gdb_byte *end = data + size; int first_piece = 1, bad = 0; while (data < end) { const gdb_byte *here = data; int disassemble = 1; if (first_piece) first_piece = 0; else fprintf_filtered (stream, _(", and ")); if (!dwarf2_always_disassemble) { data = locexpr_describe_location_piece (symbol, stream, addr, objfile, per_cu, data, end, addr_size); /* If we printed anything, or if we have an empty piece, then don't disassemble. */ if (data != here || data[0] == DW_OP_piece || data[0] == DW_OP_bit_piece) disassemble = 0; } if (disassemble) { fprintf_filtered (stream, _("a complex DWARF expression:\n")); data = disassemble_dwarf_expression (stream, get_objfile_arch (objfile), addr_size, offset_size, data, data, end, 0, dwarf2_always_disassemble, per_cu); } if (data < end) { int empty = data == here; if (disassemble) fprintf_filtered (stream, " "); if (data[0] == DW_OP_piece) { uint64_t bytes; data = safe_read_uleb128 (data + 1, end, &bytes); if (empty) fprintf_filtered (stream, _("an empty %s-byte piece"), pulongest (bytes)); else fprintf_filtered (stream, _(" [%s-byte piece]"), pulongest (bytes)); } else if (data[0] == DW_OP_bit_piece) { uint64_t bits, offset; data = safe_read_uleb128 (data + 1, end, &bits); data = safe_read_uleb128 (data, end, &offset); if (empty) fprintf_filtered (stream, _("an empty %s-bit piece"), pulongest (bits)); else fprintf_filtered (stream, _(" [%s-bit piece, offset %s bits]"), pulongest (bits), pulongest (offset)); } else { bad = 1; break; } } } if (bad || data > end) error (_("Corrupted DWARF2 expression for \"%s\"."), SYMBOL_PRINT_NAME (symbol)); } /* Print a natural-language description of SYMBOL to STREAM. This version is for a symbol with a single location. */ static void locexpr_describe_location (struct symbol *symbol, CORE_ADDR addr, struct ui_file *stream) { struct dwarf2_locexpr_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); struct objfile *objfile = dwarf2_per_cu_objfile (dlbaton->per_cu); unsigned int addr_size = dwarf2_per_cu_addr_size (dlbaton->per_cu); int offset_size = dwarf2_per_cu_offset_size (dlbaton->per_cu); locexpr_describe_location_1 (symbol, addr, stream, dlbaton->data, dlbaton->size, objfile, addr_size, offset_size, dlbaton->per_cu); } /* Describe the location of SYMBOL as an agent value in VALUE, generating any necessary bytecode in AX. */ static void locexpr_tracepoint_var_ref (struct symbol *symbol, struct gdbarch *gdbarch, struct agent_expr *ax, struct axs_value *value) { struct dwarf2_locexpr_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); unsigned int addr_size = dwarf2_per_cu_addr_size (dlbaton->per_cu); if (dlbaton->size == 0) value->optimized_out = 1; else dwarf2_compile_expr_to_ax (ax, value, gdbarch, addr_size, dlbaton->data, dlbaton->data + dlbaton->size, dlbaton->per_cu); } /* The set of location functions used with the DWARF-2 expression evaluator. */ const struct symbol_computed_ops dwarf2_locexpr_funcs = { locexpr_read_variable, locexpr_read_variable_at_entry, locexpr_read_needs_frame, locexpr_describe_location, 0, /* location_has_loclist */ locexpr_tracepoint_var_ref }; /* Wrapper functions for location lists. These generally find the appropriate location expression and call something above. */ /* Return the value of SYMBOL in FRAME using the DWARF-2 expression evaluator to calculate the location. */ static struct value * loclist_read_variable (struct symbol *symbol, struct frame_info *frame) { struct dwarf2_loclist_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); struct value *val; const gdb_byte *data; size_t size; CORE_ADDR pc = frame ? get_frame_address_in_block (frame) : 0; data = dwarf2_find_location_expression (dlbaton, &size, pc); val = dwarf2_evaluate_loc_desc (SYMBOL_TYPE (symbol), frame, data, size, dlbaton->per_cu); return val; } /* Read variable SYMBOL like loclist_read_variable at (callee) FRAME's function entry. SYMBOL should be a function parameter, otherwise NO_ENTRY_VALUE_ERROR will be thrown. Function always returns non-NULL value, it may be marked optimized out if inferior frame information is not available. It throws NO_ENTRY_VALUE_ERROR if it cannot resolve the parameter for any reason. */ static struct value * loclist_read_variable_at_entry (struct symbol *symbol, struct frame_info *frame) { struct dwarf2_loclist_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); const gdb_byte *data; size_t size; CORE_ADDR pc; if (frame == NULL || !get_frame_func_if_available (frame, &pc)) return allocate_optimized_out_value (SYMBOL_TYPE (symbol)); data = dwarf2_find_location_expression (dlbaton, &size, pc); if (data == NULL) return allocate_optimized_out_value (SYMBOL_TYPE (symbol)); return value_of_dwarf_block_entry (SYMBOL_TYPE (symbol), frame, data, size); } /* Return non-zero iff we need a frame to evaluate SYMBOL. */ static int loclist_read_needs_frame (struct symbol *symbol) { /* If there's a location list, then assume we need to have a frame to choose the appropriate location expression. With tracking of global variables this is not necessarily true, but such tracking is disabled in GCC at the moment until we figure out how to represent it. */ return 1; } /* Print a natural-language description of SYMBOL to STREAM. This version applies when there is a list of different locations, each with a specified address range. */ static void loclist_describe_location (struct symbol *symbol, CORE_ADDR addr, struct ui_file *stream) { struct dwarf2_loclist_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); const gdb_byte *loc_ptr, *buf_end; struct objfile *objfile = dwarf2_per_cu_objfile (dlbaton->per_cu); struct gdbarch *gdbarch = get_objfile_arch (objfile); enum bfd_endian byte_order = gdbarch_byte_order (gdbarch); unsigned int addr_size = dwarf2_per_cu_addr_size (dlbaton->per_cu); int offset_size = dwarf2_per_cu_offset_size (dlbaton->per_cu); int signed_addr_p = bfd_get_sign_extend_vma (objfile->obfd); /* Adjust base_address for relocatable objects. */ CORE_ADDR base_offset = dwarf2_per_cu_text_offset (dlbaton->per_cu); CORE_ADDR base_address = dlbaton->base_address + base_offset; int done = 0; loc_ptr = dlbaton->data; buf_end = dlbaton->data + dlbaton->size; fprintf_filtered (stream, _("multi-location:\n")); /* Iterate through locations until we run out. */ while (!done) { CORE_ADDR low = 0, high = 0; /* init for gcc -Wall */ int length; enum debug_loc_kind kind; const gdb_byte *new_ptr = NULL; /* init for gcc -Wall */ if (dlbaton->from_dwo) kind = decode_debug_loc_dwo_addresses (dlbaton->per_cu, loc_ptr, buf_end, &new_ptr, &low, &high, byte_order); else kind = decode_debug_loc_addresses (loc_ptr, buf_end, &new_ptr, &low, &high, byte_order, addr_size, signed_addr_p); loc_ptr = new_ptr; switch (kind) { case DEBUG_LOC_END_OF_LIST: done = 1; continue; case DEBUG_LOC_BASE_ADDRESS: base_address = high + base_offset; fprintf_filtered (stream, _(" Base address %s"), paddress (gdbarch, base_address)); continue; case DEBUG_LOC_START_END: case DEBUG_LOC_START_LENGTH: break; case DEBUG_LOC_BUFFER_OVERFLOW: case DEBUG_LOC_INVALID_ENTRY: error (_("Corrupted DWARF expression for symbol \"%s\"."), SYMBOL_PRINT_NAME (symbol)); default: gdb_assert_not_reached ("bad debug_loc_kind"); } /* Otherwise, a location expression entry. */ low += base_address; high += base_address; length = extract_unsigned_integer (loc_ptr, 2, byte_order); loc_ptr += 2; /* (It would improve readability to print only the minimum necessary digits of the second number of the range.) */ fprintf_filtered (stream, _(" Range %s-%s: "), paddress (gdbarch, low), paddress (gdbarch, high)); /* Now describe this particular location. */ locexpr_describe_location_1 (symbol, low, stream, loc_ptr, length, objfile, addr_size, offset_size, dlbaton->per_cu); fprintf_filtered (stream, "\n"); loc_ptr += length; } } /* Describe the location of SYMBOL as an agent value in VALUE, generating any necessary bytecode in AX. */ static void loclist_tracepoint_var_ref (struct symbol *symbol, struct gdbarch *gdbarch, struct agent_expr *ax, struct axs_value *value) { struct dwarf2_loclist_baton *dlbaton = SYMBOL_LOCATION_BATON (symbol); const gdb_byte *data; size_t size; unsigned int addr_size = dwarf2_per_cu_addr_size (dlbaton->per_cu); data = dwarf2_find_location_expression (dlbaton, &size, ax->scope); if (size == 0) value->optimized_out = 1; else dwarf2_compile_expr_to_ax (ax, value, gdbarch, addr_size, data, data + size, dlbaton->per_cu); } /* The set of location functions used with the DWARF-2 expression evaluator and location lists. */ const struct symbol_computed_ops dwarf2_loclist_funcs = { loclist_read_variable, loclist_read_variable_at_entry, loclist_read_needs_frame, loclist_describe_location, 1, /* location_has_loclist */ loclist_tracepoint_var_ref }; /* Provide a prototype to silence -Wmissing-prototypes. */ extern initialize_file_ftype _initialize_dwarf2loc; void _initialize_dwarf2loc (void) { add_setshow_zuinteger_cmd ("entry-values", class_maintenance, &entry_values_debug, _("Set entry values and tail call frames " "debugging."), _("Show entry values and tail call frames " "debugging."), _("When non-zero, the process of determining " "parameter values from function entry point " "and tail call frames will be printed."), NULL, show_entry_values_debug, &setdebuglist, &showdebuglist); }
nds32/binutils
gdb/dwarf2loc.c
C
gpl-2.0
123,348
## # Copyright (C) 2010, Samsung Electronics Co., Ltd. All Rights Reserved. # Written by System S/W Group, Open OS S/W R&D Team, # Mobile Communication Division. ## ## # Project Name : Samsung Private Third-Party Device Drivers # # Project Description : # # Comments : tabstop = 8, shiftwidth = 8, noexpandtab ## ## # File Name : Makefile # # File Description : # # Author : Joo, Young Jin (#4349, youngjin79.joo@samsung.com) # Dept : System S/W Group (Open OS S/W R&D Team) # Created Date : 09-Jul-2010 # Version : Baby-Raccoon ## obj-$(CONFIG_SAMSUNG_BATTERY) += battery/ obj-$(CONFIG_FMRADIO) += fm_si4709/ obj-$(CONFIG_SAMSUNG_VIBETONZ) += vibetonz/ obj-$(CONFIG_INPUT_YAS529) += yas529/ obj-$(CONFIG_INPUT_BMA222) += bma222/ obj-$(CONFIG_INPUT_GP2A) += gp2a/ obj-$(CONFIG_INPUT_ORIENTATION) += orientation/ obj-$(CONFIG_SUPPORT_GPS) += gps/ obj-$(CONFIG_INPUT_BH1721) += bh1721/ obj-$(CONFIG_INPUT_K3G) += k3g/ obj-$(CONFIG_INPUT_BMA023) += bma023/
sconosciuto/android_kernel_samsung_latona_legacy
samsung/Makefile
Makefile
gpl-2.0
965
\documentclass[a4paper,10pt]{article} \begin{document} \title{\textbf{Managed Execution}} \author{Pawel Dziepak} \date{\textit{July 16, 2008}} \maketitle \section{Introduction} \paragraph{}In Quarn OS there are three basic systems that allow the whole operating system to work. Despite many important differences, they all needs similar functions and procedures to manage data, messages, resources, calls and orders. Additionally they all need extended system of access control that will help keep system secure. That's why, these basic algorithms are grouped into main Quarn OS core called Manes (Managed Execution System). Their task is to provide objects of different type with necessary access restrictions. \section{Types} \subsection{Main types} factories: zero, filesystem, memory manager, bus, server childrens: factory, file, object/buffer, device, service \section{Objects} \section{Managers} \section{Access control} \end{document}
pdziepak/quarnos-old2
docs/Managed_Execution.tex
TeX
gpl-2.0
953
package code.vera.myblog.presenter.fragment.person; import android.content.DialogInterface; import android.graphics.drawable.ColorDrawable; import android.os.Bundle; import android.support.v7.app.AlertDialog; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.PopupWindow; import com.trello.rxlifecycle.FragmentEvent; import java.util.List; import butterknife.OnClick; import code.vera.myblog.R; import code.vera.myblog.adapter.TabPersonAllCircleAdapter; import code.vera.myblog.bean.GeoBean; import code.vera.myblog.bean.HomeRequestBean; import code.vera.myblog.bean.StatusesBean; import code.vera.myblog.config.Constants; import code.vera.myblog.listener.OnItemDeleteClickListener; import code.vera.myblog.listener.OnItemLocationListener; import code.vera.myblog.model.user.UserModel; import code.vera.myblog.presenter.activity.NearByLocationActivity; import code.vera.myblog.presenter.base.PresenterFragment; import code.vera.myblog.presenter.subscribe.CustomSubscriber; import code.vera.myblog.utils.DialogUtils; import code.vera.myblog.utils.ScreenUtils; import code.vera.myblog.utils.ToastUtil; import code.vera.myblog.view.personality.TabPersonAllCircleView; import ww.com.core.Debug; import ww.com.core.widget.CustomSwipeRefreshLayout; import static code.vera.myblog.presenter.activity.NearByLocationActivity.PARAM_LOCATION_LATITUDE; import static code.vera.myblog.presenter.activity.NearByLocationActivity.PARAM_LOCATION_LONGTITUDE; /** * 个人界面的圈子 * Created by vera on 2017/2/24 0024. */ public class TabPersonAllCircleFragment extends PresenterFragment<TabPersonAllCircleView, UserModel> implements OnItemDeleteClickListener, OnItemLocationListener { static TabPersonAllCircleFragment instance; private HomeRequestBean homeRequestBean; private TabPersonAllCircleAdapter adapter; private PopupWindow menuPopupWindow; private String uid; private AlertDialog.Builder cateDialogBuilder;//弹出框 private AlertDialog cateDialog; private int currentCateIndex = 0; private String[] cate = new String[]{"全部", "原创", "图片", "视频", "音乐"}; @Override protected int getLayoutResId() { return R.layout.fragment_tab_person_all; } @Override protected void onAttach() { super.onAttach(); homeRequestBean = new HomeRequestBean(); homeRequestBean.setUid(uid); initView(); setAdapter(); addListener(); getCircles(true); } private void initView() { View menu = LayoutInflater.from(getContext()).inflate(R.layout.pop_bottom_me, null); menuPopupWindow = new PopupWindow(menu, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); menuPopupWindow.setFocusable(true); ColorDrawable dw = new ColorDrawable(0xb0000000); menuPopupWindow.setBackgroundDrawable(dw); // 设置popWindow的显示和消失动画 menuPopupWindow.setAnimationStyle(R.style.mypopwindow_anim_style); cateDialogBuilder = new AlertDialog.Builder(getContext()); } private void addListener() { adapter.setOnItemDeleteClickListener(this); adapter.setOnItemLocationListener(this); menuPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() { @Override public void onDismiss() { // popupWindow隐藏时恢复屏幕正常透明度 ScreenUtils.backgroundAlpaha(getActivity(), 1.0f); } }); view.setOnSwipeRefreshListener(new CustomSwipeRefreshLayout.OnSwipeRefreshLayoutListener() { @Override public void onHeaderRefreshing() { homeRequestBean.page = "1"; getCircles(false); } @Override public void onFooterRefreshing() { int nextPage = Integer.parseInt(homeRequestBean.getPage()) + 1; homeRequestBean.setPage(nextPage + ""); getCircles(false); } }); } private void setAdapter() { adapter = new TabPersonAllCircleAdapter(getContext()); view.setAdapter(adapter); } private void getCircles(boolean isDialog) { model.getUserTimeLine(getContext(), homeRequestBean, bindUntilEvent(FragmentEvent.DESTROY), new CustomSubscriber<List<StatusesBean>>(mContext, isDialog) { @Override public void onNext(List<StatusesBean> statusesBeen) { super.onNext(statusesBeen); adapter.addList(statusesBeen); view.refreshFinished(); } }); } public static TabPersonAllCircleFragment getInstance() { if (instance == null) { instance = new TabPersonAllCircleFragment(); } return instance; } public void setUid(long id) { uid = id + ""; } @Override public void onItemDeleteClickListener(View view, final int pos) { final long id = adapter.getItem(pos).getId(); DialogUtils.showDialog(mContext, "", "你确定要删除这条信息吗?", "确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { deleteCircle(id, pos); } }, "取消", null); } private void deleteCircle(long id, final int pos) { model.destroyStatus(id + "", mContext, bindUntilEvent(FragmentEvent.DESTROY), new CustomSubscriber<Boolean>(mContext, false) { @Override public void onNext(Boolean aBoolean) { super.onNext(aBoolean); if (aBoolean) { //删除成功 adapter.removeItem(adapter.getItem(pos)); adapter.notifyDataSetChanged(); } else { ToastUtil.showToast(mContext, "删除失败,请检查网络"); } } }); } @OnClick(R.id.tv_filter) public void filter() { ButtonOnClick buttonOnClick = new ButtonOnClick();//默认为0表示选中第一个项目,-1表示没有项目被选中 cateDialogBuilder.setSingleChoiceItems(cate, 4, buttonOnClick); cateDialogBuilder.setSingleChoiceItems(cate, 3, buttonOnClick); cateDialogBuilder.setSingleChoiceItems(cate, 2, buttonOnClick); cateDialogBuilder.setSingleChoiceItems(cate, 1, buttonOnClick); cateDialogBuilder.setSingleChoiceItems(cate, currentCateIndex, buttonOnClick); cateDialog = cateDialogBuilder.show(); } @Override public void onItemLocation(View v, int pos) { //查看位置 Bundle bundle=new Bundle(); GeoBean geoBean=adapter.getItem(pos).getGeoBean(); bundle.putDouble(PARAM_LOCATION_LATITUDE,geoBean.getCoordinates().get(0)); bundle.putDouble(PARAM_LOCATION_LONGTITUDE,geoBean.getCoordinates().get(1)); NearByLocationActivity.start(mContext,bundle); } private class ButtonOnClick implements DialogInterface.OnClickListener { @Override public void onClick(DialogInterface dialogInterface, int i) { Debug.d("i=" + i); currentCateIndex = i; cateDialog.dismiss(); switch (i) { case 0: homeRequestBean.setFeature(Constants.FILTER_ALL); getCircles(true); break; case 1: homeRequestBean.setFeature(Constants.FILTER_ORIGI); getCircles(true); break; case 2: homeRequestBean.setFeature(Constants.FILTER_PHOTO); getCircles(true); break; case 3: homeRequestBean.setFeature(Constants.FILTER_MOVIE); getCircles(true); break; case 4: homeRequestBean.setFeature(Constants.FILTER_MUSIC); getCircles(true); break; } } } }
arronvera/MyBlog
app/src/main/java/code/vera/myblog/presenter/fragment/person/TabPersonAllCircleFragment.java
Java
gpl-2.0
8,234