code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
<?php
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Magento\ProductVideo\Test\Constraint;
use Magento\Cms\Test\Page\CmsIndex;
use Magento\Mtf\Fixture\InjectableFixture;
use Magento\Mtf\Constraint\AbstractConstraint;
use Magento\Catalog\Test\Page\Category\CatalogCategoryView;
/**
* Assert that video is displayed on category page.
*/
class AssertVideoCategoryView extends AbstractConstraint
{
/**
* Assert that video is displayed on category page on Store front.
*
* @param CmsIndex $cmsIndex
* @param CatalogCategoryView $catalogCategoryView
* @param InjectableFixture $product
* @return void
*/
public function processAssert(
CmsIndex $cmsIndex,
CatalogCategoryView $catalogCategoryView,
InjectableFixture $product
) {
$cmsIndex->open();
$cmsIndex->getTopmenu()->selectCategoryByName($product->getCategoryIds()[0]);
$src = $catalogCategoryView->getListProductBlock()->getProductItem($product)->getBaseImageSource();
\PHPUnit\Framework\Assert::assertFalse(
strpos($src, '/placeholder/') !== false,
'Video preview image is not displayed on category view when it should.'
);
}
/**
* Returns a string representation of the object.
*
* @return string
*/
public function toString()
{
return 'Video preview images is displayed on category view.';
}
}
| Java |
#!/usr/bin/env python
# **********************************************************************
#
# Copyright (c) 2003-2011 ZeroC, Inc. All rights reserved.
#
# This copy of Ice is licensed to you under the terms described in the
# ICE_LICENSE file included in this distribution.
#
# **********************************************************************
import os, sys
path = [ ".", "..", "../..", "../../..", "../../../.." ]
head = os.path.dirname(sys.argv[0])
if len(head) > 0:
path = [os.path.join(head, p) for p in path]
path = [os.path.abspath(p) for p in path if os.path.exists(os.path.join(p, "scripts", "TestUtil.py")) ]
if len(path) == 0:
raise "can't find toplevel directory!"
sys.path.append(os.path.join(path[0]))
from scripts import *
dbdir = os.path.join(os.getcwd(), "db")
TestUtil.cleanDbDir(dbdir)
client = os.path.join(os.getcwd(), "client")
if TestUtil.appverifier:
TestUtil.setAppVerifierSettings([client])
clientProc = TestUtil.startClient(client, ' --Freeze.Warn.Rollback=0 "%s"' % os.getcwd())
clientProc.waitTestSuccess()
if TestUtil.appverifier:
TestUtil.appVerifierAfterTestEnd([client])
| Java |
<?php
/**
* HTML helper class
*
* This class was developed to provide some standard HTML functions.
*
* @package VirtueMart
* @subpackage Helpers
* @author RickG
* @copyright Copyright (c) 2004-2008 Soeren Eberhardt-Biermann, 2009 VirtueMart Team. All rights reserved.
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die();
/**
* HTML Helper
*
* @package VirtueMart
* @subpackage Helpers
* @author RickG
*/
class VmHTML{
/**
* Converts all special chars to html entities
*
* @param string $string
* @param string $quote_style
* @param boolean $only_special_chars Only Convert Some Special Chars ? ( <, >, &, ... )
* @return string
*/
function shopMakeHtmlSafe( $string, $quote_style='ENT_QUOTES', $use_entities=false ) {
if( defined( $quote_style )) {
$quote_style = constant($quote_style);
}
if( $use_entities ) {
$string = @htmlentities( $string, constant($quote_style), self::vmGetCharset() );
} else {
$string = @htmlspecialchars( $string, $quote_style, self::vmGetCharset() );
}
return $string;
}
/**
* Returns the charset string from the global _ISO constant
*
* @return string UTF-8 by default
* @since 1.0.5
*/
function vmGetCharset() {
$iso = explode( '=', @constant('_ISO') );
if( !empty( $iso[1] )) {
return $iso[1];
}
else {
return 'UTF-8';
}
}
/**
* Generate HTML code for a row using VmHTML function
*
* @func string : function to call
* @label string : Text Label
* @args array : arguments
* @return string: HTML code for row table
*/
function row($func,$label){
$VmHTML="VmHTML";
$passedArgs = func_get_args();
array_shift( $passedArgs );//remove function
array_shift( $passedArgs );//remove label
$args = array();
foreach ($passedArgs as $k => $v) {
$args[] = &$passedArgs[$k];
}
$lang =& JFactory::getLanguage();
$label = $lang->hasKey($label.'_TIP') ? '<span class="hasTip" title="'.JText::_($label.'_TIP').'">'.JText::_($label).'</span>' : JText::_($label) ;
$html = '
<tr>
<td class="key">
'.$label.'
</td>
<td>
'.call_user_func_array(array($VmHTML, $func), $args).'
</td>
</tr>';
return $html ;
}
/* simple value display */
function value( $value ){
$lang =& JFactory::getLanguage();
return $lang->hasKey($value) ? JText::_($value) : $value;
}
/* simple raw render */
function raw( $value ){
return $value;
}
/**
* Generate HTML code for a checkbox
*
* @param string Name for the chekcbox
* @param mixed Current value of the checkbox
* @param mixed Value to assign when checkbox is checked
* @param mixed Value to assign when checkbox is not checked
* @return string HTML code for checkbox
*/
function checkbox($name, $value, $checkedValue=1, $uncheckedValue=0, $extraAttribs = '') {
if ($value == $checkedValue) {
$checked = 'checked="checked"';
}
else {
$checked = '';
}
$htmlcode = '<input type="hidden" name="' . $name . '" value="' . $uncheckedValue . '">';
$htmlcode .= '<input '.$extraAttribs.' id="' . $name . '" type="checkbox" name="' . $name . '" value="' . $checkedValue . '" ' . $checked . ' />';
return $htmlcode;
}
/**
* Prints an HTML dropdown box named $name using $arr to
* load the drop down. If $value is in $arr, then $value
* will be the selected option in the dropdown.
* @author gday
* @author soeren
*
* @param string $name The name of the select element
* @param string $value The pre-selected value
* @param array $arr The array containting $key and $val
* @param int $size The size of the select element
* @param string $multiple use "multiple=\"multiple\" to have a multiple choice select list
* @param string $extra More attributes when needed
* @return string HTML drop-down list
*/
function selectList($name, $value, $arrIn, $size=1, $multiple="", $extra="") {
$html = '';
if( empty( $arrIn ) ) {
$arr = array();
} else {
if(!is_array($arrIn)){
$arr=array($arrIn);
} else {
$arr=$arrIn;
}
}
$html = '<select class="inputbox" id="'.$name.'" name="'.$name.'" size="'.$size.'" '.$multiple.' '.$extra.'>';
while (list($key, $val) = each($arr)) {
// foreach ($arr as $key=>$val){
$selected = "";
if( is_array( $value )) {
if( in_array( $key, $value )) {
$selected = 'selected="selected"';
}
}
else {
if(strtolower($value) == strtolower($key) ) {
$selected = 'selected="selected"';
}
}
$html .= '<option value="'.$key.'" '.$selected.'>'.self::shopMakeHtmlSafe($val);
$html .= '</option>';
}
$html .= '</select>';
return $html;
}
// /**
// *
// */
// function selectListParamParser( $arrIn, $tag_name, $tag_attribs, $key, $text, $selected, $required=0 ) {
//// function selectListParamParser($tag_name ,$tag_attribs ,$arrIn , $key, $text, $selected, $required=0 ) {
//
// echo '<br />$tag_name '.$tag_name;
// echo '<br />$tag_attribs '.$tag_attribs;
// echo '<br />$key '.$key;
// echo '<br />$text '.$text;
// echo '<br />$selected '.$selected;
// if(empty($arrIn)){
// return 'Error selectListParamParser no first argument given';
// }
// if(!is_array($arrIn)){
// $arr=array($arrIn);
// } else {
// $arr=$arrIn;
// }
// reset( $arr );
// $html = "\n<select name=\"$tag_name\" id=\"".str_replace('[]', '', $tag_name)."\" $tag_attribs>";
// if(!$required) $html .= "\n\t<option value=\"\">".JText::_('COM_VIRTUEMART_SELECT')."</option>";
// $n=count( $arr );
// for ($i=0; $i < $n; $i++ ) {
//
// $k = stripslashes($arr[$i]->$key);
// $t = stripslashes($arr[$i]->$text);
// $id = isset($arr[$i]->id) ? $arr[$i]->id : null;
//
// $extra = '';
// $extra .= $id ? " id=\"" . $arr[$i]->id . "\"" : '';
// if (is_array( $selected )) {
// foreach ($selected as $obj) {
// $k2 = stripslashes($obj->$key);
// if ($k == $k2) {
// $extra .= " selected=\"selected\"";
// break;
// }
// }
// } else {
// $extra .= ($k == stripslashes($selected) ? " selected=\"selected\"" : '');
// }
// $html .= "\n\t<option value=\"".$k."\"$extra>";
// if( $t[0] == '_' ) $t = substr( $t, 1 );
// $html .= JText::_($t);
// $html .= "</option>";
// }
// $html .= "\n</select>\n";
// return $html;
// }
/**
* Creates a Radio Input List
*
* @param string $name
* @param string $value default value
* @param string $arr
* @param string $extra
* @return string
*/
function radioList($name, $value, &$arr, $extra="") {
$html = '';
if( empty( $arr ) ) {
$arr = array();
}
$html = '';
$i = 0;
foreach($arr as $key => $val) {
$checked = '';
if( is_array( $value )) {
if( in_array( $key, $value )) {
$checked = 'checked="checked"';
}
}
else {
if(strtolower($value) == strtolower($key) ) {
$checked = 'checked="checked"';
}
}
$html .= '<input type="radio" name="'.$name.'" id="'.$name.$i.'" value="'.htmlspecialchars($key, ENT_QUOTES).'" '.$checked.' '.$extra." />\n";
$html .= '<label for="'.$name.$i++.'">'.$val."</label><br />\n";
}
return $html;
}
/**
* Creates radio List
* @param array $radios
* @param string $name
* @param string $default
* @return string
*/
function radio( $name, $radios, $default,$key='value',$text='text') {
return '<fieldset class="radio">'.JHTML::_('select.radiolist', $radios, $name, '', $key, $text, $default).'</fieldset>';
}
/**
* Creating rows with boolean list
*
* @author Patrick Kohl
* @param string $label
* @param string $name
* @param string $value
*
*/
public function booleanlist ( $name, $value,$class='class="inputbox"'){
return '<fieldset class="radio">'.JHTML::_( 'select.booleanlist', $name , $class , $value).'</fieldset>' ;
}
/**
* Creating rows with input fields
*
* @author Patrick Kohl
* @param string $text
* @param string $name
* @param string $value
*/
public function input($name,$value,$class='class="inputbox"',$readonly='',$size='37',$maxlength='255',$more=''){
return '<input type="text" '.$readonly.' '.$class.' id="'.$name.'" name="'.$name.'" size="'.$size.'" maxlength="'.$maxlength.'" value="'.$value.'" />'.$more.'</td>';
}
/**
* Creating rows with input fields
*
* @author Patrick Kohl
* @param string $text
* @param string $name
* @param string $value
*/
public function textarea($name,$value,$class='class="inputbox"',$cols='70',$rows="10"){
return '<textarea '.$class.' id="'.$name.'" name="'.$name.'" cols="'.$cols.'" rows="'.$rows.'"/>'.$value.'</textarea ></td>';
}
/**
* render editor code
*
* @author Patrick Kohl
* @param string $text
* @param string $name
* @param string $value
*/
public function editor($name,$value,$size='100%',$height='300',$hide = array('pagebreak', 'readmore')){
$editor =& JFactory::getEditor();
return $editor->display($name, $value, $size, $height, null, null ,$hide ) ;
}
/**
*
* @author Patrick Kohl
* @param array $options( value & text)
* @param string $name option name
* @param string $defaut defaut value
* @param string $key option value
* @param string $text option text
* @param boolean $zero add a '0' value in the option
* return a select list
*/
public function select($name, $options, $default = '0',$attrib = "onchange='submit();'",$key ='value' ,$text ='text', $zero=true){
if ($zero==true) {
$option = array($key =>"0", $text => JText::_('COM_VIRTUEMART_LIST_EMPTY_OPTION'));
$options = array_merge(array($option), $options);
}
return JHTML::_('select.genericlist', $options,$name,$attrib,$key,$text,$default,false,true);
}
/**
* renders the hidden input
* @author Max Milbers
*/
public function inputHidden($values){
$html='';
foreach($values as $k=>$v){
$html .= '<input type="hidden" name="'.$k.'" value="'.$v.'" />';
}
return $html;
} /**
* renders the Edit Form hidden default input
* @author Patrick Kohl
*/
public function HiddenEdit($controller=0, $task=''){
if (!$controller) $controller = JRequest::getCmd('view');
return '
<input type="hidden" name="task" value="'.$task.'" />
<input type="hidden" name="option" value="com_virtuemart" />
<input type="hidden" name="boxchecked" value="0" />
<input type="hidden" name="controller" value="'.$controller.'" />
'. JHTML::_( 'form.token' ) ;
}
/**
* @author Patrick Kohl
* @var $type type of regular Expression to validate
* $type can be I integer, F Float, A date, M, time, T text, L link, U url, P phone
*@bool $required field is required
*@Int $min minimum of char
*@Int $max max of char
*@var $match original ID field to compare with this such as Email, passsword
*@ Return $html class for validate javascript
**/
public function validate($type='',$required=true, $min=null,$max=null,$match=null) {
if ($required) $validTxt = 'required';
else $validTxt = 'optional';
if (isset($min)) $validTxt .= ',minSize['.$min.']';
if (isset($max)) $validTxt .= ',maxSize['.$max.']';
static $validateID=0 ;
$validateID++;
if ($type=='S' ) return 'id="validate'.$validateID.'" class="validate[required,minSize[2],maxSize[255]]"';
$validate = array ( 'I'=>'onlyNumberSp', 'F'=>'number','D'=>'dateTime','A'=>'date','M'=>'time','T'=>'Text','L'=>'link','U'=>'url','P'=>'phone');
if (isset ($validate[$type])) $validTxt .= ',custom['.$validate[$type].']';
$html ='id="validate'.$validateID.'" class="validate['.$validTxt.']"';
return $html ;
}
} | Java |
#!/usr/bin/python
import os
import sys
import re
# file name unified by the following rule:
# 1. always save the osm under ../osmFiles directory
# 2. the result automatically generate to ../trajectorySets
# 3.1. change variable "osmName", or
# 3.2. use command argument to specify osm file name
# 4. this script generates a set of paths, each includes a series of of points,
# and save in originOfLife folder for further parsing.
# also, please scroll down the very bottom to see what's the next step
osmName = 'San_Jose_20x20.osm' # sample: 'ucla.osm'
#osmName = 'Los_Angeles_20x20.osm' # sample: 'ucla.osm'
#osmName = 'ucla_5x5.osm' # sample: 'ucla.osm'
optionAllowLoop = False # most of the cases are building bounding boxes
# support system parameters
if len(sys.argv) >= 2:
osmName = sys.argv[1]
if len(sys.argv) >= 3:
optionAllowLoop = (sys.argv[2] == '1')
inFile = '../../../Data/osmFiles/' + osmName
if len(osmName.split('.')) == 1:
osmNameWoExt = osmName
else:
osmNameWoExt = osmName[:-(1+len(osmName.split('.')[-1]))]
outRootDir = '../../../Data/trajectorySets/'
outFile = outRootDir + osmNameWoExt + '.tfix'
print('input file = ' + inFile)
print('output file = ' + outFile)
print('')
f = open('/tmp/in', 'w')
f.write('<in>' + inFile + '</in>');
f.close()
# the following command can be slow. a 3x3 mile^2 area takes 53 seconds to generate the result.
xmlWayDetail = outRootDir + 'originOfLife/' + osmNameWoExt + '.xml'
cmd = 'basex findWayTrajectory.xq > ' + xmlWayDetail
print('CMD: ' + cmd)
if os.path.isfile(xmlWayDetail):
print('File existed. Skip.')
else:
os.system(cmd)
# the next step should be executing the python3 ../makeElevSegMap.py with the input
# parameter outFile, but because of the relative folder path issue, integrating
# makeElevSegMap.py into this code needs to make big changes. So at this stage,
# we still stay on manually executing that script.
| Java |
#google-map
{
height: 300px;
} | Java |
package com.cf.tradeprocessor.web.rest.response;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
public class JsonResponse {
private Boolean success;
@JsonInclude(Include.NON_NULL)
private Object result;
public JsonResponse() {
}
private JsonResponse(Boolean success, Object result) {
this.success = success;
this.result = result;
}
public static JsonResponse success(Object result) {
return new JsonResponse(true, result);
}
public static JsonResponse success() {
return success(null);
}
public static JsonResponse error(String message) {
return new JsonResponse(false, message);
}
public static JsonResponse error() {
return error(null);
}
public Boolean getSuccess() {
return success;
}
public Object getResult() {
return result;
}
}
| Java |
/*jslint browser: true */ /*global jQuery: true */
/**
* jQuery Cookie plugin
*
* Copyright (c) 2010 Klaus Hartl (stilbuero.de)
* Dual licensed under the MIT and GPL licenses:
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
*
*/
// TODO JsDoc
/**
* Create a cookie with the given key and value and other optional parameters.
*
* @example $.cookie('the_cookie', 'the_value');
* @desc Set the value of a cookie.
* @example $.cookie('the_cookie', 'the_value', { expires: 7, path: '/', domain: 'jquery.com', secure: true });
* @desc Create a cookie with all available options.
* @example $.cookie('the_cookie', 'the_value');
* @desc Create a session cookie.
* @example $.cookie('the_cookie', null);
* @desc Delete a cookie by passing null as value. Keep in mind that you have to use the same path and domain
* used when the cookie was set.
*
* @param String key The key of the cookie.
* @param String value The value of the cookie.
* @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
* @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
* If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
* If set to null or omitted, the cookie will be a session cookie and will not be retained
* when the the browser exits.
* @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
* @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
* @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
* require a secure protocol (like HTTPS).
* @type undefined
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
/**
* Get the value of a cookie with the given key.
*
* @example $.cookie('the_cookie');
* @desc Get the value of a cookie.
*
* @param String key The key of the cookie.
* @return The value of the cookie.
* @type String
*
* @name $.cookie
* @cat Plugins/Cookie
* @author Klaus Hartl/klaus.hartl@stilbuero.de
*/
jQuery.cookie = function (key, value, options) {
// key and value given, set cookie...
if (arguments.length > 1 && (value === null || typeof value !== "object")) {
options = jQuery.extend({}, options);
if (value === null) {
options.expires = -1;
}
if (typeof options.expires === 'number') {
var days = options.expires, t = options.expires = new Date();
t.setDate(t.getDate() + days);
}
return (document.cookie = [
encodeURIComponent(key), '=',
options.raw ? String(value) : encodeURIComponent(String(value)),
options.expires ? '; expires=' + options.expires.toUTCString() : '', // use expires attribute, max-age is not supported by IE
options.path ? '; path=' + options.path : '',
options.domain ? '; domain=' + options.domain : '',
options.secure ? '; secure' : ''
].join(''));
}
// key and possibly options given, get cookie...
options = value || {};
var result, decode = options.raw ? function (s) { return s; } : decodeURIComponent;
return (result = new RegExp('(?:^|; )' + encodeURIComponent(key) + '=([^;]*)').exec(document.cookie)) ? decode(result[1]) : null;
};
;
(function ($) {
/**
* This script transforms a set of fieldsets into a stack of vertical
* tabs. Another tab pane can be selected by clicking on the respective
* tab.
*
* Each tab may have a summary which can be updated by another
* script. For that to work, each fieldset has an associated
* 'verticalTabCallback' (with jQuery.data() attached to the fieldset),
* which is called every time the user performs an update to a form
* element inside the tab pane.
*/
Drupal.behaviors.verticalTabs = {
attach: function (context) {
$('.vertical-tabs-panes', context).once('vertical-tabs', function () {
var focusID = $(':hidden.vertical-tabs-active-tab', this).val();
var tab_focus;
// Check if there are some fieldsets that can be converted to vertical-tabs
var $fieldsets = $('> fieldset', this);
if ($fieldsets.length == 0) {
return;
}
// Create the tab column.
var tab_list = $('<ul class="vertical-tabs-list"></ul>');
$(this).wrap('<div class="vertical-tabs clearfix"></div>').before(tab_list);
// Transform each fieldset into a tab.
$fieldsets.each(function () {
var vertical_tab = new Drupal.verticalTab({
title: $('> legend', this).text(),
fieldset: $(this)
});
tab_list.append(vertical_tab.item);
$(this)
.removeClass('collapsible collapsed')
.addClass('vertical-tabs-pane')
.data('verticalTab', vertical_tab);
if (this.id == focusID) {
tab_focus = $(this);
}
});
$('> li:first', tab_list).addClass('first');
$('> li:last', tab_list).addClass('last');
if (!tab_focus) {
// If the current URL has a fragment and one of the tabs contains an
// element that matches the URL fragment, activate that tab.
if (window.location.hash && $(this).find(window.location.hash).length) {
tab_focus = $(this).find(window.location.hash).closest('.vertical-tabs-pane');
}
else {
tab_focus = $('> .vertical-tabs-pane:first', this);
}
}
if (tab_focus.length) {
tab_focus.data('verticalTab').focus();
}
});
}
};
/**
* The vertical tab object represents a single tab within a tab group.
*
* @param settings
* An object with the following keys:
* - title: The name of the tab.
* - fieldset: The jQuery object of the fieldset that is the tab pane.
*/
Drupal.verticalTab = function (settings) {
var self = this;
$.extend(this, settings, Drupal.theme('verticalTab', settings));
this.link.click(function () {
self.focus();
return false;
});
// Keyboard events added:
// Pressing the Enter key will open the tab pane.
this.link.keydown(function(event) {
if (event.keyCode == 13) {
self.focus();
// Set focus on the first input field of the visible fieldset/tab pane.
$("fieldset.vertical-tabs-pane :input:visible:enabled:first").focus();
return false;
}
});
this.fieldset
.bind('summaryUpdated', function () {
self.updateSummary();
})
.trigger('summaryUpdated');
};
Drupal.verticalTab.prototype = {
/**
* Displays the tab's content pane.
*/
focus: function () {
this.fieldset
.siblings('fieldset.vertical-tabs-pane')
.each(function () {
var tab = $(this).data('verticalTab');
tab.fieldset.hide();
tab.item.removeClass('selected');
})
.end()
.show()
.siblings(':hidden.vertical-tabs-active-tab')
.val(this.fieldset.attr('id'));
this.item.addClass('selected');
// Mark the active tab for screen readers.
$('#active-vertical-tab').remove();
this.link.append('<span id="active-vertical-tab" class="element-invisible">' + Drupal.t('(active tab)') + '</span>');
},
/**
* Updates the tab's summary.
*/
updateSummary: function () {
this.summary.html(this.fieldset.drupalGetSummary());
},
/**
* Shows a vertical tab pane.
*/
tabShow: function () {
// Display the tab.
this.item.show();
// Update .first marker for items. We need recurse from parent to retain the
// actual DOM element order as jQuery implements sortOrder, but not as public
// method.
this.item.parent().children('.vertical-tab-button').removeClass('first')
.filter(':visible:first').addClass('first');
// Display the fieldset.
this.fieldset.removeClass('vertical-tab-hidden').show();
// Focus this tab.
this.focus();
return this;
},
/**
* Hides a vertical tab pane.
*/
tabHide: function () {
// Hide this tab.
this.item.hide();
// Update .first marker for items. We need recurse from parent to retain the
// actual DOM element order as jQuery implements sortOrder, but not as public
// method.
this.item.parent().children('.vertical-tab-button').removeClass('first')
.filter(':visible:first').addClass('first');
// Hide the fieldset.
this.fieldset.addClass('vertical-tab-hidden').hide();
// Focus the first visible tab (if there is one).
var $firstTab = this.fieldset.siblings('.vertical-tabs-pane:not(.vertical-tab-hidden):first');
if ($firstTab.length) {
$firstTab.data('verticalTab').focus();
}
return this;
}
};
/**
* Theme function for a vertical tab.
*
* @param settings
* An object with the following keys:
* - title: The name of the tab.
* @return
* This function has to return an object with at least these keys:
* - item: The root tab jQuery element
* - link: The anchor tag that acts as the clickable area of the tab
* (jQuery version)
* - summary: The jQuery element that contains the tab summary
*/
Drupal.theme.prototype.verticalTab = function (settings) {
var tab = {};
tab.item = $('<li class="vertical-tab-button" tabindex="-1"></li>')
.append(tab.link = $('<a href="#"></a>')
.append(tab.title = $('<strong></strong>').text(settings.title))
.append(tab.summary = $('<span class="summary"></span>')
)
);
return tab;
};
})(jQuery);
;
(function ($) {
/**
* The base States namespace.
*
* Having the local states variable allows us to use the States namespace
* without having to always declare "Drupal.states".
*/
var states = Drupal.states = {
// An array of functions that should be postponed.
postponed: []
};
/**
* Attaches the states.
*/
Drupal.behaviors.states = {
attach: function (context, settings) {
var $context = $(context);
for (var selector in settings.states) {
for (var state in settings.states[selector]) {
new states.Dependent({
element: $context.find(selector),
state: states.State.sanitize(state),
constraints: settings.states[selector][state]
});
}
}
// Execute all postponed functions now.
while (states.postponed.length) {
(states.postponed.shift())();
}
}
};
/**
* Object representing an element that depends on other elements.
*
* @param args
* Object with the following keys (all of which are required):
* - element: A jQuery object of the dependent element
* - state: A State object describing the state that is dependent
* - constraints: An object with dependency specifications. Lists all elements
* that this element depends on. It can be nested and can contain arbitrary
* AND and OR clauses.
*/
states.Dependent = function (args) {
$.extend(this, { values: {}, oldValue: null }, args);
this.dependees = this.getDependees();
for (var selector in this.dependees) {
this.initializeDependee(selector, this.dependees[selector]);
}
};
/**
* Comparison functions for comparing the value of an element with the
* specification from the dependency settings. If the object type can't be
* found in this list, the === operator is used by default.
*/
states.Dependent.comparisons = {
'RegExp': function (reference, value) {
return reference.test(value);
},
'Function': function (reference, value) {
// The "reference" variable is a comparison function.
return reference(value);
},
'Number': function (reference, value) {
// If "reference" is a number and "value" is a string, then cast reference
// as a string before applying the strict comparison in compare(). Otherwise
// numeric keys in the form's #states array fail to match string values
// returned from jQuery's val().
return (typeof value === 'string') ? compare(reference.toString(), value) : compare(reference, value);
}
};
states.Dependent.prototype = {
/**
* Initializes one of the elements this dependent depends on.
*
* @param selector
* The CSS selector describing the dependee.
* @param dependeeStates
* The list of states that have to be monitored for tracking the
* dependee's compliance status.
*/
initializeDependee: function (selector, dependeeStates) {
var state;
// Cache for the states of this dependee.
this.values[selector] = {};
for (var i in dependeeStates) {
if (dependeeStates.hasOwnProperty(i)) {
state = dependeeStates[i];
// Make sure we're not initializing this selector/state combination twice.
if ($.inArray(state, dependeeStates) === -1) {
continue;
}
state = states.State.sanitize(state);
// Initialize the value of this state.
this.values[selector][state.name] = null;
// Monitor state changes of the specified state for this dependee.
$(selector).bind('state:' + state, $.proxy(function (e) {
this.update(selector, state, e.value);
}, this));
// Make sure the event we just bound ourselves to is actually fired.
new states.Trigger({ selector: selector, state: state });
}
}
},
/**
* Compares a value with a reference value.
*
* @param reference
* The value used for reference.
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
*
* @return
* true or false.
*/
compare: function (reference, selector, state) {
var value = this.values[selector][state.name];
if (reference.constructor.name in states.Dependent.comparisons) {
// Use a custom compare function for certain reference value types.
return states.Dependent.comparisons[reference.constructor.name](reference, value);
}
else {
// Do a plain comparison otherwise.
return compare(reference, value);
}
},
/**
* Update the value of a dependee's state.
*
* @param selector
* CSS selector describing the dependee.
* @param state
* A State object describing the dependee's updated state.
* @param value
* The new value for the dependee's updated state.
*/
update: function (selector, state, value) {
// Only act when the 'new' value is actually new.
if (value !== this.values[selector][state.name]) {
this.values[selector][state.name] = value;
this.reevaluate();
}
},
/**
* Triggers change events in case a state changed.
*/
reevaluate: function () {
// Check whether any constraint for this dependent state is satisifed.
var value = this.verifyConstraints(this.constraints);
// Only invoke a state change event when the value actually changed.
if (value !== this.oldValue) {
// Store the new value so that we can compare later whether the value
// actually changed.
this.oldValue = value;
// Normalize the value to match the normalized state name.
value = invert(value, this.state.invert);
// By adding "trigger: true", we ensure that state changes don't go into
// infinite loops.
this.element.trigger({ type: 'state:' + this.state, value: value, trigger: true });
}
},
/**
* Evaluates child constraints to determine if a constraint is satisfied.
*
* @param constraints
* A constraint object or an array of constraints.
* @param selector
* The selector for these constraints. If undefined, there isn't yet a
* selector that these constraints apply to. In that case, the keys of the
* object are interpreted as the selector if encountered.
*
* @return
* true or false, depending on whether these constraints are satisfied.
*/
verifyConstraints: function(constraints, selector) {
var result;
if ($.isArray(constraints)) {
// This constraint is an array (OR or XOR).
var hasXor = $.inArray('xor', constraints) === -1;
for (var i = 0, len = constraints.length; i < len; i++) {
if (constraints[i] != 'xor') {
var constraint = this.checkConstraints(constraints[i], selector, i);
// Return if this is OR and we have a satisfied constraint or if this
// is XOR and we have a second satisfied constraint.
if (constraint && (hasXor || result)) {
return hasXor;
}
result = result || constraint;
}
}
}
// Make sure we don't try to iterate over things other than objects. This
// shouldn't normally occur, but in case the condition definition is bogus,
// we don't want to end up with an infinite loop.
else if ($.isPlainObject(constraints)) {
// This constraint is an object (AND).
for (var n in constraints) {
if (constraints.hasOwnProperty(n)) {
result = ternary(result, this.checkConstraints(constraints[n], selector, n));
// False and anything else will evaluate to false, so return when any
// false condition is found.
if (result === false) { return false; }
}
}
}
return result;
},
/**
* Checks whether the value matches the requirements for this constraint.
*
* @param value
* Either the value of a state or an array/object of constraints. In the
* latter case, resolving the constraint continues.
* @param selector
* The selector for this constraint. If undefined, there isn't yet a
* selector that this constraint applies to. In that case, the state key is
* propagates to a selector and resolving continues.
* @param state
* The state to check for this constraint. If undefined, resolving
* continues.
* If both selector and state aren't undefined and valid non-numeric
* strings, a lookup for the actual value of that selector's state is
* performed. This parameter is not a State object but a pristine state
* string.
*
* @return
* true or false, depending on whether this constraint is satisfied.
*/
checkConstraints: function(value, selector, state) {
// Normalize the last parameter. If it's non-numeric, we treat it either as
// a selector (in case there isn't one yet) or as a trigger/state.
if (typeof state !== 'string' || (/[0-9]/).test(state[0])) {
state = null;
}
else if (typeof selector === 'undefined') {
// Propagate the state to the selector when there isn't one yet.
selector = state;
state = null;
}
if (state !== null) {
// constraints is the actual constraints of an element to check for.
state = states.State.sanitize(state);
return invert(this.compare(value, selector, state), state.invert);
}
else {
// Resolve this constraint as an AND/OR operator.
return this.verifyConstraints(value, selector);
}
},
/**
* Gathers information about all required triggers.
*/
getDependees: function() {
var cache = {};
// Swivel the lookup function so that we can record all available selector-
// state combinations for initialization.
var _compare = this.compare;
this.compare = function(reference, selector, state) {
(cache[selector] || (cache[selector] = [])).push(state.name);
// Return nothing (=== undefined) so that the constraint loops are not
// broken.
};
// This call doesn't actually verify anything but uses the resolving
// mechanism to go through the constraints array, trying to look up each
// value. Since we swivelled the compare function, this comparison returns
// undefined and lookup continues until the very end. Instead of lookup up
// the value, we record that combination of selector and state so that we
// can initialize all triggers.
this.verifyConstraints(this.constraints);
// Restore the original function.
this.compare = _compare;
return cache;
}
};
states.Trigger = function (args) {
$.extend(this, args);
if (this.state in states.Trigger.states) {
this.element = $(this.selector);
// Only call the trigger initializer when it wasn't yet attached to this
// element. Otherwise we'd end up with duplicate events.
if (!this.element.data('trigger:' + this.state)) {
this.initialize();
}
}
};
states.Trigger.prototype = {
initialize: function () {
var trigger = states.Trigger.states[this.state];
if (typeof trigger == 'function') {
// We have a custom trigger initialization function.
trigger.call(window, this.element);
}
else {
for (var event in trigger) {
if (trigger.hasOwnProperty(event)) {
this.defaultTrigger(event, trigger[event]);
}
}
}
// Mark this trigger as initialized for this element.
this.element.data('trigger:' + this.state, true);
},
defaultTrigger: function (event, valueFn) {
var oldValue = valueFn.call(this.element);
// Attach the event callback.
this.element.bind(event, $.proxy(function (e) {
var value = valueFn.call(this.element, e);
// Only trigger the event if the value has actually changed.
if (oldValue !== value) {
this.element.trigger({ type: 'state:' + this.state, value: value, oldValue: oldValue });
oldValue = value;
}
}, this));
states.postponed.push($.proxy(function () {
// Trigger the event once for initialization purposes.
this.element.trigger({ type: 'state:' + this.state, value: oldValue, oldValue: null });
}, this));
}
};
/**
* This list of states contains functions that are used to monitor the state
* of an element. Whenever an element depends on the state of another element,
* one of these trigger functions is added to the dependee so that the
* dependent element can be updated.
*/
states.Trigger.states = {
// 'empty' describes the state to be monitored
empty: {
// 'keyup' is the (native DOM) event that we watch for.
'keyup': function () {
// The function associated to that trigger returns the new value for the
// state.
return this.val() == '';
}
},
checked: {
'change': function () {
return this.attr('checked');
}
},
// For radio buttons, only return the value if the radio button is selected.
value: {
'keyup': function () {
// Radio buttons share the same :input[name="key"] selector.
if (this.length > 1) {
// Initial checked value of radios is undefined, so we return false.
return this.filter(':checked').val() || false;
}
return this.val();
},
'change': function () {
// Radio buttons share the same :input[name="key"] selector.
if (this.length > 1) {
// Initial checked value of radios is undefined, so we return false.
return this.filter(':checked').val() || false;
}
return this.val();
}
},
collapsed: {
'collapsed': function(e) {
return (typeof e !== 'undefined' && 'value' in e) ? e.value : this.is('.collapsed');
}
}
};
/**
* A state object is used for describing the state and performing aliasing.
*/
states.State = function(state) {
// We may need the original unresolved name later.
this.pristine = this.name = state;
// Normalize the state name.
while (true) {
// Iteratively remove exclamation marks and invert the value.
while (this.name.charAt(0) == '!') {
this.name = this.name.substring(1);
this.invert = !this.invert;
}
// Replace the state with its normalized name.
if (this.name in states.State.aliases) {
this.name = states.State.aliases[this.name];
}
else {
break;
}
}
};
/**
* Creates a new State object by sanitizing the passed value.
*/
states.State.sanitize = function (state) {
if (state instanceof states.State) {
return state;
}
else {
return new states.State(state);
}
};
/**
* This list of aliases is used to normalize states and associates negated names
* with their respective inverse state.
*/
states.State.aliases = {
'enabled': '!disabled',
'invisible': '!visible',
'invalid': '!valid',
'untouched': '!touched',
'optional': '!required',
'filled': '!empty',
'unchecked': '!checked',
'irrelevant': '!relevant',
'expanded': '!collapsed',
'readwrite': '!readonly'
};
states.State.prototype = {
invert: false,
/**
* Ensures that just using the state object returns the name.
*/
toString: function() {
return this.name;
}
};
/**
* Global state change handlers. These are bound to "document" to cover all
* elements whose state changes. Events sent to elements within the page
* bubble up to these handlers. We use this system so that themes and modules
* can override these state change handlers for particular parts of a page.
*/
$(document).bind('state:disabled', function(e) {
// Only act when this change was triggered by a dependency and not by the
// element monitoring itself.
if (e.trigger) {
$(e.target)
.attr('disabled', e.value)
.closest('.form-item, .form-submit, .form-wrapper').toggleClass('form-disabled', e.value)
.find('select, input, textarea').attr('disabled', e.value);
// Note: WebKit nightlies don't reflect that change correctly.
// See https://bugs.webkit.org/show_bug.cgi?id=23789
}
});
$(document).bind('state:required', function(e) {
if (e.trigger) {
if (e.value) {
$(e.target).closest('.form-item, .form-wrapper').find('label').append('<span class="form-required">*</span>');
}
else {
$(e.target).closest('.form-item, .form-wrapper').find('label .form-required').remove();
}
}
});
$(document).bind('state:visible', function(e) {
if (e.trigger) {
$(e.target).closest('.form-item, .form-submit, .form-wrapper').toggle(e.value);
}
});
$(document).bind('state:checked', function(e) {
if (e.trigger) {
$(e.target).attr('checked', e.value);
}
});
$(document).bind('state:collapsed', function(e) {
if (e.trigger) {
if ($(e.target).is('.collapsed') !== e.value) {
$('> legend a', e.target).click();
}
}
});
/**
* These are helper functions implementing addition "operators" and don't
* implement any logic that is particular to states.
*/
// Bitwise AND with a third undefined state.
function ternary (a, b) {
return typeof a === 'undefined' ? b : (typeof b === 'undefined' ? a : a && b);
}
// Inverts a (if it's not undefined) when invert is true.
function invert (a, invert) {
return (invert && typeof a !== 'undefined') ? !a : a;
}
// Compares two values while ignoring undefined values.
function compare (a, b) {
return (a === b) ? (typeof a === 'undefined' ? a : true) : (typeof a === 'undefined' || typeof b === 'undefined');
}
})(jQuery);
;
(function ($) {
/**
* Retrieves the summary for the first element.
*/
$.fn.drupalGetSummary = function () {
var callback = this.data('summaryCallback');
return (this[0] && callback) ? $.trim(callback(this[0])) : '';
};
/**
* Sets the summary for all matched elements.
*
* @param callback
* Either a function that will be called each time the summary is
* retrieved or a string (which is returned each time).
*/
$.fn.drupalSetSummary = function (callback) {
var self = this;
// To facilitate things, the callback should always be a function. If it's
// not, we wrap it into an anonymous function which just returns the value.
if (typeof callback != 'function') {
var val = callback;
callback = function () { return val; };
}
return this
.data('summaryCallback', callback)
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind('formUpdated.summary')
.bind('formUpdated.summary', function () {
self.trigger('summaryUpdated');
})
// The actual summaryUpdated handler doesn't fire when the callback is
// changed, so we have to do this manually.
.trigger('summaryUpdated');
};
/**
* Sends a 'formUpdated' event each time a form element is modified.
*/
Drupal.behaviors.formUpdated = {
attach: function (context) {
// These events are namespaced so that we can remove them later.
var events = 'change.formUpdated click.formUpdated blur.formUpdated keyup.formUpdated';
$(context)
// Since context could be an input element itself, it's added back to
// the jQuery object and filtered again.
.find(':input').andSelf().filter(':input')
// To prevent duplicate events, the handlers are first removed and then
// (re-)added.
.unbind(events).bind(events, function () {
$(this).trigger('formUpdated');
});
}
};
/**
* Prepopulate form fields with information from the visitor cookie.
*/
Drupal.behaviors.fillUserInfoFromCookie = {
attach: function (context, settings) {
$('form.user-info-from-cookie').once('user-info-from-cookie', function () {
var formContext = this;
$.each(['name', 'mail', 'homepage'], function () {
var $element = $('[name=' + this + ']', formContext);
var cookie = $.cookie('Drupal.visitor.' + this);
if ($element.length && cookie) {
$element.val(cookie);
}
});
});
}
};
})(jQuery);
;
| Java |
/**
* MaNGOS is a full featured server for World of Warcraft, supporting
* the following clients: 1.12.x, 2.4.3, 3.3.5a, 4.3.4a and 5.4.8
*
* Copyright (C) 2005-2015 MaNGOS project <http://getmangos.eu>
*
* 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
#ifndef MANGOS_CREATIONPOLICY_H
#define MANGOS_CREATIONPOLICY_H
#include <stdlib.h>
#include "Platform/Define.h"
namespace MaNGOS
{
template<class T>
/**
* @brief OperatorNew policy creates an object on the heap using new.
*
*/
class MANGOS_DLL_DECL OperatorNew
{
public:
/**
* @brief
*
* @return T
*/
static T* Create()
{
return (new T);
}
/**
* @brief
*
* @param obj
*/
static void Destroy(T* obj)
{
delete obj;
}
};
template<class T>
/**
* @brief LocalStaticCreation policy creates an object on the stack the first time call Create.
*
*/
class MANGOS_DLL_DECL LocalStaticCreation
{
/**
* @brief
*
*/
union MaxAlign
{
char t_[sizeof(T)]; /**< TODO */
short int shortInt_; /**< TODO */
int int_; /**< TODO */
long int longInt_; /**< TODO */
float float_; /**< TODO */
double double_; /**< TODO */
long double longDouble_; /**< TODO */
struct Test;
int Test::* pMember_; /**< TODO */
/**
* @brief
*
* @param Test::pMemberFn_)(int
* @return int
*/
int (Test::*pMemberFn_)(int);
};
public:
/**
* @brief
*
* @return T
*/
static T* Create()
{
static MaxAlign si_localStatic;
return new(&si_localStatic) T;
}
/**
* @brief
*
* @param obj
*/
static void Destroy(T* obj)
{
obj->~T();
}
};
/**
* CreateUsingMalloc by pass the memory manger.
*/
template<class T>
/**
* @brief
*
*/
class MANGOS_DLL_DECL CreateUsingMalloc
{
public:
/**
* @brief
*
* @return T
*/
static T* Create()
{
void* p = malloc(sizeof(T));
if (!p)
{ return NULL; }
return new(p) T;
}
/**
* @brief
*
* @param p
*/
static void Destroy(T* p)
{
p->~T();
free(p);
}
};
template<class T, class CALL_BACK>
/**
* @brief CreateOnCallBack creates the object base on the call back.
*
*/
class MANGOS_DLL_DECL CreateOnCallBack
{
public:
/**
* @brief
*
* @return T
*/
static T* Create()
{
return CALL_BACK::createCallBack();
}
/**
* @brief
*
* @param p
*/
static void Destroy(T* p)
{
CALL_BACK::destroyCallBack(p);
}
};
}
#endif
| Java |
<?php
/**
* Profiler showing execution trace.
*
* 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.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Profiler
*/
/**
* Execution trace
* @todo document methods (?)
* @ingroup Profiler
*/
class ProfilerSimpleTrace extends ProfilerSimple {
var $trace = "Beginning trace: \n";
var $memory = 0;
function profileIn( $functionname ) {
parent::profileIn( $functionname );
$this->trace .= " " . sprintf("%6.1f",$this->memoryDiff()) .
str_repeat( " ", count($this->mWorkStack)) . " > " . $functionname . "\n";
}
function profileOut($functionname) {
global $wgDebugFunctionEntry;
if ( $wgDebugFunctionEntry ) {
$this->debug(str_repeat(' ', count($this->mWorkStack) - 1).'Exiting '.$functionname."\n");
}
list( $ofname, /* $ocount */ , $ortime ) = array_pop( $this->mWorkStack );
if ( !$ofname ) {
$this->trace .= "Profiling error: $functionname\n";
} else {
if ( $functionname == 'close' ) {
$message = "Profile section ended by close(): {$ofname}";
$functionname = $ofname;
$this->trace .= $message . "\n";
}
elseif ( $ofname != $functionname ) {
$this->trace .= "Profiling error: in({$ofname}), out($functionname)";
}
$elapsedreal = $this->getTime() - $ortime;
$this->trace .= sprintf( "%03.6f %6.1f", $elapsedreal, $this->memoryDiff() ) .
str_repeat(" ", count( $this->mWorkStack ) + 1 ) . " < " . $functionname . "\n";
}
}
function memoryDiff() {
$diff = memory_get_usage() - $this->memory;
$this->memory = memory_get_usage();
return $diff / 1024;
}
function logData() {
if ( php_sapi_name() === 'cli' ) {
print "<!-- \n {$this->trace} \n -->";
} elseif ( $this->getContentType() === 'text/html' ) {
print "<!-- \n {$this->trace} \n -->";
} elseif ( $this->getContentType() === 'text/javascript' ) {
print "\n/*\n {$this->trace}\n*/";
} elseif ( $this->getContentType() === 'text/css' ) {
print "\n/*\n {$this->trace}\n*/";
}
}
}
| Java |
/* ***** BEGIN LICENSE BLOCK *****
* Source last modified: $Id: hxstat.h,v 1.7 2004/07/09 18:21:50 hubbe Exp $
*
* Portions Copyright (c) 1995-2004 RealNetworks, Inc. All Rights Reserved.
*
* The contents of this file, and the files included with this file,
* are subject to the current version of the RealNetworks Public
* Source License (the "RPSL") available at
* http://www.helixcommunity.org/content/rpsl unless you have licensed
* the file under the current version of the RealNetworks Community
* Source License (the "RCSL") available at
* http://www.helixcommunity.org/content/rcsl, in which case the RCSL
* will apply. You may also obtain the license terms directly from
* RealNetworks. You may not use this file except in compliance with
* the RPSL or, if you have a valid RCSL with RealNetworks applicable
* to this file, the RCSL. Please see the applicable RPSL or RCSL for
* the rights, obligations and limitations governing use of the
* contents of the file.
*
* Alternatively, the contents of this file may be used under the
* terms of the GNU General Public License Version 2 or later (the
* "GPL") in which case the provisions of the GPL are applicable
* instead of those above. If you wish to allow use of your version of
* this file only under the terms of the GPL, and not to allow others
* to use your version of this file under the terms of either the RPSL
* or RCSL, indicate your decision by deleting the provisions above
* and replace them with the notice and other provisions required by
* the GPL. If you do not delete the provisions above, a recipient may
* use your version of this file under the terms of any one of the
* RPSL, the RCSL or the GPL.
*
* This file is part of the Helix DNA Technology. RealNetworks is the
* developer of the Original Code and owns the copyrights in the
* portions it created.
*
* This file, and the files included with this file, is distributed
* and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS
* ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET
* ENJOYMENT OR NON-INFRINGEMENT.
*
* Technology Compatibility Kit Test Suite(s) Location:
* http://www.helixcommunity.org/content/tck
*
* Contributor(s):
*
* ***** END LICENSE BLOCK ***** */
#ifndef _HXSTATLOG_
#define _HXSTATLOG_
#ifdef _MACINTOSH
#include <stdlib.h>
#endif
#ifdef _WINDOWS
#include <stdio.h>
#endif
#include "hlxclib/stdarg.h"
#include "hxresult.h"
#include "hxtypes.h"
#include "../fileio/pub/chxdataf.h"
#ifdef HELIX_CONFIG_NOSTATICS
# include "globals/hxglobals.h"
#endif
class HXStatLog
{
public:
HXStatLog();
~HXStatLog();
HX_RESULT Open_Read (const char * filename);
HX_RESULT Open_Write (const char * filename);
HX_RESULT Open_WriteNoAppend (const char * filename);
HX_RESULT Close (void);
LONG32 Read (char *buf, ULONG32 max_buf_length);
LONG32 Write (char *buf, ULONG32 buf_length);
HX_RESULT StatPrintf (const char* fmt, ...);
HX_RESULT ReadLine (char *buf, ULONG32 buf_length);
HX_RESULT Seek (ULONG32 offset, UINT16 fromWhere);
ULONG32 Tell (void);
private:
CHXDataFile* mStatFile;
char* mStatBuffer;
char* mStatCurrentPosition;
INT16 mStatBufferLength;
INT16 mStatBytesLeft;
};
/////
// This is static implementation of the above class so that
// the log info can be written from anywahere in the player to the same
// log file...(opened once for each session)
/////
class HXStaticStatLog
{
public:
static HX_RESULT Open_Read(const char* filename)
{
if (LogFileInstance()) return HXR_ALREADY_OPEN;
HX_RESULT theErr = HXR_OK;
LogFileInstance() = new HXStatLog;
if (!LogFileInstance())
theErr = HXR_OUTOFMEMORY;
if (!theErr)
{
theErr = LogFileInstance()->Open_Read(filename);
}
// error in opening file?
if (theErr && LogFileInstance())
{
delete LogFileInstance();
LogFileInstance() = NULL;
}
return theErr;
}
static HX_RESULT Open_Write(const char* filename)
{
if (LogFileInstance()) return HXR_ALREADY_OPEN;
HX_RESULT theErr = HXR_OK;
LogFileInstance() = new HXStatLog;
if (!LogFileInstance())
theErr = HXR_OUTOFMEMORY;
if (!theErr)
{
theErr = LogFileInstance()->Open_Write(filename);
}
// error in opening file?
if (theErr && LogFileInstance())
{
delete LogFileInstance();
LogFileInstance() = NULL;
}
return theErr;
}
static HX_RESULT Close(void)
{
if (!LogFileInstance()) return HXR_INVALID_FILE;
HX_RESULT theErr = HXR_OK;
theErr = LogFileInstance()->Close();
delete LogFileInstance();
LogFileInstance() = NULL;
return theErr;
}
static LONG32 Read(char* buf, ULONG32 max_buf_length)
{
if (!LogFileInstance()) return -1;
return LogFileInstance()->Read(buf, max_buf_length);
}
static LONG32 Write(char* buf, ULONG32 buf_length)
{
if (!LogFileInstance()) return -1;
return LogFileInstance()->Write(buf, buf_length);
}
static HX_RESULT StatPrintf(const char* fmt, ...)
{
if (!LogFileInstance()) return HXR_INVALID_FILE;
HX_RESULT theErr = HXR_OK;
#ifndef _MACINTOSH
char buf[8096]; /* Flawfinder: ignore */
LONG32 bytes_written = 0;
LONG32 bytes_towrite = 0;
va_list args;
va_start(args, fmt);
bytes_towrite = vsnprintf(buf, sizeof(buf), fmt, args); // scanf
va_end(args);
if (bytes_towrite < 0)
theErr = HXR_INVALID_PATH;
if (!theErr)
{
bytes_written = LogFileInstance()->Write(buf, (ULONG32) bytes_towrite);
if (bytes_written != bytes_towrite)
theErr = HXR_INVALID_PATH;
}
#endif
return theErr;
}
static HX_RESULT ReadLine (char *buf, ULONG32 buf_length)
{
if (!LogFileInstance()) return HXR_INVALID_FILE;
return LogFileInstance()->ReadLine(buf, buf_length);
}
static HX_RESULT Seek (ULONG32 offset, UINT16 fromWhere)
{
if (!LogFileInstance()) return HXR_INVALID_FILE;
return LogFileInstance()->Seek(offset, fromWhere);
}
static ULONG32 Tell (void)
{
if (!LogFileInstance()) return (ULONG32) -1;
return LogFileInstance()->Tell();
}
static inline HXStatLog*& LogFileInstance()
{
#if defined(HELIX_CONFIG_NOSTATICS)
static const HXStatLog* const pmLogFile = NULL;
return (HXStatLog*&)HXGlobalPtr::Get(&pmLogFile, NULL );
#else
static HXStatLog* pmLogFile = NULL;
return pmLogFile;
#endif
}
};
#endif //_HXSTATLOG_
| Java |
# OpenSSL is more stable then ssl
# but OpenSSL is different then ssl, so need a wrapper
import sys
import os
import OpenSSL
SSLError = OpenSSL.SSL.WantReadError
import select
import time
import socket
import logging
ssl_version = ''
class SSLConnection(object):
"""OpenSSL Connection Wrapper"""
def __init__(self, context, sock):
self._context = context
self._sock = sock
self._connection = OpenSSL.SSL.Connection(context, sock)
self._makefile_refs = 0
def __getattr__(self, attr):
if attr not in ('_context', '_sock', '_connection', '_makefile_refs'):
return getattr(self._connection, attr)
def __iowait(self, io_func, *args, **kwargs):
timeout = self._sock.gettimeout() or 0.1
fd = self._sock.fileno()
time_start = time.time()
while True:
try:
return io_func(*args, **kwargs)
except (OpenSSL.SSL.WantReadError, OpenSSL.SSL.WantX509LookupError):
sys.exc_clear()
_, _, errors = select.select([fd], [], [fd], timeout)
if errors:
break
time_now = time.time()
if time_now - time_start > timeout:
break
except OpenSSL.SSL.WantWriteError:
sys.exc_clear()
_, _, errors = select.select([], [fd], [fd], timeout)
if errors:
break
time_now = time.time()
if time_now - time_start > timeout:
break
def accept(self):
sock, addr = self._sock.accept()
client = OpenSSL.SSL.Connection(sock._context, sock)
return client, addr
def do_handshake(self):
self.__iowait(self._connection.do_handshake)
def connect(self, *args, **kwargs):
return self.__iowait(self._connection.connect, *args, **kwargs)
def __send(self, data, flags=0):
try:
return self.__iowait(self._connection.send, data, flags)
except OpenSSL.SSL.SysCallError as e:
if e[0] == -1 and not data:
# errors when writing empty strings are expected and can be ignored
return 0
raise
def __send_memoryview(self, data, flags=0):
if hasattr(data, 'tobytes'):
data = data.tobytes()
return self.__send(data, flags)
send = __send if sys.version_info >= (2, 7, 5) else __send_memoryview
def recv(self, bufsiz, flags=0):
pending = self._connection.pending()
if pending:
return self._connection.recv(min(pending, bufsiz))
try:
return self.__iowait(self._connection.recv, bufsiz, flags)
except OpenSSL.SSL.ZeroReturnError:
return ''
except OpenSSL.SSL.SysCallError as e:
if e[0] == -1 and 'Unexpected EOF' in e[1]:
# errors when reading empty strings are expected and can be ignored
return ''
raise
def read(self, bufsiz, flags=0):
return self.recv(bufsiz, flags)
def write(self, buf, flags=0):
return self.sendall(buf, flags)
def close(self):
if self._makefile_refs < 1:
self._connection = None
if self._sock:
socket.socket.close(self._sock)
else:
self._makefile_refs -= 1
def makefile(self, mode='r', bufsize=-1):
self._makefile_refs += 1
return socket._fileobject(self, mode, bufsize, close=True)
@staticmethod
def context_builder(ca_certs=None, cipher_suites=('ALL:!RC4-SHA:!ECDHE-RSA-RC4-SHA:!ECDHE-RSA-AES128-GCM-SHA256:!AES128-GCM-SHA256',)):
# 'ALL', '!aNULL', '!eNULL'
global ssl_version
if not ssl_version:
if hasattr(OpenSSL.SSL, "TLSv1_2_METHOD"):
ssl_version = "TLSv1_2"
elif hasattr(OpenSSL.SSL, "TLSv1_1_METHOD"):
ssl_version = "TLSv1_1"
elif hasattr(OpenSSL.SSL, "TLSv1_METHOD"):
ssl_version = "TLSv1"
else:
ssl_version = "SSLv23"
if sys.platform == "darwin":
ssl_version = "TLSv1"
logging.info("SSL use version:%s", ssl_version)
protocol_version = getattr(OpenSSL.SSL, '%s_METHOD' % ssl_version)
ssl_context = OpenSSL.SSL.Context(protocol_version)
if ca_certs:
ssl_context.load_verify_locations(os.path.abspath(ca_certs))
ssl_context.set_verify(OpenSSL.SSL.VERIFY_PEER, lambda c, x, e, d, ok: ok)
else:
ssl_context.set_verify(OpenSSL.SSL.VERIFY_NONE, lambda c, x, e, d, ok: ok)
ssl_context.set_cipher_list(':'.join(cipher_suites))
return ssl_context
| Java |
/*
Lucy the Diamond Girl - Game where player collects diamonds.
Copyright (C) 2005-2015 Joni Yrjänä <joniyrjana@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.
Complete license can be found in the LICENSE file.
*/
#include "widget.h"
#include <assert.h>
void widget_set_navigation_right(struct widget * widget, struct widget * right)
{
assert(widget != NULL);
assert(right != NULL);
assert(widget != right);
assert(widget->navigation_right_ == NULL);
widget->navigation_right_ = right;
stack_push(widget->widgets_linking_to_this, right);
stack_push(right->widgets_linking_to_this, widget);
}
| Java |
/* Eye Of Mate - Main Window
*
* Copyright (C) 2000-2008 The Free Software Foundation
*
* Author: Lucas Rocha <lucasr@gnome.org>
*
* Based on code by:
* - Federico Mena-Quintero <federico@gnu.org>
* - Jens Finke <jens@gnome.org>
* Based on evince code (shell/ev-window.c) by:
* - Martin Kretzschmar <martink@gnome.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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <math.h>
#include "eom-window.h"
#include "eom-scroll-view.h"
#include "eom-debug.h"
#include "eom-file-chooser.h"
#include "eom-thumb-view.h"
#include "eom-list-store.h"
#include "eom-sidebar.h"
#include "eom-statusbar.h"
#include "eom-preferences-dialog.h"
#include "eom-properties-dialog.h"
#include "eom-print.h"
#include "eom-error-message-area.h"
#include "eom-application.h"
#include "eom-thumb-nav.h"
#include "eom-config-keys.h"
#include "eom-job-queue.h"
#include "eom-jobs.h"
#include "eom-util.h"
#include "eom-save-as-dialog-helper.h"
#include "eom-plugin-engine.h"
#include "eom-close-confirmation-dialog.h"
#include "eom-clipboard-handler.h"
#include "eom-enum-types.h"
#include "egg-toolbar-editor.h"
#include "egg-editable-toolbar.h"
#include "egg-toolbars-model.h"
#include <glib.h>
#include <glib-object.h>
#include <glib/gi18n.h>
#include <gio/gio.h>
#include <gdk/gdkkeysyms.h>
#include <gio/gdesktopappinfo.h>
#include <gtk/gtk.h>
#if HAVE_LCMS
#include <X11/Xlib.h>
#include <X11/Xatom.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h>
#endif
#include <lcms2.h>
#endif
#define MATE_DESKTOP_USE_UNSTABLE_API
#include <libmate-desktop/mate-desktop-utils.h>
#include <libmate-desktop/mate-aboutdialog.h>
#define EOM_WINDOW_GET_PRIVATE(object) \
(G_TYPE_INSTANCE_GET_PRIVATE ((object), EOM_TYPE_WINDOW, EomWindowPrivate))
G_DEFINE_TYPE (EomWindow, eom_window, GTK_TYPE_WINDOW);
#define EOM_WINDOW_MIN_WIDTH 440
#define EOM_WINDOW_MIN_HEIGHT 350
#define EOM_WINDOW_DEFAULT_WIDTH 540
#define EOM_WINDOW_DEFAULT_HEIGHT 450
#define EOM_WINDOW_FULLSCREEN_TIMEOUT 5 * 1000
#define EOM_WINDOW_FULLSCREEN_POPUP_THRESHOLD 5
#define EOM_RECENT_FILES_GROUP "Graphics"
#define EOM_RECENT_FILES_APP_NAME "Eye of MATE Image Viewer"
#define EOM_RECENT_FILES_LIMIT 5
#define EOM_WALLPAPER_FILENAME "eom-wallpaper"
#define is_rtl (gtk_widget_get_default_direction () == GTK_TEXT_DIR_RTL)
#if GTK_CHECK_VERSION (3, 2, 0)
#define gtk_hbox_new(X,Y) gtk_box_new(GTK_ORIENTATION_HORIZONTAL,Y)
#define gtk_vbox_new(X,Y) gtk_box_new(GTK_ORIENTATION_VERTICAL,Y)
#endif
typedef enum {
EOM_WINDOW_STATUS_UNKNOWN,
EOM_WINDOW_STATUS_INIT,
EOM_WINDOW_STATUS_NORMAL
} EomWindowStatus;
enum {
PROP_0,
PROP_COLLECTION_POS,
PROP_COLLECTION_RESIZABLE,
PROP_STARTUP_FLAGS
};
enum {
SIGNAL_PREPARED,
SIGNAL_LAST
};
static guint signals[SIGNAL_LAST] = { 0 };
struct _EomWindowPrivate {
GSettings *view_settings;
GSettings *ui_settings;
GSettings *fullscreen_settings;
GSettings *lockdown_settings;
EomListStore *store;
EomImage *image;
EomWindowMode mode;
EomWindowStatus status;
GtkUIManager *ui_mgr;
GtkWidget *box;
GtkWidget *layout;
GtkWidget *cbox;
GtkWidget *view;
GtkWidget *sidebar;
GtkWidget *thumbview;
GtkWidget *statusbar;
GtkWidget *nav;
GtkWidget *message_area;
GtkWidget *toolbar;
GObject *properties_dlg;
GtkActionGroup *actions_window;
GtkActionGroup *actions_image;
GtkActionGroup *actions_collection;
GtkActionGroup *actions_recent;
GtkWidget *fullscreen_popup;
GSource *fullscreen_timeout_source;
gboolean slideshow_random;
gboolean slideshow_loop;
gint slideshow_switch_timeout;
GSource *slideshow_switch_source;
guint recent_menu_id;
EomJob *load_job;
EomJob *transform_job;
EomJob *save_job;
GFile *last_save_as_folder;
EomJob *copy_job;
guint image_info_message_cid;
guint tip_message_cid;
guint copy_file_cid;
EomStartupFlags flags;
GSList *file_list;
EomWindowCollectionPos collection_position;
gboolean collection_resizable;
GtkActionGroup *actions_open_with;
guint open_with_menu_id;
gboolean save_disabled;
gboolean needs_reload_confirmation;
GtkPageSetup *page_setup;
#ifdef HAVE_LCMS
cmsHPROFILE *display_profile;
#endif
};
static void eom_window_cmd_fullscreen (GtkAction *action, gpointer user_data);
static void eom_window_run_fullscreen (EomWindow *window, gboolean slideshow);
static void eom_window_cmd_slideshow (GtkAction *action, gpointer user_data);
static void eom_window_cmd_pause_slideshow (GtkAction *action, gpointer user_data);
static void eom_window_stop_fullscreen (EomWindow *window, gboolean slideshow);
static void eom_job_load_cb (EomJobLoad *job, gpointer data);
static void eom_job_save_progress_cb (EomJobSave *job, float progress, gpointer data);
static void eom_job_progress_cb (EomJobLoad *job, float progress, gpointer data);
static void eom_job_transform_cb (EomJobTransform *job, gpointer data);
static void fullscreen_set_timeout (EomWindow *window);
static void fullscreen_clear_timeout (EomWindow *window);
static void update_action_groups_state (EomWindow *window);
static void open_with_launch_application_cb (GtkAction *action, gpointer callback_data);
static void eom_window_update_openwith_menu (EomWindow *window, EomImage *image);
static void eom_window_list_store_image_added (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data);
static void eom_window_list_store_image_removed (GtkTreeModel *tree_model,
GtkTreePath *path,
gpointer user_data);
static void eom_window_set_wallpaper (EomWindow *window, const gchar *filename, const gchar *visible_filename);
static gboolean eom_window_save_images (EomWindow *window, GList *images);
static void eom_window_finish_saving (EomWindow *window);
static GAppInfo *get_appinfo_for_editor (EomWindow *window);
static GQuark
eom_window_error_quark (void)
{
static GQuark q = 0;
if (q == 0)
q = g_quark_from_static_string ("eom-window-error-quark");
return q;
}
static void
eom_window_set_collection_mode (EomWindow *window, EomWindowCollectionPos position, gboolean resizable)
{
EomWindowPrivate *priv;
GtkWidget *hpaned;
EomThumbNavMode mode = EOM_THUMB_NAV_MODE_ONE_ROW;
eom_debug (DEBUG_PREFERENCES);
g_return_if_fail (EOM_IS_WINDOW (window));
priv = window->priv;
if (priv->collection_position == position &&
priv->collection_resizable == resizable)
return;
priv->collection_position = position;
priv->collection_resizable = resizable;
hpaned = gtk_widget_get_parent (priv->sidebar);
g_object_ref (hpaned);
g_object_ref (priv->nav);
gtk_container_remove (GTK_CONTAINER (priv->layout), hpaned);
gtk_container_remove (GTK_CONTAINER (priv->layout), priv->nav);
gtk_widget_destroy (priv->layout);
switch (position) {
case EOM_WINDOW_COLLECTION_POS_BOTTOM:
case EOM_WINDOW_COLLECTION_POS_TOP:
if (resizable) {
mode = EOM_THUMB_NAV_MODE_MULTIPLE_ROWS;
#if GTK_CHECK_VERSION (3, 2, 0)
priv->layout = gtk_paned_new (GTK_ORIENTATION_VERTICAL);
#else
priv->layout = gtk_vpaned_new ();
#endif
if (position == EOM_WINDOW_COLLECTION_POS_BOTTOM) {
gtk_paned_pack1 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE);
gtk_paned_pack2 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE);
} else {
gtk_paned_pack1 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE);
gtk_paned_pack2 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE);
}
} else {
mode = EOM_THUMB_NAV_MODE_ONE_ROW;
priv->layout = gtk_vbox_new (FALSE, 2);
if (position == EOM_WINDOW_COLLECTION_POS_BOTTOM) {
gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0);
} else {
gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0);
}
}
break;
case EOM_WINDOW_COLLECTION_POS_LEFT:
case EOM_WINDOW_COLLECTION_POS_RIGHT:
if (resizable) {
mode = EOM_THUMB_NAV_MODE_MULTIPLE_COLUMNS;
#if GTK_CHECK_VERSION (3, 2, 0)
priv->layout = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL);
#else
priv->layout = gtk_hpaned_new ();
#endif
if (position == EOM_WINDOW_COLLECTION_POS_LEFT) {
gtk_paned_pack1 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE);
gtk_paned_pack2 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE);
} else {
gtk_paned_pack1 (GTK_PANED (priv->layout), hpaned, TRUE, FALSE);
gtk_paned_pack2 (GTK_PANED (priv->layout), priv->nav, FALSE, TRUE);
}
} else {
mode = EOM_THUMB_NAV_MODE_ONE_COLUMN;
priv->layout = gtk_hbox_new (FALSE, 2);
if (position == EOM_WINDOW_COLLECTION_POS_LEFT) {
gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0);
} else {
gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0);
gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0);
}
}
break;
}
gtk_box_pack_end (GTK_BOX (priv->cbox), priv->layout, TRUE, TRUE, 0);
eom_thumb_nav_set_mode (EOM_THUMB_NAV (priv->nav), mode);
if (priv->mode != EOM_WINDOW_MODE_UNKNOWN) {
update_action_groups_state (window);
}
}
static void
eom_window_can_save_changed_cb (GSettings *settings, gchar *key, gpointer user_data)
{
EomWindowPrivate *priv;
EomWindow *window;
gboolean save_disabled = FALSE;
GtkAction *action_save, *action_save_as;
eom_debug (DEBUG_PREFERENCES);
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = EOM_WINDOW (user_data)->priv;
save_disabled = g_settings_get_boolean (settings, key);
priv->save_disabled = save_disabled;
action_save =
gtk_action_group_get_action (priv->actions_image, "ImageSave");
action_save_as =
gtk_action_group_get_action (priv->actions_image, "ImageSaveAs");
if (priv->save_disabled) {
gtk_action_set_sensitive (action_save, FALSE);
gtk_action_set_sensitive (action_save_as, FALSE);
} else {
EomImage *image = eom_window_get_image (window);
if (EOM_IS_IMAGE (image)) {
gtk_action_set_sensitive (action_save,
eom_image_is_modified (image));
gtk_action_set_sensitive (action_save_as, TRUE);
}
}
}
#ifdef HAVE_LCMS
static cmsHPROFILE *
eom_window_get_display_profile (GdkScreen *screen)
{
Display *dpy;
Atom icc_atom, type;
int format;
gulong nitems;
gulong bytes_after;
gulong length;
guchar *str;
int result;
cmsHPROFILE *profile;
char *atom_name;
dpy = GDK_DISPLAY_XDISPLAY (gdk_screen_get_display (screen));
if (gdk_screen_get_number (screen) > 0)
atom_name = g_strdup_printf ("_ICC_PROFILE_%d", gdk_screen_get_number (screen));
else
atom_name = g_strdup ("_ICC_PROFILE");
icc_atom = gdk_x11_get_xatom_by_name_for_display (gdk_screen_get_display (screen), atom_name);
g_free (atom_name);
result = XGetWindowProperty (dpy,
GDK_WINDOW_XID (gdk_screen_get_root_window (screen)),
icc_atom,
0,
G_MAXLONG,
False,
XA_CARDINAL,
&type,
&format,
&nitems,
&bytes_after,
(guchar **)&str);
/* TODO: handle bytes_after != 0 */
if ((result == Success) && (type == XA_CARDINAL) && (nitems > 0)) {
switch (format)
{
case 8:
length = nitems;
break;
case 16:
length = sizeof(short) * nitems;
break;
case 32:
length = sizeof(long) * nitems;
break;
default:
eom_debug_message (DEBUG_LCMS, "Unable to read profile, not correcting");
XFree (str);
return NULL;
}
profile = cmsOpenProfileFromMem (str, length);
if (G_UNLIKELY (profile == NULL)) {
eom_debug_message (DEBUG_LCMS,
"Invalid display profile, "
"not correcting");
}
XFree (str);
} else {
profile = NULL;
eom_debug_message (DEBUG_LCMS, "No profile, not correcting");
}
return profile;
}
#endif
static void
update_image_pos (EomWindow *window)
{
EomWindowPrivate *priv;
gint pos = -1, n_images = 0;
priv = window->priv;
n_images = eom_list_store_length (EOM_LIST_STORE (priv->store));
if (n_images > 0) {
pos = eom_list_store_get_pos_by_image (EOM_LIST_STORE (priv->store),
priv->image);
}
/* Images: (image pos) / (n_total_images) */
eom_statusbar_set_image_number (EOM_STATUSBAR (priv->statusbar),
pos + 1,
n_images);
}
static void
update_status_bar (EomWindow *window)
{
EomWindowPrivate *priv;
char *str = NULL;
g_return_if_fail (EOM_IS_WINDOW (window));
eom_debug (DEBUG_WINDOW);
priv = window->priv;
if (priv->image != NULL &&
eom_image_has_data (priv->image, EOM_IMAGE_DATA_DIMENSION)) {
int zoom, width, height;
goffset bytes = 0;
zoom = floor (100 * eom_scroll_view_get_zoom (EOM_SCROLL_VIEW (priv->view)) + 0.5);
eom_image_get_size (priv->image, &width, &height);
bytes = eom_image_get_bytes (priv->image);
if ((width > 0) && (height > 0)) {
char *size_string;
size_string = g_format_size (bytes);
/* Translators: This is the string displayed in the statusbar
* The tokens are from left to right:
* - image width
* - image height
* - image size in bytes
* - zoom in percent */
str = g_strdup_printf (ngettext("%i × %i pixel %s %i%%",
"%i × %i pixels %s %i%%", height),
width,
height,
size_string,
zoom);
g_free (size_string);
}
update_image_pos (window);
}
gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid);
gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid, str ? str : "");
g_free (str);
}
static void
eom_window_set_message_area (EomWindow *window,
GtkWidget *message_area)
{
if (window->priv->message_area == message_area)
return;
if (window->priv->message_area != NULL)
gtk_widget_destroy (window->priv->message_area);
window->priv->message_area = message_area;
if (message_area == NULL) return;
gtk_box_pack_start (GTK_BOX (window->priv->cbox),
window->priv->message_area,
FALSE,
FALSE,
0);
g_object_add_weak_pointer (G_OBJECT (window->priv->message_area),
(void *) &window->priv->message_area);
}
static void
update_action_groups_state (EomWindow *window)
{
EomWindowPrivate *priv;
GtkAction *action_collection;
GtkAction *action_sidebar;
GtkAction *action_fscreen;
GtkAction *action_sshow;
GtkAction *action_print;
gboolean print_disabled = FALSE;
gboolean show_image_collection = FALSE;
gint n_images = 0;
g_return_if_fail (EOM_IS_WINDOW (window));
eom_debug (DEBUG_WINDOW);
priv = window->priv;
action_collection =
gtk_action_group_get_action (priv->actions_window,
"ViewImageCollection");
action_sidebar =
gtk_action_group_get_action (priv->actions_window,
"ViewSidebar");
action_fscreen =
gtk_action_group_get_action (priv->actions_image,
"ViewFullscreen");
action_sshow =
gtk_action_group_get_action (priv->actions_collection,
"ViewSlideshow");
action_print =
gtk_action_group_get_action (priv->actions_image,
"ImagePrint");
g_assert (action_collection != NULL);
g_assert (action_sidebar != NULL);
g_assert (action_fscreen != NULL);
g_assert (action_sshow != NULL);
g_assert (action_print != NULL);
if (priv->store != NULL) {
n_images = eom_list_store_length (EOM_LIST_STORE (priv->store));
}
if (n_images == 0) {
gtk_widget_hide (priv->layout);
gtk_action_group_set_sensitive (priv->actions_window, TRUE);
gtk_action_group_set_sensitive (priv->actions_image, FALSE);
gtk_action_group_set_sensitive (priv->actions_collection, FALSE);
gtk_action_set_sensitive (action_fscreen, FALSE);
gtk_action_set_sensitive (action_sshow, FALSE);
/* If there are no images on model, initialization
stops here. */
if (priv->status == EOM_WINDOW_STATUS_INIT) {
priv->status = EOM_WINDOW_STATUS_NORMAL;
}
} else {
if (priv->flags & EOM_STARTUP_DISABLE_COLLECTION) {
g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION, FALSE);
show_image_collection = FALSE;
} else {
show_image_collection =
g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION);
}
show_image_collection = show_image_collection &&
n_images > 1 &&
priv->mode != EOM_WINDOW_MODE_SLIDESHOW;
gtk_widget_show (priv->layout);
if (show_image_collection)
gtk_widget_show (priv->nav);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action_collection),
show_image_collection);
gtk_action_group_set_sensitive (priv->actions_window, TRUE);
gtk_action_group_set_sensitive (priv->actions_image, TRUE);
gtk_action_set_sensitive (action_fscreen, TRUE);
if (n_images == 1) {
gtk_action_group_set_sensitive (priv->actions_collection, FALSE);
gtk_action_set_sensitive (action_collection, FALSE);
gtk_action_set_sensitive (action_sshow, FALSE);
} else {
gtk_action_group_set_sensitive (priv->actions_collection, TRUE);
gtk_action_set_sensitive (action_sshow, TRUE);
}
if (show_image_collection)
gtk_widget_grab_focus (priv->thumbview);
else
gtk_widget_grab_focus (priv->view);
}
print_disabled = g_settings_get_boolean (priv->lockdown_settings,
EOM_CONF_LOCKDOWN_CAN_PRINT);
if (print_disabled) {
gtk_action_set_sensitive (action_print, FALSE);
}
if (eom_sidebar_is_empty (EOM_SIDEBAR (priv->sidebar))) {
gtk_action_set_sensitive (action_sidebar, FALSE);
gtk_widget_hide (priv->sidebar);
}
}
static void
update_selection_ui_visibility (EomWindow *window)
{
EomWindowPrivate *priv;
GtkAction *wallpaper_action;
gint n_selected;
priv = window->priv;
n_selected = eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview));
wallpaper_action =
gtk_action_group_get_action (priv->actions_image,
"ImageSetAsWallpaper");
if (n_selected == 1) {
gtk_action_set_sensitive (wallpaper_action, TRUE);
} else {
gtk_action_set_sensitive (wallpaper_action, FALSE);
}
}
static gboolean
add_file_to_recent_files (GFile *file)
{
gchar *text_uri;
GFileInfo *file_info;
GtkRecentData *recent_data;
static gchar *groups[2] = { EOM_RECENT_FILES_GROUP , NULL };
if (file == NULL) return FALSE;
/* The password gets stripped here because ~/.recently-used.xbel is
* readable by everyone (chmod 644). It also makes the workaround
* for the bug with gtk_recent_info_get_uri_display() easier
* (see the comment in eom_window_update_recent_files_menu()). */
text_uri = g_file_get_uri (file);
if (text_uri == NULL)
return FALSE;
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
0, NULL, NULL);
if (file_info == NULL)
return FALSE;
recent_data = g_slice_new (GtkRecentData);
recent_data->display_name = NULL;
recent_data->description = NULL;
recent_data->mime_type = (gchar *) g_file_info_get_content_type (file_info);
recent_data->app_name = EOM_RECENT_FILES_APP_NAME;
recent_data->app_exec = g_strjoin(" ", g_get_prgname (), "%u", NULL);
recent_data->groups = groups;
recent_data->is_private = FALSE;
gtk_recent_manager_add_full (gtk_recent_manager_get_default (),
text_uri,
recent_data);
g_free (recent_data->app_exec);
g_free (text_uri);
g_object_unref (file_info);
g_slice_free (GtkRecentData, recent_data);
return FALSE;
}
static void
image_thumb_changed_cb (EomImage *image, gpointer data)
{
EomWindow *window;
EomWindowPrivate *priv;
GdkPixbuf *thumb;
g_return_if_fail (EOM_IS_WINDOW (data));
window = EOM_WINDOW (data);
priv = window->priv;
thumb = eom_image_get_thumbnail (image);
if (thumb != NULL) {
gtk_window_set_icon (GTK_WINDOW (window), thumb);
if (window->priv->properties_dlg != NULL) {
eom_properties_dialog_update (EOM_PROPERTIES_DIALOG (priv->properties_dlg),
image);
}
g_object_unref (thumb);
} else if (!gtk_widget_get_visible (window->priv->nav)) {
gint img_pos = eom_list_store_get_pos_by_image (window->priv->store, image);
GtkTreePath *path = gtk_tree_path_new_from_indices (img_pos,-1);
GtkTreeIter iter;
gtk_tree_model_get_iter (GTK_TREE_MODEL (window->priv->store), &iter, path);
eom_list_store_thumbnail_set (window->priv->store, &iter);
gtk_tree_path_free (path);
}
}
static void
file_changed_info_bar_response (GtkInfoBar *info_bar,
gint response,
EomWindow *window)
{
if (response == GTK_RESPONSE_YES) {
eom_window_reload_image (window);
}
window->priv->needs_reload_confirmation = TRUE;
eom_window_set_message_area (window, NULL);
}
static void
image_file_changed_cb (EomImage *img, EomWindow *window)
{
GtkWidget *info_bar;
gchar *text, *markup;
GtkWidget *image;
GtkWidget *label;
GtkWidget *hbox;
if (window->priv->needs_reload_confirmation == FALSE)
return;
window->priv->needs_reload_confirmation = FALSE;
info_bar = gtk_info_bar_new_with_buttons (_("_Reload"),
GTK_RESPONSE_YES,
C_("MessageArea", "Hi_de"),
GTK_RESPONSE_NO, NULL);
gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
GTK_MESSAGE_QUESTION);
image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION,
GTK_ICON_SIZE_DIALOG);
label = gtk_label_new (NULL);
/* The newline character is currently necessary due to a problem
* with the automatic line break. */
text = g_strdup_printf (_("The image \"%s\" has been modified by an external application."
"\nWould you like to reload it?"), eom_image_get_caption (img));
markup = g_markup_printf_escaped ("<b>%s</b>", text);
gtk_label_set_markup (GTK_LABEL (label), markup);
g_free (text);
g_free (markup);
hbox = gtk_hbox_new (FALSE, 8);
gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
#if GTK_CHECK_VERSION (3, 14, 0)
gtk_widget_set_valign (image, GTK_ALIGN_START);
gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
gtk_widget_set_halign (label, GTK_ALIGN_START);
#else
gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0);
gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
#endif
gtk_box_pack_start (GTK_BOX (gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar))), hbox, TRUE, TRUE, 0);
gtk_widget_show_all (hbox);
gtk_widget_show (info_bar);
eom_window_set_message_area (window, info_bar);
g_signal_connect (info_bar, "response",
G_CALLBACK (file_changed_info_bar_response), window);
}
static void
eom_window_display_image (EomWindow *window, EomImage *image)
{
EomWindowPrivate *priv;
GFile *file;
g_return_if_fail (EOM_IS_WINDOW (window));
g_return_if_fail (EOM_IS_IMAGE (image));
eom_debug (DEBUG_WINDOW);
g_assert (eom_image_has_data (image, EOM_IMAGE_DATA_IMAGE));
priv = window->priv;
if (image != NULL) {
g_signal_connect (image,
"thumbnail_changed",
G_CALLBACK (image_thumb_changed_cb),
window);
g_signal_connect (image, "file-changed",
G_CALLBACK (image_file_changed_cb),
window);
image_thumb_changed_cb (image, window);
}
priv->needs_reload_confirmation = TRUE;
eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), image);
gtk_window_set_title (GTK_WINDOW (window), eom_image_get_caption (image));
update_status_bar (window);
file = eom_image_get_file (image);
g_idle_add_full (G_PRIORITY_LOW,
(GSourceFunc) add_file_to_recent_files,
file,
(GDestroyNotify) g_object_unref);
eom_window_update_openwith_menu (window, image);
}
static void
open_with_launch_application_cb (GtkAction *action, gpointer data) {
EomImage *image;
GAppInfo *app;
GFile *file;
GList *files = NULL;
image = EOM_IMAGE (data);
file = eom_image_get_file (image);
app = g_object_get_data (G_OBJECT (action), "app");
files = g_list_append (files, file);
g_app_info_launch (app,
files,
NULL, NULL);
g_object_unref (file);
g_list_free (files);
}
static void
eom_window_update_openwith_menu (EomWindow *window, EomImage *image)
{
gboolean edit_button_active;
GAppInfo *editor_app;
GFile *file;
GFileInfo *file_info;
GList *iter;
gchar *label, *tip;
const gchar *mime_type;
GtkAction *action;
EomWindowPrivate *priv;
GList *apps;
guint action_id = 0;
GIcon *app_icon;
char *path;
GtkWidget *menuitem;
priv = window->priv;
edit_button_active = FALSE;
editor_app = get_appinfo_for_editor (window);
file = eom_image_get_file (image);
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_STANDARD_CONTENT_TYPE,
0, NULL, NULL);
if (file_info == NULL)
return;
else {
mime_type = g_file_info_get_content_type (file_info);
}
if (priv->open_with_menu_id != 0) {
gtk_ui_manager_remove_ui (priv->ui_mgr, priv->open_with_menu_id);
priv->open_with_menu_id = 0;
}
if (priv->actions_open_with != NULL) {
gtk_ui_manager_remove_action_group (priv->ui_mgr, priv->actions_open_with);
priv->actions_open_with = NULL;
}
if (mime_type == NULL) {
g_object_unref (file_info);
return;
}
apps = g_app_info_get_all_for_type (mime_type);
g_object_unref (file_info);
if (!apps)
return;
priv->actions_open_with = gtk_action_group_new ("OpenWithActions");
gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_open_with, -1);
priv->open_with_menu_id = gtk_ui_manager_new_merge_id (priv->ui_mgr);
for (iter = apps; iter; iter = iter->next) {
GAppInfo *app = iter->data;
gchar name[64];
if (editor_app != NULL && g_app_info_equal (editor_app, app)) {
edit_button_active = TRUE;
}
/* Do not include eom itself */
if (g_ascii_strcasecmp (g_app_info_get_executable (app),
g_get_prgname ()) == 0) {
g_object_unref (app);
continue;
}
g_snprintf (name, sizeof (name), "OpenWith%u", action_id++);
label = g_strdup (g_app_info_get_name (app));
tip = g_strdup_printf (_("Use \"%s\" to open the selected image"), g_app_info_get_name (app));
action = gtk_action_new (name, label, tip, NULL);
app_icon = g_app_info_get_icon (app);
if (G_LIKELY (app_icon != NULL)) {
g_object_ref (app_icon);
gtk_action_set_gicon (action, app_icon);
g_object_unref (app_icon);
}
g_free (label);
g_free (tip);
g_object_set_data_full (G_OBJECT (action), "app", app,
(GDestroyNotify) g_object_unref);
g_signal_connect (action,
"activate",
G_CALLBACK (open_with_launch_application_cb),
image);
gtk_action_group_add_action (priv->actions_open_with, action);
g_object_unref (action);
gtk_ui_manager_add_ui (priv->ui_mgr,
priv->open_with_menu_id,
"/MainMenu/Image/ImageOpenWith/Applications Placeholder",
name,
name,
GTK_UI_MANAGER_MENUITEM,
FALSE);
gtk_ui_manager_add_ui (priv->ui_mgr,
priv->open_with_menu_id,
"/ThumbnailPopup/ImageOpenWith/Applications Placeholder",
name,
name,
GTK_UI_MANAGER_MENUITEM,
FALSE);
gtk_ui_manager_add_ui (priv->ui_mgr,
priv->open_with_menu_id,
"/ViewPopup/ImageOpenWith/Applications Placeholder",
name,
name,
GTK_UI_MANAGER_MENUITEM,
FALSE);
path = g_strdup_printf ("/MainMenu/Image/ImageOpenWith/Applications Placeholder/%s", name);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path);
/* Only force displaying the icon if it is an application icon */
gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL);
g_free (path);
path = g_strdup_printf ("/ThumbnailPopup/ImageOpenWith/Applications Placeholder/%s", name);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path);
/* Only force displaying the icon if it is an application icon */
gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL);
g_free (path);
path = g_strdup_printf ("/ViewPopup/ImageOpenWith/Applications Placeholder/%s", name);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr, path);
/* Only force displaying the icon if it is an application icon */
gtk_image_menu_item_set_always_show_image (GTK_IMAGE_MENU_ITEM (menuitem), app_icon != NULL);
g_free (path);
}
g_list_free (apps);
action = gtk_action_group_get_action (window->priv->actions_image,
"OpenEditor");
if (action != NULL) {
gtk_action_set_sensitive (action, edit_button_active);
}
}
static void
eom_window_clear_load_job (EomWindow *window)
{
EomWindowPrivate *priv = window->priv;
if (priv->load_job != NULL) {
if (!priv->load_job->finished)
eom_job_queue_remove_job (priv->load_job);
g_signal_handlers_disconnect_by_func (priv->load_job,
eom_job_progress_cb,
window);
g_signal_handlers_disconnect_by_func (priv->load_job,
eom_job_load_cb,
window);
eom_image_cancel_load (EOM_JOB_LOAD (priv->load_job)->image);
g_object_unref (priv->load_job);
priv->load_job = NULL;
/* Hide statusbar */
eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), 0);
}
}
static void
eom_job_progress_cb (EomJobLoad *job, float progress, gpointer user_data)
{
EomWindow *window;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
eom_statusbar_set_progress (EOM_STATUSBAR (window->priv->statusbar),
progress);
}
static void
eom_job_save_progress_cb (EomJobSave *job, float progress, gpointer user_data)
{
EomWindowPrivate *priv;
EomWindow *window;
static EomImage *image = NULL;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar),
progress);
if (image != job->current_image) {
gchar *str_image, *status_message;
guint n_images;
image = job->current_image;
n_images = g_list_length (job->images);
str_image = eom_image_get_uri_for_display (image);
/* Translators: This string is displayed in the statusbar
* while saving images. The tokens are from left to right:
* - the original filename
* - the current image's position in the queue
* - the total number of images queued for saving */
status_message = g_strdup_printf (_("Saving image \"%s\" (%u/%u)"),
str_image,
job->current_pos + 1,
n_images);
g_free (str_image);
gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid);
gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid,
status_message);
g_free (status_message);
}
if (progress == 1.0)
image = NULL;
}
static void
eom_window_obtain_desired_size (EomImage *image,
gint width,
gint height,
EomWindow *window)
{
GdkScreen *screen;
GdkRectangle monitor;
GtkAllocation allocation;
gint final_width, final_height;
gint screen_width, screen_height;
gint window_width, window_height;
gint img_width, img_height;
gint view_width, view_height;
gint deco_width, deco_height;
update_action_groups_state (window);
img_width = width;
img_height = height;
if (!gtk_widget_get_realized (window->priv->view)) {
gtk_widget_realize (window->priv->view);
}
gtk_widget_get_allocation (window->priv->view, &allocation);
view_width = allocation.width;
view_height = allocation.height;
if (!gtk_widget_get_realized (GTK_WIDGET (window))) {
gtk_widget_realize (GTK_WIDGET (window));
}
gtk_widget_get_allocation (GTK_WIDGET (window), &allocation);
window_width = allocation.width;
window_height = allocation.height;
screen = gtk_window_get_screen (GTK_WINDOW (window));
gdk_screen_get_monitor_geometry (screen,
gdk_screen_get_monitor_at_window (screen,
gtk_widget_get_window (GTK_WIDGET (window))),
&monitor);
screen_width = monitor.width;
screen_height = monitor.height;
deco_width = window_width - view_width;
deco_height = window_height - view_height;
if (img_width > 0 && img_height > 0) {
if ((img_width + deco_width > screen_width) ||
(img_height + deco_height > screen_height))
{
double factor;
if (img_width > img_height) {
factor = (screen_width * 0.75 - deco_width) / (double) img_width;
} else {
factor = (screen_height * 0.75 - deco_height) / (double) img_height;
}
img_width = img_width * factor;
img_height = img_height * factor;
}
}
final_width = MAX (EOM_WINDOW_MIN_WIDTH, img_width + deco_width);
final_height = MAX (EOM_WINDOW_MIN_HEIGHT, img_height + deco_height);
eom_debug_message (DEBUG_WINDOW, "Setting window size: %d x %d", final_width, final_height);
gtk_window_set_default_size (GTK_WINDOW (window), final_width, final_height);
g_signal_emit (window, signals[SIGNAL_PREPARED], 0);
}
static void
eom_window_error_message_area_response (GtkInfoBar *message_area,
gint response_id,
EomWindow *window)
{
if (response_id != GTK_RESPONSE_OK) {
eom_window_set_message_area (window, NULL);
return;
}
/* Trigger loading for current image again */
eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview),
EOM_THUMB_VIEW_SELECT_CURRENT);
}
static void
eom_job_load_cb (EomJobLoad *job, gpointer data)
{
EomWindow *window;
EomWindowPrivate *priv;
GtkAction *action_undo, *action_save;
g_return_if_fail (EOM_IS_WINDOW (data));
eom_debug (DEBUG_WINDOW);
window = EOM_WINDOW (data);
priv = window->priv;
eom_statusbar_set_progress (EOM_STATUSBAR (priv->statusbar), 0.0);
gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar),
priv->image_info_message_cid);
if (priv->image != NULL) {
g_signal_handlers_disconnect_by_func (priv->image,
image_thumb_changed_cb,
window);
g_signal_handlers_disconnect_by_func (priv->image,
image_file_changed_cb,
window);
g_object_unref (priv->image);
}
priv->image = g_object_ref (job->image);
if (EOM_JOB (job)->error == NULL) {
#ifdef HAVE_LCMS
eom_image_apply_display_profile (job->image,
priv->display_profile);
#endif
gtk_action_group_set_sensitive (priv->actions_image, TRUE);
eom_window_display_image (window, job->image);
} else {
GtkWidget *message_area;
message_area = eom_image_load_error_message_area_new (
eom_image_get_caption (job->image),
EOM_JOB (job)->error);
g_signal_connect (message_area,
"response",
G_CALLBACK (eom_window_error_message_area_response),
window);
gtk_window_set_icon (GTK_WINDOW (window), NULL);
gtk_window_set_title (GTK_WINDOW (window),
eom_image_get_caption (job->image));
eom_window_set_message_area (window, message_area);
gtk_info_bar_set_default_response (GTK_INFO_BAR (message_area),
GTK_RESPONSE_CANCEL);
gtk_widget_show (message_area);
update_status_bar (window);
eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view), NULL);
if (window->priv->status == EOM_WINDOW_STATUS_INIT) {
update_action_groups_state (window);
g_signal_emit (window, signals[SIGNAL_PREPARED], 0);
}
gtk_action_group_set_sensitive (priv->actions_image, FALSE);
}
eom_window_clear_load_job (window);
if (window->priv->status == EOM_WINDOW_STATUS_INIT) {
window->priv->status = EOM_WINDOW_STATUS_NORMAL;
g_signal_handlers_disconnect_by_func
(job->image,
G_CALLBACK (eom_window_obtain_desired_size),
window);
}
action_save = gtk_action_group_get_action (priv->actions_image, "ImageSave");
action_undo = gtk_action_group_get_action (priv->actions_image, "EditUndo");
/* Set Save and Undo sensitive according to image state.
* Respect lockdown in case of Save.*/
gtk_action_set_sensitive (action_save, (!priv->save_disabled && eom_image_is_modified (job->image)));
gtk_action_set_sensitive (action_undo, eom_image_is_modified (job->image));
g_object_unref (job->image);
}
static void
eom_window_clear_transform_job (EomWindow *window)
{
EomWindowPrivate *priv = window->priv;
if (priv->transform_job != NULL) {
if (!priv->transform_job->finished)
eom_job_queue_remove_job (priv->transform_job);
g_signal_handlers_disconnect_by_func (priv->transform_job,
eom_job_transform_cb,
window);
g_object_unref (priv->transform_job);
priv->transform_job = NULL;
}
}
static void
eom_job_transform_cb (EomJobTransform *job, gpointer data)
{
EomWindow *window;
GtkAction *action_undo, *action_save;
EomImage *image;
g_return_if_fail (EOM_IS_WINDOW (data));
window = EOM_WINDOW (data);
eom_window_clear_transform_job (window);
action_undo =
gtk_action_group_get_action (window->priv->actions_image, "EditUndo");
action_save =
gtk_action_group_get_action (window->priv->actions_image, "ImageSave");
image = eom_window_get_image (window);
gtk_action_set_sensitive (action_undo, eom_image_is_modified (image));
if (!window->priv->save_disabled)
{
gtk_action_set_sensitive (action_save, eom_image_is_modified (image));
}
}
static void
apply_transformation (EomWindow *window, EomTransform *trans)
{
EomWindowPrivate *priv;
GList *images;
g_return_if_fail (EOM_IS_WINDOW (window));
priv = window->priv;
images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview));
eom_window_clear_transform_job (window);
priv->transform_job = eom_job_transform_new (images, trans);
g_signal_connect (priv->transform_job,
"finished",
G_CALLBACK (eom_job_transform_cb),
window);
g_signal_connect (priv->transform_job,
"progress",
G_CALLBACK (eom_job_progress_cb),
window);
eom_job_queue_add_job (priv->transform_job);
}
static void
handle_image_selection_changed_cb (EomThumbView *thumbview, EomWindow *window)
{
EomWindowPrivate *priv;
EomImage *image;
gchar *status_message;
gchar *str_image;
priv = window->priv;
if (eom_list_store_length (EOM_LIST_STORE (priv->store)) == 0) {
gtk_window_set_title (GTK_WINDOW (window),
g_get_application_name());
gtk_statusbar_remove_all (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid);
eom_scroll_view_set_image (EOM_SCROLL_VIEW (priv->view),
NULL);
}
if (eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview)) == 0)
return;
update_selection_ui_visibility (window);
image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview));
g_assert (EOM_IS_IMAGE (image));
eom_window_clear_load_job (window);
eom_window_set_message_area (window, NULL);
gtk_statusbar_pop (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid);
if (image == priv->image) {
update_status_bar (window);
return;
}
if (eom_image_has_data (image, EOM_IMAGE_DATA_IMAGE)) {
if (priv->image != NULL)
g_object_unref (priv->image);
priv->image = image;
eom_window_display_image (window, image);
return;
}
if (priv->status == EOM_WINDOW_STATUS_INIT) {
g_signal_connect (image,
"size-prepared",
G_CALLBACK (eom_window_obtain_desired_size),
window);
}
priv->load_job = eom_job_load_new (image, EOM_IMAGE_DATA_ALL);
g_signal_connect (priv->load_job,
"finished",
G_CALLBACK (eom_job_load_cb),
window);
g_signal_connect (priv->load_job,
"progress",
G_CALLBACK (eom_job_progress_cb),
window);
eom_job_queue_add_job (priv->load_job);
str_image = eom_image_get_uri_for_display (image);
status_message = g_strdup_printf (_("Opening image \"%s\""),
str_image);
g_free (str_image);
gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar),
priv->image_info_message_cid, status_message);
g_free (status_message);
}
static void
view_zoom_changed_cb (GtkWidget *widget, double zoom, gpointer user_data)
{
EomWindow *window;
GtkAction *action_zoom_in;
GtkAction *action_zoom_out;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
update_status_bar (window);
action_zoom_in =
gtk_action_group_get_action (window->priv->actions_image,
"ViewZoomIn");
action_zoom_out =
gtk_action_group_get_action (window->priv->actions_image,
"ViewZoomOut");
gtk_action_set_sensitive (action_zoom_in,
!eom_scroll_view_get_zoom_is_max (EOM_SCROLL_VIEW (window->priv->view)));
gtk_action_set_sensitive (action_zoom_out,
!eom_scroll_view_get_zoom_is_min (EOM_SCROLL_VIEW (window->priv->view)));
}
static void
eom_window_open_recent_cb (GtkAction *action, EomWindow *window)
{
GtkRecentInfo *info;
const gchar *uri;
GSList *list = NULL;
info = g_object_get_data (G_OBJECT (action), "gtk-recent-info");
g_return_if_fail (info != NULL);
uri = gtk_recent_info_get_uri (info);
list = g_slist_prepend (list, g_strdup (uri));
eom_application_open_uri_list (EOM_APP,
list,
GDK_CURRENT_TIME,
0,
NULL);
g_slist_foreach (list, (GFunc) g_free, NULL);
g_slist_free (list);
}
static void
file_open_dialog_response_cb (GtkWidget *chooser,
gint response_id,
EomWindow *ev_window)
{
if (response_id == GTK_RESPONSE_OK) {
GSList *uris;
uris = gtk_file_chooser_get_uris (GTK_FILE_CHOOSER (chooser));
eom_application_open_uri_list (EOM_APP,
uris,
GDK_CURRENT_TIME,
0,
NULL);
g_slist_foreach (uris, (GFunc) g_free, NULL);
g_slist_free (uris);
}
gtk_widget_destroy (chooser);
}
static void
eom_window_update_fullscreen_action (EomWindow *window)
{
GtkAction *action;
action = gtk_action_group_get_action (window->priv->actions_image,
"ViewFullscreen");
g_signal_handlers_block_by_func
(action, G_CALLBACK (eom_window_cmd_fullscreen), window);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action),
window->priv->mode == EOM_WINDOW_MODE_FULLSCREEN);
g_signal_handlers_unblock_by_func
(action, G_CALLBACK (eom_window_cmd_fullscreen), window);
}
static void
eom_window_update_slideshow_action (EomWindow *window)
{
GtkAction *action;
action = gtk_action_group_get_action (window->priv->actions_collection,
"ViewSlideshow");
g_signal_handlers_block_by_func
(action, G_CALLBACK (eom_window_cmd_slideshow), window);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action),
window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW);
g_signal_handlers_unblock_by_func
(action, G_CALLBACK (eom_window_cmd_slideshow), window);
}
static void
eom_window_update_pause_slideshow_action (EomWindow *window)
{
GtkAction *action;
action = gtk_action_group_get_action (window->priv->actions_image,
"PauseSlideshow");
g_signal_handlers_block_by_func
(action, G_CALLBACK (eom_window_cmd_pause_slideshow), window);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action),
window->priv->mode != EOM_WINDOW_MODE_SLIDESHOW);
g_signal_handlers_unblock_by_func
(action, G_CALLBACK (eom_window_cmd_pause_slideshow), window);
}
static void
eom_window_update_fullscreen_popup (EomWindow *window)
{
GtkWidget *popup = window->priv->fullscreen_popup;
GdkRectangle screen_rect;
GdkScreen *screen;
g_return_if_fail (popup != NULL);
if (gtk_widget_get_window (GTK_WIDGET (window)) == NULL) return;
screen = gtk_widget_get_screen (GTK_WIDGET (window));
gdk_screen_get_monitor_geometry (screen,
gdk_screen_get_monitor_at_window
(screen,
gtk_widget_get_window (GTK_WIDGET (window))),
&screen_rect);
gtk_widget_set_size_request (popup,
screen_rect.width,
-1);
gtk_window_move (GTK_WINDOW (popup), screen_rect.x, screen_rect.y);
}
static void
screen_size_changed_cb (GdkScreen *screen, EomWindow *window)
{
eom_window_update_fullscreen_popup (window);
}
static void
fullscreen_popup_size_request_cb (GtkWidget *popup,
GtkRequisition *req,
EomWindow *window)
{
eom_window_update_fullscreen_popup (window);
}
static gboolean
fullscreen_timeout_cb (gpointer data)
{
EomWindow *window = EOM_WINDOW (data);
gtk_widget_hide (window->priv->fullscreen_popup);
eom_scroll_view_hide_cursor (EOM_SCROLL_VIEW (window->priv->view));
fullscreen_clear_timeout (window);
return FALSE;
}
static gboolean
slideshow_is_loop_end (EomWindow *window)
{
EomWindowPrivate *priv = window->priv;
EomImage *image = NULL;
gint pos;
image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview));
pos = eom_list_store_get_pos_by_image (priv->store, image);
return (pos == (eom_list_store_length (priv->store) - 1));
}
static gboolean
slideshow_switch_cb (gpointer data)
{
EomWindow *window = EOM_WINDOW (data);
EomWindowPrivate *priv = window->priv;
eom_debug (DEBUG_WINDOW);
if (priv->slideshow_random) {
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_RANDOM);
return TRUE;
}
if (!priv->slideshow_loop && slideshow_is_loop_end (window)) {
eom_window_stop_fullscreen (window, TRUE);
return FALSE;
}
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_RIGHT);
return TRUE;
}
static void
fullscreen_clear_timeout (EomWindow *window)
{
eom_debug (DEBUG_WINDOW);
if (window->priv->fullscreen_timeout_source != NULL) {
g_source_unref (window->priv->fullscreen_timeout_source);
g_source_destroy (window->priv->fullscreen_timeout_source);
}
window->priv->fullscreen_timeout_source = NULL;
}
static void
fullscreen_set_timeout (EomWindow *window)
{
GSource *source;
eom_debug (DEBUG_WINDOW);
fullscreen_clear_timeout (window);
source = g_timeout_source_new (EOM_WINDOW_FULLSCREEN_TIMEOUT);
g_source_set_callback (source, fullscreen_timeout_cb, window, NULL);
g_source_attach (source, NULL);
window->priv->fullscreen_timeout_source = source;
eom_scroll_view_show_cursor (EOM_SCROLL_VIEW (window->priv->view));
}
static void
slideshow_clear_timeout (EomWindow *window)
{
eom_debug (DEBUG_WINDOW);
if (window->priv->slideshow_switch_source != NULL) {
g_source_unref (window->priv->slideshow_switch_source);
g_source_destroy (window->priv->slideshow_switch_source);
}
window->priv->slideshow_switch_source = NULL;
}
static void
slideshow_set_timeout (EomWindow *window)
{
GSource *source;
eom_debug (DEBUG_WINDOW);
slideshow_clear_timeout (window);
if (window->priv->slideshow_switch_timeout <= 0)
return;
source = g_timeout_source_new (window->priv->slideshow_switch_timeout * 1000);
g_source_set_callback (source, slideshow_switch_cb, window, NULL);
g_source_attach (source, NULL);
window->priv->slideshow_switch_source = source;
}
static void
show_fullscreen_popup (EomWindow *window)
{
eom_debug (DEBUG_WINDOW);
if (!gtk_widget_get_visible (window->priv->fullscreen_popup)) {
gtk_widget_show_all (GTK_WIDGET (window->priv->fullscreen_popup));
}
fullscreen_set_timeout (window);
}
static gboolean
fullscreen_motion_notify_cb (GtkWidget *widget,
GdkEventMotion *event,
gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
eom_debug (DEBUG_WINDOW);
if (event->y < EOM_WINDOW_FULLSCREEN_POPUP_THRESHOLD) {
show_fullscreen_popup (window);
} else {
fullscreen_set_timeout (window);
}
return FALSE;
}
static gboolean
fullscreen_leave_notify_cb (GtkWidget *widget,
GdkEventCrossing *event,
gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
eom_debug (DEBUG_WINDOW);
fullscreen_clear_timeout (window);
return FALSE;
}
static void
exit_fullscreen_button_clicked_cb (GtkWidget *button, EomWindow *window)
{
GtkAction *action;
eom_debug (DEBUG_WINDOW);
if (window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) {
action = gtk_action_group_get_action (window->priv->actions_collection,
"ViewSlideshow");
} else {
action = gtk_action_group_get_action (window->priv->actions_image,
"ViewFullscreen");
}
g_return_if_fail (action != NULL);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), FALSE);
}
static GtkWidget *
eom_window_get_exit_fullscreen_button (EomWindow *window)
{
GtkWidget *button;
button = gtk_button_new_from_stock (GTK_STOCK_LEAVE_FULLSCREEN);
g_signal_connect (button, "clicked",
G_CALLBACK (exit_fullscreen_button_clicked_cb),
window);
return button;
}
static GtkWidget *
eom_window_create_fullscreen_popup (EomWindow *window)
{
GtkWidget *popup;
GtkWidget *hbox;
GtkWidget *button;
GtkWidget *toolbar;
GdkScreen *screen;
eom_debug (DEBUG_WINDOW);
popup = gtk_window_new (GTK_WINDOW_POPUP);
hbox = gtk_hbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (popup), hbox);
toolbar = gtk_ui_manager_get_widget (window->priv->ui_mgr,
"/FullscreenToolbar");
g_assert (GTK_IS_WIDGET (toolbar));
gtk_toolbar_set_style (GTK_TOOLBAR (toolbar), GTK_TOOLBAR_ICONS);
gtk_box_pack_start (GTK_BOX (hbox), toolbar, TRUE, TRUE, 0);
button = eom_window_get_exit_fullscreen_button (window);
gtk_box_pack_start (GTK_BOX (hbox), button, FALSE, FALSE, 0);
gtk_window_set_resizable (GTK_WINDOW (popup), FALSE);
screen = gtk_widget_get_screen (GTK_WIDGET (window));
g_signal_connect_object (screen, "size-changed",
G_CALLBACK (screen_size_changed_cb),
window, 0);
g_signal_connect_object (popup, "size_request",
G_CALLBACK (fullscreen_popup_size_request_cb),
window, 0);
g_signal_connect (popup,
"enter-notify-event",
G_CALLBACK (fullscreen_leave_notify_cb),
window);
gtk_window_set_screen (GTK_WINDOW (popup), screen);
return popup;
}
static void
update_ui_visibility (EomWindow *window)
{
EomWindowPrivate *priv;
GtkAction *action;
GtkWidget *menubar;
gboolean fullscreen_mode, visible;
g_return_if_fail (EOM_IS_WINDOW (window));
eom_debug (DEBUG_WINDOW);
priv = window->priv;
fullscreen_mode = priv->mode == EOM_WINDOW_MODE_FULLSCREEN ||
priv->mode == EOM_WINDOW_MODE_SLIDESHOW;
menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu");
g_assert (GTK_IS_WIDGET (menubar));
visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_TOOLBAR);
visible = visible && !fullscreen_mode;
action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/ToolbarToggle");
g_assert (action != NULL);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible);
g_object_set (G_OBJECT (priv->toolbar), "visible", visible, NULL);
visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_STATUSBAR);
visible = visible && !fullscreen_mode;
action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/StatusbarToggle");
g_assert (action != NULL);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible);
g_object_set (G_OBJECT (priv->statusbar), "visible", visible, NULL);
if (priv->status != EOM_WINDOW_STATUS_INIT) {
visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION);
visible = visible && priv->mode != EOM_WINDOW_MODE_SLIDESHOW;
action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/ImageCollectionToggle");
g_assert (action != NULL);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible);
if (visible) {
gtk_widget_show (priv->nav);
} else {
gtk_widget_hide (priv->nav);
}
}
visible = g_settings_get_boolean (priv->ui_settings, EOM_CONF_UI_SIDEBAR);
visible = visible && !fullscreen_mode;
action = gtk_ui_manager_get_action (priv->ui_mgr, "/MainMenu/View/SidebarToggle");
g_assert (action != NULL);
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible);
if (visible) {
gtk_widget_show (priv->sidebar);
} else {
gtk_widget_hide (priv->sidebar);
}
if (priv->fullscreen_popup != NULL) {
gtk_widget_hide (priv->fullscreen_popup);
}
}
static void
eom_window_run_fullscreen (EomWindow *window, gboolean slideshow)
{
#if GTK_CHECK_VERSION (3, 0, 0)
static const GdkRGBA black = { 0., 0., 0., 1.};
#endif
EomWindowPrivate *priv;
GtkWidget *menubar;
gboolean upscale;
eom_debug (DEBUG_WINDOW);
priv = window->priv;
if (slideshow) {
priv->mode = EOM_WINDOW_MODE_SLIDESHOW;
} else {
/* Stop the timer if we come from slideshowing */
if (priv->mode == EOM_WINDOW_MODE_SLIDESHOW)
slideshow_clear_timeout (window);
priv->mode = EOM_WINDOW_MODE_FULLSCREEN;
}
if (window->priv->fullscreen_popup == NULL)
priv->fullscreen_popup
= eom_window_create_fullscreen_popup (window);
update_ui_visibility (window);
menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu");
g_assert (GTK_IS_WIDGET (menubar));
gtk_widget_hide (menubar);
g_signal_connect (priv->view,
"motion-notify-event",
G_CALLBACK (fullscreen_motion_notify_cb),
window);
g_signal_connect (priv->view,
"leave-notify-event",
G_CALLBACK (fullscreen_leave_notify_cb),
window);
g_signal_connect (priv->thumbview,
"motion-notify-event",
G_CALLBACK (fullscreen_motion_notify_cb),
window);
g_signal_connect (priv->thumbview,
"leave-notify-event",
G_CALLBACK (fullscreen_leave_notify_cb),
window);
fullscreen_set_timeout (window);
if (slideshow) {
priv->slideshow_random =
g_settings_get_boolean (priv->fullscreen_settings,
EOM_CONF_FULLSCREEN_RANDOM);
priv->slideshow_loop =
g_settings_get_boolean (priv->fullscreen_settings,
EOM_CONF_FULLSCREEN_LOOP);
priv->slideshow_switch_timeout =
g_settings_get_int (priv->fullscreen_settings,
EOM_CONF_FULLSCREEN_SECONDS);
slideshow_set_timeout (window);
}
upscale = g_settings_get_boolean (priv->fullscreen_settings,
EOM_CONF_FULLSCREEN_UPSCALE);
eom_scroll_view_set_zoom_upscale (EOM_SCROLL_VIEW (priv->view),
upscale);
gtk_widget_grab_focus (priv->view);
eom_scroll_view_override_bg_color (EOM_SCROLL_VIEW (window->priv->view),
#if GTK_CHECK_VERSION (3, 0, 0)
&black);
#else
&(gtk_widget_get_style (GTK_WIDGET (window))->black));
#endif
#if !GTK_CHECK_VERSION (3, 0, 0)
{
GtkStyle *style;
style = gtk_style_copy (gtk_widget_get_style (gtk_widget_get_parent (priv->view)));
style->xthickness = 0;
style->ythickness = 0;
gtk_widget_set_style (gtk_widget_get_parent (priv->view),
style);
g_object_unref (style);
}
#endif
gtk_window_fullscreen (GTK_WINDOW (window));
eom_window_update_fullscreen_popup (window);
#ifdef HAVE_DBUS
eom_application_screensaver_disable (EOM_APP);
#endif
/* Update both actions as we could've already been in one those modes */
eom_window_update_slideshow_action (window);
eom_window_update_fullscreen_action (window);
eom_window_update_pause_slideshow_action (window);
}
static void
eom_window_stop_fullscreen (EomWindow *window, gboolean slideshow)
{
EomWindowPrivate *priv;
GtkWidget *menubar;
eom_debug (DEBUG_WINDOW);
priv = window->priv;
if (priv->mode != EOM_WINDOW_MODE_SLIDESHOW &&
priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return;
priv->mode = EOM_WINDOW_MODE_NORMAL;
fullscreen_clear_timeout (window);
if (slideshow) {
slideshow_clear_timeout (window);
}
g_signal_handlers_disconnect_by_func (priv->view,
(gpointer) fullscreen_motion_notify_cb,
window);
g_signal_handlers_disconnect_by_func (priv->view,
(gpointer) fullscreen_leave_notify_cb,
window);
g_signal_handlers_disconnect_by_func (priv->thumbview,
(gpointer) fullscreen_motion_notify_cb,
window);
g_signal_handlers_disconnect_by_func (priv->thumbview,
(gpointer) fullscreen_leave_notify_cb,
window);
update_ui_visibility (window);
menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu");
g_assert (GTK_IS_WIDGET (menubar));
gtk_widget_show (menubar);
eom_scroll_view_set_zoom_upscale (EOM_SCROLL_VIEW (priv->view), FALSE);
eom_scroll_view_override_bg_color (EOM_SCROLL_VIEW (window->priv->view),
NULL);
#if !GTK_CHECK_VERSION (3, 0, 0)
gtk_widget_set_style (gtk_widget_get_parent (window->priv->view), NULL);
#endif
gtk_window_unfullscreen (GTK_WINDOW (window));
if (slideshow) {
eom_window_update_slideshow_action (window);
} else {
eom_window_update_fullscreen_action (window);
}
eom_scroll_view_show_cursor (EOM_SCROLL_VIEW (priv->view));
#ifdef HAVE_DBUS
eom_application_screensaver_enable (EOM_APP);
#endif
}
static void
eom_window_print (EomWindow *window)
{
GtkWidget *dialog;
GError *error = NULL;
GtkPrintOperation *print;
GtkPrintOperationResult res;
GtkPageSetup *page_setup;
GtkPrintSettings *print_settings;
gboolean page_setup_disabled = FALSE;
eom_debug (DEBUG_PRINTING);
print_settings = eom_print_get_print_settings ();
/* Make sure the window stays valid while printing */
g_object_ref (window);
if (window->priv->page_setup !=NULL)
page_setup = g_object_ref (window->priv->page_setup);
else
page_setup = NULL;
print = eom_print_operation_new (window->priv->image,
print_settings,
page_setup);
// Disable page setup options if they are locked down
page_setup_disabled = g_settings_get_boolean (window->priv->lockdown_settings,
EOM_CONF_LOCKDOWN_CAN_SETUP_PAGE);
if (page_setup_disabled)
gtk_print_operation_set_embed_page_setup (print, FALSE);
res = gtk_print_operation_run (print,
GTK_PRINT_OPERATION_ACTION_PRINT_DIALOG,
GTK_WINDOW (window), &error);
if (res == GTK_PRINT_OPERATION_RESULT_ERROR) {
dialog = gtk_message_dialog_new (GTK_WINDOW (window),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_CLOSE,
_("Error printing file:\n%s"),
error->message);
g_signal_connect (dialog, "response",
G_CALLBACK (gtk_widget_destroy), NULL);
gtk_widget_show (dialog);
g_error_free (error);
} else if (res == GTK_PRINT_OPERATION_RESULT_APPLY) {
GtkPageSetup *new_page_setup;
eom_print_set_print_settings (gtk_print_operation_get_print_settings (print));
new_page_setup = gtk_print_operation_get_default_page_setup (print);
if (window->priv->page_setup != NULL)
g_object_unref (window->priv->page_setup);
window->priv->page_setup = g_object_ref (new_page_setup);
}
if (page_setup != NULL)
g_object_unref (page_setup);
g_object_unref (print_settings);
g_object_unref (window);
}
static void
eom_window_cmd_file_open (GtkAction *action, gpointer user_data)
{
EomWindow *window;
EomWindowPrivate *priv;
EomImage *current;
GtkWidget *dlg;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
dlg = eom_file_chooser_new (GTK_FILE_CHOOSER_ACTION_OPEN);
current = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview));
if (current != NULL) {
gchar *dir_uri, *file_uri;
file_uri = eom_image_get_uri_for_display (current);
dir_uri = g_path_get_dirname (file_uri);
gtk_file_chooser_set_current_folder_uri (GTK_FILE_CHOOSER (dlg),
dir_uri);
g_free (file_uri);
g_free (dir_uri);
g_object_unref (current);
} else {
/* If desired by the user,
fallback to the XDG_PICTURES_DIR (if available) */
const gchar *pics_dir;
gboolean use_fallback;
use_fallback = g_settings_get_boolean (priv->ui_settings,
EOM_CONF_UI_FILECHOOSER_XDG_FALLBACK);
pics_dir = g_get_user_special_dir (G_USER_DIRECTORY_PICTURES);
if (use_fallback && pics_dir) {
gtk_file_chooser_set_current_folder (GTK_FILE_CHOOSER (dlg),
pics_dir);
}
}
g_signal_connect (dlg, "response",
G_CALLBACK (file_open_dialog_response_cb),
window);
gtk_widget_show_all (dlg);
}
static void
eom_job_close_save_cb (EomJobSave *job, gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
g_signal_handlers_disconnect_by_func (job,
eom_job_close_save_cb,
window);
gtk_widget_destroy (GTK_WIDGET (window));
}
static void
close_confirmation_dialog_response_handler (EomCloseConfirmationDialog *dlg,
gint response_id,
EomWindow *window)
{
GList *selected_images;
EomWindowPrivate *priv;
priv = window->priv;
switch (response_id)
{
case GTK_RESPONSE_YES:
/* save selected images */
selected_images = eom_close_confirmation_dialog_get_selected_images (dlg);
eom_close_confirmation_dialog_set_sensitive (dlg, FALSE);
if (eom_window_save_images (window, selected_images)) {
g_signal_connect (priv->save_job,
"finished",
G_CALLBACK (eom_job_close_save_cb),
window);
eom_job_queue_add_job (priv->save_job);
}
break;
case GTK_RESPONSE_NO:
/* dont save */
gtk_widget_destroy (GTK_WIDGET (window));
break;
default:
/* Cancel */
gtk_widget_destroy (GTK_WIDGET (dlg));
break;
}
}
static gboolean
eom_window_unsaved_images_confirm (EomWindow *window)
{
EomWindowPrivate *priv;
gboolean disabled;
GtkWidget *dialog;
GList *list;
EomImage *image;
GtkTreeIter iter;
priv = window->priv;
disabled = g_settings_get_boolean(priv->ui_settings,
EOM_CONF_UI_DISABLE_CLOSE_CONFIRMATION);
disabled |= window->priv->save_disabled;
if (disabled) {
return FALSE;
}
list = NULL;
if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (priv->store), &iter)) {
do {
gtk_tree_model_get (GTK_TREE_MODEL (priv->store), &iter,
EOM_LIST_STORE_EOM_IMAGE, &image,
-1);
if (!image)
continue;
if (eom_image_is_modified (image)) {
list = g_list_prepend (list, image);
}
} while (gtk_tree_model_iter_next (GTK_TREE_MODEL (priv->store), &iter));
}
if (list) {
list = g_list_reverse (list);
dialog = eom_close_confirmation_dialog_new (GTK_WINDOW (window),
list);
g_list_free (list);
g_signal_connect (dialog,
"response",
G_CALLBACK (close_confirmation_dialog_response_handler),
window);
gtk_window_set_destroy_with_parent (GTK_WINDOW (dialog), TRUE);
gtk_widget_show (dialog);
return TRUE;
}
return FALSE;
}
static void
eom_window_cmd_close_window (GtkAction *action, gpointer user_data)
{
EomWindow *window;
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
if (priv->save_job != NULL) {
eom_window_finish_saving (window);
}
if (!eom_window_unsaved_images_confirm (window)) {
gtk_widget_destroy (GTK_WIDGET (user_data));
}
}
static void
eom_window_cmd_preferences (GtkAction *action, gpointer user_data)
{
EomWindow *window;
GObject *pref_dlg;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
pref_dlg = eom_preferences_dialog_get_instance (GTK_WINDOW (window));
eom_dialog_show (EOM_DIALOG (pref_dlg));
}
#define EOM_TB_EDITOR_DLG_RESET_RESPONSE 128
static void
eom_window_cmd_edit_toolbar_cb (GtkDialog *dialog, gint response, gpointer data)
{
EomWindow *window = EOM_WINDOW (data);
if (response == EOM_TB_EDITOR_DLG_RESET_RESPONSE) {
EggToolbarsModel *model;
EggToolbarEditor *editor;
editor = g_object_get_data (G_OBJECT (dialog),
"EggToolbarEditor");
g_return_if_fail (editor != NULL);
egg_editable_toolbar_set_edit_mode
(EGG_EDITABLE_TOOLBAR (window->priv->toolbar), FALSE);
eom_application_reset_toolbars_model (EOM_APP);
model = eom_application_get_toolbars_model (EOM_APP);
egg_editable_toolbar_set_model
(EGG_EDITABLE_TOOLBAR (window->priv->toolbar), model);
egg_toolbar_editor_set_model (editor, model);
/* Toolbar would be uneditable now otherwise */
egg_editable_toolbar_set_edit_mode
(EGG_EDITABLE_TOOLBAR (window->priv->toolbar), TRUE);
} else if (response == GTK_RESPONSE_HELP) {
eom_util_show_help ("eom-toolbareditor", NULL);
} else {
egg_editable_toolbar_set_edit_mode
(EGG_EDITABLE_TOOLBAR (window->priv->toolbar), FALSE);
eom_application_save_toolbars_model (EOM_APP);
gtk_widget_destroy (GTK_WIDGET (dialog));
}
}
static void
eom_window_cmd_edit_toolbar (GtkAction *action, gpointer *user_data)
{
EomWindow *window;
GtkWidget *dialog;
GtkWidget *editor;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
dialog = gtk_dialog_new_with_buttons (_("Toolbar Editor"),
GTK_WINDOW (window),
GTK_DIALOG_DESTROY_WITH_PARENT,
_("_Reset to Default"),
EOM_TB_EDITOR_DLG_RESET_RESPONSE,
GTK_STOCK_CLOSE,
GTK_RESPONSE_CLOSE,
GTK_STOCK_HELP,
GTK_RESPONSE_HELP,
NULL);
gtk_dialog_set_default_response (GTK_DIALOG (dialog),
GTK_RESPONSE_CLOSE);
gtk_container_set_border_width (GTK_CONTAINER (dialog), 5);
gtk_box_set_spacing (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), 2);
gtk_window_set_default_size (GTK_WINDOW (dialog), 500, 400);
editor = egg_toolbar_editor_new (window->priv->ui_mgr,
eom_application_get_toolbars_model (EOM_APP));
gtk_container_set_border_width (GTK_CONTAINER (editor), 5);
#if GTK_CHECK_VERSION (3, 0, 0)
// Use as much vertical space as available
gtk_widget_set_vexpand (GTK_WIDGET (editor), TRUE);
#endif
gtk_box_set_spacing (GTK_BOX (EGG_TOOLBAR_EDITOR (editor)), 5);
gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area (GTK_DIALOG (dialog))), editor);
egg_editable_toolbar_set_edit_mode
(EGG_EDITABLE_TOOLBAR (window->priv->toolbar), TRUE);
g_object_set_data (G_OBJECT (dialog), "EggToolbarEditor", editor);
g_signal_connect (dialog,
"response",
G_CALLBACK (eom_window_cmd_edit_toolbar_cb),
window);
gtk_widget_show_all (dialog);
}
static void
eom_window_cmd_help (GtkAction *action, gpointer user_data)
{
EomWindow *window;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
eom_util_show_help (NULL, GTK_WINDOW (window));
}
static void
eom_window_cmd_about (GtkAction *action, gpointer user_data)
{
EomWindow *window;
g_return_if_fail (EOM_IS_WINDOW (user_data));
static const char *authors[] = {
"Perberos <perberos@gmail.com>",
"Steve Zesch <stevezesch2@gmail.com>",
"Stefano Karapetsas <stefano@karapetsas.com>",
"",
"Claudio Saavedra <csaavedra@igalia.com> (maintainer)",
"Felix Riemann <friemann@gnome.org> (maintainer)",
"",
"Lucas Rocha <lucasr@gnome.org>",
"Tim Gerla <tim+matebugs@gerla.net>",
"Philip Van Hoof <pvanhoof@gnome.org>",
"Paolo Borelli <pborelli@katamail.com>",
"Jens Finke <jens@triq.net>",
"Martin Baulig <martin@home-of-linux.org>",
"Arik Devens <arik@gnome.org>",
"Michael Meeks <mmeeks@gnu.org>",
"Federico Mena-Quintero <federico@gnu.org>",
"Lutz M\xc3\xbcller <urc8@rz.uni-karlsruhe.de>",
NULL
};
static const char *documenters[] = {
"Eliot Landrum <eliot@landrum.cx>",
"Federico Mena-Quintero <federico@gnu.org>",
"Sun GNOME Documentation Team <gdocteam@sun.com>",
NULL
};
const char *translators;
translators = _("translator-credits");
const char *license[] = {
N_("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.\n"),
N_("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.\n"),
N_("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 St, Fifth Floor, Boston, MA 02110-1301, USA.")
};
char *license_trans;
license_trans = g_strconcat (_(license[0]), "\n", _(license[1]), "\n",
_(license[2]), "\n", NULL);
window = EOM_WINDOW (user_data);
mate_show_about_dialog (GTK_WINDOW (window),
"program-name", _("Eye of MATE"),
"version", VERSION,
"copyright", "Copyright \xc2\xa9 2000-2010 Free Software Foundation, Inc.\n"
"Copyright \xc2\xa9 2011 Perberos\n"
"Copyright \xc2\xa9 2012-2014 MATE developers",
"comments",_("The MATE image viewer."),
"authors", authors,
"documenters", documenters,
"translator-credits", translators,
"website", "http://www.mate-desktop.org/",
"logo-icon-name", "eom",
"wrap-license", TRUE,
"license", license_trans,
NULL);
g_free (license_trans);
}
static void
eom_window_cmd_show_hide_bar (GtkAction *action, gpointer user_data)
{
EomWindow *window;
EomWindowPrivate *priv;
gboolean visible;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
if (priv->mode != EOM_WINDOW_MODE_NORMAL &&
priv->mode != EOM_WINDOW_MODE_FULLSCREEN) return;
visible = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action));
if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewToolbar") == 0) {
g_object_set (G_OBJECT (priv->toolbar), "visible", visible, NULL);
if (priv->mode == EOM_WINDOW_MODE_NORMAL)
g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_TOOLBAR, visible);
} else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewStatusbar") == 0) {
g_object_set (G_OBJECT (priv->statusbar), "visible", visible, NULL);
if (priv->mode == EOM_WINDOW_MODE_NORMAL)
g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_STATUSBAR, visible);
} else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewImageCollection") == 0) {
if (visible) {
/* Make sure the focus widget is realized to
* avoid warnings on keypress events */
if (!gtk_widget_get_realized (window->priv->thumbview))
gtk_widget_realize (window->priv->thumbview);
gtk_widget_show (priv->nav);
gtk_widget_grab_focus (priv->thumbview);
} else {
/* Make sure the focus widget is realized to
* avoid warnings on keypress events.
* Don't do it during init phase or the view
* will get a bogus allocation. */
if (!gtk_widget_get_realized (priv->view)
&& priv->status == EOM_WINDOW_STATUS_NORMAL)
gtk_widget_realize (priv->view);
gtk_widget_hide (priv->nav);
if (gtk_widget_get_realized (priv->view))
gtk_widget_grab_focus (priv->view);
}
g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION, visible);
} else if (g_ascii_strcasecmp (gtk_action_get_name (action), "ViewSidebar") == 0) {
if (visible) {
gtk_widget_show (priv->sidebar);
} else {
gtk_widget_hide (priv->sidebar);
}
g_settings_set_boolean (priv->ui_settings, EOM_CONF_UI_SIDEBAR, visible);
}
}
static void
wallpaper_info_bar_response (GtkInfoBar *bar, gint response, EomWindow *window)
{
if (response == GTK_RESPONSE_YES) {
GdkScreen *screen;
screen = gtk_widget_get_screen (GTK_WIDGET (window));
mate_gdk_spawn_command_line_on_screen (screen,
"mate-appearance-properties"
" --show-page=background",
NULL);
}
/* Close message area on every response */
eom_window_set_message_area (window, NULL);
}
static void
eom_window_set_wallpaper (EomWindow *window, const gchar *filename, const gchar *visible_filename)
{
GtkWidget *info_bar;
GtkWidget *image;
GtkWidget *label;
GtkWidget *hbox;
gchar *markup;
gchar *text;
gchar *basename;
GSettings *wallpaper_settings;
wallpaper_settings = g_settings_new (EOM_CONF_BACKGROUND_SCHEMA);
g_settings_set_string (wallpaper_settings,
EOM_CONF_BACKGROUND_FILE,
filename);
g_object_unref (wallpaper_settings);
/* I18N: When setting mnemonics for these strings, watch out to not
clash with mnemonics from eom's menubar */
info_bar = gtk_info_bar_new_with_buttons (_("_Open Background Preferences"),
GTK_RESPONSE_YES,
C_("MessageArea","Hi_de"),
GTK_RESPONSE_NO, NULL);
gtk_info_bar_set_message_type (GTK_INFO_BAR (info_bar),
GTK_MESSAGE_QUESTION);
image = gtk_image_new_from_stock (GTK_STOCK_DIALOG_QUESTION,
GTK_ICON_SIZE_DIALOG);
label = gtk_label_new (NULL);
if (!visible_filename)
basename = g_path_get_basename (filename);
/* The newline character is currently necessary due to a problem
* with the automatic line break. */
text = g_strdup_printf (_("The image \"%s\" has been set as Desktop Background."
"\nWould you like to modify its appearance?"),
visible_filename ? visible_filename : basename);
markup = g_markup_printf_escaped ("<b>%s</b>", text);
gtk_label_set_markup (GTK_LABEL (label), markup);
g_free (markup);
g_free (text);
if (!visible_filename)
g_free (basename);
hbox = gtk_hbox_new (FALSE, 8);
gtk_box_pack_start (GTK_BOX (hbox), image, FALSE, FALSE, 0);
#if GTK_CHECK_VERSION (3, 14, 0)
gtk_widget_set_valign (image, GTK_ALIGN_START);
gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
gtk_widget_set_halign (label, GTK_ALIGN_START);
#else
gtk_misc_set_alignment (GTK_MISC (image), 0.5, 0);
gtk_box_pack_start (GTK_BOX (hbox), label, TRUE, TRUE, 0);
gtk_misc_set_alignment (GTK_MISC (label), 0, 0.5);
#endif
gtk_box_pack_start (GTK_BOX (gtk_info_bar_get_content_area (GTK_INFO_BAR (info_bar))), hbox, TRUE, TRUE, 0);
gtk_widget_show_all (hbox);
gtk_widget_show (info_bar);
eom_window_set_message_area (window, info_bar);
gtk_info_bar_set_default_response (GTK_INFO_BAR (info_bar),
GTK_RESPONSE_YES);
g_signal_connect (info_bar, "response",
G_CALLBACK (wallpaper_info_bar_response), window);
}
static void
eom_job_save_cb (EomJobSave *job, gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
GtkAction *action_save;
g_signal_handlers_disconnect_by_func (job,
eom_job_save_cb,
window);
g_signal_handlers_disconnect_by_func (job,
eom_job_save_progress_cb,
window);
g_object_unref (window->priv->save_job);
window->priv->save_job = NULL;
update_status_bar (window);
action_save = gtk_action_group_get_action (window->priv->actions_image,
"ImageSave");
gtk_action_set_sensitive (action_save, FALSE);
}
static void
eom_job_copy_cb (EomJobCopy *job, gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
gchar *filepath, *basename, *filename, *extension;
GtkAction *action;
GFile *source_file, *dest_file;
/* Create source GFile */
basename = g_file_get_basename (job->images->data);
filepath = g_build_filename (job->dest, basename, NULL);
source_file = g_file_new_for_path (filepath);
g_free (filepath);
/* Create destination GFile */
extension = eom_util_filename_get_extension (basename);
filename = g_strdup_printf ("%s.%s", EOM_WALLPAPER_FILENAME, extension);
filepath = g_build_filename (job->dest, filename, NULL);
dest_file = g_file_new_for_path (filepath);
g_free (filename);
g_free (extension);
/* Move the file */
g_file_move (source_file, dest_file, G_FILE_COPY_OVERWRITE,
NULL, NULL, NULL, NULL);
/* Set the wallpaper */
eom_window_set_wallpaper (window, filepath, basename);
g_free (basename);
g_free (filepath);
gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar),
window->priv->copy_file_cid);
action = gtk_action_group_get_action (window->priv->actions_image,
"ImageSetAsWallpaper");
gtk_action_set_sensitive (action, TRUE);
window->priv->copy_job = NULL;
g_object_unref (source_file);
g_object_unref (dest_file);
g_object_unref (G_OBJECT (job->images->data));
g_list_free (job->images);
g_object_unref (job);
}
static gboolean
eom_window_save_images (EomWindow *window, GList *images)
{
EomWindowPrivate *priv;
priv = window->priv;
if (window->priv->save_job != NULL)
return FALSE;
priv->save_job = eom_job_save_new (images);
g_signal_connect (priv->save_job,
"finished",
G_CALLBACK (eom_job_save_cb),
window);
g_signal_connect (priv->save_job,
"progress",
G_CALLBACK (eom_job_save_progress_cb),
window);
return TRUE;
}
static void
eom_window_cmd_save (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
EomWindow *window;
GList *images;
window = EOM_WINDOW (user_data);
priv = window->priv;
if (window->priv->save_job != NULL)
return;
images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview));
if (eom_window_save_images (window, images)) {
eom_job_queue_add_job (priv->save_job);
}
}
static GFile*
eom_window_retrieve_save_as_file (EomWindow *window, EomImage *image)
{
GtkWidget *dialog;
GFile *save_file = NULL;
GFile *last_dest_folder;
gint response;
g_assert (image != NULL);
dialog = eom_file_chooser_new (GTK_FILE_CHOOSER_ACTION_SAVE);
last_dest_folder = window->priv->last_save_as_folder;
if (last_dest_folder && g_file_query_exists (last_dest_folder, NULL)) {
gtk_file_chooser_set_current_folder_file (GTK_FILE_CHOOSER (dialog), last_dest_folder, NULL);
gtk_file_chooser_set_current_name (GTK_FILE_CHOOSER (dialog),
eom_image_get_caption (image));
} else {
GFile *image_file;
image_file = eom_image_get_file (image);
/* Setting the file will also navigate to its parent folder */
gtk_file_chooser_set_file (GTK_FILE_CHOOSER (dialog),
image_file, NULL);
g_object_unref (image_file);
}
response = gtk_dialog_run (GTK_DIALOG (dialog));
gtk_widget_hide (dialog);
if (response == GTK_RESPONSE_OK) {
save_file = gtk_file_chooser_get_file (GTK_FILE_CHOOSER (dialog));
if (window->priv->last_save_as_folder)
g_object_unref (window->priv->last_save_as_folder);
window->priv->last_save_as_folder = g_file_get_parent (save_file);
}
gtk_widget_destroy (dialog);
return save_file;
}
static void
eom_window_cmd_save_as (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
EomWindow *window;
GList *images;
guint n_images;
window = EOM_WINDOW (user_data);
priv = window->priv;
if (window->priv->save_job != NULL)
return;
images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview));
n_images = g_list_length (images);
if (n_images == 1) {
GFile *file;
file = eom_window_retrieve_save_as_file (window, images->data);
if (!file) {
g_list_free (images);
return;
}
priv->save_job = eom_job_save_as_new (images, NULL, file);
g_object_unref (file);
} else if (n_images > 1) {
GFile *base_file;
GtkWidget *dialog;
gchar *basedir;
EomURIConverter *converter;
basedir = g_get_current_dir ();
base_file = g_file_new_for_path (basedir);
g_free (basedir);
dialog = eom_save_as_dialog_new (GTK_WINDOW (window),
images,
base_file);
gtk_widget_show_all (dialog);
if (gtk_dialog_run (GTK_DIALOG (dialog)) != GTK_RESPONSE_OK) {
g_object_unref (base_file);
g_list_free (images);
gtk_widget_destroy (dialog);
return;
}
converter = eom_save_as_dialog_get_converter (dialog);
g_assert (converter != NULL);
priv->save_job = eom_job_save_as_new (images, converter, NULL);
gtk_widget_destroy (dialog);
g_object_unref (converter);
g_object_unref (base_file);
} else {
/* n_images = 0 -- No Image selected */
return;
}
g_signal_connect (priv->save_job,
"finished",
G_CALLBACK (eom_job_save_cb),
window);
g_signal_connect (priv->save_job,
"progress",
G_CALLBACK (eom_job_save_progress_cb),
window);
eom_job_queue_add_job (priv->save_job);
}
static void
eom_window_cmd_print (GtkAction *action, gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
eom_window_print (window);
}
static void
eom_window_cmd_properties (GtkAction *action, gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
EomWindowPrivate *priv;
GtkAction *next_image_action, *previous_image_action;
priv = window->priv;
next_image_action =
gtk_action_group_get_action (priv->actions_collection,
"GoNext");
previous_image_action =
gtk_action_group_get_action (priv->actions_collection,
"GoPrevious");
if (window->priv->properties_dlg == NULL) {
window->priv->properties_dlg =
eom_properties_dialog_new (GTK_WINDOW (window),
EOM_THUMB_VIEW (priv->thumbview),
next_image_action,
previous_image_action);
eom_properties_dialog_update (EOM_PROPERTIES_DIALOG (priv->properties_dlg),
priv->image);
g_settings_bind (priv->ui_settings,
EOM_CONF_UI_PROPSDIALOG_NETBOOK_MODE,
priv->properties_dlg, "netbook-mode",
G_SETTINGS_BIND_GET);
}
eom_dialog_show (EOM_DIALOG (window->priv->properties_dlg));
}
static void
eom_window_cmd_undo (GtkAction *action, gpointer user_data)
{
g_return_if_fail (EOM_IS_WINDOW (user_data));
apply_transformation (EOM_WINDOW (user_data), NULL);
}
static void
eom_window_cmd_flip_horizontal (GtkAction *action, gpointer user_data)
{
g_return_if_fail (EOM_IS_WINDOW (user_data));
apply_transformation (EOM_WINDOW (user_data),
eom_transform_flip_new (EOM_TRANSFORM_FLIP_HORIZONTAL));
}
static void
eom_window_cmd_flip_vertical (GtkAction *action, gpointer user_data)
{
g_return_if_fail (EOM_IS_WINDOW (user_data));
apply_transformation (EOM_WINDOW (user_data),
eom_transform_flip_new (EOM_TRANSFORM_FLIP_VERTICAL));
}
static void
eom_window_cmd_rotate_90 (GtkAction *action, gpointer user_data)
{
g_return_if_fail (EOM_IS_WINDOW (user_data));
apply_transformation (EOM_WINDOW (user_data),
eom_transform_rotate_new (90));
}
static void
eom_window_cmd_rotate_270 (GtkAction *action, gpointer user_data)
{
g_return_if_fail (EOM_IS_WINDOW (user_data));
apply_transformation (EOM_WINDOW (user_data),
eom_transform_rotate_new (270));
}
static void
eom_window_cmd_wallpaper (GtkAction *action, gpointer user_data)
{
EomWindow *window;
EomWindowPrivate *priv;
EomImage *image;
GFile *file;
char *filename = NULL;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
/* If currently copying an image to set it as wallpaper, return. */
if (priv->copy_job != NULL)
return;
image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview));
g_return_if_fail (EOM_IS_IMAGE (image));
file = eom_image_get_file (image);
filename = g_file_get_path (file);
/* Currently only local files can be set as wallpaper */
if (filename == NULL || !eom_util_file_is_persistent (file))
{
GList *files = NULL;
GtkAction *action;
action = gtk_action_group_get_action (window->priv->actions_image,
"ImageSetAsWallpaper");
gtk_action_set_sensitive (action, FALSE);
priv->copy_file_cid = gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar),
"copy_file_cid");
gtk_statusbar_push (GTK_STATUSBAR (priv->statusbar),
priv->copy_file_cid,
_("Saving image locally…"));
files = g_list_append (files, eom_image_get_file (image));
priv->copy_job = eom_job_copy_new (files, g_get_user_data_dir ());
g_signal_connect (priv->copy_job,
"finished",
G_CALLBACK (eom_job_copy_cb),
window);
g_signal_connect (priv->copy_job,
"progress",
G_CALLBACK (eom_job_progress_cb),
window);
eom_job_queue_add_job (priv->copy_job);
g_object_unref (file);
g_free (filename);
return;
}
g_object_unref (file);
eom_window_set_wallpaper (window, filename, NULL);
g_free (filename);
}
static gboolean
eom_window_all_images_trasheable (GList *images)
{
GFile *file;
GFileInfo *file_info;
GList *iter;
EomImage *image;
gboolean can_trash = TRUE;
for (iter = images; iter != NULL; iter = g_list_next (iter)) {
image = (EomImage *) iter->data;
file = eom_image_get_file (image);
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH,
0, NULL, NULL);
can_trash = g_file_info_get_attribute_boolean (file_info,
G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH);
g_object_unref (file_info);
g_object_unref (file);
if (can_trash == FALSE)
break;
}
return can_trash;
}
static int
show_move_to_trash_confirm_dialog (EomWindow *window, GList *images, gboolean can_trash)
{
GtkWidget *dlg;
char *prompt;
int response;
int n_images;
EomImage *image;
static gboolean dontaskagain = FALSE;
gboolean neverask = FALSE;
GtkWidget* dontask_cbutton = NULL;
/* Check if the user never wants to be bugged. */
neverask = g_settings_get_boolean (window->priv->ui_settings,
EOM_CONF_UI_DISABLE_TRASH_CONFIRMATION);
/* Assume agreement, if the user doesn't want to be
* asked and the trash is available */
if (can_trash && (dontaskagain || neverask))
return GTK_RESPONSE_OK;
n_images = g_list_length (images);
if (n_images == 1) {
image = EOM_IMAGE (images->data);
if (can_trash) {
prompt = g_strdup_printf (_("Are you sure you want to move\n\"%s\" to the trash?"),
eom_image_get_caption (image));
} else {
prompt = g_strdup_printf (_("A trash for \"%s\" couldn't be found. Do you want to remove "
"this image permanently?"), eom_image_get_caption (image));
}
} else {
if (can_trash) {
prompt = g_strdup_printf (ngettext("Are you sure you want to move\n"
"the selected image to the trash?",
"Are you sure you want to move\n"
"the %d selected images to the trash?", n_images), n_images);
} else {
prompt = g_strdup (_("Some of the selected images can't be moved to the trash "
"and will be removed permanently. Are you sure you want "
"to proceed?"));
}
}
dlg = gtk_message_dialog_new_with_markup (GTK_WINDOW (window),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_WARNING,
GTK_BUTTONS_NONE,
"<span weight=\"bold\" size=\"larger\">%s</span>",
prompt);
g_free (prompt);
gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL);
if (can_trash) {
gtk_dialog_add_button (GTK_DIALOG (dlg), _("Move to _Trash"), GTK_RESPONSE_OK);
dontask_cbutton = gtk_check_button_new_with_mnemonic (_("_Do not ask again during this session"));
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (dontask_cbutton), FALSE);
gtk_box_pack_end (GTK_BOX (gtk_dialog_get_content_area (GTK_DIALOG (dlg))), dontask_cbutton, TRUE, TRUE, 0);
} else {
if (n_images == 1) {
gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_DELETE, GTK_RESPONSE_OK);
} else {
gtk_dialog_add_button (GTK_DIALOG (dlg), GTK_STOCK_YES, GTK_RESPONSE_OK);
}
}
gtk_dialog_set_default_response (GTK_DIALOG (dlg), GTK_RESPONSE_OK);
gtk_window_set_title (GTK_WINDOW (dlg), "");
gtk_widget_show_all (dlg);
response = gtk_dialog_run (GTK_DIALOG (dlg));
/* Only update the property if the user has accepted */
if (can_trash && response == GTK_RESPONSE_OK)
dontaskagain = gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (dontask_cbutton));
/* The checkbutton is destroyed together with the dialog */
gtk_widget_destroy (dlg);
return response;
}
static gboolean
move_to_trash_real (EomImage *image, GError **error)
{
GFile *file;
GFileInfo *file_info;
gboolean can_trash, result;
g_return_val_if_fail (EOM_IS_IMAGE (image), FALSE);
file = eom_image_get_file (image);
file_info = g_file_query_info (file,
G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH,
0, NULL, NULL);
if (file_info == NULL) {
g_set_error (error,
EOM_WINDOW_ERROR,
EOM_WINDOW_ERROR_TRASH_NOT_FOUND,
_("Couldn't access trash."));
return FALSE;
}
can_trash = g_file_info_get_attribute_boolean (file_info,
G_FILE_ATTRIBUTE_ACCESS_CAN_TRASH);
g_object_unref (file_info);
if (can_trash)
{
result = g_file_trash (file, NULL, NULL);
if (result == FALSE) {
g_set_error (error,
EOM_WINDOW_ERROR,
EOM_WINDOW_ERROR_TRASH_NOT_FOUND,
_("Couldn't access trash."));
}
} else {
result = g_file_delete (file, NULL, NULL);
if (result == FALSE) {
g_set_error (error,
EOM_WINDOW_ERROR,
EOM_WINDOW_ERROR_IO,
_("Couldn't delete file"));
}
}
g_object_unref (file);
return result;
}
static void
eom_window_cmd_copy_image (GtkAction *action, gpointer user_data)
{
GtkClipboard *clipboard;
EomWindow *window;
EomWindowPrivate *priv;
EomImage *image;
EomClipboardHandler *cbhandler;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
image = eom_thumb_view_get_first_selected_image (EOM_THUMB_VIEW (priv->thumbview));
g_return_if_fail (EOM_IS_IMAGE (image));
clipboard = gtk_clipboard_get (GDK_SELECTION_CLIPBOARD);
cbhandler = eom_clipboard_handler_new (image);
// cbhandler will self-destruct when it's not needed anymore
eom_clipboard_handler_copy_to_clipboard (cbhandler, clipboard);
}
static void
eom_window_cmd_move_to_trash (GtkAction *action, gpointer user_data)
{
GList *images;
GList *it;
EomWindowPrivate *priv;
EomListStore *list;
int pos;
EomImage *img;
EomWindow *window;
int response;
int n_images;
gboolean success;
gboolean can_trash;
g_return_if_fail (EOM_IS_WINDOW (user_data));
window = EOM_WINDOW (user_data);
priv = window->priv;
list = priv->store;
n_images = eom_thumb_view_get_n_selected (EOM_THUMB_VIEW (priv->thumbview));
if (n_images < 1) return;
/* save position of selected image after the deletion */
images = eom_thumb_view_get_selected_images (EOM_THUMB_VIEW (priv->thumbview));
g_assert (images != NULL);
/* HACK: eom_list_store_get_n_selected return list in reverse order */
images = g_list_reverse (images);
can_trash = eom_window_all_images_trasheable (images);
if (g_ascii_strcasecmp (gtk_action_get_name (action), "Delete") == 0 ||
can_trash == FALSE) {
response = show_move_to_trash_confirm_dialog (window, images, can_trash);
if (response != GTK_RESPONSE_OK) return;
}
pos = eom_list_store_get_pos_by_image (list, EOM_IMAGE (images->data));
/* FIXME: make a nice progress dialog */
/* Do the work actually. First try to delete the image from the disk. If this
* is successfull, remove it from the screen. Otherwise show error dialog.
*/
for (it = images; it != NULL; it = it->next) {
GError *error = NULL;
EomImage *image;
image = EOM_IMAGE (it->data);
success = move_to_trash_real (image, &error);
if (success) {
eom_list_store_remove_image (list, image);
} else {
char *header;
GtkWidget *dlg;
header = g_strdup_printf (_("Error on deleting image %s"),
eom_image_get_caption (image));
dlg = gtk_message_dialog_new (GTK_WINDOW (window),
GTK_DIALOG_MODAL | GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_MESSAGE_ERROR,
GTK_BUTTONS_OK,
"%s", header);
gtk_message_dialog_format_secondary_text (GTK_MESSAGE_DIALOG (dlg),
"%s", error->message);
gtk_dialog_run (GTK_DIALOG (dlg));
gtk_widget_destroy (dlg);
g_free (header);
}
}
/* free list */
g_list_foreach (images, (GFunc) g_object_unref, NULL);
g_list_free (images);
/* select image at previously saved position */
pos = MIN (pos, eom_list_store_length (list) - 1);
if (pos >= 0) {
img = eom_list_store_get_image_by_pos (list, pos);
eom_thumb_view_set_current_image (EOM_THUMB_VIEW (priv->thumbview),
img,
TRUE);
if (img != NULL) {
g_object_unref (img);
}
}
}
static void
eom_window_cmd_fullscreen (GtkAction *action, gpointer user_data)
{
EomWindow *window;
gboolean fullscreen;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
window = EOM_WINDOW (user_data);
fullscreen = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action));
if (fullscreen) {
eom_window_run_fullscreen (window, FALSE);
} else {
eom_window_stop_fullscreen (window, FALSE);
}
}
static void
eom_window_cmd_slideshow (GtkAction *action, gpointer user_data)
{
EomWindow *window;
gboolean slideshow;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
window = EOM_WINDOW (user_data);
slideshow = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action));
if (slideshow) {
eom_window_run_fullscreen (window, TRUE);
} else {
eom_window_stop_fullscreen (window, TRUE);
}
}
static void
eom_window_cmd_pause_slideshow (GtkAction *action, gpointer user_data)
{
EomWindow *window;
gboolean slideshow;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
window = EOM_WINDOW (user_data);
slideshow = window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW;
if (!slideshow && window->priv->mode != EOM_WINDOW_MODE_FULLSCREEN)
return;
eom_window_run_fullscreen (window, !slideshow);
}
static void
eom_window_cmd_zoom_in (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
if (priv->view) {
eom_scroll_view_zoom_in (EOM_SCROLL_VIEW (priv->view), FALSE);
}
}
static void
eom_window_cmd_zoom_out (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
if (priv->view) {
eom_scroll_view_zoom_out (EOM_SCROLL_VIEW (priv->view), FALSE);
}
}
static void
eom_window_cmd_zoom_normal (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
if (priv->view) {
eom_scroll_view_set_zoom (EOM_SCROLL_VIEW (priv->view), 1.0);
}
}
static void
eom_window_cmd_zoom_fit (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
if (priv->view) {
eom_scroll_view_zoom_fit (EOM_SCROLL_VIEW (priv->view));
}
}
static void
eom_window_cmd_go_prev (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_LEFT);
}
static void
eom_window_cmd_go_next (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_RIGHT);
}
static void
eom_window_cmd_go_first (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_FIRST);
}
static void
eom_window_cmd_go_last (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_LAST);
}
static void
eom_window_cmd_go_random (GtkAction *action, gpointer user_data)
{
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (user_data));
eom_debug (DEBUG_WINDOW);
priv = EOM_WINDOW (user_data)->priv;
eom_thumb_view_select_single (EOM_THUMB_VIEW (priv->thumbview),
EOM_THUMB_VIEW_SELECT_RANDOM);
}
static const GtkActionEntry action_entries_window[] = {
{ "Image", NULL, N_("_Image") },
{ "Edit", NULL, N_("_Edit") },
{ "View", NULL, N_("_View") },
{ "Go", NULL, N_("_Go") },
{ "Tools", NULL, N_("_Tools") },
{ "Help", NULL, N_("_Help") },
{ "ImageOpen", GTK_STOCK_OPEN, N_("_Open…"), "<control>O",
N_("Open a file"),
G_CALLBACK (eom_window_cmd_file_open) },
{ "ImageClose", GTK_STOCK_CLOSE, N_("_Close"), "<control>W",
N_("Close window"),
G_CALLBACK (eom_window_cmd_close_window) },
{ "EditToolbar", NULL, N_("T_oolbar"), NULL,
N_("Edit the application toolbar"),
G_CALLBACK (eom_window_cmd_edit_toolbar) },
{ "EditPreferences", GTK_STOCK_PREFERENCES, N_("Prefere_nces"), NULL,
N_("Preferences for Eye of MATE"),
G_CALLBACK (eom_window_cmd_preferences) },
{ "HelpManual", GTK_STOCK_HELP, N_("_Contents"), "F1",
N_("Help on this application"),
G_CALLBACK (eom_window_cmd_help) },
{ "HelpAbout", GTK_STOCK_ABOUT, N_("_About"), NULL,
N_("About this application"),
G_CALLBACK (eom_window_cmd_about) }
};
static const GtkToggleActionEntry toggle_entries_window[] = {
{ "ViewToolbar", NULL, N_("_Toolbar"), NULL,
N_("Changes the visibility of the toolbar in the current window"),
G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE },
{ "ViewStatusbar", NULL, N_("_Statusbar"), NULL,
N_("Changes the visibility of the statusbar in the current window"),
G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE },
{ "ViewImageCollection", "eom-image-collection", N_("_Image Collection"), "F9",
N_("Changes the visibility of the image collection pane in the current window"),
G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE },
{ "ViewSidebar", NULL, N_("Side _Pane"), "<control>F9",
N_("Changes the visibility of the side pane in the current window"),
G_CALLBACK (eom_window_cmd_show_hide_bar), TRUE },
};
static const GtkActionEntry action_entries_image[] = {
{ "ImageSave", GTK_STOCK_SAVE, N_("_Save"), "<control>s",
N_("Save changes in currently selected images"),
G_CALLBACK (eom_window_cmd_save) },
{ "ImageOpenWith", NULL, N_("Open _with"), NULL,
N_("Open the selected image with a different application"),
NULL},
{ "ImageSaveAs", GTK_STOCK_SAVE_AS, N_("Save _As…"), "<control><shift>s",
N_("Save the selected images with a different name"),
G_CALLBACK (eom_window_cmd_save_as) },
{ "ImagePrint", GTK_STOCK_PRINT, N_("_Print…"), "<control>p",
N_("Print the selected image"),
G_CALLBACK (eom_window_cmd_print) },
{ "ImageProperties", GTK_STOCK_PROPERTIES, N_("Prope_rties"), "<alt>Return",
N_("Show the properties and metadata of the selected image"),
G_CALLBACK (eom_window_cmd_properties) },
{ "EditUndo", GTK_STOCK_UNDO, N_("_Undo"), "<control>z",
N_("Undo the last change in the image"),
G_CALLBACK (eom_window_cmd_undo) },
{ "EditFlipHorizontal", "object-flip-horizontal", N_("Flip _Horizontal"), NULL,
N_("Mirror the image horizontally"),
G_CALLBACK (eom_window_cmd_flip_horizontal) },
{ "EditFlipVertical", "object-flip-vertical", N_("Flip _Vertical"), NULL,
N_("Mirror the image vertically"),
G_CALLBACK (eom_window_cmd_flip_vertical) },
{ "EditRotate90", "object-rotate-right", N_("_Rotate Clockwise"), "<control>r",
N_("Rotate the image 90 degrees to the right"),
G_CALLBACK (eom_window_cmd_rotate_90) },
{ "EditRotate270", "object-rotate-left", N_("Rotate Counterc_lockwise"), "<ctrl><shift>r",
N_("Rotate the image 90 degrees to the left"),
G_CALLBACK (eom_window_cmd_rotate_270) },
{ "ImageSetAsWallpaper", NULL, N_("Set as _Desktop Background"),
"<control>F8", N_("Set the selected image as the desktop background"),
G_CALLBACK (eom_window_cmd_wallpaper) },
{ "EditMoveToTrash", "user-trash", N_("Move to _Trash"), NULL,
N_("Move the selected image to the trash folder"),
G_CALLBACK (eom_window_cmd_move_to_trash) },
{ "EditCopyImage", "edit-copy", N_("_Copy"), "<control>C",
N_("Copy the selected image to the clipboard"),
G_CALLBACK (eom_window_cmd_copy_image) },
{ "ViewZoomIn", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>plus",
N_("Enlarge the image"),
G_CALLBACK (eom_window_cmd_zoom_in) },
{ "ViewZoomOut", GTK_STOCK_ZOOM_OUT, N_("Zoom _Out"), "<control>minus",
N_("Shrink the image"),
G_CALLBACK (eom_window_cmd_zoom_out) },
{ "ViewZoomNormal", GTK_STOCK_ZOOM_100, N_("_Normal Size"), "<control>0",
N_("Show the image at its normal size"),
G_CALLBACK (eom_window_cmd_zoom_normal) },
{ "ViewZoomFit", GTK_STOCK_ZOOM_FIT, N_("_Best Fit"), "F",
N_("Fit the image to the window"),
G_CALLBACK (eom_window_cmd_zoom_fit) },
{ "ControlEqual", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>equal",
N_("Enlarge the image"),
G_CALLBACK (eom_window_cmd_zoom_in) },
{ "ControlKpAdd", GTK_STOCK_ZOOM_IN, N_("_Zoom In"), "<control>KP_Add",
N_("Shrink the image"),
G_CALLBACK (eom_window_cmd_zoom_in) },
{ "ControlKpSub", GTK_STOCK_ZOOM_OUT, N_("Zoom _Out"), "<control>KP_Subtract",
N_("Shrink the image"),
G_CALLBACK (eom_window_cmd_zoom_out) },
{ "Delete", NULL, N_("Move to _Trash"), "Delete",
NULL,
G_CALLBACK (eom_window_cmd_move_to_trash) },
};
static const GtkToggleActionEntry toggle_entries_image[] = {
{ "ViewFullscreen", GTK_STOCK_FULLSCREEN, N_("_Fullscreen"), "F11",
N_("Show the current image in fullscreen mode"),
G_CALLBACK (eom_window_cmd_fullscreen), FALSE },
{ "PauseSlideshow", "media-playback-pause", N_("Pause Slideshow"),
NULL, N_("Pause or resume the slideshow"),
G_CALLBACK (eom_window_cmd_pause_slideshow), FALSE },
};
static const GtkActionEntry action_entries_collection[] = {
{ "GoPrevious", GTK_STOCK_GO_BACK, N_("_Previous Image"), "<Alt>Left",
N_("Go to the previous image of the collection"),
G_CALLBACK (eom_window_cmd_go_prev) },
{ "GoNext", GTK_STOCK_GO_FORWARD, N_("_Next Image"), "<Alt>Right",
N_("Go to the next image of the collection"),
G_CALLBACK (eom_window_cmd_go_next) },
{ "GoFirst", GTK_STOCK_GOTO_FIRST, N_("_First Image"), "<Alt>Home",
N_("Go to the first image of the collection"),
G_CALLBACK (eom_window_cmd_go_first) },
{ "GoLast", GTK_STOCK_GOTO_LAST, N_("_Last Image"), "<Alt>End",
N_("Go to the last image of the collection"),
G_CALLBACK (eom_window_cmd_go_last) },
{ "GoRandom", NULL, N_("_Random Image"), "<control>M",
N_("Go to a random image of the collection"),
G_CALLBACK (eom_window_cmd_go_random) },
{ "BackSpace", NULL, N_("_Previous Image"), "BackSpace",
NULL,
G_CALLBACK (eom_window_cmd_go_prev) },
{ "Home", NULL, N_("_First Image"), "Home",
NULL,
G_CALLBACK (eom_window_cmd_go_first) },
{ "End", NULL, N_("_Last Image"), "End",
NULL,
G_CALLBACK (eom_window_cmd_go_last) },
};
static const GtkToggleActionEntry toggle_entries_collection[] = {
{ "ViewSlideshow", "slideshow-play", N_("S_lideshow"), "F5",
N_("Start a slideshow view of the images"),
G_CALLBACK (eom_window_cmd_slideshow), FALSE },
};
static void
menu_item_select_cb (GtkMenuItem *proxy, EomWindow *window)
{
GtkAction *action;
char *message;
action = gtk_activatable_get_related_action (GTK_ACTIVATABLE (proxy));
g_return_if_fail (action != NULL);
g_object_get (G_OBJECT (action), "tooltip", &message, NULL);
if (message) {
gtk_statusbar_push (GTK_STATUSBAR (window->priv->statusbar),
window->priv->tip_message_cid, message);
g_free (message);
}
}
static void
menu_item_deselect_cb (GtkMenuItem *proxy, EomWindow *window)
{
gtk_statusbar_pop (GTK_STATUSBAR (window->priv->statusbar),
window->priv->tip_message_cid);
}
static void
connect_proxy_cb (GtkUIManager *manager,
GtkAction *action,
GtkWidget *proxy,
EomWindow *window)
{
if (GTK_IS_MENU_ITEM (proxy)) {
g_signal_connect (proxy, "select",
G_CALLBACK (menu_item_select_cb), window);
g_signal_connect (proxy, "deselect",
G_CALLBACK (menu_item_deselect_cb), window);
}
}
static void
disconnect_proxy_cb (GtkUIManager *manager,
GtkAction *action,
GtkWidget *proxy,
EomWindow *window)
{
if (GTK_IS_MENU_ITEM (proxy)) {
g_signal_handlers_disconnect_by_func
(proxy, G_CALLBACK (menu_item_select_cb), window);
g_signal_handlers_disconnect_by_func
(proxy, G_CALLBACK (menu_item_deselect_cb), window);
}
}
static void
set_action_properties (GtkActionGroup *window_group,
GtkActionGroup *image_group,
GtkActionGroup *collection_group)
{
GtkAction *action;
action = gtk_action_group_get_action (collection_group, "GoPrevious");
g_object_set (action, "short_label", _("Previous"), NULL);
g_object_set (action, "is-important", TRUE, NULL);
action = gtk_action_group_get_action (collection_group, "GoNext");
g_object_set (action, "short_label", _("Next"), NULL);
g_object_set (action, "is-important", TRUE, NULL);
action = gtk_action_group_get_action (image_group, "EditRotate90");
g_object_set (action, "short_label", _("Right"), NULL);
action = gtk_action_group_get_action (image_group, "EditRotate270");
g_object_set (action, "short_label", _("Left"), NULL);
action = gtk_action_group_get_action (image_group, "ViewZoomIn");
g_object_set (action, "short_label", _("In"), NULL);
action = gtk_action_group_get_action (image_group, "ViewZoomOut");
g_object_set (action, "short_label", _("Out"), NULL);
action = gtk_action_group_get_action (image_group, "ViewZoomNormal");
g_object_set (action, "short_label", _("Normal"), NULL);
action = gtk_action_group_get_action (image_group, "ViewZoomFit");
g_object_set (action, "short_label", _("Fit"), NULL);
action = gtk_action_group_get_action (window_group, "ViewImageCollection");
g_object_set (action, "short_label", _("Collection"), NULL);
action = gtk_action_group_get_action (image_group, "EditMoveToTrash");
g_object_set (action, "short_label", C_("action (to trash)", "Trash"), NULL);
}
static gint
sort_recents_mru (GtkRecentInfo *a, GtkRecentInfo *b)
{
gboolean has_eom_a, has_eom_b;
/* We need to check this first as gtk_recent_info_get_application_info
* will treat it as a non-fatal error when the GtkRecentInfo doesn't
* have the application registered. */
has_eom_a = gtk_recent_info_has_application (a,
EOM_RECENT_FILES_APP_NAME);
has_eom_b = gtk_recent_info_has_application (b,
EOM_RECENT_FILES_APP_NAME);
if (has_eom_a && has_eom_b) {
time_t time_a, time_b;
/* These should not fail as we already checked that
* the application is registered with the info objects */
gtk_recent_info_get_application_info (a,
EOM_RECENT_FILES_APP_NAME,
NULL,
NULL,
&time_a);
gtk_recent_info_get_application_info (b,
EOM_RECENT_FILES_APP_NAME,
NULL,
NULL,
&time_b);
return (time_b - time_a);
} else if (has_eom_a) {
return -1;
} else if (has_eom_b) {
return 1;
}
return 0;
}
static void
eom_window_update_recent_files_menu (EomWindow *window)
{
EomWindowPrivate *priv;
GList *actions = NULL, *li = NULL, *items = NULL;
guint count_recent = 0;
priv = window->priv;
if (priv->recent_menu_id != 0)
gtk_ui_manager_remove_ui (priv->ui_mgr, priv->recent_menu_id);
actions = gtk_action_group_list_actions (priv->actions_recent);
for (li = actions; li != NULL; li = li->next) {
g_signal_handlers_disconnect_by_func (GTK_ACTION (li->data),
G_CALLBACK(eom_window_open_recent_cb),
window);
gtk_action_group_remove_action (priv->actions_recent,
GTK_ACTION (li->data));
}
g_list_free (actions);
priv->recent_menu_id = gtk_ui_manager_new_merge_id (priv->ui_mgr);
items = gtk_recent_manager_get_items (gtk_recent_manager_get_default());
items = g_list_sort (items, (GCompareFunc) sort_recents_mru);
for (li = items; li != NULL && count_recent < EOM_RECENT_FILES_LIMIT; li = li->next) {
gchar *action_name;
gchar *label;
gchar *tip;
gchar **display_name;
gchar *label_filename;
GtkAction *action;
GtkRecentInfo *info = li->data;
/* Sorting moves non-EOM files to the end of the list.
* So no file of interest will follow if this test fails */
if (!gtk_recent_info_has_application (info, EOM_RECENT_FILES_APP_NAME))
break;
count_recent++;
action_name = g_strdup_printf ("recent-info-%d", count_recent);
display_name = g_strsplit (gtk_recent_info_get_display_name (info), "_", -1);
label_filename = g_strjoinv ("__", display_name);
label = g_strdup_printf ("%s_%d. %s",
(is_rtl ? "\xE2\x80\x8F" : ""), count_recent, label_filename);
g_free (label_filename);
g_strfreev (display_name);
tip = gtk_recent_info_get_uri_display (info);
/* This is a workaround for a bug (#351945) regarding
* gtk_recent_info_get_uri_display() and remote URIs.
* mate_vfs_format_uri_for_display is sufficient here
* since the password gets stripped when adding the
* file to the recently used list. */
if (tip == NULL)
tip = g_uri_unescape_string (gtk_recent_info_get_uri (info), NULL);
action = gtk_action_new (action_name, label, tip, NULL);
gtk_action_set_always_show_image (action, TRUE);
g_object_set_data_full (G_OBJECT (action), "gtk-recent-info",
gtk_recent_info_ref (info),
(GDestroyNotify) gtk_recent_info_unref);
g_object_set (G_OBJECT (action), "icon-name", "image-x-generic", NULL);
g_signal_connect (action, "activate",
G_CALLBACK (eom_window_open_recent_cb),
window);
gtk_action_group_add_action (priv->actions_recent, action);
g_object_unref (action);
gtk_ui_manager_add_ui (priv->ui_mgr, priv->recent_menu_id,
"/MainMenu/Image/RecentDocuments",
action_name, action_name,
GTK_UI_MANAGER_AUTO, FALSE);
g_free (action_name);
g_free (label);
g_free (tip);
}
g_list_foreach (items, (GFunc) gtk_recent_info_unref, NULL);
g_list_free (items);
}
static void
eom_window_recent_manager_changed_cb (GtkRecentManager *manager, EomWindow *window)
{
eom_window_update_recent_files_menu (window);
}
static void
eom_window_drag_data_received (GtkWidget *widget,
GdkDragContext *context,
gint x, gint y,
GtkSelectionData *selection_data,
guint info, guint time)
{
GSList *file_list;
EomWindow *window;
GdkAtom target;
GtkWidget *src;
target = gtk_selection_data_get_target (selection_data);
if (!gtk_targets_include_uri (&target, 1))
return;
/* if the request is from another process this will return NULL */
src = gtk_drag_get_source_widget (context);
/* if the drag request originates from the current eom instance, ignore
the request if the source window is the same as the dest window */
if (src &&
gtk_widget_get_toplevel (src) == gtk_widget_get_toplevel (widget))
{
gdk_drag_status (context, 0, time);
return;
}
if (gdk_drag_context_get_suggested_action (context) == GDK_ACTION_COPY) {
window = EOM_WINDOW (widget);
file_list = eom_util_parse_uri_string_list_to_file_list ((const gchar *) gtk_selection_data_get_data (selection_data));
eom_window_open_file_list (window, file_list);
}
}
static void
eom_window_set_drag_dest (EomWindow *window)
{
gtk_drag_dest_set (GTK_WIDGET (window),
GTK_DEST_DEFAULT_MOTION | GTK_DEST_DEFAULT_DROP,
NULL, 0,
GDK_ACTION_COPY | GDK_ACTION_ASK);
gtk_drag_dest_add_uri_targets (GTK_WIDGET (window));
}
static void
eom_window_sidebar_visibility_changed (GtkWidget *widget, EomWindow *window)
{
GtkAction *action;
gboolean visible;
visible = gtk_widget_get_visible (window->priv->sidebar);
g_settings_set_boolean (window->priv->ui_settings,
EOM_CONF_UI_SIDEBAR,
visible);
action = gtk_action_group_get_action (window->priv->actions_window,
"ViewSidebar");
if (gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action)) != visible)
gtk_toggle_action_set_active (GTK_TOGGLE_ACTION (action), visible);
/* Focus the image */
if (!visible && window->priv->image != NULL)
gtk_widget_grab_focus (window->priv->view);
}
static void
eom_window_sidebar_page_added (EomSidebar *sidebar,
GtkWidget *main_widget,
EomWindow *window)
{
if (eom_sidebar_get_n_pages (sidebar) == 1) {
GtkAction *action;
gboolean show;
action = gtk_action_group_get_action (window->priv->actions_window,
"ViewSidebar");
gtk_action_set_sensitive (action, TRUE);
show = gtk_toggle_action_get_active (GTK_TOGGLE_ACTION (action));
if (show)
gtk_widget_show (GTK_WIDGET (sidebar));
}
}
static void
eom_window_sidebar_page_removed (EomSidebar *sidebar,
GtkWidget *main_widget,
EomWindow *window)
{
if (eom_sidebar_is_empty (sidebar)) {
GtkAction *action;
gtk_widget_hide (GTK_WIDGET (sidebar));
action = gtk_action_group_get_action (window->priv->actions_window,
"ViewSidebar");
gtk_action_set_sensitive (action, FALSE);
}
}
static void
eom_window_finish_saving (EomWindow *window)
{
EomWindowPrivate *priv = window->priv;
gtk_widget_set_sensitive (GTK_WIDGET (window), FALSE);
do {
gtk_main_iteration ();
} while (priv->save_job != NULL);
}
static GAppInfo *
get_appinfo_for_editor (EomWindow *window)
{
/* We want this function to always return the same thing, not
* just for performance reasons, but because if someone edits
* GConf while eom is running, the application could get into an
* inconsistent state. If the editor exists once, it gets added
* to the "available" list of the EggToolbarsModel (for which
* there is no API to remove it). If later the editor no longer
* existed when constructing a new window, we'd be unable to
* construct a GtkAction for the editor for that window, causing
* assertion failures when viewing the "Edit Toolbars" dialog
* (item is available, but can't find the GtkAction for it).
*
* By ensuring we keep the GAppInfo around, we avoid the
* possibility of that situation occuring.
*/
static GDesktopAppInfo *app_info = NULL;
static gboolean initialised;
if (!initialised) {
gchar *editor;
editor = g_settings_get_string (window->priv->ui_settings,
EOM_CONF_UI_EXTERNAL_EDITOR);
if (editor != NULL) {
app_info = g_desktop_app_info_new (editor);
}
initialised = TRUE;
g_free (editor);
}
return (GAppInfo *) app_info;
}
static void
eom_window_open_editor (GtkAction *action,
EomWindow *window)
{
GdkAppLaunchContext *context;
GAppInfo *app_info;
GList files;
app_info = get_appinfo_for_editor (window);
if (app_info == NULL)
return;
#if GTK_CHECK_VERSION (3, 0, 0)
context = gdk_display_get_app_launch_context (
gtk_widget_get_display (GTK_WIDGET (window)));
#else
context = gdk_app_launch_context_new ();
#endif
gdk_app_launch_context_set_screen (context,
gtk_widget_get_screen (GTK_WIDGET (window)));
gdk_app_launch_context_set_icon (context,
g_app_info_get_icon (app_info));
gdk_app_launch_context_set_timestamp (context,
gtk_get_current_event_time ());
{
GList f = { eom_image_get_file (window->priv->image) };
files = f;
}
g_app_info_launch (app_info, &files,
G_APP_LAUNCH_CONTEXT (context), NULL);
g_object_unref (files.data);
g_object_unref (context);
}
static void
eom_window_add_open_editor_action (EomWindow *window)
{
EggToolbarsModel *model;
GAppInfo *app_info;
GtkAction *action;
gchar *tooltip;
app_info = get_appinfo_for_editor (window);
if (app_info == NULL)
return;
model = eom_application_get_toolbars_model (EOM_APP);
egg_toolbars_model_set_name_flags (model, "OpenEditor",
EGG_TB_MODEL_NAME_KNOWN);
tooltip = g_strdup_printf (_("Edit the current image using %s"),
g_app_info_get_name (app_info));
action = gtk_action_new ("OpenEditor", _("Edit Image"), tooltip, NULL);
gtk_action_set_gicon (action, g_app_info_get_icon (app_info));
gtk_action_set_is_important (action, TRUE);
g_signal_connect (action, "activate",
G_CALLBACK (eom_window_open_editor), window);
gtk_action_group_add_action (window->priv->actions_image, action);
g_object_unref (action);
g_free (tooltip);
}
static void
eom_window_construct_ui (EomWindow *window)
{
EomWindowPrivate *priv;
GError *error = NULL;
GtkWidget *menubar;
GtkWidget *thumb_popup;
GtkWidget *view_popup;
GtkWidget *hpaned;
GtkWidget *menuitem;
g_return_if_fail (EOM_IS_WINDOW (window));
priv = window->priv;
priv->box = gtk_vbox_new (FALSE, 0);
gtk_container_add (GTK_CONTAINER (window), priv->box);
gtk_widget_show (priv->box);
priv->ui_mgr = gtk_ui_manager_new ();
priv->actions_window = gtk_action_group_new ("MenuActionsWindow");
gtk_action_group_set_translation_domain (priv->actions_window,
GETTEXT_PACKAGE);
gtk_action_group_add_actions (priv->actions_window,
action_entries_window,
G_N_ELEMENTS (action_entries_window),
window);
gtk_action_group_add_toggle_actions (priv->actions_window,
toggle_entries_window,
G_N_ELEMENTS (toggle_entries_window),
window);
gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_window, 0);
priv->actions_image = gtk_action_group_new ("MenuActionsImage");
gtk_action_group_set_translation_domain (priv->actions_image,
GETTEXT_PACKAGE);
gtk_action_group_add_actions (priv->actions_image,
action_entries_image,
G_N_ELEMENTS (action_entries_image),
window);
eom_window_add_open_editor_action (window);
gtk_action_group_add_toggle_actions (priv->actions_image,
toggle_entries_image,
G_N_ELEMENTS (toggle_entries_image),
window);
gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_image, 0);
priv->actions_collection = gtk_action_group_new ("MenuActionsCollection");
gtk_action_group_set_translation_domain (priv->actions_collection,
GETTEXT_PACKAGE);
gtk_action_group_add_actions (priv->actions_collection,
action_entries_collection,
G_N_ELEMENTS (action_entries_collection),
window);
gtk_action_group_add_toggle_actions (priv->actions_collection,
toggle_entries_collection,
G_N_ELEMENTS (toggle_entries_collection),
window);
set_action_properties (priv->actions_window,
priv->actions_image,
priv->actions_collection);
gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_collection, 0);
if (!gtk_ui_manager_add_ui_from_file (priv->ui_mgr,
EOM_DATA_DIR"/eom-ui.xml",
&error)) {
g_warning ("building menus failed: %s", error->message);
g_error_free (error);
}
g_signal_connect (priv->ui_mgr, "connect_proxy",
G_CALLBACK (connect_proxy_cb), window);
g_signal_connect (priv->ui_mgr, "disconnect_proxy",
G_CALLBACK (disconnect_proxy_cb), window);
menubar = gtk_ui_manager_get_widget (priv->ui_mgr, "/MainMenu");
g_assert (GTK_IS_WIDGET (menubar));
gtk_box_pack_start (GTK_BOX (priv->box), menubar, FALSE, FALSE, 0);
gtk_widget_show (menubar);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr,
"/MainMenu/Edit/EditFlipHorizontal");
gtk_image_menu_item_set_always_show_image (
GTK_IMAGE_MENU_ITEM (menuitem), TRUE);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr,
"/MainMenu/Edit/EditFlipVertical");
gtk_image_menu_item_set_always_show_image (
GTK_IMAGE_MENU_ITEM (menuitem), TRUE);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr,
"/MainMenu/Edit/EditRotate90");
gtk_image_menu_item_set_always_show_image (
GTK_IMAGE_MENU_ITEM (menuitem), TRUE);
menuitem = gtk_ui_manager_get_widget (priv->ui_mgr,
"/MainMenu/Edit/EditRotate270");
gtk_image_menu_item_set_always_show_image (
GTK_IMAGE_MENU_ITEM (menuitem), TRUE);
priv->toolbar = GTK_WIDGET
(g_object_new (EGG_TYPE_EDITABLE_TOOLBAR,
"ui-manager", priv->ui_mgr,
"model", eom_application_get_toolbars_model (EOM_APP),
NULL));
#if GTK_CHECK_VERSION (3, 0, 2)
gtk_style_context_add_class (gtk_widget_get_style_context (GTK_WIDGET (priv->toolbar)),
GTK_STYLE_CLASS_PRIMARY_TOOLBAR);
#endif
egg_editable_toolbar_show (EGG_EDITABLE_TOOLBAR (priv->toolbar),
"Toolbar");
gtk_box_pack_start (GTK_BOX (priv->box),
priv->toolbar,
FALSE,
FALSE,
0);
gtk_widget_show (priv->toolbar);
gtk_window_add_accel_group (GTK_WINDOW (window),
gtk_ui_manager_get_accel_group (priv->ui_mgr));
priv->actions_recent = gtk_action_group_new ("RecentFilesActions");
gtk_action_group_set_translation_domain (priv->actions_recent,
GETTEXT_PACKAGE);
g_signal_connect (gtk_recent_manager_get_default (), "changed",
G_CALLBACK (eom_window_recent_manager_changed_cb),
window);
eom_window_update_recent_files_menu (window);
gtk_ui_manager_insert_action_group (priv->ui_mgr, priv->actions_recent, 0);
priv->cbox = gtk_vbox_new (FALSE, 0);
gtk_box_pack_start (GTK_BOX (priv->box), priv->cbox, TRUE, TRUE, 0);
gtk_widget_show (priv->cbox);
priv->statusbar = eom_statusbar_new ();
gtk_box_pack_end (GTK_BOX (priv->box),
GTK_WIDGET (priv->statusbar),
FALSE, FALSE, 0);
gtk_widget_show (priv->statusbar);
priv->image_info_message_cid =
gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar),
"image_info_message");
priv->tip_message_cid =
gtk_statusbar_get_context_id (GTK_STATUSBAR (priv->statusbar),
"tip_message");
priv->layout = gtk_vbox_new (FALSE, 2);
#if GTK_CHECK_VERSION (3, 2, 0)
hpaned = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL);
#else
hpaned = gtk_hpaned_new ();
#endif
priv->sidebar = eom_sidebar_new ();
/* The sidebar shouldn't be shown automatically on show_all(),
but only when the user actually wants it. */
gtk_widget_set_no_show_all (priv->sidebar, TRUE);
gtk_widget_set_size_request (priv->sidebar, 210, -1);
g_signal_connect_after (priv->sidebar,
"show",
G_CALLBACK (eom_window_sidebar_visibility_changed),
window);
g_signal_connect_after (priv->sidebar,
"hide",
G_CALLBACK (eom_window_sidebar_visibility_changed),
window);
g_signal_connect_after (priv->sidebar,
"page-added",
G_CALLBACK (eom_window_sidebar_page_added),
window);
g_signal_connect_after (priv->sidebar,
"page-removed",
G_CALLBACK (eom_window_sidebar_page_removed),
window);
priv->view = eom_scroll_view_new ();
gtk_widget_set_size_request (GTK_WIDGET (priv->view), 100, 100);
g_signal_connect (G_OBJECT (priv->view),
"zoom_changed",
G_CALLBACK (view_zoom_changed_cb),
window);
g_settings_bind (priv->view_settings, EOM_CONF_VIEW_SCROLL_WHEEL_ZOOM,
priv->view, "scrollwheel-zoom", G_SETTINGS_BIND_GET);
g_settings_bind (priv->view_settings, EOM_CONF_VIEW_ZOOM_MULTIPLIER,
priv->view, "zoom-multiplier", G_SETTINGS_BIND_GET);
view_popup = gtk_ui_manager_get_widget (priv->ui_mgr, "/ViewPopup");
eom_scroll_view_set_popup (EOM_SCROLL_VIEW (priv->view),
GTK_MENU (view_popup));
gtk_paned_pack1 (GTK_PANED (hpaned),
priv->sidebar,
FALSE,
FALSE);
gtk_paned_pack2 (GTK_PANED (hpaned),
priv->view,
TRUE,
FALSE);
gtk_widget_show_all (hpaned);
gtk_box_pack_start (GTK_BOX (priv->layout), hpaned, TRUE, TRUE, 0);
priv->thumbview = g_object_ref (eom_thumb_view_new ());
/* giving shape to the view */
gtk_icon_view_set_margin (GTK_ICON_VIEW (priv->thumbview), 4);
gtk_icon_view_set_row_spacing (GTK_ICON_VIEW (priv->thumbview), 0);
g_signal_connect (G_OBJECT (priv->thumbview), "selection_changed",
G_CALLBACK (handle_image_selection_changed_cb), window);
priv->nav = eom_thumb_nav_new (priv->thumbview,
EOM_THUMB_NAV_MODE_ONE_ROW,
g_settings_get_boolean (priv->ui_settings,
EOM_CONF_UI_SCROLL_BUTTONS));
// Bind the scroll buttons to their GSettings key
g_settings_bind (priv->ui_settings, EOM_CONF_UI_SCROLL_BUTTONS,
priv->nav, "show-buttons", G_SETTINGS_BIND_GET);
thumb_popup = gtk_ui_manager_get_widget (priv->ui_mgr, "/ThumbnailPopup");
eom_thumb_view_set_thumbnail_popup (EOM_THUMB_VIEW (priv->thumbview),
GTK_MENU (thumb_popup));
gtk_box_pack_start (GTK_BOX (priv->layout), priv->nav, FALSE, FALSE, 0);
gtk_box_pack_end (GTK_BOX (priv->cbox), priv->layout, TRUE, TRUE, 0);
eom_window_can_save_changed_cb (priv->lockdown_settings,
EOM_CONF_LOCKDOWN_CAN_SAVE,
window);
g_settings_bind (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION_POSITION,
window, "collection-position", G_SETTINGS_BIND_GET);
g_settings_bind (priv->ui_settings, EOM_CONF_UI_IMAGE_COLLECTION_RESIZABLE,
window, "collection-resizable", G_SETTINGS_BIND_GET);
if ((priv->flags & EOM_STARTUP_FULLSCREEN) ||
(priv->flags & EOM_STARTUP_SLIDE_SHOW)) {
eom_window_run_fullscreen (window, (priv->flags & EOM_STARTUP_SLIDE_SHOW));
} else {
priv->mode = EOM_WINDOW_MODE_NORMAL;
update_ui_visibility (window);
}
eom_window_set_drag_dest (window);
}
static void
eom_window_init (EomWindow *window)
{
GdkGeometry hints;
GdkScreen *screen;
EomWindowPrivate *priv;
eom_debug (DEBUG_WINDOW);
hints.min_width = EOM_WINDOW_MIN_WIDTH;
hints.min_height = EOM_WINDOW_MIN_HEIGHT;
screen = gtk_widget_get_screen (GTK_WIDGET (window));
priv = window->priv = EOM_WINDOW_GET_PRIVATE (window);
priv->view_settings = g_settings_new (EOM_CONF_VIEW);
priv->ui_settings = g_settings_new (EOM_CONF_UI);
priv->fullscreen_settings = g_settings_new (EOM_CONF_FULLSCREEN);
priv->lockdown_settings = g_settings_new (EOM_CONF_LOCKDOWN_SCHEMA);
g_signal_connect (priv->lockdown_settings,
"changed::" EOM_CONF_LOCKDOWN_CAN_SAVE,
G_CALLBACK (eom_window_can_save_changed_cb),
window);
window->priv->store = NULL;
window->priv->image = NULL;
window->priv->fullscreen_popup = NULL;
window->priv->fullscreen_timeout_source = NULL;
window->priv->slideshow_random = FALSE;
window->priv->slideshow_loop = FALSE;
window->priv->slideshow_switch_timeout = 0;
window->priv->slideshow_switch_source = NULL;
gtk_window_set_geometry_hints (GTK_WINDOW (window),
GTK_WIDGET (window),
&hints,
GDK_HINT_MIN_SIZE);
gtk_window_set_default_size (GTK_WINDOW (window),
EOM_WINDOW_DEFAULT_WIDTH,
EOM_WINDOW_DEFAULT_HEIGHT);
gtk_window_set_position (GTK_WINDOW (window), GTK_WIN_POS_CENTER);
window->priv->mode = EOM_WINDOW_MODE_UNKNOWN;
window->priv->status = EOM_WINDOW_STATUS_UNKNOWN;
#ifdef HAVE_LCMS
window->priv->display_profile =
eom_window_get_display_profile (screen);
#endif
window->priv->recent_menu_id = 0;
window->priv->collection_position = 0;
window->priv->collection_resizable = FALSE;
window->priv->save_disabled = FALSE;
window->priv->page_setup = NULL;
}
static void
eom_window_dispose (GObject *object)
{
EomWindow *window;
EomWindowPrivate *priv;
g_return_if_fail (object != NULL);
g_return_if_fail (EOM_IS_WINDOW (object));
eom_debug (DEBUG_WINDOW);
window = EOM_WINDOW (object);
priv = window->priv;
if (priv->page_setup != NULL) {
g_object_unref (priv->page_setup);
priv->page_setup = NULL;
}
if (priv->thumbview)
{
/* Disconnect so we don't get any unwanted callbacks
* when the thumb view is disposed. */
g_signal_handlers_disconnect_by_func (priv->thumbview,
G_CALLBACK (handle_image_selection_changed_cb),
window);
g_clear_object (&priv->thumbview);
}
eom_plugin_engine_garbage_collect ();
if (priv->store != NULL) {
g_signal_handlers_disconnect_by_func (priv->store,
eom_window_list_store_image_added,
window);
g_signal_handlers_disconnect_by_func (priv->store,
eom_window_list_store_image_removed,
window);
g_object_unref (priv->store);
priv->store = NULL;
}
if (priv->image != NULL) {
g_signal_handlers_disconnect_by_func (priv->image,
image_thumb_changed_cb,
window);
g_signal_handlers_disconnect_by_func (priv->image,
image_file_changed_cb,
window);
g_object_unref (priv->image);
priv->image = NULL;
}
if (priv->actions_window != NULL) {
g_object_unref (priv->actions_window);
priv->actions_window = NULL;
}
if (priv->actions_image != NULL) {
g_object_unref (priv->actions_image);
priv->actions_image = NULL;
}
if (priv->actions_collection != NULL) {
g_object_unref (priv->actions_collection);
priv->actions_collection = NULL;
}
if (priv->actions_recent != NULL) {
g_object_unref (priv->actions_recent);
priv->actions_recent = NULL;
}
if (priv->actions_open_with != NULL) {
g_object_unref (priv->actions_open_with);
priv->actions_open_with = NULL;
}
fullscreen_clear_timeout (window);
if (window->priv->fullscreen_popup != NULL) {
gtk_widget_destroy (priv->fullscreen_popup);
priv->fullscreen_popup = NULL;
}
slideshow_clear_timeout (window);
g_signal_handlers_disconnect_by_func (gtk_recent_manager_get_default (),
G_CALLBACK (eom_window_recent_manager_changed_cb),
window);
priv->recent_menu_id = 0;
eom_window_clear_load_job (window);
eom_window_clear_transform_job (window);
if (priv->view_settings) {
g_object_unref (priv->view_settings);
priv->view_settings = NULL;
}
if (priv->ui_settings) {
g_object_unref (priv->ui_settings);
priv->ui_settings = NULL;
}
if (priv->fullscreen_settings) {
g_object_unref (priv->fullscreen_settings);
priv->fullscreen_settings = NULL;
}
if (priv->lockdown_settings) {
g_object_unref (priv->lockdown_settings);
priv->lockdown_settings = NULL;
}
if (priv->file_list != NULL) {
g_slist_foreach (priv->file_list, (GFunc) g_object_unref, NULL);
g_slist_free (priv->file_list);
priv->file_list = NULL;
}
#ifdef HAVE_LCMS
if (priv->display_profile != NULL) {
cmsCloseProfile (priv->display_profile);
priv->display_profile = NULL;
}
#endif
if (priv->last_save_as_folder != NULL) {
g_object_unref (priv->last_save_as_folder);
priv->last_save_as_folder = NULL;
}
eom_plugin_engine_garbage_collect ();
G_OBJECT_CLASS (eom_window_parent_class)->dispose (object);
}
static void
eom_window_finalize (GObject *object)
{
GList *windows = eom_application_get_windows (EOM_APP);
g_return_if_fail (EOM_IS_WINDOW (object));
eom_debug (DEBUG_WINDOW);
if (windows == NULL) {
eom_application_shutdown (EOM_APP);
} else {
g_list_free (windows);
}
G_OBJECT_CLASS (eom_window_parent_class)->finalize (object);
}
static gint
eom_window_delete (GtkWidget *widget, GdkEventAny *event)
{
EomWindow *window;
EomWindowPrivate *priv;
g_return_val_if_fail (EOM_IS_WINDOW (widget), FALSE);
window = EOM_WINDOW (widget);
priv = window->priv;
if (priv->save_job != NULL) {
eom_window_finish_saving (window);
}
if (eom_window_unsaved_images_confirm (window)) {
return TRUE;
}
gtk_widget_destroy (widget);
return TRUE;
}
static gint
eom_window_key_press (GtkWidget *widget, GdkEventKey *event)
{
GtkContainer *tbcontainer = GTK_CONTAINER ((EOM_WINDOW (widget)->priv->toolbar));
gint result = FALSE;
gboolean handle_selection = FALSE;
switch (event->keyval) {
case GDK_KEY_space:
if (event->state & GDK_CONTROL_MASK) {
handle_selection = TRUE;
break;
}
case GDK_KEY_Return:
if (gtk_container_get_focus_child (tbcontainer) == NULL) {
/* Image properties dialog case */
if (event->state & GDK_MOD1_MASK) {
result = FALSE;
break;
}
if (event->state & GDK_SHIFT_MASK) {
eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget));
} else {
eom_window_cmd_go_next (NULL, EOM_WINDOW (widget));
}
result = TRUE;
}
break;
case GDK_KEY_p:
case GDK_KEY_P:
if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_FULLSCREEN || EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) {
gboolean slideshow;
slideshow = EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW;
eom_window_run_fullscreen (EOM_WINDOW (widget), !slideshow);
}
break;
case GDK_KEY_Q:
case GDK_KEY_q:
case GDK_KEY_Escape:
if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_FULLSCREEN) {
eom_window_stop_fullscreen (EOM_WINDOW (widget), FALSE);
} else if (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW) {
eom_window_stop_fullscreen (EOM_WINDOW (widget), TRUE);
} else {
eom_window_cmd_close_window (NULL, EOM_WINDOW (widget));
return TRUE;
}
break;
case GDK_KEY_Left:
if (event->state & GDK_MOD1_MASK) {
/* Alt+Left moves to previous image */
if (is_rtl) { /* move to next in RTL mode */
eom_window_cmd_go_next (NULL, EOM_WINDOW (widget));
} else {
eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget));
}
result = TRUE;
break;
} /* else fall-trough is intended */
case GDK_KEY_Up:
if (eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) {
/* break to let scrollview handle the key */
break;
}
if (gtk_container_get_focus_child (tbcontainer) != NULL)
break;
if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) {
if (is_rtl && event->keyval == GDK_KEY_Left) {
/* handle RTL fall-through,
* need to behave like GDK_Down then */
eom_window_cmd_go_next (NULL,
EOM_WINDOW (widget));
} else {
eom_window_cmd_go_prev (NULL,
EOM_WINDOW (widget));
}
result = TRUE;
break;
}
case GDK_KEY_Right:
if (event->state & GDK_MOD1_MASK) {
/* Alt+Right moves to next image */
if (is_rtl) { /* move to previous in RTL mode */
eom_window_cmd_go_prev (NULL, EOM_WINDOW (widget));
} else {
eom_window_cmd_go_next (NULL, EOM_WINDOW (widget));
}
result = TRUE;
break;
} /* else fall-trough is intended */
case GDK_KEY_Down:
if (eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) {
/* break to let scrollview handle the key */
break;
}
if (gtk_container_get_focus_child (tbcontainer) != NULL)
break;
if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) {
if (is_rtl && event->keyval == GDK_KEY_Right) {
/* handle RTL fall-through,
* need to behave like GDK_Up then */
eom_window_cmd_go_prev (NULL,
EOM_WINDOW (widget));
} else {
eom_window_cmd_go_next (NULL,
EOM_WINDOW (widget));
}
result = TRUE;
break;
}
case GDK_KEY_Page_Up:
if (!eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) {
if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) {
/* If the iconview is not visible skip to the
* previous image manually as it won't handle
* the keypress then. */
eom_window_cmd_go_prev (NULL,
EOM_WINDOW (widget));
result = TRUE;
} else
handle_selection = TRUE;
}
break;
case GDK_KEY_Page_Down:
if (!eom_scroll_view_scrollbars_visible (EOM_SCROLL_VIEW (EOM_WINDOW (widget)->priv->view))) {
if (!gtk_widget_get_visible (EOM_WINDOW (widget)->priv->nav)) {
/* If the iconview is not visible skip to the
* next image manually as it won't handle
* the keypress then. */
eom_window_cmd_go_next (NULL,
EOM_WINDOW (widget));
result = TRUE;
} else
handle_selection = TRUE;
}
break;
}
/* Update slideshow timeout */
if (result && (EOM_WINDOW (widget)->priv->mode == EOM_WINDOW_MODE_SLIDESHOW)) {
slideshow_set_timeout (EOM_WINDOW (widget));
}
if (handle_selection == TRUE && result == FALSE) {
gtk_widget_grab_focus (GTK_WIDGET (EOM_WINDOW (widget)->priv->thumbview));
result = gtk_widget_event (GTK_WIDGET (EOM_WINDOW (widget)->priv->thumbview),
(GdkEvent *) event);
}
/* If the focus is not in the toolbar and we still haven't handled the
event, give the scrollview a chance to do it. */
if (!gtk_container_get_focus_child (tbcontainer) && result == FALSE &&
gtk_widget_get_realized (GTK_WIDGET (EOM_WINDOW (widget)->priv->view))) {
result = gtk_widget_event (GTK_WIDGET (EOM_WINDOW (widget)->priv->view),
(GdkEvent *) event);
}
if (result == FALSE && GTK_WIDGET_CLASS (eom_window_parent_class)->key_press_event) {
result = (* GTK_WIDGET_CLASS (eom_window_parent_class)->key_press_event) (widget, event);
}
return result;
}
static gint
eom_window_button_press (GtkWidget *widget, GdkEventButton *event)
{
EomWindow *window = EOM_WINDOW (widget);
gint result = FALSE;
if (event->type == GDK_BUTTON_PRESS) {
switch (event->button) {
case 6:
eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview),
EOM_THUMB_VIEW_SELECT_LEFT);
result = TRUE;
break;
case 7:
eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview),
EOM_THUMB_VIEW_SELECT_RIGHT);
result = TRUE;
break;
}
}
if (result == FALSE && GTK_WIDGET_CLASS (eom_window_parent_class)->button_press_event) {
result = (* GTK_WIDGET_CLASS (eom_window_parent_class)->button_press_event) (widget, event);
}
return result;
}
static gboolean
eom_window_focus_out_event (GtkWidget *widget, GdkEventFocus *event)
{
EomWindow *window = EOM_WINDOW (widget);
EomWindowPrivate *priv = window->priv;
gboolean fullscreen;
eom_debug (DEBUG_WINDOW);
fullscreen = priv->mode == EOM_WINDOW_MODE_FULLSCREEN ||
priv->mode == EOM_WINDOW_MODE_SLIDESHOW;
if (fullscreen) {
gtk_widget_hide (priv->fullscreen_popup);
}
return GTK_WIDGET_CLASS (eom_window_parent_class)->focus_out_event (widget, event);
}
static void
eom_window_set_property (GObject *object,
guint property_id,
const GValue *value,
GParamSpec *pspec)
{
EomWindow *window;
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (object));
window = EOM_WINDOW (object);
priv = window->priv;
switch (property_id) {
case PROP_COLLECTION_POS:
eom_window_set_collection_mode (window, g_value_get_enum (value),
priv->collection_resizable);
break;
case PROP_COLLECTION_RESIZABLE:
eom_window_set_collection_mode (window, priv->collection_position,
g_value_get_boolean (value));
break;
case PROP_STARTUP_FLAGS:
priv->flags = g_value_get_flags (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static void
eom_window_get_property (GObject *object,
guint property_id,
GValue *value,
GParamSpec *pspec)
{
EomWindow *window;
EomWindowPrivate *priv;
g_return_if_fail (EOM_IS_WINDOW (object));
window = EOM_WINDOW (object);
priv = window->priv;
switch (property_id) {
case PROP_COLLECTION_POS:
g_value_set_enum (value, priv->collection_position);
break;
case PROP_COLLECTION_RESIZABLE:
g_value_set_boolean (value, priv->collection_resizable);
break;
case PROP_STARTUP_FLAGS:
g_value_set_flags (value, priv->flags);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, property_id, pspec);
}
}
static GObject *
eom_window_constructor (GType type,
guint n_construct_properties,
GObjectConstructParam *construct_params)
{
GObject *object;
object = G_OBJECT_CLASS (eom_window_parent_class)->constructor
(type, n_construct_properties, construct_params);
eom_window_construct_ui (EOM_WINDOW (object));
eom_plugin_engine_update_plugins_ui (EOM_WINDOW (object), TRUE);
return object;
}
static void
eom_window_class_init (EomWindowClass *class)
{
GObjectClass *g_object_class = (GObjectClass *) class;
GtkWidgetClass *widget_class = (GtkWidgetClass *) class;
g_object_class->constructor = eom_window_constructor;
g_object_class->dispose = eom_window_dispose;
g_object_class->finalize = eom_window_finalize;
g_object_class->set_property = eom_window_set_property;
g_object_class->get_property = eom_window_get_property;
widget_class->delete_event = eom_window_delete;
widget_class->key_press_event = eom_window_key_press;
widget_class->button_press_event = eom_window_button_press;
widget_class->drag_data_received = eom_window_drag_data_received;
widget_class->focus_out_event = eom_window_focus_out_event;
/**
* EomWindow:collection-position:
*
* Determines the position of the image collection in the window
* relative to the image.
*/
g_object_class_install_property (
g_object_class, PROP_COLLECTION_POS,
g_param_spec_enum ("collection-position", NULL, NULL,
EOM_TYPE_WINDOW_COLLECTION_POS,
EOM_WINDOW_COLLECTION_POS_BOTTOM,
G_PARAM_READWRITE | G_PARAM_STATIC_NAME));
/**
* EomWindow:collection-resizable:
*
* If %TRUE the collection will be resizable by the user otherwise it will be
* in single column/row mode.
*/
g_object_class_install_property (
g_object_class, PROP_COLLECTION_RESIZABLE,
g_param_spec_boolean ("collection-resizable", NULL, NULL, FALSE,
G_PARAM_READWRITE | G_PARAM_STATIC_NAME));
/**
* EomWindow:startup-flags:
*
* A bitwise OR of #EomStartupFlags elements, indicating how the window
* should behave upon creation.
*/
g_object_class_install_property (g_object_class,
PROP_STARTUP_FLAGS,
g_param_spec_flags ("startup-flags",
NULL,
NULL,
EOM_TYPE_STARTUP_FLAGS,
0,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY));
/**
* EomWindow::prepared:
* @window: the object which received the signal.
*
* The #EomWindow::prepared signal is emitted when the @window is ready
* to be shown.
*/
signals [SIGNAL_PREPARED] =
g_signal_new ("prepared",
EOM_TYPE_WINDOW,
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (EomWindowClass, prepared),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
g_type_class_add_private (g_object_class, sizeof (EomWindowPrivate));
}
/**
* eom_window_new:
* @flags: the initialization parameters for the new window.
*
*
* Creates a new and empty #EomWindow. Use @flags to indicate
* if the window should be initialized fullscreen, in slideshow mode,
* and/or without the thumbnails collection visible. See #EomStartupFlags.
*
* Returns: a newly created #EomWindow.
**/
GtkWidget*
eom_window_new (EomStartupFlags flags)
{
EomWindow *window;
eom_debug (DEBUG_WINDOW);
window = EOM_WINDOW (g_object_new (EOM_TYPE_WINDOW,
"type", GTK_WINDOW_TOPLEVEL,
"startup-flags", flags,
NULL));
return GTK_WIDGET (window);
}
static void
eom_window_list_store_image_added (GtkTreeModel *tree_model,
GtkTreePath *path,
GtkTreeIter *iter,
gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
update_image_pos (window);
update_action_groups_state (window);
}
static void
eom_window_list_store_image_removed (GtkTreeModel *tree_model,
GtkTreePath *path,
gpointer user_data)
{
EomWindow *window = EOM_WINDOW (user_data);
update_image_pos (window);
update_action_groups_state (window);
}
static void
eom_job_model_cb (EomJobModel *job, gpointer data)
{
EomWindow *window;
EomWindowPrivate *priv;
gint n_images;
eom_debug (DEBUG_WINDOW);
#ifdef HAVE_EXIF
int i;
EomImage *image;
#endif
g_return_if_fail (EOM_IS_WINDOW (data));
window = EOM_WINDOW (data);
priv = window->priv;
if (priv->store != NULL) {
g_object_unref (priv->store);
priv->store = NULL;
}
priv->store = g_object_ref (job->store);
n_images = eom_list_store_length (EOM_LIST_STORE (priv->store));
#ifdef HAVE_EXIF
if (g_settings_get_boolean (priv->view_settings, EOM_CONF_VIEW_AUTOROTATE)) {
for (i = 0; i < n_images; i++) {
image = eom_list_store_get_image_by_pos (priv->store, i);
eom_image_autorotate (image);
g_object_unref (image);
}
}
#endif
eom_thumb_view_set_model (EOM_THUMB_VIEW (priv->thumbview), priv->store);
g_signal_connect (G_OBJECT (priv->store),
"row-inserted",
G_CALLBACK (eom_window_list_store_image_added),
window);
g_signal_connect (G_OBJECT (priv->store),
"row-deleted",
G_CALLBACK (eom_window_list_store_image_removed),
window);
if (n_images == 0) {
gint n_files;
priv->status = EOM_WINDOW_STATUS_NORMAL;
update_action_groups_state (window);
n_files = g_slist_length (priv->file_list);
if (n_files > 0) {
GtkWidget *message_area;
GFile *file = NULL;
if (n_files == 1) {
file = (GFile *) priv->file_list->data;
}
message_area = eom_no_images_error_message_area_new (file);
eom_window_set_message_area (window, message_area);
gtk_widget_show (message_area);
}
g_signal_emit (window, signals[SIGNAL_PREPARED], 0);
}
}
/**
* eom_window_open_file_list:
* @window: An #EomWindow.
* @file_list: (element-type GFile): A %NULL-terminated list of #GFile's.
*
* Opens a list of files, adding them to the collection in @window.
* Files will be checked to be readable and later filtered according
* with eom_list_store_add_files().
**/
void
eom_window_open_file_list (EomWindow *window, GSList *file_list)
{
EomJob *job;
eom_debug (DEBUG_WINDOW);
window->priv->status = EOM_WINDOW_STATUS_INIT;
g_slist_foreach (file_list, (GFunc) g_object_ref, NULL);
window->priv->file_list = file_list;
job = eom_job_model_new (file_list);
g_signal_connect (job,
"finished",
G_CALLBACK (eom_job_model_cb),
window);
eom_job_queue_add_job (job);
g_object_unref (job);
}
/**
* eom_window_get_ui_manager:
* @window: An #EomWindow.
*
* Gets the #GtkUIManager that describes the UI of @window.
*
* Returns: (transfer none): A #GtkUIManager.
**/
GtkUIManager *
eom_window_get_ui_manager (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->ui_mgr;
}
/**
* eom_window_get_mode:
* @window: An #EomWindow.
*
* Gets the mode of @window. See #EomWindowMode for details.
*
* Returns: An #EomWindowMode.
**/
EomWindowMode
eom_window_get_mode (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), EOM_WINDOW_MODE_UNKNOWN);
return window->priv->mode;
}
/**
* eom_window_set_mode:
* @window: an #EomWindow.
* @mode: an #EomWindowMode value.
*
* Changes the mode of @window to normal, fullscreen, or slideshow.
* See #EomWindowMode for details.
**/
void
eom_window_set_mode (EomWindow *window, EomWindowMode mode)
{
g_return_if_fail (EOM_IS_WINDOW (window));
if (window->priv->mode == mode)
return;
switch (mode) {
case EOM_WINDOW_MODE_NORMAL:
eom_window_stop_fullscreen (window,
window->priv->mode == EOM_WINDOW_MODE_SLIDESHOW);
break;
case EOM_WINDOW_MODE_FULLSCREEN:
eom_window_run_fullscreen (window, FALSE);
break;
case EOM_WINDOW_MODE_SLIDESHOW:
eom_window_run_fullscreen (window, TRUE);
break;
case EOM_WINDOW_MODE_UNKNOWN:
break;
}
}
/**
* eom_window_get_store:
* @window: An #EomWindow.
*
* Gets the #EomListStore that contains the images in the collection
* of @window.
*
* Returns: (transfer none): an #EomListStore.
**/
EomListStore *
eom_window_get_store (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return EOM_LIST_STORE (window->priv->store);
}
/**
* eom_window_get_view:
* @window: An #EomWindow.
*
* Gets the #EomScrollView in the window.
*
* Returns: (transfer none): the #EomScrollView.
**/
GtkWidget *
eom_window_get_view (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->view;
}
/**
* eom_window_get_sidebar:
* @window: An #EomWindow.
*
* Gets the sidebar widget of @window.
*
* Returns: (transfer none): the #EomSidebar.
**/
GtkWidget *
eom_window_get_sidebar (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->sidebar;
}
/**
* eom_window_get_thumb_view:
* @window: an #EomWindow.
*
* Gets the thumbnails view in @window.
*
* Returns: (transfer none): an #EomThumbView.
**/
GtkWidget *
eom_window_get_thumb_view (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->thumbview;
}
/**
* eom_window_get_thumb_nav:
* @window: an #EomWindow.
*
* Gets the thumbnails navigation pane in @window.
*
* Returns: (transfer none): an #EomThumbNav.
**/
GtkWidget *
eom_window_get_thumb_nav (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->nav;
}
/**
* eom_window_get_statusbar:
* @window: an #EomWindow.
*
* Gets the statusbar in @window.
*
* Returns: (transfer none): a #EomStatusBar.
**/
GtkWidget *
eom_window_get_statusbar (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->statusbar;
}
/**
* eom_window_get_image:
* @window: an #EomWindow.
*
* Gets the image currently displayed in @window or %NULL if
* no image is being displayed.
*
* Returns: (transfer none): an #EomImage.
**/
EomImage *
eom_window_get_image (EomWindow *window)
{
g_return_val_if_fail (EOM_IS_WINDOW (window), NULL);
return window->priv->image;
}
/**
* eom_window_is_empty:
* @window: an #EomWindow.
*
* Tells whether @window is currently empty or not.
*
* Returns: %TRUE if @window has no images, %FALSE otherwise.
**/
gboolean
eom_window_is_empty (EomWindow *window)
{
EomWindowPrivate *priv;
gboolean empty = TRUE;
eom_debug (DEBUG_WINDOW);
g_return_val_if_fail (EOM_IS_WINDOW (window), FALSE);
priv = window->priv;
if (priv->store != NULL) {
empty = (eom_list_store_length (EOM_LIST_STORE (priv->store)) == 0);
}
return empty;
}
void
eom_window_reload_image (EomWindow *window)
{
GtkWidget *view;
g_return_if_fail (EOM_IS_WINDOW (window));
if (window->priv->image == NULL)
return;
g_object_unref (window->priv->image);
window->priv->image = NULL;
view = eom_window_get_view (window);
eom_scroll_view_set_image (EOM_SCROLL_VIEW (view), NULL);
eom_thumb_view_select_single (EOM_THUMB_VIEW (window->priv->thumbview),
EOM_THUMB_VIEW_SELECT_CURRENT);
}
| Java |
<html>
<head>
<title>LitKicks: Mexico</title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<meta name="description" content="The beat legacy of Mexico">
<meta name="keywords" content="Mexico,Beat,Kerouac,Road,Kicks,Marijuana,Burroughs,Mexico City,Border">
<BASE HREF="http://www.litkicks.com/BeatPages/">
</head>
<BODY BACKGROUND="" BGCOLOR="#FFFFFF" TEXT="#000000"
LINK="#006F9F" ALINK="#0000FF" VLINK="#009F6F">
<FONT FACE="helvetica, arial">
<H2>Literary Kicks</H2>
<TABLE WIDTH="375" BORDER="0" CELLPADDING="5">
<TR>
<TD WIDTH="75"> </TD>
<TD BGCOLOR="#FFFF2F" WIDTH="180">
<FONT SIZE="-1">
Visit the
<A HREF="http://www.litkicks.com/BeatPages/page.jsp?what=Utterances">general discussion board</A>
or view
<A HREF="http://www.litkicks.com/BeatPages/AllBoards.jsp">list of boards</A>
<BR>
</FONT>
</TD>
</TR>
</TABLE>
<BR>
<CENTER>
<TABLE WIDTH="580" CELLPADDING="6">
<TR><TD BGCOLOR="#FFEECC">
<CENTER>
<FONT COLOR="#002F6F">
<H1>Mexico</H1>
</CENTER>
<FONT FACE="Verdana">
In the autumn of 1947, 25-year-old <A HREF="page.jsp?what=JackKerouac">Jack Kerouac</A> left <A HREF="page.jsp?what=SanFrancisco">San Francisco</A> and headed for Southern California in search of unforeseen adventures. He met a Mexican girl named Bea Franco on a bus and ended up following her to an encampment of Mexican grape- and cotton-pickers, where they briefly contemplated a life together before Kerouac returned home. Kerouac's telling of this poignant episode would become part of the first trip in '<A HREF="page.jsp?what=OnTheRoad">On The Road</A>,' and was published as an excerpt ('The Mexican Girl') in The Paris Review. Kerouac hadn't even reached Mexico yet (he would soon), but the Beat fascination for Mexican culture was already clear.<P>
The Beats didn't have much money, but they craved alternative cultures, and going to Mexico was the cheapest and easiest way to delve into what we now call the Third World. <A HREF="page.jsp?what=WilliamSBurroughs">William S. Burroughs</A> lived in Mexico City for a time, and it was here that he caused the death of his wife while playing with guns. He had to flee Mexico, but later explored South American jungles in search of a drug called Yage, and the letters he wrote to <A HREF="page.jsp?what=AllenGinsberg">Allen Ginsberg</A> during this time have been published as 'The Yage Letters.'<P>
Ginsberg had his own Mexican adventures. The year before he became famous for '<A HREF="page.jsp?what=Howl">Howl</A>,' he went on an archeological expedition to the Mayan ruins of the Yucatan Peninsula, and ended up leading a spontaneous expedition of over fifty villagers to explore a volcano during an earthquake. This episode is typical of Ginsberg's career -- he didn't know exactly what he was doing, but he had the courage to do it, and when people sensed this they named him their leader. <P>
There are more Beat connections to Mexico than I can possibly capture here. Kerouac's novel 'Tristessa' takes place there. <A HREF="page.jsp?what=LawrenceFerlinghetti">Lawrence Ferlinghetti</A> published a travel journal called 'The Mexican Night' in 1962. Timothy Leary's experiments with mind-altering drugs began with his discovery of natural Mexican psychedelics, although Leary soon adopted the use of synthetic psychedelics. Natural Mexican drugs like peyote and mescaline have always been popular, though, and Carlos Casteneda's 'Don Juan' books helped to spread this mystique. <A HREF="page.jsp?what=KenKesey">Ken Kesey</A>, another one who liked to use synthetic psychedelics, was a fugitive from American justice in Mexico during the mid-Sixties. <A HREF="page.jsp?what=NealCassady">Neal Cassady</A> died while trying to walk the railroad tracks between two Mexican villages on a cold night.<P>
The European conquest of Mexico began in 1519, a few decades after Columbus' discovery of the Americas. Several advanced Native American populations such as the Aztecs and Mayans were decimated by Europeans (Cortez's murderous confrontation with Montezuma's grand empire is the subject of Neil Young's excellent song 'Cortez the Killer'). The area was known as New Spain, but the Native American population survived better than in North America, and the current population of Mexico is largely Native American in origin. The nation of Mexico was created in 1821, during the wave of independent uprisings that followed Napoleon's disruption of the European order and his conquest of Spain.<P>
I've been to the Yucatan, and the Mayan ruins there are an amazing experience. I also just can't say enough good things about Mexican food, although I doubt any true Mexican would be very impressed by the California concoctions we Americans refer to as burritos and tacos. <P>
<CENTER><I>-- <A HREF="profile.jsp?who=brooklyn">brooklyn</A> --</I></CENTER>
</FONT>
</TD></TR>
</TABLE>
</CENTER>
<BR>
<CENTER>
<TABLE WIDTH="580" CELLPADDING=0 CELLSPACING=0 BORDER=0>
<TR>
<TD WIDTH="270"> </TD>
<TD WIDTH="230" BGCOLOR="#5F0F3F" ALIGN="CENTER" VALIGN="MIDDLE">
<BR>
<FONT FACE="Verdana" COLOR="#FFFFFF">
Go to <A HREF="page.jsp?what=Beatitude">Beatitude Board</A>
to post responses, corrections, questions or further thoughts
<BR>
</FONT><BR>
</TD>
<TD WIDTH="80"> </TD>
</TR>
</TABLE>
</CENTER>
<BR>
<BR>
<a href="http://www.litkicks.com/">Literary Kicks</a>
</font>
</body>
</html>
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_66) on Tue Dec 08 01:24:03 CST 2015 -->
<title>Uses of Class com.online.lakeshoremarket.representation.order.OrderRequest</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.online.lakeshoremarket.representation.order.OrderRequest";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/online/lakeshoremarket/representation/order/class-use/OrderRequest.html" target="_top">Frames</a></li>
<li><a href="OrderRequest.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.online.lakeshoremarket.representation.order.OrderRequest" class="title">Uses of Class<br>com.online.lakeshoremarket.representation.order.OrderRequest</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#com.online.lakeshoremarket.activity">com.online.lakeshoremarket.activity</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#com.online.lakeshoremarket.resource">com.online.lakeshoremarket.resource</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="com.online.lakeshoremarket.activity">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a> in <a href="../../../../../../com/online/lakeshoremarket/activity/package-summary.html">com.online.lakeshoremarket.activity</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/online/lakeshoremarket/activity/package-summary.html">com.online.lakeshoremarket.activity</a> with parameters of type <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><span class="typeNameLabel">PaymentActivity.</span><code><span class="memberNameLink"><a href="../../../../../../com/online/lakeshoremarket/activity/PaymentActivity.html#buyProduct-com.online.lakeshoremarket.representation.order.OrderRequest-">buyProduct</a></span>(<a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a> orderRequest)</code>
<div class="block">creates a new payment domain for an order representation</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="com.online.lakeshoremarket.resource">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a> in <a href="../../../../../../com/online/lakeshoremarket/resource/package-summary.html">com.online.lakeshoremarket.resource</a></h3>
<table class="useSummary" border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../com/online/lakeshoremarket/resource/package-summary.html">com.online.lakeshoremarket.resource</a> with parameters of type <a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../com/online/lakeshoremarket/representation/generic/GenericResponse.html" title="class in com.online.lakeshoremarket.representation.generic">GenericResponse</a></code></td>
<td class="colLast"><span class="typeNameLabel">PaymentResource.</span><code><span class="memberNameLink"><a href="../../../../../../com/online/lakeshoremarket/resource/PaymentResource.html#buyProduct-com.online.lakeshoremarket.representation.order.OrderRequest-java.lang.String-java.lang.String-">buyProduct</a></span>(<a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">OrderRequest</a> orderRequest,
java.lang.String email,
java.lang.String password)</code>
<div class="block">PUT method request for placing an order</div>
</td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../com/online/lakeshoremarket/representation/order/OrderRequest.html" title="class in com.online.lakeshoremarket.representation.order">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?com/online/lakeshoremarket/representation/order/class-use/OrderRequest.html" target="_top">Frames</a></li>
<li><a href="OrderRequest.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
<?php
namespace Guzzle\Common\Filter;
/**
* Check if the supplied variable is a string
*
* @author Michael Dowling <michael@guzzlephp.org>
*/
class StringFilter extends AbstractFilter
{
/**
* {@inheritdoc}
*/
protected function filterCommand($command)
{
if (!is_string($command)) {
return 'The supplied value is not a string: ' . gettype($command)
. ' supplied';
}
return true;
}
} | Java |
<?php
return array(
'id' => 'jkreativ_page_fssingle_video',
'types' => array('page'),
'title' => 'Jkreativ Fullscreen Single video',
'priority' => 'high',
'template' => array(
array(
'name' => 'video_type',
'type' => 'select',
'label' => 'Video Type',
'default' => 'youtube',
'items' => array(
array(
'value' => 'youtube',
'label' => 'Youtube',
),
array(
'value' => 'vimeo',
'label' => 'Vimeo',
)
)
),
array(
'type' => 'textbox',
'name' => 'youtube_video',
'label' => 'Youtube Video',
'description' => 'url of your youtube url, ex : http://www.youtube.com/watch?v=9B7UcTBJYCA',
'dependency' => array(
'field' => 'video_type',
'function' => 'jeg_heading_type_youtube',
),
),
array(
'type' => 'textbox',
'name' => 'vimeo_video',
'label' => 'Vimeo Video',
'description' => 'url of your vimeo url, ex : http://vimeo.com/71536276',
'dependency' => array(
'field' => 'video_type',
'function' => 'jeg_heading_type_vimeo',
),
),
array(
'type' => 'toggle',
'name' => 'enable_autoplay',
'label' => 'Enable Video Autoplay'
),
),
); | Java |
/*
This file is part of Valgrind, a dynamic binary instrumentation
framework.
Copyright (C) 2004-2012 OpenWorks LLP
info@open-works.net
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.
The GNU General Public License is contained in the file COPYING.
Neither the names of the U.S. Department of Energy nor the
University of California nor the names of its contributors may be
used to endorse or promote products derived from this software
without prior written permission.
*/
#include "libvex_basictypes.h"
#include "libvex_ir.h"
#include "libvex.h"
#include "ir_match.h"
#include "main_util.h"
#include "main_globals.h"
#include "host_generic_regs.h"
#include "host_generic_simd64.h"
#include "host_ppc_defs.h"
#define HRcGPR(__mode64) (__mode64 ? HRcInt64 : HRcInt32)
static IRExpr* unop ( IROp op, IRExpr* a )
{
return IRExpr_Unop(op, a);
}
static IRExpr* mkU32 ( UInt i )
{
return IRExpr_Const(IRConst_U32(i));
}
static IRExpr* bind ( Int binder )
{
return IRExpr_Binder(binder);
}
typedef
struct {
IRTypeEnv* type_env;
HReg* vregmapLo;
HReg* vregmapMedLo;
HReg* vregmapMedHi;
HReg* vregmapHi;
Int n_vregmap;
UInt hwcaps;
Bool mode64;
VexAbiInfo* vbi;
Bool chainingAllowed;
Addr64 max_ga;
HInstrArray* code;
Int vreg_ctr;
IRExpr* previous_rm;
}
ISelEnv;
static HReg lookupIRTemp ( ISelEnv* env, IRTemp tmp )
{
vassert(tmp >= 0);
vassert(tmp < env->n_vregmap);
return env->vregmapLo[tmp];
}
static void lookupIRTempPair ( HReg* vrHI, HReg* vrLO,
ISelEnv* env, IRTemp tmp )
{
vassert(tmp >= 0);
vassert(tmp < env->n_vregmap);
vassert(env->vregmapMedLo[tmp] != INVALID_HREG);
*vrLO = env->vregmapLo[tmp];
*vrHI = env->vregmapMedLo[tmp];
}
static void lookupIRTempQuad ( HReg* vrHi, HReg* vrMedHi, HReg* vrMedLo,
HReg* vrLo, ISelEnv* env, IRTemp tmp )
{
vassert(!env->mode64);
vassert(tmp >= 0);
vassert(tmp < env->n_vregmap);
vassert(env->vregmapMedLo[tmp] != INVALID_HREG);
*vrHi = env->vregmapHi[tmp];
*vrMedHi = env->vregmapMedHi[tmp];
*vrMedLo = env->vregmapMedLo[tmp];
*vrLo = env->vregmapLo[tmp];
}
static void addInstr ( ISelEnv* env, PPCInstr* instr )
{
addHInstr(env->code, instr);
if (vex_traceflags & VEX_TRACE_VCODE) {
ppPPCInstr(instr, env->mode64);
vex_printf("\n");
}
}
static HReg newVRegI ( ISelEnv* env )
{
HReg reg = mkHReg(env->vreg_ctr, HRcGPR(env->mode64),
True);
env->vreg_ctr++;
return reg;
}
static HReg newVRegF ( ISelEnv* env )
{
HReg reg = mkHReg(env->vreg_ctr, HRcFlt64, True);
env->vreg_ctr++;
return reg;
}
static HReg newVRegV ( ISelEnv* env )
{
HReg reg = mkHReg(env->vreg_ctr, HRcVec128, True);
env->vreg_ctr++;
return reg;
}
static HReg iselWordExpr_R_wrk ( ISelEnv* env, IRExpr* e );
static HReg iselWordExpr_R ( ISelEnv* env, IRExpr* e );
static PPCRH* iselWordExpr_RH_wrk ( ISelEnv* env,
Bool syned, IRExpr* e );
static PPCRH* iselWordExpr_RH ( ISelEnv* env,
Bool syned, IRExpr* e );
static PPCRI* iselWordExpr_RI_wrk ( ISelEnv* env, IRExpr* e );
static PPCRI* iselWordExpr_RI ( ISelEnv* env, IRExpr* e );
static PPCRH* iselWordExpr_RH5u_wrk ( ISelEnv* env, IRExpr* e );
static PPCRH* iselWordExpr_RH5u ( ISelEnv* env, IRExpr* e );
static PPCRH* iselWordExpr_RH6u_wrk ( ISelEnv* env, IRExpr* e );
static PPCRH* iselWordExpr_RH6u ( ISelEnv* env, IRExpr* e );
static PPCAMode* iselWordExpr_AMode_wrk ( ISelEnv* env, IRExpr* e, IRType xferTy );
static PPCAMode* iselWordExpr_AMode ( ISelEnv* env, IRExpr* e, IRType xferTy );
static void iselInt128Expr_to_32x4_wrk ( HReg* rHi, HReg* rMedHi,
HReg* rMedLo, HReg* rLo,
ISelEnv* env, IRExpr* e );
static void iselInt128Expr_to_32x4 ( HReg* rHi, HReg* rMedHi,
HReg* rMedLo, HReg* rLo,
ISelEnv* env, IRExpr* e );
static void iselInt64Expr_wrk ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e );
static void iselInt64Expr ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e );
static void iselInt128Expr_wrk ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e );
static void iselInt128Expr ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e );
static PPCCondCode iselCondCode_wrk ( ISelEnv* env, IRExpr* e );
static PPCCondCode iselCondCode ( ISelEnv* env, IRExpr* e );
static HReg iselDblExpr_wrk ( ISelEnv* env, IRExpr* e );
static HReg iselDblExpr ( ISelEnv* env, IRExpr* e );
static HReg iselFltExpr_wrk ( ISelEnv* env, IRExpr* e );
static HReg iselFltExpr ( ISelEnv* env, IRExpr* e );
static HReg iselVecExpr_wrk ( ISelEnv* env, IRExpr* e );
static HReg iselVecExpr ( ISelEnv* env, IRExpr* e );
static HReg iselDfp64Expr_wrk ( ISelEnv* env, IRExpr* e );
static HReg iselDfp64Expr ( ISelEnv* env, IRExpr* e );
static void iselDfp128Expr_wrk ( HReg* rHi, HReg* rLo, ISelEnv* env,
IRExpr* e );
static void iselDfp128Expr ( HReg* rHi, HReg* rLo, ISelEnv* env,
IRExpr* e );
static PPCInstr* mk_iMOVds_RR ( HReg r_dst, HReg r_src )
{
vassert(hregClass(r_dst) == hregClass(r_src));
vassert(hregClass(r_src) == HRcInt32 ||
hregClass(r_src) == HRcInt64);
return PPCInstr_Alu(Palu_OR, r_dst, r_src, PPCRH_Reg(r_src));
}
static void add_to_sp ( ISelEnv* env, UInt n )
{
HReg sp = StackFramePtr(env->mode64);
vassert(n < 256 && (n%16) == 0);
addInstr(env, PPCInstr_Alu( Palu_ADD, sp, sp,
PPCRH_Imm(True,toUShort(n)) ));
}
static void sub_from_sp ( ISelEnv* env, UInt n )
{
HReg sp = StackFramePtr(env->mode64);
vassert(n < 256 && (n%16) == 0);
addInstr(env, PPCInstr_Alu( Palu_SUB, sp, sp,
PPCRH_Imm(True,toUShort(n)) ));
}
static HReg get_sp_aligned16 ( ISelEnv* env )
{
HReg r = newVRegI(env);
HReg align16 = newVRegI(env);
addInstr(env, mk_iMOVds_RR(r, StackFramePtr(env->mode64)));
addInstr(env, PPCInstr_Alu( Palu_ADD, r, r,
PPCRH_Imm(True,toUShort(16)) ));
addInstr(env,
PPCInstr_LI(align16, 0xFFFFFFFFFFFFFFF0ULL, env->mode64));
addInstr(env, PPCInstr_Alu(Palu_AND, r,r, PPCRH_Reg(align16)));
return r;
}
static HReg mk_LoadRR32toFPR ( ISelEnv* env,
HReg r_srcHi, HReg r_srcLo )
{
HReg fr_dst = newVRegF(env);
PPCAMode *am_addr0, *am_addr1;
vassert(!env->mode64);
vassert(hregClass(r_srcHi) == HRcInt32);
vassert(hregClass(r_srcLo) == HRcInt32);
sub_from_sp( env, 16 );
am_addr0 = PPCAMode_IR( 0, StackFramePtr(env->mode64) );
am_addr1 = PPCAMode_IR( 4, StackFramePtr(env->mode64) );
addInstr(env, PPCInstr_Store( 4, am_addr0, r_srcHi, env->mode64 ));
addInstr(env, PPCInstr_Store( 4, am_addr1, r_srcLo, env->mode64 ));
addInstr(env, PPCInstr_FpLdSt(True, 8, fr_dst, am_addr0));
add_to_sp( env, 16 );
return fr_dst;
}
static HReg mk_LoadR64toFPR ( ISelEnv* env, HReg r_src )
{
HReg fr_dst = newVRegF(env);
PPCAMode *am_addr0;
vassert(env->mode64);
vassert(hregClass(r_src) == HRcInt64);
sub_from_sp( env, 16 );
am_addr0 = PPCAMode_IR( 0, StackFramePtr(env->mode64) );
addInstr(env, PPCInstr_Store( 8, am_addr0, r_src, env->mode64 ));
addInstr(env, PPCInstr_FpLdSt(True, 8, fr_dst, am_addr0));
add_to_sp( env, 16 );
return fr_dst;
}
static PPCAMode* advance4 ( ISelEnv* env, PPCAMode* am )
{
PPCAMode* am4 = dopyPPCAMode( am );
if (am4->tag == Pam_IR
&& am4->Pam.IR.index + 4 <= 32767) {
am4->Pam.IR.index += 4;
} else {
vpanic("advance4(ppc,host)");
}
return am4;
}
static
PPCAMode* genGuestArrayOffset ( ISelEnv* env, IRRegArray* descr,
IRExpr* off, Int bias )
{
HReg rtmp, roff;
Int elemSz = sizeofIRType(descr->elemTy);
Int nElems = descr->nElems;
Int shift = 0;
if (nElems != 16 && nElems != 32)
vpanic("genGuestArrayOffset(ppc host)(1)");
switch (elemSz) {
case 4: shift = 2; break;
case 8: shift = 3; break;
default: vpanic("genGuestArrayOffset(ppc host)(2)");
}
if (bias < -100 || bias > 100)
vpanic("genGuestArrayOffset(ppc host)(3)");
if (descr->base < 0 || descr->base > 5000)
vpanic("genGuestArrayOffset(ppc host)(4)");
roff = iselWordExpr_R(env, off);
rtmp = newVRegI(env);
addInstr(env, PPCInstr_Alu(
Palu_ADD,
rtmp, roff,
PPCRH_Imm(True, toUShort(bias))));
addInstr(env, PPCInstr_Alu(
Palu_AND,
rtmp, rtmp,
PPCRH_Imm(False, toUShort(nElems-1))));
addInstr(env, PPCInstr_Shft(
Pshft_SHL,
env->mode64 ? False : True,
rtmp, rtmp,
PPCRH_Imm(False, toUShort(shift))));
addInstr(env, PPCInstr_Alu(
Palu_ADD,
rtmp, rtmp,
PPCRH_Imm(True, toUShort(descr->base))));
return
PPCAMode_RR( GuestStatePtr(env->mode64), rtmp );
}
static
Bool mightRequireFixedRegs ( IRExpr* e )
{
switch (e->tag) {
case Iex_RdTmp: case Iex_Const: case Iex_Get:
return False;
default:
return True;
}
}
static
void doHelperCall ( ISelEnv* env,
Bool passBBP,
IRExpr* guard, IRCallee* cee, IRExpr** args )
{
PPCCondCode cc;
HReg argregs[PPC_N_REGPARMS];
HReg tmpregs[PPC_N_REGPARMS];
Bool go_fast;
Int n_args, i, argreg;
UInt argiregs;
ULong target;
Bool mode64 = env->mode64;
Bool regalign_int64s
= (!mode64) && env->vbi->host_ppc32_regalign_int64_args;
n_args = 0;
for (i = 0; args[i]; i++)
n_args++;
if (PPC_N_REGPARMS < n_args + (passBBP ? 1 : 0)) {
vpanic("doHelperCall(PPC): cannot currently handle > 8 args");
}
argregs[0] = hregPPC_GPR3(mode64);
argregs[1] = hregPPC_GPR4(mode64);
argregs[2] = hregPPC_GPR5(mode64);
argregs[3] = hregPPC_GPR6(mode64);
argregs[4] = hregPPC_GPR7(mode64);
argregs[5] = hregPPC_GPR8(mode64);
argregs[6] = hregPPC_GPR9(mode64);
argregs[7] = hregPPC_GPR10(mode64);
argiregs = 0;
tmpregs[0] = tmpregs[1] = tmpregs[2] =
tmpregs[3] = tmpregs[4] = tmpregs[5] =
tmpregs[6] = tmpregs[7] = INVALID_HREG;
go_fast = True;
if (guard) {
if (guard->tag == Iex_Const
&& guard->Iex.Const.con->tag == Ico_U1
&& guard->Iex.Const.con->Ico.U1 == True) {
} else {
go_fast = False;
}
}
if (go_fast) {
for (i = 0; i < n_args; i++) {
if (mightRequireFixedRegs(args[i])) {
go_fast = False;
break;
}
}
}
if (go_fast) {
argreg = 0;
if (passBBP) {
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg],
GuestStatePtr(mode64) ));
argreg++;
}
for (i = 0; i < n_args; i++) {
vassert(argreg < PPC_N_REGPARMS);
vassert(typeOfIRExpr(env->type_env, args[i]) == Ity_I32 ||
typeOfIRExpr(env->type_env, args[i]) == Ity_I64);
if (!mode64) {
if (typeOfIRExpr(env->type_env, args[i]) == Ity_I32) {
argiregs |= (1 << (argreg+3));
addInstr(env,
mk_iMOVds_RR( argregs[argreg],
iselWordExpr_R(env, args[i]) ));
} else {
HReg rHi, rLo;
if (regalign_int64s && (argreg%2) == 1)
argreg++;
vassert(argreg < PPC_N_REGPARMS-1);
iselInt64Expr(&rHi,&rLo, env, args[i]);
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg++], rHi ));
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg], rLo));
}
} else {
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg],
iselWordExpr_R(env, args[i]) ));
}
argreg++;
}
cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
} else {
argreg = 0;
if (passBBP) {
tmpregs[argreg] = newVRegI(env);
addInstr(env, mk_iMOVds_RR( tmpregs[argreg],
GuestStatePtr(mode64) ));
argreg++;
}
for (i = 0; i < n_args; i++) {
vassert(argreg < PPC_N_REGPARMS);
vassert(typeOfIRExpr(env->type_env, args[i]) == Ity_I32 ||
typeOfIRExpr(env->type_env, args[i]) == Ity_I64);
if (!mode64) {
if (typeOfIRExpr(env->type_env, args[i]) == Ity_I32) {
tmpregs[argreg] = iselWordExpr_R(env, args[i]);
} else {
HReg rHi, rLo;
if (regalign_int64s && (argreg%2) == 1)
argreg++;
vassert(argreg < PPC_N_REGPARMS-1);
iselInt64Expr(&rHi,&rLo, env, args[i]);
tmpregs[argreg++] = rHi;
tmpregs[argreg] = rLo;
}
} else {
tmpregs[argreg] = iselWordExpr_R(env, args[i]);
}
argreg++;
}
cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
if (guard) {
if (guard->tag == Iex_Const
&& guard->Iex.Const.con->tag == Ico_U1
&& guard->Iex.Const.con->Ico.U1 == True) {
} else {
cc = iselCondCode( env, guard );
}
}
for (i = 0; i < argreg; i++) {
if (tmpregs[i] == INVALID_HREG)
continue;
argiregs |= (1 << (i+3));
addInstr( env, mk_iMOVds_RR( argregs[i], tmpregs[i] ) );
}
}
target = mode64 ? Ptr_to_ULong(cee->addr) :
toUInt(Ptr_to_ULong(cee->addr));
addInstr(env, PPCInstr_Call( cc, (Addr64)target, argiregs ));
}
static HReg roundModeIRtoPPC ( ISelEnv* env, HReg r_rmIR )
{
HReg r_rmPPC = newVRegI(env);
HReg r_tmp1 = newVRegI(env);
HReg r_tmp2 = newVRegI(env);
vassert(hregClass(r_rmIR) == HRcGPR(env->mode64));
addInstr(env, PPCInstr_Shft(Pshft_SHL, True,
r_tmp1, r_rmIR, PPCRH_Imm(False,1)));
addInstr( env, PPCInstr_Alu( Palu_AND,
r_tmp2, r_tmp1, PPCRH_Imm( False, 3 ) ) );
addInstr( env, PPCInstr_Alu( Palu_XOR,
r_rmPPC, r_rmIR, PPCRH_Reg( r_tmp2 ) ) );
return r_rmPPC;
}
static
void _set_FPU_rounding_mode ( ISelEnv* env, IRExpr* mode, Bool dfp_rm )
{
HReg fr_src = newVRegF(env);
HReg r_src;
vassert(typeOfIRExpr(env->type_env,mode) == Ity_I32);
if (env->previous_rm
&& env->previous_rm->tag == Iex_RdTmp
&& mode->tag == Iex_RdTmp
&& env->previous_rm->Iex.RdTmp.tmp == mode->Iex.RdTmp.tmp) {
vassert(typeOfIRExpr(env->type_env, env->previous_rm) == Ity_I32);
return;
}
env->previous_rm = mode;
r_src = roundModeIRtoPPC( env, iselWordExpr_R(env, mode) );
if (env->mode64) {
if (dfp_rm) {
HReg r_tmp1 = newVRegI( env );
addInstr( env,
PPCInstr_Shft( Pshft_SHL, False,
r_tmp1, r_src, PPCRH_Imm( False, 32 ) ) );
fr_src = mk_LoadR64toFPR( env, r_tmp1 );
} else {
fr_src = mk_LoadR64toFPR( env, r_src );
}
} else {
if (dfp_rm) {
HReg r_zero = newVRegI( env );
addInstr( env, PPCInstr_LI( r_zero, 0, env->mode64 ) );
fr_src = mk_LoadRR32toFPR( env, r_src, r_zero );
} else {
fr_src = mk_LoadRR32toFPR( env, r_src, r_src );
}
}
addInstr(env, PPCInstr_FpLdFPSCR( fr_src, dfp_rm ));
}
static void set_FPU_rounding_mode ( ISelEnv* env, IRExpr* mode )
{
_set_FPU_rounding_mode(env, mode, False);
}
static void set_FPU_DFP_rounding_mode ( ISelEnv* env, IRExpr* mode )
{
_set_FPU_rounding_mode(env, mode, True);
}
static HReg generate_zeroes_V128 ( ISelEnv* env )
{
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBinary(Pav_XOR, dst, dst, dst));
return dst;
}
static HReg generate_ones_V128 ( ISelEnv* env )
{
HReg dst = newVRegV(env);
PPCVI5s * src = PPCVI5s_Imm(-1);
addInstr(env, PPCInstr_AvSplat(8, dst, src));
return dst;
}
static HReg mk_AvDuplicateRI( ISelEnv* env, IRExpr* e )
{
HReg r_src;
HReg dst = newVRegV(env);
PPCRI* ri = iselWordExpr_RI(env, e);
IRType ty = typeOfIRExpr(env->type_env,e);
UInt sz = (ty == Ity_I8) ? 8 : (ty == Ity_I16) ? 16 : 32;
vassert(ty == Ity_I8 || ty == Ity_I16 || ty == Ity_I32);
if (ri->tag == Pri_Imm) {
Int simm32 = (Int)ri->Pri.Imm;
if (simm32 >= -32 && simm32 <= 31) {
Char simm6 = (Char)simm32;
if (simm6 > 15) {
HReg v1 = newVRegV(env);
HReg v2 = newVRegV(env);
addInstr(env, PPCInstr_AvSplat(sz, v1, PPCVI5s_Imm(-16)));
addInstr(env, PPCInstr_AvSplat(sz, v2, PPCVI5s_Imm(simm6-16)));
addInstr(env,
(sz== 8) ? PPCInstr_AvBin8x16(Pav_SUBU, dst, v2, v1) :
(sz==16) ? PPCInstr_AvBin16x8(Pav_SUBU, dst, v2, v1)
: PPCInstr_AvBin32x4(Pav_SUBU, dst, v2, v1) );
return dst;
}
if (simm6 < -16) {
HReg v1 = newVRegV(env);
HReg v2 = newVRegV(env);
addInstr(env, PPCInstr_AvSplat(sz, v1, PPCVI5s_Imm(-16)));
addInstr(env, PPCInstr_AvSplat(sz, v2, PPCVI5s_Imm(simm6+16)));
addInstr(env,
(sz== 8) ? PPCInstr_AvBin8x16(Pav_ADDU, dst, v2, v1) :
(sz==16) ? PPCInstr_AvBin16x8(Pav_ADDU, dst, v2, v1)
: PPCInstr_AvBin32x4(Pav_ADDU, dst, v2, v1) );
return dst;
}
addInstr(env, PPCInstr_AvSplat(sz, dst, PPCVI5s_Imm(simm6)));
return dst;
}
r_src = newVRegI(env);
addInstr(env, PPCInstr_LI(r_src, (Long)simm32, env->mode64));
}
else {
r_src = ri->Pri.Reg;
}
{
HReg r_aligned16;
HReg v_src = newVRegV(env);
PPCAMode *am_off12;
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off12 = PPCAMode_IR( 12, r_aligned16 );
addInstr(env, PPCInstr_Store( 4, am_off12, r_src, env->mode64 ));
addInstr(env, PPCInstr_AvLdSt( True, 4, v_src, am_off12 ) );
add_to_sp( env, 32 );
addInstr(env, PPCInstr_AvSplat(sz, dst, PPCVI5s_Reg(v_src)));
return dst;
}
}
static HReg isNan ( ISelEnv* env, HReg vSrc )
{
HReg zeros, msk_exp, msk_mnt, expt, mnts, vIsNan;
vassert(hregClass(vSrc) == HRcVec128);
zeros = mk_AvDuplicateRI(env, mkU32(0));
msk_exp = mk_AvDuplicateRI(env, mkU32(0x7F800000));
msk_mnt = mk_AvDuplicateRI(env, mkU32(0x7FFFFF));
expt = newVRegV(env);
mnts = newVRegV(env);
vIsNan = newVRegV(env);
addInstr(env, PPCInstr_AvBinary(Pav_AND, expt, vSrc, msk_exp));
addInstr(env, PPCInstr_AvBin32x4(Pav_CMPEQU, expt, expt, msk_exp));
addInstr(env, PPCInstr_AvBinary(Pav_AND, mnts, vSrc, msk_mnt));
addInstr(env, PPCInstr_AvBin32x4(Pav_CMPGTU, mnts, mnts, zeros));
addInstr(env, PPCInstr_AvBinary(Pav_AND, vIsNan, expt, mnts));
return vIsNan;
}
static HReg iselWordExpr_R ( ISelEnv* env, IRExpr* e )
{
HReg r = iselWordExpr_R_wrk(env, e);
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(r) == HRcGPR(env->mode64));
vassert(hregIsVirtual(r));
return r;
}
static HReg iselWordExpr_R_wrk ( ISelEnv* env, IRExpr* e )
{
Bool mode64 = env->mode64;
MatchInfo mi;
DECLARE_PATTERN(p_32to1_then_1Uto8);
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && mode64));
switch (e->tag) {
case Iex_RdTmp:
return lookupIRTemp(env, e->Iex.RdTmp.tmp);
case Iex_Load: {
HReg r_dst;
PPCAMode* am_addr;
if (e->Iex.Load.end != Iend_BE)
goto irreducible;
r_dst = newVRegI(env);
am_addr = iselWordExpr_AMode( env, e->Iex.Load.addr, ty );
addInstr(env, PPCInstr_Load( toUChar(sizeofIRType(ty)),
r_dst, am_addr, mode64 ));
return r_dst;
}
case Iex_Binop: {
PPCAluOp aluOp;
PPCShftOp shftOp;
switch (e->Iex.Binop.op) {
case Iop_Add8: case Iop_Add16: case Iop_Add32: case Iop_Add64:
aluOp = Palu_ADD; break;
case Iop_Sub8: case Iop_Sub16: case Iop_Sub32: case Iop_Sub64:
aluOp = Palu_SUB; break;
case Iop_And8: case Iop_And16: case Iop_And32: case Iop_And64:
aluOp = Palu_AND; break;
case Iop_Or8: case Iop_Or16: case Iop_Or32: case Iop_Or64:
aluOp = Palu_OR; break;
case Iop_Xor8: case Iop_Xor16: case Iop_Xor32: case Iop_Xor64:
aluOp = Palu_XOR; break;
default:
aluOp = Palu_INVALID; break;
}
if (aluOp != Palu_INVALID) {
HReg r_dst = newVRegI(env);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
PPCRH* ri_srcR = NULL;
switch (aluOp) {
case Palu_ADD: case Palu_SUB:
ri_srcR = iselWordExpr_RH(env, True,
e->Iex.Binop.arg2);
break;
case Palu_AND: case Palu_OR: case Palu_XOR:
ri_srcR = iselWordExpr_RH(env, False,
e->Iex.Binop.arg2);
break;
default:
vpanic("iselWordExpr_R_wrk-aluOp-arg2");
}
addInstr(env, PPCInstr_Alu(aluOp, r_dst, r_srcL, ri_srcR));
return r_dst;
}
switch (e->Iex.Binop.op) {
case Iop_Shl8: case Iop_Shl16: case Iop_Shl32: case Iop_Shl64:
shftOp = Pshft_SHL; break;
case Iop_Shr8: case Iop_Shr16: case Iop_Shr32: case Iop_Shr64:
shftOp = Pshft_SHR; break;
case Iop_Sar8: case Iop_Sar16: case Iop_Sar32: case Iop_Sar64:
shftOp = Pshft_SAR; break;
default:
shftOp = Pshft_INVALID; break;
}
if (shftOp != Pshft_INVALID) {
HReg r_dst = newVRegI(env);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
PPCRH* ri_srcR = NULL;
switch (shftOp) {
case Pshft_SHL: case Pshft_SHR: case Pshft_SAR:
if (!mode64)
ri_srcR = iselWordExpr_RH5u(env, e->Iex.Binop.arg2);
else
ri_srcR = iselWordExpr_RH6u(env, e->Iex.Binop.arg2);
break;
default:
vpanic("iselIntExpr_R_wrk-shftOp-arg2");
}
if (shftOp == Pshft_SHR || shftOp == Pshft_SAR) {
if (ty == Ity_I8 || ty == Ity_I16) {
PPCRH* amt = PPCRH_Imm(False,
toUShort(ty == Ity_I8 ? 24 : 16));
HReg tmp = newVRegI(env);
addInstr(env, PPCInstr_Shft(Pshft_SHL,
True,
tmp, r_srcL, amt));
addInstr(env, PPCInstr_Shft(shftOp,
True,
tmp, tmp, amt));
r_srcL = tmp;
vassert(0);
}
}
if (ty == Ity_I64) {
vassert(mode64);
addInstr(env, PPCInstr_Shft(shftOp, False,
r_dst, r_srcL, ri_srcR));
} else {
addInstr(env, PPCInstr_Shft(shftOp, True,
r_dst, r_srcL, ri_srcR));
}
return r_dst;
}
if (e->Iex.Binop.op == Iop_DivS32 ||
e->Iex.Binop.op == Iop_DivU32 ||
e->Iex.Binop.op == Iop_DivS32E ||
e->Iex.Binop.op == Iop_DivU32E) {
Bool syned = toBool((e->Iex.Binop.op == Iop_DivS32) || (e->Iex.Binop.op == Iop_DivS32E));
HReg r_dst = newVRegI(env);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2);
addInstr( env,
PPCInstr_Div( ( ( e->Iex.Binop.op == Iop_DivU32E )
|| ( e->Iex.Binop.op == Iop_DivS32E ) ) ? True
: False,
syned,
True,
r_dst,
r_srcL,
r_srcR ) );
return r_dst;
}
if (e->Iex.Binop.op == Iop_DivS64 ||
e->Iex.Binop.op == Iop_DivU64 || e->Iex.Binop.op == Iop_DivS64E
|| e->Iex.Binop.op == Iop_DivU64E ) {
Bool syned = toBool((e->Iex.Binop.op == Iop_DivS64) ||(e->Iex.Binop.op == Iop_DivS64E));
HReg r_dst = newVRegI(env);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2);
vassert(mode64);
addInstr( env,
PPCInstr_Div( ( ( e->Iex.Binop.op == Iop_DivS64E )
|| ( e->Iex.Binop.op
== Iop_DivU64E ) ) ? True
: False,
syned,
False,
r_dst,
r_srcL,
r_srcR ) );
return r_dst;
}
if (e->Iex.Binop.op == Iop_Mul32
|| e->Iex.Binop.op == Iop_Mul64) {
Bool syned = False;
Bool sz32 = (e->Iex.Binop.op != Iop_Mul64);
HReg r_dst = newVRegI(env);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_MulL(syned, False, sz32,
r_dst, r_srcL, r_srcR));
return r_dst;
}
if (mode64
&& (e->Iex.Binop.op == Iop_MullU32
|| e->Iex.Binop.op == Iop_MullS32)) {
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
HReg r_dst = newVRegI(env);
Bool syned = toBool(e->Iex.Binop.op == Iop_MullS32);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_MulL(False,
False, True,
tLo, r_srcL, r_srcR));
addInstr(env, PPCInstr_MulL(syned,
True, True,
tHi, r_srcL, r_srcR));
addInstr(env, PPCInstr_Shft(Pshft_SHL, False,
r_dst, tHi, PPCRH_Imm(False,32)));
addInstr(env, PPCInstr_Alu(Palu_OR,
r_dst, r_dst, PPCRH_Reg(tLo)));
return r_dst;
}
if (e->Iex.Binop.op == Iop_CmpORD32S
|| e->Iex.Binop.op == Iop_CmpORD32U) {
Bool syned = toBool(e->Iex.Binop.op == Iop_CmpORD32S);
HReg dst = newVRegI(env);
HReg srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
PPCRH* srcR = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Cmp(syned, True,
7, srcL, srcR));
addInstr(env, PPCInstr_MfCR(dst));
addInstr(env, PPCInstr_Alu(Palu_AND, dst, dst,
PPCRH_Imm(False,7<<1)));
return dst;
}
if (e->Iex.Binop.op == Iop_CmpORD64S
|| e->Iex.Binop.op == Iop_CmpORD64U) {
Bool syned = toBool(e->Iex.Binop.op == Iop_CmpORD64S);
HReg dst = newVRegI(env);
HReg srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
PPCRH* srcR = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2);
vassert(mode64);
addInstr(env, PPCInstr_Cmp(syned, False,
7, srcL, srcR));
addInstr(env, PPCInstr_MfCR(dst));
addInstr(env, PPCInstr_Alu(Palu_AND, dst, dst,
PPCRH_Imm(False,7<<1)));
return dst;
}
if (e->Iex.Binop.op == Iop_Max32U) {
HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r2 = iselWordExpr_R(env, e->Iex.Binop.arg2);
HReg rdst = newVRegI(env);
PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7LT );
addInstr(env, mk_iMOVds_RR(rdst, r1));
addInstr(env, PPCInstr_Cmp(False, True,
7, rdst, PPCRH_Reg(r2)));
addInstr(env, PPCInstr_CMov(cc, rdst, PPCRI_Reg(r2)));
return rdst;
}
if (e->Iex.Binop.op == Iop_32HLto64) {
HReg r_Hi = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_Lo = iselWordExpr_R(env, e->Iex.Binop.arg2);
HReg r_dst = newVRegI(env);
HReg msk = newVRegI(env);
vassert(mode64);
addInstr(env, PPCInstr_Shft(Pshft_SHL, False,
r_dst, r_Hi, PPCRH_Imm(False,32)));
addInstr(env, PPCInstr_LI(msk, 0xFFFFFFFF, mode64));
addInstr(env, PPCInstr_Alu( Palu_AND, r_Lo, r_Lo,
PPCRH_Reg(msk) ));
addInstr(env, PPCInstr_Alu( Palu_OR, r_dst, r_dst,
PPCRH_Reg(r_Lo) ));
return r_dst;
}
if ((e->Iex.Binop.op == Iop_CmpF64) ||
(e->Iex.Binop.op == Iop_CmpD64) ||
(e->Iex.Binop.op == Iop_CmpD128)) {
HReg fr_srcL;
HReg fr_srcL_lo;
HReg fr_srcR;
HReg fr_srcR_lo;
HReg r_ccPPC = newVRegI(env);
HReg r_ccIR = newVRegI(env);
HReg r_ccIR_b0 = newVRegI(env);
HReg r_ccIR_b2 = newVRegI(env);
HReg r_ccIR_b6 = newVRegI(env);
if (e->Iex.Binop.op == Iop_CmpF64) {
fr_srcL = iselDblExpr(env, e->Iex.Binop.arg1);
fr_srcR = iselDblExpr(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_FpCmp(r_ccPPC, fr_srcL, fr_srcR));
} else if (e->Iex.Binop.op == Iop_CmpD64) {
fr_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1);
fr_srcR = iselDfp64Expr(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Dfp64Cmp(r_ccPPC, fr_srcL, fr_srcR));
} else {
iselDfp128Expr(&fr_srcL, &fr_srcL_lo, env, e->Iex.Binop.arg1);
iselDfp128Expr(&fr_srcR, &fr_srcR_lo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Dfp128Cmp(r_ccPPC, fr_srcL, fr_srcL_lo,
fr_srcR, fr_srcR_lo));
}
addInstr(env, PPCInstr_Shft(Pshft_SHR, True,
r_ccIR_b0, r_ccPPC,
PPCRH_Imm(False,0x3)));
addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR_b0,
r_ccPPC, PPCRH_Reg(r_ccIR_b0)));
addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b0,
r_ccIR_b0, PPCRH_Imm(False,0x1)));
addInstr(env, PPCInstr_Shft(Pshft_SHL, True,
r_ccIR_b2, r_ccPPC,
PPCRH_Imm(False,0x2)));
addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b2,
r_ccIR_b2, PPCRH_Imm(False,0x4)));
addInstr(env, PPCInstr_Shft(Pshft_SHR, True,
r_ccIR_b6, r_ccPPC,
PPCRH_Imm(False,0x1)));
addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR_b6,
r_ccPPC, PPCRH_Reg(r_ccIR_b6)));
addInstr(env, PPCInstr_Shft(Pshft_SHL, True,
r_ccIR_b6, r_ccIR_b6,
PPCRH_Imm(False,0x6)));
addInstr(env, PPCInstr_Alu(Palu_AND, r_ccIR_b6,
r_ccIR_b6, PPCRH_Imm(False,0x40)));
addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR,
r_ccIR_b0, PPCRH_Reg(r_ccIR_b2)));
addInstr(env, PPCInstr_Alu(Palu_OR, r_ccIR,
r_ccIR, PPCRH_Reg(r_ccIR_b6)));
return r_ccIR;
}
if ( e->Iex.Binop.op == Iop_F64toI32S ||
e->Iex.Binop.op == Iop_F64toI32U ) {
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2);
HReg ftmp = newVRegF(env);
HReg idst = newVRegI(env);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_FpCftI(False, True,
e->Iex.Binop.op == Iop_F64toI32S ? True
: False,
True,
ftmp, fsrc));
addInstr(env, PPCInstr_FpSTFIW(r1, ftmp));
addInstr(env, PPCInstr_Load(4, idst, zero_r1, mode64));
if (mode64)
addInstr(env, PPCInstr_Unary(Pun_EXTSW, idst, idst));
add_to_sp( env, 16 );
return idst;
}
if (e->Iex.Binop.op == Iop_F64toI64S || e->Iex.Binop.op == Iop_F64toI64U ) {
if (mode64) {
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2);
HReg idst = newVRegI(env);
HReg ftmp = newVRegF(env);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_FpCftI(False, False,
( e->Iex.Binop.op == Iop_F64toI64S ) ? True
: False,
True, ftmp, fsrc));
addInstr(env, PPCInstr_FpLdSt(False, 8, ftmp, zero_r1));
addInstr(env, PPCInstr_Load(8, idst, zero_r1, True));
add_to_sp( env, 16 );
return idst;
}
}
break;
}
case Iex_Unop: {
IROp op_unop = e->Iex.Unop.op;
DEFINE_PATTERN(p_32to1_then_1Uto8,
unop(Iop_1Uto8,unop(Iop_32to1,bind(0))));
if (matchIRExpr(&mi,p_32to1_then_1Uto8,e)) {
IRExpr* expr32 = mi.bindee[0];
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, expr32);
addInstr(env, PPCInstr_Alu(Palu_AND, r_dst,
r_src, PPCRH_Imm(False,1)));
return r_dst;
}
{
DECLARE_PATTERN(p_LDbe16_then_16Uto32);
DEFINE_PATTERN(p_LDbe16_then_16Uto32,
unop(Iop_16Uto32,
IRExpr_Load(Iend_BE,Ity_I16,bind(0))) );
if (matchIRExpr(&mi,p_LDbe16_then_16Uto32,e)) {
HReg r_dst = newVRegI(env);
PPCAMode* amode
= iselWordExpr_AMode( env, mi.bindee[0], Ity_I16 );
addInstr(env, PPCInstr_Load(2,r_dst,amode, mode64));
return r_dst;
}
}
switch (op_unop) {
case Iop_8Uto16:
case Iop_8Uto32:
case Iop_8Uto64:
case Iop_16Uto32:
case Iop_16Uto64: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
UShort mask = toUShort(op_unop==Iop_16Uto64 ? 0xFFFF :
op_unop==Iop_16Uto32 ? 0xFFFF : 0xFF);
addInstr(env, PPCInstr_Alu(Palu_AND,r_dst,r_src,
PPCRH_Imm(False,mask)));
return r_dst;
}
case Iop_32Uto64: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
vassert(mode64);
addInstr(env,
PPCInstr_Shft(Pshft_SHL, False,
r_dst, r_src, PPCRH_Imm(False,32)));
addInstr(env,
PPCInstr_Shft(Pshft_SHR, False,
r_dst, r_dst, PPCRH_Imm(False,32)));
return r_dst;
}
case Iop_8Sto16:
case Iop_8Sto32:
case Iop_16Sto32: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
UShort amt = toUShort(op_unop==Iop_16Sto32 ? 16 : 24);
addInstr(env,
PPCInstr_Shft(Pshft_SHL, True,
r_dst, r_src, PPCRH_Imm(False,amt)));
addInstr(env,
PPCInstr_Shft(Pshft_SAR, True,
r_dst, r_dst, PPCRH_Imm(False,amt)));
return r_dst;
}
case Iop_8Sto64:
case Iop_16Sto64: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
UShort amt = toUShort(op_unop==Iop_8Sto64 ? 56 : 48);
vassert(mode64);
addInstr(env,
PPCInstr_Shft(Pshft_SHL, False,
r_dst, r_src, PPCRH_Imm(False,amt)));
addInstr(env,
PPCInstr_Shft(Pshft_SAR, False,
r_dst, r_dst, PPCRH_Imm(False,amt)));
return r_dst;
}
case Iop_32Sto64: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
vassert(mode64);
addInstr(env,
PPCInstr_Shft(Pshft_SAR, True,
r_dst, r_src, PPCRH_Imm(False,0)));
return r_dst;
}
case Iop_Not8:
case Iop_Not16:
case Iop_Not32:
case Iop_Not64: {
if (op_unop == Iop_Not64) vassert(mode64);
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Unary(Pun_NOT,r_dst,r_src));
return r_dst;
}
case Iop_64HIto32: {
if (!mode64) {
HReg rHi, rLo;
iselInt64Expr(&rHi,&rLo, env, e->Iex.Unop.arg);
return rHi;
} else {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env,
PPCInstr_Shft(Pshft_SHR, False,
r_dst, r_src, PPCRH_Imm(False,32)));
return r_dst;
}
}
case Iop_64to32: {
if (!mode64) {
HReg rHi, rLo;
iselInt64Expr(&rHi,&rLo, env, e->Iex.Unop.arg);
return rLo;
} else {
return iselWordExpr_R(env, e->Iex.Unop.arg);
}
}
case Iop_64to16: {
if (mode64) {
return iselWordExpr_R(env, e->Iex.Unop.arg);
}
break;
}
case Iop_16HIto8:
case Iop_32HIto16: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
UShort shift = toUShort(op_unop == Iop_16HIto8 ? 8 : 16);
addInstr(env,
PPCInstr_Shft(Pshft_SHR, True,
r_dst, r_src, PPCRH_Imm(False,shift)));
return r_dst;
}
case Iop_128HIto64:
if (mode64) {
HReg rHi, rLo;
iselInt128Expr(&rHi,&rLo, env, e->Iex.Unop.arg);
return rHi;
}
break;
case Iop_128to64:
if (mode64) {
HReg rHi, rLo;
iselInt128Expr(&rHi,&rLo, env, e->Iex.Unop.arg);
return rLo;
}
break;
case Iop_1Uto64:
case Iop_1Uto32:
case Iop_1Uto8:
if ((op_unop != Iop_1Uto64) || mode64) {
HReg r_dst = newVRegI(env);
PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Set(cond,r_dst));
return r_dst;
}
break;
case Iop_1Sto8:
case Iop_1Sto16:
case Iop_1Sto32: {
HReg r_dst = newVRegI(env);
PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Set(cond,r_dst));
addInstr(env,
PPCInstr_Shft(Pshft_SHL, True,
r_dst, r_dst, PPCRH_Imm(False,31)));
addInstr(env,
PPCInstr_Shft(Pshft_SAR, True,
r_dst, r_dst, PPCRH_Imm(False,31)));
return r_dst;
}
case Iop_1Sto64:
if (mode64) {
HReg r_dst = newVRegI(env);
PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Set(cond,r_dst));
addInstr(env, PPCInstr_Shft(Pshft_SHL, False,
r_dst, r_dst, PPCRH_Imm(False,63)));
addInstr(env, PPCInstr_Shft(Pshft_SAR, False,
r_dst, r_dst, PPCRH_Imm(False,63)));
return r_dst;
}
break;
case Iop_Clz32:
case Iop_Clz64: {
HReg r_src, r_dst;
PPCUnaryOp op_clz = (op_unop == Iop_Clz32) ? Pun_CLZ32 :
Pun_CLZ64;
if (op_unop == Iop_Clz64 && !mode64)
goto irreducible;
r_dst = newVRegI(env);
r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Unary(op_clz,r_dst,r_src));
return r_dst;
}
case Iop_Left8:
case Iop_Left32:
case Iop_Left64: {
HReg r_src, r_dst;
if (op_unop == Iop_Left64 && !mode64)
goto irreducible;
r_dst = newVRegI(env);
r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src));
addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src)));
return r_dst;
}
case Iop_CmpwNEZ32: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src));
addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src)));
addInstr(env, PPCInstr_Shft(Pshft_SAR, True,
r_dst, r_dst, PPCRH_Imm(False, 31)));
return r_dst;
}
case Iop_CmpwNEZ64: {
HReg r_dst = newVRegI(env);
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
if (!mode64) goto irreducible;
addInstr(env, PPCInstr_Unary(Pun_NEG,r_dst,r_src));
addInstr(env, PPCInstr_Alu(Palu_OR, r_dst, r_dst, PPCRH_Reg(r_src)));
addInstr(env, PPCInstr_Shft(Pshft_SAR, False,
r_dst, r_dst, PPCRH_Imm(False, 63)));
return r_dst;
}
case Iop_V128to32: {
HReg r_aligned16;
HReg dst = newVRegI(env);
HReg vec = iselVecExpr(env, e->Iex.Unop.arg);
PPCAMode *am_off0, *am_off12;
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off0 = PPCAMode_IR( 0, r_aligned16 );
am_off12 = PPCAMode_IR( 12,r_aligned16 );
addInstr(env,
PPCInstr_AvLdSt( False, 16, vec, am_off0 ));
addInstr(env,
PPCInstr_Load( 4, dst, am_off12, mode64 ));
add_to_sp( env, 32 );
return dst;
}
case Iop_V128to64:
case Iop_V128HIto64:
if (mode64) {
HReg r_aligned16;
HReg dst = newVRegI(env);
HReg vec = iselVecExpr(env, e->Iex.Unop.arg);
PPCAMode *am_off0, *am_off8;
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off0 = PPCAMode_IR( 0, r_aligned16 );
am_off8 = PPCAMode_IR( 8 ,r_aligned16 );
addInstr(env,
PPCInstr_AvLdSt( False, 16, vec, am_off0 ));
addInstr(env,
PPCInstr_Load(
8, dst,
op_unop == Iop_V128HIto64 ? am_off0 : am_off8,
mode64 ));
add_to_sp( env, 32 );
return dst;
}
break;
case Iop_16to8:
case Iop_32to8:
case Iop_32to16:
case Iop_64to8:
return iselWordExpr_R(env, e->Iex.Unop.arg);
case Iop_ReinterpF64asI64:
if (mode64) {
PPCAMode *am_addr;
HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg);
HReg r_dst = newVRegI(env);
sub_from_sp( env, 16 );
am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) );
addInstr(env, PPCInstr_FpLdSt( False, 8,
fr_src, am_addr ));
addInstr(env, PPCInstr_Load( 8, r_dst, am_addr, mode64 ));
add_to_sp( env, 16 );
return r_dst;
}
break;
case Iop_ReinterpF32asI32: {
PPCAMode *am_addr;
HReg fr_src = iselFltExpr(env, e->Iex.Unop.arg);
HReg r_dst = newVRegI(env);
sub_from_sp( env, 16 );
am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) );
addInstr(env, PPCInstr_FpLdSt( False, 4,
fr_src, am_addr ));
addInstr(env, PPCInstr_Load( 4, r_dst, am_addr, mode64 ));
add_to_sp( env, 16 );
return r_dst;
}
break;
case Iop_ReinterpD64asI64:
if (mode64) {
PPCAMode *am_addr;
HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg);
HReg r_dst = newVRegI(env);
sub_from_sp( env, 16 );
am_addr = PPCAMode_IR( 0, StackFramePtr(mode64) );
addInstr(env, PPCInstr_FpLdSt( False, 8,
fr_src, am_addr ));
addInstr(env, PPCInstr_Load( 8, r_dst, am_addr, mode64 ));
add_to_sp( env, 16 );
return r_dst;
}
break;
case Iop_BCDtoDPB: {
PPCCondCode cc;
UInt argiregs;
HReg argregs[1];
HReg r_dst = newVRegI(env);
Int argreg;
HWord* fdescr;
argiregs = 0;
argreg = 0;
argregs[0] = hregPPC_GPR3(mode64);
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg++],
iselWordExpr_R(env, e->Iex.Unop.arg) ) );
cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
fdescr = (HWord*)h_BCDtoDPB;
addInstr(env, PPCInstr_Call( cc, (Addr64)(fdescr[0]), argiregs ) );
addInstr(env, mk_iMOVds_RR(r_dst, argregs[0]));
return r_dst;
}
case Iop_DPBtoBCD: {
PPCCondCode cc;
UInt argiregs;
HReg argregs[1];
HReg r_dst = newVRegI(env);
Int argreg;
HWord* fdescr;
argiregs = 0;
argreg = 0;
argregs[0] = hregPPC_GPR3(mode64);
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg++],
iselWordExpr_R(env, e->Iex.Unop.arg) ) );
cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
fdescr = (HWord*)h_DPBtoBCD;
addInstr(env, PPCInstr_Call( cc, (Addr64)(fdescr[0]), argiregs ) );
addInstr(env, mk_iMOVds_RR(r_dst, argregs[0]));
return r_dst;
}
default:
break;
}
break;
}
case Iex_Get: {
if (ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && mode64)) {
HReg r_dst = newVRegI(env);
PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset,
GuestStatePtr(mode64) );
addInstr(env, PPCInstr_Load( toUChar(sizeofIRType(ty)),
r_dst, am_addr, mode64 ));
return r_dst;
}
break;
}
case Iex_GetI: {
PPCAMode* src_am
= genGuestArrayOffset( env, e->Iex.GetI.descr,
e->Iex.GetI.ix, e->Iex.GetI.bias );
HReg r_dst = newVRegI(env);
if (mode64 && ty == Ity_I64) {
addInstr(env, PPCInstr_Load( toUChar(8),
r_dst, src_am, mode64 ));
return r_dst;
}
if ((!mode64) && ty == Ity_I32) {
addInstr(env, PPCInstr_Load( toUChar(4),
r_dst, src_am, mode64 ));
return r_dst;
}
break;
}
case Iex_CCall: {
HReg r_dst = newVRegI(env);
vassert(ty == Ity_I32);
if (e->Iex.CCall.retty != Ity_I32)
goto irreducible;
doHelperCall( env, False, NULL,
e->Iex.CCall.cee, e->Iex.CCall.args );
addInstr(env, mk_iMOVds_RR(r_dst, hregPPC_GPR3(mode64)));
return r_dst;
}
case Iex_Const: {
Long l;
HReg r_dst = newVRegI(env);
IRConst* con = e->Iex.Const.con;
switch (con->tag) {
case Ico_U64: if (!mode64) goto irreducible;
l = (Long) con->Ico.U64; break;
case Ico_U32: l = (Long)(Int) con->Ico.U32; break;
case Ico_U16: l = (Long)(Int)(Short)con->Ico.U16; break;
case Ico_U8: l = (Long)(Int)(Char )con->Ico.U8; break;
default: vpanic("iselIntExpr_R.const(ppc)");
}
addInstr(env, PPCInstr_LI(r_dst, (ULong)l, mode64));
return r_dst;
}
case Iex_Mux0X: {
if ((ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && mode64)) &&
typeOfIRExpr(env->type_env,e->Iex.Mux0X.cond) == Ity_I8) {
PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond);
HReg rX = iselWordExpr_R(env, e->Iex.Mux0X.exprX);
PPCRI* r0 = iselWordExpr_RI(env, e->Iex.Mux0X.expr0);
HReg r_dst = newVRegI(env);
HReg r_tmp = newVRegI(env);
addInstr(env, mk_iMOVds_RR(r_dst,rX));
addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp,
r_cond, PPCRH_Imm(False,0xFF)));
addInstr(env, PPCInstr_Cmp(False, True,
7, r_tmp, PPCRH_Imm(False,0)));
addInstr(env, PPCInstr_CMov(cc,r_dst,r0));
return r_dst;
}
break;
}
default:
break;
}
irreducible:
ppIRExpr(e);
vpanic("iselIntExpr_R(ppc): cannot reduce tree");
}
static Bool uInt_fits_in_16_bits ( UInt u )
{
Int i = u & 0xFFFF;
i <<= 16;
i >>= 16;
return toBool(u == (UInt)i);
}
static Bool uLong_fits_in_16_bits ( ULong u )
{
Long i = u & 0xFFFFULL;
i <<= 48;
i >>= 48;
return toBool(u == (ULong)i);
}
static Bool uLong_is_4_aligned ( ULong u )
{
return toBool((u & 3ULL) == 0);
}
static Bool sane_AMode ( ISelEnv* env, PPCAMode* am )
{
Bool mode64 = env->mode64;
switch (am->tag) {
case Pam_IR:
return toBool( hregClass(am->Pam.IR.base) == HRcGPR(mode64) &&
hregIsVirtual(am->Pam.IR.base) &&
uInt_fits_in_16_bits(am->Pam.IR.index) );
case Pam_RR:
return toBool( hregClass(am->Pam.RR.base) == HRcGPR(mode64) &&
hregIsVirtual(am->Pam.RR.base) &&
hregClass(am->Pam.RR.index) == HRcGPR(mode64) &&
hregIsVirtual(am->Pam.IR.index) );
default:
vpanic("sane_AMode: unknown ppc amode tag");
}
}
static
PPCAMode* iselWordExpr_AMode ( ISelEnv* env, IRExpr* e, IRType xferTy )
{
PPCAMode* am = iselWordExpr_AMode_wrk(env, e, xferTy);
vassert(sane_AMode(env, am));
return am;
}
static PPCAMode* iselWordExpr_AMode_wrk ( ISelEnv* env, IRExpr* e, IRType xferTy )
{
IRType ty = typeOfIRExpr(env->type_env,e);
if (env->mode64) {
Bool aligned4imm = toBool(xferTy == Ity_I32 || xferTy == Ity_I64);
vassert(ty == Ity_I64);
if (e->tag == Iex_Binop
&& e->Iex.Binop.op == Iop_Add64
&& e->Iex.Binop.arg2->tag == Iex_Const
&& e->Iex.Binop.arg2->Iex.Const.con->tag == Ico_U64
&& (aligned4imm ? uLong_is_4_aligned(e->Iex.Binop.arg2
->Iex.Const.con->Ico.U64)
: True)
&& uLong_fits_in_16_bits(e->Iex.Binop.arg2
->Iex.Const.con->Ico.U64)) {
return PPCAMode_IR( (Int)e->Iex.Binop.arg2->Iex.Const.con->Ico.U64,
iselWordExpr_R(env, e->Iex.Binop.arg1) );
}
if (e->tag == Iex_Binop
&& e->Iex.Binop.op == Iop_Add64) {
HReg r_base = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_idx = iselWordExpr_R(env, e->Iex.Binop.arg2);
return PPCAMode_RR( r_idx, r_base );
}
} else {
vassert(ty == Ity_I32);
if (e->tag == Iex_Binop
&& e->Iex.Binop.op == Iop_Add32
&& e->Iex.Binop.arg2->tag == Iex_Const
&& e->Iex.Binop.arg2->Iex.Const.con->tag == Ico_U32
&& uInt_fits_in_16_bits(e->Iex.Binop.arg2
->Iex.Const.con->Ico.U32)) {
return PPCAMode_IR( (Int)e->Iex.Binop.arg2->Iex.Const.con->Ico.U32,
iselWordExpr_R(env, e->Iex.Binop.arg1) );
}
if (e->tag == Iex_Binop
&& e->Iex.Binop.op == Iop_Add32) {
HReg r_base = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_idx = iselWordExpr_R(env, e->Iex.Binop.arg2);
return PPCAMode_RR( r_idx, r_base );
}
}
return PPCAMode_IR( 0, iselWordExpr_R(env,e) );
}
static PPCRH* iselWordExpr_RH ( ISelEnv* env, Bool syned, IRExpr* e )
{
PPCRH* ri = iselWordExpr_RH_wrk(env, syned, e);
switch (ri->tag) {
case Prh_Imm:
vassert(ri->Prh.Imm.syned == syned);
if (syned)
vassert(ri->Prh.Imm.imm16 != 0x8000);
return ri;
case Prh_Reg:
vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64));
vassert(hregIsVirtual(ri->Prh.Reg.reg));
return ri;
default:
vpanic("iselIntExpr_RH: unknown ppc RH tag");
}
}
static PPCRH* iselWordExpr_RH_wrk ( ISelEnv* env, Bool syned, IRExpr* e )
{
ULong u;
Long l;
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && env->mode64));
if (e->tag == Iex_Const) {
IRConst* con = e->Iex.Const.con;
switch (con->tag) {
case Ico_U64: vassert(env->mode64);
u = con->Ico.U64; break;
case Ico_U32: u = 0xFFFFFFFF & con->Ico.U32; break;
case Ico_U16: u = 0x0000FFFF & con->Ico.U16; break;
case Ico_U8: u = 0x000000FF & con->Ico.U8; break;
default: vpanic("iselIntExpr_RH.Iex_Const(ppch)");
}
l = (Long)u;
if (!syned && u <= 65535) {
return PPCRH_Imm(False, toUShort(u & 0xFFFF));
}
if (syned && l >= -32767 && l <= 32767) {
return PPCRH_Imm(True, toUShort(u & 0xFFFF));
}
}
return PPCRH_Reg( iselWordExpr_R ( env, e ) );
}
static PPCRI* iselWordExpr_RI ( ISelEnv* env, IRExpr* e )
{
PPCRI* ri = iselWordExpr_RI_wrk(env, e);
switch (ri->tag) {
case Pri_Imm:
return ri;
case Pri_Reg:
vassert(hregClass(ri->Pri.Reg) == HRcGPR(env->mode64));
vassert(hregIsVirtual(ri->Pri.Reg));
return ri;
default:
vpanic("iselIntExpr_RI: unknown ppc RI tag");
}
}
static PPCRI* iselWordExpr_RI_wrk ( ISelEnv* env, IRExpr* e )
{
Long l;
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && env->mode64));
if (e->tag == Iex_Const) {
IRConst* con = e->Iex.Const.con;
switch (con->tag) {
case Ico_U64: vassert(env->mode64);
l = (Long) con->Ico.U64; break;
case Ico_U32: l = (Long)(Int) con->Ico.U32; break;
case Ico_U16: l = (Long)(Int)(Short)con->Ico.U16; break;
case Ico_U8: l = (Long)(Int)(Char )con->Ico.U8; break;
default: vpanic("iselIntExpr_RI.Iex_Const(ppch)");
}
return PPCRI_Imm((ULong)l);
}
return PPCRI_Reg( iselWordExpr_R ( env, e ) );
}
static PPCRH* iselWordExpr_RH5u ( ISelEnv* env, IRExpr* e )
{
PPCRH* ri;
vassert(!env->mode64);
ri = iselWordExpr_RH5u_wrk(env, e);
switch (ri->tag) {
case Prh_Imm:
vassert(ri->Prh.Imm.imm16 >= 1 && ri->Prh.Imm.imm16 <= 31);
vassert(!ri->Prh.Imm.syned);
return ri;
case Prh_Reg:
vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64));
vassert(hregIsVirtual(ri->Prh.Reg.reg));
return ri;
default:
vpanic("iselIntExpr_RH5u: unknown ppc RI tag");
}
}
static PPCRH* iselWordExpr_RH5u_wrk ( ISelEnv* env, IRExpr* e )
{
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(ty == Ity_I8);
if (e->tag == Iex_Const
&& e->Iex.Const.con->tag == Ico_U8
&& e->Iex.Const.con->Ico.U8 >= 1
&& e->Iex.Const.con->Ico.U8 <= 31) {
return PPCRH_Imm(False, e->Iex.Const.con->Ico.U8);
}
return PPCRH_Reg( iselWordExpr_R ( env, e ) );
}
static PPCRH* iselWordExpr_RH6u ( ISelEnv* env, IRExpr* e )
{
PPCRH* ri;
vassert(env->mode64);
ri = iselWordExpr_RH6u_wrk(env, e);
switch (ri->tag) {
case Prh_Imm:
vassert(ri->Prh.Imm.imm16 >= 1 && ri->Prh.Imm.imm16 <= 63);
vassert(!ri->Prh.Imm.syned);
return ri;
case Prh_Reg:
vassert(hregClass(ri->Prh.Reg.reg) == HRcGPR(env->mode64));
vassert(hregIsVirtual(ri->Prh.Reg.reg));
return ri;
default:
vpanic("iselIntExpr_RH6u: unknown ppc64 RI tag");
}
}
static PPCRH* iselWordExpr_RH6u_wrk ( ISelEnv* env, IRExpr* e )
{
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(ty == Ity_I8);
if (e->tag == Iex_Const
&& e->Iex.Const.con->tag == Ico_U8
&& e->Iex.Const.con->Ico.U8 >= 1
&& e->Iex.Const.con->Ico.U8 <= 63) {
return PPCRH_Imm(False, e->Iex.Const.con->Ico.U8);
}
return PPCRH_Reg( iselWordExpr_R ( env, e ) );
}
static PPCCondCode iselCondCode ( ISelEnv* env, IRExpr* e )
{
return iselCondCode_wrk(env,e);
}
static PPCCondCode iselCondCode_wrk ( ISelEnv* env, IRExpr* e )
{
vassert(e);
vassert(typeOfIRExpr(env->type_env,e) == Ity_I1);
if (e->tag == Iex_Const && e->Iex.Const.con->Ico.U1 == True) {
HReg r_zero = newVRegI(env);
addInstr(env, PPCInstr_LI(r_zero, 0, env->mode64));
addInstr(env, PPCInstr_Cmp(False, True,
7, r_zero, PPCRH_Reg(r_zero)));
return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
}
if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_Not1) {
PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg);
cond.test = invertCondTest(cond.test);
return cond;
}
if (e->tag == Iex_Unop &&
(e->Iex.Unop.op == Iop_32to1 || e->Iex.Unop.op == Iop_64to1)) {
HReg src = iselWordExpr_R(env, e->Iex.Unop.arg);
HReg tmp = newVRegI(env);
addInstr(env, PPCInstr_Alu(Palu_AND, tmp,
src, PPCRH_Imm(False,1)));
addInstr(env, PPCInstr_Cmp(False, True,
7, tmp, PPCRH_Imm(False,1)));
return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
}
if (e->tag == Iex_Unop
&& e->Iex.Unop.op == Iop_CmpNEZ8) {
HReg arg = iselWordExpr_R(env, e->Iex.Unop.arg);
HReg tmp = newVRegI(env);
addInstr(env, PPCInstr_Alu(Palu_AND, tmp, arg,
PPCRH_Imm(False,0xFF)));
addInstr(env, PPCInstr_Cmp(False, True,
7, tmp, PPCRH_Imm(False,0)));
return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ );
}
if (e->tag == Iex_Unop
&& e->Iex.Unop.op == Iop_CmpNEZ32) {
HReg r1 = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Cmp(False, True,
7, r1, PPCRH_Imm(False,0)));
return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ );
}
if (e->tag == Iex_Binop
&& (e->Iex.Binop.op == Iop_CmpEQ32
|| e->Iex.Binop.op == Iop_CmpNE32
|| e->Iex.Binop.op == Iop_CmpLT32S
|| e->Iex.Binop.op == Iop_CmpLT32U
|| e->Iex.Binop.op == Iop_CmpLE32S
|| e->Iex.Binop.op == Iop_CmpLE32U)) {
Bool syned = (e->Iex.Binop.op == Iop_CmpLT32S ||
e->Iex.Binop.op == Iop_CmpLE32S);
HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1);
PPCRH* ri2 = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Cmp(syned, True,
7, r1, ri2));
switch (e->Iex.Binop.op) {
case Iop_CmpEQ32: return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
case Iop_CmpNE32: return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ );
case Iop_CmpLT32U: case Iop_CmpLT32S:
return mk_PPCCondCode( Pct_TRUE, Pcf_7LT );
case Iop_CmpLE32U: case Iop_CmpLE32S:
return mk_PPCCondCode( Pct_FALSE, Pcf_7GT );
default: vpanic("iselCondCode(ppc): CmpXX32");
}
}
if (e->tag == Iex_Unop
&& e->Iex.Unop.op == Iop_CmpNEZ64) {
if (!env->mode64) {
HReg hi, lo;
HReg tmp = newVRegI(env);
iselInt64Expr( &hi, &lo, env, e->Iex.Unop.arg );
addInstr(env, PPCInstr_Alu(Palu_OR, tmp, lo, PPCRH_Reg(hi)));
addInstr(env, PPCInstr_Cmp(False, True,
7, tmp,PPCRH_Imm(False,0)));
return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ );
} else {
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Cmp(False, False,
7, r_src,PPCRH_Imm(False,0)));
return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ );
}
}
if (e->tag == Iex_Binop
&& (e->Iex.Binop.op == Iop_CmpEQ64
|| e->Iex.Binop.op == Iop_CmpNE64
|| e->Iex.Binop.op == Iop_CmpLT64S
|| e->Iex.Binop.op == Iop_CmpLT64U
|| e->Iex.Binop.op == Iop_CmpLE64S
|| e->Iex.Binop.op == Iop_CmpLE64U)) {
Bool syned = (e->Iex.Binop.op == Iop_CmpLT64S ||
e->Iex.Binop.op == Iop_CmpLE64S);
HReg r1 = iselWordExpr_R(env, e->Iex.Binop.arg1);
PPCRH* ri2 = iselWordExpr_RH(env, syned, e->Iex.Binop.arg2);
vassert(env->mode64);
addInstr(env, PPCInstr_Cmp(syned, False,
7, r1, ri2));
switch (e->Iex.Binop.op) {
case Iop_CmpEQ64: return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
case Iop_CmpNE64: return mk_PPCCondCode( Pct_FALSE, Pcf_7EQ );
case Iop_CmpLT64U: return mk_PPCCondCode( Pct_TRUE, Pcf_7LT );
case Iop_CmpLE64U: return mk_PPCCondCode( Pct_FALSE, Pcf_7GT );
default: vpanic("iselCondCode(ppc): CmpXX64");
}
}
if (e->tag == Iex_RdTmp) {
HReg r_src = lookupIRTemp(env, e->Iex.RdTmp.tmp);
HReg src_masked = newVRegI(env);
addInstr(env,
PPCInstr_Alu(Palu_AND, src_masked,
r_src, PPCRH_Imm(False,1)));
addInstr(env,
PPCInstr_Cmp(False, True,
7, src_masked, PPCRH_Imm(False,1)));
return mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
}
vex_printf("iselCondCode(ppc): No such tag(%u)\n", e->tag);
ppIRExpr(e);
vpanic("iselCondCode(ppc)");
}
static void iselInt128Expr ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e )
{
vassert(env->mode64);
iselInt128Expr_wrk(rHi, rLo, env, e);
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(*rHi) == HRcGPR(env->mode64));
vassert(hregIsVirtual(*rHi));
vassert(hregClass(*rLo) == HRcGPR(env->mode64));
vassert(hregIsVirtual(*rLo));
}
static void iselInt128Expr_wrk ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e )
{
vassert(e);
vassert(typeOfIRExpr(env->type_env,e) == Ity_I128);
if (e->tag == Iex_RdTmp) {
lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp);
return;
}
if (e->tag == Iex_Binop) {
switch (e->Iex.Binop.op) {
case Iop_MullU64:
case Iop_MullS64: {
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
Bool syned = toBool(e->Iex.Binop.op == Iop_MullS64);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_MulL(False,
False, False,
tLo, r_srcL, r_srcR));
addInstr(env, PPCInstr_MulL(syned,
True, False,
tHi, r_srcL, r_srcR));
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_64HLto128:
*rHi = iselWordExpr_R(env, e->Iex.Binop.arg1);
*rLo = iselWordExpr_R(env, e->Iex.Binop.arg2);
return;
default:
break;
}
}
if (e->tag == Iex_Unop) {
switch (e->Iex.Unop.op) {
default:
break;
}
}
vex_printf("iselInt128Expr(ppc64): No such tag(%u)\n", e->tag);
ppIRExpr(e);
vpanic("iselInt128Expr(ppc64)");
}
static void iselInt128Expr_to_32x4 ( HReg* rHi, HReg* rMedHi, HReg* rMedLo,
HReg* rLo, ISelEnv* env, IRExpr* e )
{
vassert(!env->mode64);
iselInt128Expr_to_32x4_wrk(rHi, rMedHi, rMedLo, rLo, env, e);
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(*rHi) == HRcInt32);
vassert(hregIsVirtual(*rHi));
vassert(hregClass(*rMedHi) == HRcInt32);
vassert(hregIsVirtual(*rMedHi));
vassert(hregClass(*rMedLo) == HRcInt32);
vassert(hregIsVirtual(*rMedLo));
vassert(hregClass(*rLo) == HRcInt32);
vassert(hregIsVirtual(*rLo));
}
static void iselInt128Expr_to_32x4_wrk ( HReg* rHi, HReg* rMedHi,
HReg* rMedLo, HReg* rLo,
ISelEnv* env, IRExpr* e )
{
vassert(e);
vassert(typeOfIRExpr(env->type_env,e) == Ity_I128);
if (e->tag == Iex_RdTmp) {
lookupIRTempQuad( rHi, rMedHi, rMedLo, rLo, env, e->Iex.RdTmp.tmp);
return;
}
if (e->tag == Iex_Binop) {
IROp op_binop = e->Iex.Binop.op;
switch (op_binop) {
case Iop_64HLto128:
iselInt64Expr(rHi, rMedHi, env, e->Iex.Binop.arg1);
iselInt64Expr(rMedLo, rLo, env, e->Iex.Binop.arg2);
return;
default:
vex_printf("iselInt128Expr_to_32x4_wrk: Binop case 0x%x not found\n",
op_binop);
break;
}
}
vex_printf("iselInt128Expr_to_32x4_wrk: e->tag 0x%x not found\n", e->tag);
return;
}
static void iselInt64Expr ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e )
{
vassert(!env->mode64);
iselInt64Expr_wrk(rHi, rLo, env, e);
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(*rHi) == HRcInt32);
vassert(hregIsVirtual(*rHi));
vassert(hregClass(*rLo) == HRcInt32);
vassert(hregIsVirtual(*rLo));
}
static void iselInt64Expr_wrk ( HReg* rHi, HReg* rLo,
ISelEnv* env, IRExpr* e )
{
vassert(e);
vassert(typeOfIRExpr(env->type_env,e) == Ity_I64);
if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) {
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
HReg r_addr = iselWordExpr_R(env, e->Iex.Load.addr);
vassert(!env->mode64);
addInstr(env, PPCInstr_Load( 4,
tHi, PPCAMode_IR( 0, r_addr ),
False) );
addInstr(env, PPCInstr_Load( 4,
tLo, PPCAMode_IR( 4, r_addr ),
False) );
*rHi = tHi;
*rLo = tLo;
return;
}
if (e->tag == Iex_Const) {
ULong w64 = e->Iex.Const.con->Ico.U64;
UInt wHi = ((UInt)(w64 >> 32)) & 0xFFFFFFFF;
UInt wLo = ((UInt)w64) & 0xFFFFFFFF;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
vassert(e->Iex.Const.con->tag == Ico_U64);
addInstr(env, PPCInstr_LI(tHi, (Long)(Int)wHi, False));
addInstr(env, PPCInstr_LI(tLo, (Long)(Int)wLo, False));
*rHi = tHi;
*rLo = tLo;
return;
}
if (e->tag == Iex_RdTmp) {
lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp);
return;
}
if (e->tag == Iex_Get) {
PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset,
GuestStatePtr(False) );
PPCAMode* am_addr4 = advance4(env, am_addr);
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
addInstr(env, PPCInstr_Load( 4, tHi, am_addr, False ));
addInstr(env, PPCInstr_Load( 4, tLo, am_addr4, False ));
*rHi = tHi;
*rLo = tLo;
return;
}
if (e->tag == Iex_Mux0X) {
HReg e0Lo, e0Hi, eXLo, eXHi;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond);
HReg r_tmp = newVRegI(env);
iselInt64Expr(&e0Hi, &e0Lo, env, e->Iex.Mux0X.expr0);
iselInt64Expr(&eXHi, &eXLo, env, e->Iex.Mux0X.exprX);
addInstr(env, mk_iMOVds_RR(tHi,eXHi));
addInstr(env, mk_iMOVds_RR(tLo,eXLo));
addInstr(env, PPCInstr_Alu(Palu_AND,
r_tmp, r_cond, PPCRH_Imm(False,0xFF)));
addInstr(env, PPCInstr_Cmp(False, True,
7, r_tmp, PPCRH_Imm(False,0)));
addInstr(env, PPCInstr_CMov(cc,tHi,PPCRI_Reg(e0Hi)));
addInstr(env, PPCInstr_CMov(cc,tLo,PPCRI_Reg(e0Lo)));
*rHi = tHi;
*rLo = tLo;
return;
}
if (e->tag == Iex_Binop) {
IROp op_binop = e->Iex.Binop.op;
switch (op_binop) {
case Iop_MullU32:
case Iop_MullS32: {
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
Bool syned = toBool(op_binop == Iop_MullS32);
HReg r_srcL = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg r_srcR = iselWordExpr_R(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_MulL(False,
False, True,
tLo, r_srcL, r_srcR));
addInstr(env, PPCInstr_MulL(syned,
True, True,
tHi, r_srcL, r_srcR));
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_Or64:
case Iop_And64:
case Iop_Xor64: {
HReg xLo, xHi, yLo, yHi;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
PPCAluOp op = (op_binop == Iop_Or64) ? Palu_OR :
(op_binop == Iop_And64) ? Palu_AND : Palu_XOR;
iselInt64Expr(&xHi, &xLo, env, e->Iex.Binop.arg1);
iselInt64Expr(&yHi, &yLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Alu(op, tHi, xHi, PPCRH_Reg(yHi)));
addInstr(env, PPCInstr_Alu(op, tLo, xLo, PPCRH_Reg(yLo)));
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_Add64: {
HReg xLo, xHi, yLo, yHi;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
iselInt64Expr(&xHi, &xLo, env, e->Iex.Binop.arg1);
iselInt64Expr(&yHi, &yLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_AddSubC( True, True ,
tLo, xLo, yLo));
addInstr(env, PPCInstr_AddSubC( True, False,
tHi, xHi, yHi));
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_32HLto64:
*rHi = iselWordExpr_R(env, e->Iex.Binop.arg1);
*rLo = iselWordExpr_R(env, e->Iex.Binop.arg2);
return;
case Iop_F64toI64S: case Iop_F64toI64U: {
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
PPCAMode* four_r1 = PPCAMode_IR( 4, r1 );
HReg fsrc = iselDblExpr(env, e->Iex.Binop.arg2);
HReg ftmp = newVRegF(env);
vassert(!env->mode64);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_FpCftI(False, False,
(op_binop == Iop_F64toI64S) ? True : False,
True, ftmp, fsrc));
addInstr(env, PPCInstr_FpLdSt(False, 8, ftmp, zero_r1));
addInstr(env, PPCInstr_Load(4, tHi, zero_r1, False));
addInstr(env, PPCInstr_Load(4, tLo, four_r1, False));
add_to_sp( env, 16 );
*rHi = tHi;
*rLo = tLo;
return;
}
default:
break;
}
}
if (e->tag == Iex_Unop) {
switch (e->Iex.Unop.op) {
case Iop_CmpwNEZ64: {
HReg argHi, argLo;
HReg tmp1 = newVRegI(env);
HReg tmp2 = newVRegI(env);
iselInt64Expr(&argHi, &argLo, env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Alu(Palu_OR, tmp1, argHi, PPCRH_Reg(argLo)));
addInstr(env, PPCInstr_Unary(Pun_NEG,tmp2,tmp1));
addInstr(env, PPCInstr_Alu(Palu_OR, tmp2, tmp2, PPCRH_Reg(tmp1)));
addInstr(env, PPCInstr_Shft(Pshft_SAR, True,
tmp2, tmp2, PPCRH_Imm(False, 31)));
*rHi = tmp2;
*rLo = tmp2;
return;
}
case Iop_Left64: {
HReg argHi, argLo;
HReg zero32 = newVRegI(env);
HReg resHi = newVRegI(env);
HReg resLo = newVRegI(env);
iselInt64Expr(&argHi, &argLo, env, e->Iex.Unop.arg);
vassert(env->mode64 == False);
addInstr(env, PPCInstr_LI(zero32, 0, env->mode64));
addInstr(env, PPCInstr_AddSubC( False, True,
resLo, zero32, argLo ));
addInstr(env, PPCInstr_AddSubC( False, False,
resHi, zero32, argHi ));
addInstr(env, PPCInstr_Alu(Palu_OR, resLo, resLo, PPCRH_Reg(argLo)));
addInstr(env, PPCInstr_Alu(Palu_OR, resHi, resHi, PPCRH_Reg(argHi)));
*rHi = resHi;
*rLo = resLo;
return;
}
case Iop_32Sto64: {
HReg tHi = newVRegI(env);
HReg src = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Shft(Pshft_SAR, True,
tHi, src, PPCRH_Imm(False,31)));
*rHi = tHi;
*rLo = src;
return;
}
case Iop_32Uto64: {
HReg tHi = newVRegI(env);
HReg tLo = iselWordExpr_R(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_LI(tHi, 0, False));
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_128to64: {
HReg r_Hi = INVALID_HREG;
HReg r_MedHi = INVALID_HREG;
HReg r_MedLo = INVALID_HREG;
HReg r_Lo = INVALID_HREG;
iselInt128Expr_to_32x4(&r_Hi, &r_MedHi, &r_MedLo, &r_Lo,
env, e->Iex.Unop.arg);
*rHi = r_MedLo;
*rLo = r_Lo;
return;
}
case Iop_128HIto64: {
HReg r_Hi = INVALID_HREG;
HReg r_MedHi = INVALID_HREG;
HReg r_MedLo = INVALID_HREG;
HReg r_Lo = INVALID_HREG;
iselInt128Expr_to_32x4(&r_Hi, &r_MedHi, &r_MedLo, &r_Lo,
env, e->Iex.Unop.arg);
*rHi = r_Hi;
*rLo = r_MedHi;
return;
}
case Iop_V128HIto64:
case Iop_V128to64: {
HReg r_aligned16;
Int off = e->Iex.Unop.op==Iop_V128HIto64 ? 0 : 8;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
HReg vec = iselVecExpr(env, e->Iex.Unop.arg);
PPCAMode *am_off0, *am_offLO, *am_offHI;
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off0 = PPCAMode_IR( 0, r_aligned16 );
am_offHI = PPCAMode_IR( off, r_aligned16 );
am_offLO = PPCAMode_IR( off+4, r_aligned16 );
addInstr(env,
PPCInstr_AvLdSt( False, 16, vec, am_off0 ));
addInstr(env,
PPCInstr_Load( 4, tHi, am_offHI, False ));
addInstr(env,
PPCInstr_Load( 4, tLo, am_offLO, False ));
add_to_sp( env, 32 );
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_1Sto64: {
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
PPCCondCode cond = iselCondCode(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Set(cond,tLo));
addInstr(env, PPCInstr_Shft(Pshft_SHL, True,
tLo, tLo, PPCRH_Imm(False,31)));
addInstr(env, PPCInstr_Shft(Pshft_SAR, True,
tLo, tLo, PPCRH_Imm(False,31)));
addInstr(env, mk_iMOVds_RR(tHi, tLo));
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_Not64: {
HReg xLo, xHi;
HReg tmpLo = newVRegI(env);
HReg tmpHi = newVRegI(env);
iselInt64Expr(&xHi, &xLo, env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Unary(Pun_NOT,tmpLo,xLo));
addInstr(env, PPCInstr_Unary(Pun_NOT,tmpHi,xHi));
*rHi = tmpHi;
*rLo = tmpLo;
return;
}
case Iop_ReinterpF64asI64: {
PPCAMode *am_addr0, *am_addr1;
HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg);
HReg r_dstLo = newVRegI(env);
HReg r_dstHi = newVRegI(env);
sub_from_sp( env, 16 );
am_addr0 = PPCAMode_IR( 0, StackFramePtr(False) );
am_addr1 = PPCAMode_IR( 4, StackFramePtr(False) );
addInstr(env, PPCInstr_FpLdSt( False, 8,
fr_src, am_addr0 ));
addInstr(env, PPCInstr_Load( 4, r_dstHi,
am_addr0, False ));
addInstr(env, PPCInstr_Load( 4, r_dstLo,
am_addr1, False ));
*rHi = r_dstHi;
*rLo = r_dstLo;
add_to_sp( env, 16 );
return;
}
case Iop_ReinterpD64asI64: {
HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg);
PPCAMode *am_addr0, *am_addr1;
HReg r_dstLo = newVRegI(env);
HReg r_dstHi = newVRegI(env);
sub_from_sp( env, 16 );
am_addr0 = PPCAMode_IR( 0, StackFramePtr(False) );
am_addr1 = PPCAMode_IR( 4, StackFramePtr(False) );
addInstr(env, PPCInstr_FpLdSt( False, 8,
fr_src, am_addr0 ));
addInstr(env, PPCInstr_Load( 4, r_dstHi,
am_addr0, False ));
addInstr(env, PPCInstr_Load( 4, r_dstLo,
am_addr1, False ));
*rHi = r_dstHi;
*rLo = r_dstLo;
add_to_sp( env, 16 );
return;
}
case Iop_BCDtoDPB: {
PPCCondCode cc;
UInt argiregs;
HReg argregs[2];
Int argreg;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
HReg tmpHi;
HReg tmpLo;
ULong target;
Bool mode64 = env->mode64;
argregs[0] = hregPPC_GPR3(mode64);
argregs[1] = hregPPC_GPR4(mode64);
argiregs = 0;
argreg = 0;
iselInt64Expr( &tmpHi, &tmpLo, env, e->Iex.Unop.arg );
argiregs |= ( 1 << (argreg+3 ) );
addInstr( env, mk_iMOVds_RR( argregs[argreg++], tmpHi ) );
argiregs |= ( 1 << (argreg+3 ) );
addInstr( env, mk_iMOVds_RR( argregs[argreg], tmpLo ) );
cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
target = toUInt( Ptr_to_ULong(h_BCDtoDPB ) );
addInstr( env, PPCInstr_Call( cc, (Addr64)target, argiregs ) );
addInstr( env, mk_iMOVds_RR( tHi, argregs[argreg-1] ) );
addInstr( env, mk_iMOVds_RR( tLo, argregs[argreg] ) );
*rHi = tHi;
*rLo = tLo;
return;
}
case Iop_DPBtoBCD: {
PPCCondCode cc;
UInt argiregs;
HReg argregs[2];
Int argreg;
HReg tLo = newVRegI(env);
HReg tHi = newVRegI(env);
HReg tmpHi;
HReg tmpLo;
ULong target;
Bool mode64 = env->mode64;
argregs[0] = hregPPC_GPR3(mode64);
argregs[1] = hregPPC_GPR4(mode64);
argiregs = 0;
argreg = 0;
iselInt64Expr(&tmpHi, &tmpLo, env, e->Iex.Unop.arg);
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg++], tmpHi ));
argiregs |= (1 << (argreg+3));
addInstr(env, mk_iMOVds_RR( argregs[argreg], tmpLo));
cc = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
target = toUInt( Ptr_to_ULong( h_DPBtoBCD ) );
addInstr(env, PPCInstr_Call( cc, (Addr64)target, argiregs ) );
addInstr(env, mk_iMOVds_RR(tHi, argregs[argreg-1]));
addInstr(env, mk_iMOVds_RR(tLo, argregs[argreg]));
*rHi = tHi;
*rLo = tLo;
return;
}
default:
break;
}
}
vex_printf("iselInt64Expr(ppc): No such tag(%u)\n", e->tag);
ppIRExpr(e);
vpanic("iselInt64Expr(ppc)");
}
static HReg iselFltExpr ( ISelEnv* env, IRExpr* e )
{
HReg r = iselFltExpr_wrk( env, e );
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(r) == HRcFlt64);
vassert(hregIsVirtual(r));
return r;
}
static HReg iselFltExpr_wrk ( ISelEnv* env, IRExpr* e )
{
Bool mode64 = env->mode64;
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(ty == Ity_F32);
if (e->tag == Iex_RdTmp) {
return lookupIRTemp(env, e->Iex.RdTmp.tmp);
}
if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) {
PPCAMode* am_addr;
HReg r_dst = newVRegF(env);
vassert(e->Iex.Load.ty == Ity_F32);
am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_F32);
addInstr(env, PPCInstr_FpLdSt(True, 4, r_dst, am_addr));
return r_dst;
}
if (e->tag == Iex_Get) {
HReg r_dst = newVRegF(env);
PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset,
GuestStatePtr(env->mode64) );
addInstr(env, PPCInstr_FpLdSt( True, 4, r_dst, am_addr ));
return r_dst;
}
if (e->tag == Iex_Unop && e->Iex.Unop.op == Iop_TruncF64asF32) {
/* This is quite subtle. The only way to do the relevant
truncation is to do a single-precision store and then a
double precision load to get it back into a register. The
problem is, if the data is then written to memory a second
time, as in
STbe(...) = TruncF64asF32(...)
then will the second truncation further alter the value? The
answer is no: flds (as generated here) followed by fsts
(generated for the STbe) is the identity function on 32-bit
floats, so we are safe.
Another upshot of this is that if iselStmt can see the
entirety of
STbe(...) = TruncF64asF32(arg)
then it can short circuit having to deal with TruncF64asF32
individually; instead just compute arg into a 64-bit FP
register and do 'fsts' (since that itself does the
truncation).
We generate pretty poor code here (should be ok both for
32-bit and 64-bit mode); but it is expected that for the most
part the latter optimisation will apply and hence this code
will not often be used.
*/
HReg fsrc = iselDblExpr(env, e->Iex.Unop.arg);
HReg fdst = newVRegF(env);
PPCAMode* zero_r1 = PPCAMode_IR( 0, StackFramePtr(env->mode64) );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_FpLdSt( False, 4,
fsrc, zero_r1 ));
addInstr(env, PPCInstr_FpLdSt( True, 4,
fdst, zero_r1 ));
add_to_sp( env, 16 );
return fdst;
}
if (e->tag == Iex_Binop && e->Iex.Binop.op == Iop_I64UtoF32) {
if (mode64) {
HReg fdst = newVRegF(env);
HReg isrc = iselWordExpr_R(env, e->Iex.Binop.arg2);
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_Store(8, zero_r1, isrc, True));
addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1));
addInstr(env, PPCInstr_FpCftI(True, False,
False, False,
fdst, fdst));
add_to_sp( env, 16 );
return fdst;
} else {
HReg fdst = newVRegF(env);
HReg isrcHi, isrcLo;
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
PPCAMode* four_r1 = PPCAMode_IR( 4, r1 );
iselInt64Expr(&isrcHi, &isrcLo, env, e->Iex.Binop.arg2);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_Store(4, zero_r1, isrcHi, False));
addInstr(env, PPCInstr_Store(4, four_r1, isrcLo, False));
addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1));
addInstr(env, PPCInstr_FpCftI(True, False,
False, False,
fdst, fdst));
add_to_sp( env, 16 );
return fdst;
}
}
vex_printf("iselFltExpr(ppc): No such tag(%u)\n", e->tag);
ppIRExpr(e);
vpanic("iselFltExpr_wrk(ppc)");
}
static HReg iselDblExpr ( ISelEnv* env, IRExpr* e )
{
HReg r = iselDblExpr_wrk( env, e );
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(r) == HRcFlt64);
vassert(hregIsVirtual(r));
return r;
}
static HReg iselDblExpr_wrk ( ISelEnv* env, IRExpr* e )
{
Bool mode64 = env->mode64;
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(e);
vassert(ty == Ity_F64);
if (e->tag == Iex_RdTmp) {
return lookupIRTemp(env, e->Iex.RdTmp.tmp);
}
if (e->tag == Iex_Const) {
union { UInt u32x2[2]; ULong u64; Double f64; } u;
vassert(sizeof(u) == 8);
vassert(sizeof(u.u64) == 8);
vassert(sizeof(u.f64) == 8);
vassert(sizeof(u.u32x2) == 8);
if (e->Iex.Const.con->tag == Ico_F64) {
u.f64 = e->Iex.Const.con->Ico.F64;
}
else if (e->Iex.Const.con->tag == Ico_F64i) {
u.u64 = e->Iex.Const.con->Ico.F64i;
}
else
vpanic("iselDblExpr(ppc): const");
if (!mode64) {
HReg r_srcHi = newVRegI(env);
HReg r_srcLo = newVRegI(env);
addInstr(env, PPCInstr_LI(r_srcHi, u.u32x2[0], mode64));
addInstr(env, PPCInstr_LI(r_srcLo, u.u32x2[1], mode64));
return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo );
} else {
HReg r_src = newVRegI(env);
addInstr(env, PPCInstr_LI(r_src, u.u64, mode64));
return mk_LoadR64toFPR( env, r_src );
}
}
if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) {
HReg r_dst = newVRegF(env);
PPCAMode* am_addr;
vassert(e->Iex.Load.ty == Ity_F64);
am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_F64);
addInstr(env, PPCInstr_FpLdSt(True, 8, r_dst, am_addr));
return r_dst;
}
if (e->tag == Iex_Get) {
HReg r_dst = newVRegF(env);
PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset,
GuestStatePtr(mode64) );
addInstr(env, PPCInstr_FpLdSt( True, 8, r_dst, am_addr ));
return r_dst;
}
if (e->tag == Iex_Qop) {
PPCFpOp fpop = Pfp_INVALID;
switch (e->Iex.Qop.details->op) {
case Iop_MAddF64: fpop = Pfp_MADDD; break;
case Iop_MAddF64r32: fpop = Pfp_MADDS; break;
case Iop_MSubF64: fpop = Pfp_MSUBD; break;
case Iop_MSubF64r32: fpop = Pfp_MSUBS; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg r_dst = newVRegF(env);
HReg r_srcML = iselDblExpr(env, e->Iex.Qop.details->arg2);
HReg r_srcMR = iselDblExpr(env, e->Iex.Qop.details->arg3);
HReg r_srcAcc = iselDblExpr(env, e->Iex.Qop.details->arg4);
set_FPU_rounding_mode( env, e->Iex.Qop.details->arg1 );
addInstr(env, PPCInstr_FpMulAcc(fpop, r_dst,
r_srcML, r_srcMR, r_srcAcc));
return r_dst;
}
}
if (e->tag == Iex_Triop) {
IRTriop *triop = e->Iex.Triop.details;
PPCFpOp fpop = Pfp_INVALID;
switch (triop->op) {
case Iop_AddF64: fpop = Pfp_ADDD; break;
case Iop_SubF64: fpop = Pfp_SUBD; break;
case Iop_MulF64: fpop = Pfp_MULD; break;
case Iop_DivF64: fpop = Pfp_DIVD; break;
case Iop_AddF64r32: fpop = Pfp_ADDS; break;
case Iop_SubF64r32: fpop = Pfp_SUBS; break;
case Iop_MulF64r32: fpop = Pfp_MULS; break;
case Iop_DivF64r32: fpop = Pfp_DIVS; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg r_dst = newVRegF(env);
HReg r_srcL = iselDblExpr(env, triop->arg2);
HReg r_srcR = iselDblExpr(env, triop->arg3);
set_FPU_rounding_mode( env, triop->arg1 );
addInstr(env, PPCInstr_FpBinary(fpop, r_dst, r_srcL, r_srcR));
return r_dst;
}
switch (triop->op) {
case Iop_QuantizeD64: fpop = Pfp_DQUA; break;
case Iop_SignificanceRoundD64: fpop = Pfp_RRDTR; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg r_dst = newVRegF(env);
HReg r_srcL = iselDblExpr(env, triop->arg2);
HReg r_srcR = iselDblExpr(env, triop->arg3);
PPCRI* rmc = iselWordExpr_RI(env, triop->arg1);
addInstr(env, PPCInstr_DfpQuantize(fpop, r_dst, r_srcL, r_srcR, rmc));
return r_dst;
}
}
if (e->tag == Iex_Binop) {
PPCFpOp fpop = Pfp_INVALID;
switch (e->Iex.Binop.op) {
case Iop_SqrtF64: fpop = Pfp_SQRT; break;
case Iop_I64StoD64: fpop = Pfp_DCFFIX; break;
case Iop_D64toI64S: fpop = Pfp_DCTFIX; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg fr_dst = newVRegF(env);
HReg fr_src = iselDblExpr(env, e->Iex.Binop.arg2);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
addInstr(env, PPCInstr_FpUnary(fpop, fr_dst, fr_src));
return fr_dst;
}
}
if (e->tag == Iex_Binop) {
if (e->Iex.Binop.op == Iop_RoundF64toF32) {
HReg r_dst = newVRegF(env);
HReg r_src = iselDblExpr(env, e->Iex.Binop.arg2);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
addInstr(env, PPCInstr_FpRSP(r_dst, r_src));
return r_dst;
}
if (e->Iex.Binop.op == Iop_I64StoF64 || e->Iex.Binop.op == Iop_I64UtoF64) {
if (mode64) {
HReg fdst = newVRegF(env);
HReg isrc = iselWordExpr_R(env, e->Iex.Binop.arg2);
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_Store(8, zero_r1, isrc, True));
addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1));
addInstr(env, PPCInstr_FpCftI(True, False,
e->Iex.Binop.op == Iop_I64StoF64,
True,
fdst, fdst));
add_to_sp( env, 16 );
return fdst;
} else {
HReg fdst = newVRegF(env);
HReg isrcHi, isrcLo;
HReg r1 = StackFramePtr(env->mode64);
PPCAMode* zero_r1 = PPCAMode_IR( 0, r1 );
PPCAMode* four_r1 = PPCAMode_IR( 4, r1 );
iselInt64Expr(&isrcHi, &isrcLo, env, e->Iex.Binop.arg2);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
sub_from_sp( env, 16 );
addInstr(env, PPCInstr_Store(4, zero_r1, isrcHi, False));
addInstr(env, PPCInstr_Store(4, four_r1, isrcLo, False));
addInstr(env, PPCInstr_FpLdSt(True, 8, fdst, zero_r1));
addInstr(env, PPCInstr_FpCftI(True, False,
e->Iex.Binop.op == Iop_I64StoF64,
True,
fdst, fdst));
add_to_sp( env, 16 );
return fdst;
}
}
}
if (e->tag == Iex_Unop) {
PPCFpOp fpop = Pfp_INVALID;
switch (e->Iex.Unop.op) {
case Iop_NegF64: fpop = Pfp_NEG; break;
case Iop_AbsF64: fpop = Pfp_ABS; break;
case Iop_Est5FRSqrt: fpop = Pfp_RSQRTE; break;
case Iop_RoundF64toF64_NegINF: fpop = Pfp_FRIM; break;
case Iop_RoundF64toF64_PosINF: fpop = Pfp_FRIP; break;
case Iop_RoundF64toF64_NEAREST: fpop = Pfp_FRIN; break;
case Iop_RoundF64toF64_ZERO: fpop = Pfp_FRIZ; break;
case Iop_ExtractExpD64: fpop = Pfp_DXEX; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg fr_dst = newVRegF(env);
HReg fr_src = iselDblExpr(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_FpUnary(fpop, fr_dst, fr_src));
return fr_dst;
}
}
if (e->tag == Iex_Unop) {
switch (e->Iex.Unop.op) {
case Iop_ReinterpI64asF64: {
if (!mode64) {
HReg r_srcHi, r_srcLo;
iselInt64Expr( &r_srcHi, &r_srcLo, env, e->Iex.Unop.arg);
return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo );
} else {
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
return mk_LoadR64toFPR( env, r_src );
}
}
case Iop_F32toF64: {
if (e->Iex.Unop.arg->tag == Iex_Unop &&
e->Iex.Unop.arg->Iex.Unop.op == Iop_ReinterpI32asF32 ) {
e = e->Iex.Unop.arg;
HReg src = iselWordExpr_R(env, e->Iex.Unop.arg);
HReg fr_dst = newVRegF(env);
PPCAMode *am_addr;
sub_from_sp( env, 16 );
am_addr = PPCAMode_IR( 0, StackFramePtr(env->mode64) );
addInstr(env, PPCInstr_Store( 4, am_addr, src, env->mode64 ));
addInstr(env, PPCInstr_FpLdSt(True, 4, fr_dst, am_addr));
add_to_sp( env, 16 );
return fr_dst;
}
HReg res = iselFltExpr(env, e->Iex.Unop.arg);
return res;
}
default:
break;
}
}
if (e->tag == Iex_Mux0X) {
if (ty == Ity_F64
&& typeOfIRExpr(env->type_env,e->Iex.Mux0X.cond) == Ity_I8) {
PPCCondCode cc = mk_PPCCondCode( Pct_TRUE, Pcf_7EQ );
HReg r_cond = iselWordExpr_R(env, e->Iex.Mux0X.cond);
HReg frX = iselDblExpr(env, e->Iex.Mux0X.exprX);
HReg fr0 = iselDblExpr(env, e->Iex.Mux0X.expr0);
HReg fr_dst = newVRegF(env);
HReg r_tmp = newVRegI(env);
addInstr(env, PPCInstr_Alu(Palu_AND, r_tmp,
r_cond, PPCRH_Imm(False,0xFF)));
addInstr(env, PPCInstr_FpUnary( Pfp_MOV, fr_dst, frX ));
addInstr(env, PPCInstr_Cmp(False, True,
7, r_tmp, PPCRH_Imm(False,0)));
addInstr(env, PPCInstr_FpCMov( cc, fr_dst, fr0 ));
return fr_dst;
}
}
vex_printf("iselDblExpr(ppc): No such tag(%u)\n", e->tag);
ppIRExpr(e);
vpanic("iselDblExpr_wrk(ppc)");
}
static HReg iselDfp64Expr(ISelEnv* env, IRExpr* e)
{
HReg r = iselDfp64Expr_wrk( env, e );
vassert(hregClass(r) == HRcFlt64);
vassert( hregIsVirtual(r) );
return r;
}
static HReg iselDfp64Expr_wrk(ISelEnv* env, IRExpr* e)
{
Bool mode64 = env->mode64;
IRType ty = typeOfIRExpr( env->type_env, e );
HReg r_dstHi, r_dstLo;
vassert( e );
vassert( ty == Ity_D64 );
if (e->tag == Iex_RdTmp) {
return lookupIRTemp( env, e->Iex.RdTmp.tmp );
}
if (e->tag == Iex_Get) {
HReg r_dst = newVRegF( env );
PPCAMode* am_addr = PPCAMode_IR( e->Iex.Get.offset,
GuestStatePtr(mode64) );
addInstr( env, PPCInstr_FpLdSt( True, 8, r_dst, am_addr ) );
return r_dst;
}
if (e->tag == Iex_Qop) {
HReg r_dst = newVRegF( env );
return r_dst;
}
if (e->tag == Iex_Unop) {
HReg fr_dst = newVRegF(env);
switch (e->Iex.Unop.op) {
case Iop_ReinterpI64asD64: {
if (!mode64) {
HReg r_srcHi, r_srcLo;
iselInt64Expr( &r_srcHi, &r_srcLo, env, e->Iex.Unop.arg);
return mk_LoadRR32toFPR( env, r_srcHi, r_srcLo );
} else {
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
return mk_LoadR64toFPR( env, r_src );
}
}
case Iop_ExtractExpD64: {
HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Dfp64Unary(Pfp_DXEX, fr_dst, fr_src));
return fr_dst;
}
case Iop_ExtractExpD128: {
HReg r_srcHi;
HReg r_srcLo;
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_ExtractExpD128(Pfp_DXEXQ, fr_dst,
r_srcHi, r_srcLo));
return fr_dst;
}
case Iop_D32toD64: {
HReg fr_src = iselDfp64Expr(env, e->Iex.Unop.arg);
addInstr(env, PPCInstr_Dfp64Unary(Pfp_DCTDP, fr_dst, fr_src));
return fr_dst;
}
case Iop_D128HItoD64:
iselDfp128Expr( &r_dstHi, &r_dstLo, env, e->Iex.Unop.arg );
return r_dstHi;
case Iop_D128LOtoD64:
iselDfp128Expr( &r_dstHi, &r_dstLo, env, e->Iex.Unop.arg );
return r_dstLo;
case Iop_InsertExpD64: {
HReg fr_srcL = iselDblExpr(env, e->Iex.Binop.arg1);
HReg fr_srcR = iselDblExpr(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Dfp64Binary(Pfp_DIEX, fr_dst, fr_srcL,
fr_srcR));
return fr_dst;
}
default:
vex_printf( "ERROR: iselDfp64Expr_wrk, UNKNOWN unop case %d\n",
e->Iex.Unop.op );
}
}
if (e->tag == Iex_Binop) {
switch (e->Iex.Binop.op) {
case Iop_D128toI64S: {
PPCFpOp fpop = Pfp_DCTFIXQ;
HReg fr_dst = newVRegF(env);
HReg r_srcHi = newVRegF(env);
HReg r_srcLo = newVRegF(env);
set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 );
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo));
return fr_dst;
}
case Iop_D128toD64: {
PPCFpOp fpop = Pfp_DRDPQ;
HReg fr_dst = newVRegF(env);
HReg r_srcHi = newVRegF(env);
HReg r_srcLo = newVRegF(env);
set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 );
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo));
return fr_dst;
}
break;
default:
break;
}
if (e->Iex.Unop.op == Iop_RoundD64toInt) {
HReg fr_dst = newVRegF(env);
HReg fr_src = newVRegF(env);
PPCRI* r_rmc = iselWordExpr_RI(env, e->Iex.Binop.arg1);
fr_src = iselDfp64Expr(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_DfpRound(fr_dst, fr_src, r_rmc));
return fr_dst;
}
}
if (e->tag == Iex_Binop) {
PPCFpOp fpop = Pfp_INVALID;
HReg fr_dst = newVRegF(env);
switch (e->Iex.Binop.op) {
case Iop_D64toD32: fpop = Pfp_DRSP; break;
case Iop_I64StoD64: fpop = Pfp_DCFFIX; break;
case Iop_D64toI64S: fpop = Pfp_DCTFIX; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg fr_src = iselDfp64Expr(env, e->Iex.Binop.arg2);
set_FPU_DFP_rounding_mode( env, e->Iex.Binop.arg1 );
addInstr(env, PPCInstr_Dfp64Unary(fpop, fr_dst, fr_src));
return fr_dst;
}
switch (e->Iex.Binop.op) {
case Iop_ShlD64: fpop = Pfp_DSCLI; break;
case Iop_ShrD64: fpop = Pfp_DSCRI; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg fr_src = iselDfp64Expr(env, e->Iex.Binop.arg1);
PPCRI* shift = iselWordExpr_RI(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_DfpShift(fpop, fr_dst, fr_src, shift));
return fr_dst;
}
switch (e->Iex.Binop.op) {
case Iop_InsertExpD64:
fpop = Pfp_DIEX;
break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg fr_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1);
HReg fr_srcR = iselDfp64Expr(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Dfp64Binary(fpop, fr_dst, fr_srcL, fr_srcR));
return fr_dst;
}
}
if (e->tag == Iex_Triop) {
IRTriop *triop = e->Iex.Triop.details;
PPCFpOp fpop = Pfp_INVALID;
switch (triop->op) {
case Iop_AddD64:
fpop = Pfp_DFPADD;
break;
case Iop_SubD64:
fpop = Pfp_DFPSUB;
break;
case Iop_MulD64:
fpop = Pfp_DFPMUL;
break;
case Iop_DivD64:
fpop = Pfp_DFPDIV;
break;
default:
break;
}
if (fpop != Pfp_INVALID) {
HReg r_dst = newVRegF( env );
HReg r_srcL = iselDfp64Expr( env, triop->arg2 );
HReg r_srcR = iselDfp64Expr( env, triop->arg3 );
set_FPU_DFP_rounding_mode( env, triop->arg1 );
addInstr( env, PPCInstr_Dfp64Binary( fpop, r_dst, r_srcL, r_srcR ) );
return r_dst;
}
switch (triop->op) {
case Iop_QuantizeD64: fpop = Pfp_DQUA; break;
case Iop_SignificanceRoundD64: fpop = Pfp_RRDTR; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg r_dst = newVRegF(env);
HReg r_srcL = iselDfp64Expr(env, triop->arg2);
HReg r_srcR = iselDfp64Expr(env, triop->arg3);
PPCRI* rmc = iselWordExpr_RI(env, triop->arg1);
addInstr(env, PPCInstr_DfpQuantize(fpop, r_dst, r_srcL, r_srcR,
rmc));
return r_dst;
}
}
ppIRExpr( e );
vpanic( "iselDfp64Expr_wrk(ppc)" );
}
static void iselDfp128Expr(HReg* rHi, HReg* rLo, ISelEnv* env, IRExpr* e)
{
iselDfp128Expr_wrk( rHi, rLo, env, e );
vassert( hregIsVirtual(*rHi) );
vassert( hregIsVirtual(*rLo) );
}
static void iselDfp128Expr_wrk(HReg* rHi, HReg *rLo, ISelEnv* env, IRExpr* e)
{
vassert( e );
vassert( typeOfIRExpr(env->type_env,e) == Ity_D128 );
if (e->tag == Iex_RdTmp) {
lookupIRTempPair( rHi, rLo, env, e->Iex.RdTmp.tmp );
return;
}
if (e->tag == Iex_Unop) {
PPCFpOp fpop = Pfp_INVALID;
HReg r_dstHi = newVRegF(env);
HReg r_dstLo = newVRegF(env);
if (e->Iex.Unop.op == Iop_I64StoD128) {
HReg r_src = iselDfp64Expr(env, e->Iex.Unop.arg);
fpop = Pfp_DCFFIXQ;
addInstr(env, PPCInstr_DfpI64StoD128(fpop, r_dstHi, r_dstLo,
r_src));
}
if (e->Iex.Unop.op == Iop_D64toD128) {
HReg r_src = iselDfp64Expr(env, e->Iex.Unop.arg);
fpop = Pfp_DCTQPQ;
addInstr(env, PPCInstr_Dfp128Unary(fpop, r_dstHi, r_dstLo,
r_src, r_src));
}
*rHi = r_dstHi;
*rLo = r_dstLo;
return;
}
if (e->tag == Iex_Binop) {
HReg r_srcHi;
HReg r_srcLo;
switch (e->Iex.Binop.op) {
case Iop_D64HLtoD128:
r_srcHi = iselDfp64Expr( env, e->Iex.Binop.arg1 );
r_srcLo = iselDfp64Expr( env, e->Iex.Binop.arg2 );
*rHi = r_srcHi;
*rLo = r_srcLo;
return;
break;
case Iop_D128toD64: {
PPCFpOp fpop = Pfp_DRDPQ;
HReg fr_dst = newVRegF(env);
set_FPU_rounding_mode( env, e->Iex.Binop.arg1 );
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_DfpD128toD64(fpop, fr_dst, r_srcHi, r_srcLo));
*rHi = fr_dst;
*rLo = fr_dst;
return;
}
case Iop_ShlD128:
case Iop_ShrD128: {
HReg fr_dst_hi = newVRegF(env);
HReg fr_dst_lo = newVRegF(env);
PPCRI* shift = iselWordExpr_RI(env, e->Iex.Binop.arg2);
PPCFpOp fpop = Pfp_DSCLIQ;
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg1);
if (e->Iex.Binop.op == Iop_ShrD128)
fpop = Pfp_DSCRIQ;
addInstr(env, PPCInstr_DfpShift128(fpop, fr_dst_hi, fr_dst_lo,
r_srcHi, r_srcLo, shift));
*rHi = fr_dst_hi;
*rLo = fr_dst_lo;
return;
}
case Iop_RoundD128toInt: {
HReg r_dstHi = newVRegF(env);
HReg r_dstLo = newVRegF(env);
PPCRI* r_rmc = iselWordExpr_RI(env, e->Iex.Binop.arg1);
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_DfpRound128(r_dstHi, r_dstLo,
r_srcHi, r_srcLo, r_rmc));
*rHi = r_dstHi;
*rLo = r_dstLo;
return;
}
case Iop_InsertExpD128: {
HReg r_dstHi = newVRegF(env);
HReg r_dstLo = newVRegF(env);
HReg r_srcL = newVRegF(env);
r_srcL = iselDfp64Expr(env, e->Iex.Binop.arg1);
iselDfp128Expr(&r_srcHi, &r_srcLo, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_InsertExpD128(Pfp_DIEXQ,
r_dstHi, r_dstLo,
r_srcL, r_srcHi, r_srcLo));
*rHi = r_dstHi;
*rLo = r_dstLo;
return;
}
default:
vex_printf( "ERROR: iselDfp128Expr_wrk, UNKNOWN binop case %d\n",
e->Iex.Binop.op );
break;
}
}
if (e->tag == Iex_Triop) {
IRTriop *triop = e->Iex.Triop.details;
PPCFpOp fpop = Pfp_INVALID;
switch (triop->op) {
case Iop_AddD128:
fpop = Pfp_DFPADDQ;
break;
case Iop_SubD128:
fpop = Pfp_DFPSUBQ;
break;
case Iop_MulD128:
fpop = Pfp_DFPMULQ;
break;
case Iop_DivD128:
fpop = Pfp_DFPDIVQ;
break;
default:
break;
}
if (fpop != Pfp_INVALID) {
HReg r_dstHi = newVRegV( env );
HReg r_dstLo = newVRegV( env );
HReg r_srcRHi = newVRegV( env );
HReg r_srcRLo = newVRegV( env );
iselDfp128Expr( &r_dstHi, &r_dstLo, env, triop->arg2 );
iselDfp128Expr( &r_srcRHi, &r_srcRLo, env, triop->arg3 );
set_FPU_rounding_mode( env, triop->arg1 );
addInstr( env,
PPCInstr_Dfp128Binary( fpop, r_dstHi, r_dstLo,
r_srcRHi, r_srcRLo ) );
*rHi = r_dstHi;
*rLo = r_dstLo;
return;
}
switch (triop->op) {
case Iop_QuantizeD128: fpop = Pfp_DQUAQ; break;
case Iop_SignificanceRoundD128: fpop = Pfp_DRRNDQ; break;
default: break;
}
if (fpop != Pfp_INVALID) {
HReg r_dstHi = newVRegF(env);
HReg r_dstLo = newVRegF(env);
HReg r_srcHi = newVRegF(env);
HReg r_srcLo = newVRegF(env);
PPCRI* rmc = iselWordExpr_RI(env, triop->arg1);
iselDfp128Expr(&r_dstHi, &r_dstLo, env, triop->arg2);
iselDfp128Expr(&r_srcHi, &r_srcLo, env, triop->arg3);
addInstr(env, PPCInstr_DfpQuantize128(fpop, r_dstHi, r_dstLo,
r_srcHi, r_srcLo, rmc));
*rHi = r_dstHi;
*rLo = r_dstLo;
return;
}
}
ppIRExpr( e );
vpanic( "iselDfp128Expr(ppc64)" );
}
static HReg iselVecExpr ( ISelEnv* env, IRExpr* e )
{
HReg r = iselVecExpr_wrk( env, e );
# if 0
vex_printf("\n"); ppIRExpr(e); vex_printf("\n");
# endif
vassert(hregClass(r) == HRcVec128);
vassert(hregIsVirtual(r));
return r;
}
static HReg iselVecExpr_wrk ( ISelEnv* env, IRExpr* e )
{
Bool mode64 = env->mode64;
PPCAvOp op = Pav_INVALID;
PPCAvFpOp fpop = Pavfp_INVALID;
IRType ty = typeOfIRExpr(env->type_env,e);
vassert(e);
vassert(ty == Ity_V128);
if (e->tag == Iex_RdTmp) {
return lookupIRTemp(env, e->Iex.RdTmp.tmp);
}
if (e->tag == Iex_Get) {
HReg dst = newVRegV(env);
addInstr(env,
PPCInstr_AvLdSt( True, 16, dst,
PPCAMode_IR( e->Iex.Get.offset,
GuestStatePtr(mode64) )));
return dst;
}
if (e->tag == Iex_Load && e->Iex.Load.end == Iend_BE) {
PPCAMode* am_addr;
HReg v_dst = newVRegV(env);
vassert(e->Iex.Load.ty == Ity_V128);
am_addr = iselWordExpr_AMode(env, e->Iex.Load.addr, Ity_V128);
addInstr(env, PPCInstr_AvLdSt( True, 16, v_dst, am_addr));
return v_dst;
}
if (e->tag == Iex_Unop) {
switch (e->Iex.Unop.op) {
case Iop_NotV128: {
HReg arg = iselVecExpr(env, e->Iex.Unop.arg);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, arg));
return dst;
}
case Iop_CmpNEZ8x16: {
HReg arg = iselVecExpr(env, e->Iex.Unop.arg);
HReg zero = newVRegV(env);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero));
addInstr(env, PPCInstr_AvBin8x16(Pav_CMPEQU, dst, arg, zero));
addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst));
return dst;
}
case Iop_CmpNEZ16x8: {
HReg arg = iselVecExpr(env, e->Iex.Unop.arg);
HReg zero = newVRegV(env);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero));
addInstr(env, PPCInstr_AvBin16x8(Pav_CMPEQU, dst, arg, zero));
addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst));
return dst;
}
case Iop_CmpNEZ32x4: {
HReg arg = iselVecExpr(env, e->Iex.Unop.arg);
HReg zero = newVRegV(env);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBinary(Pav_XOR, zero, zero, zero));
addInstr(env, PPCInstr_AvBin32x4(Pav_CMPEQU, dst, arg, zero));
addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst));
return dst;
}
case Iop_Recip32Fx4: fpop = Pavfp_RCPF; goto do_32Fx4_unary;
case Iop_RSqrt32Fx4: fpop = Pavfp_RSQRTF; goto do_32Fx4_unary;
case Iop_I32UtoFx4: fpop = Pavfp_CVTU2F; goto do_32Fx4_unary;
case Iop_I32StoFx4: fpop = Pavfp_CVTS2F; goto do_32Fx4_unary;
case Iop_QFtoI32Ux4_RZ: fpop = Pavfp_QCVTF2U; goto do_32Fx4_unary;
case Iop_QFtoI32Sx4_RZ: fpop = Pavfp_QCVTF2S; goto do_32Fx4_unary;
case Iop_RoundF32x4_RM: fpop = Pavfp_ROUNDM; goto do_32Fx4_unary;
case Iop_RoundF32x4_RP: fpop = Pavfp_ROUNDP; goto do_32Fx4_unary;
case Iop_RoundF32x4_RN: fpop = Pavfp_ROUNDN; goto do_32Fx4_unary;
case Iop_RoundF32x4_RZ: fpop = Pavfp_ROUNDZ; goto do_32Fx4_unary;
do_32Fx4_unary:
{
HReg arg = iselVecExpr(env, e->Iex.Unop.arg);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvUn32Fx4(fpop, dst, arg));
return dst;
}
case Iop_32UtoV128: {
HReg r_aligned16, r_zeros;
HReg r_src = iselWordExpr_R(env, e->Iex.Unop.arg);
HReg dst = newVRegV(env);
PPCAMode *am_off0, *am_off4, *am_off8, *am_off12;
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off0 = PPCAMode_IR( 0, r_aligned16 );
am_off4 = PPCAMode_IR( 4, r_aligned16 );
am_off8 = PPCAMode_IR( 8, r_aligned16 );
am_off12 = PPCAMode_IR( 12, r_aligned16 );
r_zeros = newVRegI(env);
addInstr(env, PPCInstr_LI(r_zeros, 0x0, mode64));
addInstr(env, PPCInstr_Store( 4, am_off0, r_zeros, mode64 ));
addInstr(env, PPCInstr_Store( 4, am_off4, r_zeros, mode64 ));
addInstr(env, PPCInstr_Store( 4, am_off8, r_zeros, mode64 ));
addInstr(env, PPCInstr_Store( 4, am_off12, r_src, mode64 ));
addInstr(env, PPCInstr_AvLdSt( True, 4, dst, am_off12 ));
add_to_sp( env, 32 );
return dst;
}
case Iop_Dup8x16:
case Iop_Dup16x8:
case Iop_Dup32x4:
return mk_AvDuplicateRI(env, e->Iex.Unop.arg);
default:
break;
}
}
if (e->tag == Iex_Binop) {
switch (e->Iex.Binop.op) {
case Iop_64HLtoV128: {
if (!mode64) {
HReg r3, r2, r1, r0, r_aligned16;
PPCAMode *am_off0, *am_off4, *am_off8, *am_off12;
HReg dst = newVRegV(env);
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off0 = PPCAMode_IR( 0, r_aligned16 );
am_off4 = PPCAMode_IR( 4, r_aligned16 );
am_off8 = PPCAMode_IR( 8, r_aligned16 );
am_off12 = PPCAMode_IR( 12, r_aligned16 );
iselInt64Expr(&r1, &r0, env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_Store( 4, am_off12, r0, mode64 ));
addInstr(env, PPCInstr_Store( 4, am_off8, r1, mode64 ));
iselInt64Expr(&r3, &r2, env, e->Iex.Binop.arg1);
addInstr(env, PPCInstr_Store( 4, am_off4, r2, mode64 ));
addInstr(env, PPCInstr_Store( 4, am_off0, r3, mode64 ));
addInstr(env, PPCInstr_AvLdSt(True, 16, dst, am_off0));
add_to_sp( env, 32 );
return dst;
} else {
HReg rHi = iselWordExpr_R(env, e->Iex.Binop.arg1);
HReg rLo = iselWordExpr_R(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
HReg r_aligned16;
PPCAMode *am_off0, *am_off8;
sub_from_sp( env, 32 );
r_aligned16 = get_sp_aligned16( env );
am_off0 = PPCAMode_IR( 0, r_aligned16 );
am_off8 = PPCAMode_IR( 8, r_aligned16 );
addInstr(env, PPCInstr_Store( 8, am_off0, rHi, mode64 ));
addInstr(env, PPCInstr_Store( 8, am_off8, rLo, mode64 ));
addInstr(env, PPCInstr_AvLdSt(True, 16, dst, am_off0));
add_to_sp( env, 32 );
return dst;
}
}
case Iop_Add32Fx4: fpop = Pavfp_ADDF; goto do_32Fx4;
case Iop_Sub32Fx4: fpop = Pavfp_SUBF; goto do_32Fx4;
case Iop_Max32Fx4: fpop = Pavfp_MAXF; goto do_32Fx4;
case Iop_Min32Fx4: fpop = Pavfp_MINF; goto do_32Fx4;
case Iop_Mul32Fx4: fpop = Pavfp_MULF; goto do_32Fx4;
case Iop_CmpEQ32Fx4: fpop = Pavfp_CMPEQF; goto do_32Fx4;
case Iop_CmpGT32Fx4: fpop = Pavfp_CMPGTF; goto do_32Fx4;
case Iop_CmpGE32Fx4: fpop = Pavfp_CMPGEF; goto do_32Fx4;
do_32Fx4:
{
HReg argL = iselVecExpr(env, e->Iex.Binop.arg1);
HReg argR = iselVecExpr(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBin32Fx4(fpop, dst, argL, argR));
return dst;
}
case Iop_CmpLE32Fx4: {
HReg argL = iselVecExpr(env, e->Iex.Binop.arg1);
HReg argR = iselVecExpr(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
HReg isNanLR = newVRegV(env);
HReg isNanL = isNan(env, argL);
HReg isNanR = isNan(env, argR);
addInstr(env, PPCInstr_AvBinary(Pav_OR, isNanLR,
isNanL, isNanR));
addInstr(env, PPCInstr_AvBin32Fx4(Pavfp_CMPGTF, dst,
argL, argR));
addInstr(env, PPCInstr_AvBinary(Pav_OR, dst, dst, isNanLR));
addInstr(env, PPCInstr_AvUnary(Pav_NOT, dst, dst));
return dst;
}
case Iop_AndV128: op = Pav_AND; goto do_AvBin;
case Iop_OrV128: op = Pav_OR; goto do_AvBin;
case Iop_XorV128: op = Pav_XOR; goto do_AvBin;
do_AvBin: {
HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1);
HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBinary(op, dst, arg1, arg2));
return dst;
}
case Iop_Shl8x16: op = Pav_SHL; goto do_AvBin8x16;
case Iop_Shr8x16: op = Pav_SHR; goto do_AvBin8x16;
case Iop_Sar8x16: op = Pav_SAR; goto do_AvBin8x16;
case Iop_Rol8x16: op = Pav_ROTL; goto do_AvBin8x16;
case Iop_InterleaveHI8x16: op = Pav_MRGHI; goto do_AvBin8x16;
case Iop_InterleaveLO8x16: op = Pav_MRGLO; goto do_AvBin8x16;
case Iop_Add8x16: op = Pav_ADDU; goto do_AvBin8x16;
case Iop_QAdd8Ux16: op = Pav_QADDU; goto do_AvBin8x16;
case Iop_QAdd8Sx16: op = Pav_QADDS; goto do_AvBin8x16;
case Iop_Sub8x16: op = Pav_SUBU; goto do_AvBin8x16;
case Iop_QSub8Ux16: op = Pav_QSUBU; goto do_AvBin8x16;
case Iop_QSub8Sx16: op = Pav_QSUBS; goto do_AvBin8x16;
case Iop_Avg8Ux16: op = Pav_AVGU; goto do_AvBin8x16;
case Iop_Avg8Sx16: op = Pav_AVGS; goto do_AvBin8x16;
case Iop_Max8Ux16: op = Pav_MAXU; goto do_AvBin8x16;
case Iop_Max8Sx16: op = Pav_MAXS; goto do_AvBin8x16;
case Iop_Min8Ux16: op = Pav_MINU; goto do_AvBin8x16;
case Iop_Min8Sx16: op = Pav_MINS; goto do_AvBin8x16;
case Iop_MullEven8Ux16: op = Pav_OMULU; goto do_AvBin8x16;
case Iop_MullEven8Sx16: op = Pav_OMULS; goto do_AvBin8x16;
case Iop_CmpEQ8x16: op = Pav_CMPEQU; goto do_AvBin8x16;
case Iop_CmpGT8Ux16: op = Pav_CMPGTU; goto do_AvBin8x16;
case Iop_CmpGT8Sx16: op = Pav_CMPGTS; goto do_AvBin8x16;
do_AvBin8x16: {
HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1);
HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBin8x16(op, dst, arg1, arg2));
return dst;
}
case Iop_Shl16x8: op = Pav_SHL; goto do_AvBin16x8;
case Iop_Shr16x8: op = Pav_SHR; goto do_AvBin16x8;
case Iop_Sar16x8: op = Pav_SAR; goto do_AvBin16x8;
case Iop_Rol16x8: op = Pav_ROTL; goto do_AvBin16x8;
case Iop_NarrowBin16to8x16: op = Pav_PACKUU; goto do_AvBin16x8;
case Iop_QNarrowBin16Uto8Ux16: op = Pav_QPACKUU; goto do_AvBin16x8;
case Iop_QNarrowBin16Sto8Sx16: op = Pav_QPACKSS; goto do_AvBin16x8;
case Iop_InterleaveHI16x8: op = Pav_MRGHI; goto do_AvBin16x8;
case Iop_InterleaveLO16x8: op = Pav_MRGLO; goto do_AvBin16x8;
case Iop_Add16x8: op = Pav_ADDU; goto do_AvBin16x8;
case Iop_QAdd16Ux8: op = Pav_QADDU; goto do_AvBin16x8;
case Iop_QAdd16Sx8: op = Pav_QADDS; goto do_AvBin16x8;
case Iop_Sub16x8: op = Pav_SUBU; goto do_AvBin16x8;
case Iop_QSub16Ux8: op = Pav_QSUBU; goto do_AvBin16x8;
case Iop_QSub16Sx8: op = Pav_QSUBS; goto do_AvBin16x8;
case Iop_Avg16Ux8: op = Pav_AVGU; goto do_AvBin16x8;
case Iop_Avg16Sx8: op = Pav_AVGS; goto do_AvBin16x8;
case Iop_Max16Ux8: op = Pav_MAXU; goto do_AvBin16x8;
case Iop_Max16Sx8: op = Pav_MAXS; goto do_AvBin16x8;
case Iop_Min16Ux8: op = Pav_MINU; goto do_AvBin16x8;
case Iop_Min16Sx8: op = Pav_MINS; goto do_AvBin16x8;
case Iop_MullEven16Ux8: op = Pav_OMULU; goto do_AvBin16x8;
case Iop_MullEven16Sx8: op = Pav_OMULS; goto do_AvBin16x8;
case Iop_CmpEQ16x8: op = Pav_CMPEQU; goto do_AvBin16x8;
case Iop_CmpGT16Ux8: op = Pav_CMPGTU; goto do_AvBin16x8;
case Iop_CmpGT16Sx8: op = Pav_CMPGTS; goto do_AvBin16x8;
do_AvBin16x8: {
HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1);
HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBin16x8(op, dst, arg1, arg2));
return dst;
}
case Iop_Shl32x4: op = Pav_SHL; goto do_AvBin32x4;
case Iop_Shr32x4: op = Pav_SHR; goto do_AvBin32x4;
case Iop_Sar32x4: op = Pav_SAR; goto do_AvBin32x4;
case Iop_Rol32x4: op = Pav_ROTL; goto do_AvBin32x4;
case Iop_NarrowBin32to16x8: op = Pav_PACKUU; goto do_AvBin32x4;
case Iop_QNarrowBin32Uto16Ux8: op = Pav_QPACKUU; goto do_AvBin32x4;
case Iop_QNarrowBin32Sto16Sx8: op = Pav_QPACKSS; goto do_AvBin32x4;
case Iop_InterleaveHI32x4: op = Pav_MRGHI; goto do_AvBin32x4;
case Iop_InterleaveLO32x4: op = Pav_MRGLO; goto do_AvBin32x4;
case Iop_Add32x4: op = Pav_ADDU; goto do_AvBin32x4;
case Iop_QAdd32Ux4: op = Pav_QADDU; goto do_AvBin32x4;
case Iop_QAdd32Sx4: op = Pav_QADDS; goto do_AvBin32x4;
case Iop_Sub32x4: op = Pav_SUBU; goto do_AvBin32x4;
case Iop_QSub32Ux4: op = Pav_QSUBU; goto do_AvBin32x4;
case Iop_QSub32Sx4: op = Pav_QSUBS; goto do_AvBin32x4;
case Iop_Avg32Ux4: op = Pav_AVGU; goto do_AvBin32x4;
case Iop_Avg32Sx4: op = Pav_AVGS; goto do_AvBin32x4;
case Iop_Max32Ux4: op = Pav_MAXU; goto do_AvBin32x4;
case Iop_Max32Sx4: op = Pav_MAXS; goto do_AvBin32x4;
case Iop_Min32Ux4: op = Pav_MINU; goto do_AvBin32x4;
case Iop_Min32Sx4: op = Pav_MINS; goto do_AvBin32x4;
case Iop_CmpEQ32x4: op = Pav_CMPEQU; goto do_AvBin32x4;
case Iop_CmpGT32Ux4: op = Pav_CMPGTU; goto do_AvBin32x4;
case Iop_CmpGT32Sx4: op = Pav_CMPGTS; goto do_AvBin32x4;
do_AvBin32x4: {
HReg arg1 = iselVecExpr(env, e->Iex.Binop.arg1);
HReg arg2 = iselVecExpr(env, e->Iex.Binop.arg2);
HReg dst = newVRegV(env);
addInstr(env, PPCInstr_AvBin32x4(op, dst, arg1, arg2));
return dst;
}
case Iop_ShlN8x16: op = Pav_SHL; goto do_AvShift8x16;
case Iop_SarN8x16: op = Pav_SAR; goto do_AvShift8x16;
do_AvShift8x16: {
HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1);
HReg dst = newVRegV(env);
HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_AvBin8x16(op, dst, r_src, v_shft));
return dst;
}
case Iop_ShlN16x8: op = Pav_SHL; goto do_AvShift16x8;
case Iop_ShrN16x8: op = Pav_SHR; goto do_AvShift16x8;
case Iop_SarN16x8: op = Pav_SAR; goto do_AvShift16x8;
do_AvShift16x8: {
HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1);
HReg dst = newVRegV(env);
HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_AvBin16x8(op, dst, r_src, v_shft));
return dst;
}
case Iop_ShlN32x4: op = Pav_SHL; goto do_AvShift32x4;
case Iop_ShrN32x4: op = Pav_SHR; goto do_AvShift32x4;
case Iop_SarN32x4: op = Pav_SAR; goto do_AvShift32x4;
do_AvShift32x4: {
HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1);
HReg dst = newVRegV(env);
HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_AvBin32x4(op, dst, r_src, v_shft));
return dst;
}
case Iop_ShrV128: op = Pav_SHR; goto do_AvShiftV128;
case Iop_ShlV128: op = Pav_SHL; goto do_AvShiftV128;
do_AvShiftV128: {
HReg dst = newVRegV(env);
HReg r_src = iselVecExpr(env, e->Iex.Binop.arg1);
HReg v_shft = mk_AvDuplicateRI(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_AvBinary(op, dst, r_src, v_shft));
return dst;
}
case Iop_Perm8x16: {
HReg dst = newVRegV(env);
HReg v_src = iselVecExpr(env, e->Iex.Binop.arg1);
HReg v_ctl = iselVecExpr(env, e->Iex.Binop.arg2);
addInstr(env, PPCInstr_AvPerm(dst, v_src, v_src, v_ctl));
return dst;
}
default:
break;
}
}
if (e->tag == Iex_Const ) {
vassert(e->Iex.Const.con->tag == Ico_V128);
if (e->Iex.Const.con->Ico.V128 == 0x0000) {
return generate_zeroes_V128(env);
}
else if (e->Iex.Const.con->Ico.V128 == 0xffff) {
return generate_ones_V128(env);
}
}
vex_printf("iselVecExpr(ppc) (subarch = %s): can't reduce\n",
LibVEX_ppVexHwCaps(mode64 ? VexArchPPC64 : VexArchPPC32,
env->hwcaps));
ppIRExpr(e);
vpanic("iselVecExpr_wrk(ppc)");
}
static void iselStmt ( ISelEnv* env, IRStmt* stmt )
{
Bool mode64 = env->mode64;
if (vex_traceflags & VEX_TRACE_VCODE) {
vex_printf("\n -- ");
ppIRStmt(stmt);
vex_printf("\n");
}
switch (stmt->tag) {
case Ist_Store: {
IRType tya = typeOfIRExpr(env->type_env, stmt->Ist.Store.addr);
IRType tyd = typeOfIRExpr(env->type_env, stmt->Ist.Store.data);
IREndness end = stmt->Ist.Store.end;
if (end != Iend_BE)
goto stmt_fail;
if (!mode64 && (tya != Ity_I32))
goto stmt_fail;
if (mode64 && (tya != Ity_I64))
goto stmt_fail;
if (tyd == Ity_I8 || tyd == Ity_I16 || tyd == Ity_I32 ||
(mode64 && (tyd == Ity_I64))) {
PPCAMode* am_addr
= iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd);
HReg r_src = iselWordExpr_R(env, stmt->Ist.Store.data);
addInstr(env, PPCInstr_Store( toUChar(sizeofIRType(tyd)),
am_addr, r_src, mode64 ));
return;
}
if (tyd == Ity_F64) {
PPCAMode* am_addr
= iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd);
HReg fr_src = iselDblExpr(env, stmt->Ist.Store.data);
addInstr(env,
PPCInstr_FpLdSt(False, 8, fr_src, am_addr));
return;
}
if (tyd == Ity_F32) {
PPCAMode* am_addr
= iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd);
HReg fr_src = iselFltExpr(env, stmt->Ist.Store.data);
addInstr(env,
PPCInstr_FpLdSt(False, 4, fr_src, am_addr));
return;
}
if (tyd == Ity_V128) {
PPCAMode* am_addr
= iselWordExpr_AMode(env, stmt->Ist.Store.addr, tyd);
HReg v_src = iselVecExpr(env, stmt->Ist.Store.data);
addInstr(env,
PPCInstr_AvLdSt(False, 16, v_src, am_addr));
return;
}
if (tyd == Ity_I64 && !mode64) {
HReg rHi32, rLo32;
HReg r_addr = iselWordExpr_R(env, stmt->Ist.Store.addr);
iselInt64Expr( &rHi32, &rLo32, env, stmt->Ist.Store.data );
addInstr(env, PPCInstr_Store( 4,
PPCAMode_IR( 0, r_addr ),
rHi32,
False) );
addInstr(env, PPCInstr_Store( 4,
PPCAMode_IR( 4, r_addr ),
rLo32,
False) );
return;
}
break;
}
case Ist_Put: {
IRType ty = typeOfIRExpr(env->type_env, stmt->Ist.Put.data);
if (ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && mode64)) {
HReg r_src = iselWordExpr_R(env, stmt->Ist.Put.data);
PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset,
GuestStatePtr(mode64) );
addInstr(env, PPCInstr_Store( toUChar(sizeofIRType(ty)),
am_addr, r_src, mode64 ));
return;
}
if (!mode64 && ty == Ity_I64) {
HReg rHi, rLo;
PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset,
GuestStatePtr(mode64) );
PPCAMode* am_addr4 = advance4(env, am_addr);
iselInt64Expr(&rHi,&rLo, env, stmt->Ist.Put.data);
addInstr(env, PPCInstr_Store( 4, am_addr, rHi, mode64 ));
addInstr(env, PPCInstr_Store( 4, am_addr4, rLo, mode64 ));
return;
}
if (ty == Ity_V128) {
HReg v_src = iselVecExpr(env, stmt->Ist.Put.data);
PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset,
GuestStatePtr(mode64) );
addInstr(env,
PPCInstr_AvLdSt(False, 16, v_src, am_addr));
return;
}
if (ty == Ity_F64) {
HReg fr_src = iselDblExpr(env, stmt->Ist.Put.data);
PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset,
GuestStatePtr(mode64) );
addInstr(env, PPCInstr_FpLdSt( False, 8,
fr_src, am_addr ));
return;
}
if (ty == Ity_D64) {
HReg fr_src = iselDfp64Expr( env, stmt->Ist.Put.data );
PPCAMode* am_addr = PPCAMode_IR( stmt->Ist.Put.offset,
GuestStatePtr(mode64) );
addInstr( env, PPCInstr_FpLdSt( False, 8, fr_src, am_addr ) );
return;
}
break;
}
case Ist_PutI: {
IRPutI *puti = stmt->Ist.PutI.details;
PPCAMode* dst_am
= genGuestArrayOffset(
env, puti->descr,
puti->ix, puti->bias );
IRType ty = typeOfIRExpr(env->type_env, puti->data);
if (mode64 && ty == Ity_I64) {
HReg r_src = iselWordExpr_R(env, puti->data);
addInstr(env, PPCInstr_Store( toUChar(8),
dst_am, r_src, mode64 ));
return;
}
if ((!mode64) && ty == Ity_I32) {
HReg r_src = iselWordExpr_R(env, puti->data);
addInstr(env, PPCInstr_Store( toUChar(4),
dst_am, r_src, mode64 ));
return;
}
break;
}
case Ist_WrTmp: {
IRTemp tmp = stmt->Ist.WrTmp.tmp;
IRType ty = typeOfIRTemp(env->type_env, tmp);
if (ty == Ity_I8 || ty == Ity_I16 ||
ty == Ity_I32 || ((ty == Ity_I64) && mode64)) {
HReg r_dst = lookupIRTemp(env, tmp);
HReg r_src = iselWordExpr_R(env, stmt->Ist.WrTmp.data);
addInstr(env, mk_iMOVds_RR( r_dst, r_src ));
return;
}
if (!mode64 && ty == Ity_I64) {
HReg r_srcHi, r_srcLo, r_dstHi, r_dstLo;
iselInt64Expr(&r_srcHi,&r_srcLo, env, stmt->Ist.WrTmp.data);
lookupIRTempPair( &r_dstHi, &r_dstLo, env, tmp);
addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) );
addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) );
return;
}
if (mode64 && ty == Ity_I128) {
HReg r_srcHi, r_srcLo, r_dstHi, r_dstLo;
iselInt128Expr(&r_srcHi,&r_srcLo, env, stmt->Ist.WrTmp.data);
lookupIRTempPair( &r_dstHi, &r_dstLo, env, tmp);
addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) );
addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) );
return;
}
if (!mode64 && ty == Ity_I128) {
HReg r_srcHi, r_srcMedHi, r_srcMedLo, r_srcLo;
HReg r_dstHi, r_dstMedHi, r_dstMedLo, r_dstLo;
iselInt128Expr_to_32x4(&r_srcHi, &r_srcMedHi,
&r_srcMedLo, &r_srcLo,
env, stmt->Ist.WrTmp.data);
lookupIRTempQuad( &r_dstHi, &r_dstMedHi, &r_dstMedLo,
&r_dstLo, env, tmp);
addInstr(env, mk_iMOVds_RR(r_dstHi, r_srcHi) );
addInstr(env, mk_iMOVds_RR(r_dstMedHi, r_srcMedHi) );
addInstr(env, mk_iMOVds_RR(r_dstMedLo, r_srcMedLo) );
addInstr(env, mk_iMOVds_RR(r_dstLo, r_srcLo) );
return;
}
if (ty == Ity_I1) {
PPCCondCode cond = iselCondCode(env, stmt->Ist.WrTmp.data);
HReg r_dst = lookupIRTemp(env, tmp);
addInstr(env, PPCInstr_Set(cond, r_dst));
return;
}
if (ty == Ity_F64) {
HReg fr_dst = lookupIRTemp(env, tmp);
HReg fr_src = iselDblExpr(env, stmt->Ist.WrTmp.data);
addInstr(env, PPCInstr_FpUnary(Pfp_MOV, fr_dst, fr_src));
return;
}
if (ty == Ity_F32) {
HReg fr_dst = lookupIRTemp(env, tmp);
HReg fr_src = iselFltExpr(env, stmt->Ist.WrTmp.data);
addInstr(env, PPCInstr_FpUnary(Pfp_MOV, fr_dst, fr_src));
return;
}
if (ty == Ity_V128) {
HReg v_dst = lookupIRTemp(env, tmp);
HReg v_src = iselVecExpr(env, stmt->Ist.WrTmp.data);
addInstr(env, PPCInstr_AvUnary(Pav_MOV, v_dst, v_src));
return;
}
if (ty == Ity_D64) {
HReg fr_dst = lookupIRTemp( env, tmp );
HReg fr_src = iselDfp64Expr( env, stmt->Ist.WrTmp.data );
addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dst, fr_src ) );
return;
}
if (ty == Ity_D128) {
HReg fr_srcHi, fr_srcLo, fr_dstHi, fr_dstLo;
lookupIRTempPair( &fr_dstHi, &fr_dstLo, env, tmp );
iselDfp128Expr( &fr_srcHi, &fr_srcLo, env, stmt->Ist.WrTmp.data );
addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dstHi, fr_srcHi ) );
addInstr( env, PPCInstr_Dfp64Unary( Pfp_MOV, fr_dstLo, fr_srcLo ) );
return;
}
break;
}
case Ist_LLSC: {
IRTemp res = stmt->Ist.LLSC.result;
IRType tyRes = typeOfIRTemp(env->type_env, res);
IRType tyAddr = typeOfIRExpr(env->type_env, stmt->Ist.LLSC.addr);
if (stmt->Ist.LLSC.end != Iend_BE)
goto stmt_fail;
if (!mode64 && (tyAddr != Ity_I32))
goto stmt_fail;
if (mode64 && (tyAddr != Ity_I64))
goto stmt_fail;
if (stmt->Ist.LLSC.storedata == NULL) {
HReg r_addr = iselWordExpr_R( env, stmt->Ist.LLSC.addr );
HReg r_dst = lookupIRTemp(env, res);
if (tyRes == Ity_I32) {
addInstr(env, PPCInstr_LoadL( 4, r_dst, r_addr, mode64 ));
return;
}
if (tyRes == Ity_I64 && mode64) {
addInstr(env, PPCInstr_LoadL( 8, r_dst, r_addr, mode64 ));
return;
}
;
} else {
HReg r_res = lookupIRTemp(env, res);
HReg r_a = iselWordExpr_R(env, stmt->Ist.LLSC.addr);
HReg r_src = iselWordExpr_R(env, stmt->Ist.LLSC.storedata);
HReg r_tmp = newVRegI(env);
IRType tyData = typeOfIRExpr(env->type_env,
stmt->Ist.LLSC.storedata);
vassert(tyRes == Ity_I1);
if (tyData == Ity_I32 || (tyData == Ity_I64 && mode64)) {
addInstr(env, PPCInstr_StoreC( tyData==Ity_I32 ? 4 : 8,
r_a, r_src, mode64 ));
addInstr(env, PPCInstr_MfCR( r_tmp ));
addInstr(env, PPCInstr_Shft(
Pshft_SHR,
env->mode64 ? False : True
,
r_tmp, r_tmp,
PPCRH_Imm(False, 29)));
addInstr(env, PPCInstr_Alu(
Palu_AND,
r_res, r_tmp,
PPCRH_Imm(False, 1)));
return;
}
}
goto stmt_fail;
}
case Ist_Dirty: {
IRType retty;
IRDirty* d = stmt->Ist.Dirty.details;
Bool passBBP = False;
if (d->nFxState == 0)
vassert(!d->needsBBP);
passBBP = toBool(d->nFxState > 0 && d->needsBBP);
doHelperCall( env, passBBP, d->guard, d->cee, d->args );
if (d->tmp == IRTemp_INVALID)
return;
retty = typeOfIRTemp(env->type_env, d->tmp);
if (!mode64 && retty == Ity_I64) {
HReg r_dstHi, r_dstLo;
lookupIRTempPair( &r_dstHi, &r_dstLo, env, d->tmp);
addInstr(env, mk_iMOVds_RR(r_dstHi, hregPPC_GPR3(mode64)));
addInstr(env, mk_iMOVds_RR(r_dstLo, hregPPC_GPR4(mode64)));
return;
}
if (retty == Ity_I8 || retty == Ity_I16 ||
retty == Ity_I32 || ((retty == Ity_I64) && mode64)) {
HReg r_dst = lookupIRTemp(env, d->tmp);
addInstr(env, mk_iMOVds_RR(r_dst, hregPPC_GPR3(mode64)));
return;
}
break;
}
case Ist_MBE:
switch (stmt->Ist.MBE.event) {
case Imbe_Fence:
addInstr(env, PPCInstr_MFence());
return;
default:
break;
}
break;
case Ist_IMark:
return;
case Ist_AbiHint:
return;
case Ist_NoOp:
return;
case Ist_Exit: {
IRConst* dst = stmt->Ist.Exit.dst;
if (!mode64 && dst->tag != Ico_U32)
vpanic("iselStmt(ppc): Ist_Exit: dst is not a 32-bit value");
if (mode64 && dst->tag != Ico_U64)
vpanic("iselStmt(ppc64): Ist_Exit: dst is not a 64-bit value");
PPCCondCode cc = iselCondCode(env, stmt->Ist.Exit.guard);
PPCAMode* amCIA = PPCAMode_IR(stmt->Ist.Exit.offsIP,
hregPPC_GPR31(mode64));
if (stmt->Ist.Exit.jk == Ijk_Boring
|| stmt->Ist.Exit.jk == Ijk_Call
) {
if (env->chainingAllowed) {
Bool toFastEP
= mode64
? (((Addr64)stmt->Ist.Exit.dst->Ico.U64) > (Addr64)env->max_ga)
: (((Addr32)stmt->Ist.Exit.dst->Ico.U32) > (Addr32)env->max_ga);
if (0) vex_printf("%s", toFastEP ? "Y" : ",");
addInstr(env, PPCInstr_XDirect(
mode64 ? (Addr64)stmt->Ist.Exit.dst->Ico.U64
: (Addr64)stmt->Ist.Exit.dst->Ico.U32,
amCIA, cc, toFastEP));
} else {
HReg r = iselWordExpr_R(env, IRExpr_Const(stmt->Ist.Exit.dst));
addInstr(env, PPCInstr_XAssisted(r, amCIA, cc, Ijk_Boring));
}
return;
}
switch (stmt->Ist.Exit.jk) {
case Ijk_ClientReq:
case Ijk_EmFail:
case Ijk_EmWarn:
case Ijk_NoDecode:
case Ijk_NoRedir:
case Ijk_SigBUS:
case Ijk_SigTRAP:
case Ijk_Sys_syscall:
case Ijk_TInval:
{
HReg r = iselWordExpr_R(env, IRExpr_Const(stmt->Ist.Exit.dst));
addInstr(env, PPCInstr_XAssisted(r, amCIA, cc,
stmt->Ist.Exit.jk));
return;
}
default:
break;
}
goto stmt_fail;
}
default: break;
}
stmt_fail:
ppIRStmt(stmt);
vpanic("iselStmt(ppc)");
}
static void iselNext ( ISelEnv* env,
IRExpr* next, IRJumpKind jk, Int offsIP )
{
if (vex_traceflags & VEX_TRACE_VCODE) {
vex_printf( "\n-- PUT(%d) = ", offsIP);
ppIRExpr( next );
vex_printf( "; exit-");
ppIRJumpKind(jk);
vex_printf( "\n");
}
PPCCondCode always = mk_PPCCondCode( Pct_ALWAYS, Pcf_NONE );
if (next->tag == Iex_Const) {
IRConst* cdst = next->Iex.Const.con;
vassert(cdst->tag == (env->mode64 ? Ico_U64 :Ico_U32));
if (jk == Ijk_Boring || jk == Ijk_Call) {
PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64));
if (env->chainingAllowed) {
Bool toFastEP
= env->mode64
? (((Addr64)cdst->Ico.U64) > (Addr64)env->max_ga)
: (((Addr32)cdst->Ico.U32) > (Addr32)env->max_ga);
if (0) vex_printf("%s", toFastEP ? "X" : ".");
addInstr(env, PPCInstr_XDirect(
env->mode64 ? (Addr64)cdst->Ico.U64
: (Addr64)cdst->Ico.U32,
amCIA, always, toFastEP));
} else {
HReg r = iselWordExpr_R(env, next);
addInstr(env, PPCInstr_XAssisted(r, amCIA, always,
Ijk_Boring));
}
return;
}
}
switch (jk) {
case Ijk_Boring: case Ijk_Ret: case Ijk_Call: {
HReg r = iselWordExpr_R(env, next);
PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64));
if (env->chainingAllowed) {
addInstr(env, PPCInstr_XIndir(r, amCIA, always));
} else {
addInstr(env, PPCInstr_XAssisted(r, amCIA, always,
Ijk_Boring));
}
return;
}
default:
break;
}
switch (jk) {
case Ijk_ClientReq:
case Ijk_EmFail:
case Ijk_EmWarn:
case Ijk_NoDecode:
case Ijk_NoRedir:
case Ijk_SigBUS:
case Ijk_SigTRAP:
case Ijk_Sys_syscall:
case Ijk_TInval:
{
HReg r = iselWordExpr_R(env, next);
PPCAMode* amCIA = PPCAMode_IR(offsIP, hregPPC_GPR31(env->mode64));
addInstr(env, PPCInstr_XAssisted(r, amCIA, always, jk));
return;
}
default:
break;
}
vex_printf( "\n-- PUT(%d) = ", offsIP);
ppIRExpr( next );
vex_printf( "; exit-");
ppIRJumpKind(jk);
vex_printf( "\n");
vassert(0);
}
HInstrArray* iselSB_PPC ( IRSB* bb,
VexArch arch_host,
VexArchInfo* archinfo_host,
VexAbiInfo* vbi,
Int offs_Host_EvC_Counter,
Int offs_Host_EvC_FailAddr,
Bool chainingAllowed,
Bool addProfInc,
Addr64 max_ga )
{
Int i, j;
HReg hregLo, hregMedLo, hregMedHi, hregHi;
ISelEnv* env;
UInt hwcaps_host = archinfo_host->hwcaps;
Bool mode64 = False;
UInt mask32, mask64;
PPCAMode *amCounter, *amFailAddr;
vassert(arch_host == VexArchPPC32 || arch_host == VexArchPPC64);
mode64 = arch_host == VexArchPPC64;
if (!mode64) vassert(max_ga <= 0xFFFFFFFFULL);
mask32 = VEX_HWCAPS_PPC32_F | VEX_HWCAPS_PPC32_V
| VEX_HWCAPS_PPC32_FX | VEX_HWCAPS_PPC32_GX | VEX_HWCAPS_PPC32_VX
| VEX_HWCAPS_PPC32_DFP;
mask64 = VEX_HWCAPS_PPC64_V | VEX_HWCAPS_PPC64_FX
| VEX_HWCAPS_PPC64_GX | VEX_HWCAPS_PPC64_VX | VEX_HWCAPS_PPC64_DFP;
if (mode64) {
vassert((hwcaps_host & mask32) == 0);
} else {
vassert((hwcaps_host & mask64) == 0);
}
env = LibVEX_Alloc(sizeof(ISelEnv));
env->vreg_ctr = 0;
env->mode64 = mode64;
env->code = newHInstrArray();
env->type_env = bb->tyenv;
env->n_vregmap = bb->tyenv->types_used;
env->vregmapLo = LibVEX_Alloc(env->n_vregmap * sizeof(HReg));
env->vregmapMedLo = LibVEX_Alloc(env->n_vregmap * sizeof(HReg));
if (mode64) {
env->vregmapMedHi = NULL;
env->vregmapHi = NULL;
} else {
env->vregmapMedHi = LibVEX_Alloc(env->n_vregmap * sizeof(HReg));
env->vregmapHi = LibVEX_Alloc(env->n_vregmap * sizeof(HReg));
}
env->chainingAllowed = chainingAllowed;
env->max_ga = max_ga;
env->hwcaps = hwcaps_host;
env->previous_rm = NULL;
env->vbi = vbi;
j = 0;
for (i = 0; i < env->n_vregmap; i++) {
hregLo = hregMedLo = hregMedHi = hregHi = INVALID_HREG;
switch (bb->tyenv->types[i]) {
case Ity_I1:
case Ity_I8:
case Ity_I16:
case Ity_I32:
if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); break;
} else { hregLo = mkHReg(j++, HRcInt32, True); break;
}
case Ity_I64:
if (mode64) { hregLo = mkHReg(j++, HRcInt64, True); break;
} else { hregLo = mkHReg(j++, HRcInt32, True);
hregMedLo = mkHReg(j++, HRcInt32, True); break;
}
case Ity_I128:
if (mode64) { hregLo = mkHReg(j++, HRcInt64, True);
hregMedLo = mkHReg(j++, HRcInt64, True); break;
} else { hregLo = mkHReg(j++, HRcInt32, True);
hregMedLo = mkHReg(j++, HRcInt32, True);
hregMedHi = mkHReg(j++, HRcInt32, True);
hregHi = mkHReg(j++, HRcInt32, True); break;
}
case Ity_F32:
case Ity_F64: hregLo = mkHReg(j++, HRcFlt64, True); break;
case Ity_V128: hregLo = mkHReg(j++, HRcVec128, True); break;
case Ity_D64: hregLo = mkHReg(j++, HRcFlt64, True); break;
case Ity_D128: hregLo = mkHReg(j++, HRcFlt64, True);
hregMedLo = mkHReg(j++, HRcFlt64, True); break;
default:
ppIRType(bb->tyenv->types[i]);
vpanic("iselBB(ppc): IRTemp type");
}
env->vregmapLo[i] = hregLo;
env->vregmapMedLo[i] = hregMedLo;
if (!mode64) {
env->vregmapMedHi[i] = hregMedHi;
env->vregmapHi[i] = hregHi;
}
}
env->vreg_ctr = j;
amCounter = PPCAMode_IR(offs_Host_EvC_Counter, hregPPC_GPR31(mode64));
amFailAddr = PPCAMode_IR(offs_Host_EvC_FailAddr, hregPPC_GPR31(mode64));
addInstr(env, PPCInstr_EvCheck(amCounter, amFailAddr));
if (addProfInc) {
addInstr(env, PPCInstr_ProfInc());
}
for (i = 0; i < bb->stmts_used; i++)
iselStmt(env, bb->stmts[i]);
iselNext(env, bb->next, bb->jumpkind, bb->offsIP);
env->code->n_vregs = env->vreg_ctr;
return env->code;
}
| Java |
<?php
chdir('../../');
require_once ('pika-danio.php');
pika_init();
$report_title = 'LSC Interim Case Services';
$report_name = "lsc_interim";
$base_url = pl_settings_get('base_url');
if(!pika_report_authorize($report_name))
{
$main_html = array();
$main_html['base_url'] = $base_url;
$main_html['page_title'] = $report_title;
$main_html['nav'] = "<a href=\"{$base_url}/\">Pika Home</a>
> <a href=\"{$base_url}/reports/\">Reports</a>
> $report_title";
$main_html['content'] = "You are not authorized to run this report";
$buffer = pl_template('templates/default.html', $main_html);
pika_exit($buffer);
}
$report_format = pl_grab_get('report_format');
$close_date_begin = pl_grab_get('close_date_begin');
$close_date_end = pl_grab_get('close_date_end');
$open_on_date = pl_grab_get('open_on_date');
$funding = pl_grab_get('funding');
$office = pl_grab_get('office');
$status = pl_grab_get('status');
$county = pl_grab_get('county');
$gender = pl_grab_get('gender');
$undup = pl_grab_get('undup');
$calendar_year = pl_grab_get('calendar_year');
$clean_calendar_year = mysql_real_escape_string($calendar_year);
$show_sql = pl_grab_get('show_sql');
$menu_undup = pl_menu_get('undup');
if ('csv' == $report_format)
{
require_once ('app/lib/plCsvReportTable.php');
require_once ('app/lib/plCsvReport.php');
$t = new plCsvReport();
}
else
{
require_once ('app/lib/plHtmlReportTable.php');
require_once ('app/lib/plHtmlReport.php');
$t = new plHtmlReport();
}
// run the report
$clb = $clean_calendar_year . "-01-01";
$cle = $clean_calendar_year . "-06-30";
$ood = $clean_calendar_year . "-06-30";
$eth_sql = "SELECT SUBSTRING(LPAD(problem, 2, '0'),1,1) AS category,
SUM(IF(close_code IN ('A', 'B'), 1, 0)) AS 'Cases Closed after Limited Service',
SUM(IF(close_code IN ('F', 'G', 'H', 'IA', 'IB', 'IC', 'K', 'L'), 1, 0)) AS 'Cases Closed after Extended Service',
SUM(IF(ISNULL(close_date) OR close_date > '{$clean_calendar_year}-06-30', 1, 0)) AS 'Cases Remaining Open on June 30'
FROM cases
WHERE status='2'";
// handle the crazy date range selection
$range1 = $range2 = "";
$sql = '';
$safe_clb = mysql_real_escape_string($clb);
$safe_cle = mysql_real_escape_string($cle);
$safe_ood = mysql_real_escape_string($ood);
if ($clb && $cle)
{
//$t->add_parameter('Closed Between', $safe_clb . " - " . $safe_cle);
$range1 = "close_date >= '{$safe_clb}' AND close_date <= '{$safe_cle}'";
}
elseif ($clb)
{
//$t->add_parameter('Closed After', $safe_clb);
$range1 = "close_date >= '{$safe_clb}'";
}
elseif ($cle)
{
//$t->add_parameter('Closed Before', $safe_cle);
$range1 = "close_date <= '{$safe_cle}'";
}
if ($ood)
{
//$t->add_parameter('Open On', $safe_ood);
$range2 = "(open_date <= '{$safe_ood}' AND (close_date IS NULL OR close_date > '{$safe_ood}'))";
}
if ($ood)
{
if ($clb || $cle)
{
$sql .= " AND (($range1) OR $range2)";
}
else
{
$sql .= " AND $range2";
}
}
else
{
if ($clb || $cle)
{
$sql .= " AND $range1";
}
}
// Other filters
$x = pl_process_comma_vals($funding);
if ($x != false)
{
$t->add_parameter('Funding Code(s)',$funding);
$sql .= " AND funding IN $x";
}
$x = pl_process_comma_vals($office);
if ($x != false)
{
$t->add_parameter('Office Code(s)',$office);
$sql .= " AND office IN $x";
}
$x = pl_process_comma_vals($status);
if ($x != false)
{
$t->add_parameter('Case Status Code(s)',$status);
$sql .= " AND status IN $x";
}
$x = pl_process_comma_vals($county);
if ($x != false)
{
$t->add_parameter('Counties',$county);
$sql .= " AND county IN $x";
}
if ($gender)
{
$t->add_parameter('Gender Code',$gender);
$safe_gender = mysql_real_escape_string($gender);
$sql .= " AND gender='{$safe_gender}'";
}
if ($undup == 1 || ($undup == 0 && $undup != ''))
{
$t->add_parameter('Undup Service',pl_array_lookup($undup,$menu_undup));
$safe_undup = mysql_real_escape_string($undup);
$sql .= " AND undup = '{$safe_undup}'";
}
$eth_sql .= $sql . " GROUP BY category";
$t->title = $report_title;
$t->set_table_title("Form G-1: Interim Case Services");
$t->display_row_count(false);
$t->set_header(array('Category','Cases Closed after Limited Service','Cases Closed after Extended Service','Cases Remaining Open on June 30'));
$t->add_parameter('Cases open between', $safe_clb . " - " . $safe_cle);
$t->add_parameter('Status Codes', "2, 5");
$t->add_parameter('Limited Service Closing Codes', 'A, B');
$t->add_parameter('Extended Service Closing Codes', 'F, G, H, IA, IB, IC, K, L');
$t->add_parameter('Funding', $funding);
$total = array();
$total['code'] = "";
$total['category'] = "";
$total["A"] = "0";
$total["B"] = "0";
$total["C"] = "0";
$total["D"] = "0";
$total["total"] = "0";
$result = mysql_query($eth_sql) or trigger_error();
while ($row = mysql_fetch_assoc($result))
{
$t->add_row($row);
$total["A"] += $row["Under 18"];
$total["B"] += $row["18 to 59"];
$total["C"] += $row["60 and Older"];
$total["D"] += $row["No Age Data"];
$total["total"] += $row["Total"];
}
//$t->add_row($total);
if($show_sql)
{
$t->set_sql($eth_sql);
}
// Add the PAI table
$t->add_table();
$t->set_table_title("Form G-1(d): Interim Case Services (PAI)");
$t->display_row_count(false);
$t->set_header(array('Category', 'Cases Closed after Limited Service','Cases Closed after Extended Service','Cases Remaining Open on June 30'));
$pai_sql = "SELECT SUBSTRING(LPAD(problem, 2, '0'),1,1) AS category,
SUM(IF(close_code IN ('A', 'B'), 1, 0)) AS 'Cases Closed after Limited Service',
SUM(IF(close_code IN ('F', 'G', 'H', 'IA', 'IB', 'IC', 'K', 'L'), 1, 0)) AS 'Cases Closed after Extended Service',
SUM(IF(ISNULL(close_date) OR close_date > '{$clean_calendar_year}-06-30', 1, 0)) AS 'Cases Remaining Open on June 30'
FROM cases
WHERE status='5'" . $sql . " GROUP BY category";
$result = mysql_query($pai_sql) or trigger_error();
while ($row = mysql_fetch_assoc($result))
{
$t->add_row($row);
}
//$t->add_row($total);
if($show_sql)
{
$t->set_sql($pai_sql);
}
$t->display();
exit();
?>
| Java |
\section{Open Source und Lizenz}\label{open-source-und-lizenz}
\subsection{Open Source}\label{open-source}
Die Ersteller der App arbeiten alle mit Linux und unterstützen dessen
Philosophie der freien Weitergabe von (Quell)offener Software.\\Da der
Quelltext der App teil der Bewertungsgrundlage ist und wir die Plattform
Github verwenden war Open Source von Anfang an Teil des
Entwicklungskonzeptes.\\Das erleichtert nicht nur die kooperative Arbeit
an der App sondern bietet auch anderen Menschen die Möglichkeit den von
uns erstellten Quellcode zum Lernen zu nutzen und weiterzuentwickeln.
\subsubsection{Lizenz}\label{lizenz}
Wir haben uns für die GPLv2 (GNU General Public License) entschieden,
welche die Nutzung, Bearbeitung und Weitergabe des von uns erstellen
Quellcodes regelt.\\Die GPLv2 existiert bereits seit 1991 und ist einer
der am weitesten verbreiteten Softwarelizenzen für freie Software. Sie
gestattet es dem Lizenznehmer die Software frei zu verwenden, bearbeiten
und weiterzuverbreiten. Sie verpflichtet den Lizenznehmer dabei die
Software nur mit dem selbigen Lizenzmodell weiterzugeben was eine
kommerzielle Nutzung unseres Quellcodes weitestgehend ausschließt.
| Java |
<?php
namespace Gh\Gloggiheime\Controller;
use FluidTYPO3\Flux\Controller\AbstractFluxController;
/**
* My custom ContentController to render my package's Content templates.
*
* @package Gloggiheime
* @subpackage Controller
*/
class ContentController extends AbstractFluxController {
/**
* bookingRepository
*
* @var \Gh\Gloggiheime\Domain\Repository\BookingRepository
* @inject
*/
protected $bookingRepository = NULL;
/**
* heimeRepository
*
* @var \Gh\Gloggiheime\Domain\Repository\HeimeRepository
* @inject
*/
protected $heimeRepository = NULL;
public function bookingAction() {
// Fix for stupid Extbase Persistency problems in Repository
$ext_conf = $this->getData();
$heim_id = $ext_conf[settings][flexform][heim_id];
$end_date_months = $ext_conf[settings][flexform][monate];
$heime = $this->heimeRepository->findAll();
$this->view->assign('heime', $heime);
// $bookings = $this->bookingRepository->findAll();
// $this->view->assign('bookings', $bookings);
$query = $this->bookingRepository->createQuery();
$date_start = new \DateTime('-1 month');
// $date_end = new \DateTime('+'.end_date_months.' month');
$query->matching(
$query->greaterThanOrEqual('from_booking', $date_start->format('Y-m-d H:i:s'))
);
debug($query);
$bookings = $query->execute();
$this->view->assign('bookings', $bookings);
$heim = $this->heimeRepository->findByUid($heim_id);
$this->view->assign('selectedheim', $heim);
}
public function preiseAction() {
// print($this);
$heime = $this->heimeRepository->findAll();
$this->view->assign('heime', $heime);
}
public function mapAction() {
$ext_conf = $this->getData();
$heim_id = $ext_conf[settings][flexform][heim_id];
$heimsingle = $this->heimeRepository->findByUid($heim_id);
$this->view->assign('heimsingle', $heimsingle);
// print($this);
$heime = $this->heimeRepository->findAll();
$this->view->assign('heime', $heime);
}
public function detailsAction() {
$ext_conf = $this->getData();
$heim_id = $ext_conf[settings][flexform][heim_id];
$heim = $this->heimeRepository->findByUid($heim_id);
$this->view->assign('heim', $heim);
}
}
?>
| Java |
#!/bin/sh
#
# git-submodule.sh: add, init, update or list git submodules
#
# Copyright (c) 2007 Lars Hjemli
dashless=$(basename "$0" | sed -e 's/-/ /')
USAGE="[--quiet] add [-b <branch>] [-f|--force] [--name <name>] [--reference <repository>] [--] <repository> [<path>]
or: $dashless [--quiet] status [--cached] [--recursive] [--] [<path>...]
or: $dashless [--quiet] init [--] [<path>...]
or: $dashless [--quiet] deinit [-f|--force] (--all| [--] <path>...)
or: $dashless [--quiet] update [--init] [--remote] [-N|--no-fetch] [-f|--force] [--checkout|--merge|--rebase] [--[no-]recommend-shallow] [--reference <repository>] [--recursive] [--] [<path>...]
or: $dashless [--quiet] summary [--cached|--files] [--summary-limit <n>] [commit] [--] [<path>...]
or: $dashless [--quiet] foreach [--recursive] <command>
or: $dashless [--quiet] sync [--recursive] [--] [<path>...]
or: $dashless [--quiet] absorbgitdirs [--] [<path>...]"
OPTIONS_SPEC=
SUBDIRECTORY_OK=Yes
. git-sh-setup
. git-parse-remote
require_work_tree
wt_prefix=$(git rev-parse --show-prefix)
cd_to_toplevel
# Tell the rest of git that any URLs we get don't come
# directly from the user, so it can apply policy as appropriate.
GIT_PROTOCOL_FROM_USER=0
export GIT_PROTOCOL_FROM_USER
command=
branch=
force=
reference=
cached=
recursive=
init=
files=
remote=
nofetch=
update=
prefix=
custom_name=
depth=
progress=
die_if_unmatched ()
{
if test "$1" = "#unmatched"
then
exit ${2:-1}
fi
}
#
# Print a submodule configuration setting
#
# $1 = submodule name
# $2 = option name
# $3 = default value
#
# Checks in the usual git-config places first (for overrides),
# otherwise it falls back on .gitmodules. This allows you to
# distribute project-wide defaults in .gitmodules, while still
# customizing individual repositories if necessary. If the option is
# not in .gitmodules either, print a default value.
#
get_submodule_config () {
name="$1"
option="$2"
default="$3"
value=$(git config submodule."$name"."$option")
if test -z "$value"
then
value=$(git config -f .gitmodules submodule."$name"."$option")
fi
printf '%s' "${value:-$default}"
}
isnumber()
{
n=$(($1 + 0)) 2>/dev/null && test "$n" = "$1"
}
# Sanitize the local git environment for use within a submodule. We
# can't simply use clear_local_git_env since we want to preserve some
# of the settings from GIT_CONFIG_PARAMETERS.
sanitize_submodule_env()
{
save_config=$GIT_CONFIG_PARAMETERS
clear_local_git_env
GIT_CONFIG_PARAMETERS=$save_config
export GIT_CONFIG_PARAMETERS
}
#
# Add a new submodule to the working tree, .gitmodules and the index
#
# $@ = repo path
#
# optional branch is stored in global branch variable
#
cmd_add()
{
# parse $args after "submodule ... add".
reference_path=
while test $# -ne 0
do
case "$1" in
-b | --branch)
case "$2" in '') usage ;; esac
branch=$2
shift
;;
-f | --force)
force=$1
;;
-q|--quiet)
GIT_QUIET=1
;;
--reference)
case "$2" in '') usage ;; esac
reference_path=$2
shift
;;
--reference=*)
reference_path="${1#--reference=}"
;;
--name)
case "$2" in '') usage ;; esac
custom_name=$2
shift
;;
--depth)
case "$2" in '') usage ;; esac
depth="--depth=$2"
shift
;;
--depth=*)
depth=$1
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
if test -n "$reference_path"
then
is_absolute_path "$reference_path" ||
reference_path="$wt_prefix$reference_path"
reference="--reference=$reference_path"
fi
repo=$1
sm_path=$2
if test -z "$sm_path"; then
sm_path=$(printf '%s\n' "$repo" |
sed -e 's|/$||' -e 's|:*/*\.git$||' -e 's|.*[/:]||g')
fi
if test -z "$repo" || test -z "$sm_path"; then
usage
fi
is_absolute_path "$sm_path" || sm_path="$wt_prefix$sm_path"
# assure repo is absolute or relative to parent
case "$repo" in
./*|../*)
test -z "$wt_prefix" ||
die "$(gettext "Relative path can only be used from the toplevel of the working tree")"
# dereference source url relative to parent's url
realrepo=$(git submodule--helper resolve-relative-url "$repo") || exit
;;
*:*|/*)
# absolute url
realrepo=$repo
;;
*)
die "$(eval_gettext "repo URL: '\$repo' must be absolute or begin with ./|../")"
;;
esac
# normalize path:
# multiple //; leading ./; /./; /../; trailing /
sm_path=$(printf '%s/\n' "$sm_path" |
sed -e '
s|//*|/|g
s|^\(\./\)*||
s|/\(\./\)*|/|g
:start
s|\([^/]*\)/\.\./||
tstart
s|/*$||
')
if test -z "$force"
then
git ls-files --error-unmatch "$sm_path" > /dev/null 2>&1 &&
die "$(eval_gettext "'\$sm_path' already exists in the index")"
else
git ls-files -s "$sm_path" | sane_grep -v "^160000" > /dev/null 2>&1 &&
die "$(eval_gettext "'\$sm_path' already exists in the index and is not a submodule")"
fi
if test -z "$force" && ! git add --dry-run --ignore-missing "$sm_path" > /dev/null 2>&1
then
eval_gettextln "The following path is ignored by one of your .gitignore files:
\$sm_path
Use -f if you really want to add it." >&2
exit 1
fi
if test -n "$custom_name"
then
sm_name="$custom_name"
else
sm_name="$sm_path"
fi
# perhaps the path exists and is already a git repo, else clone it
if test -e "$sm_path"
then
if test -d "$sm_path"/.git || test -f "$sm_path"/.git
then
eval_gettextln "Adding existing repo at '\$sm_path' to the index"
else
die "$(eval_gettext "'\$sm_path' already exists and is not a valid git repo")"
fi
else
if test -d ".git/modules/$sm_name"
then
if test -z "$force"
then
eval_gettextln >&2 "A git directory for '\$sm_name' is found locally with remote(s):"
GIT_DIR=".git/modules/$sm_name" GIT_WORK_TREE=. git remote -v | grep '(fetch)' | sed -e s,^," ", -e s,' (fetch)',, >&2
die "$(eval_gettextln "\
If you want to reuse this local git directory instead of cloning again from
\$realrepo
use the '--force' option. If the local git directory is not the correct repo
or you are unsure what this means choose another name with the '--name' option.")"
else
eval_gettextln "Reactivating local git directory for submodule '\$sm_name'."
fi
fi
git submodule--helper clone ${GIT_QUIET:+--quiet} --prefix "$wt_prefix" --path "$sm_path" --name "$sm_name" --url "$realrepo" ${reference:+"$reference"} ${depth:+"$depth"} || exit
(
sanitize_submodule_env
cd "$sm_path" &&
# ash fails to wordsplit ${branch:+-b "$branch"...}
case "$branch" in
'') git checkout -f -q ;;
?*) git checkout -f -q -B "$branch" "origin/$branch" ;;
esac
) || die "$(eval_gettext "Unable to checkout submodule '\$sm_path'")"
fi
git config submodule."$sm_name".url "$realrepo"
git add $force "$sm_path" ||
die "$(eval_gettext "Failed to add submodule '\$sm_path'")"
git config -f .gitmodules submodule."$sm_name".path "$sm_path" &&
git config -f .gitmodules submodule."$sm_name".url "$repo" &&
if test -n "$branch"
then
git config -f .gitmodules submodule."$sm_name".branch "$branch"
fi &&
git add --force .gitmodules ||
die "$(eval_gettext "Failed to register submodule '\$sm_path'")"
}
#
# Execute an arbitrary command sequence in each checked out
# submodule
#
# $@ = command to execute
#
cmd_foreach()
{
# parse $args after "submodule ... foreach".
while test $# -ne 0
do
case "$1" in
-q|--quiet)
GIT_QUIET=1
;;
--recursive)
recursive=1
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
toplevel=$(pwd)
# dup stdin so that it can be restored when running the external
# command in the subshell (and a recursive call to this function)
exec 3<&0
{
git submodule--helper list --prefix "$wt_prefix" ||
echo "#unmatched" $?
} |
while read mode sha1 stage sm_path
do
die_if_unmatched "$mode" "$sha1"
if test -e "$sm_path"/.git
then
displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix")
say "$(eval_gettext "Entering '\$displaypath'")"
name=$(git submodule--helper name "$sm_path")
(
prefix="$prefix$sm_path/"
sanitize_submodule_env
cd "$sm_path" &&
sm_path=$(git submodule--helper relative-path "$sm_path" "$wt_prefix") &&
# we make $path available to scripts ...
path=$sm_path &&
if test $# -eq 1
then
eval "$1"
else
"$@"
fi &&
if test -n "$recursive"
then
cmd_foreach "--recursive" "$@"
fi
) <&3 3<&- ||
die "$(eval_gettext "Stopping at '\$displaypath'; script returned non-zero status.")"
fi
done
}
#
# Register submodules in .git/config
#
# $@ = requested paths (default to all)
#
cmd_init()
{
# parse $args after "submodule ... init".
while test $# -ne 0
do
case "$1" in
-q|--quiet)
GIT_QUIET=1
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
git ${wt_prefix:+-C "$wt_prefix"} ${prefix:+--super-prefix "$prefix"} submodule--helper init ${GIT_QUIET:+--quiet} "$@"
}
#
# Unregister submodules from .git/config and remove their work tree
#
cmd_deinit()
{
# parse $args after "submodule ... deinit".
deinit_all=
while test $# -ne 0
do
case "$1" in
-f|--force)
force=$1
;;
-q|--quiet)
GIT_QUIET=1
;;
--all)
deinit_all=t
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
if test -n "$deinit_all" && test "$#" -ne 0
then
echo >&2 "$(eval_gettext "pathspec and --all are incompatible")"
usage
fi
if test $# = 0 && test -z "$deinit_all"
then
die "$(eval_gettext "Use '--all' if you really want to deinitialize all submodules")"
fi
{
git submodule--helper list --prefix "$wt_prefix" "$@" ||
echo "#unmatched" $?
} |
while read mode sha1 stage sm_path
do
die_if_unmatched "$mode" "$sha1"
name=$(git submodule--helper name "$sm_path") || exit
displaypath=$(git submodule--helper relative-path "$sm_path" "$wt_prefix")
# Remove the submodule work tree (unless the user already did it)
if test -d "$sm_path"
then
# Protect submodules containing a .git directory
if test -d "$sm_path/.git"
then
die "$(eval_gettext "\
Submodule work tree '\$displaypath' contains a .git directory
(use 'rm -rf' if you really want to remove it including all of its history)")"
fi
if test -z "$force"
then
git rm -qn "$sm_path" ||
die "$(eval_gettext "Submodule work tree '\$displaypath' contains local modifications; use '-f' to discard them")"
fi
rm -rf "$sm_path" &&
say "$(eval_gettext "Cleared directory '\$displaypath'")" ||
say "$(eval_gettext "Could not remove submodule work tree '\$displaypath'")"
fi
mkdir "$sm_path" || say "$(eval_gettext "Could not create empty submodule directory '\$displaypath'")"
# Remove the .git/config entries (unless the user already did it)
if test -n "$(git config --get-regexp submodule."$name\.")"
then
# Remove the whole section so we have a clean state when
# the user later decides to init this submodule again
url=$(git config submodule."$name".url)
git config --remove-section submodule."$name" 2>/dev/null &&
say "$(eval_gettext "Submodule '\$name' (\$url) unregistered for path '\$displaypath'")"
fi
done
}
is_tip_reachable () (
sanitize_submodule_env &&
cd "$1" &&
rev=$(git rev-list -n 1 "$2" --not --all 2>/dev/null) &&
test -z "$rev"
)
fetch_in_submodule () (
sanitize_submodule_env &&
cd "$1" &&
case "$2" in
'')
git fetch ;;
*)
shift
git fetch $(get_default_remote) "$@" ;;
esac
)
#
# Update each submodule path to correct revision, using clone and checkout as needed
#
# $@ = requested paths (default to all)
#
cmd_update()
{
# parse $args after "submodule ... update".
while test $# -ne 0
do
case "$1" in
-q|--quiet)
GIT_QUIET=1
;;
--progress)
progress="--progress"
;;
-i|--init)
init=1
;;
--remote)
remote=1
;;
-N|--no-fetch)
nofetch=1
;;
-f|--force)
force=$1
;;
-r|--rebase)
update="rebase"
;;
--reference)
case "$2" in '') usage ;; esac
reference="--reference=$2"
shift
;;
--reference=*)
reference="$1"
;;
-m|--merge)
update="merge"
;;
--recursive)
recursive=1
;;
--checkout)
update="checkout"
;;
--recommend-shallow)
recommend_shallow="--recommend-shallow"
;;
--no-recommend-shallow)
recommend_shallow="--no-recommend-shallow"
;;
--depth)
case "$2" in '') usage ;; esac
depth="--depth=$2"
shift
;;
--depth=*)
depth=$1
;;
-j|--jobs)
case "$2" in '') usage ;; esac
jobs="--jobs=$2"
shift
;;
--jobs=*)
jobs=$1
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
if test -n "$init"
then
cmd_init "--" "$@" || return
fi
{
git submodule--helper update-clone ${GIT_QUIET:+--quiet} \
${progress:+"$progress"} \
${wt_prefix:+--prefix "$wt_prefix"} \
${prefix:+--recursive-prefix "$prefix"} \
${update:+--update "$update"} \
${reference:+"$reference"} \
${depth:+--depth "$depth"} \
${recommend_shallow:+"$recommend_shallow"} \
${jobs:+$jobs} \
"$@" || echo "#unmatched" $?
} | {
err=
while read mode sha1 stage just_cloned sm_path
do
die_if_unmatched "$mode" "$sha1"
name=$(git submodule--helper name "$sm_path") || exit
url=$(git config submodule."$name".url)
if ! test -z "$update"
then
update_module=$update
else
update_module=$(git config submodule."$name".update)
if test -z "$update_module"
then
update_module="checkout"
fi
fi
displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix")
if test $just_cloned -eq 1
then
subsha1=
update_module=checkout
else
subsha1=$(sanitize_submodule_env; cd "$sm_path" &&
git rev-parse --verify HEAD) ||
die "$(eval_gettext "Unable to find current revision in submodule path '\$displaypath'")"
fi
if test -n "$remote"
then
branch=$(git submodule--helper remote-branch "$sm_path")
if test -z "$nofetch"
then
# Fetch remote before determining tracking $sha1
fetch_in_submodule "$sm_path" $depth ||
die "$(eval_gettext "Unable to fetch in submodule path '\$sm_path'")"
fi
remote_name=$(sanitize_submodule_env; cd "$sm_path" && get_default_remote)
sha1=$(sanitize_submodule_env; cd "$sm_path" &&
git rev-parse --verify "${remote_name}/${branch}") ||
die "$(eval_gettext "Unable to find current \${remote_name}/\${branch} revision in submodule path '\$sm_path'")"
fi
if test "$subsha1" != "$sha1" || test -n "$force"
then
subforce=$force
# If we don't already have a -f flag and the submodule has never been checked out
if test -z "$subsha1" && test -z "$force"
then
subforce="-f"
fi
if test -z "$nofetch"
then
# Run fetch only if $sha1 isn't present or it
# is not reachable from a ref.
is_tip_reachable "$sm_path" "$sha1" ||
fetch_in_submodule "$sm_path" $depth ||
die "$(eval_gettext "Unable to fetch in submodule path '\$displaypath'")"
# Now we tried the usual fetch, but $sha1 may
# not be reachable from any of the refs
is_tip_reachable "$sm_path" "$sha1" ||
fetch_in_submodule "$sm_path" $depth "$sha1" ||
die "$(eval_gettext "Fetched in submodule path '\$displaypath', but it did not contain \$sha1. Direct fetching of that commit failed.")"
fi
must_die_on_failure=
case "$update_module" in
checkout)
command="git checkout $subforce -q"
die_msg="$(eval_gettext "Unable to checkout '\$sha1' in submodule path '\$displaypath'")"
say_msg="$(eval_gettext "Submodule path '\$displaypath': checked out '\$sha1'")"
;;
rebase)
command="git rebase"
die_msg="$(eval_gettext "Unable to rebase '\$sha1' in submodule path '\$displaypath'")"
say_msg="$(eval_gettext "Submodule path '\$displaypath': rebased into '\$sha1'")"
must_die_on_failure=yes
;;
merge)
command="git merge"
die_msg="$(eval_gettext "Unable to merge '\$sha1' in submodule path '\$displaypath'")"
say_msg="$(eval_gettext "Submodule path '\$displaypath': merged in '\$sha1'")"
must_die_on_failure=yes
;;
!*)
command="${update_module#!}"
die_msg="$(eval_gettext "Execution of '\$command \$sha1' failed in submodule path '\$displaypath'")"
say_msg="$(eval_gettext "Submodule path '\$displaypath': '\$command \$sha1'")"
must_die_on_failure=yes
;;
*)
die "$(eval_gettext "Invalid update mode '$update_module' for submodule '$name'")"
esac
if (sanitize_submodule_env; cd "$sm_path" && $command "$sha1")
then
say "$say_msg"
elif test -n "$must_die_on_failure"
then
die_with_status 2 "$die_msg"
else
err="${err};$die_msg"
continue
fi
fi
if test -n "$recursive"
then
(
prefix=$(git submodule--helper relative-path "$prefix$sm_path/" "$wt_prefix")
wt_prefix=
sanitize_submodule_env
cd "$sm_path" &&
eval cmd_update
)
res=$?
if test $res -gt 0
then
die_msg="$(eval_gettext "Failed to recurse into submodule path '\$displaypath'")"
if test $res -ne 2
then
err="${err};$die_msg"
continue
else
die_with_status $res "$die_msg"
fi
fi
fi
done
if test -n "$err"
then
OIFS=$IFS
IFS=';'
for e in $err
do
if test -n "$e"
then
echo >&2 "$e"
fi
done
IFS=$OIFS
exit 1
fi
}
}
set_name_rev () {
revname=$( (
sanitize_submodule_env
cd "$1" && {
git describe "$2" 2>/dev/null ||
git describe --tags "$2" 2>/dev/null ||
git describe --contains "$2" 2>/dev/null ||
git describe --all --always "$2"
}
) )
test -z "$revname" || revname=" ($revname)"
}
#
# Show commit summary for submodules in index or working tree
#
# If '--cached' is given, show summary between index and given commit,
# or between working tree and given commit
#
# $@ = [commit (default 'HEAD'),] requested paths (default all)
#
cmd_summary() {
summary_limit=-1
for_status=
diff_cmd=diff-index
# parse $args after "submodule ... summary".
while test $# -ne 0
do
case "$1" in
--cached)
cached="$1"
;;
--files)
files="$1"
;;
--for-status)
for_status="$1"
;;
-n|--summary-limit)
summary_limit="$2"
isnumber "$summary_limit" || usage
shift
;;
--summary-limit=*)
summary_limit="${1#--summary-limit=}"
isnumber "$summary_limit" || usage
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
test $summary_limit = 0 && return
if rev=$(git rev-parse -q --verify --default HEAD ${1+"$1"})
then
head=$rev
test $# = 0 || shift
elif test -z "$1" || test "$1" = "HEAD"
then
# before the first commit: compare with an empty tree
head=$(git hash-object -w -t tree --stdin </dev/null)
test -z "$1" || shift
else
head="HEAD"
fi
if [ -n "$files" ]
then
test -n "$cached" &&
die "$(gettext "The --cached option cannot be used with the --files option")"
diff_cmd=diff-files
head=
fi
cd_to_toplevel
eval "set $(git rev-parse --sq --prefix "$wt_prefix" -- "$@")"
# Get modified modules cared by user
modules=$(git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- "$@" |
sane_egrep '^:([0-7]* )?160000' |
while read mod_src mod_dst sha1_src sha1_dst status sm_path
do
# Always show modules deleted or type-changed (blob<->module)
if test "$status" = D || test "$status" = T
then
printf '%s\n' "$sm_path"
continue
fi
# Respect the ignore setting for --for-status.
if test -n "$for_status"
then
name=$(git submodule--helper name "$sm_path")
ignore_config=$(get_submodule_config "$name" ignore none)
test $status != A && test $ignore_config = all && continue
fi
# Also show added or modified modules which are checked out
GIT_DIR="$sm_path/.git" git-rev-parse --git-dir >/dev/null 2>&1 &&
printf '%s\n' "$sm_path"
done
)
test -z "$modules" && return
git $diff_cmd $cached --ignore-submodules=dirty --raw $head -- $modules |
sane_egrep '^:([0-7]* )?160000' |
cut -c2- |
while read mod_src mod_dst sha1_src sha1_dst status name
do
if test -z "$cached" &&
test $sha1_dst = 0000000000000000000000000000000000000000
then
case "$mod_dst" in
160000)
sha1_dst=$(GIT_DIR="$name/.git" git rev-parse HEAD)
;;
100644 | 100755 | 120000)
sha1_dst=$(git hash-object $name)
;;
000000)
;; # removed
*)
# unexpected type
eval_gettextln "unexpected mode \$mod_dst" >&2
continue ;;
esac
fi
missing_src=
missing_dst=
test $mod_src = 160000 &&
! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_src^0 >/dev/null &&
missing_src=t
test $mod_dst = 160000 &&
! GIT_DIR="$name/.git" git-rev-parse -q --verify $sha1_dst^0 >/dev/null &&
missing_dst=t
display_name=$(git submodule--helper relative-path "$name" "$wt_prefix")
total_commits=
case "$missing_src,$missing_dst" in
t,)
errmsg="$(eval_gettext " Warn: \$display_name doesn't contain commit \$sha1_src")"
;;
,t)
errmsg="$(eval_gettext " Warn: \$display_name doesn't contain commit \$sha1_dst")"
;;
t,t)
errmsg="$(eval_gettext " Warn: \$display_name doesn't contain commits \$sha1_src and \$sha1_dst")"
;;
*)
errmsg=
total_commits=$(
if test $mod_src = 160000 && test $mod_dst = 160000
then
range="$sha1_src...$sha1_dst"
elif test $mod_src = 160000
then
range=$sha1_src
else
range=$sha1_dst
fi
GIT_DIR="$name/.git" \
git rev-list --first-parent $range -- | wc -l
)
total_commits=" ($(($total_commits + 0)))"
;;
esac
sha1_abbr_src=$(echo $sha1_src | cut -c1-7)
sha1_abbr_dst=$(echo $sha1_dst | cut -c1-7)
if test $status = T
then
blob="$(gettext "blob")"
submodule="$(gettext "submodule")"
if test $mod_dst = 160000
then
echo "* $display_name $sha1_abbr_src($blob)->$sha1_abbr_dst($submodule)$total_commits:"
else
echo "* $display_name $sha1_abbr_src($submodule)->$sha1_abbr_dst($blob)$total_commits:"
fi
else
echo "* $display_name $sha1_abbr_src...$sha1_abbr_dst$total_commits:"
fi
if test -n "$errmsg"
then
# Don't give error msg for modification whose dst is not submodule
# i.e. deleted or changed to blob
test $mod_dst = 160000 && echo "$errmsg"
else
if test $mod_src = 160000 && test $mod_dst = 160000
then
limit=
test $summary_limit -gt 0 && limit="-$summary_limit"
GIT_DIR="$name/.git" \
git log $limit --pretty='format: %m %s' \
--first-parent $sha1_src...$sha1_dst
elif test $mod_dst = 160000
then
GIT_DIR="$name/.git" \
git log --pretty='format: > %s' -1 $sha1_dst
else
GIT_DIR="$name/.git" \
git log --pretty='format: < %s' -1 $sha1_src
fi
echo
fi
echo
done
}
#
# List all submodules, prefixed with:
# - submodule not initialized
# + different revision checked out
#
# If --cached was specified the revision in the index will be printed
# instead of the currently checked out revision.
#
# $@ = requested paths (default to all)
#
cmd_status()
{
# parse $args after "submodule ... status".
while test $# -ne 0
do
case "$1" in
-q|--quiet)
GIT_QUIET=1
;;
--cached)
cached=1
;;
--recursive)
recursive=1
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
{
git submodule--helper list --prefix "$wt_prefix" "$@" ||
echo "#unmatched" $?
} |
while read mode sha1 stage sm_path
do
die_if_unmatched "$mode" "$sha1"
name=$(git submodule--helper name "$sm_path") || exit
url=$(git config submodule."$name".url)
displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix")
if test "$stage" = U
then
say "U$sha1 $displaypath"
continue
fi
if test -z "$url" ||
{
! test -d "$sm_path"/.git &&
! test -f "$sm_path"/.git
}
then
say "-$sha1 $displaypath"
continue;
fi
if git diff-files --ignore-submodules=dirty --quiet -- "$sm_path"
then
set_name_rev "$sm_path" "$sha1"
say " $sha1 $displaypath$revname"
else
if test -z "$cached"
then
sha1=$(sanitize_submodule_env; cd "$sm_path" && git rev-parse --verify HEAD)
fi
set_name_rev "$sm_path" "$sha1"
say "+$sha1 $displaypath$revname"
fi
if test -n "$recursive"
then
(
prefix="$displaypath/"
sanitize_submodule_env
wt_prefix=
cd "$sm_path" &&
eval cmd_status
) ||
die "$(eval_gettext "Failed to recurse into submodule path '\$sm_path'")"
fi
done
}
#
# Sync remote urls for submodules
# This makes the value for remote.$remote.url match the value
# specified in .gitmodules.
#
cmd_sync()
{
while test $# -ne 0
do
case "$1" in
-q|--quiet)
GIT_QUIET=1
shift
;;
--recursive)
recursive=1
shift
;;
--)
shift
break
;;
-*)
usage
;;
*)
break
;;
esac
done
cd_to_toplevel
{
git submodule--helper list --prefix "$wt_prefix" "$@" ||
echo "#unmatched" $?
} |
while read mode sha1 stage sm_path
do
die_if_unmatched "$mode" "$sha1"
name=$(git submodule--helper name "$sm_path")
url=$(git config -f .gitmodules --get submodule."$name".url)
# Possibly a url relative to parent
case "$url" in
./*|../*)
# rewrite foo/bar as ../.. to find path from
# submodule work tree to superproject work tree
up_path="$(printf '%s\n' "$sm_path" | sed "s/[^/][^/]*/../g")" &&
# guarantee a trailing /
up_path=${up_path%/}/ &&
# path from submodule work tree to submodule origin repo
sub_origin_url=$(git submodule--helper resolve-relative-url "$url" "$up_path") &&
# path from superproject work tree to submodule origin repo
super_config_url=$(git submodule--helper resolve-relative-url "$url") || exit
;;
*)
sub_origin_url="$url"
super_config_url="$url"
;;
esac
if git config "submodule.$name.url" >/dev/null 2>/dev/null
then
displaypath=$(git submodule--helper relative-path "$prefix$sm_path" "$wt_prefix")
say "$(eval_gettext "Synchronizing submodule url for '\$displaypath'")"
git config submodule."$name".url "$super_config_url"
if test -e "$sm_path"/.git
then
(
sanitize_submodule_env
cd "$sm_path"
remote=$(get_default_remote)
git config remote."$remote".url "$sub_origin_url"
if test -n "$recursive"
then
prefix="$prefix$sm_path/"
eval cmd_sync
fi
)
fi
fi
done
}
cmd_absorbgitdirs()
{
git submodule--helper absorb-git-dirs --prefix "$wt_prefix" "$@"
}
# This loop parses the command line arguments to find the
# subcommand name to dispatch. Parsing of the subcommand specific
# options are primarily done by the subcommand implementations.
# Subcommand specific options such as --branch and --cached are
# parsed here as well, for backward compatibility.
while test $# != 0 && test -z "$command"
do
case "$1" in
add | foreach | init | deinit | update | status | summary | sync | absorbgitdirs)
command=$1
;;
-q|--quiet)
GIT_QUIET=1
;;
-b|--branch)
case "$2" in
'')
usage
;;
esac
branch="$2"; shift
;;
--cached)
cached="$1"
;;
--)
break
;;
-*)
usage
;;
*)
break
;;
esac
shift
done
# No command word defaults to "status"
if test -z "$command"
then
if test $# = 0
then
command=status
else
usage
fi
fi
# "-b branch" is accepted only by "add"
if test -n "$branch" && test "$command" != add
then
usage
fi
# "--cached" is accepted only by "status" and "summary"
if test -n "$cached" && test "$command" != status && test "$command" != summary
then
usage
fi
"cmd_$command" "$@"
| Java |
/*
* Implementation of the security services.
*
* Authors : Stephen Smalley, <sds@epoch.ncsc.mil>
* James Morris <jmorris@redhat.com>
*
* Updated: Trusted Computer Solutions, Inc. <dgoeddel@trustedcs.com>
*
* Support for enhanced MLS infrastructure.
* Support for context based audit filters.
*
* Updated: Frank Mayer <mayerf@tresys.com> and Karl MacMillan <kmacmillan@tresys.com>
*
* Added conditional policy language extensions
*
* Updated: Hewlett-Packard <paul@paul-moore.com>
*
* Added support for NetLabel
* Added support for the policy capability bitmap
*
* Updated: Chad Sellers <csellers@tresys.com>
*
* Added validation of kernel classes and permissions
*
* Updated: KaiGai Kohei <kaigai@ak.jp.nec.com>
*
* Added support for bounds domain and audit messaged on masked permissions
*
* Updated: Guido Trentalancia <guido@trentalancia.com>
*
* Added support for runtime switching of the policy type
*
* Copyright (C) 2008, 2009 NEC Corporation
* Copyright (C) 2006, 2007 Hewlett-Packard Development Company, L.P.
* Copyright (C) 2004-2006 Trusted Computer Solutions, Inc.
* Copyright (C) 2003 - 2004, 2006 Tresys Technology, LLC
* Copyright (C) 2003 Red Hat, Inc., James Morris <jmorris@redhat.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.
*/
#include <linux/kernel.h>
#include <linux/slab.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/rcupdate.h>
#include <linux/errno.h>
#include <linux/in.h>
#include <linux/sched.h>
#include <linux/audit.h>
#include <linux/mutex.h>
#include <linux/selinux.h>
#include <linux/flex_array.h>
#include <linux/vmalloc.h>
#include <net/netlabel.h>
#include "flask.h"
#include "avc.h"
#include "avc_ss.h"
#include "security.h"
#include "context.h"
#include "policydb.h"
#include "sidtab.h"
#include "services.h"
#include "conditional.h"
#include "mls.h"
#include "objsec.h"
#include "netlabel.h"
#include "xfrm.h"
#include "ebitmap.h"
#include "audit.h"
int selinux_policycap_netpeer;
int selinux_policycap_openperm;
static DEFINE_RWLOCK(policy_rwlock);
static struct sidtab sidtab;
struct policydb policydb;
int ss_initialized;
/*
* The largest sequence number that has been used when
* providing an access decision to the access vector cache.
* The sequence number only changes when a policy change
* occurs.
*/
static u32 latest_granting;
/* Forward declaration. */
static int context_struct_to_string(struct context *context, char **scontext,
u32 *scontext_len);
static void context_struct_compute_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
struct av_decision *avd);
struct selinux_mapping {
u16 value; /* policy value */
unsigned num_perms;
u32 perms[sizeof(u32) * 8];
};
static struct selinux_mapping *current_mapping;
static u16 current_mapping_size;
static int selinux_set_mapping(struct policydb *pol,
struct security_class_mapping *map,
struct selinux_mapping **out_map_p,
u16 *out_map_size)
{
struct selinux_mapping *out_map = NULL;
size_t size = sizeof(struct selinux_mapping);
u16 i, j;
unsigned k;
bool print_unknown_handle = false;
/* Find number of classes in the input mapping */
if (!map)
return -EINVAL;
i = 0;
while (map[i].name)
i++;
/* Allocate space for the class records, plus one for class zero */
out_map = kcalloc(++i, size, GFP_ATOMIC);
if (!out_map)
return -ENOMEM;
/* Store the raw class and permission values */
j = 0;
while (map[j].name) {
struct security_class_mapping *p_in = map + (j++);
struct selinux_mapping *p_out = out_map + j;
/* An empty class string skips ahead */
if (!strcmp(p_in->name, "")) {
p_out->num_perms = 0;
continue;
}
p_out->value = string_to_security_class(pol, p_in->name);
if (!p_out->value) {
printk(KERN_INFO
"SELinux: Class %s not defined in policy.\n",
p_in->name);
if (pol->reject_unknown)
goto err;
p_out->num_perms = 0;
print_unknown_handle = true;
continue;
}
k = 0;
while (p_in->perms && p_in->perms[k]) {
/* An empty permission string skips ahead */
if (!*p_in->perms[k]) {
k++;
continue;
}
p_out->perms[k] = string_to_av_perm(pol, p_out->value,
p_in->perms[k]);
if (!p_out->perms[k]) {
printk(KERN_INFO
"SELinux: Permission %s in class %s not defined in policy.\n",
p_in->perms[k], p_in->name);
if (pol->reject_unknown)
goto err;
print_unknown_handle = true;
}
k++;
}
p_out->num_perms = k;
}
if (print_unknown_handle)
printk(KERN_INFO "SELinux: the above unknown classes and permissions will be %s\n",
pol->allow_unknown ? "allowed" : "denied");
*out_map_p = out_map;
*out_map_size = i;
return 0;
err:
kfree(out_map);
return -EINVAL;
}
/*
* Get real, policy values from mapped values
*/
static u16 unmap_class(u16 tclass)
{
if (tclass < current_mapping_size)
return current_mapping[tclass].value;
return tclass;
}
/*
* Get kernel value for class from its policy value
*/
static u16 map_class(u16 pol_value)
{
u16 i;
for (i = 1; i < current_mapping_size; i++) {
if (current_mapping[i].value == pol_value)
return i;
}
return SECCLASS_NULL;
}
static void map_decision(u16 tclass, struct av_decision *avd,
int allow_unknown)
{
if (tclass < current_mapping_size) {
unsigned i, n = current_mapping[tclass].num_perms;
u32 result;
for (i = 0, result = 0; i < n; i++) {
if (avd->allowed & current_mapping[tclass].perms[i])
result |= 1<<i;
if (allow_unknown && !current_mapping[tclass].perms[i])
result |= 1<<i;
}
avd->allowed = result;
for (i = 0, result = 0; i < n; i++)
if (avd->auditallow & current_mapping[tclass].perms[i])
result |= 1<<i;
avd->auditallow = result;
for (i = 0, result = 0; i < n; i++) {
if (avd->auditdeny & current_mapping[tclass].perms[i])
result |= 1<<i;
if (!allow_unknown && !current_mapping[tclass].perms[i])
result |= 1<<i;
}
/*
* In case the kernel has a bug and requests a permission
* between num_perms and the maximum permission number, we
* should audit that denial
*/
for (; i < (sizeof(u32)*8); i++)
result |= 1<<i;
avd->auditdeny = result;
}
}
int security_mls_enabled(void)
{
return policydb.mls_enabled;
}
/*
* Return the boolean value of a constraint expression
* when it is applied to the specified source and target
* security contexts.
*
* xcontext is a special beast... It is used by the validatetrans rules
* only. For these rules, scontext is the context before the transition,
* tcontext is the context after the transition, and xcontext is the context
* of the process performing the transition. All other callers of
* constraint_expr_eval should pass in NULL for xcontext.
*/
static int constraint_expr_eval(struct context *scontext,
struct context *tcontext,
struct context *xcontext,
struct constraint_expr *cexpr)
{
u32 val1, val2;
struct context *c;
struct role_datum *r1, *r2;
struct mls_level *l1, *l2;
struct constraint_expr *e;
int s[CEXPR_MAXDEPTH];
int sp = -1;
for (e = cexpr; e; e = e->next) {
switch (e->expr_type) {
case CEXPR_NOT:
BUG_ON(sp < 0);
s[sp] = !s[sp];
break;
case CEXPR_AND:
BUG_ON(sp < 1);
sp--;
s[sp] &= s[sp + 1];
break;
case CEXPR_OR:
BUG_ON(sp < 1);
sp--;
s[sp] |= s[sp + 1];
break;
case CEXPR_ATTR:
if (sp == (CEXPR_MAXDEPTH - 1))
return 0;
switch (e->attr) {
case CEXPR_USER:
val1 = scontext->user;
val2 = tcontext->user;
break;
case CEXPR_TYPE:
val1 = scontext->type;
val2 = tcontext->type;
break;
case CEXPR_ROLE:
val1 = scontext->role;
val2 = tcontext->role;
r1 = policydb.role_val_to_struct[val1 - 1];
r2 = policydb.role_val_to_struct[val2 - 1];
switch (e->op) {
case CEXPR_DOM:
s[++sp] = ebitmap_get_bit(&r1->dominates,
val2 - 1);
continue;
case CEXPR_DOMBY:
s[++sp] = ebitmap_get_bit(&r2->dominates,
val1 - 1);
continue;
case CEXPR_INCOMP:
s[++sp] = (!ebitmap_get_bit(&r1->dominates,
val2 - 1) &&
!ebitmap_get_bit(&r2->dominates,
val1 - 1));
continue;
default:
break;
}
break;
case CEXPR_L1L2:
l1 = &(scontext->range.level[0]);
l2 = &(tcontext->range.level[0]);
goto mls_ops;
case CEXPR_L1H2:
l1 = &(scontext->range.level[0]);
l2 = &(tcontext->range.level[1]);
goto mls_ops;
case CEXPR_H1L2:
l1 = &(scontext->range.level[1]);
l2 = &(tcontext->range.level[0]);
goto mls_ops;
case CEXPR_H1H2:
l1 = &(scontext->range.level[1]);
l2 = &(tcontext->range.level[1]);
goto mls_ops;
case CEXPR_L1H1:
l1 = &(scontext->range.level[0]);
l2 = &(scontext->range.level[1]);
goto mls_ops;
case CEXPR_L2H2:
l1 = &(tcontext->range.level[0]);
l2 = &(tcontext->range.level[1]);
goto mls_ops;
mls_ops:
switch (e->op) {
case CEXPR_EQ:
s[++sp] = mls_level_eq(l1, l2);
continue;
case CEXPR_NEQ:
s[++sp] = !mls_level_eq(l1, l2);
continue;
case CEXPR_DOM:
s[++sp] = mls_level_dom(l1, l2);
continue;
case CEXPR_DOMBY:
s[++sp] = mls_level_dom(l2, l1);
continue;
case CEXPR_INCOMP:
s[++sp] = mls_level_incomp(l2, l1);
continue;
default:
BUG();
return 0;
}
break;
default:
BUG();
return 0;
}
switch (e->op) {
case CEXPR_EQ:
s[++sp] = (val1 == val2);
break;
case CEXPR_NEQ:
s[++sp] = (val1 != val2);
break;
default:
BUG();
return 0;
}
break;
case CEXPR_NAMES:
if (sp == (CEXPR_MAXDEPTH-1))
return 0;
c = scontext;
if (e->attr & CEXPR_TARGET)
c = tcontext;
else if (e->attr & CEXPR_XTARGET) {
c = xcontext;
if (!c) {
BUG();
return 0;
}
}
if (e->attr & CEXPR_USER)
val1 = c->user;
else if (e->attr & CEXPR_ROLE)
val1 = c->role;
else if (e->attr & CEXPR_TYPE)
val1 = c->type;
else {
BUG();
return 0;
}
switch (e->op) {
case CEXPR_EQ:
s[++sp] = ebitmap_get_bit(&e->names, val1 - 1);
break;
case CEXPR_NEQ:
s[++sp] = !ebitmap_get_bit(&e->names, val1 - 1);
break;
default:
BUG();
return 0;
}
break;
default:
BUG();
return 0;
}
}
BUG_ON(sp != 0);
return s[0];
}
/*
* security_dump_masked_av - dumps masked permissions during
* security_compute_av due to RBAC, MLS/Constraint and Type bounds.
*/
static int dump_masked_av_helper(void *k, void *d, void *args)
{
struct perm_datum *pdatum = d;
char **permission_names = args;
BUG_ON(pdatum->value < 1 || pdatum->value > 32);
permission_names[pdatum->value - 1] = (char *)k;
return 0;
}
static void security_dump_masked_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
u32 permissions,
const char *reason)
{
struct common_datum *common_dat;
struct class_datum *tclass_dat;
struct audit_buffer *ab;
char *tclass_name;
char *scontext_name = NULL;
char *tcontext_name = NULL;
char *permission_names[32];
int index;
u32 length;
bool need_comma = false;
if (!permissions)
return;
tclass_name = sym_name(&policydb, SYM_CLASSES, tclass - 1);
tclass_dat = policydb.class_val_to_struct[tclass - 1];
common_dat = tclass_dat->comdatum;
/* init permission_names */
if (common_dat &&
hashtab_map(common_dat->permissions.table,
dump_masked_av_helper, permission_names) < 0)
goto out;
if (hashtab_map(tclass_dat->permissions.table,
dump_masked_av_helper, permission_names) < 0)
goto out;
/* get scontext/tcontext in text form */
if (context_struct_to_string(scontext,
&scontext_name, &length) < 0)
goto out;
if (context_struct_to_string(tcontext,
&tcontext_name, &length) < 0)
goto out;
/* audit a message */
ab = audit_log_start(current->audit_context,
GFP_ATOMIC, AUDIT_SELINUX_ERR);
if (!ab)
goto out;
audit_log_format(ab, "op=security_compute_av reason=%s "
"scontext=%s tcontext=%s tclass=%s perms=",
reason, scontext_name, tcontext_name, tclass_name);
for (index = 0; index < 32; index++) {
u32 mask = (1 << index);
if ((mask & permissions) == 0)
continue;
audit_log_format(ab, "%s%s",
need_comma ? "," : "",
permission_names[index]
? permission_names[index] : "????");
need_comma = true;
}
audit_log_end(ab);
out:
/* release scontext/tcontext */
kfree(tcontext_name);
kfree(scontext_name);
return;
}
/*
* security_boundary_permission - drops violated permissions
* on boundary constraint.
*/
static void type_attribute_bounds_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
struct av_decision *avd)
{
struct context lo_scontext;
struct context lo_tcontext;
struct av_decision lo_avd;
struct type_datum *source;
struct type_datum *target;
u32 masked = 0;
source = flex_array_get_ptr(policydb.type_val_to_struct_array,
scontext->type - 1);
BUG_ON(!source);
target = flex_array_get_ptr(policydb.type_val_to_struct_array,
tcontext->type - 1);
BUG_ON(!target);
if (source->bounds) {
memset(&lo_avd, 0, sizeof(lo_avd));
memcpy(&lo_scontext, scontext, sizeof(lo_scontext));
lo_scontext.type = source->bounds;
context_struct_compute_av(&lo_scontext,
tcontext,
tclass,
&lo_avd);
if ((lo_avd.allowed & avd->allowed) == avd->allowed)
return; /* no masked permission */
masked = ~lo_avd.allowed & avd->allowed;
}
if (target->bounds) {
memset(&lo_avd, 0, sizeof(lo_avd));
memcpy(&lo_tcontext, tcontext, sizeof(lo_tcontext));
lo_tcontext.type = target->bounds;
context_struct_compute_av(scontext,
&lo_tcontext,
tclass,
&lo_avd);
if ((lo_avd.allowed & avd->allowed) == avd->allowed)
return; /* no masked permission */
masked = ~lo_avd.allowed & avd->allowed;
}
if (source->bounds && target->bounds) {
memset(&lo_avd, 0, sizeof(lo_avd));
/*
* lo_scontext and lo_tcontext are already
* set up.
*/
context_struct_compute_av(&lo_scontext,
&lo_tcontext,
tclass,
&lo_avd);
if ((lo_avd.allowed & avd->allowed) == avd->allowed)
return; /* no masked permission */
masked = ~lo_avd.allowed & avd->allowed;
}
if (masked) {
/* mask violated permissions */
avd->allowed &= ~masked;
/* audit masked permissions */
security_dump_masked_av(scontext, tcontext,
tclass, masked, "bounds");
}
}
/*
* Compute access vectors based on a context structure pair for
* the permissions in a particular class.
*/
static void context_struct_compute_av(struct context *scontext,
struct context *tcontext,
u16 tclass,
struct av_decision *avd)
{
struct constraint_node *constraint;
struct role_allow *ra;
struct avtab_key avkey;
struct avtab_node *node;
struct class_datum *tclass_datum;
struct ebitmap *sattr, *tattr;
struct ebitmap_node *snode, *tnode;
unsigned int i, j;
avd->allowed = 0;
avd->auditallow = 0;
avd->auditdeny = 0xffffffff;
if (unlikely(!tclass || tclass > policydb.p_classes.nprim)) {
if (printk_ratelimit())
printk(KERN_WARNING "SELinux: Invalid class %hu\n", tclass);
return;
}
tclass_datum = policydb.class_val_to_struct[tclass - 1];
/*
* If a specific type enforcement rule was defined for
* this permission check, then use it.
*/
avkey.target_class = tclass;
avkey.specified = AVTAB_AV;
sattr = flex_array_get(policydb.type_attr_map_array, scontext->type - 1);
BUG_ON(!sattr);
tattr = flex_array_get(policydb.type_attr_map_array, tcontext->type - 1);
BUG_ON(!tattr);
ebitmap_for_each_positive_bit(sattr, snode, i) {
ebitmap_for_each_positive_bit(tattr, tnode, j) {
avkey.source_type = i + 1;
avkey.target_type = j + 1;
for (node = avtab_search_node(&policydb.te_avtab, &avkey);
node;
node = avtab_search_node_next(node, avkey.specified)) {
if (node->key.specified == AVTAB_ALLOWED)
avd->allowed |= node->datum.data;
else if (node->key.specified == AVTAB_AUDITALLOW)
avd->auditallow |= node->datum.data;
else if (node->key.specified == AVTAB_AUDITDENY)
avd->auditdeny &= node->datum.data;
}
/* Check conditional av table for additional permissions */
cond_compute_av(&policydb.te_cond_avtab, &avkey, avd);
}
}
/*
* Remove any permissions prohibited by a constraint (this includes
* the MLS policy).
*/
constraint = tclass_datum->constraints;
while (constraint) {
if ((constraint->permissions & (avd->allowed)) &&
!constraint_expr_eval(scontext, tcontext, NULL,
constraint->expr)) {
avd->allowed &= ~(constraint->permissions);
}
constraint = constraint->next;
}
/*
* If checking process transition permission and the
* role is changing, then check the (current_role, new_role)
* pair.
*/
if (tclass == policydb.process_class &&
(avd->allowed & policydb.process_trans_perms) &&
scontext->role != tcontext->role) {
for (ra = policydb.role_allow; ra; ra = ra->next) {
if (scontext->role == ra->role &&
tcontext->role == ra->new_role)
break;
}
if (!ra)
avd->allowed &= ~policydb.process_trans_perms;
}
/*
* If the given source and target types have boundary
* constraint, lazy checks have to mask any violated
* permission and notice it to userspace via audit.
*/
type_attribute_bounds_av(scontext, tcontext,
tclass, avd);
}
static int security_validtrans_handle_fail(struct context *ocontext,
struct context *ncontext,
struct context *tcontext,
u16 tclass)
{
char *o = NULL, *n = NULL, *t = NULL;
u32 olen, nlen, tlen;
if (context_struct_to_string(ocontext, &o, &olen))
goto out;
if (context_struct_to_string(ncontext, &n, &nlen))
goto out;
if (context_struct_to_string(tcontext, &t, &tlen))
goto out;
audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"security_validate_transition: denied for"
" oldcontext=%s newcontext=%s taskcontext=%s tclass=%s",
o, n, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
out:
kfree(o);
kfree(n);
kfree(t);
#ifdef CONFIG_ALWAYS_ENFORCE
selinux_enforcing = 1;
#endif
if (!selinux_enforcing)
return 0;
return -EPERM;
}
int security_validate_transition(u32 oldsid, u32 newsid, u32 tasksid,
u16 orig_tclass)
{
struct context *ocontext;
struct context *ncontext;
struct context *tcontext;
struct class_datum *tclass_datum;
struct constraint_node *constraint;
u16 tclass;
int rc = 0;
if (!ss_initialized)
return 0;
read_lock(&policy_rwlock);
tclass = unmap_class(orig_tclass);
if (!tclass || tclass > policydb.p_classes.nprim) {
printk(KERN_ERR "SELinux: %s: unrecognized class %d\n",
__func__, tclass);
rc = -EINVAL;
goto out;
}
tclass_datum = policydb.class_val_to_struct[tclass - 1];
ocontext = sidtab_search(&sidtab, oldsid);
if (!ocontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, oldsid);
rc = -EINVAL;
goto out;
}
ncontext = sidtab_search(&sidtab, newsid);
if (!ncontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, newsid);
rc = -EINVAL;
goto out;
}
tcontext = sidtab_search(&sidtab, tasksid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tasksid);
rc = -EINVAL;
goto out;
}
constraint = tclass_datum->validatetrans;
while (constraint) {
if (!constraint_expr_eval(ocontext, ncontext, tcontext,
constraint->expr)) {
rc = security_validtrans_handle_fail(ocontext, ncontext,
tcontext, tclass);
goto out;
}
constraint = constraint->next;
}
out:
read_unlock(&policy_rwlock);
return rc;
}
/*
* security_bounded_transition - check whether the given
* transition is directed to bounded, or not.
* It returns 0, if @newsid is bounded by @oldsid.
* Otherwise, it returns error code.
*
* @oldsid : current security identifier
* @newsid : destinated security identifier
*/
int security_bounded_transition(u32 old_sid, u32 new_sid)
{
struct context *old_context, *new_context;
struct type_datum *type;
int index;
int rc;
read_lock(&policy_rwlock);
rc = -EINVAL;
old_context = sidtab_search(&sidtab, old_sid);
if (!old_context) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
__func__, old_sid);
goto out;
}
rc = -EINVAL;
new_context = sidtab_search(&sidtab, new_sid);
if (!new_context) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %u\n",
__func__, new_sid);
goto out;
}
rc = 0;
/* type/domain unchanged */
if (old_context->type == new_context->type)
goto out;
index = new_context->type;
while (true) {
type = flex_array_get_ptr(policydb.type_val_to_struct_array,
index - 1);
BUG_ON(!type);
/* not bounded anymore */
rc = -EPERM;
if (!type->bounds)
break;
/* @newsid is bounded by @oldsid */
rc = 0;
if (type->bounds == old_context->type)
break;
index = type->bounds;
}
if (rc) {
char *old_name = NULL;
char *new_name = NULL;
u32 length;
if (!context_struct_to_string(old_context,
&old_name, &length) &&
!context_struct_to_string(new_context,
&new_name, &length)) {
audit_log(current->audit_context,
GFP_ATOMIC, AUDIT_SELINUX_ERR,
"op=security_bounded_transition "
"result=denied "
"oldcontext=%s newcontext=%s",
old_name, new_name);
}
kfree(new_name);
kfree(old_name);
}
out:
read_unlock(&policy_rwlock);
return rc;
}
static void avd_init(struct av_decision *avd)
{
avd->allowed = 0;
avd->auditallow = 0;
avd->auditdeny = 0xffffffff;
avd->seqno = latest_granting;
avd->flags = 0;
}
/**
* security_compute_av - Compute access vector decisions.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @avd: access vector decisions
*
* Compute a set of access vector decisions based on the
* SID pair (@ssid, @tsid) for the permissions in @tclass.
*/
void security_compute_av(u32 ssid,
u32 tsid,
u16 orig_tclass,
struct av_decision *avd)
{
u16 tclass;
struct context *scontext = NULL, *tcontext = NULL;
read_lock(&policy_rwlock);
avd_init(avd);
if (!ss_initialized)
goto allow;
scontext = sidtab_search(&sidtab, ssid);
if (!scontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, ssid);
goto out;
}
/* permissive domain? */
if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
avd->flags |= AVD_FLAGS_PERMISSIVE;
tcontext = sidtab_search(&sidtab, tsid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tsid);
goto out;
}
tclass = unmap_class(orig_tclass);
if (unlikely(orig_tclass && !tclass)) {
if (policydb.allow_unknown)
goto allow;
goto out;
}
context_struct_compute_av(scontext, tcontext, tclass, avd);
map_decision(orig_tclass, avd, policydb.allow_unknown);
out:
read_unlock(&policy_rwlock);
return;
allow:
avd->allowed = 0xffffffff;
goto out;
}
void security_compute_av_user(u32 ssid,
u32 tsid,
u16 tclass,
struct av_decision *avd)
{
struct context *scontext = NULL, *tcontext = NULL;
read_lock(&policy_rwlock);
avd_init(avd);
if (!ss_initialized)
goto allow;
scontext = sidtab_search(&sidtab, ssid);
if (!scontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, ssid);
goto out;
}
/* permissive domain? */
if (ebitmap_get_bit(&policydb.permissive_map, scontext->type))
avd->flags |= AVD_FLAGS_PERMISSIVE;
tcontext = sidtab_search(&sidtab, tsid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tsid);
goto out;
}
if (unlikely(!tclass)) {
if (policydb.allow_unknown)
goto allow;
goto out;
}
context_struct_compute_av(scontext, tcontext, tclass, avd);
out:
read_unlock(&policy_rwlock);
return;
allow:
avd->allowed = 0xffffffff;
goto out;
}
/*
* Write the security context string representation of
* the context structure `context' into a dynamically
* allocated string of the correct size. Set `*scontext'
* to point to this string and set `*scontext_len' to
* the length of the string.
*/
static int context_struct_to_string(struct context *context, char **scontext, u32 *scontext_len)
{
char *scontextp;
if (scontext)
*scontext = NULL;
*scontext_len = 0;
if (context->len) {
*scontext_len = context->len;
if (scontext) {
*scontext = kstrdup(context->str, GFP_ATOMIC);
if (!(*scontext))
return -ENOMEM;
}
return 0;
}
/* Compute the size of the context. */
*scontext_len += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) + 1;
*scontext_len += strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) + 1;
*scontext_len += strlen(sym_name(&policydb, SYM_TYPES, context->type - 1)) + 1;
*scontext_len += mls_compute_context_len(context);
if (!scontext)
return 0;
/* Allocate space for the context; caller must free this space. */
scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
if (!scontextp)
return -ENOMEM;
*scontext = scontextp;
/*
* Copy the user name, role name and type name into the context.
*/
sprintf(scontextp, "%s:%s:%s",
sym_name(&policydb, SYM_USERS, context->user - 1),
sym_name(&policydb, SYM_ROLES, context->role - 1),
sym_name(&policydb, SYM_TYPES, context->type - 1));
scontextp += strlen(sym_name(&policydb, SYM_USERS, context->user - 1)) +
1 + strlen(sym_name(&policydb, SYM_ROLES, context->role - 1)) +
1 + strlen(sym_name(&policydb, SYM_TYPES, context->type - 1));
mls_sid_to_context(context, &scontextp);
*scontextp = 0;
return 0;
}
#include "initial_sid_to_string.h"
const char *security_get_initial_sid_context(u32 sid)
{
if (unlikely(sid > SECINITSID_NUM))
return NULL;
return initial_sid_to_string[sid];
}
static int security_sid_to_context_core(u32 sid, char **scontext,
u32 *scontext_len, int force)
{
struct context *context;
int rc = 0;
if (scontext)
*scontext = NULL;
*scontext_len = 0;
if (!ss_initialized) {
if (sid <= SECINITSID_NUM) {
char *scontextp;
*scontext_len = strlen(initial_sid_to_string[sid]) + 1;
if (!scontext)
goto out;
scontextp = kmalloc(*scontext_len, GFP_ATOMIC);
if (!scontextp) {
rc = -ENOMEM;
goto out;
}
strcpy(scontextp, initial_sid_to_string[sid]);
*scontext = scontextp;
goto out;
}
printk(KERN_ERR "SELinux: %s: called before initial "
"load_policy on unknown SID %d\n", __func__, sid);
rc = -EINVAL;
goto out;
}
read_lock(&policy_rwlock);
if (force)
context = sidtab_search_force(&sidtab, sid);
else
context = sidtab_search(&sidtab, sid);
if (!context) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, sid);
rc = -EINVAL;
goto out_unlock;
}
rc = context_struct_to_string(context, scontext, scontext_len);
out_unlock:
read_unlock(&policy_rwlock);
out:
return rc;
}
/**
* security_sid_to_context - Obtain a context for a given SID.
* @sid: security identifier, SID
* @scontext: security context
* @scontext_len: length in bytes
*
* Write the string representation of the context associated with @sid
* into a dynamically allocated string of the correct size. Set @scontext
* to point to this string and set @scontext_len to the length of the string.
*/
int security_sid_to_context(u32 sid, char **scontext, u32 *scontext_len)
{
return security_sid_to_context_core(sid, scontext, scontext_len, 0);
}
int security_sid_to_context_force(u32 sid, char **scontext, u32 *scontext_len)
{
return security_sid_to_context_core(sid, scontext, scontext_len, 1);
}
/*
* Caveat: Mutates scontext.
*/
static int string_to_context_struct(struct policydb *pol,
struct sidtab *sidtabp,
char *scontext,
u32 scontext_len,
struct context *ctx,
u32 def_sid)
{
struct role_datum *role;
struct type_datum *typdatum;
struct user_datum *usrdatum;
char *scontextp, *p, oldc;
int rc = 0;
context_init(ctx);
/* Parse the security context. */
rc = -EINVAL;
scontextp = (char *) scontext;
/* Extract the user. */
p = scontextp;
while (*p && *p != ':')
p++;
if (*p == 0)
goto out;
*p++ = 0;
usrdatum = hashtab_search(pol->p_users.table, scontextp);
if (!usrdatum)
goto out;
ctx->user = usrdatum->value;
/* Extract role. */
scontextp = p;
while (*p && *p != ':')
p++;
if (*p == 0)
goto out;
*p++ = 0;
role = hashtab_search(pol->p_roles.table, scontextp);
if (!role)
goto out;
ctx->role = role->value;
/* Extract type. */
scontextp = p;
while (*p && *p != ':')
p++;
oldc = *p;
*p++ = 0;
typdatum = hashtab_search(pol->p_types.table, scontextp);
if (!typdatum || typdatum->attribute)
goto out;
ctx->type = typdatum->value;
rc = mls_context_to_sid(pol, oldc, &p, ctx, sidtabp, def_sid);
if (rc)
goto out;
rc = -EINVAL;
if ((p - scontext) < scontext_len)
goto out;
/* Check the validity of the new context. */
if (!policydb_context_isvalid(pol, ctx))
goto out;
rc = 0;
out:
if (rc)
context_destroy(ctx);
return rc;
}
static int security_context_to_sid_core(const char *scontext, u32 scontext_len,
u32 *sid, u32 def_sid, gfp_t gfp_flags,
int force)
{
char *scontext2, *str = NULL;
struct context context;
int rc = 0;
/* An empty security context is never valid. */
if (!scontext_len)
return -EINVAL;
/* An empty security context is never valid. */
if (!scontext_len)
return -EINVAL;
if (!ss_initialized) {
int i;
for (i = 1; i < SECINITSID_NUM; i++) {
if (!strcmp(initial_sid_to_string[i], scontext)) {
*sid = i;
return 0;
}
}
*sid = SECINITSID_KERNEL;
return 0;
}
*sid = SECSID_NULL;
/* Copy the string so that we can modify the copy as we parse it. */
scontext2 = kmalloc(scontext_len + 1, gfp_flags);
if (!scontext2)
return -ENOMEM;
memcpy(scontext2, scontext, scontext_len);
scontext2[scontext_len] = 0;
if (force) {
/* Save another copy for storing in uninterpreted form */
rc = -ENOMEM;
str = kstrdup(scontext2, gfp_flags);
if (!str)
goto out;
}
read_lock(&policy_rwlock);
rc = string_to_context_struct(&policydb, &sidtab, scontext2,
scontext_len, &context, def_sid);
if (rc == -EINVAL && force) {
context.str = str;
context.len = scontext_len;
str = NULL;
} else if (rc)
goto out_unlock;
rc = sidtab_context_to_sid(&sidtab, &context, sid);
context_destroy(&context);
out_unlock:
read_unlock(&policy_rwlock);
out:
kfree(scontext2);
kfree(str);
return rc;
}
/**
* security_context_to_sid - Obtain a SID for a given security context.
* @scontext: security context
* @scontext_len: length in bytes
* @sid: security identifier, SID
*
* Obtains a SID associated with the security context that
* has the string representation specified by @scontext.
* Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
* memory is available, or 0 on success.
*/
int security_context_to_sid(const char *scontext, u32 scontext_len, u32 *sid)
{
return security_context_to_sid_core(scontext, scontext_len,
sid, SECSID_NULL, GFP_KERNEL, 0);
}
/**
* security_context_to_sid_default - Obtain a SID for a given security context,
* falling back to specified default if needed.
*
* @scontext: security context
* @scontext_len: length in bytes
* @sid: security identifier, SID
* @def_sid: default SID to assign on error
*
* Obtains a SID associated with the security context that
* has the string representation specified by @scontext.
* The default SID is passed to the MLS layer to be used to allow
* kernel labeling of the MLS field if the MLS field is not present
* (for upgrading to MLS without full relabel).
* Implicitly forces adding of the context even if it cannot be mapped yet.
* Returns -%EINVAL if the context is invalid, -%ENOMEM if insufficient
* memory is available, or 0 on success.
*/
int security_context_to_sid_default(const char *scontext, u32 scontext_len,
u32 *sid, u32 def_sid, gfp_t gfp_flags)
{
return security_context_to_sid_core(scontext, scontext_len,
sid, def_sid, gfp_flags, 1);
}
int security_context_to_sid_force(const char *scontext, u32 scontext_len,
u32 *sid)
{
return security_context_to_sid_core(scontext, scontext_len,
sid, SECSID_NULL, GFP_KERNEL, 1);
}
static int compute_sid_handle_invalid_context(
struct context *scontext,
struct context *tcontext,
u16 tclass,
struct context *newcontext)
{
char *s = NULL, *t = NULL, *n = NULL;
u32 slen, tlen, nlen;
if (context_struct_to_string(scontext, &s, &slen))
goto out;
if (context_struct_to_string(tcontext, &t, &tlen))
goto out;
if (context_struct_to_string(newcontext, &n, &nlen))
goto out;
audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"security_compute_sid: invalid context %s"
" for scontext=%s"
" tcontext=%s"
" tclass=%s",
n, s, t, sym_name(&policydb, SYM_CLASSES, tclass-1));
out:
kfree(s);
kfree(t);
kfree(n);
#ifdef CONFIG_ALWAYS_ENFORCE
selinux_enforcing = 1;
#endif
if (!selinux_enforcing)
return 0;
return -EACCES;
}
static void filename_compute_type(struct policydb *p, struct context *newcontext,
u32 stype, u32 ttype, u16 tclass,
const char *objname)
{
struct filename_trans ft;
struct filename_trans_datum *otype;
/*
* Most filename trans rules are going to live in specific directories
* like /dev or /var/run. This bitmap will quickly skip rule searches
* if the ttype does not contain any rules.
*/
if (!ebitmap_get_bit(&p->filename_trans_ttypes, ttype))
return;
ft.stype = stype;
ft.ttype = ttype;
ft.tclass = tclass;
ft.name = objname;
otype = hashtab_search(p->filename_trans, &ft);
if (otype)
newcontext->type = otype->otype;
}
static int security_compute_sid(u32 ssid,
u32 tsid,
u16 orig_tclass,
u32 specified,
const char *objname,
u32 *out_sid,
bool kern)
{
struct class_datum *cladatum = NULL;
struct context *scontext = NULL, *tcontext = NULL, newcontext;
struct role_trans *roletr = NULL;
struct avtab_key avkey;
struct avtab_datum *avdatum;
struct avtab_node *node;
u16 tclass;
int rc = 0;
bool sock;
if (!ss_initialized) {
switch (orig_tclass) {
case SECCLASS_PROCESS: /* kernel value */
*out_sid = ssid;
break;
default:
*out_sid = tsid;
break;
}
goto out;
}
context_init(&newcontext);
read_lock(&policy_rwlock);
if (kern) {
tclass = unmap_class(orig_tclass);
sock = security_is_socket_class(orig_tclass);
} else {
tclass = orig_tclass;
sock = security_is_socket_class(map_class(tclass));
}
scontext = sidtab_search(&sidtab, ssid);
if (!scontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, ssid);
rc = -EINVAL;
goto out_unlock;
}
tcontext = sidtab_search(&sidtab, tsid);
if (!tcontext) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, tsid);
rc = -EINVAL;
goto out_unlock;
}
if (tclass && tclass <= policydb.p_classes.nprim)
cladatum = policydb.class_val_to_struct[tclass - 1];
/* Set the user identity. */
switch (specified) {
case AVTAB_TRANSITION:
case AVTAB_CHANGE:
if (cladatum && cladatum->default_user == DEFAULT_TARGET) {
newcontext.user = tcontext->user;
} else {
/* notice this gets both DEFAULT_SOURCE and unset */
/* Use the process user identity. */
newcontext.user = scontext->user;
}
break;
case AVTAB_MEMBER:
/* Use the related object owner. */
newcontext.user = tcontext->user;
break;
}
/* Set the role to default values. */
if (cladatum && cladatum->default_role == DEFAULT_SOURCE) {
newcontext.role = scontext->role;
} else if (cladatum && cladatum->default_role == DEFAULT_TARGET) {
newcontext.role = tcontext->role;
} else {
if ((tclass == policydb.process_class) || (sock == true))
newcontext.role = scontext->role;
else
newcontext.role = OBJECT_R_VAL;
}
/* Set the type to default values. */
if (cladatum && cladatum->default_type == DEFAULT_SOURCE) {
newcontext.type = scontext->type;
} else if (cladatum && cladatum->default_type == DEFAULT_TARGET) {
newcontext.type = tcontext->type;
} else {
if ((tclass == policydb.process_class) || (sock == true)) {
/* Use the type of process. */
newcontext.type = scontext->type;
} else {
/* Use the type of the related object. */
newcontext.type = tcontext->type;
}
}
/* Look for a type transition/member/change rule. */
avkey.source_type = scontext->type;
avkey.target_type = tcontext->type;
avkey.target_class = tclass;
avkey.specified = specified;
avdatum = avtab_search(&policydb.te_avtab, &avkey);
/* If no permanent rule, also check for enabled conditional rules */
if (!avdatum) {
node = avtab_search_node(&policydb.te_cond_avtab, &avkey);
for (; node; node = avtab_search_node_next(node, specified)) {
if (node->key.specified & AVTAB_ENABLED) {
avdatum = &node->datum;
break;
}
}
}
if (avdatum) {
/* Use the type from the type transition/member/change rule. */
newcontext.type = avdatum->data;
}
/* if we have a objname this is a file trans check so check those rules */
if (objname)
filename_compute_type(&policydb, &newcontext, scontext->type,
tcontext->type, tclass, objname);
/* Check for class-specific changes. */
if (specified & AVTAB_TRANSITION) {
/* Look for a role transition rule. */
for (roletr = policydb.role_tr; roletr; roletr = roletr->next) {
if ((roletr->role == scontext->role) &&
(roletr->type == tcontext->type) &&
(roletr->tclass == tclass)) {
/* Use the role transition rule. */
newcontext.role = roletr->new_role;
break;
}
}
}
/* Set the MLS attributes.
This is done last because it may allocate memory. */
rc = mls_compute_sid(scontext, tcontext, tclass, specified,
&newcontext, sock);
if (rc)
goto out_unlock;
/* Check the validity of the context. */
if (!policydb_context_isvalid(&policydb, &newcontext)) {
rc = compute_sid_handle_invalid_context(scontext,
tcontext,
tclass,
&newcontext);
if (rc)
goto out_unlock;
}
/* Obtain the sid for the context. */
rc = sidtab_context_to_sid(&sidtab, &newcontext, out_sid);
out_unlock:
read_unlock(&policy_rwlock);
context_destroy(&newcontext);
out:
return rc;
}
/**
* security_transition_sid - Compute the SID for a new subject/object.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @out_sid: security identifier for new subject/object
*
* Compute a SID to use for labeling a new subject or object in the
* class @tclass based on a SID pair (@ssid, @tsid).
* Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
* if insufficient memory is available, or %0 if the new SID was
* computed successfully.
*/
int security_transition_sid(u32 ssid, u32 tsid, u16 tclass,
const struct qstr *qstr, u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
qstr ? qstr->name : NULL, out_sid, true);
}
int security_transition_sid_user(u32 ssid, u32 tsid, u16 tclass,
const char *objname, u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_TRANSITION,
objname, out_sid, false);
}
/**
* security_member_sid - Compute the SID for member selection.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @out_sid: security identifier for selected member
*
* Compute a SID to use when selecting a member of a polyinstantiated
* object of class @tclass based on a SID pair (@ssid, @tsid).
* Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
* if insufficient memory is available, or %0 if the SID was
* computed successfully.
*/
int security_member_sid(u32 ssid,
u32 tsid,
u16 tclass,
u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_MEMBER, NULL,
out_sid, false);
}
/**
* security_change_sid - Compute the SID for object relabeling.
* @ssid: source security identifier
* @tsid: target security identifier
* @tclass: target security class
* @out_sid: security identifier for selected member
*
* Compute a SID to use for relabeling an object of class @tclass
* based on a SID pair (@ssid, @tsid).
* Return -%EINVAL if any of the parameters are invalid, -%ENOMEM
* if insufficient memory is available, or %0 if the SID was
* computed successfully.
*/
int security_change_sid(u32 ssid,
u32 tsid,
u16 tclass,
u32 *out_sid)
{
return security_compute_sid(ssid, tsid, tclass, AVTAB_CHANGE, NULL,
out_sid, false);
}
/* Clone the SID into the new SID table. */
static int clone_sid(u32 sid,
struct context *context,
void *arg)
{
struct sidtab *s = arg;
if (sid > SECINITSID_NUM)
return sidtab_insert(s, sid, context);
else
return 0;
}
static inline int convert_context_handle_invalid_context(struct context *context)
{
char *s;
u32 len;
#ifdef CONFIG_ALWAYS_ENFORCE
selinux_enforcing = 1;
#endif
if (selinux_enforcing)
return -EINVAL;
if (!context_struct_to_string(context, &s, &len)) {
printk(KERN_WARNING "SELinux: Context %s would be invalid if enforcing\n", s);
kfree(s);
}
return 0;
}
struct convert_context_args {
struct policydb *oldp;
struct policydb *newp;
};
/*
* Convert the values in the security context
* structure `c' from the values specified
* in the policy `p->oldp' to the values specified
* in the policy `p->newp'. Verify that the
* context is valid under the new policy.
*/
static int convert_context(u32 key,
struct context *c,
void *p)
{
struct convert_context_args *args;
struct context oldc;
struct ocontext *oc;
struct mls_range *range;
struct role_datum *role;
struct type_datum *typdatum;
struct user_datum *usrdatum;
char *s;
u32 len;
int rc = 0;
if (key <= SECINITSID_NUM)
goto out;
args = p;
if (c->str) {
struct context ctx;
rc = -ENOMEM;
s = kstrdup(c->str, GFP_KERNEL);
if (!s)
goto out;
rc = string_to_context_struct(args->newp, NULL, s,
c->len, &ctx, SECSID_NULL);
kfree(s);
if (!rc) {
printk(KERN_INFO "SELinux: Context %s became valid (mapped).\n",
c->str);
/* Replace string with mapped representation. */
kfree(c->str);
memcpy(c, &ctx, sizeof(*c));
goto out;
} else if (rc == -EINVAL) {
/* Retain string representation for later mapping. */
rc = 0;
goto out;
} else {
/* Other error condition, e.g. ENOMEM. */
printk(KERN_ERR "SELinux: Unable to map context %s, rc = %d.\n",
c->str, -rc);
goto out;
}
}
rc = context_cpy(&oldc, c);
if (rc)
goto out;
/* Convert the user. */
rc = -EINVAL;
usrdatum = hashtab_search(args->newp->p_users.table,
sym_name(args->oldp, SYM_USERS, c->user - 1));
if (!usrdatum)
goto bad;
c->user = usrdatum->value;
/* Convert the role. */
rc = -EINVAL;
role = hashtab_search(args->newp->p_roles.table,
sym_name(args->oldp, SYM_ROLES, c->role - 1));
if (!role)
goto bad;
c->role = role->value;
/* Convert the type. */
rc = -EINVAL;
typdatum = hashtab_search(args->newp->p_types.table,
sym_name(args->oldp, SYM_TYPES, c->type - 1));
if (!typdatum)
goto bad;
c->type = typdatum->value;
/* Convert the MLS fields if dealing with MLS policies */
if (args->oldp->mls_enabled && args->newp->mls_enabled) {
rc = mls_convert_context(args->oldp, args->newp, c);
if (rc)
goto bad;
} else if (args->oldp->mls_enabled && !args->newp->mls_enabled) {
/*
* Switching between MLS and non-MLS policy:
* free any storage used by the MLS fields in the
* context for all existing entries in the sidtab.
*/
mls_context_destroy(c);
} else if (!args->oldp->mls_enabled && args->newp->mls_enabled) {
/*
* Switching between non-MLS and MLS policy:
* ensure that the MLS fields of the context for all
* existing entries in the sidtab are filled in with a
* suitable default value, likely taken from one of the
* initial SIDs.
*/
oc = args->newp->ocontexts[OCON_ISID];
while (oc && oc->sid[0] != SECINITSID_UNLABELED)
oc = oc->next;
rc = -EINVAL;
if (!oc) {
printk(KERN_ERR "SELinux: unable to look up"
" the initial SIDs list\n");
goto bad;
}
range = &oc->context[0].range;
rc = mls_range_set(c, range);
if (rc)
goto bad;
}
/* Check the validity of the new context. */
if (!policydb_context_isvalid(args->newp, c)) {
rc = convert_context_handle_invalid_context(&oldc);
if (rc)
goto bad;
}
context_destroy(&oldc);
rc = 0;
out:
return rc;
bad:
/* Map old representation to string and save it. */
rc = context_struct_to_string(&oldc, &s, &len);
if (rc)
return rc;
context_destroy(&oldc);
context_destroy(c);
c->str = s;
c->len = len;
printk(KERN_INFO "SELinux: Context %s became invalid (unmapped).\n",
c->str);
rc = 0;
goto out;
}
static void security_load_policycaps(void)
{
selinux_policycap_netpeer = ebitmap_get_bit(&policydb.policycaps,
POLICYDB_CAPABILITY_NETPEER);
selinux_policycap_openperm = ebitmap_get_bit(&policydb.policycaps,
POLICYDB_CAPABILITY_OPENPERM);
}
static int security_preserve_bools(struct policydb *p);
/**
* security_load_policy - Load a security policy configuration.
* @data: binary policy data
* @len: length of data in bytes
*
* Load a new set of security policy configuration data,
* validate it and convert the SID table as necessary.
* This function will flush the access vector cache after
* loading the new policy.
*/
int security_load_policy(void *data, size_t len)
{
struct policydb oldpolicydb, newpolicydb;
struct sidtab oldsidtab, newsidtab;
struct selinux_mapping *oldmap, *map = NULL;
struct convert_context_args args;
u32 seqno;
u16 map_size;
int rc = 0;
struct policy_file file = { data, len }, *fp = &file;
if (!ss_initialized) {
avtab_cache_init();
rc = policydb_read(&policydb, fp);
if (rc) {
avtab_cache_destroy();
return rc;
}
policydb.len = len;
rc = selinux_set_mapping(&policydb, secclass_map,
¤t_mapping,
¤t_mapping_size);
if (rc) {
policydb_destroy(&policydb);
avtab_cache_destroy();
return rc;
}
rc = policydb_load_isids(&policydb, &sidtab);
if (rc) {
policydb_destroy(&policydb);
avtab_cache_destroy();
return rc;
}
security_load_policycaps();
ss_initialized = 1;
seqno = ++latest_granting;
selinux_complete_init();
avc_ss_reset(seqno);
selnl_notify_policyload(seqno);
selinux_status_update_policyload(seqno);
selinux_netlbl_cache_invalidate();
selinux_xfrm_notify_policyload();
return 0;
}
#if 0
sidtab_hash_eval(&sidtab, "sids");
#endif
rc = policydb_read(&newpolicydb, fp);
if (rc)
return rc;
newpolicydb.len = len;
/* If switching between different policy types, log MLS status */
if (policydb.mls_enabled && !newpolicydb.mls_enabled)
printk(KERN_INFO "SELinux: Disabling MLS support...\n");
else if (!policydb.mls_enabled && newpolicydb.mls_enabled)
printk(KERN_INFO "SELinux: Enabling MLS support...\n");
rc = policydb_load_isids(&newpolicydb, &newsidtab);
if (rc) {
printk(KERN_ERR "SELinux: unable to load the initial SIDs\n");
policydb_destroy(&newpolicydb);
return rc;
}
rc = selinux_set_mapping(&newpolicydb, secclass_map, &map, &map_size);
if (rc)
goto err;
rc = security_preserve_bools(&newpolicydb);
if (rc) {
printk(KERN_ERR "SELinux: unable to preserve booleans\n");
goto err;
}
/* Clone the SID table. */
sidtab_shutdown(&sidtab);
rc = sidtab_map(&sidtab, clone_sid, &newsidtab);
if (rc)
goto err;
/*
* Convert the internal representations of contexts
* in the new SID table.
*/
args.oldp = &policydb;
args.newp = &newpolicydb;
rc = sidtab_map(&newsidtab, convert_context, &args);
if (rc) {
printk(KERN_ERR "SELinux: unable to convert the internal"
" representation of contexts in the new SID"
" table\n");
goto err;
}
/* Save the old policydb and SID table to free later. */
memcpy(&oldpolicydb, &policydb, sizeof policydb);
sidtab_set(&oldsidtab, &sidtab);
/* Install the new policydb and SID table. */
write_lock_irq(&policy_rwlock);
memcpy(&policydb, &newpolicydb, sizeof policydb);
sidtab_set(&sidtab, &newsidtab);
security_load_policycaps();
oldmap = current_mapping;
current_mapping = map;
current_mapping_size = map_size;
seqno = ++latest_granting;
write_unlock_irq(&policy_rwlock);
/* Free the old policydb and SID table. */
policydb_destroy(&oldpolicydb);
sidtab_destroy(&oldsidtab);
kfree(oldmap);
avc_ss_reset(seqno);
selnl_notify_policyload(seqno);
selinux_status_update_policyload(seqno);
selinux_netlbl_cache_invalidate();
selinux_xfrm_notify_policyload();
return 0;
err:
kfree(map);
sidtab_destroy(&newsidtab);
policydb_destroy(&newpolicydb);
return rc;
}
size_t security_policydb_len(void)
{
size_t len;
read_lock(&policy_rwlock);
len = policydb.len;
read_unlock(&policy_rwlock);
return len;
}
/**
* security_port_sid - Obtain the SID for a port.
* @protocol: protocol number
* @port: port number
* @out_sid: security identifier
*/
int security_port_sid(u8 protocol, u16 port, u32 *out_sid)
{
struct ocontext *c;
int rc = 0;
read_lock(&policy_rwlock);
c = policydb.ocontexts[OCON_PORT];
while (c) {
if (c->u.port.protocol == protocol &&
c->u.port.low_port <= port &&
c->u.port.high_port >= port)
break;
c = c->next;
}
if (c) {
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab,
&c->context[0],
&c->sid[0]);
if (rc)
goto out;
}
*out_sid = c->sid[0];
} else {
*out_sid = SECINITSID_PORT;
}
out:
read_unlock(&policy_rwlock);
return rc;
}
/**
* security_netif_sid - Obtain the SID for a network interface.
* @name: interface name
* @if_sid: interface SID
*/
int security_netif_sid(char *name, u32 *if_sid)
{
int rc = 0;
struct ocontext *c;
read_lock(&policy_rwlock);
c = policydb.ocontexts[OCON_NETIF];
while (c) {
if (strcmp(name, c->u.name) == 0)
break;
c = c->next;
}
if (c) {
if (!c->sid[0] || !c->sid[1]) {
rc = sidtab_context_to_sid(&sidtab,
&c->context[0],
&c->sid[0]);
if (rc)
goto out;
rc = sidtab_context_to_sid(&sidtab,
&c->context[1],
&c->sid[1]);
if (rc)
goto out;
}
*if_sid = c->sid[0];
} else
*if_sid = SECINITSID_NETIF;
out:
read_unlock(&policy_rwlock);
return rc;
}
static int match_ipv6_addrmask(u32 *input, u32 *addr, u32 *mask)
{
int i, fail = 0;
for (i = 0; i < 4; i++)
if (addr[i] != (input[i] & mask[i])) {
fail = 1;
break;
}
return !fail;
}
/**
* security_node_sid - Obtain the SID for a node (host).
* @domain: communication domain aka address family
* @addrp: address
* @addrlen: address length in bytes
* @out_sid: security identifier
*/
int security_node_sid(u16 domain,
void *addrp,
u32 addrlen,
u32 *out_sid)
{
int rc;
struct ocontext *c;
read_lock(&policy_rwlock);
switch (domain) {
case AF_INET: {
u32 addr;
rc = -EINVAL;
if (addrlen != sizeof(u32))
goto out;
addr = *((u32 *)addrp);
c = policydb.ocontexts[OCON_NODE];
while (c) {
if (c->u.node.addr == (addr & c->u.node.mask))
break;
c = c->next;
}
break;
}
case AF_INET6:
rc = -EINVAL;
if (addrlen != sizeof(u64) * 2)
goto out;
c = policydb.ocontexts[OCON_NODE6];
while (c) {
if (match_ipv6_addrmask(addrp, c->u.node6.addr,
c->u.node6.mask))
break;
c = c->next;
}
break;
default:
rc = 0;
*out_sid = SECINITSID_NODE;
goto out;
}
if (c) {
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab,
&c->context[0],
&c->sid[0]);
if (rc)
goto out;
}
*out_sid = c->sid[0];
} else {
*out_sid = SECINITSID_NODE;
}
rc = 0;
out:
read_unlock(&policy_rwlock);
return rc;
}
#define SIDS_NEL 25
/**
* security_get_user_sids - Obtain reachable SIDs for a user.
* @fromsid: starting SID
* @username: username
* @sids: array of reachable SIDs for user
* @nel: number of elements in @sids
*
* Generate the set of SIDs for legal security contexts
* for a given user that can be reached by @fromsid.
* Set *@sids to point to a dynamically allocated
* array containing the set of SIDs. Set *@nel to the
* number of elements in the array.
*/
int security_get_user_sids(u32 fromsid,
char *username,
u32 **sids,
u32 *nel)
{
struct context *fromcon, usercon;
u32 *mysids = NULL, *mysids2, sid;
u32 mynel = 0, maxnel = SIDS_NEL;
struct user_datum *user;
struct role_datum *role;
struct ebitmap_node *rnode, *tnode;
int rc = 0, i, j;
*sids = NULL;
*nel = 0;
if (!ss_initialized)
goto out;
read_lock(&policy_rwlock);
context_init(&usercon);
rc = -EINVAL;
fromcon = sidtab_search(&sidtab, fromsid);
if (!fromcon)
goto out_unlock;
rc = -EINVAL;
user = hashtab_search(policydb.p_users.table, username);
if (!user)
goto out_unlock;
usercon.user = user->value;
rc = -ENOMEM;
mysids = kcalloc(maxnel, sizeof(*mysids), GFP_ATOMIC);
if (!mysids)
goto out_unlock;
ebitmap_for_each_positive_bit(&user->roles, rnode, i) {
role = policydb.role_val_to_struct[i];
usercon.role = i + 1;
ebitmap_for_each_positive_bit(&role->types, tnode, j) {
usercon.type = j + 1;
if (mls_setup_user_range(fromcon, user, &usercon))
continue;
rc = sidtab_context_to_sid(&sidtab, &usercon, &sid);
if (rc)
goto out_unlock;
if (mynel < maxnel) {
mysids[mynel++] = sid;
} else {
rc = -ENOMEM;
maxnel += SIDS_NEL;
mysids2 = kcalloc(maxnel, sizeof(*mysids2), GFP_ATOMIC);
if (!mysids2)
goto out_unlock;
memcpy(mysids2, mysids, mynel * sizeof(*mysids2));
kfree(mysids);
mysids = mysids2;
mysids[mynel++] = sid;
}
}
}
rc = 0;
out_unlock:
read_unlock(&policy_rwlock);
if (rc || !mynel) {
kfree(mysids);
goto out;
}
rc = -ENOMEM;
mysids2 = kcalloc(mynel, sizeof(*mysids2), GFP_KERNEL);
if (!mysids2) {
kfree(mysids);
goto out;
}
for (i = 0, j = 0; i < mynel; i++) {
struct av_decision dummy_avd;
rc = avc_has_perm_noaudit(fromsid, mysids[i],
SECCLASS_PROCESS, /* kernel value */
PROCESS__TRANSITION, AVC_STRICT,
&dummy_avd);
if (!rc)
mysids2[j++] = mysids[i];
cond_resched();
}
rc = 0;
kfree(mysids);
*sids = mysids2;
*nel = j;
out:
return rc;
}
/**
* security_genfs_sid - Obtain a SID for a file in a filesystem
* @fstype: filesystem type
* @path: path from root of mount
* @sclass: file security class
* @sid: SID for path
*
* Obtain a SID to use for a file in a filesystem that
* cannot support xattr or use a fixed labeling behavior like
* transition SIDs or task SIDs.
*/
int security_genfs_sid(const char *fstype,
char *path,
u16 orig_sclass,
u32 *sid)
{
int len;
u16 sclass;
struct genfs *genfs;
struct ocontext *c;
int rc, cmp = 0;
while (path[0] == '/' && path[1] == '/')
path++;
read_lock(&policy_rwlock);
sclass = unmap_class(orig_sclass);
*sid = SECINITSID_UNLABELED;
for (genfs = policydb.genfs; genfs; genfs = genfs->next) {
cmp = strcmp(fstype, genfs->fstype);
if (cmp <= 0)
break;
}
rc = -ENOENT;
if (!genfs || cmp)
goto out;
for (c = genfs->head; c; c = c->next) {
len = strlen(c->u.name);
if ((!c->v.sclass || sclass == c->v.sclass) &&
(strncmp(c->u.name, path, len) == 0))
break;
}
rc = -ENOENT;
if (!c)
goto out;
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab, &c->context[0], &c->sid[0]);
if (rc)
goto out;
}
*sid = c->sid[0];
rc = 0;
out:
read_unlock(&policy_rwlock);
return rc;
}
/**
* security_fs_use - Determine how to handle labeling for a filesystem.
* @fstype: filesystem type
* @behavior: labeling behavior
* @sid: SID for filesystem (superblock)
*/
int security_fs_use(
const char *fstype,
unsigned int *behavior,
u32 *sid)
{
int rc = 0;
struct ocontext *c;
read_lock(&policy_rwlock);
c = policydb.ocontexts[OCON_FSUSE];
while (c) {
if (strcmp(fstype, c->u.name) == 0)
break;
c = c->next;
}
if (c) {
*behavior = c->v.behavior;
if (!c->sid[0]) {
rc = sidtab_context_to_sid(&sidtab, &c->context[0],
&c->sid[0]);
if (rc)
goto out;
}
*sid = c->sid[0];
} else {
rc = security_genfs_sid(fstype, "/", SECCLASS_DIR, sid);
if (rc) {
*behavior = SECURITY_FS_USE_NONE;
rc = 0;
} else {
*behavior = SECURITY_FS_USE_GENFS;
}
}
out:
read_unlock(&policy_rwlock);
return rc;
}
int security_get_bools(int *len, char ***names, int **values)
{
int i, rc;
read_lock(&policy_rwlock);
*names = NULL;
*values = NULL;
rc = 0;
*len = policydb.p_bools.nprim;
if (!*len)
goto out;
rc = -ENOMEM;
*names = kcalloc(*len, sizeof(char *), GFP_ATOMIC);
if (!*names)
goto err;
rc = -ENOMEM;
*values = kcalloc(*len, sizeof(int), GFP_ATOMIC);
if (!*values)
goto err;
for (i = 0; i < *len; i++) {
size_t name_len;
(*values)[i] = policydb.bool_val_to_struct[i]->state;
name_len = strlen(sym_name(&policydb, SYM_BOOLS, i)) + 1;
rc = -ENOMEM;
(*names)[i] = kmalloc(sizeof(char) * name_len, GFP_ATOMIC);
if (!(*names)[i])
goto err;
strncpy((*names)[i], sym_name(&policydb, SYM_BOOLS, i), name_len);
(*names)[i][name_len - 1] = 0;
}
rc = 0;
out:
read_unlock(&policy_rwlock);
return rc;
err:
if (*names) {
for (i = 0; i < *len; i++)
kfree((*names)[i]);
}
kfree(*values);
goto out;
}
int security_set_bools(int len, int *values)
{
int i, rc;
int lenp, seqno = 0;
struct cond_node *cur;
write_lock_irq(&policy_rwlock);
rc = -EFAULT;
lenp = policydb.p_bools.nprim;
if (len != lenp)
goto out;
for (i = 0; i < len; i++) {
if (!!values[i] != policydb.bool_val_to_struct[i]->state) {
audit_log(current->audit_context, GFP_ATOMIC,
AUDIT_MAC_CONFIG_CHANGE,
"bool=%s val=%d old_val=%d auid=%u ses=%u",
sym_name(&policydb, SYM_BOOLS, i),
!!values[i],
policydb.bool_val_to_struct[i]->state,
from_kuid(&init_user_ns, audit_get_loginuid(current)),
audit_get_sessionid(current));
}
if (values[i])
policydb.bool_val_to_struct[i]->state = 1;
else
policydb.bool_val_to_struct[i]->state = 0;
}
for (cur = policydb.cond_list; cur; cur = cur->next) {
rc = evaluate_cond_node(&policydb, cur);
if (rc)
goto out;
}
seqno = ++latest_granting;
rc = 0;
out:
write_unlock_irq(&policy_rwlock);
if (!rc) {
avc_ss_reset(seqno);
selnl_notify_policyload(seqno);
selinux_status_update_policyload(seqno);
selinux_xfrm_notify_policyload();
}
return rc;
}
int security_get_bool_value(int bool)
{
int rc;
int len;
read_lock(&policy_rwlock);
rc = -EFAULT;
len = policydb.p_bools.nprim;
if (bool >= len)
goto out;
rc = policydb.bool_val_to_struct[bool]->state;
out:
read_unlock(&policy_rwlock);
return rc;
}
static int security_preserve_bools(struct policydb *p)
{
int rc, nbools = 0, *bvalues = NULL, i;
char **bnames = NULL;
struct cond_bool_datum *booldatum;
struct cond_node *cur;
rc = security_get_bools(&nbools, &bnames, &bvalues);
if (rc)
goto out;
for (i = 0; i < nbools; i++) {
booldatum = hashtab_search(p->p_bools.table, bnames[i]);
if (booldatum)
booldatum->state = bvalues[i];
}
for (cur = p->cond_list; cur; cur = cur->next) {
rc = evaluate_cond_node(p, cur);
if (rc)
goto out;
}
out:
if (bnames) {
for (i = 0; i < nbools; i++)
kfree(bnames[i]);
}
kfree(bnames);
kfree(bvalues);
return rc;
}
/*
* security_sid_mls_copy() - computes a new sid based on the given
* sid and the mls portion of mls_sid.
*/
int security_sid_mls_copy(u32 sid, u32 mls_sid, u32 *new_sid)
{
struct context *context1;
struct context *context2;
struct context newcon;
char *s;
u32 len;
int rc;
rc = 0;
if (!ss_initialized || !policydb.mls_enabled) {
*new_sid = sid;
goto out;
}
context_init(&newcon);
read_lock(&policy_rwlock);
rc = -EINVAL;
context1 = sidtab_search(&sidtab, sid);
if (!context1) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, sid);
goto out_unlock;
}
rc = -EINVAL;
context2 = sidtab_search(&sidtab, mls_sid);
if (!context2) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, mls_sid);
goto out_unlock;
}
newcon.user = context1->user;
newcon.role = context1->role;
newcon.type = context1->type;
rc = mls_context_cpy(&newcon, context2);
if (rc)
goto out_unlock;
/* Check the validity of the new context. */
if (!policydb_context_isvalid(&policydb, &newcon)) {
rc = convert_context_handle_invalid_context(&newcon);
if (rc) {
if (!context_struct_to_string(&newcon, &s, &len)) {
audit_log(current->audit_context, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"security_sid_mls_copy: invalid context %s", s);
kfree(s);
}
goto out_unlock;
}
}
rc = sidtab_context_to_sid(&sidtab, &newcon, new_sid);
out_unlock:
read_unlock(&policy_rwlock);
context_destroy(&newcon);
out:
return rc;
}
/**
* security_net_peersid_resolve - Compare and resolve two network peer SIDs
* @nlbl_sid: NetLabel SID
* @nlbl_type: NetLabel labeling protocol type
* @xfrm_sid: XFRM SID
*
* Description:
* Compare the @nlbl_sid and @xfrm_sid values and if the two SIDs can be
* resolved into a single SID it is returned via @peer_sid and the function
* returns zero. Otherwise @peer_sid is set to SECSID_NULL and the function
* returns a negative value. A table summarizing the behavior is below:
*
* | function return | @sid
* ------------------------------+-----------------+-----------------
* no peer labels | 0 | SECSID_NULL
* single peer label | 0 | <peer_label>
* multiple, consistent labels | 0 | <peer_label>
* multiple, inconsistent labels | -<errno> | SECSID_NULL
*
*/
int security_net_peersid_resolve(u32 nlbl_sid, u32 nlbl_type,
u32 xfrm_sid,
u32 *peer_sid)
{
int rc;
struct context *nlbl_ctx;
struct context *xfrm_ctx;
*peer_sid = SECSID_NULL;
/* handle the common (which also happens to be the set of easy) cases
* right away, these two if statements catch everything involving a
* single or absent peer SID/label */
if (xfrm_sid == SECSID_NULL) {
*peer_sid = nlbl_sid;
return 0;
}
/* NOTE: an nlbl_type == NETLBL_NLTYPE_UNLABELED is a "fallback" label
* and is treated as if nlbl_sid == SECSID_NULL when a XFRM SID/label
* is present */
if (nlbl_sid == SECSID_NULL || nlbl_type == NETLBL_NLTYPE_UNLABELED) {
*peer_sid = xfrm_sid;
return 0;
}
/* we don't need to check ss_initialized here since the only way both
* nlbl_sid and xfrm_sid are not equal to SECSID_NULL would be if the
* security server was initialized and ss_initialized was true */
if (!policydb.mls_enabled)
return 0;
read_lock(&policy_rwlock);
rc = -EINVAL;
nlbl_ctx = sidtab_search(&sidtab, nlbl_sid);
if (!nlbl_ctx) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, nlbl_sid);
goto out;
}
rc = -EINVAL;
xfrm_ctx = sidtab_search(&sidtab, xfrm_sid);
if (!xfrm_ctx) {
printk(KERN_ERR "SELinux: %s: unrecognized SID %d\n",
__func__, xfrm_sid);
goto out;
}
rc = (mls_context_cmp(nlbl_ctx, xfrm_ctx) ? 0 : -EACCES);
if (rc)
goto out;
/* at present NetLabel SIDs/labels really only carry MLS
* information so if the MLS portion of the NetLabel SID
* matches the MLS portion of the labeled XFRM SID/label
* then pass along the XFRM SID as it is the most
* expressive */
*peer_sid = xfrm_sid;
out:
read_unlock(&policy_rwlock);
return rc;
}
static int get_classes_callback(void *k, void *d, void *args)
{
struct class_datum *datum = d;
char *name = k, **classes = args;
int value = datum->value - 1;
classes[value] = kstrdup(name, GFP_ATOMIC);
if (!classes[value])
return -ENOMEM;
return 0;
}
int security_get_classes(char ***classes, int *nclasses)
{
int rc;
read_lock(&policy_rwlock);
rc = -ENOMEM;
*nclasses = policydb.p_classes.nprim;
*classes = kcalloc(*nclasses, sizeof(**classes), GFP_ATOMIC);
if (!*classes)
goto out;
rc = hashtab_map(policydb.p_classes.table, get_classes_callback,
*classes);
if (rc) {
int i;
for (i = 0; i < *nclasses; i++)
kfree((*classes)[i]);
kfree(*classes);
}
out:
read_unlock(&policy_rwlock);
return rc;
}
static int get_permissions_callback(void *k, void *d, void *args)
{
struct perm_datum *datum = d;
char *name = k, **perms = args;
int value = datum->value - 1;
perms[value] = kstrdup(name, GFP_ATOMIC);
if (!perms[value])
return -ENOMEM;
return 0;
}
int security_get_permissions(char *class, char ***perms, int *nperms)
{
int rc, i;
struct class_datum *match;
read_lock(&policy_rwlock);
rc = -EINVAL;
match = hashtab_search(policydb.p_classes.table, class);
if (!match) {
printk(KERN_ERR "SELinux: %s: unrecognized class %s\n",
__func__, class);
goto out;
}
rc = -ENOMEM;
*nperms = match->permissions.nprim;
*perms = kcalloc(*nperms, sizeof(**perms), GFP_ATOMIC);
if (!*perms)
goto out;
if (match->comdatum) {
rc = hashtab_map(match->comdatum->permissions.table,
get_permissions_callback, *perms);
if (rc)
goto err;
}
rc = hashtab_map(match->permissions.table, get_permissions_callback,
*perms);
if (rc)
goto err;
out:
read_unlock(&policy_rwlock);
return rc;
err:
read_unlock(&policy_rwlock);
for (i = 0; i < *nperms; i++)
kfree((*perms)[i]);
kfree(*perms);
return rc;
}
int security_get_reject_unknown(void)
{
return policydb.reject_unknown;
}
int security_get_allow_unknown(void)
{
return policydb.allow_unknown;
}
/**
* security_policycap_supported - Check for a specific policy capability
* @req_cap: capability
*
* Description:
* This function queries the currently loaded policy to see if it supports the
* capability specified by @req_cap. Returns true (1) if the capability is
* supported, false (0) if it isn't supported.
*
*/
int security_policycap_supported(unsigned int req_cap)
{
int rc;
read_lock(&policy_rwlock);
rc = ebitmap_get_bit(&policydb.policycaps, req_cap);
read_unlock(&policy_rwlock);
return rc;
}
struct selinux_audit_rule {
u32 au_seqno;
struct context au_ctxt;
};
void selinux_audit_rule_free(void *vrule)
{
struct selinux_audit_rule *rule = vrule;
if (rule) {
context_destroy(&rule->au_ctxt);
kfree(rule);
}
}
int selinux_audit_rule_init(u32 field, u32 op, char *rulestr, void **vrule)
{
struct selinux_audit_rule *tmprule;
struct role_datum *roledatum;
struct type_datum *typedatum;
struct user_datum *userdatum;
struct selinux_audit_rule **rule = (struct selinux_audit_rule **)vrule;
int rc = 0;
#ifdef CONFIG_TIMA_RKP_RO_CRED
if ((rc = security_integrity_current()))
return rc;
#endif
*rule = NULL;
if (!ss_initialized)
return -EOPNOTSUPP;
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
/* only 'equals' and 'not equals' fit user, role, and type */
if (op != Audit_equal && op != Audit_not_equal)
return -EINVAL;
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
/* we do not allow a range, indicated by the presence of '-' */
if (strchr(rulestr, '-'))
return -EINVAL;
break;
default:
/* only the above fields are valid */
return -EINVAL;
}
tmprule = kzalloc(sizeof(struct selinux_audit_rule), GFP_KERNEL);
if (!tmprule)
return -ENOMEM;
context_init(&tmprule->au_ctxt);
read_lock(&policy_rwlock);
tmprule->au_seqno = latest_granting;
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_OBJ_USER:
rc = -EINVAL;
userdatum = hashtab_search(policydb.p_users.table, rulestr);
if (!userdatum)
goto out;
tmprule->au_ctxt.user = userdatum->value;
break;
case AUDIT_SUBJ_ROLE:
case AUDIT_OBJ_ROLE:
rc = -EINVAL;
roledatum = hashtab_search(policydb.p_roles.table, rulestr);
if (!roledatum)
goto out;
tmprule->au_ctxt.role = roledatum->value;
break;
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_TYPE:
rc = -EINVAL;
typedatum = hashtab_search(policydb.p_types.table, rulestr);
if (!typedatum)
goto out;
tmprule->au_ctxt.type = typedatum->value;
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
rc = mls_from_string(rulestr, &tmprule->au_ctxt, GFP_ATOMIC);
if (rc)
goto out;
break;
}
rc = 0;
out:
read_unlock(&policy_rwlock);
if (rc) {
selinux_audit_rule_free(tmprule);
tmprule = NULL;
}
*rule = tmprule;
return rc;
}
/* Check to see if the rule contains any selinux fields */
int selinux_audit_rule_known(struct audit_krule *rule)
{
int i;
#ifdef CONFIG_TIMA_RKP_RO_CRED
int rc;
if ((rc = security_integrity_current()))
return rc;
#endif
for (i = 0; i < rule->field_count; i++) {
struct audit_field *f = &rule->fields[i];
switch (f->type) {
case AUDIT_SUBJ_USER:
case AUDIT_SUBJ_ROLE:
case AUDIT_SUBJ_TYPE:
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_USER:
case AUDIT_OBJ_ROLE:
case AUDIT_OBJ_TYPE:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
return 1;
}
}
return 0;
}
int selinux_audit_rule_match(u32 sid, u32 field, u32 op, void *vrule,
struct audit_context *actx)
{
struct context *ctxt;
struct mls_level *level;
struct selinux_audit_rule *rule = vrule;
int match = 0;
#ifdef CONFIG_TIMA_RKP_RO_CRED
int rc;
if ((rc = security_integrity_current()))
return rc;
#endif
if (!rule) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: missing rule\n");
return -ENOENT;
}
read_lock(&policy_rwlock);
if (rule->au_seqno < latest_granting) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: stale rule\n");
match = -ESTALE;
goto out;
}
ctxt = sidtab_search(&sidtab, sid);
if (!ctxt) {
audit_log(actx, GFP_ATOMIC, AUDIT_SELINUX_ERR,
"selinux_audit_rule_match: unrecognized SID %d\n",
sid);
match = -ENOENT;
goto out;
}
/* a field/op pair that is not caught here will simply fall through
without a match */
switch (field) {
case AUDIT_SUBJ_USER:
case AUDIT_OBJ_USER:
switch (op) {
case Audit_equal:
match = (ctxt->user == rule->au_ctxt.user);
break;
case Audit_not_equal:
match = (ctxt->user != rule->au_ctxt.user);
break;
}
break;
case AUDIT_SUBJ_ROLE:
case AUDIT_OBJ_ROLE:
switch (op) {
case Audit_equal:
match = (ctxt->role == rule->au_ctxt.role);
break;
case Audit_not_equal:
match = (ctxt->role != rule->au_ctxt.role);
break;
}
break;
case AUDIT_SUBJ_TYPE:
case AUDIT_OBJ_TYPE:
switch (op) {
case Audit_equal:
match = (ctxt->type == rule->au_ctxt.type);
break;
case Audit_not_equal:
match = (ctxt->type != rule->au_ctxt.type);
break;
}
break;
case AUDIT_SUBJ_SEN:
case AUDIT_SUBJ_CLR:
case AUDIT_OBJ_LEV_LOW:
case AUDIT_OBJ_LEV_HIGH:
level = ((field == AUDIT_SUBJ_SEN ||
field == AUDIT_OBJ_LEV_LOW) ?
&ctxt->range.level[0] : &ctxt->range.level[1]);
switch (op) {
case Audit_equal:
match = mls_level_eq(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_not_equal:
match = !mls_level_eq(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_lt:
match = (mls_level_dom(&rule->au_ctxt.range.level[0],
level) &&
!mls_level_eq(&rule->au_ctxt.range.level[0],
level));
break;
case Audit_le:
match = mls_level_dom(&rule->au_ctxt.range.level[0],
level);
break;
case Audit_gt:
match = (mls_level_dom(level,
&rule->au_ctxt.range.level[0]) &&
!mls_level_eq(level,
&rule->au_ctxt.range.level[0]));
break;
case Audit_ge:
match = mls_level_dom(level,
&rule->au_ctxt.range.level[0]);
break;
}
}
out:
read_unlock(&policy_rwlock);
return match;
}
static int (*aurule_callback)(void) = audit_update_lsm_rules;
static int aurule_avc_callback(u32 event)
{
int err = 0;
if (event == AVC_CALLBACK_RESET && aurule_callback)
err = aurule_callback();
return err;
}
static int __init aurule_init(void)
{
int err;
err = avc_add_callback(aurule_avc_callback, AVC_CALLBACK_RESET);
if (err)
panic("avc_add_callback() failed, error %d\n", err);
return err;
}
__initcall(aurule_init);
#ifdef CONFIG_NETLABEL
/**
* security_netlbl_cache_add - Add an entry to the NetLabel cache
* @secattr: the NetLabel packet security attributes
* @sid: the SELinux SID
*
* Description:
* Attempt to cache the context in @ctx, which was derived from the packet in
* @skb, in the NetLabel subsystem cache. This function assumes @secattr has
* already been initialized.
*
*/
static void security_netlbl_cache_add(struct netlbl_lsm_secattr *secattr,
u32 sid)
{
u32 *sid_cache;
sid_cache = kmalloc(sizeof(*sid_cache), GFP_ATOMIC);
if (sid_cache == NULL)
return;
secattr->cache = netlbl_secattr_cache_alloc(GFP_ATOMIC);
if (secattr->cache == NULL) {
kfree(sid_cache);
return;
}
*sid_cache = sid;
secattr->cache->free = kfree;
secattr->cache->data = sid_cache;
secattr->flags |= NETLBL_SECATTR_CACHE;
}
/**
* security_netlbl_secattr_to_sid - Convert a NetLabel secattr to a SELinux SID
* @secattr: the NetLabel packet security attributes
* @sid: the SELinux SID
*
* Description:
* Convert the given NetLabel security attributes in @secattr into a
* SELinux SID. If the @secattr field does not contain a full SELinux
* SID/context then use SECINITSID_NETMSG as the foundation. If possible the
* 'cache' field of @secattr is set and the CACHE flag is set; this is to
* allow the @secattr to be used by NetLabel to cache the secattr to SID
* conversion for future lookups. Returns zero on success, negative values on
* failure.
*
*/
int security_netlbl_secattr_to_sid(struct netlbl_lsm_secattr *secattr,
u32 *sid)
{
int rc;
struct context *ctx;
struct context ctx_new;
if (!ss_initialized) {
*sid = SECSID_NULL;
return 0;
}
read_lock(&policy_rwlock);
if (secattr->flags & NETLBL_SECATTR_CACHE)
*sid = *(u32 *)secattr->cache->data;
else if (secattr->flags & NETLBL_SECATTR_SECID)
*sid = secattr->attr.secid;
else if (secattr->flags & NETLBL_SECATTR_MLS_LVL) {
rc = -EIDRM;
ctx = sidtab_search(&sidtab, SECINITSID_NETMSG);
if (ctx == NULL)
goto out;
context_init(&ctx_new);
ctx_new.user = ctx->user;
ctx_new.role = ctx->role;
ctx_new.type = ctx->type;
mls_import_netlbl_lvl(&ctx_new, secattr);
if (secattr->flags & NETLBL_SECATTR_MLS_CAT) {
rc = ebitmap_netlbl_import(&ctx_new.range.level[0].cat,
secattr->attr.mls.cat);
if (rc)
goto out;
memcpy(&ctx_new.range.level[1].cat,
&ctx_new.range.level[0].cat,
sizeof(ctx_new.range.level[0].cat));
}
rc = -EIDRM;
if (!mls_context_isvalid(&policydb, &ctx_new))
goto out_free;
rc = sidtab_context_to_sid(&sidtab, &ctx_new, sid);
if (rc)
goto out_free;
security_netlbl_cache_add(secattr, *sid);
ebitmap_destroy(&ctx_new.range.level[0].cat);
} else
*sid = SECSID_NULL;
read_unlock(&policy_rwlock);
return 0;
out_free:
ebitmap_destroy(&ctx_new.range.level[0].cat);
out:
read_unlock(&policy_rwlock);
return rc;
}
/**
* security_netlbl_sid_to_secattr - Convert a SELinux SID to a NetLabel secattr
* @sid: the SELinux SID
* @secattr: the NetLabel packet security attributes
*
* Description:
* Convert the given SELinux SID in @sid into a NetLabel security attribute.
* Returns zero on success, negative values on failure.
*
*/
int security_netlbl_sid_to_secattr(u32 sid, struct netlbl_lsm_secattr *secattr)
{
int rc;
struct context *ctx;
if (!ss_initialized)
return 0;
read_lock(&policy_rwlock);
rc = -ENOENT;
ctx = sidtab_search(&sidtab, sid);
if (ctx == NULL)
goto out;
rc = -ENOMEM;
secattr->domain = kstrdup(sym_name(&policydb, SYM_TYPES, ctx->type - 1),
GFP_ATOMIC);
if (secattr->domain == NULL)
goto out;
secattr->attr.secid = sid;
secattr->flags |= NETLBL_SECATTR_DOMAIN_CPY | NETLBL_SECATTR_SECID;
mls_export_netlbl_lvl(ctx, secattr);
rc = mls_export_netlbl_cat(ctx, secattr);
out:
read_unlock(&policy_rwlock);
return rc;
}
#endif /* CONFIG_NETLABEL */
/**
* security_read_policy - read the policy.
* @data: binary policy data
* @len: length of data in bytes
*
*/
int security_read_policy(void **data, size_t *len)
{
int rc;
struct policy_file fp;
if (!ss_initialized)
return -EINVAL;
*len = security_policydb_len();
*data = vmalloc_user(*len);
if (!*data)
return -ENOMEM;
fp.data = *data;
fp.len = *len;
read_lock(&policy_rwlock);
rc = policydb_write(&policydb, &fp);
read_unlock(&policy_rwlock);
if (rc)
return rc;
*len = (unsigned long)fp.data - (unsigned long)*data;
return 0;
}
| Java |
/*
* linux/arch/arm/mm/flush.c
*
* Copyright (C) 1995-2002 Russell King
*
* 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/module.h>
#include <linux/mm.h>
#include <linux/pagemap.h>
#include <linux/highmem.h>
#include <asm/cacheflush.h>
#include <asm/cachetype.h>
#include <asm/highmem.h>
#include <asm/smp_plat.h>
#include <asm/tlbflush.h>
#include "mm.h"
#ifdef CONFIG_CPU_CACHE_VIPT
static void flush_pfn_alias(unsigned long pfn, unsigned long vaddr)
{
unsigned long to = FLUSH_ALIAS_START + (CACHE_COLOUR(vaddr) << PAGE_SHIFT);
const int zero = 0;
set_top_pte(to, pfn_pte(pfn, PAGE_KERNEL));
asm( "mcrr p15, 0, %1, %0, c14\n"
" mcr p15, 0, %2, c7, c10, 4"
:
: "r" (to), "r" (to + PAGE_SIZE - L1_CACHE_BYTES), "r" (zero)
: "cc");
}
static void flush_icache_alias(unsigned long pfn, unsigned long vaddr, unsigned long len)
{
unsigned long va = FLUSH_ALIAS_START + (CACHE_COLOUR(vaddr) << PAGE_SHIFT);
unsigned long offset = vaddr & (PAGE_SIZE - 1);
unsigned long to;
set_top_pte(va, pfn_pte(pfn, PAGE_KERNEL));
to = va + offset;
flush_icache_range(to, to + len);
}
void flush_cache_mm(struct mm_struct *mm)
{
if (cache_is_vivt()) {
vivt_flush_cache_mm(mm);
return;
}
if (cache_is_vipt_aliasing()) {
asm( "mcr p15, 0, %0, c7, c14, 0\n"
" mcr p15, 0, %0, c7, c10, 4"
:
: "r" (0)
: "cc");
}
}
void flush_cache_range(struct vm_area_struct *vma, unsigned long start, unsigned long end)
{
if (cache_is_vivt()) {
vivt_flush_cache_range(vma, start, end);
return;
}
if (cache_is_vipt_aliasing()) {
asm( "mcr p15, 0, %0, c7, c14, 0\n"
" mcr p15, 0, %0, c7, c10, 4"
:
: "r" (0)
: "cc");
}
if (vma->vm_flags & VM_EXEC)
__flush_icache_all();
}
void flush_cache_page(struct vm_area_struct *vma, unsigned long user_addr, unsigned long pfn)
{
if (cache_is_vivt()) {
vivt_flush_cache_page(vma, user_addr, pfn);
return;
}
if (cache_is_vipt_aliasing()) {
flush_pfn_alias(pfn, user_addr);
__flush_icache_all();
}
if (vma->vm_flags & VM_EXEC && icache_is_vivt_asid_tagged())
__flush_icache_all();
}
#else
#define flush_pfn_alias(pfn,vaddr) do { } while (0)
#define flush_icache_alias(pfn,vaddr,len) do { } while (0)
#endif
static void flush_ptrace_access_other(void *args)
{
__flush_icache_all();
}
static
void flush_ptrace_access(struct vm_area_struct *vma, struct page *page,
unsigned long uaddr, void *kaddr, unsigned long len)
{
if (cache_is_vivt()) {
if (cpumask_test_cpu(smp_processor_id(), mm_cpumask(vma->vm_mm))) {
unsigned long addr = (unsigned long)kaddr;
__cpuc_coherent_kern_range(addr, addr + len);
}
return;
}
if (cache_is_vipt_aliasing()) {
flush_pfn_alias(page_to_pfn(page), uaddr);
__flush_icache_all();
return;
}
/* VIPT non-aliasing D-cache */
if (vma->vm_flags & VM_EXEC) {
unsigned long addr = (unsigned long)kaddr;
if (icache_is_vipt_aliasing())
flush_icache_alias(page_to_pfn(page), uaddr, len);
else
__cpuc_coherent_kern_range(addr, addr + len);
if (cache_ops_need_broadcast())
smp_call_function(flush_ptrace_access_other,
NULL, 1);
}
}
/*
* Copy user data from/to a page which is mapped into a different
* processes address space. Really, we want to allow our "user
* space" model to handle this.
*
* Note that this code needs to run on the current CPU.
*/
void copy_to_user_page(struct vm_area_struct *vma, struct page *page,
unsigned long uaddr, void *dst, const void *src,
unsigned long len)
{
#ifdef CONFIG_SMP
preempt_disable();
#endif
memcpy(dst, src, len);
flush_ptrace_access(vma, page, uaddr, dst, len);
#ifdef CONFIG_SMP
preempt_enable();
#endif
}
void __flush_dcache_page(struct address_space *mapping, struct page *page)
{
/*
* Writeback any data associated with the kernel mapping of this
* page. This ensures that data in the physical page is mutually
* coherent with the kernels mapping.
*/
if (!PageHighMem(page)) {
__cpuc_flush_dcache_area(page_address(page), PAGE_SIZE);
} else {
void *addr = kmap_high_get(page);
if (addr) {
__cpuc_flush_dcache_area(addr, PAGE_SIZE);
kunmap_high(page);
} else if (cache_is_vipt()) {
/* unmapped pages might still be cached */
addr = kmap_atomic(page);
__cpuc_flush_dcache_area(addr, PAGE_SIZE);
kunmap_atomic(addr);
}
}
/*
* If this is a page cache page, and we have an aliasing VIPT cache,
* we only need to do one flush - which would be at the relevant
* userspace colour, which is congruent with page->index.
*/
if (mapping && cache_is_vipt_aliasing())
flush_pfn_alias(page_to_pfn(page),
page->index << PAGE_CACHE_SHIFT);
}
static void __flush_dcache_aliases(struct address_space *mapping, struct page *page)
{
struct mm_struct *mm = current->active_mm;
struct vm_area_struct *mpnt;
struct prio_tree_iter iter;
pgoff_t pgoff;
/*
* There are possible user space mappings of this page:
* - VIVT cache: we need to also write back and invalidate all user
* data in the current VM view associated with this page.
* - aliasing VIPT: we only need to find one mapping of this page.
*/
pgoff = page->index << (PAGE_CACHE_SHIFT - PAGE_SHIFT);
flush_dcache_mmap_lock(mapping);
vma_prio_tree_foreach(mpnt, &iter, &mapping->i_mmap, pgoff, pgoff) {
unsigned long offset;
/*
* If this VMA is not in our MM, we can ignore it.
*/
if (mpnt->vm_mm != mm)
continue;
if (!(mpnt->vm_flags & VM_MAYSHARE))
continue;
offset = (pgoff - mpnt->vm_pgoff) << PAGE_SHIFT;
flush_cache_page(mpnt, mpnt->vm_start + offset, page_to_pfn(page));
}
flush_dcache_mmap_unlock(mapping);
}
#if __LINUX_ARM_ARCH__ >= 6
void __sync_icache_dcache(pte_t pteval)
{
unsigned long pfn;
struct page *page;
struct address_space *mapping;
if (!pte_present_user(pteval))
return;
if (cache_is_vipt_nonaliasing() && !pte_exec(pteval))
/* only flush non-aliasing VIPT caches for exec mappings */
return;
pfn = pte_pfn(pteval);
if (!pfn_valid(pfn))
return;
page = pfn_to_page(pfn);
if (cache_is_vipt_aliasing())
mapping = page_mapping(page);
else
mapping = NULL;
if (!test_and_set_bit(PG_dcache_clean, &page->flags))
__flush_dcache_page(mapping, page);
if (pte_exec(pteval))
__flush_icache_all();
}
#endif
/*
* Ensure cache coherency between kernel mapping and userspace mapping
* of this page.
*
* We have three cases to consider:
* - VIPT non-aliasing cache: fully coherent so nothing required.
* - VIVT: fully aliasing, so we need to handle every alias in our
* current VM view.
* - VIPT aliasing: need to handle one alias in our current VM view.
*
* If we need to handle aliasing:
* If the page only exists in the page cache and there are no user
* space mappings, we can be lazy and remember that we may have dirty
* kernel cache lines for later. Otherwise, we assume we have
* aliasing mappings.
*
* Note that we disable the lazy flush for SMP configurations where
* the cache maintenance operations are not automatically broadcasted.
*/
void flush_dcache_page(struct page *page)
{
struct address_space *mapping;
/*
* The zero page is never written to, so never has any dirty
* cache lines, and therefore never needs to be flushed.
*/
if (page == ZERO_PAGE(0))
return;
mapping = page_mapping(page);
if (!cache_ops_need_broadcast() &&
mapping && !mapping_mapped(mapping))
clear_bit(PG_dcache_clean, &page->flags);
else {
__flush_dcache_page(mapping, page);
if (mapping && cache_is_vivt())
__flush_dcache_aliases(mapping, page);
else if (mapping)
__flush_icache_all();
set_bit(PG_dcache_clean, &page->flags);
}
}
EXPORT_SYMBOL(flush_dcache_page);
/*
* Flush an anonymous page so that users of get_user_pages()
* can safely access the data. The expected sequence is:
*
* get_user_pages()
* -> flush_anon_page
* memcpy() to/from page
* if written to page, flush_dcache_page()
*/
void __flush_anon_page(struct vm_area_struct *vma, struct page *page, unsigned long vmaddr)
{
unsigned long pfn;
/* VIPT non-aliasing caches need do nothing */
if (cache_is_vipt_nonaliasing())
return;
/*
* Write back and invalidate userspace mapping.
*/
pfn = page_to_pfn(page);
if (cache_is_vivt()) {
flush_cache_page(vma, vmaddr, pfn);
} else {
/*
* For aliasing VIPT, we can flush an alias of the
* userspace address only.
*/
flush_pfn_alias(pfn, vmaddr);
__flush_icache_all();
}
/*
* Invalidate kernel mapping. No data should be contained
* in this mapping of the page. FIXME: this is overkill
* since we actually ask for a write-back and invalidate.
*/
__cpuc_flush_dcache_area(page_address(page), PAGE_SIZE);
}
| Java |
// STLport regression testsuite component.
// To compile as a separate example, please #define MAIN.
#include <iterator>
#include <vector>
#include <algorithm>
#include <iostream>
#include <numeric>
#include <iterator>
#ifdef MAIN
#define partsum1_test main
#endif
#if !defined (STLPORT) || defined(__STL_USE_NAMESPACES)
using namespace std;
#endif
int partsum1_test(int, char**)
{
cout<<"Results of partsum1_test:"<<endl;
vector <int> v1(10);
iota(v1.begin(), v1.end(), 0);
vector <int> v2(v1.size());
partial_sum(v1.begin(), v1.end(), v2.begin());
ostream_iterator <int> iter(cout, " ");
copy(v1.begin(), v1.end(), iter);
cout << endl;
copy(v2.begin(), v2.end(), iter);
cout << endl;
return 0;
}
| Java |
/*
* Copyright (c) 2011-2012, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only 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.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <mach/rpm-regulator.h>
#include <mach/msm_bus_board.h>
#include <mach/msm_bus.h>
#include "mach/socinfo.h"
#include "acpuclock.h"
#include "acpuclock-krait.h"
#ifdef CONFIG_PERFLOCK
#include <mach/perflock.h>
#endif
static struct hfpll_data hfpll_data __initdata = {
.mode_offset = 0x00,
.l_offset = 0x08,
.m_offset = 0x0C,
.n_offset = 0x10,
.config_offset = 0x04,
.config_val = 0x7845C665,
.has_droop_ctl = true,
.droop_offset = 0x14,
.droop_val = 0x0108C000,
.low_vdd_l_max = 22,
.nom_vdd_l_max = 42,
.vdd[HFPLL_VDD_NONE] = 0,
.vdd[HFPLL_VDD_LOW] = 945000,
.vdd[HFPLL_VDD_NOM] = 1050000,
.vdd[HFPLL_VDD_HIGH] = 1150000,
};
static struct scalable scalable[] __initdata = {
[CPU0] = {
.hfpll_phys_base = 0x00903200,
.aux_clk_sel_phys = 0x02088014,
.aux_clk_sel = 3,
.sec_clk_sel = 2,
.l2cpmr_iaddr = 0x4501,
.vreg[VREG_CORE] = { "krait0", 1350000 },
.vreg[VREG_MEM] = { "krait0_mem", 1150000 },
.vreg[VREG_DIG] = { "krait0_dig", 1150000 },
.vreg[VREG_HFPLL_A] = { "krait0_hfpll", 1800000 },
},
[CPU1] = {
.hfpll_phys_base = 0x00903240,
.aux_clk_sel_phys = 0x02098014,
.aux_clk_sel = 3,
.sec_clk_sel = 2,
.l2cpmr_iaddr = 0x5501,
.vreg[VREG_CORE] = { "krait1", 1350000 },
.vreg[VREG_MEM] = { "krait1_mem", 1150000 },
.vreg[VREG_DIG] = { "krait1_dig", 1150000 },
.vreg[VREG_HFPLL_A] = { "krait1_hfpll", 1800000 },
},
[CPU2] = {
.hfpll_phys_base = 0x00903280,
.aux_clk_sel_phys = 0x020A8014,
.aux_clk_sel = 3,
.sec_clk_sel = 2,
.l2cpmr_iaddr = 0x6501,
.vreg[VREG_CORE] = { "krait2", 1350000 },
.vreg[VREG_MEM] = { "krait2_mem", 1150000 },
.vreg[VREG_DIG] = { "krait2_dig", 1150000 },
.vreg[VREG_HFPLL_A] = { "krait2_hfpll", 1800000 },
},
[CPU3] = {
.hfpll_phys_base = 0x009032C0,
.aux_clk_sel_phys = 0x020B8014,
.aux_clk_sel = 3,
.sec_clk_sel = 2,
.l2cpmr_iaddr = 0x7501,
.vreg[VREG_CORE] = { "krait3", 1350000 },
.vreg[VREG_MEM] = { "krait3_mem", 1150000 },
.vreg[VREG_DIG] = { "krait3_dig", 1150000 },
.vreg[VREG_HFPLL_A] = { "krait3_hfpll", 1800000 },
},
[L2] = {
.hfpll_phys_base = 0x00903300,
.aux_clk_sel_phys = 0x02011028,
.aux_clk_sel = 3,
.sec_clk_sel = 2,
.l2cpmr_iaddr = 0x0500,
.vreg[VREG_HFPLL_A] = { "l2_hfpll", 1800000 },
},
};
static struct msm_bus_paths bw_level_tbl[] __initdata = {
[0] = BW_MBPS(640),
[1] = BW_MBPS(1064),
[2] = BW_MBPS(1600),
[3] = BW_MBPS(2128),
[4] = BW_MBPS(3200),
[5] = BW_MBPS(4264),
};
static struct msm_bus_scale_pdata bus_scale_data __initdata = {
.usecase = bw_level_tbl,
.num_usecases = ARRAY_SIZE(bw_level_tbl),
.active_only = 1,
.name = "acpuclk-8064",
};
static struct l2_level l2_freq_tbl[] __initdata = {
[0] = { { 378000, HFPLL, 2, 0x1C }, 950000, 1050000, 1 },
[0] = { { 384000, PLL_8, 0, 0x00 }, 950000, 1050000, 1 },
[1] = { { 432000, HFPLL, 2, 0x20 }, 1050000, 1050000, 2 },
[2] = { { 486000, HFPLL, 2, 0x24 }, 1050000, 1050000, 2 },
[3] = { { 540000, HFPLL, 2, 0x28 }, 1050000, 1050000, 2 },
[4] = { { 594000, HFPLL, 1, 0x16 }, 1050000, 1050000, 2 },
[5] = { { 648000, HFPLL, 1, 0x18 }, 1050000, 1050000, 4 },
[6] = { { 702000, HFPLL, 1, 0x1A }, 1150000, 1150000, 4 },
[7] = { { 756000, HFPLL, 1, 0x1C }, 1150000, 1150000, 4 },
[8] = { { 810000, HFPLL, 1, 0x1E }, 1150000, 1150000, 4 },
[9] = { { 864000, HFPLL, 1, 0x20 }, 1150000, 1150000, 4 },
[10] = { { 918000, HFPLL, 1, 0x22 }, 1150000, 1150000, 5 },
[11] = { { 972000, HFPLL, 1, 0x24 }, 1150000, 1150000, 5 },
[12] = { { 1134000, HFPLL, 1, 0x2A }, 1150000, 1150000, 5 },
[13] = { { 1242000, HFPLL, 1, 0x2E }, 1150000, 1150000, 5 },
[14] = { { 1296000, HFPLL, 1, 0x30 }, 1150000, 1150000, 5 },
[15] = { { 1350000, HFPLL, 1, 0x32 }, 1150000, 1150000, 5 },
[16] = { { 1404000, HFPLL, 1, 0x34 }, 1150000, 1150000, 5 },
[17] = { { 1458000, HFPLL, 1, 0x36 }, 1150000, 1150000, 5 },
{ }
};
static struct acpu_level tbl_slow[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 },
{ 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 975000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 975000 },
{ 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 1000000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 1000000 },
{ 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 1025000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 1025000 },
{ 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 1075000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1075000 },
{ 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1100000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1100000 },
{ 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1125000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1125000 },
{ 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1175000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1175000 },
{ 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1200000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1200000 },
{ 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1225000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1225000 },
{ 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1237500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1237500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1250000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_nom[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 },
{ 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 925000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 },
{ 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 950000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 },
{ 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 975000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 975000 },
{ 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 1025000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1025000 },
{ 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1050000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1050000 },
{ 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1075000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1075000 },
{ 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1125000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1125000 },
{ 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1150000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1150000 },
{ 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1175000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1175000 },
{ 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1187500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1187500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1200000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_fast[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 850000 },
{ 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 900000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 },
{ 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 925000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 },
{ 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 975000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 975000 },
{ 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 1000000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1000000 },
{ 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1025000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1025000 },
{ 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1075000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1075000 },
{ 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1100000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1100000 },
{ 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1125000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1125000 },
{ 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1137500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1137500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_faster[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 850000 },
{ 0, { 432000, HFPLL, 2, 0x20 }, L2(5), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 0, { 540000, HFPLL, 2, 0x28 }, L2(5), 900000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 },
{ 0, { 648000, HFPLL, 1, 0x18 }, L2(5), 925000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 },
{ 0, { 756000, HFPLL, 1, 0x1C }, L2(5), 962500 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 962500 },
{ 0, { 864000, HFPLL, 1, 0x20 }, L2(5), 975000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 975000 },
{ 0, { 972000, HFPLL, 1, 0x24 }, L2(5), 1000000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1000000 },
{ 0, { 1080000, HFPLL, 1, 0x28 }, L2(14), 1050000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1050000 },
{ 0, { 1188000, HFPLL, 1, 0x2C }, L2(14), 1075000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1075000 },
{ 0, { 1296000, HFPLL, 1, 0x30 }, L2(14), 1100000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1100000 },
{ 0, { 1404000, HFPLL, 1, 0x34 }, L2(15), 1112500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1112500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1125000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS0_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 962500 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 1000000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1025000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1037500 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1075000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1087500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1125000 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1150000 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1175000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1150000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1175000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1175000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1200000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS1_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 962500 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 975000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 1000000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1012500 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1037500 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1050000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1087500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1112500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1150000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1150000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1175000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1175000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1200000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS2_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 925000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 925000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 937500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 950000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 975000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1000000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1012500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1037500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1075000 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1100000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1125000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1150000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1150000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1175000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1225000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS3_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 900000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 925000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 950000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 975000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 987500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 1000000 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1037500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1062500 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1100000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1125000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS4_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 950000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 962500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 975000 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 1000000 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1037500 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1075000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1100000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS5_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 962500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 987500 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1012500 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1050000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1075000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1125000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1150000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS6_1700MHz[] __initdata = {
{ 1, { 162000, HFPLL, 2, 0x0C }, L2(0), 900000 },
{ 1, { 216000, HFPLL, 2, 0x10 }, L2(0), 900000 },
{ 1, { 270000, HFPLL, 2, 0x14 }, L2(0), 900000 },
{ 1, { 324000, HFPLL, 2, 0x18 }, L2(0), 925000 },
{ 1, { 378000, HFPLL, 2, 0x1C }, L2(0), 925000 },
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(15), 962500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(15), 975000 },
{ 1, { 1512000, HFPLL, 1, 0x38 }, L2(15), 1150000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(15), 1000000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(15), 1025000 },
{ 1, { 1728000, HFPLL, 1, 0x40 }, L2(15), 1050000 },
#ifdef CONFIG_CPU_OC
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(15), 1100000 },
{ 1, { 1836000, HFPLL, 1, 0x44 }, L2(15), 1125000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(15), 1175000 },
#endif
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS0_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 950000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 950000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 950000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 950000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 962500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 975000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 1000000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1025000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1037500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1062500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1100000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1125000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1175000 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1225000 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1287500 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS1_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 925000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 925000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 925000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 925000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 937500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 950000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 975000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 1000000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 1012500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1037500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1075000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1100000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1137500 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1187500 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1250000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS2_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 912500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 925000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 950000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 975000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 987500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1012500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1050000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1075000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1112500 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1162500 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1212500 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS3_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 900000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 900000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 900000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 900000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 900000 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 912500 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 937500 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 962500 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 975000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 1000000 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1025000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1050000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1087500 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1137500 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1175000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS4_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 950000 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 962500 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 975000 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 1000000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1037500 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1075000 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1112500 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1150000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS5_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 962500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 987500 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1012500 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1050000 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1087500 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1125000 },
{ 0, { 0 } }
};
static struct acpu_level tbl_PVS6_2000MHz[] __initdata = {
{ 1, { 384000, PLL_8, 0, 0x00 }, L2(0), 875000 },
{ 1, { 486000, HFPLL, 2, 0x24 }, L2(5), 875000 },
{ 1, { 594000, HFPLL, 1, 0x16 }, L2(5), 875000 },
{ 1, { 702000, HFPLL, 1, 0x1A }, L2(5), 875000 },
{ 1, { 810000, HFPLL, 1, 0x1E }, L2(5), 887500 },
{ 1, { 918000, HFPLL, 1, 0x22 }, L2(5), 900000 },
{ 1, { 1026000, HFPLL, 1, 0x26 }, L2(5), 925000 },
{ 1, { 1134000, HFPLL, 1, 0x2A }, L2(14), 937500 },
{ 1, { 1242000, HFPLL, 1, 0x2E }, L2(14), 950000 },
{ 1, { 1350000, HFPLL, 1, 0x32 }, L2(14), 962500 },
{ 1, { 1458000, HFPLL, 1, 0x36 }, L2(14), 975000 },
{ 1, { 1566000, HFPLL, 1, 0x3A }, L2(14), 1000000 },
{ 1, { 1674000, HFPLL, 1, 0x3E }, L2(14), 1025000 },
{ 1, { 1782000, HFPLL, 1, 0x42 }, L2(14), 1062500 },
{ 1, { 1890000, HFPLL, 1, 0x46 }, L2(14), 1100000 },
{ 0, { 0 } }
};
static struct pvs_table pvs_tables[NUM_SPEED_BINS][NUM_PVS] __initdata = {
[0][PVS_SLOW] = {tbl_slow, sizeof(tbl_slow), 0 },
[0][PVS_NOMINAL] = {tbl_nom, sizeof(tbl_nom), 25000 },
[0][PVS_FAST] = {tbl_fast, sizeof(tbl_fast), 25000 },
[0][PVS_FASTER] = {tbl_faster, sizeof(tbl_faster), 25000 },
[1][0] = { tbl_PVS0_1700MHz, sizeof(tbl_PVS0_1700MHz), 0 },
[1][1] = { tbl_PVS1_1700MHz, sizeof(tbl_PVS1_1700MHz), 25000 },
[1][2] = { tbl_PVS2_1700MHz, sizeof(tbl_PVS2_1700MHz), 25000 },
[1][3] = { tbl_PVS3_1700MHz, sizeof(tbl_PVS3_1700MHz), 25000 },
[1][4] = { tbl_PVS4_1700MHz, sizeof(tbl_PVS4_1700MHz), 25000 },
[1][5] = { tbl_PVS5_1700MHz, sizeof(tbl_PVS5_1700MHz), 25000 },
[1][6] = { tbl_PVS6_1700MHz, sizeof(tbl_PVS6_1700MHz), 25000 },
[2][0] = { tbl_PVS0_2000MHz, sizeof(tbl_PVS0_2000MHz), 0 },
[2][1] = { tbl_PVS1_2000MHz, sizeof(tbl_PVS1_2000MHz), 25000 },
[2][2] = { tbl_PVS2_2000MHz, sizeof(tbl_PVS2_2000MHz), 25000 },
[2][3] = { tbl_PVS3_2000MHz, sizeof(tbl_PVS3_2000MHz), 25000 },
[2][4] = { tbl_PVS4_2000MHz, sizeof(tbl_PVS4_2000MHz), 25000 },
[2][5] = { tbl_PVS5_2000MHz, sizeof(tbl_PVS5_2000MHz), 25000 },
[2][6] = { tbl_PVS6_2000MHz, sizeof(tbl_PVS6_2000MHz), 25000 },
};
static struct acpuclk_krait_params acpuclk_8064_params __initdata = {
.scalable = scalable,
.scalable_size = sizeof(scalable),
.hfpll_data = &hfpll_data,
.pvs_tables = pvs_tables,
.l2_freq_tbl = l2_freq_tbl,
.l2_freq_tbl_size = sizeof(l2_freq_tbl),
.bus_scale = &bus_scale_data,
.pte_efuse_phys = 0x007000C0,
.stby_khz = 384000,
};
static int __init acpuclk_8064_probe(struct platform_device *pdev)
{
int ret;
if (cpu_is_apq8064ab() ||
SOCINFO_VERSION_MAJOR(socinfo_get_version()) == 2) {
acpuclk_8064_params.hfpll_data->low_vdd_l_max = 37;
acpuclk_8064_params.hfpll_data->nom_vdd_l_max = 74;
}
ret = acpuclk_krait_init(&pdev->dev, &acpuclk_8064_params);
return ret;
}
static struct platform_driver acpuclk_8064_driver = {
.driver = {
.name = "acpuclk-8064",
.owner = THIS_MODULE,
},
};
static int __init acpuclk_8064_init(void)
{
return platform_driver_probe(&acpuclk_8064_driver,
acpuclk_8064_probe);
}
device_initcall(acpuclk_8064_init); | Java |
#include <stdio.h>
#include <stdlib.h>
#include <string.h> /* memset */
#include <libwzd-core/wzd_structs.h>
#include <libwzd-core/wzd_crc32.h>
#define C1 0x12345678
#define C2 0x9abcdef0
int main(int argc, char *argv[])
{
unsigned long c1 = C1;
unsigned long crc = 0x0;
char input1[1024];
const char * file1 = "file_crc.txt";
const unsigned long crc_ref = 0xEB2FAFAF; /* cksfv file_crc.txt */
char * srcdir = NULL;
unsigned long c2 = C2;
if (argc > 1) {
srcdir = argv[1];
} else {
srcdir = getenv("srcdir");
if (srcdir == NULL) {
fprintf(stderr, "Environment variable $srcdir not found, aborting\n");
return 1;
}
}
snprintf(input1,sizeof(input1)-1,"%s/%s",srcdir,file1);
if ( calc_crc32(input1,&crc,0,(unsigned long)-1) ) {
fprintf(stderr, "calc_crc32 failed\n");
return 1;
}
if ( crc != crc_ref ) {
fprintf(stderr, "calc_crc32 returned crap\n");
return 1;
}
if (c1 != C1) {
fprintf(stderr, "c1 nuked !\n");
return -1;
}
if (c2 != C2) {
fprintf(stderr, "c2 nuked !\n");
return -1;
}
return 0;
}
| Java |
import json
import bottle
from pyrouted.util import make_spec
def route(method, path):
def decorator(f):
f.http_route = path
f.http_method = method
return f
return decorator
class APIv1(object):
prefix = '/v1'
def __init__(self, ndb, config):
self.ndb = ndb
self.config = config
@route('GET', '/sources')
def sources_list(self, mode='short'):
ret = {}
mode = bottle.request.query.mode or mode
for name, spec in self.ndb.sources.items():
ret[name] = {'class': spec.nl.__class__.__name__,
'status': spec.status}
if mode == 'full':
ret[name]['config'] = spec.nl_kwarg
return bottle.template('{{!ret}}', ret=json.dumps(ret))
@route('PUT', '/sources')
def sources_restart(self):
node = bottle.request.body.getvalue().decode('utf-8')
self.ndb.sources[node].start()
@route('POST', '/sources')
def sources_add(self):
data = bottle.request.body.getvalue().decode('utf-8')
node, spec = make_spec(data, self.config)
self.config['sources'].append(node)
self.ndb.connect_source(node, spec)
@route('DELETE', '/sources')
def sources_del(self):
node = bottle.request.body.getvalue().decode('utf-8')
self.config['sources'].remove(node)
self.ndb.disconnect_source(node)
@route('GET', '/config')
def config_get(self):
return bottle.template('{{!ret}}',
ret=json.dumps(self.config))
@route('PUT', '/config')
def config_dump(self):
path = bottle.request.body.getvalue().decode('utf-8')
self.config.dump(path)
@route('GET', '/<name:re:(%s|%s|%s|%s|%s|%s)>' % ('interfaces',
'addresses',
'routes',
'neighbours',
'vlans',
'bridges'))
def view(self, name):
ret = []
obj = getattr(self.ndb, name)
for line in obj.dump():
ret.append(line)
return bottle.template('{{!ret}}', ret=json.dumps(ret))
@route('GET', '/query/<name:re:(%s|%s|%s|%s)>' % ('nodes',
'p2p_edges',
'l2_edges',
'l3_edges'))
def query(self, name):
ret = []
obj = getattr(self.ndb.query, name)
for line in obj():
ret.append(line)
return bottle.template('{{!ret}}', ret=json.dumps(ret))
| Java |
\documentclass{article}
\usepackage{epsfig}
\usepackage{color}
\usepackage{amsmath}
\usepackage[T1]{fontenc}
\usepackage[latin1]{inputenc}
\usepackage[german]{babel}
\usepackage{helvet}
\selectlanguage{german}
\oddsidemargin15pt
\evensidemargin15pt
\textheight25mm
\textwidth20cm
\begin{document}
\definecolor{bunt}{rgb}{1.0,1.0,0.9}
\thispagestyle{empty}
\sffamily
\LARGE
\pagecolor{black}
\color{white}
\noindent
Die zwei Brennpunkte der Marsbahn werden mit
einem \color{red}roten +\color{white} ~markiert.
Die Sonne steht in einem Brennpunkt der Bahn.
\end{document}
| Java |
/* Copyright (C) 2022, Specify Collections Consortium
*
* Specify Collections Consortium, Biodiversity Institute, University of Kansas,
* 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA, support@specifysoftware.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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package edu.ku.brc.specify.datamodel.busrules;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.DateFormat;
import java.util.List;
import java.util.Set;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import edu.ku.brc.af.core.AppContextMgr;
import edu.ku.brc.af.core.db.DBFieldInfo;
import edu.ku.brc.af.core.db.DBTableIdMgr;
import edu.ku.brc.af.core.db.DBTableInfo;
import edu.ku.brc.af.core.expresssearch.QueryAdjusterForDomain;
import edu.ku.brc.af.ui.forms.FormViewObj;
import edu.ku.brc.af.ui.forms.Viewable;
import edu.ku.brc.af.ui.forms.persist.AltViewIFace.CreationMode;
import edu.ku.brc.af.ui.forms.validation.UIValidator;
import edu.ku.brc.af.ui.forms.validation.ValComboBox;
import edu.ku.brc.af.ui.forms.validation.ValComboBoxFromQuery;
import edu.ku.brc.af.ui.forms.validation.ValTextField;
import edu.ku.brc.dbsupport.DataProviderFactory;
import edu.ku.brc.dbsupport.DataProviderSessionIFace;
import edu.ku.brc.dbsupport.DataProviderSessionIFace.QueryIFace;
import edu.ku.brc.specify.config.SpecifyAppContextMgr;
import edu.ku.brc.specify.conversion.BasicSQLUtils;
import edu.ku.brc.specify.datamodel.CollectionMember;
import edu.ku.brc.specify.datamodel.Discipline;
import edu.ku.brc.specify.datamodel.SpTaskSemaphore;
import edu.ku.brc.specify.datamodel.TreeDefIface;
import edu.ku.brc.specify.datamodel.TreeDefItemIface;
import edu.ku.brc.specify.datamodel.TreeDefItemStandardEntry;
import edu.ku.brc.specify.datamodel.Treeable;
import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr;
import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgr.USER_ACTION;
import edu.ku.brc.specify.dbsupport.TaskSemaphoreMgrCallerIFace;
import edu.ku.brc.specify.dbsupport.TreeDefStatusMgr;
import edu.ku.brc.specify.treeutils.TreeDataService;
import edu.ku.brc.specify.treeutils.TreeDataServiceFactory;
import edu.ku.brc.specify.treeutils.TreeHelper;
import edu.ku.brc.ui.GetSetValueIFace;
import edu.ku.brc.ui.UIRegistry;
/**
* @author rod
*
* (original author was JDS)
*
* @code_status Alpha
*
* Jan 10, 2008
*
* @param <T>
* @param <D>
* @param <I>
*/
public abstract class BaseTreeBusRules<T extends Treeable<T,D,I>,
D extends TreeDefIface<T,D,I>,
I extends TreeDefItemIface<T,D,I>>
extends AttachmentOwnerBaseBusRules
{
public static final boolean ALLOW_CONCURRENT_FORM_ACCESS = true;
public static final long FORM_SAVE_LOCK_MAX_DURATION_IN_MILLIS = 60000;
private static final Logger log = Logger.getLogger(BaseTreeBusRules.class);
private boolean processedRules = false;
/**
* Constructor.
*
* @param dataClasses a var args list of classes that this business rules implementation handles
*/
public BaseTreeBusRules(Class<?>... dataClasses)
{
super(dataClasses);
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#initialize(edu.ku.brc.ui.forms.Viewable)
*/
@Override
public void initialize(Viewable viewableArg)
{
super.initialize(viewableArg);
GetSetValueIFace parentField = (GetSetValueIFace)formViewObj.getControlByName("parent");
Component comp = formViewObj.getControlByName("definitionItem");
if (comp instanceof ValComboBox)
{
final ValComboBox rankComboBox = (ValComboBox)comp;
final JCheckBox acceptedCheckBox = (JCheckBox)formViewObj.getControlByName("isAccepted");
Component apComp = formViewObj.getControlByName("acceptedParent");
final ValComboBoxFromQuery acceptedParentWidget = apComp instanceof ValComboBoxFromQuery ?
(ValComboBoxFromQuery )apComp : null;
if (parentField instanceof ValComboBoxFromQuery)
{
final ValComboBoxFromQuery parentCBX = (ValComboBoxFromQuery)parentField;
if (parentCBX != null && rankComboBox != null)
{
parentCBX.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e)
{
if (e == null || !e.getValueIsAdjusting())
{
parentChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, acceptedParentWidget);
}
}
});
rankComboBox.getComboBox().addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e)
{
rankChanged(formViewObj, parentCBX, rankComboBox, acceptedCheckBox, acceptedParentWidget);
}
});
}
}
if (acceptedCheckBox != null && acceptedParentWidget != null)
{
acceptedCheckBox.addItemListener(new ItemListener()
{
public void itemStateChanged(ItemEvent e)
{
if (acceptedCheckBox.isSelected())
{
acceptedParentWidget.setValue(null, null);
acceptedParentWidget.setChanged(true); // This should be done automatically
acceptedParentWidget.setEnabled(false);
}
else
{
acceptedParentWidget.setEnabled(true);
}
}
});
}
}
}
/**
* @return list of foreign key relationships for purposes of checking
* if a record can be deleted.
* The list contains two entries for each relationship. The first entry
* is the related table name. The second is the name of the foreign key field in the related table.
*/
public abstract String[] getRelatedTableAndColumnNames();
/**
* @return list of ass foreign key relationships.
* The list contains two entries for each relationship. The first entry
* is the related table name. The second is the name of the foreign key field in the related table.
*/
public String[] getAllRelatedTableAndColumnNames()
{
return getRelatedTableAndColumnNames();
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#okToEnableDelete(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean okToEnableDelete(Object dataObj)
{
// This is a little weak and chessey, but it gets the job done.
// Becase both the Tree and Definition want/need to share Business Rules.
String viewName = formViewObj.getView().getName();
if (StringUtils.contains(viewName, "TreeDef"))
{
final I treeDefItem = (I)dataObj;
if (treeDefItem != null && treeDefItem.getTreeDef() != null)
{
return treeDefItem.getTreeDef().isRequiredLevel(treeDefItem.getRankId());
}
}
return super.okToEnableDelete(dataObj);
}
/**
* @param node
* @return
*/
@SuppressWarnings("unchecked")
public boolean okToDeleteNode(T node)
{
if (node.getDefinition() != null && !node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress())
{
//Scary. If nodes are not up to date, tree rules may not work.
//The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading
//workbenches.
throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers.");
}
if (node.getDefinition() != null && node.getDefinition().isUploadInProgress())
{
//don't think this will ever get called during an upload/upload-undo, but just in case.
return true;
}
Integer id = node.getTreeId();
if (id == null)
{
return true;
}
String[] relationships = getRelatedTableAndColumnNames();
// if the given node can't be deleted, return false
if (!super.okToDelete(relationships, node.getTreeId()))
{
return false;
}
// now check the children
// get a list of all descendent IDs
DataProviderSessionIFace session = null;
List<Integer> childIDs = null;
try
{
session = DataProviderFactory.getInstance().createSession();
String queryStr = "SELECT n.id FROM " + node.getClass().getName() + " n WHERE n.nodeNumber <= :highChild AND n.nodeNumber > :nodeNum ORDER BY n.rankId DESC";
QueryIFace query = session.createQuery(queryStr, false);
query.setParameter("highChild", node.getHighestChildNodeNumber());
query.setParameter("nodeNum", node.getNodeNumber());
childIDs = (List<Integer>)query.list();
} catch (Exception ex)
{
edu.ku.brc.exceptions.ExceptionTracker.getInstance().capture(BaseTreeBusRules.class, ex);
// Error Dialog
ex.printStackTrace();
} finally
{
if (session != null)
{
session.close();
}
}
// if there are no descendent nodes, return true
if (childIDs != null && childIDs.size() == 0)
{
return true;
}
// break the descendent checks up into chunks or queries
// This is an arbitrary number. Trial and error will determine a good value. This determines
// the number of IDs that wind up in the "IN" clause of the query run inside okToDelete().
int chunkSize = 250;
int lastRecordChecked = -1;
boolean childrenDeletable = true;
while (lastRecordChecked + 1 < childIDs.size() && childrenDeletable)
{
int startOfChunk = lastRecordChecked + 1;
int endOfChunk = Math.min(lastRecordChecked+1+chunkSize, childIDs.size());
// grabs selected subset, exclusive of the last index
List<Integer> chunk = childIDs.subList(startOfChunk, endOfChunk);
Integer[] idChunk = chunk.toArray(new Integer[1]);
childrenDeletable = super.okToDelete(relationships, idChunk);
lastRecordChecked = endOfChunk - 1;
}
return childrenDeletable;
}
@Override
protected String getExtraWhereColumns(DBTableInfo tableInfo) {
String result = super.getExtraWhereColumns(tableInfo);
if (CollectionMember.class.isAssignableFrom(tableInfo.getClassObj()))
{
Vector<Object> cols = BasicSQLUtils.querySingleCol("select distinct CollectionID from collection "
+ "where DisciplineID = " + AppContextMgr.getInstance().getClassObject(Discipline.class).getId());
if (cols != null)
{
String colList = "";
for (Object col : cols)
{
if (!"".equals(colList))
{
colList += ",";
}
colList += col;
}
if (!"".equals(colList))
{
result = "((" + result + ") or " + tableInfo.getAbbrev() + ".CollectionMemberID in(" + colList + "))";
}
}
}
return result;
}
@SuppressWarnings("unchecked")
protected void rankChanged(final FormViewObj form,
final ValComboBoxFromQuery parentComboBox,
final ValComboBox rankComboBox,
final JCheckBox acceptedCheckBox,
final ValComboBoxFromQuery acceptedParentWidget)
{
if (form.getAltView().getMode() != CreationMode.EDIT)
{
return;
}
//log.debug("form was validated: calling adjustRankComboBoxModel()");
Object objInForm = form.getDataObj();
//log.debug("form data object = " + objInForm);
if (objInForm == null)
{
return;
}
final T formNode = (T)objInForm;
T parent = null;
if (parentComboBox.getValue() instanceof String)
{
// the data is still in the VIEW mode for some reason
log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String");
parentComboBox.getValue();
parent = formNode.getParent();
}
else
{
parent = (T)parentComboBox.getValue();
}
final T theParent = parent;
I rankObj = (I )rankComboBox.getValue();
final int rank = rankObj == null ? -2 : rankObj.getRankId();
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
boolean canSynonymize = false;
if (canAccessSynonymy(formNode, rank))
{
canSynonymize = formNode.getDefinition() != null && formNode.getDefinition()
.getSynonymizedLevel() <= rank
&& formNode.getDescendantCount() == 0;
}
if (acceptedCheckBox != null && acceptedParentWidget != null)
{
acceptedCheckBox.setEnabled(canSynonymize && theParent != null);
if (acceptedCheckBox.isSelected() && acceptedCheckBox.isEnabled())
{
acceptedParentWidget.setValue(null, null);
acceptedParentWidget.setChanged(true); // This should be done automatically
acceptedParentWidget.setEnabled(false);
}
}
form.getValidator().validateForm();
}
});
}
@SuppressWarnings("unchecked")
protected void parentChanged(final FormViewObj form,
final ValComboBoxFromQuery parentComboBox,
final ValComboBox rankComboBox,
final JCheckBox acceptedCheckBox,
final ValComboBoxFromQuery acceptedParentWidget)
{
if (form.getAltView().getMode() != CreationMode.EDIT)
{
return;
}
//log.debug("form was validated: calling adjustRankComboBoxModel()");
Object objInForm = form.getDataObj();
//log.debug("form data object = " + objInForm);
if (objInForm == null)
{
return;
}
final T formNode = (T)objInForm;
// set the contents of this combobox based on the value chosen as the parent
adjustRankComboBoxModel(parentComboBox, rankComboBox, formNode);
T parent = null;
if (parentComboBox.getValue() instanceof String)
{
// the data is still in the VIEW mode for some reason
log.debug("Form is in mode (" + form.getAltView().getMode() + ") but the parent data is a String");
parentComboBox.getValue();
parent = formNode.getParent();
}
else
{
parent = (T)parentComboBox.getValue();
}
// set the tree def for the object being edited by using the parent node's tree def
// set the parent too??? (lookups for the AcceptedParent QueryComboBox need this)
if (parent != null)
{
formNode.setDefinition(parent.getDefinition());
formNode.setParent(parent);
}
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
boolean rnkEnabled = rankComboBox.getComboBox().getModel().getSize() > 0;
rankComboBox.setEnabled(rnkEnabled);
JLabel label = form.getLabelFor(rankComboBox);
if (label != null)
{
label.setEnabled(rnkEnabled);
}
if (rankComboBox.hasFocus() && !rnkEnabled)
{
parentComboBox.requestFocus();
}
rankChanged(formViewObj, parentComboBox, rankComboBox, acceptedCheckBox, acceptedParentWidget);
form.getValidator().validateForm();
}
});
}
/**
* @param parentField
* @param rankComboBox
* @param nodeInForm
*/
@SuppressWarnings("unchecked")
protected void adjustRankComboBoxModel(final GetSetValueIFace parentField,
final ValComboBox rankComboBox,
final T nodeInForm)
{
log.debug("Adjusting the model for the 'rank' combo box in a tree node form");
if (nodeInForm == null)
{
return;
}
log.debug("nodeInForm = " + nodeInForm.getName());
DefaultComboBoxModel<I> model = (DefaultComboBoxModel<I>)rankComboBox.getModel();
model.removeAllElements();
// this is the highest rank the edited item can possibly be
I topItem = null;
// this is the lowest rank the edited item can possibly be
I bottomItem = null;
Object value = parentField.getValue();
T parent = null;
if (value instanceof String)
{
// this happens when the combobox is in view mode, which means it's really a textfield
// in that case, the parent of the node in the form will do, since the user can't change the parents
parent = nodeInForm.getParent();
}
else
{
parent = (T)parentField.getValue();
}
if (parent == null)
{
return;
}
// grab all the def items from just below the parent's item all the way to the next enforced level
// or to the level of the highest ranked child
topItem = parent.getDefinitionItem().getChild();
log.debug("highest valid tree level: " + topItem);
if (topItem == null)
{
// this only happens if a parent was chosen that cannot have children b/c it is at the
// lowest defined level in the tree
log.warn("Chosen node cannot be a parent node. It is at the lowest defined level of the tree.");
return;
}
// find the child with the highest rank and set that child's def item as the bottom of the range
if (!nodeInForm.getChildren().isEmpty())
{
for (T child: nodeInForm.getChildren())
{
if (bottomItem==null || child.getRankId()>bottomItem.getRankId())
{
bottomItem = child.getDefinitionItem().getParent();
}
}
}
log.debug("lowest valid tree level: " + bottomItem);
I item = topItem;
boolean done = false;
while (!done)
{
model.addElement(item);
if (item.getChild()==null || item.getIsEnforced()==Boolean.TRUE || (bottomItem != null && item.getRankId().intValue()==bottomItem.getRankId().intValue()) )
{
done = true;
}
item = item.getChild();
}
if (nodeInForm.getDefinitionItem() != null)
{
I defItem = nodeInForm.getDefinitionItem();
for (int i = 0; i < model.getSize(); ++i)
{
I modelItem = (I)model.getElementAt(i);
if (modelItem.getRankId().equals(defItem.getRankId()))
{
log.debug("setting rank selected value to " + modelItem);
model.setSelectedItem(modelItem);
}
}
// if (model.getIndexOf(defItem) != -1)
// {
// model.setSelectedItem(defItem);
// }
}
else if (model.getSize() == 1)
{
Object defItem = model.getElementAt(0);
log.debug("setting rank selected value to the only available option: " + defItem);
model.setSelectedItem(defItem);
}
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#afterFillForm(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public void afterFillForm(final Object dataObj)
{
// This is a little weak and cheesey, but it gets the job done.
// Because both the Tree and Definition want/need to share Business Rules.
String viewName = formViewObj.getView().getName();
if (StringUtils.contains(viewName, "TreeDef"))
{
if (formViewObj.getAltView().getMode() != CreationMode.EDIT)
{
// when we're not in edit mode, we don't need to setup any listeners since the user can't change anything
//log.debug("form is not in edit mode: no special listeners will be attached");
return;
}
if (!StringUtils.contains(viewName, "TreeDefItem"))
{
return;
}
final I nodeInForm = (I)formViewObj.getDataObj();
//disable FullName -related fields if TreeDefItem is used by nodes in the tree
//NOTE: Can remove the edit restriction. Tree rebuilds now update fullname fields. Need to add tree rebuild after fullname def edits.
if (nodeInForm != null && nodeInForm.getTreeDef() != null)
{
// boolean canNOTEditFullNameFlds = nodeInForm.hasTreeEntries();
// if (canNOTEditFullNameFlds)
// {
// ValTextField ftCtrl = (ValTextField )formViewObj.getControlByName("textAfter");
// if (ftCtrl != null)
// {
// ftCtrl.setEnabled(false);
// }
// ftCtrl = (ValTextField )formViewObj.getControlByName("textBefore");
// if (ftCtrl != null)
// {
// ftCtrl.setEnabled(false);
// }
// ftCtrl = (ValTextField )formViewObj.getControlByName("fullNameSeparator");
// if (ftCtrl != null)
// {
// ftCtrl.setEnabled(false);
// }
// ValCheckBox ftBox = (ValCheckBox )formViewObj.getControlByName("isInFullName");
// if (ftBox != null)
// {
// ftBox.setEnabled(false);
// }
// }
if (!viewName.endsWith("TreeDefItem"))
{
return;
}
//disabling editing of name and rank for standard levels.
List<TreeDefItemStandardEntry> stds = nodeInForm.getTreeDef().getStandardLevels();
TreeDefItemStandardEntry stdLevel = null;
for (TreeDefItemStandardEntry std : stds)
{
//if (std.getTitle().equals(nodeInForm.getName()) && std.getRank() == nodeInForm.getRankId())
if (std.getRank() == nodeInForm.getRankId())
{
stdLevel = std;
break;
}
}
if (stdLevel != null)
{
ValTextField nameCtrl = (ValTextField )formViewObj.getControlByName("name");
Component rankCtrl = formViewObj.getControlByName("rankId");
if (nameCtrl != null)
{
nameCtrl.setEnabled(false);
}
if (rankCtrl != null)
{
rankCtrl.setEnabled(false);
}
if (nodeInForm.getTreeDef().isRequiredLevel(stdLevel.getRank()))
{
Component enforcedCtrl = formViewObj.getControlByName("isEnforced");
if (enforcedCtrl != null)
{
enforcedCtrl.setEnabled(false);
}
}
}
}
return;
}
final T nodeInForm = (T) formViewObj.getDataObj();
if (formViewObj.getAltView().getMode() != CreationMode.EDIT)
{
if (nodeInForm != null)
{
//XXX this MAY be necessary due to a bug with TextFieldFromPickListTable??
// TextFieldFromPickListTable.setValue() does nothing because of a null adapter member.
Component comp = formViewObj.getControlByName("definitionItem");
if (comp instanceof JTextField)
{
((JTextField )comp).setText(nodeInForm.getDefinitionItem().getName());
}
}
}
else
{
processedRules = false;
GetSetValueIFace parentField = (GetSetValueIFace) formViewObj
.getControlByName("parent");
Component comp = formViewObj.getControlByName("definitionItem");
if (comp instanceof ValComboBox)
{
final ValComboBox rankComboBox = (ValComboBox) comp;
if (parentField instanceof ValComboBoxFromQuery)
{
final ValComboBoxFromQuery parentCBX = (ValComboBoxFromQuery) parentField;
if (parentCBX != null && rankComboBox != null && nodeInForm != null)
{
parentCBX.registerQueryBuilder(new TreeableSearchQueryBuilder(nodeInForm,
rankComboBox, TreeableSearchQueryBuilder.PARENT));
}
}
if (nodeInForm != null && nodeInForm.getDefinitionItem() != null)
{
// log.debug("node in form already has a set rank: forcing a call to
// adjustRankComboBoxModel()");
UIValidator.setIgnoreAllValidation(this, true);
adjustRankComboBoxModel(parentField, rankComboBox, nodeInForm);
UIValidator.setIgnoreAllValidation(this, false);
}
// TODO: the form system MUST require the accepted parent widget to be present if
// the
// isAccepted checkbox is present
final JCheckBox acceptedCheckBox = (JCheckBox) formViewObj
.getControlByName("isAccepted");
final ValComboBoxFromQuery acceptedParentWidget = (ValComboBoxFromQuery) formViewObj
.getControlByName("acceptedParent");
if (canAccessSynonymy(nodeInForm))
{
if (acceptedCheckBox != null
&& acceptedParentWidget != null)
{
if (acceptedCheckBox.isSelected() && nodeInForm != null
&& nodeInForm.getDefinition() != null)
{
// disable if necessary
boolean canSynonymize = nodeInForm.getDefinition()
.getSynonymizedLevel() <= nodeInForm
.getRankId()
&& nodeInForm.getDescendantCount() == 0;
acceptedCheckBox.setEnabled(canSynonymize);
}
acceptedParentWidget.setEnabled(!acceptedCheckBox
.isSelected()
&& acceptedCheckBox.isEnabled());
if (acceptedCheckBox.isSelected())
{
acceptedParentWidget.setValue(null, null);
}
if (nodeInForm != null && acceptedParentWidget != null
&& rankComboBox != null)
{
acceptedParentWidget
.registerQueryBuilder(new TreeableSearchQueryBuilder(
nodeInForm,
rankComboBox,
TreeableSearchQueryBuilder.ACCEPTED_PARENT));
}
}
}
else
{
if (acceptedCheckBox != null)
{
acceptedCheckBox.setEnabled(false);
}
if (acceptedParentWidget != null)
{
acceptedParentWidget.setEnabled(false);
}
}
if (parentField instanceof ValComboBoxFromQuery)
{
parentChanged(formViewObj, (ValComboBoxFromQuery) parentField, rankComboBox,
acceptedCheckBox, acceptedParentWidget);
}
}
}
}
/**
* @param tableInfo
*
* @return Select (i.e. everything before where clause) of sqlTemplate
*/
protected String getSqlSelectTemplate(final DBTableInfo tableInfo)
{
StringBuilder sb = new StringBuilder();
sb.append("select %s1 FROM "); //$NON-NLS-1$
sb.append(tableInfo.getClassName());
sb.append(" as "); //$NON-NLS-1$
sb.append(tableInfo.getAbbrev());
String joinSnipet = QueryAdjusterForDomain.getInstance().getJoinClause(tableInfo, true, null, false); //arg 2: false means SQL
if (joinSnipet != null)
{
sb.append(' ');
sb.append(joinSnipet);
}
sb.append(' ');
return sb.toString();
}
/**
* @param dataObj
*
* return true if acceptedParent and accepted fields should be enabled on data forms.
*/
@SuppressWarnings("unchecked")
protected boolean canAccessSynonymy(final T dataObj)
{
if (dataObj == null)
{
return false; //??
}
if (dataObj.getChildren().size() > 0)
{
return false;
}
TreeDefItemIface<?,?,?> defItem = dataObj.getDefinitionItem();
if (defItem == null)
{
return false; //???
}
TreeDefIface<?,?,?> def = dataObj.getDefinition();
if (def == null)
{
def = ((SpecifyAppContextMgr )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass());
}
if (!def.isSynonymySupported())
{
return false;
}
return defItem.getRankId() >= def.getSynonymizedLevel();
}
/**
* @param dataObj
* @param rank
* @return true if the rank is synonymizable according to the relevant TreeDefinition
*
* For use when dataObj's rank has not yet been assigned or updated.
*/
@SuppressWarnings("unchecked")
protected boolean canAccessSynonymy(final T dataObj, final int rank)
{
if (dataObj == null)
{
return false; //??
}
if (dataObj.getChildren().size() > 0)
{
return false;
}
TreeDefIface<?,?,?> def = ((SpecifyAppContextMgr )AppContextMgr.getInstance()).getTreeDefForClass((Class<? extends Treeable<?,?,?>> )dataObj.getClass());
if (!def.isSynonymySupported())
{
return false;
}
return rank >= def.getSynonymizedLevel();
}
/**
* Updates the fullname field of any nodes effected by changes to <code>node</code> that are about
* to be saved to the DB.
*
* @param node
* @param session
* @param nameChanged
* @param parentChanged
* @param rankChanged
*/
@SuppressWarnings("unchecked")
protected void updateFullNamesIfNecessary(T node, DataProviderSessionIFace session)
{
if (!(node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate())) {
return;
}
if (node.getTreeId() == null)
{
// this is a new node
// it shouldn't need updating since we set the fullname at creation time
return;
}
boolean updateNodeFullName = false;
boolean updateDescFullNames = false;
// we need a way to determine if the name changed
// load a fresh copy from the DB and get the values needed for comparison
DataProviderSessionIFace tmpSession = DataProviderFactory.getInstance().createSession();
T fromDB = (T)tmpSession.get(node.getClass(), node.getTreeId());
tmpSession.close();
if (fromDB == null)
{
// this node is new and hasn't yet been flushed to the DB, so we don't need to worry about updating fullnames
//return;
fromDB = node;
}
T origParent = fromDB.getParent();
boolean parentChanged = false;
T currentParent = node.getParent();
if ((currentParent == null && origParent != null) || (currentParent != null && origParent == null))
{
// I can't imagine how this would ever happen, but just in case
parentChanged = true;
}
if (currentParent != null && origParent != null && !currentParent.getTreeId().equals(origParent.getTreeId()))
{
// the parent ID changed
parentChanged = true;
}
boolean higherLevelsIncluded = false;
if (parentChanged)
{
higherLevelsIncluded = higherLevelsIncludedInFullname(node);
higherLevelsIncluded |= higherLevelsIncludedInFullname(fromDB);
}
if (parentChanged && higherLevelsIncluded)
{
updateNodeFullName = true;
updateDescFullNames = true;
}
boolean nameChanged = !(fromDB.getName().equals(node.getName()));
boolean rankChanged = !(fromDB.getRankId().equals(node.getRankId()));
if (rankChanged || nameChanged)
{
updateNodeFullName = true;
if (booleanValue(fromDB.getDefinitionItem().getIsInFullName(), false) == true)
{
updateDescFullNames = true;
}
if (booleanValue(node.getDefinitionItem().getIsInFullName(), false) == true)
{
updateDescFullNames = true;
}
} else if (fromDB == node)
{
updateNodeFullName = true;
}
if (updateNodeFullName)
{
if (updateDescFullNames)
{
// this could take a long time
TreeHelper.fixFullnameForNodeAndDescendants(node);
}
else
{
// this should be really fast
String fullname = TreeHelper.generateFullname(node);
node.setFullName(fullname);
}
}
}
protected boolean higherLevelsIncludedInFullname(T node)
{
boolean higherLevelsIncluded = false;
// this doesn't necessarily mean the fullname has to be changed
// if no higher levels are included in the fullname, then nothing needs updating
// so, let's see if higher levels factor into the fullname
T l = node.getParent();
while (l != null)
{
if ((l.getDefinitionItem().getIsInFullName() != null) &&
(l.getDefinitionItem().getIsInFullName().booleanValue() == true))
{
higherLevelsIncluded = true;
break;
}
l = l.getParent();
}
return higherLevelsIncluded;
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#beforeSave(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@SuppressWarnings("unchecked")
@Override
public void beforeSave(Object dataObj, DataProviderSessionIFace session)
{
super.beforeSave(dataObj, session);
if (dataObj instanceof Treeable)
{
// NOTE: the instanceof check can't check against 'T' since T isn't a class
// this has a SMALL amount of risk to it
T node = (T)dataObj;
if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress())
{
//Scary. If nodes are not up to date, tree rules may not work (actually this one is OK. (for now)).
//The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading
//workbenches.
throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers.");
}
// set it's fullname
String fullname = TreeHelper.generateFullname(node);
node.setFullName(fullname);
}
}
/* (non-Javadoc)
* @see edu.ku.brc.specify.datamodel.busrules.BaseBusRules#afterSaveCommit(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public boolean beforeSaveCommit(final Object dataObj, final DataProviderSessionIFace session) throws Exception
{
// PLEASE NOTE!
// If any changes are made to this check to make sure no one (Like GeologicTimePeriod) is overriding this method
// and make the appropriate changes there also.
if (!super.beforeSaveCommit(dataObj, session))
{
return false;
}
boolean success = true;
// compare the dataObj values to the nodeBeforeSave values to determine if a node was moved or added
if (dataObj instanceof Treeable)
{
// NOTE: the instanceof check can't check against 'T' since T isn't a class
// this has a SMALL amount of risk to it
T node = (T)dataObj;
if (!node.getDefinition().getNodeNumbersAreUpToDate() && !node.getDefinition().isUploadInProgress())
{
//Scary. If nodes are not up to date, tree rules may not work.
//The application should prevent edits to items/trees whose tree numbers are not up to date except while uploading
//workbenches.
throw new RuntimeException(node.getDefinition().getName() + " has out of date node numbers.");
}
// if the node doesn't have any assigned node number, it must be new
boolean added = (node.getNodeNumber() == null);
if (node.getDefinition().getDoNodeNumberUpdates() && node.getDefinition().getNodeNumbersAreUpToDate())
{
log.info("Saved tree node was added. Updating node numbers appropriately.");
TreeDataService<T,D,I> dataServ = TreeDataServiceFactory.createService();
if (added)
{
success = dataServ.updateNodeNumbersAfterNodeAddition(node, session);
}
else
{
success = dataServ.updateNodeNumbersAfterNodeEdit(node, session);
}
}
else
{
node.getDefinition().setNodeNumbersAreUpToDate(false);
}
}
return success;
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#beforeDeleteCommit(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
/*
* NOTE: If this method is overridden, freeLocks() MUST be called when result is false
* !!
*
*/
@Override
public boolean beforeDeleteCommit(Object dataObj,
DataProviderSessionIFace session) throws Exception
{
if (!super.beforeDeleteCommit(dataObj, session))
{
return false;
}
if (dataObj != null && (formViewObj == null || !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")) &&
BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
return getRequiredLocks(dataObj);
}
else
{
return true;
}
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#afterDeleteCommit(java.lang.Object)
*/
@SuppressWarnings("unchecked")
@Override
public void afterDeleteCommit(Object dataObj)
{
try
{
if (dataObj instanceof Treeable)
{
// NOTE: the instanceof check can't check against 'T' since T
// isn't a class
// this has a SMALL amount of risk to it
T node = (T) dataObj;
if (!node.getDefinition().getNodeNumbersAreUpToDate()
&& !node.getDefinition().isUploadInProgress())
{
// Scary. If nodes are not up to date, tree rules may not
// work.
// The application should prevent edits to items/trees whose
// tree numbers are not up to date except while uploading
// workbenches.
throw new RuntimeException(node.getDefinition().getName()
+ " has out of date node numbers.");
}
if (node.getDefinition().getDoNodeNumberUpdates()
&& node.getDefinition().getNodeNumbersAreUpToDate())
{
log
.info("A tree node was deleted. Updating node numbers appropriately.");
TreeDataService<T, D, I> dataServ = TreeDataServiceFactory
.createService();
// apparently a refresh() is necessary. node can hold
// obsolete values otherwise.
// Possibly needs to be done for all business rules??
DataProviderSessionIFace session = null;
try
{
session = DataProviderFactory.getInstance()
.createSession();
// rods - 07/28/08 commented out because the node is
// already deleted
// session.refresh(node);
dataServ.updateNodeNumbersAfterNodeDeletion(node,
session);
} catch (Exception ex)
{
edu.ku.brc.exceptions.ExceptionTracker.getInstance()
.capture(BaseTreeBusRules.class, ex);
ex.printStackTrace();
} finally
{
if (session != null)
{
session.close();
}
}
} else
{
node.getDefinition().setNodeNumbersAreUpToDate(false);
}
}
} finally
{
if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
this.freeLocks();
}
}
}
/**
* Handles the {@link #beforeSave(Object)} method if the passed in {@link Object}
* is an instance of {@link TreeDefItemIface}. The real work of this method is to
* update the 'fullname' field of all {@link Treeable} objects effected by the changes
* to the passed in {@link TreeDefItemIface}.
*
* @param defItem the {@link TreeDefItemIface} being saved
*/
@SuppressWarnings("unchecked")
protected void beforeSaveTreeDefItem(I defItem)
{
// we need a way to determine if the 'isInFullname' value changed
// load a fresh copy from the DB and get the values needed for comparison
DataProviderSessionIFace tmpSession = DataProviderFactory.getInstance().createSession();
I fromDB = (I)tmpSession.load(defItem.getClass(), defItem.getTreeDefItemId());
tmpSession.close();
DataProviderSessionIFace session = DataProviderFactory.getInstance().createSession();
session.attach(defItem);
boolean changeThisLevel = false;
boolean changeAllDescendants = false;
boolean fromDBIsInFullname = makeNotNull(fromDB.getIsInFullName());
boolean currentIsInFullname = makeNotNull(defItem.getIsInFullName());
if (fromDBIsInFullname != currentIsInFullname)
{
changeAllDescendants = true;
}
// look for changes in the 'textBefore', 'textAfter' or 'fullNameSeparator' fields
String fromDbBeforeText = makeNotNull(fromDB.getTextBefore());
String fromDbAfterText = makeNotNull(fromDB.getTextAfter());
String fromDbSeparator = makeNotNull(fromDB.getFullNameSeparator());
String before = makeNotNull(defItem.getTextBefore());
String after = makeNotNull(defItem.getTextAfter());
String separator = makeNotNull(defItem.getFullNameSeparator());
boolean textFieldChanged = false;
boolean beforeChanged = !before.equals(fromDbBeforeText);
boolean afterChanged = !after.equals(fromDbAfterText);
boolean sepChanged = !separator.equals(fromDbSeparator);
if (beforeChanged || afterChanged || sepChanged)
{
textFieldChanged = true;
}
if (textFieldChanged)
{
if (currentIsInFullname)
{
changeAllDescendants = true;
}
changeThisLevel = true;
}
if (changeThisLevel && !changeAllDescendants)
{
Set<T> levelNodes = defItem.getTreeEntries();
for (T node: levelNodes)
{
String generated = TreeHelper.generateFullname(node);
node.setFullName(generated);
}
}
else if (changeThisLevel && changeAllDescendants)
{
Set<T> levelNodes = defItem.getTreeEntries();
for (T node: levelNodes)
{
TreeHelper.fixFullnameForNodeAndDescendants(node);
}
}
else if (!changeThisLevel && changeAllDescendants)
{
Set<T> levelNodes = defItem.getTreeEntries();
for (T node: levelNodes)
{
// grab all child nodes and go from there
for (T child: node.getChildren())
{
TreeHelper.fixFullnameForNodeAndDescendants(child);
}
}
}
// else don't change anything
session.close();
}
protected boolean booleanValue(Boolean bool, boolean defaultIfNull)
{
if (bool != null)
{
return bool.booleanValue();
}
return defaultIfNull;
}
/**
* Converts a null string into an empty string. If the provided String is not
* null, it is returned unchanged.
*
* @param s a string
* @return the string or " ", if null
*/
private String makeNotNull(String s)
{
return (s == null) ? "" : s;
}
/**
* Returns the provided {@link Boolean}, or <code>false</code> if null
*
* @param b the {@link Boolean} to convert to non-null
* @return the provided {@link Boolean}, or <code>false</code> if null
*/
private boolean makeNotNull(Boolean b)
{
return (b == null) ? false : b.booleanValue();
}
/* (non-Javadoc)
* @see edu.ku.brc.ui.forms.BaseBusRules#beforeDelete(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@Override
public Object beforeDelete(Object dataObj, DataProviderSessionIFace session)
{
super.beforeDelete(dataObj, session);
if (dataObj instanceof Treeable<?,?,?>)
{
Treeable<?, ?, ?> node = (Treeable<?,?,?> )dataObj;
if (node.getAcceptedParent() != null)
{
node.getAcceptedParent().getAcceptedChildren().remove(node);
node.setAcceptedParent(null);
}
}
return dataObj;
}
/**
* @param parentDataObj
* @param dataObj
* @return
*/
@SuppressWarnings("unchecked")
protected boolean parentHasChildWithSameName(final Object parentDataObj, final Object dataObj)
{
if (dataObj instanceof Treeable<?,?,?>)
{
Treeable<T, D, I> node = (Treeable<T,D,I> )dataObj;
Treeable<T, D, I> parent = parentDataObj == null ? node.getParent() : (Treeable<T, D, I> )parentDataObj;
if (parent != null)
{
//XXX the sql below will only work if all Treeable tables use fields named 'isAccepted' and 'name' to store
//the name and isAccepted properties.
String tblName = DBTableIdMgr.getInstance().getInfoById(node.getTableId()).getName();
String sql = "SELECT count(*) FROM " + tblName + " where isAccepted "
+ "and name = " + BasicSQLUtils.getEscapedSQLStrExpr(node.getName());
if (parent.getTreeId() != null)
{
sql += " and parentid = " + parent.getTreeId();
}
if (node.getTreeId() != null)
{
sql += " and " + tblName + "id != " + node.getTreeId();
}
return BasicSQLUtils.getNumRecords(sql) > 0;
}
}
return false;
}
/**
* @param parentDataObj
* @param dataObj
* @param isExistingObject
* @return
*/
@SuppressWarnings("unchecked")
public STATUS checkForSiblingWithSameName(final Object parentDataObj, final Object dataObj,
final boolean isExistingObject)
{
STATUS result = STATUS.OK;
if (parentHasChildWithSameName(parentDataObj, dataObj))
{
String parentName;
if (parentDataObj == null)
{
parentName = ((Treeable<T,D,I> )dataObj).getParent().getFullName();
}
else
{
parentName = ((Treeable<T,D,I> )parentDataObj).getFullName();
}
boolean saveIt = UIRegistry.displayConfirm(
UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_TITLE"),
String.format(UIRegistry.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING_MSG"),
parentName, ((Treeable<T,D,I> )dataObj).getName()),
UIRegistry.getResourceString("SAVE"),
UIRegistry.getResourceString("CANCEL"),
JOptionPane.QUESTION_MESSAGE);
if (!saveIt)
{
//Adding to reasonList prevents blank "Issue of Concern" popup -
//but causes annoying second "duplicate child" nag.
reasonList
.add(UIRegistry
.getResourceString("BaseTreeBusRules.IDENTICALLY_NAMED_SIBLING")); // XXX
// i18n
result = STATUS.Error;
}
}
return result;
}
/**
* @param dataObj
* @return OK if required data is present.
*
* Checks for requirements that can't be defined in the database schema.
*/
protected STATUS checkForRequiredFields(Object dataObj)
{
if (dataObj instanceof Treeable<?,?,?>)
{
STATUS result = STATUS.OK;
Treeable<?,?,?> obj = (Treeable<?,?,?> )dataObj;
if (obj.getParent() == null )
{
if (obj.getDefinitionItem() != null && obj.getDefinitionItem().getParent() == null)
{
//it's the root, null parent is OK.
return result;
}
result = STATUS.Error;
DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId());
DBFieldInfo fld = info.getFieldByColumnName("Parent");
String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("PARENT");
reasonList.add(String.format(UIRegistry.getResourceString("GENERIC_FIELD_MISSING"), fldTitle));
}
//check that non-accepted node has an 'AcceptedParent'
if (obj.getIsAccepted() == null || !obj.getIsAccepted() && obj.getAcceptedParent() == null)
{
result = STATUS.Error;
DBTableInfo info = DBTableIdMgr.getInstance().getInfoById(obj.getTableId());
DBFieldInfo fld = info.getFieldByColumnName("AcceptedParent");
String fldTitle = fld != null ? fld.getTitle() : UIRegistry.getResourceString("ACCEPTED");
reasonList.add(String.format(UIRegistry.getResourceString("GENERIC_FIELD_MISSING"), fldTitle));
}
return result;
}
return STATUS.None; //???
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#processBusinessRules(java.lang.Object, java.lang.Object, boolean)
*/
@Override
public STATUS processBusinessRules(Object parentDataObj, Object dataObj,
boolean isExistingObject)
{
reasonList.clear();
STATUS result = STATUS.OK;
if (!processedRules && dataObj instanceof Treeable<?, ?, ?>)
{
result = checkForSiblingWithSameName(parentDataObj, dataObj, isExistingObject);
if (result == STATUS.OK)
{
result = checkForRequiredFields(dataObj);
}
if (result == STATUS.OK)
{
processedRules = true;
}
}
return result;
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#isOkToSave(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
/*
* NOTE: If this method is overridden, freeLocks() MUST be called when result is false
* !!
*
*/
@Override
public boolean isOkToSave(Object dataObj, DataProviderSessionIFace session)
{
boolean result = super.isOkToSave(dataObj, session);
if (result && dataObj != null && !StringUtils.contains(formViewObj.getView().getName(), "TreeDef")
&& BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS)
{
if (!getRequiredLocks(dataObj))
{
result = false;
reasonList.add(getUnableToLockMsg());
}
}
return result;
}
/**
* @return true if locks were aquired.
*
* Locks necessary tables prior to a save.
* Only used when ALLOW_CONCURRENT_FORM_ACCESS is true.
*/
protected boolean getRequiredLocks(Object dataObj)
{
TreeDefIface<?,?,?> treeDef = ((Treeable<?,?,?>)dataObj).getDefinition();
boolean result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.isNodeNumbersAreUpToDate(treeDef);
if (!result) {
try {
Thread.sleep(1500);
result = !TreeDefStatusMgr.isRenumberingNodes(treeDef) && TreeDefStatusMgr.isNodeNumbersAreUpToDate(treeDef);
} catch (Exception e) {
result = false;
}
}
if (result) {
TaskSemaphoreMgr.USER_ACTION r = TaskSemaphoreMgr.lock(getFormSaveLockTitle(), getFormSaveLockName(), "save",
TaskSemaphoreMgr.SCOPE.Discipline, false, new TaskSemaphoreMgrCallerIFace(){
/* (non-Javadoc)
* @see edu.ku.brc.specify.dbsupport.TaskSemaphoreMgrCallerIFace#resolveConflict(edu.ku.brc.specify.datamodel.SpTaskSemaphore, boolean, java.lang.String)
*/
@Override
public USER_ACTION resolveConflict(
SpTaskSemaphore semaphore,
boolean previouslyLocked, String prevLockBy)
{
if (System.currentTimeMillis() - semaphore.getLockedTime().getTime() > FORM_SAVE_LOCK_MAX_DURATION_IN_MILLIS) {
//something is clearly wrong with the lock. Ignore it and re-use it. It will be cleared when save succeeds.
log.warn("automatically overriding expired " + getFormSaveLockTitle() + " lock set by " +
prevLockBy + " at " + DateFormat.getDateTimeInstance().format(semaphore.getLockedTime()));
return USER_ACTION.OK;
} else {
return USER_ACTION.Error;
}
}
}, false);
result = r == TaskSemaphoreMgr.USER_ACTION.OK;
}
return result;
}
/**
* @return the class for the generic parameter <T>
*/
protected abstract Class<?> getNodeClass();
/**
* @return the title for the form save lock.
*/
protected String getFormSaveLockTitle()
{
return String.format(UIRegistry.getResourceString("BaseTreeBusRules.SaveLockTitle"), getNodeClass().getSimpleName());
}
/**
* @return the name for the form save lock.
*/
protected String getFormSaveLockName()
{
return getNodeClass().getSimpleName() + "Save";
}
/**
* @return localized message to display in case of failure to lock for saving.
*/
protected String getUnableToLockMsg()
{
return UIRegistry.getResourceString("BaseTreeBusRules.UnableToLockForSave");
}
/**
* Free locks acquired for saving.
*/
protected void freeLocks()
{
TaskSemaphoreMgr.unlock(getFormSaveLockTitle(), getFormSaveLockName(), TaskSemaphoreMgr.SCOPE.Discipline);
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveCommit(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@Override
public boolean afterSaveCommit(Object dataObj,
DataProviderSessionIFace session)
{
boolean result = false;
if (!super.afterSaveCommit(dataObj, session))
{
result = false;
}
if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
freeLocks();
}
return result;
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#afterSaveFailure(java.lang.Object, edu.ku.brc.dbsupport.DataProviderSessionIFace)
*/
@Override
public void afterSaveFailure(Object dataObj,
DataProviderSessionIFace session)
{
super.afterSaveFailure(dataObj, session);
if (BaseTreeBusRules.ALLOW_CONCURRENT_FORM_ACCESS && viewable != null)
{
freeLocks();
}
}
/* (non-Javadoc)
* @see edu.ku.brc.af.ui.forms.BaseBusRules#processBusinessRules(java.lang.Object)
*/
@Override
public STATUS processBusinessRules(Object dataObj) {
STATUS result = STATUS.OK;
if (!processedRules)
{
result = super.processBusinessRules(dataObj);
if (result == STATUS.OK)
{
result = checkForSiblingWithSameName(null, dataObj, false);
}
if (result == STATUS.OK)
{
result = checkForRequiredFields(dataObj);
}
}
else
{
processedRules = false;
}
return result;
}
}
| Java |
<?php
/**
* @package WordPress Plugin
* @subpackage CMSMasters Content Composer
* @version 1.1.0
*
* Profiles Post Type
* Created by CMSMasters
*
*/
class Cmsms_Profiles {
function Cmsms_Profiles() {
$cmsms_option = cmsms_get_global_options();
$profile_labels = array(
'name' => __('Profiles', 'cmsms_content_composer'),
'singular_name' => __('Profiles', 'cmsms_content_composer'),
'menu_name' => __('Profiles', 'cmsms_content_composer'),
'all_items' => __('All Profiles', 'cmsms_content_composer'),
'add_new' => __('Add New', 'cmsms_content_composer'),
'add_new_item' => __('Add New Profile', 'cmsms_content_composer'),
'edit_item' => __('Edit Profile', 'cmsms_content_composer'),
'new_item' => __('New Profile', 'cmsms_content_composer'),
'view_item' => __('View Profile', 'cmsms_content_composer'),
'search_items' => __('Search Profiles', 'cmsms_content_composer'),
'not_found' => __('No Profiles found', 'cmsms_content_composer'),
'not_found_in_trash' => __('No Profiles found in Trash', 'cmsms_content_composer')
);
$profile_args = array(
'labels' => $profile_labels,
'query_var' => 'profile',
'capability_type' => 'post',
'menu_position' => 52,
'menu_icon' => 'dashicons-id',
'public' => true,
'show_ui' => true,
'hierarchical' => false,
'has_archive' => true,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'trackbacks',
'custom-fields',
'comments',
'revisions',
'page-attributes'
),
'rewrite' => array(
'slug' => $cmsms_option[CMSMS_SHORTNAME . '_profile_post_slug'],
'with_front' => true
)
);
register_post_type('profile', $profile_args);
add_filter('manage_edit-profile_columns', array(&$this, 'edit_columns'));
add_filter('manage_edit-profile_sortable_columns', array(&$this, 'edit_sortable_columns'));
register_taxonomy('pl-categs', array('profile'), array(
'hierarchical' => true,
'label' => __('Profile Categories', 'cmsms_content_composer'),
'singular_label' => __('Profile Category', 'cmsms_content_composer'),
'rewrite' => array(
'slug' => 'pl-categs',
'with_front' => true
)
));
add_action('manage_posts_custom_column', array(&$this, 'custom_columns'));
}
function edit_columns($columns) {
unset($columns['author']);
unset($columns['comments']);
unset($columns['date']);
$new_columns = array(
'cb' => '<input type="checkbox" />',
'title' => __('Title', 'cmsms_content_composer'),
'pl_avatar' => __('Avatar', 'cmsms_content_composer'),
'pl_categs' => __('Categories', 'cmsms_content_composer'),
'comments' => '<span class="vers"><div title="' . __('Comments', 'cmsms_content_composer') . '" class="comment-grey-bubble"></div></span>',
'menu_order' => '<span class="vers"><div class="dashicons dashicons-sort" title="' . __('Order', 'cmsms_content_composer') . '"></div></span>'
);
$result_columns = array_merge($columns, $new_columns);
return $result_columns;
}
function custom_columns($column) {
switch ($column) {
case 'pl_avatar':
if (has_post_thumbnail() != '') {
echo get_the_post_thumbnail(get_the_ID(), 'thumbnail', array(
'alt' => cmsms_title(get_the_ID(), false),
'title' => cmsms_title(get_the_ID(), false),
'style' => 'width:75px; height:75px;'
));
} else {
echo '<em>' . __('No Avatar', 'cmsms_content_composer') . '</em>';
}
break;
case 'pl_categs':
if (get_the_terms(0, 'pl-categs') != '') {
$pl_categs = get_the_terms(0, 'pl-categs');
$pl_categs_html = array();
foreach ($pl_categs as $pl_categ) {
array_push($pl_categs_html, '<a href="' . get_term_link($pl_categ->slug, 'pl-categs') . '">' . $pl_categ->name . '</a>');
}
echo implode($pl_categs_html, ', ');
} else {
echo '<em>' . __('Uncategorized', 'cmsms_content_composer') . '</em>';
}
break;
case 'menu_order':
$custom_pl_post = get_post(get_the_ID());
$custom_pl_ord = $custom_pl_post->menu_order;
echo $custom_pl_ord;
break;
}
}
function edit_sortable_columns($columns) {
$columns['menu_order'] = 'menu_order';
return $columns;
}
}
function cmsms_profiles_init() {
global $pl;
$pl = new Cmsms_Profiles();
}
add_action('init', 'cmsms_profiles_init');
| Java |
<?php
namespace Goetas\XML\XSDReader\Schema\Element;
interface ElementSingle extends ElementItem
{
/**
* @return \Goetas\XML\XSDReader\Schema\Type\Type
*/
public function getType();
/**
*
* @return int
*/
public function getMin();
/**
*
* @param int $qualified
*/
public function setMin($min);
/**
*
* @return int
*/
public function getMax();
/**
*
* @param int $qualified
*/
public function setMax($max);
/**
*
* @return bool
*/
public function isQualified();
/**
*
* @param boolean $qualified
*/
public function setQualified($qualified);
/**
*
* @return bool
*/
public function isNil();
/**
*
* @param boolean $qualified
*/
public function setNil($nil);
}
| Java |
// Copyright 2017 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#include <QComboBox>
#include <QDialogButtonBox>
#include <QGroupBox>
#include <QHBoxLayout>
#include <QMessageBox>
#include <QPushButton>
#include <QTabWidget>
#include <QVBoxLayout>
#include "DolphinQt2/Config/Mapping/MappingWindow.h"
#include "Common/FileUtil.h"
#include "Common/IniFile.h"
#include "Core/Core.h"
#include "Core/HW/GCPad.h"
#include "DolphinQt2/Config/Mapping/GCKeyboardEmu.h"
#include "DolphinQt2/Config/Mapping/GCPadEmu.h"
#include "DolphinQt2/Config/Mapping/GCPadWiiU.h"
#include "DolphinQt2/Config/Mapping/WiimoteEmuExtension.h"
#include "DolphinQt2/Config/Mapping/WiimoteEmuGeneral.h"
#include "DolphinQt2/Config/Mapping/WiimoteEmuMotionControl.h"
#include "DolphinQt2/Settings.h"
#include "InputCommon/ControllerEmu/ControllerEmu.h"
#include "InputCommon/ControllerInterface/Device.h"
#include "InputCommon/InputConfig.h"
#include "InputCommon/ControllerInterface/ControllerInterface.h"
MappingWindow::MappingWindow(QWidget* parent, int port_num) : QDialog(parent), m_port(port_num)
{
setWindowTitle(tr("Port %1").arg(port_num + 1));
CreateDevicesLayout();
CreateProfilesLayout();
CreateResetLayout();
CreateMainLayout();
ConnectWidgets();
}
void MappingWindow::CreateDevicesLayout()
{
m_devices_layout = new QHBoxLayout();
m_devices_box = new QGroupBox(tr("Devices"));
m_devices_combo = new QComboBox();
m_devices_refresh = new QPushButton(tr("Refresh"));
m_devices_refresh->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_devices_layout->addWidget(m_devices_combo);
m_devices_layout->addWidget(m_devices_refresh);
m_devices_box->setLayout(m_devices_layout);
}
void MappingWindow::CreateProfilesLayout()
{
m_profiles_layout = new QVBoxLayout();
m_profiles_box = new QGroupBox(tr("Profiles"));
m_profiles_combo = new QComboBox();
m_profiles_load = new QPushButton(tr("Load"));
m_profiles_save = new QPushButton(tr("Save"));
m_profiles_delete = new QPushButton(tr("Delete"));
auto* button_layout = new QHBoxLayout();
m_profiles_box->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
m_profiles_combo->setEditable(true);
m_profiles_layout->addWidget(m_profiles_combo);
button_layout->addWidget(m_profiles_load);
button_layout->addWidget(m_profiles_save);
button_layout->addWidget(m_profiles_delete);
m_profiles_layout->addItem(button_layout);
m_profiles_box->setLayout(m_profiles_layout);
}
void MappingWindow::CreateResetLayout()
{
m_reset_layout = new QVBoxLayout();
m_reset_box = new QGroupBox(tr("Reset"));
m_reset_clear = new QPushButton(tr("Clear"));
m_reset_default = new QPushButton(tr("Default"));
m_reset_box->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
m_reset_layout->addWidget(m_reset_clear);
m_reset_layout->addWidget(m_reset_default);
m_reset_box->setLayout(m_reset_layout);
}
void MappingWindow::CreateMainLayout()
{
m_main_layout = new QVBoxLayout();
m_config_layout = new QHBoxLayout();
m_tab_widget = new QTabWidget();
m_button_box = new QDialogButtonBox(QDialogButtonBox::Ok);
m_config_layout->addWidget(m_profiles_box);
m_config_layout->addWidget(m_reset_box);
m_main_layout->addWidget(m_devices_box);
m_main_layout->addItem(m_config_layout);
m_main_layout->addWidget(m_tab_widget);
m_main_layout->addWidget(m_button_box);
setLayout(m_main_layout);
}
void MappingWindow::ConnectWidgets()
{
connect(m_devices_refresh, &QPushButton::clicked, this, &MappingWindow::RefreshDevices);
connect(m_devices_combo, static_cast<void (QComboBox::*)(int)>(&QComboBox::currentIndexChanged),
this, &MappingWindow::OnDeviceChanged);
connect(m_reset_clear, &QPushButton::clicked, this, [this] { emit ClearFields(); });
connect(m_reset_default, &QPushButton::clicked, this, &MappingWindow::OnDefaultFieldsPressed);
connect(m_profiles_save, &QPushButton::clicked, this, &MappingWindow::OnSaveProfilePressed);
connect(m_profiles_load, &QPushButton::clicked, this, &MappingWindow::OnLoadProfilePressed);
connect(m_profiles_delete, &QPushButton::clicked, this, &MappingWindow::OnDeleteProfilePressed);
connect(m_button_box, &QDialogButtonBox::accepted, this, &MappingWindow::accept);
}
void MappingWindow::OnDeleteProfilePressed()
{
auto& settings = Settings::Instance();
const QString profile_name = m_profiles_combo->currentText();
if (!settings.GetProfiles(m_config).contains(profile_name))
{
QMessageBox error;
error.setIcon(QMessageBox::Critical);
error.setText(tr("The profile '%1' does not exist").arg(profile_name));
error.exec();
return;
}
QMessageBox confirm(this);
confirm.setIcon(QMessageBox::Warning);
confirm.setText(tr("Are you sure that you want to delete '%1'?").arg(profile_name));
confirm.setInformativeText(tr("This cannot be undone!"));
confirm.setStandardButtons(QMessageBox::Yes | QMessageBox::Cancel);
if (confirm.exec() != QMessageBox::Yes)
{
return;
}
m_profiles_combo->removeItem(m_profiles_combo->currentIndex());
QMessageBox result(this);
std::string profile_path = settings.GetProfileINIPath(m_config, profile_name).toStdString();
File::CreateFullPath(profile_path);
File::Delete(profile_path);
result.setIcon(QMessageBox::Information);
result.setText(tr("Successfully deleted '%1'.").arg(profile_name));
}
void MappingWindow::OnLoadProfilePressed()
{
const QString profile_name = m_profiles_combo->currentText();
if (profile_name.isEmpty())
return;
std::string profile_path =
Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString();
File::CreateFullPath(profile_path);
IniFile ini;
ini.Load(profile_path);
m_controller->LoadConfig(ini.GetOrCreateSection("Profile"));
m_controller->UpdateReferences(g_controller_interface);
emit Update();
RefreshDevices();
}
void MappingWindow::OnSaveProfilePressed()
{
const QString profile_name = m_profiles_combo->currentText();
if (profile_name.isEmpty())
return;
std::string profile_path =
Settings::Instance().GetProfileINIPath(m_config, profile_name).toStdString();
File::CreateFullPath(profile_path);
IniFile ini;
m_controller->SaveConfig(ini.GetOrCreateSection("Profile"));
ini.Save(profile_path);
if (m_profiles_combo->currentIndex() == 0)
{
m_profiles_combo->addItem(profile_name);
m_profiles_combo->setCurrentIndex(m_profiles_combo->count() - 1);
}
}
void MappingWindow::OnDeviceChanged(int index)
{
const auto device = m_devices_combo->currentText().toStdString();
m_devq.FromString(device);
m_controller->default_device.FromString(device);
}
void MappingWindow::RefreshDevices()
{
m_devices_combo->clear();
const bool paused = Core::PauseAndLock(true);
g_controller_interface.RefreshDevices();
m_controller->UpdateReferences(g_controller_interface);
m_controller->UpdateDefaultDevice();
const auto default_device = m_controller->default_device.ToString();
m_devices_combo->addItem(QString::fromStdString(default_device));
for (const auto& name : g_controller_interface.GetAllDeviceStrings())
{
if (name != default_device)
m_devices_combo->addItem(QString::fromStdString(name));
}
m_devices_combo->setCurrentIndex(0);
Core::PauseAndLock(false, paused);
}
void MappingWindow::ChangeMappingType(MappingWindow::Type type)
{
if (m_mapping_type == type)
return;
ClearWidgets();
m_controller = nullptr;
MappingWidget* widget;
switch (type)
{
case Type::MAPPING_GC_KEYBOARD:
widget = new GCKeyboardEmu(this);
AddWidget(tr("GameCube Keyboard"), widget);
setWindowTitle(tr("GameCube Keyboard at Port %1").arg(GetPort() + 1));
break;
case Type::MAPPING_GC_BONGOS:
case Type::MAPPING_GC_STEERINGWHEEL:
case Type::MAPPING_GC_DANCEMAT:
case Type::MAPPING_GCPAD:
widget = new GCPadEmu(this);
setWindowTitle(tr("GameCube Controller at Port %1").arg(GetPort() + 1));
AddWidget(tr("GameCube Controller"), widget);
break;
case Type::MAPPING_GCPAD_WIIU:
widget = new GCPadWiiU(this);
setWindowTitle(tr("GameCube Adapter for Wii U at Port %1").arg(GetPort() + 1));
AddWidget(tr("GameCube Adapter for Wii U"), widget);
break;
case Type::MAPPING_WIIMOTE_EMU:
case Type::MAPPING_WIIMOTE_HYBRID:
{
auto* extension = new WiimoteEmuExtension(this);
widget = new WiimoteEmuGeneral(this, extension);
setWindowTitle(tr("Wii Remote at Port %1").arg(GetPort() + 1));
AddWidget(tr("General and Options"), widget);
AddWidget(tr("Motion Controls and IR"), new WiimoteEmuMotionControl(this));
AddWidget(tr("Extension"), extension);
break;
}
default:
return;
}
widget->LoadSettings();
m_profiles_combo->clear();
m_config = widget->GetConfig();
if (m_config)
{
m_controller = m_config->GetController(GetPort());
m_profiles_combo->addItem(QStringLiteral(""));
for (const auto& item : Settings::Instance().GetProfiles(m_config))
m_profiles_combo->addItem(item);
}
SetLayoutComplex(type != Type::MAPPING_GCPAD_WIIU);
if (m_controller != nullptr)
RefreshDevices();
m_mapping_type = type;
}
void MappingWindow::ClearWidgets()
{
m_tab_widget->clear();
}
void MappingWindow::AddWidget(const QString& name, QWidget* widget)
{
m_tab_widget->addTab(widget, name);
}
void MappingWindow::SetLayoutComplex(bool is_complex)
{
m_reset_box->setHidden(!is_complex);
m_profiles_box->setHidden(!is_complex);
m_devices_box->setHidden(!is_complex);
m_is_complex = is_complex;
}
int MappingWindow::GetPort() const
{
return m_port;
}
const ciface::Core::DeviceQualifier& MappingWindow::GetDeviceQualifier() const
{
return m_devq;
}
std::shared_ptr<ciface::Core::Device> MappingWindow::GetDevice() const
{
return g_controller_interface.FindDevice(m_devq);
}
void MappingWindow::SetBlockInputs(const bool block)
{
m_block = block;
}
bool MappingWindow::event(QEvent* event)
{
if (!m_block)
return QDialog::event(event);
return false;
}
| Java |
<?php
/**
* Created by PhpStorm.
* User: Angga Ari Wijaya
* Date: 9/12/2015
* Time: 1:04 AM
*/
namespace DecoratorPattern;
class VisaPayment implements PaymentMethod
{
public function getDescription()
{
return "Visa description";
}
} | Java |
#ifdef CONFIG_COMPAT
#include <linux/compat.h> /* for compat_old_sigset_t */
#endif
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/signal.h>
#include <linux/errno.h>
#include <linux/wait.h>
#include <linux/ptrace.h>
#include <linux/tracehook.h>
#include <linux/unistd.h>
#include <linux/mm.h>
#include <linux/tty.h>
#include <linux/binfmts.h>
#include <linux/bitops.h>
#include <asm/uaccess.h>
#include <asm/ptrace.h>
#include <asm/pgtable.h>
#include <asm/fpumacro.h>
#include <asm/uctx.h>
#include <asm/siginfo.h>
#include <asm/visasm.h>
#include "entry.h"
#include "systbls.h"
#define _BLOCKABLE (~(sigmask(SIGKILL) | sigmask(SIGSTOP)))
/* {set, get}context() needed for 64-bit SparcLinux userland. */
asmlinkage void sparc64_set_context(struct pt_regs *regs)
{
struct ucontext __user *ucp = (struct ucontext __user *)
regs->u_regs[UREG_I0];
mc_gregset_t __user *grp;
unsigned long pc, npc, tstate;
unsigned long fp, i7;
unsigned char fenab;
int err;
flush_user_windows();
if (get_thread_wsaved() ||
(((unsigned long)ucp) & (sizeof(unsigned long)-1)) ||
(!__access_ok(ucp, sizeof(*ucp))))
goto do_sigsegv;
grp = &ucp->uc_mcontext.mc_gregs;
err = __get_user(pc, &((*grp)[MC_PC]));
err |= __get_user(npc, &((*grp)[MC_NPC]));
if (err || ((pc | npc) & 3))
goto do_sigsegv;
if (regs->u_regs[UREG_I1]) {
sigset_t set;
if (_NSIG_WORDS == 1) {
if (__get_user(set.sig[0], &ucp->uc_sigmask.sig[0]))
goto do_sigsegv;
} else {
if (__copy_from_user(&set, &ucp->uc_sigmask, sizeof(sigset_t)))
goto do_sigsegv;
}
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
}
if (test_thread_flag(TIF_32BIT)) {
pc &= 0xffffffff;
npc &= 0xffffffff;
}
regs->tpc = pc;
regs->tnpc = npc;
err |= __get_user(regs->y, &((*grp)[MC_Y]));
err |= __get_user(tstate, &((*grp)[MC_TSTATE]));
regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC);
regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC));
err |= __get_user(regs->u_regs[UREG_G1], (&(*grp)[MC_G1]));
err |= __get_user(regs->u_regs[UREG_G2], (&(*grp)[MC_G2]));
err |= __get_user(regs->u_regs[UREG_G3], (&(*grp)[MC_G3]));
err |= __get_user(regs->u_regs[UREG_G4], (&(*grp)[MC_G4]));
err |= __get_user(regs->u_regs[UREG_G5], (&(*grp)[MC_G5]));
err |= __get_user(regs->u_regs[UREG_G6], (&(*grp)[MC_G6]));
/* Skip %g7 as that's the thread register in userspace. */
err |= __get_user(regs->u_regs[UREG_I0], (&(*grp)[MC_O0]));
err |= __get_user(regs->u_regs[UREG_I1], (&(*grp)[MC_O1]));
err |= __get_user(regs->u_regs[UREG_I2], (&(*grp)[MC_O2]));
err |= __get_user(regs->u_regs[UREG_I3], (&(*grp)[MC_O3]));
err |= __get_user(regs->u_regs[UREG_I4], (&(*grp)[MC_O4]));
err |= __get_user(regs->u_regs[UREG_I5], (&(*grp)[MC_O5]));
err |= __get_user(regs->u_regs[UREG_I6], (&(*grp)[MC_O6]));
err |= __get_user(regs->u_regs[UREG_I7], (&(*grp)[MC_O7]));
err |= __get_user(fp, &(ucp->uc_mcontext.mc_fp));
err |= __get_user(i7, &(ucp->uc_mcontext.mc_i7));
err |= __put_user(fp,
(&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6])));
err |= __put_user(i7,
(&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7])));
err |= __get_user(fenab, &(ucp->uc_mcontext.mc_fpregs.mcfpu_enab));
if (fenab) {
unsigned long *fpregs = current_thread_info()->fpregs;
unsigned long fprs;
fprs_write(0);
err |= __get_user(fprs, &(ucp->uc_mcontext.mc_fpregs.mcfpu_fprs));
if (fprs & FPRS_DL)
err |= copy_from_user(fpregs,
&(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs),
(sizeof(unsigned int) * 32));
if (fprs & FPRS_DU)
err |= copy_from_user(fpregs+16,
((unsigned long __user *)&(ucp->uc_mcontext.mc_fpregs.mcfpu_fregs))+16,
(sizeof(unsigned int) * 32));
err |= __get_user(current_thread_info()->xfsr[0],
&(ucp->uc_mcontext.mc_fpregs.mcfpu_fsr));
err |= __get_user(current_thread_info()->gsr[0],
&(ucp->uc_mcontext.mc_fpregs.mcfpu_gsr));
regs->tstate &= ~TSTATE_PEF;
}
if (err)
goto do_sigsegv;
return;
do_sigsegv:
force_sig(SIGSEGV, current);
}
asmlinkage void sparc64_get_context(struct pt_regs *regs)
{
struct ucontext __user *ucp = (struct ucontext __user *)
regs->u_regs[UREG_I0];
mc_gregset_t __user *grp;
mcontext_t __user *mcp;
unsigned long fp, i7;
unsigned char fenab;
int err;
synchronize_user_stack();
if (get_thread_wsaved() || clear_user(ucp, sizeof(*ucp)))
goto do_sigsegv;
#if 1
fenab = 0; /* IMO get_context is like any other system call, thus modifies FPU state -jj */
#else
fenab = (current_thread_info()->fpsaved[0] & FPRS_FEF);
#endif
mcp = &ucp->uc_mcontext;
grp = &mcp->mc_gregs;
/* Skip over the trap instruction, first. */
if (test_thread_flag(TIF_32BIT)) {
regs->tpc = (regs->tnpc & 0xffffffff);
regs->tnpc = (regs->tnpc + 4) & 0xffffffff;
} else {
regs->tpc = regs->tnpc;
regs->tnpc += 4;
}
err = 0;
if (_NSIG_WORDS == 1)
err |= __put_user(current->blocked.sig[0],
(unsigned long __user *)&ucp->uc_sigmask);
else
err |= __copy_to_user(&ucp->uc_sigmask, ¤t->blocked,
sizeof(sigset_t));
err |= __put_user(regs->tstate, &((*grp)[MC_TSTATE]));
err |= __put_user(regs->tpc, &((*grp)[MC_PC]));
err |= __put_user(regs->tnpc, &((*grp)[MC_NPC]));
err |= __put_user(regs->y, &((*grp)[MC_Y]));
err |= __put_user(regs->u_regs[UREG_G1], &((*grp)[MC_G1]));
err |= __put_user(regs->u_regs[UREG_G2], &((*grp)[MC_G2]));
err |= __put_user(regs->u_regs[UREG_G3], &((*grp)[MC_G3]));
err |= __put_user(regs->u_regs[UREG_G4], &((*grp)[MC_G4]));
err |= __put_user(regs->u_regs[UREG_G5], &((*grp)[MC_G5]));
err |= __put_user(regs->u_regs[UREG_G6], &((*grp)[MC_G6]));
err |= __put_user(regs->u_regs[UREG_G7], &((*grp)[MC_G7]));
err |= __put_user(regs->u_regs[UREG_I0], &((*grp)[MC_O0]));
err |= __put_user(regs->u_regs[UREG_I1], &((*grp)[MC_O1]));
err |= __put_user(regs->u_regs[UREG_I2], &((*grp)[MC_O2]));
err |= __put_user(regs->u_regs[UREG_I3], &((*grp)[MC_O3]));
err |= __put_user(regs->u_regs[UREG_I4], &((*grp)[MC_O4]));
err |= __put_user(regs->u_regs[UREG_I5], &((*grp)[MC_O5]));
err |= __put_user(regs->u_regs[UREG_I6], &((*grp)[MC_O6]));
err |= __put_user(regs->u_regs[UREG_I7], &((*grp)[MC_O7]));
err |= __get_user(fp,
(&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[6])));
err |= __get_user(i7,
(&(((struct reg_window __user *)(STACK_BIAS+regs->u_regs[UREG_I6]))->ins[7])));
err |= __put_user(fp, &(mcp->mc_fp));
err |= __put_user(i7, &(mcp->mc_i7));
err |= __put_user(fenab, &(mcp->mc_fpregs.mcfpu_enab));
if (fenab) {
unsigned long *fpregs = current_thread_info()->fpregs;
unsigned long fprs;
fprs = current_thread_info()->fpsaved[0];
if (fprs & FPRS_DL)
err |= copy_to_user(&(mcp->mc_fpregs.mcfpu_fregs), fpregs,
(sizeof(unsigned int) * 32));
if (fprs & FPRS_DU)
err |= copy_to_user(
((unsigned long __user *)&(mcp->mc_fpregs.mcfpu_fregs))+16, fpregs+16,
(sizeof(unsigned int) * 32));
err |= __put_user(current_thread_info()->xfsr[0], &(mcp->mc_fpregs.mcfpu_fsr));
err |= __put_user(current_thread_info()->gsr[0], &(mcp->mc_fpregs.mcfpu_gsr));
err |= __put_user(fprs, &(mcp->mc_fpregs.mcfpu_fprs));
}
if (err)
goto do_sigsegv;
return;
do_sigsegv:
force_sig(SIGSEGV, current);
}
struct rt_signal_frame {
struct sparc_stackf ss;
siginfo_t info;
struct pt_regs regs;
__siginfo_fpu_t __user *fpu_save;
stack_t stack;
sigset_t mask;
__siginfo_fpu_t fpu_state;
};
static long _sigpause_common(old_sigset_t set)
{
set &= _BLOCKABLE;
spin_lock_irq(¤t->sighand->siglock);
current->saved_sigmask = current->blocked;
siginitset(¤t->blocked, set);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
current->state = TASK_INTERRUPTIBLE;
schedule();
set_restore_sigmask();
return -ERESTARTNOHAND;
}
asmlinkage long sys_sigpause(unsigned int set)
{
return _sigpause_common(set);
}
asmlinkage long sys_sigsuspend(old_sigset_t set)
{
return _sigpause_common(set);
}
static inline int
restore_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu)
{
unsigned long *fpregs = current_thread_info()->fpregs;
unsigned long fprs;
int err;
err = __get_user(fprs, &fpu->si_fprs);
fprs_write(0);
regs->tstate &= ~TSTATE_PEF;
if (fprs & FPRS_DL)
err |= copy_from_user(fpregs, &fpu->si_float_regs[0],
(sizeof(unsigned int) * 32));
if (fprs & FPRS_DU)
err |= copy_from_user(fpregs+16, &fpu->si_float_regs[32],
(sizeof(unsigned int) * 32));
err |= __get_user(current_thread_info()->xfsr[0], &fpu->si_fsr);
err |= __get_user(current_thread_info()->gsr[0], &fpu->si_gsr);
current_thread_info()->fpsaved[0] |= fprs;
return err;
}
void do_rt_sigreturn(struct pt_regs *regs)
{
struct rt_signal_frame __user *sf;
unsigned long tpc, tnpc, tstate;
__siginfo_fpu_t __user *fpu_save;
sigset_t set;
int err;
/* Always make any pending restarted system calls return -EINTR */
current_thread_info()->restart_block.fn = do_no_restart_syscall;
synchronize_user_stack ();
sf = (struct rt_signal_frame __user *)
(regs->u_regs [UREG_FP] + STACK_BIAS);
/* 1. Make sure we are not getting garbage from the user */
if (((unsigned long) sf) & 3)
goto segv;
err = get_user(tpc, &sf->regs.tpc);
err |= __get_user(tnpc, &sf->regs.tnpc);
if (test_thread_flag(TIF_32BIT)) {
tpc &= 0xffffffff;
tnpc &= 0xffffffff;
}
err |= ((tpc | tnpc) & 3);
/* 2. Restore the state */
err |= __get_user(regs->y, &sf->regs.y);
err |= __get_user(tstate, &sf->regs.tstate);
err |= copy_from_user(regs->u_regs, sf->regs.u_regs, sizeof(regs->u_regs));
/* User can only change condition codes and %asi in %tstate. */
regs->tstate &= ~(TSTATE_ASI | TSTATE_ICC | TSTATE_XCC);
regs->tstate |= (tstate & (TSTATE_ASI | TSTATE_ICC | TSTATE_XCC));
err |= __get_user(fpu_save, &sf->fpu_save);
if (fpu_save)
err |= restore_fpu_state(regs, &sf->fpu_state);
err |= __copy_from_user(&set, &sf->mask, sizeof(sigset_t));
err |= do_sigaltstack(&sf->stack, NULL, (unsigned long)sf);
if (err)
goto segv;
regs->tpc = tpc;
regs->tnpc = tnpc;
/* Prevent syscall restart. */
pt_regs_clear_syscall(regs);
sigdelsetmask(&set, ~_BLOCKABLE);
spin_lock_irq(¤t->sighand->siglock);
current->blocked = set;
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
return;
segv:
force_sig(SIGSEGV, current);
}
/* Checks if the fp is valid */
static int invalid_frame_pointer(void __user *fp, int fplen)
{
if (((unsigned long) fp) & 15)
return 1;
return 0;
}
static inline int
save_fpu_state(struct pt_regs *regs, __siginfo_fpu_t __user *fpu)
{
unsigned long *fpregs = current_thread_info()->fpregs;
unsigned long fprs;
int err = 0;
fprs = current_thread_info()->fpsaved[0];
if (fprs & FPRS_DL)
err |= copy_to_user(&fpu->si_float_regs[0], fpregs,
(sizeof(unsigned int) * 32));
if (fprs & FPRS_DU)
err |= copy_to_user(&fpu->si_float_regs[32], fpregs+16,
(sizeof(unsigned int) * 32));
err |= __put_user(current_thread_info()->xfsr[0], &fpu->si_fsr);
err |= __put_user(current_thread_info()->gsr[0], &fpu->si_gsr);
err |= __put_user(fprs, &fpu->si_fprs);
return err;
}
static inline void __user *get_sigframe(struct k_sigaction *ka, struct pt_regs *regs, unsigned long framesize)
{
unsigned long sp = regs->u_regs[UREG_FP] + STACK_BIAS;
/*
* If we are on the alternate signal stack and would overflow it, don't.
* Return an always-bogus address instead so we will die with SIGSEGV.
*/
if (on_sig_stack(sp) && !likely(on_sig_stack(sp - framesize)))
return (void __user *) -1L;
/* This is the X/Open sanctioned signal stack switching. */
if (ka->sa.sa_flags & SA_ONSTACK) {
if (sas_ss_flags(sp) == 0)
sp = current->sas_ss_sp + current->sas_ss_size;
}
sp -= framesize;
/* Always align the stack frame. This handles two cases. First,
* sigaltstack need not be mindful of platform specific stack
* alignment. Second, if we took this signal because the stack
* is not aligned properly, we'd like to take the signal cleanly
* and report that.
*/
sp &= ~15UL;
return (void __user *) sp;
}
static inline void
setup_rt_frame(struct k_sigaction *ka, struct pt_regs *regs,
int signo, sigset_t *oldset, siginfo_t *info)
{
struct rt_signal_frame __user *sf;
int sigframe_size, err;
/* 1. Make sure everything is clean */
synchronize_user_stack();
save_and_clear_fpu();
sigframe_size = sizeof(struct rt_signal_frame);
if (!(current_thread_info()->fpsaved[0] & FPRS_FEF))
sigframe_size -= sizeof(__siginfo_fpu_t);
sf = (struct rt_signal_frame __user *)
get_sigframe(ka, regs, sigframe_size);
if (invalid_frame_pointer (sf, sigframe_size))
goto sigill;
if (get_thread_wsaved() != 0)
goto sigill;
/* 2. Save the current process state */
err = copy_to_user(&sf->regs, regs, sizeof (*regs));
if (current_thread_info()->fpsaved[0] & FPRS_FEF) {
err |= save_fpu_state(regs, &sf->fpu_state);
err |= __put_user((u64)&sf->fpu_state, &sf->fpu_save);
} else {
err |= __put_user(0, &sf->fpu_save);
}
/* Setup sigaltstack */
err |= __put_user(current->sas_ss_sp, &sf->stack.ss_sp);
err |= __put_user(sas_ss_flags(regs->u_regs[UREG_FP]), &sf->stack.ss_flags);
err |= __put_user(current->sas_ss_size, &sf->stack.ss_size);
err |= copy_to_user(&sf->mask, oldset, sizeof(sigset_t));
err |= copy_in_user((u64 __user *)sf,
(u64 __user *)(regs->u_regs[UREG_FP]+STACK_BIAS),
sizeof(struct reg_window));
if (info)
err |= copy_siginfo_to_user(&sf->info, info);
else {
err |= __put_user(signo, &sf->info.si_signo);
err |= __put_user(SI_NOINFO, &sf->info.si_code);
}
if (err)
goto sigsegv;
/* 3. signal handler back-trampoline and parameters */
regs->u_regs[UREG_FP] = ((unsigned long) sf) - STACK_BIAS;
regs->u_regs[UREG_I0] = signo;
regs->u_regs[UREG_I1] = (unsigned long) &sf->info;
/* The sigcontext is passed in this way because of how it
* is defined in GLIBC's /usr/include/bits/sigcontext.h
* for sparc64. It includes the 128 bytes of siginfo_t.
*/
regs->u_regs[UREG_I2] = (unsigned long) &sf->info;
/* 5. signal handler */
regs->tpc = (unsigned long) ka->sa.sa_handler;
regs->tnpc = (regs->tpc + 4);
if (test_thread_flag(TIF_32BIT)) {
regs->tpc &= 0xffffffff;
regs->tnpc &= 0xffffffff;
}
/* 4. return to kernel instructions */
regs->u_regs[UREG_I7] = (unsigned long)ka->ka_restorer;
return;
sigill:
do_exit(SIGILL);
sigsegv:
force_sigsegv(signo, current);
}
static inline void handle_signal(unsigned long signr, struct k_sigaction *ka,
siginfo_t *info,
sigset_t *oldset, struct pt_regs *regs)
{
setup_rt_frame(ka, regs, signr, oldset,
(ka->sa.sa_flags & SA_SIGINFO) ? info : NULL);
spin_lock_irq(¤t->sighand->siglock);
sigorsets(¤t->blocked,¤t->blocked,&ka->sa.sa_mask);
if (!(ka->sa.sa_flags & SA_NOMASK))
sigaddset(¤t->blocked,signr);
recalc_sigpending();
spin_unlock_irq(¤t->sighand->siglock);
}
static inline void syscall_restart(unsigned long orig_i0, struct pt_regs *regs,
struct sigaction *sa)
{
switch (regs->u_regs[UREG_I0]) {
case ERESTART_RESTARTBLOCK:
case ERESTARTNOHAND:
no_system_call_restart:
regs->u_regs[UREG_I0] = EINTR;
regs->tstate |= (TSTATE_ICARRY|TSTATE_XCARRY);
break;
case ERESTARTSYS:
if (!(sa->sa_flags & SA_RESTART))
goto no_system_call_restart;
/* fallthrough */
case ERESTARTNOINTR:
regs->u_regs[UREG_I0] = orig_i0;
regs->tpc -= 4;
regs->tnpc -= 4;
}
}
static void do_signal(struct pt_regs *regs, unsigned long orig_i0)
{
struct k_sigaction ka;
int restart_syscall;
sigset_t *oldset;
siginfo_t info;
int signr;
if (pt_regs_is_syscall(regs) &&
(regs->tstate & (TSTATE_XCARRY | TSTATE_ICARRY))) {
restart_syscall = 1;
} else
restart_syscall = 0;
if (current_thread_info()->status & TS_RESTORE_SIGMASK)
oldset = ¤t->saved_sigmask;
else
oldset = ¤t->blocked;
#ifdef CONFIG_COMPAT
if (test_thread_flag(TIF_32BIT)) {
extern void do_signal32(sigset_t *, struct pt_regs *,
int restart_syscall,
unsigned long orig_i0);
do_signal32(oldset, regs, restart_syscall, orig_i0);
return;
}
#endif
signr = get_signal_to_deliver(&info, &ka, regs, NULL);
/* If the debugger messes with the program counter, it clears
* the software "in syscall" bit, directing us to not perform
* a syscall restart.
*/
if (restart_syscall && !pt_regs_is_syscall(regs))
restart_syscall = 0;
if (signr > 0) {
if (restart_syscall)
syscall_restart(orig_i0, regs, &ka.sa);
handle_signal(signr, &ka, &info, oldset, regs);
/* A signal was successfully delivered; the saved
* sigmask will have been stored in the signal frame,
* and will be restored by sigreturn, so we can simply
* clear the TS_RESTORE_SIGMASK flag.
*/
current_thread_info()->status &= ~TS_RESTORE_SIGMASK;
tracehook_signal_handler(signr, &info, &ka, regs, 0);
return;
}
if (restart_syscall &&
(regs->u_regs[UREG_I0] == ERESTARTNOHAND ||
regs->u_regs[UREG_I0] == ERESTARTSYS ||
regs->u_regs[UREG_I0] == ERESTARTNOINTR)) {
/* replay the system call when we are done */
regs->u_regs[UREG_I0] = orig_i0;
regs->tpc -= 4;
regs->tnpc -= 4;
}
if (restart_syscall &&
regs->u_regs[UREG_I0] == ERESTART_RESTARTBLOCK) {
regs->u_regs[UREG_G1] = __NR_restart_syscall;
regs->tpc -= 4;
regs->tnpc -= 4;
}
/* If there's no signal to deliver, we just put the saved sigmask
* back
*/
if (current_thread_info()->status & TS_RESTORE_SIGMASK) {
current_thread_info()->status &= ~TS_RESTORE_SIGMASK;
sigprocmask(SIG_SETMASK, ¤t->saved_sigmask, NULL);
}
}
void do_notify_resume(struct pt_regs *regs, unsigned long orig_i0, unsigned long thread_info_flags)
{
if (thread_info_flags & _TIF_SIGPENDING)
do_signal(regs, orig_i0);
if (thread_info_flags & _TIF_NOTIFY_RESUME) {
clear_thread_flag(TIF_NOTIFY_RESUME);
tracehook_notify_resume(regs);
if (current->replacement_session_keyring)
key_replace_session_keyring();
}
}
| Java |
/*
* * Copyright (C) 2009-2011 Ali <aliov@xfce.org>
* * Copyright (C) 2012-2013 Sean Davis <smd.seandavis@gmail.com>
* * Copyright (C) 2012-2013 Simon Steinbeiß <ochosi@xfce.org
*
* Licensed under the GNU General Public License Version 2
*
* 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
*/
#ifndef __PAROLE_MODULE_H
#define __PAROLE_MODULE_H
#include <glib-object.h>
#include <src/misc/parole.h>
#include "parole-plugin-player.h"
G_BEGIN_DECLS
#define PAROLE_TYPE_PROVIDER_MODULE (parole_provider_module_get_type () )
#define PAROLE_PROVIDER_MODULE(o) (G_TYPE_CHECK_INSTANCE_CAST ((o), PAROLE_TYPE_PROVIDER_MODULE, ParoleProviderModule))
#define PAROLE_PROVIDER_MODULE_CLASS(klass) (G_TYPE_CHECK_CLASS_CAST ((klass), PAROLE_TYPE_PROVIDER_MODULE, ParoleProviderModuleClass))
#define PAROLE_IS_PROVIDER_MODULE(o) (G_TYPE_CHECK_INSTANCE_TYPE ((o), PAROLE_TYPE_PROVIDER_MODULE))
#define PAROLE_IS_PROVIDER_MODULE_CLASS(klass) (G_TYPE_CHECK_CLASS_TYPE ((klass), PAROLE_TYPE_PROVIDER_MODULE))
#define PAROLE_PROVIDER_MODULE_GET_CLASS(o) (G_TYPE_INSTANCE_GET_CLASS((o), PAROLE_TYPE_PROVIDER_MODULE, ParoleProviderModuleClass))
typedef struct _ParoleProviderModuleClass ParoleProviderModuleClass;
typedef struct _ParoleProviderModule ParoleProviderModule;
struct _ParoleProviderModule
{
GTypeModule parent;
GModule *library;
ParolePluginPlayer *player;
GType (*initialize) (ParoleProviderModule *module);
void (*shutdown) (void);
GType provider_type;
gboolean active;
gpointer instance;
gchar *desktop_file;
};
struct _ParoleProviderModuleClass
{
GTypeModuleClass parent_class;
} ;
GType parole_provider_module_get_type (void) G_GNUC_CONST;
ParoleProviderModule *parole_provider_module_new (const gchar *filename,
const gchar *desktop_file);
gboolean parole_provider_module_new_plugin (ParoleProviderModule *module);
void parole_provider_module_free_plugin (ParoleProviderModule *module);
gboolean parole_provider_module_get_is_active (ParoleProviderModule *module);
G_END_DECLS
#endif /* __PAROLE_MODULE_H */
| Java |
/**
* @file cp_campaign.h
* @brief Header file for single player campaign control.
*/
/*
Copyright (C) 2002-2010 UFO: Alien Invasion.
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.
*/
#ifndef CP_CAMPAIGN_H
#define CP_CAMPAIGN_H
extern memPool_t *cp_campaignPool;
struct aircraft_s;
struct installation_s;
struct employee_s;
struct ugv_s;
struct campaign_s;
struct uiNode_s; /**< @todo remove this once the uiNode_t usage is cleaned up */
#define MAX_CAMPAIGNS 16
#define MAX_ASSEMBLIES 16
/** @todo rename this after merging with savegame breakage branch and also change the value to -1 */
#define BYTES_NONE 0xFF
#include "cp_rank.h"
#include "cp_save.h"
#include "cp_parse.h"
#include "cp_event.h"
#include "cp_ufopedia.h"
#include "cp_research.h"
#include "cp_radar.h"
#include "cp_aircraft.h"
#include "cp_base.h"
#include "cp_employee.h"
#include "cp_transfer.h"
#include "cp_nation.h"
#include "cp_installation.h"
#include "cp_produce.h"
#include "cp_uforecovery.h"
#include "cp_airfight.h"
#include "cp_messageoptions.h"
#include "cp_alienbase.h"
#include "cp_market.h"
#include "cp_statistics.h"
/* check for water */
/* blue value is 64 */
#define MapIsWater(color) (color[0] == 0 && color[1] == 0 && color[2] == 64)
/* terrain types */
#define MapIsArctic(color) (color[0] == 128 && color[1] == 255 && color[2] == 255)
#define MapIsDesert(color) (color[0] == 255 && color[1] == 128 && color[2] == 0)
#define MapIsMountain(color) (color[0] == 255 && color[1] == 0 && color[2] == 0)
#define MapIsTropical(color) (color[0] == 128 && color[1] == 128 && color[2] == 255)
#define MapIsGrass(color) (color[0] == 128 && color[1] == 255 && color[2] == 0)
#define MapIsWasted(color) (color[0] == 128 && color[1] == 0 && color[2] == 128)
#define MapIsCold(color) (color[0] == 0 && color[1] == 0 && color[2] == 255)
/* culture types */
#define MapIsWestern(color) (color[0] == 128 && color[1] == 255 && color[2] == 255)
#define MapIsEastern(color) (color[0] == 255 && color[1] == 128 && color[2] == 0)
#define MapIsOriental(color) (color[0] == 255 && color[1] == 0 && color[2] == 0)
#define MapIsAfrican(color) (color[0] == 128 && color[1] == 128 && color[2] == 255)
/* population types */
#define MapIsUrban(color) (color[0] == 128 && color[1] == 255 && color[2] == 255)
#define MapIsSuburban(color) (color[0] == 255 && color[1] == 128 && color[2] == 0)
#define MapIsVillage(color) (color[0] == 255 && color[1] == 0 && color[2] == 0)
#define MapIsRural(color) (color[0] == 128 && color[1] == 128 && color[2] == 255)
#define MapIsNopopulation(color) (color[0] == 128 && color[1] == 255 && color[2] == 0)
/* RASTER enables a better performance for CP_GetRandomPosOnGeoscapeWithParameters set it to 1-6
* the higher the value the better the performance, but the smaller the coverage */
#define RASTER 2
/* nation happiness constants */
#define HAPPINESS_SUBVERSION_LOSS -0.15
#define HAPPINESS_ALIEN_MISSION_LOSS -0.02
#define HAPPINESS_UFO_SALE_GAIN 0.02
#define HAPPINESS_UFO_SALE_LOSS 0.005
#define HAPPINESS_MAX_MISSION_IMPACT 0.07
/* Maximum alien groups per alien team category */
#define MAX_ALIEN_GROUP_PER_CATEGORY 4
/* Maximum alien team category defined in scripts */
#define ALIENCATEGORY_MAX 8
#define BID_FACTOR 0.9
#define MAX_PROJECTILESONGEOSCAPE 32
/**
* @brief The amount of time (in hours) it takes for the interest to increase by 1. Is later affected by difficulty.
*/
#define HOURS_PER_ONE_INTEREST 22
/**
* @brief Determines the interest interval for a single campaign
*/
#define INITIAL_OVERALL_INTEREST 20
#define FINAL_OVERALL_INTEREST 1000
/**
* @brief The length of a single mission spawn cycle
*/
#define DELAY_BETWEEN_MISSION_SPAWNING 4
/**
* @brief The minimum and maximum amount of missions per mission cycle.
* @note some of the missions can be non-occurrence missions.
*/
#define MINIMUM_MISSIONS_PER_CYCLE 5
#define MAXIMUM_MISSIONS_PER_CYCLE 40
/**
* @brief The probability that any new alien mission will be a non-occurrence mission.
*/
#define NON_OCCURRENCE_PROBABILITY 0.65
/** possible map types */
typedef enum mapType_s {
MAPTYPE_TERRAIN,
MAPTYPE_CULTURE,
MAPTYPE_POPULATION,
MAPTYPE_NATIONS,
MAPTYPE_MAX
} mapType_t;
/** @brief possible mission detection status */
typedef enum missionDetectionStatus_s {
MISDET_CANT_BE_DETECTED, /**< Mission can't be seen on geoscape */
MISDET_ALWAYS_DETECTED, /**< Mission is seen on geoscape, whatever it's position */
MISDET_MAY_BE_DETECTED /**< Mission may be seen on geoscape, if a probability test is done */
} missionDetectionStatus_t;
/** possible campaign interest categories: type of missions that aliens can undertake */
typedef enum interestCategory_s {
INTERESTCATEGORY_NONE, /**< No mission */
INTERESTCATEGORY_RECON, /**< Aerial recon mission or ground mission (UFO may or not land) */
INTERESTCATEGORY_TERROR_ATTACK, /**< Terror attack */
INTERESTCATEGORY_BASE_ATTACK, /**< Alien attack a phalanx base */
INTERESTCATEGORY_BUILDING, /**< Alien build a new base or subverse governments */
INTERESTCATEGORY_SUPPLY, /**< Alien supply one of their bases */
INTERESTCATEGORY_XVI, /**< Alien try to spread XVI */
INTERESTCATEGORY_INTERCEPT, /**< Alien try to intercept PHALANX aircraft */
INTERESTCATEGORY_HARVEST, /**< Alien try to harvest */
INTERESTCATEGORY_ALIENBASE, /**< Alien base already built on earth
* @note This is not a mission alien can undertake, but the result of
* INTERESTCATEGORY_BUILDING */
INTERESTCATEGORY_RESCUE,
INTERESTCATEGORY_MAX
} interestCategory_t;
/** possible stage for campaign missions (i.e. possible actions for UFO) */
typedef enum missionStage_s {
STAGE_NOT_ACTIVE, /**< mission did not begin yet */
STAGE_COME_FROM_ORBIT, /**< UFO is arriving */
STAGE_RECON_AIR, /**< Aerial Recon */
STAGE_MISSION_GOTO, /**< Going to a new position */
STAGE_RECON_GROUND, /**< Ground Recon */
STAGE_TERROR_MISSION, /**< Terror mission */
STAGE_BUILD_BASE, /**< Building a base */
STAGE_BASE_ATTACK, /**< Base attack */
STAGE_SUBVERT_GOV, /**< Subvert government */
STAGE_SUPPLY, /**< Supply already existing base */
STAGE_SPREAD_XVI, /**< Spreading XVI Virus */
STAGE_INTERCEPT, /**< UFO attacks any encountered PHALANX aircraft or attack an installation */
STAGE_BASE_DISCOVERED, /**< PHALANX discovered the base */
STAGE_HARVEST, /**< Harvesting */
STAGE_RETURN_TO_ORBIT, /**< UFO is going back to base */
STAGE_OVER /**< Mission is over */
} missionStage_t;
/** @brief alien team group definition.
* @note This is the definition of one groups of aliens (several races) that can
* be used on the same map.
* @sa alienTeamCategory_s
*/
typedef struct alienTeamGroup_s {
int idx; /**< idx of the group in the alien team category */
int categoryIdx; /**< idx of category it's used in */
int minInterest; /**< Minimum interest value this group should be used with. */
int maxInterest; /**< Maximum interest value this group should be used with. */
teamDef_t *alienTeams[MAX_TEAMS_PER_MISSION]; /**< different alien teams available
* that will be used in mission */
int numAlienTeams; /**< Number of alienTeams defined in this group. */
} alienTeamGroup_t;
/** @brief alien team category definition
* @note This is the definition of all groups of aliens that can be used for
* a mission category
* @sa alienTeamGroup_s
*/
typedef struct alienTeamCategory_s {
char id[MAX_VAR]; /**< id of the category */
interestCategory_t missionCategories[INTERESTCATEGORY_MAX]; /**< Mission category that should use this
* alien team Category. */
int numMissionCategories; /**< Number of category using this alien team Category. */
linkedList_t *equipment; /**< Equipment definitions that may be used for this def. */
alienTeamGroup_t alienTeamGroups[MAX_ALIEN_GROUP_PER_CATEGORY]; /**< Different alien group available
* for this category */
int numAlienTeamGroups; /**< Number of alien group defined for this category */
} alienTeamCategory_t;
/** @brief mission definition
* @note A mission is different from a map: a mission is the whole set of actions aliens will carry.
* For example, coming with a UFO on earth, land, explore earth, and leave with UFO
*/
typedef struct mission_s {
int idx; /**< unique id of this mission */
char id[MAX_VAR]; /**< script id */
mapDef_t* mapDef; /**< mapDef used for this mission */
qboolean active; /**< aircraft at place? */
union missionData_t {
base_t *base;
aircraft_t *aircraft;
installation_t *installation;
alienBase_t *alienBase;
} data; /**< may be related to mission type (like pointer to base attacked, or to alien base) */
char location[MAX_VAR]; /**< The name of the ground mission that will appear on geoscape */
interestCategory_t category; /**< The category of the event */
missionStage_t stage; /**< in which stage is this event? */
int initialOverallInterest; /**< The overall interest value when this event has been created */
int initialIndividualInterest; /**< The individual interest value (of type type) when this event has been created */
date_t startDate; /**< Date when the event should start */
date_t finalDate; /**< Date when the event should finish (e.g. for aerial recon)
* if finaleDate.day == 0, then delay is not a limitating factor for next stage */
vec2_t pos; /**< Position of the mission */
aircraft_t *ufo; /**< UFO on geoscape fulfilling the mission (may be NULL) */
qboolean onGeoscape; /**< Should the mission be displayed on geoscape */
qboolean crashed; /**< is UFO crashed ? (only used if mission is spawned from a UFO */
char onwin[MAX_VAR]; /**< trigger command after you've won a battle, @sa CP_ExecuteMissionTrigger */
char onlose[MAX_VAR]; /**< trigger command after you've lost a battle, @sa CP_ExecuteMissionTrigger */
qboolean posAssigned; /**< is the position of this mission already set? */
} mission_t;
/**
* @brief iterates through missions
*/
#define MIS_Foreach(var) LIST_Foreach(ccs.missions, mission_t, var)
/** battlescape parameters that were used */
typedef struct battleParam_s {
mission_t *mission;
alienTeamGroup_t *alienTeamGroup; /**< Races of aliens present in battle */
char *param; /**< in case of a random map assembly we can't use the param from mapDef - because
* this is global for the mapDef - but we need a local mission param */
char alienEquipment[MAX_VAR]; /**< Equipment of alien team */
char civTeam[MAX_VAR]; /**< Type of civilian (European, ...) */
qboolean day; /**< Mission is played during day */
const char *zoneType; /**< Terrain type (used for texture replacement in some missions (base, ufocrash)) */
int aliens, civilians; /**< number of aliens and civilians in that particular mission */
struct nation_s *nation; /**< nation where the mission takes place */
float probability;
} battleParam_t;
/** @brief Structure with mission info needed to create results summary at menu won. */
typedef struct missionResults_s {
qboolean won;
qboolean recovery; /**< @c true if player secured a UFO (landed or crashed). */
qboolean crashsite; /**< @c true if secured UFO was crashed one. */
ufoType_t ufotype; /**< Type of UFO secured during the mission. */
float ufoCondition; /**< How much the UFO is damaged */
float winProbability; /**< the win probability that was calculated for auto missions */
int itemTypes; /**< Types of items gathered from a mission. */
int itemAmount; /**< Amount of items (all) gathered from a mission. */
int aliensKilled;
int aliensStunned;
int aliensSurvived;
int ownKilled;
int ownStunned;
int ownKilledFriendlyFire;
int ownSurvived;
int civiliansKilled;
int civiliansKilledFriendlyFire;
int civiliansSurvived;
} missionResults_t;
/** salary values for a campaign */
typedef struct salary_s {
int base[MAX_EMPL];
int rankBonus[MAX_EMPL];
int admin[MAX_EMPL];
int aircraftFactor;
int aircraftDivisor;
int baseUpkeep;
int adminInitial;
float debtInterest;
} salary_t;
/** campaign definition */
typedef struct campaign_s {
int idx; /**< own index in global campaign array */
char id[MAX_VAR]; /**< id of the campaign */
char name[MAX_VAR]; /**< name of the campaign */
int team; /**< what team can play this campaign */
char researched[MAX_VAR]; /**< name of the researched tech list to use on campaign start */
char soldierEquipment[MAX_VAR]; /**< name of the equipment list that is used to equip soldiers on crafts that are added to the first base */
char equipment[MAX_VAR]; /**< name of the equipment list to use on campaign start */
char market[MAX_VAR]; /**< name of the market list containing initial items on market */
char asymptoticMarket[MAX_VAR]; /**< name of the market list containing items on market at the end of the game */
const equipDef_t *marketDef; /**< market definition for this campaign (how many items on the market) containing initial items */
const equipDef_t *asymptoticMarketDef; /**< market definition for this campaign (how many items on the market) containing finale items */
char text[MAX_VAR]; /**< placeholder for gettext stuff */
char map[MAX_VAR]; /**< geoscape map */
int soldiers; /**< start with x soldiers */
int scientists; /**< start with x scientists */
int workers; /**< start with x workers */
int pilots; /**< start with x pilots */
int ugvs; /**< start with x ugvs (robots) */
int credits; /**< start with x credits */
int num;
signed int difficulty; /**< difficulty level -4 - 4 */
float minhappiness; /**< minimum value of mean happiness before the game is lost */
int negativeCreditsUntilLost; /**< bankrupt - negative credits until you've lost the game */
int maxAllowedXVIRateUntilLost; /**< 0 - 100 - the average rate of XVI over all nations before you've lost the game */
qboolean visible; /**< visible in campaign menu? */
date_t date; /**< starting date for this campaign */
int basecost; /**< base building cost for empty base */
char firstBaseTemplate[MAX_VAR]; /**< template to use for setting up the first base */
qboolean finished;
const campaignEvents_t *events;
salary_t salaries;
} campaign_t;
int CP_GetSalaryBaseEmployee(const salary_t *salary, employeeType_t type);
int CP_GetSalaryAdminEmployee(const salary_t *salary, employeeType_t type);
int CP_GetSalaryRankBonusEmployee(const salary_t *salary, employeeType_t type);
int CP_GetSalaryAdministrative(const salary_t *salary);
int CP_GetSalaryUpKeepBase(const salary_t *salary, const base_t *base);
/** possible geoscape actions */
typedef enum mapAction_s {
MA_NONE,
MA_NEWBASE, /**< build a new base */
MA_NEWINSTALLATION, /**< build a new installation */
MA_INTERCEPT, /**< intercept */
MA_BASEATTACK, /**< base attacking */
MA_UFORADAR /**< ufos are in our radar */
} mapAction_t;
/**
* @brief client campaign structure
* @sa csi_t
*/
typedef struct ccs_s {
equipDef_t eMission;
market_t eMarket; /**< Prices, evolution and number of items on market */
linkedList_t *missions; /**< Missions spawned (visible on geoscape or not) */
battleParam_t battleParameters; /**< Structure used to remember every parameter used during last battle */
int lastInterestIncreaseDelay; /**< How many hours since last increase of alien overall interest */
int overallInterest; /**< overall interest of aliens: how far is the player in the campaign */
int interest[INTERESTCATEGORY_MAX]; /**< interest of aliens: determine which actions aliens will undertake */
int lastMissionSpawnedDelay; /**< How many days since last mission has been spawned */
vec2_t mapPos; /**< geoscape map position (from the menu node) */
vec2_t mapSize; /**< geoscape map size (from the menu node) */
int credits; /**< actual credits amount */
int civiliansKilled; /**< how many civilians were killed already */
int aliensKilled; /**< how many aliens were killed already */
date_t date; /**< current date */
qboolean XVIShowMap; /**< means that PHALANX has a map of XVI - @see CP_IsXVIResearched */
qboolean breathingMailSent; /**< status flag indicating that mail about died aliens due to missing breathing tech was sent */
float timer;
vec3_t angles; /**< 3d geoscape rotation */
vec2_t center; /**< latitude and longitude of the point we're looking at on earth */
float zoom; /**< zoom used when looking at earth */
/* Smoothing variables */
qboolean smoothRotation; /**< @c true if the rotation of 3D geoscape must me smooth */
vec3_t smoothFinalGlobeAngle; /**< value of final ccs.angles for a smooth change of angle (see MAP_CenterOnPoint)*/
vec2_t smoothFinal2DGeoscapeCenter; /**< value of ccs.center for a smooth change of position (see MAP_CenterOnPoint) */
float smoothDeltaLength; /**< angle/position difference that we need to change when smoothing */
float smoothFinalZoom; /**< value of final ccs.zoom for a smooth change of angle (see MAP_CenterOnPoint)*/
float smoothDeltaZoom; /**< zoom difference that we need to change when smoothing */
float curZoomSpeed; /**< The current zooming speed. Used for smooth zooming. */
float curRotationSpeed; /**< The current rotation speed. Used for smooth rotating.*/
struct {
mission_t *selectedMission; /**< Currently selected mission on geoscape */
aircraft_t *selectedAircraft; /**< Currently selected aircraft on geoscape */
aircraft_t *selectedUFO; /**< Currently selected UFO on geoscape */
aircraft_t *interceptAircraft; /**< selected aircraft for interceptions */
aircraft_t *missionAircraft; /**< aircraft pointer for mission handling */
} geoscape;
/* == misc == */
/* MA_NEWBASE, MA_INTERCEPT, MA_BASEATTACK, ... */
mapAction_t mapAction;
/** @todo move into the base node extra data */
/* BA_NEWBUILDING ... */
baseAction_t baseAction;
/* how fast the game is running */
int gameTimeScale;
int gameLapse;
/* already paid in this month? */
qboolean paid;
/** Coordinates to place the new base at (long, lat) */
vec2_t newBasePos;
/* == employees == */
/* A list of all phalanx employees (soldiers, scientists, workers, etc...) */
linkedList_t *employees[MAX_EMPL];
/* == technologies == */
/* A list of all research-topics resp. the research-tree. */
technology_t technologies[MAX_TECHNOLOGIES];
/* Total number of technologies. */
int numTechnologies;
/* == bases == */
/* A list of _all_ bases ... even unbuilt ones. */
base_t bases[MAX_BASES];
/* Total number of built bases (how many are enabled). */
int numBases;
/* a list of all templates for building bases */
baseTemplate_t baseTemplates[MAX_BASETEMPLATES];
int numBaseTemplates;
/* == aircraft == */
linkedList_t *aircraft;
/* == Alien bases == */
linkedList_t *alienBases;
/* == Nations == */
nation_t nations[MAX_NATIONS];
int numNations;
/* == Cities == */
linkedList_t *cities;
int numCities;
/* Projectiles on geoscape (during fights) */
aircraftProjectile_t projectiles[MAX_PROJECTILESONGEOSCAPE];
int numProjectiles;
/* == Transfers == */
linkedList_t* transfers;
/* UFO components. */
int numComponents;
components_t components[MAX_ASSEMBLIES];
/* == stored UFOs == */
linkedList_t *storedUFOs;
/* Alien Team Definitions. */
teamDef_t *alienTeams[MAX_TEAMDEFS];
int numAliensTD;
/* Alien Team Package used during battle */
alienTeamCategory_t alienCategories[ALIENCATEGORY_MAX]; /**< different alien team available
* that will be used in mission */
int numAlienCategories; /** number of alien team categories defined */
/* == ufopedia == */
/* A list of all UFOpaedia chapters. */
pediaChapter_t upChapters[MAX_PEDIACHAPTERS];
/* Total number of UFOpaedia chapters */
int numChapters;
int numUnreadMails; /**< only for faster access (don't cycle all techs every frame) */
eventMail_t eventMails[MAX_EVENTMAILS]; /**< holds all event mails (cl_event.c) */
int numEventMails; /**< how many eventmails (script-id: mail) parsed */
campaignEvents_t campaignEvents[MAX_CAMPAIGNS]; /**< holds all campaign events (cl_event.c) */
int numCampaignEventDefinitions; /**< how many event definitions (script-id: events) parsed */
/* == buildings in bases == */
/* A list of all possible unique buildings. */
building_t buildingTemplates[MAX_BUILDINGS];
int numBuildingTemplates;
/* A list of the building-list per base. (new buildings in a base get copied from buildingTypes) */
building_t buildings[MAX_BASES][MAX_BUILDINGS];
/* Total number of buildings per base. */
int numBuildings[MAX_BASES];
/* == installations == */
/* A template for each possible installation with configurable values */
installationTemplate_t installationTemplates[MAX_INSTALLATION_TEMPLATES];
int numInstallationTemplates;
/* A list of _all_ installations ... even unbuilt ones. */
installation_t installations[MAX_INSTALLATIONS];
/* Total number of built installations (how many are enabled). */
int numInstallations;
/* UFOs on geoscape */
aircraft_t ufos[MAX_UFOONGEOSCAPE];
int numUFOs; /**< The current amount of UFOS on the geoscape. */
/* message categories */
msgCategory_t messageCategories[MAX_MESSAGECATEGORIES];
int numMsgCategories;
/* entries for message categories */
msgCategoryEntry_t msgCategoryEntries[NT_NUM_NOTIFYTYPE + MAX_MESSAGECATEGORIES];
int numMsgCategoryEntries;
/* == Ranks == */
/* Global list of all ranks defined in medals.ufo. */
rank_t ranks[MAX_RANKS];
/* The number of entries in the list above. */
int numRanks;
/* cache for techdef technologies */
technology_t *teamDefTechs[MAX_TEAMDEFS];
/* cache for item technologies */
technology_t *objDefTechs[MAX_OBJDEFS];
campaign_t *curCampaign; /**< Current running campaign */
stats_t campaignStats;
missionResults_t missionResults;
campaign_t campaigns[MAX_CAMPAIGNS];
int numCampaigns;
aircraft_t aircraftTemplates[MAX_AIRCRAFT]; /**< Available aircraft types/templates/samples. */
int numAircraftTemplates; /**< Number of aircraft templates. */
} ccs_t;
/**
* @brief Human readable time information in the game.
* @note Use this on runtime - please avoid for structs that get saved.
* @sa date_t For storage & network transmitting (engine only).
* @sa CL_DateConvertLong
*/
typedef struct dateLong_s {
short year; /**< Year in yyyy notation. */
byte month; /**< Number of month (starting with 1). */
byte day; /**< Number of day (starting with 1). */
byte hour; /**< Hour of the day. @todo check what number-range this gives) */
byte min; /**< Minute of the hour. */
byte sec; /**< Second of the minute. */
} dateLong_t;
typedef struct {
int x, y;
} screenPoint_t;
extern ccs_t ccs;
extern const int DETECTION_INTERVAL;
extern cvar_t *cp_campaign;
extern cvar_t *cp_missiontest;
extern cvar_t *cp_start_employees;
#define MAX_CREDITS 10000000
/* Campaign functions */
void CP_InitStartup(void);
campaign_t* CL_GetCampaign(const char *name);
void CP_CampaignInit(campaign_t *campaign, qboolean load);
void CL_ReadSinglePlayerData(void);
void CL_ReadCampaignData(const campaign_t *campaign);
qboolean CP_IsRunning(void);
void CL_CampaignRun(campaign_t *campaign);
void CP_CheckLostCondition(const campaign_t *campaign);
void CP_EndCampaign(qboolean won);
void CP_Shutdown(void);
void CL_ResetSinglePlayerData(void);
/* Date functions */
void CL_DateConvertLong(const date_t * date, dateLong_t * dateLong);
const char* CL_SecondConvert(int second);
/* Mission related functions */
int CP_CountMissionOnGeoscape(void);
void CP_UpdateMissionVisibleOnGeoscape(void);
int CP_TerrorMissionAvailableUFOs(const mission_t const *mission, ufoType_t *ufoTypes);
qboolean AIR_SendAircraftToMission(aircraft_t *aircraft, mission_t *mission);
void AIR_AircraftsNotifyMissionRemoved(const mission_t *mission);
void CP_UFOProceedMission(const campaign_t* campaign, aircraft_t *ufocraft);
void CP_InitMissionResults(qboolean won, const missionResults_t *results);
mission_t *CP_CreateNewMission(interestCategory_t category, qboolean beginNow);
qboolean CP_ChooseMap(mission_t *mission, const vec2_t pos);
void CP_StartSelectedMission(void);
void CL_HandleNationData(float minHappiness, qboolean won, mission_t * mis, const nation_t *nation, const missionResults_t *results);
void CL_UpdateCharacterStats(const base_t *base, const aircraft_t *aircraft);
/* Credits management */
qboolean CP_CheckCredits (int costs);
void CL_UpdateCredits(int credits);
/* Other functions */
void CP_ParseCharacterData(struct dbuffer *msg);
qboolean CP_CheckNextStageDestination(const campaign_t* campaign, aircraft_t *ufo);
aircraft_t* AIR_NewAircraft(base_t * base, const aircraft_t *aircraftTemplate);
void CP_GetRandomPosOnGeoscape(vec2_t pos, qboolean noWater);
qboolean CP_GetRandomPosOnGeoscapeWithParameters(vec2_t pos, const linkedList_t *terrainTypes, const linkedList_t *cultureTypes, const linkedList_t *populationTypes, const linkedList_t *nations);
void CL_GameAutoGo(mission_t *mission, aircraft_t *aircraft, const campaign_t *campaign, const battleParam_t *battleParameters, missionResults_t *results);
qboolean CP_OnGeoscape(void);
#endif /* CP_CAMPAIGN_H */
| Java |
StealDB
=======
Get any database file - an app to demonstrate how easy it is
maliciously upload and decrypt an android db store
fetch these extensions in /WhatsApp/Databases/*.db
the apk has one hello world activity and the uploading is done by a background
worker. The api endpoint is setup in flask
## Whatsapp DB
- msgstore.db.crypt
- msgstore.db
| Java |
/*
* symlink.c
*
* Symlink methods.
*
* Author: Steve Longerbeam <stevel@mvista.com, or source@mvista.com>
*
* 2003 (c) MontaVista Software, Inc.
* Copyright 2003 Sony Corporation
* Copyright 2003 Matsushita Electric Industrial Co., Ltd.
*
* This software is being distributed under the terms of the GNU General Public
* License version 2. Some or all of the technology encompassed by this
* software may be subject to one or more patents pending as of the date of
* this notice. No additional patent license will be required for GPL
* implementations of the technology. If you want to create a non-GPL
* implementation of the technology encompassed by this software, please
* contact legal@mvista.com for details including licensing terms and fees.
*
* This file is licensed under the terms of the GNU General Public License
* version 2. This program is licensed "as is" without any warranty of any
* kind, whether express or implied.
*/
#include <linux/fs.h>
#include <linux/pram_fs.h>
int pram_block_symlink(struct inode *inode, const char *symname, int len)
{
struct super_block * sb = inode->i_sb;
pram_off_t block;
char* blockp;
unsigned long flags;
int err;
err = pram_alloc_blocks (inode, 0, 1);
if (err)
return err;
block = pram_find_data_block(inode, 0);
blockp = pram_get_block(sb, block);
pram_lock_block(sb, blockp);
memcpy(blockp, symname, len);
blockp[len] = '\0';
pram_unlock_block(sb, blockp);
return 0;
}
static int pram_readlink(struct dentry *dentry, char *buffer, int buflen)
{
struct inode * inode = dentry->d_inode;
struct super_block * sb = inode->i_sb;
pram_off_t block;
char* blockp;
block = pram_find_data_block(inode, 0);
blockp = pram_get_block(sb, block);
return vfs_readlink(dentry, buffer, buflen, blockp);
}
static int pram_follow_link(struct dentry *dentry, struct nameidata *nd)
{
struct inode * inode = dentry->d_inode;
struct super_block * sb = inode->i_sb;
pram_off_t block;
char* blockp;
block = pram_find_data_block(inode, 0);
blockp = pram_get_block(sb, block);
return vfs_follow_link(nd, blockp);
}
struct inode_operations pram_symlink_inode_operations = {
readlink: pram_readlink,
follow_link: pram_follow_link,
};
| Java |
.pane-bundle-videos {
background: white;
}
.pane-bundle-videos .field-collection-item-field-video {
border-bottom: 1px lightgray solid;
}
.pane-bundle-videos .field-name-field-link-single {
border-top: 10px #231f20 solid;
}
.pane-bundle-videos {
-moz-box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px;
-webkit-box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px;
box-shadow: rgba(0, 0, 0, 0.1) 0 1px 0, rgba(0, 0, 0, 0.1) 0 0 0 1px;
margin: 1px;
}
.pane-bundle-videos {
padding: 0 26px;
}
.pane-bundle-videos .field-name-field-link-single {
color: #231f20;
font-family: "NewsGothicBT-Demi", "Avant Garde", "Futura", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 18px;
font-weight: normal;
line-height: 1.3;
padding-top: 12px;
}
.pane-bundle-videos .field-name-field-link-single a {
color: #231f20;
}
.pane-bundle-videos .field-collection-item-field-video {
overflow: hidden;
*zoom: 1;
padding: 22px 26px;
margin: 0 -26px;
}
.pane-bundle-videos .field-collection-item-field-video:last-of-type {
border-bottom: 0;
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-title {
display: inline;
font-size: 22px;
font-weight: bold;
line-height: 1.3;
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-title:hover {
text-decoration: underline;
}
.wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title {
max-width: 65%;
}
@media (min-width: 35.5625em) and (max-width: 44.375em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title {
max-width: 100%;
}
}
@media (max-width: 22.8125em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title {
max-width: 100%;
}
}
@media (min-width: 20.0625em) and (max-width: 35.5em) {
.narrow-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-title {
max-width: 65%;
}
}
.pane-bundle-videos .field-collection-item-field-video .video-channeltitle,
.pane-bundle-videos .field-collection-item-field-video .video-viewcount {
font-size: 14px;
line-height: 1.2;
}
.wide-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .wide-view
.pane-bundle-videos .field-collection-item-field-video .video-viewcount {
max-width: 65%;
}
@media (min-width: 35.5625em) and (max-width: 44.375em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .wide-view
.pane-bundle-videos .field-collection-item-field-video .video-viewcount {
max-width: 100%;
}
}
@media (max-width: 22.8125em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .wide-view
.pane-bundle-videos .field-collection-item-field-video .video-viewcount {
max-width: 100%;
}
}
@media (min-width: 20.0625em) and (max-width: 35.5em) {
.narrow-view .pane-bundle-videos .field-collection-item-field-video .video-channeltitle, .narrow-view
.pane-bundle-videos .field-collection-item-field-video .video-viewcount {
max-width: 65%;
}
}
.pane-bundle-videos .field-collection-item-field-video .video-channeltitle {
margin-top: 8px;
}
.pane-bundle-videos .field-collection-item-field-video .video-channeltitle span {
margin-right: 5px;
}
.pane-bundle-videos .field-collection-item-field-video .video-viewcount {
margin-bottom: 8px;
}
.pane-bundle-videos .field-collection-item-field-video .video-viewcount span {
margin-left: 5px;
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-body {
font-size: 16px;
line-height: 1.3;
}
.wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body {
max-width: 65%;
}
@media (min-width: 35.5625em) and (max-width: 44.375em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body {
max-width: 100%;
}
}
@media (max-width: 22.8125em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body {
max-width: 100%;
}
}
@media (min-width: 20.0625em) and (max-width: 35.5em) {
.narrow-view .pane-bundle-videos .field-collection-item-field-video .field-name-field-body {
max-width: 65%;
}
}
.pane-bundle-videos .field-collection-item-field-video .group-wrapper-video {
position: relative;
}
.wide-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video {
float: right;
margin-left: 10px;
max-width: 125px;
}
@media (min-width: 35.5625em) and (max-width: 44.375em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video {
float: none;
margin-bottom: 12px;
margin-left: 0;
max-width: 216px;
}
}
@media (max-width: 22.8125em) {
.wide-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video {
float: none;
margin-bottom: 12px;
margin-left: 0;
max-width: 216px;
}
}
.narrow-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video {
margin-bottom: 12px;
max-width: 216px;
}
@media (min-width: 20.0625em) and (max-width: 35.5em) {
.narrow-view .pane-bundle-videos .field-collection-item-field-video .group-wrapper-video {
float: right;
margin-left: 10px;
max-width: 125px;
}
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:before {
content: "\f10c";
display: inline;
speak: none;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-transform: none;
line-height: 1;
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'icons';
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:before {
font-size: 51px;
margin-top: -30px;
margin-left: -22px;
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:after {
content: "\f11a";
display: inline;
speak: none;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-transform: none;
line-height: 1;
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'icons';
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .gsb-image-video-popup a.fancybox:after {
font-size: 16px;
margin-top: -12px;
margin-left: -4px;
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:before {
content: "\f10c";
display: inline;
speak: none;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-transform: none;
line-height: 1;
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'icons';
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:before {
font-size: 51px;
margin-top: -30px;
margin-left: -22px;
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:after {
content: "\f11a";
display: inline;
speak: none;
text-rendering: optimizeLegibility;
-moz-osx-font-smoothing: grayscale;
-webkit-font-smoothing: antialiased;
font-smoothing: antialiased;
text-transform: none;
line-height: 1;
font-style: normal;
font-variant: normal;
font-weight: normal;
font-family: 'icons';
}
.pane-bundle-videos .field-collection-item-field-video .field-name-field-video-url .field-type-file .gsb-responsive-preview .file-video a:after {
font-size: 16px;
margin-top: -12px;
margin-left: -4px;
}
.pane-bundle-videos .field-collection-item-field-video .video-duration {
background: #231f20;
color: white;
display: inline-block;
float: right;
font-size: 11px;
font-weight: bold;
line-height: 1.2;
padding: 4px;
position: absolute;
right: 0;
bottom: 2px;
}
| Java |
--犬タウルス
function c91754175.initial_effect(c)
--atk up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(91754175,0))
e1:SetCategory(CATEGORY_TOGRAVE+CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c91754175.condition)
e1:SetTarget(c91754175.target)
e1:SetOperation(c91754175.operation)
c:RegisterEffect(e1)
end
function c91754175.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttackTarget()~=nil
end
function c91754175.tgfilter(c)
return c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR+RACE_WINDBEAST) and c:IsAbleToGrave()
end
function c91754175.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c91754175.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c91754175.tgfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil)
local c=e:GetHandler()
local tc=g:GetFirst()
if tc and Duel.SendtoGrave(tc,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_GRAVE)
and c:IsRelateToBattle() and c:IsFaceup() then
local lv=tc:GetLevel()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(lv*100)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
c:RegisterEffect(e1)
end
end
| Java |
CREATE TABLE IF NOT EXISTS `#__formmaker_sessions` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`form_id` int(20) NOT NULL,
`group_id` int(20) NOT NULL,
`ip` varchar(20) NOT NULL,
`ord_date` datetime NOT NULL,
`ord_last_modified` datetime NOT NULL,
`status` varchar(50) NOT NULL,
`full_name` varchar(100) NOT NULL,
`email` varchar(50) NOT NULL,
`phone` varchar(50) NOT NULL,
`mobile_phone` varchar(255) NOT NULL,
`fax` varchar(255) NOT NULL,
`address` varchar(300) NOT NULL,
`paypal_info` text NOT NULL,
`without_paypal_info` text NOT NULL,
`ipn` varchar(20) NOT NULL,
`checkout_method` varchar(20) NOT NULL,
`tax` float NOT NULL,
`shipping` float NOT NULL,
`shipping_type` varchar(200) NOT NULL,
`read` int(11) NOT NULL,
`total` float NOT NULL,
`currency` varchar(24) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
| Java |
/*
* ux_text.c - Unix interface, text functions
*
* This file is part of Frotz.
*
* Frotz 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.
*
* Frotz 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
*/
#define __UNIX_PORT_FILE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef USE_NCURSES_H
#include <ncurses.h>
#else
#include <curses.h>
#endif
#include "ux_frotz.h"
/* When color_enabled is FALSE, we still minimally keep track of colors by
* setting current_color to A_REVERSE if the game reads the default
* foreground and background colors and swaps them. If we don't do this,
* Strange Results can happen when playing certain V6 games when
* color_enabled is FALSE.
*/
bool color_enabled = FALSE;
/* int current_color = 0; */
static char latin1_to_ascii[] =
" ! c L >o<Y | S '' C a << not- R _ "
"^0 +/-^2 ^3 ' my P . , ^1 o >> 1/41/23/4? "
"A A A A Ae A AE C E E E E I I I I "
"Th N O O O O Oe * O U U U Ue Y Th ss "
"a a a a ae a ae c e e e e i i i i "
"th n o o o o oe : o u u u ue y th y ";
/*
* os_font_data
*
* Return true if the given font is available. The font can be
*
* TEXT_FONT
* PICTURE_FONT
* GRAPHICS_FONT
* FIXED_WIDTH_FONT
*
* The font size should be stored in "height" and "width". If
* the given font is unavailable then these values must _not_
* be changed.
*
*/
int os_font_data (int font, int *height, int *width)
{
if (font == TEXT_FONT) {
*height = 1; *width = 1; return 1; /* Truth in advertising */
}
return 0;
}/* os_font_data */
#ifdef COLOR_SUPPORT
/*
* unix_convert
*
* Converts frotz's (and Infocom's) color values to ncurses color values.
*
*/
static int unix_convert(int color)
{
switch(color) {
case BLACK_COLOUR: return COLOR_BLACK;
case RED_COLOUR: return COLOR_RED;
case GREEN_COLOUR: return COLOR_GREEN;
case YELLOW_COLOUR: return COLOR_YELLOW;
case BLUE_COLOUR: return COLOR_BLUE;
case MAGENTA_COLOUR: return COLOR_MAGENTA;
case CYAN_COLOUR: return COLOR_CYAN;
case WHITE_COLOUR: return COLOR_WHITE;
}
return 0;
}
#endif
/*
* os_set_colour
*
* Set the foreground and background colours which can be:
*
* DEFAULT_COLOUR
* BLACK_COLOUR
* RED_COLOUR
* GREEN_COLOUR
* YELLOW_COLOUR
* BLUE_COLOUR
* MAGENTA_COLOUR
* CYAN_COLOUR
* WHITE_COLOUR
*
* MS-DOS 320 columns MCGA mode only:
*
* GREY_COLOUR
*
* Amiga only:
*
* LIGHTGREY_COLOUR
* MEDIUMGREY_COLOUR
* DARKGREY_COLOUR
*
* There may be more colours in the range from 16 to 255; see the
* remarks on os_peek_colour.
*
*/
void os_set_colour (int new_foreground, int new_background)
{
if (new_foreground == 1) new_foreground = z_header.h_default_foreground;
if (new_background == 1) new_background = z_header.h_default_background;
if (u_setup.color_enabled) {
#ifdef COLOR_SUPPORT
static int colorspace[10][10];
static int n_colors = 0;
if (!colorspace[new_foreground][new_background]) {
init_pair(++n_colors, unix_convert(new_foreground),
unix_convert(new_background));
colorspace[new_foreground][new_background] = n_colors;
}
u_setup.current_color = COLOR_PAIR(colorspace[new_foreground][new_background]);
#endif
} else
u_setup.current_color = (((new_foreground == z_header.h_default_background)
&& (new_background == z_header.h_default_foreground))
? A_REVERSE : 0);
os_set_text_style(u_setup.current_text_style);
}/* os_set_colour */
/*
* os_set_text_style
*
* Set the current text style. Following flags can be set:
*
* REVERSE_STYLE
* BOLDFACE_STYLE
* EMPHASIS_STYLE (aka underline aka italics)
* FIXED_WIDTH_STYLE
*
*/
void os_set_text_style (int new_style)
{
int temp = 0;
u_setup.current_text_style = new_style;
if (new_style & REVERSE_STYLE) temp |= A_REVERSE;
if (new_style & BOLDFACE_STYLE) temp |= A_BOLD;
if (new_style & EMPHASIS_STYLE) temp |= A_UNDERLINE;
attrset(temp ^ u_setup.current_color);
}/* os_set_text_style */
/*
* os_set_font
*
* Set the font for text output. The interpreter takes care not to
* choose fonts which aren't supported by the interface.
*
*/
void os_set_font (int new_font)
{
/* Not implemented */
}/* os_set_font */
/*
* os_display_char
*
* Display a character of the current font using the current colours and
* text style. The cursor moves to the next position. Printable codes are
* all ASCII values from 32 to 126, ISO Latin-1 characters from 160 to
* 255, ZC_GAP (gap between two sentences) and ZC_INDENT (paragraph
* indentation). The screen should not be scrolled after printing to the
* bottom right corner.
*
*/
void os_display_char (zchar c)
{
if (c >= ZC_LATIN1_MIN) {
if (u_setup.plain_ascii) {
char *ptr = latin1_to_ascii + 3 * (c - ZC_LATIN1_MIN);
char c1 = *ptr++;
char c2 = *ptr++;
char c3 = *ptr++;
addch(c1);
if (c2 != ' ')
addch(c2);
if (c3 != ' ')
addch(c3);
} else
addch(c);
return;
}
if (c >= ZC_ASCII_MIN && c <= ZC_ASCII_MAX) {
addch(c);
return;
}
if (c == ZC_INDENT) {
addch(' '); addch(' '); addch(' ');
return;
}
if (c == ZC_GAP) {
addch(' '); addch(' ');
return;
}
}/* os_display_char */
/*
* os_display_string
*
* Pass a string of characters to os_display_char.
*
*/
void os_display_string (const zchar *s)
{
zchar c;
while ((c = (unsigned char) *s++) != 0)
/* Is this superfluous given it's also done in screen_word()? */
if (c == ZC_NEW_FONT || c == ZC_NEW_STYLE) {
int arg = (unsigned char) *s++;
if (c == ZC_NEW_FONT)
os_set_font (arg);
if (c == ZC_NEW_STYLE)
os_set_text_style (arg);
} else os_display_char (c);
}/* os_display_string */
/*
* os_char_width
*
* Return the width of the character in screen units.
*
*/
int os_char_width (zchar c)
{
if (c >= ZC_LATIN1_MIN && u_setup.plain_ascii) {
int width = 0;
const char *ptr = latin1_to_ascii + 3 * (c - ZC_LATIN1_MIN);
char c1 = *ptr++;
char c2 = *ptr++;
char c3 = *ptr++;
/* Why, oh, why did you declare variables that way??? */
if (c1 == c1) /* let's avoid confusing the compiler (and me) */
width++;
if (c2 != ' ')
width++;
if (c3 != ' ')
width++;
return width;
}
return 1;
}/* os_char_width*/
/*
* os_string_width
*
* Calculate the length of a word in screen units. Apart from letters,
* the word may contain special codes:
*
* NEW_STYLE - next character is a new text style
* NEW_FONT - next character is a new font
*
*/
int os_string_width (const zchar *s)
{
int width = 0;
zchar c;
while ((c = *s++) != 0)
if (c == ZC_NEW_STYLE || c == ZC_NEW_FONT) {
s++;
/* No effect */
} else width += os_char_width(c);
return width;
}/* os_string_width */
/*
* os_set_cursor
*
* Place the text cursor at the given coordinates. Top left is (1,1).
*
*/
void os_set_cursor (int y, int x)
{
/* Curses thinks the top left is (0,0) */
move(--y, --x);
}/* os_set_cursor */
/*
* os_more_prompt
*
* Display a MORE prompt, wait for a keypress and remove the MORE
* prompt from the screen.
*
*/
void os_more_prompt (void)
{
int saved_style, saved_x, saved_y;
/* Save some useful information */
saved_style = u_setup.current_text_style;
getyx(stdscr, saved_y, saved_x);
os_set_text_style(0);
addstr("[MORE]");
os_read_key(0, TRUE);
move(saved_y, saved_x);
addstr(" ");
move(saved_y, saved_x);
os_set_text_style(saved_style);
}/* os_more_prompt */
| Java |
.ds-users-list .modal-body input:nth-child(2), .ds-permission-list .modal-body input:nth-child(2), .ds-group-list .modal-body input:nth-child(2) {
margin-bottom: 1em; }
.ds-users-list tbody tr, .ds-permission-list tbody tr, .ds-group-list tbody tr {
cursor: pointer; }
.ds-users-list #header-area, .ds-permission-list #header-area, .ds-group-list #header-area {
padding: 0.1em 0 1em 0; }
.ds-users-list #header-area h3, .ds-permission-list #header-area h3, .ds-group-list #header-area h3 {
margin-top: 0.25em;
float: left; }
.ds-users-list #header-area a, .ds-permission-list #header-area a, .ds-group-list #header-area a {
text-decoration: none;
cursor: pointer;
float: right;
margin-top: 1em; }
.ds-users-list #alert-area, .ds-permission-list #alert-area, .ds-group-list #alert-area {
padding: 0; }
.ds-logs-view table {
white-space: nowrap; }
.ds-logs-view > div:nth-child(1) {
padding: 0.1em 0 1em 0; }
.ds-logs-view > div:nth-child(1) div {
margin-bottom: 0; }
.ds-user-edit, .ds-permission-edit, .ds-group-edit {
margin: 1em 0 7em 0; }
.ds-user-edit .btn, .ds-permission-edit .btn, .ds-group-edit .btn {
margin-bottom: 1em; }
.ds-user-edit .btn-danger, .ds-permission-edit .btn-danger, .ds-group-edit .btn-danger {
float: right; }
.ds-user-edit > h4, .ds-permission-edit > h4, .ds-group-edit > h4 {
margin: 2em 0 0 0 !important; }
.ds-user-edit hr, .ds-permission-edit hr, .ds-group-edit hr {
margin-top: 0.5em; }
.ds-user-edit table tr td:nth-child(1), .ds-permission-edit table tr td:nth-child(1), .ds-group-edit table tr td:nth-child(1) {
font-weight: bold; }
.ds-user-edit #reset-password, .ds-permission-edit #reset-password, .ds-group-edit #reset-password {
margin-top: 1em;
margin-bottom: 1em;
cursor: pointer; }
.ds-user-add {
padding-top: 1em; }
.ds-user-add button {
margin-bottom: 1em; }
#password-collapse {
cursor: pointer; }
.permission-check {
font-size: 1.2em;
padding-bottom: 0.9em; }
.permission-check div {
padding-left: 0.6em;
user-select: none;
-moz-user-select: none;
-webkit-user-select: none; }
/*# sourceMappingURL=administrator.css.map */
| Java |
PYTHON = `which python2`
all:
@echo no build make rule yet, just '"make check"'
test-end2end:
@cd tests/ && PYTHON=${PYTHON} ./testsuite
test-unit:
PYTHONPATH=..:$${PYTHONPATH} ${PYTHON} -m pytest `[ ! -z ${COVERAGE} ] && echo "--cov distgen"` tests/unittests/
# Note that flake8 reports both W503 and W504 ATM :-/ so ignore W503 for now,
# which is what should be considered the right setup.
test-lint:
flake8 distgen/ --ignore=W503
# Check that testsuite in packaged sources work fine, too.
test-sdist-check:
rm -rf dist
$(PYTHON) setup.py sdist
cd dist/ && tar xf *.tar.gz && cd distgen-*/ && $(MAKE) check PYTHON=$(PYTHON)
# Check that tarball generated by git-archive also passes the testsuite
test-git-archive-check:
rm -rf archive && mkdir archive
git archive --prefix distgen/ HEAD | tar -x -C archive
cd archive/distgen && $(MAKE) check PYTHON=$(PYTHON)
check: test-unit test-end2end
| Java |
import sys,os
#sys.path.append(os.path.join(os.path.dirname(__file__), '../../..'))
#from ethosgame.ethos.level import Level
from ..level import Level
#from ethosgame.ethos.gameobject import GameObject
from ..gameobject import GameObject
#from ethosgame.ethos.drawnobject import DrawnObject
from ..drawnobject import DrawnObject
import pygame
from pygame.locals import *
from pygame import Color, image, font, sprite
class Level0(Level):
def __init__(self):
super(Level0, self).__init__()
self.activeSprites = sprite.RenderClear()
self.drawnSprites = []
self.npc = GameObject(image.load('User.png'), 100,50)
self.activeSprites.add(self.npc)
self.block1 = GameObject(image.load('platform.png'), 100, 400)
self.activeSprites.add(self.block1);
self.mousex = 0
self.mousey = 0
#The highest height our npc
#can climb. If a the dY with a
#point is higher than this, the
#npc will just fall to his death
self.MAX_HILL_HEIGHT = 3
self.toDrawRectTopLeft = (0,0)
self.toDrawRectBottomRight = (0,0)
self.drawing = False
self.pts = []
print "Level 0 initialized."
def update(self, dT):
#print "Running level0"
#Character info
for gobject in self.activeSprites:
if gobject is not self.npc:
if not gobject.rect.colliderect(self.npc.rect):
#if self.npc.vy < 0.3 and (gobject.rect.y >= self.npc.rect.y + self.npc.rect.height):
if self.npc.vy < 0.3:
self.npc.vy += 0.1
else:
self.npc.vy = 0
gobject.update(dT)
collidingPoints = []
for drawnstuff in self.drawnSprites:
for point in drawnstuff.pts:
x = self.npc.rect.collidepoint(point)
if x:
collidingPoints.append(point)
if(len(collidingPoints) > 0):
self.npc.processPointCollision(collidingPoints)
def processKeyDown(self,key):
print "You hit the key " + str(key) + "!"
if key == pygame.K_RIGHT:
self.npc.vx = 0.1
def processMouseMotion(self,pos):
#print "Your mouse is at " + str(pos[0]) + " " + str(pos[1])
self.mousex = pos[0]
self.mousey = pos[1]
if self.drawing and len(self.pts) < 100:
self.pts.append( pos )
def processMouseButtonDown(self, pos):
print "Ya clicked at " + str(pos[0]) + " " + str(pos[1]) + " ya goof!"
self.drawing = True
self.toDrawRectTopLeft = (pos[0],pos[1])
if len(self.pts) > 0:
self.pts = []
def processMouseButtonUp(self, pos):
print "Ya let go"
if self.drawing is True:
self.drawing = False
self.drawnSprites.append ( DrawnObject(self.pts) )
self.toDrawRectBottomRight = (pos[0], pos[1])
| Java |
<?php
/*
Template Name: Nos fromages
*
* This is your custom page template. You can create as many of these as you need.
* Simply name is "page-whatever.php" and in add the "Template Name" title at the
* top, the same way it is here.
*
* When you create your page, you can just select the template and viola, you have
* a custom page template to call your very own. Your mother would be so proud.
*
* For more info: http://codex.wordpress.org/Page_Templates
*/
?>
<?php get_header(); ?>
<div id="content" class="montagneBackground">
<div class="container_12">
<section class="categories-f-r">
<?php $taxonomy = 'fromages_cat';
$tax_terms = get_terms( $taxonomy, array( 'hide_empty' => 0, 'orderby' => 'id', 'order' => DESC ) ); ?>
<div class="text-wrapper">
<h1>Nos Fromages RichesMonts</h1>
<h2>Variez les plaisirs ! <br> Découvrez toutes nos Raclettes,<br> Fondues et Tartiflettes !</h2>
</div>
<div class="categorie-bloc">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-1.jpg" alt="">
<a href="<?php echo get_term_link($tax_terms[0]); ?>"><h3><?php echo $tax_terms[0]->name; ?></h3></a>
</div>
<div class="categorie-bloc">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-2.jpg" alt="">
<a href="<?php echo get_term_link($tax_terms[1]); ?>"><h3><?php echo $tax_terms[1]->name; ?></h3></a>
</div>
<div class="categorie-bloc">
<img src="<?php echo get_template_directory_uri(); ?>/library/images/categorie-fromage-3.jpg" alt="">
<a href="<?php echo get_term_link($tax_terms[2]); ?>"><h3><?php echo $tax_terms[2]->name; ?></h3></a>
</div>
</section>
<div class="clearfix"></div>
<?php $the_query = new WP_Query( array('post_type' => 'partenaires', 'showposts' => 5) );
if ( $the_query->have_posts() ) { ?>
<section class="partenaires container_12">
<div class="outer-center">
<div class="inner-center">
<h2>Nos partenaires :</h2>
<?php while ( $the_query->have_posts() ) { ?>
<?php $the_query->the_post(); ?>
<?php $image = get_field('logo'); ?>
<a href="<?php the_field('lien'); ?>"><img src="<?php echo $image['url'] ?>" alt="<?php the_title(); ?>"></a>
<?php } ?>
</div>
</div>
</section>
<?php } wp_reset_postdata(); ?>
<div class="clearfix"></div>
</div>
</div>
<?php get_footer(); ?> | Java |
hr{margin:20px auto;}
.wrap{margin: 40px 0 0 60px;padding:30px;}
.choice{padding:10px 0;overflow:hidden;}
.choice .span1{float:left;}
.choice .span2{float:left;margin-top:10px;}
.choice input[type=text]{width:300px;margin-left:70px;padding:8px 4px;}
.choice textarea{width: 320px;height: 35px;}
.choice_radio{margin-left:150px;}
.submit{margin-top:20px;margin-right:10px;padding:0;float:left;}
.submit input,.submit input:hover,.submit input:active{padding:6px 10px;border:none;border-radius:0;background:#299982;color:#fff;text-shadow:none;}
| Java |
<?php
/**
* Sample implementation of the Custom Header feature.
*
* You can add an optional custom header image to header.php like so ...
*
<?php if ( get_header_image() ) : ?>
<a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home">
<img src="<?php header_image(); ?>" width="<?php echo esc_attr( get_custom_header()->width ); ?>" height="<?php echo esc_attr( get_custom_header()->height ); ?>" alt="">
</a>
<?php endif; // End header image check. ?>
*
* @link https://developer.wordpress.org/themes/functionality/custom-headers/
*
* @package sachyya
*/
/**
* Set up the WordPress core custom header feature.
*
* @uses sachyya_header_style()
*/
function sachyya_custom_header_setup() {
add_theme_support( 'custom-header', apply_filters( 'sachyya_custom_header_args', array(
'default-image' => '',
'default-text-color' => '000000',
'width' => 1000,
'height' => 250,
'flex-height' => true,
'wp-head-callback' => 'sachyya_header_style',
) ) );
}
add_action( 'after_setup_theme', 'sachyya_custom_header_setup' );
if ( ! function_exists( 'sachyya_header_style' ) ) :
/**
* Styles the header image and text displayed on the blog.
*
* @see sachyya_custom_header_setup().
*/
function sachyya_header_style() {
$header_text_color = get_header_textcolor();
/*
* If no custom options for text are set, let's bail.
* get_header_textcolor() options: Any hex value, 'blank' to hide text. Default: HEADER_TEXTCOLOR.
*/
if ( HEADER_TEXTCOLOR === $header_text_color ) {
return;
}
// If we get this far, we have custom styles. Let's do this.
?>
<style type="text/css">
<?php
// Has the text been hidden?
if ( ! display_header_text() ) :
?>
.site-title,
.site-description {
position: absolute;
clip: rect(1px, 1px, 1px, 1px);
}
<?php
// If the user has set a custom color for the text use that.
else :
?>
.site-title a,
.site-description {
color: #<?php echo esc_attr( $header_text_color ); ?>;
}
<?php endif; ?>
</style>
<?php
}
endif;
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Sun Feb 15 12:26:29 PST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>org.apache.solr.client.solrj.embedded (Solr 5.0.0 API)</title>
<meta name="date" content="2015-02-15">
<link rel="stylesheet" type="text/css" href="../../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="org.apache.solr.client.solrj.embedded (Solr 5.0.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/solr/analysis/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../org/apache/solr/cloud/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/client/solrj/embedded/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 title="Package" class="title">Package org.apache.solr.client.solrj.embedded</h1>
<div class="docSummary">
<div class="block">
SolrJ client implementations for embedded solr access.</div>
</div>
<p>See: <a href="#package_description">Description</a></p>
</div>
<div class="contentContainer">
<ul class="blockList">
<li class="blockList">
<table class="packageSummary" border="0" cellpadding="3" cellspacing="0" summary="Class Summary table, listing classes, and an explanation">
<caption><span>Class Summary</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Class</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/EmbeddedSolrServer.html" title="class in org.apache.solr.client.solrj.embedded">EmbeddedSolrServer</a></td>
<td class="colLast">
<div class="block">SolrClient that connects directly to SolrCore.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner</a></td>
<td class="colLast">
<div class="block">Run solr using jetty</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.DebugFilter.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner.DebugFilter</a></td>
<td class="colLast"> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/JettySolrRunner.Servlet404.html" title="class in org.apache.solr.client.solrj.embedded">JettySolrRunner.Servlet404</a></td>
<td class="colLast">
<div class="block">This is a stupid hack to give jetty something to attach to</div>
</td>
</tr>
<tr class="altColor">
<td class="colFirst"><a href="../../../../../../org/apache/solr/client/solrj/embedded/SSLConfig.html" title="class in org.apache.solr.client.solrj.embedded">SSLConfig</a></td>
<td class="colLast"> </td>
</tr>
</tbody>
</table>
</li>
</ul>
<a name="package_description">
<!-- -->
</a>
<h2 title="Package org.apache.solr.client.solrj.embedded Description">Package org.apache.solr.client.solrj.embedded Description</h2>
<div class="block"><p>
SolrJ client implementations for embedded solr access.
</p>
<p>
See <a href="../../../../../../../solr-solrj/org/apache/solr/client/solrj/package-summary.html?is-external=true"><code>org.apache.solr.client.solrj</code></a> for additional details.
</p></div>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li class="navBarCell1Rev">Package</li>
<li>Class</li>
<li><a href="package-use.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../../../org/apache/solr/analysis/package-summary.html">Prev Package</a></li>
<li><a href="../../../../../../org/apache/solr/cloud/package-summary.html">Next Package</a></li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/client/solrj/embedded/package-summary.html" target="_top">Frames</a></li>
<li><a href="package-summary.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| Java |
<?php
require_once(sfConfig::get('sf_lib_dir').'/filter/base/BaseFormFilterPropel.class.php');
/**
* CatArt filter form base class.
*
* @package sf_sandbox
* @subpackage filter
* @author Your name here
* @version SVN: $Id: sfPropelFormFilterGeneratedTemplate.php 16976 2009-04-04 12:47:44Z fabien $
*/
class BaseCatArtFormFilter extends BaseFormFilterPropel
{
public function setup()
{
$this->setWidgets(array(
'cat_des' => new sfWidgetFormFilterInput(),
'dis_cen' => new sfWidgetFormFilterInput(),
'campo1' => new sfWidgetFormFilterInput(),
'campo2' => new sfWidgetFormFilterInput(),
'campo3' => new sfWidgetFormFilterInput(),
'campo4' => new sfWidgetFormFilterInput(),
'co_us_in' => new sfWidgetFormFilterInput(),
'fe_us_in' => new sfWidgetFormFilterInput(),
'co_us_mo' => new sfWidgetFormFilterInput(),
'fe_us_mo' => new sfWidgetFormFilterInput(),
'co_us_el' => new sfWidgetFormFilterInput(),
'fe_us_el' => new sfWidgetFormFilterInput(),
'revisado' => new sfWidgetFormFilterInput(),
'trasnfe' => new sfWidgetFormFilterInput(),
'co_sucu' => new sfWidgetFormFilterInput(),
'rowguid' => new sfWidgetFormFilterInput(),
'co_imun' => new sfWidgetFormFilterInput(),
'co_reten' => new sfWidgetFormFilterInput(),
'row_id' => new sfWidgetFormFilterInput(),
'movil' => new sfWidgetFormChoice(array('choices' => array('' => 'yes or no', 1 => 'yes', 0 => 'no'))),
));
$this->setValidators(array(
'cat_des' => new sfValidatorPass(array('required' => false)),
'dis_cen' => new sfValidatorPass(array('required' => false)),
'campo1' => new sfValidatorPass(array('required' => false)),
'campo2' => new sfValidatorPass(array('required' => false)),
'campo3' => new sfValidatorPass(array('required' => false)),
'campo4' => new sfValidatorPass(array('required' => false)),
'co_us_in' => new sfValidatorPass(array('required' => false)),
'fe_us_in' => new sfValidatorPass(array('required' => false)),
'co_us_mo' => new sfValidatorPass(array('required' => false)),
'fe_us_mo' => new sfValidatorPass(array('required' => false)),
'co_us_el' => new sfValidatorPass(array('required' => false)),
'fe_us_el' => new sfValidatorPass(array('required' => false)),
'revisado' => new sfValidatorPass(array('required' => false)),
'trasnfe' => new sfValidatorPass(array('required' => false)),
'co_sucu' => new sfValidatorPass(array('required' => false)),
'rowguid' => new sfValidatorPass(array('required' => false)),
'co_imun' => new sfValidatorPass(array('required' => false)),
'co_reten' => new sfValidatorPass(array('required' => false)),
'row_id' => new sfValidatorPass(array('required' => false)),
'movil' => new sfValidatorChoice(array('required' => false, 'choices' => array('', 1, 0))),
));
$this->widgetSchema->setNameFormat('cat_art_filters[%s]');
$this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
parent::setup();
}
public function getModelName()
{
return 'CatArt';
}
public function getFields()
{
return array(
'co_cat' => 'Text',
'cat_des' => 'Text',
'dis_cen' => 'Text',
'campo1' => 'Text',
'campo2' => 'Text',
'campo3' => 'Text',
'campo4' => 'Text',
'co_us_in' => 'Text',
'fe_us_in' => 'Text',
'co_us_mo' => 'Text',
'fe_us_mo' => 'Text',
'co_us_el' => 'Text',
'fe_us_el' => 'Text',
'revisado' => 'Text',
'trasnfe' => 'Text',
'co_sucu' => 'Text',
'rowguid' => 'Text',
'co_imun' => 'Text',
'co_reten' => 'Text',
'row_id' => 'Text',
'movil' => 'Boolean',
);
}
}
| Java |
require File.join(File.dirname(__FILE__), 'test_helper')
class PointTest < Test::Unit::TestCase
context "A point" do
setup do
@point = Pathfinder::Point.new 1, 2
end
should "respond to #x and #y" do
assert_equal 1, @point.x
assert_equal 2, @point.y
end
should "convert to an Array using #to_a" do
assert_equal [1,2], @point.to_a
end
should "output in ordered-pair notation upon #inspect" do
assert_equal "(1,2)", @point.inspect
end
should "have distance zero from itself" do
assert_equal 0.0, @point.distance(@point)
end
should "use the distance formula to calculate #distance" do
origin = Pathfinder::Point.new 0,0
assert_in_delta Math.sqrt(5), @point.distance(origin), 0.0001
end
end
end
| Java |
package org.iq4j.webcam;
import java.awt.Canvas;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Image;
import java.awt.KeyEventDispatcher;
import java.awt.KeyboardFocusManager;
import java.awt.Transparency;
import java.awt.color.ColorSpace;
import java.awt.color.ICC_ColorSpace;
import java.awt.color.ICC_ProfileRGB;
import java.awt.event.KeyEvent;
import java.awt.image.BufferStrategy;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;
import com.googlecode.javacv.cpp.opencv_core.CvScalar;
import com.googlecode.javacv.cpp.opencv_core.IplImage;
/**
*
* @author Samuel Audet
*
*
* Make sure OpenGL or XRender is enabled to get low latency, something like
* export _JAVA_OPTIONS=-Dsun.java2d.opengl=True
* export _JAVA_OPTIONS=-Dsun.java2d.xrender=True
*
* @author Sertac ANADOLLU ( anatolian )
*
* JPanel version of javacv CanvasFrame
*
*/
public class CanvasPanel extends JPanel {
private static final long serialVersionUID = 1L;
public static class Exception extends java.lang.Exception {
private static final long serialVersionUID = 1L;
public Exception(String message) { super(message); }
public Exception(String message, Throwable cause) { super(message, cause); }
}
public static GraphicsDevice getDefaultScreenDevice() {
return GraphicsEnvironment.getLocalGraphicsEnvironment().getDefaultScreenDevice();
}
public static double getGamma(GraphicsDevice screen) {
ColorSpace cs = screen.getDefaultConfiguration().getColorModel().getColorSpace();
if (cs.isCS_sRGB()) {
return 2.2;
} else {
try {
return ((ICC_ProfileRGB)((ICC_ColorSpace)cs).getProfile()).getGamma(0);
} catch (RuntimeException e) { }
}
return 0.0;
}
public CanvasPanel() {
this(0.0);
}
public CanvasPanel(double gamma) {
this(gamma, Dimensions.DEFAULT_SIZE);
}
public CanvasPanel(double gamma, Dimension size) {
this.gamma = gamma;
setPreferredSize(size);
setSize(size);
setBackground(Color.LIGHT_GRAY);
}
private void startCanvas() {
Runnable r = new Runnable() { public void run() {
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(keyEventDispatch);
GraphicsDevice gd = getGraphicsConfiguration().getDevice();
double g = gamma == 0.0 ? getGamma(gd) : gamma;
inverseGamma = g == 0.0 ? 1.0 : 1.0/g;
setVisible(true);
setupCanvas(gamma);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
if (EventQueue.isDispatchThread()) {
r.run();
setCanvasSize(getSize().width, getSize().height);
} else {
try {
EventQueue.invokeAndWait(r);
} catch (java.lang.Exception ex) { }
}
}
public void resetCanvas() {
canvas = null;
}
protected void setupCanvas(double gamma) {
canvas = new Canvas() {
private static final long serialVersionUID = 1L;
@Override public void update(Graphics g) {
paint(g);
}
@Override public void paint(Graphics g) {
// Calling BufferStrategy.show() here sometimes throws
// NullPointerException or IllegalStateException,
// but otherwise seems to work fine.
try {
BufferStrategy strategy = canvas.getBufferStrategy();
do {
do {
g = strategy.getDrawGraphics();
if (color != null) {
g.setColor(color);
g.fillRect(0, 0, getWidth(), getHeight());
}
if (image != null) {
g.drawImage(image, 0, 0, getWidth(), getHeight(), null);
}
if (buffer != null) {
g.drawImage(buffer, 0, 0, getWidth(), getHeight(), null);
}
g.dispose();
} while (strategy.contentsRestored());
strategy.show();
} while (strategy.contentsLost());
} catch (NullPointerException e) {
} catch (IllegalStateException e) { }
}
};
needInitialResize = true;
add(canvas);
canvas.setVisible(true);
canvas.createBufferStrategy(2);
}
// used for example as debugging console...
public static CanvasPanel global = null;
// Latency is about 60 ms on Metacity and Windows XP, and 90 ms on Compiz Fusion,
// but we set the default to twice as much to take into account the roundtrip
// camera latency as well, just to be sure
public static final long DEFAULT_LATENCY = 200;
private long latency = DEFAULT_LATENCY;
private KeyEvent keyEvent = null;
private KeyEventDispatcher keyEventDispatch = new KeyEventDispatcher() {
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED) {
synchronized (CanvasPanel.this) {
keyEvent = e;
CanvasPanel.this.notify();
}
}
return false;
}
};
protected Canvas canvas = null;
protected boolean needInitialResize = false;
protected double initialScale = 1.0;
protected double inverseGamma = 1.0;
private Color color = null;
private Image image = null;
private BufferedImage buffer = null;
private final double gamma;
public long getLatency() {
// if there exists some way to estimate the latency in real time,
// add it here
return latency;
}
public void setLatency(long latency) {
this.latency = latency;
}
public void waitLatency() throws InterruptedException {
Thread.sleep(getLatency());
}
public KeyEvent waitKey() throws InterruptedException {
return waitKey(0);
}
public synchronized KeyEvent waitKey(int delay) throws InterruptedException {
if (delay >= 0) {
keyEvent = null;
wait(delay);
}
KeyEvent e = keyEvent;
keyEvent = null;
return e;
}
public Canvas getCanvas() {
return canvas;
}
public Dimension getCanvasSize() {
return canvas.getSize();
}
public void setCanvasSize(final int width, final int height) {
Dimension d = getCanvasSize();
if (d.width == width && d.height == height) {
return;
}
Runnable r = new Runnable() { public void run() {
// There is apparently a bug in Java code for Linux, and what happens goes like this:
// 1. Canvas gets resized, checks the visible area (has not changed) and updates
// BufferStrategy with the same size. 2. pack() resizes the frame and changes
// the visible area 3. We call Canvas.setSize() with different dimensions, to make
// it check the visible area and reallocate the BufferStrategy almost correctly
// 4. Finally, we resize the Canvas to the desired size... phew!
canvas.setSize(width, height);
setSize(width, height);
canvas.setSize(width+1, height+1);
canvas.setSize(width, height);
needInitialResize = false;
}};
if (EventQueue.isDispatchThread()) {
r.run();
} else {
try {
EventQueue.invokeAndWait(r);
} catch (java.lang.Exception ex) { }
}
}
public double getCanvasScale() {
return initialScale;
}
public void setCanvasScale(double initialScale) {
this.initialScale = initialScale;
this.needInitialResize = true;
}
public Graphics2D createGraphics() {
if (buffer == null || buffer.getWidth() != canvas.getWidth() || buffer.getHeight() != canvas.getHeight()) {
BufferedImage newbuffer = canvas.getGraphicsConfiguration().createCompatibleImage(
canvas.getWidth(), canvas.getHeight(), Transparency.TRANSLUCENT);
if (buffer != null) {
Graphics g = newbuffer.getGraphics();
g.drawImage(buffer, 0, 0, null);
g.dispose();
}
buffer = newbuffer;
}
return buffer.createGraphics();
}
public void releaseGraphics(Graphics2D g) {
g.dispose();
canvas.paint(null);
}
public void showColor(CvScalar color) {
showColor(new Color((int)color.red(), (int)color.green(), (int)color.blue()));
}
public void showColor(Color color) {
this.color = color;
this.image = null;
canvas.paint(null);
}
// Java2D will do gamma correction for TYPE_CUSTOM BufferedImage, but
// not for the standard types, so we need to do it manually.
public void showImage(IplImage image) {
showImage(image, false);
}
public void showImage(IplImage image, boolean flipChannels) {
showImage(image.getBufferedImage(image.getBufferedImageType() ==
BufferedImage.TYPE_CUSTOM ? 1.0 : inverseGamma, flipChannels));
}
public void showImage(Image image) {
if(canvas == null) {
startCanvas();
}
if (image == null) {
return;
} else if (needInitialResize) {
int w = (int)Math.round(image.getWidth (null)*initialScale);
int h = (int)Math.round(image.getHeight(null)*initialScale);
setCanvasSize(w, h);
}
this.color = null;
this.image = image;
canvas.paint(null);
}
}
| Java |
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.map, name='map'),
url(r'^mapSim', views.mapSim, name='mapSim'),
url(r'^api/getPos', views.getPos, name='getPos'),
url(r'^api/getProjAndPos', views.getProjAndPos, name='getProjAndPos'),
]
| Java |
// RUN: %clang_cc1 -triple x86_64-unknown-unknown %s -fsyntax-only -verify
#define SA(n, p) int a##n[(p) ? 1 : -1]
struct A { int a; };
SA(0, sizeof(A) == 4);
struct B { };
SA(1, sizeof(B) == 1);
struct C : A, B { };
SA(2, sizeof(C) == 4);
struct D { };
struct E : D { };
struct F : E { };
struct G : E, F { };
SA(3, sizeof(G) == 2);
struct Empty { Empty(); };
struct I : Empty {
Empty e;
};
SA(4, sizeof(I) == 2);
struct J : Empty {
Empty e[2];
};
SA(5, sizeof(J) == 3);
template<int N> struct Derived : Empty, Derived<N - 1> {
};
template<> struct Derived<0> : Empty { };
struct S1 : virtual Derived<10> {
Empty e;
};
SA(6, sizeof(S1) == 24);
struct S2 : virtual Derived<10> {
Empty e[2];
};
SA(7, sizeof(S2) == 24);
struct S3 {
Empty e;
};
struct S4 : Empty, S3 {
};
SA(8, sizeof(S4) == 2);
struct S5 : S3, Empty {};
SA(9, sizeof(S5) == 2);
struct S6 : S5 { };
SA(10, sizeof(S6) == 2);
struct S7 : Empty {
void *v;
};
SA(11, sizeof(S7) == 8);
struct S8 : Empty, A {
};
SA(12, sizeof(S8) == 4);
| Java |
using Halsign.DWM.Framework;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Threading;
namespace Halsign.DWM.Domain
{
public class DwmHost : DwmBase
{
private int _numCpus = 1;
private int _numVCpus;
private int _cpuSpeed;
private int _numNics = 1;
private bool _isPoolMaster;
private bool _enabled = true;
private string _ipAddress;
private bool _isEnterpriseOrHigher;
private PowerStatus _powerState;
private bool _participatesInPowerManagement;
private bool _excludeFromPlacementRecommendations;
private bool _excludeFromEvacuationRecommendations;
private bool _excludeFromPoolOptimizationAcceptVMs;
private long _memOverhead;
private DateTime _metricsLastRetrieved = DateTime.MinValue;
private DwmVirtualMachineCollection _listVMs;
private DwmPifCollection _listPIFs;
private DwmPbdCollection _listPBDs;
private DwmStorageRepositoryCollection _availableStorage;
private DwmHostAverageMetric _metrics;
private static Dictionary<string, int> _uuidCache = new Dictionary<string, int>();
private static Dictionary<string, int> _nameCache = new Dictionary<string, int>();
private static Dictionary<string, string> _uuidNameCache = new Dictionary<string, string>();
private static object _uuidCacheLock = new object();
private static object _nameCacheLock = new object();
private static object _uuidNameCacheLock = new object();
private double _cpuScore;
public int NumCpus
{
get
{
return this._numCpus;
}
set
{
this._numCpus = value;
}
}
public int NumVCpus
{
get
{
return this._numVCpus;
}
set
{
this._numVCpus = value;
}
}
public int CpuSpeed
{
get
{
return this._cpuSpeed;
}
set
{
this._cpuSpeed = value;
}
}
public int NumNics
{
get
{
return this._numNics;
}
set
{
this._numNics = value;
}
}
public string IPAddress
{
get
{
return this._ipAddress;
}
set
{
this._ipAddress = value;
}
}
public bool IsPoolMaster
{
get
{
return this._isPoolMaster;
}
set
{
this._isPoolMaster = value;
}
}
public bool Enabled
{
get
{
return this._enabled;
}
set
{
this._enabled = value;
}
}
public bool IsEnterpriseOrHigher
{
get
{
return this._isEnterpriseOrHigher;
}
set
{
this._isEnterpriseOrHigher = value;
}
}
public PowerStatus PowerState
{
get
{
return this._powerState;
}
set
{
this._powerState = value;
}
}
public long MemoryOverhead
{
get
{
return this._memOverhead;
}
set
{
this._memOverhead = value;
}
}
internal bool ParticipatesInPowerManagement
{
get
{
return this._participatesInPowerManagement;
}
set
{
this._participatesInPowerManagement = value;
}
}
internal bool ExcludeFromPlacementRecommendations
{
get
{
return this._excludeFromPlacementRecommendations;
}
set
{
this._excludeFromPlacementRecommendations = value;
}
}
internal bool ExcludeFromEvacuationRecommendations
{
get
{
return this._excludeFromEvacuationRecommendations;
}
set
{
this._excludeFromEvacuationRecommendations = value;
}
}
internal bool ExcludeFromPoolOptimizationAcceptVMs
{
get
{
return this._excludeFromPoolOptimizationAcceptVMs;
}
set
{
this._excludeFromPoolOptimizationAcceptVMs = value;
}
}
public DwmVirtualMachineCollection VirtualMachines
{
get
{
return DwmBase.SafeGetItem<DwmVirtualMachineCollection>(ref this._listVMs);
}
internal set
{
this._listVMs = value;
}
}
public DwmPifCollection PIFs
{
get
{
return DwmBase.SafeGetItem<DwmPifCollection>(ref this._listPIFs);
}
}
public DwmPbdCollection PBDs
{
get
{
return DwmBase.SafeGetItem<DwmPbdCollection>(ref this._listPBDs);
}
}
public DwmStorageRepositoryCollection AvailableStorage
{
get
{
return DwmBase.SafeGetItem<DwmStorageRepositoryCollection>(ref this._availableStorage);
}
internal set
{
this._availableStorage = value;
}
}
public DwmHostAverageMetric Metrics
{
get
{
return DwmBase.SafeGetItem<DwmHostAverageMetric>(ref this._metrics);
}
internal set
{
this._metrics = value;
}
}
internal double CpuScore
{
get
{
this._cpuScore = (double)(this.NumCpus * this.CpuSpeed);
if (this.Metrics.MetricsNow != null)
{
this._cpuScore *= 1.0 - this.Metrics.MetricsNow.AverageCpuUtilization;
}
return this._cpuScore;
}
}
public DateTime MetricsLastRetrieved
{
get
{
if (this._metricsLastRetrieved == DateTime.MinValue)
{
string sqlStatement = "get_host_last_metric_time";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", base.Id));
using (DBAccess dBAccess = new DBAccess())
{
this._metricsLastRetrieved = dBAccess.ExecuteScalarDateTime(sqlStatement, storedProcParamCollection);
}
if (this._metricsLastRetrieved == DateTime.MinValue)
{
this._metricsLastRetrieved = DateTime.UtcNow.AddMinutes(-1.0);
}
}
return this._metricsLastRetrieved;
}
set
{
this._metricsLastRetrieved = value;
}
}
public DwmHost(string uuid, string name, string poolUuid) : base(uuid, name)
{
base.PoolId = DwmBase.PoolUuidToId(poolUuid);
if (!string.IsNullOrEmpty(uuid))
{
base.Id = DwmHost.UuidToId(uuid, base.PoolId);
}
else
{
if (string.IsNullOrEmpty(name))
{
throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null);
}
base.Id = DwmHost.NameToId(name, base.PoolId);
}
}
public DwmHost(string uuid, string name, int poolId) : base(uuid, name)
{
base.PoolId = poolId;
if (!string.IsNullOrEmpty(uuid))
{
base.Id = DwmHost.UuidToId(uuid, base.PoolId);
}
else
{
if (string.IsNullOrEmpty(name))
{
throw new DwmException("The uuid or name of the Physical Host must be specified.", DwmErrorCode.InvalidParameter, null);
}
base.Id = DwmHost.NameToId(name, base.PoolId);
}
}
public DwmHost(int hostID) : base(hostID)
{
}
internal static void RefreshCache()
{
object uuidCacheLock = DwmHost._uuidCacheLock;
Monitor.Enter(uuidCacheLock);
try
{
DwmHost._uuidCache.Clear();
}
finally
{
Monitor.Exit(uuidCacheLock);
}
object nameCacheLock = DwmHost._nameCacheLock;
Monitor.Enter(nameCacheLock);
try
{
DwmHost._nameCache.Clear();
}
finally
{
Monitor.Exit(nameCacheLock);
}
object uuidNameCacheLock = DwmHost._uuidNameCacheLock;
Monitor.Enter(uuidNameCacheLock);
try
{
DwmHost._uuidNameCache.Clear();
}
finally
{
Monitor.Exit(uuidNameCacheLock);
}
}
internal static int UuidToId(string uuid, int poolId)
{
int num = 0;
if (!string.IsNullOrEmpty(uuid))
{
string key = Localization.Format("{0}|{1}", uuid, poolId);
if (!DwmHost._uuidCache.TryGetValue(key, out num))
{
using (DBAccess dBAccess = new DBAccess())
{
num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where uuid='{0}' and poolid={1}", uuid.Replace("'", "''"), poolId));
if (num != 0)
{
object uuidCacheLock = DwmHost._uuidCacheLock;
Monitor.Enter(uuidCacheLock);
try
{
if (!DwmHost._uuidCache.ContainsKey(key))
{
DwmHost._uuidCache.Add(key, num);
}
}
finally
{
Monitor.Exit(uuidCacheLock);
}
}
}
}
}
return num;
}
public static int NameToId(string name, int poolId)
{
int num = 0;
if (!string.IsNullOrEmpty(name))
{
string key = Localization.Format("{0}|{1}", name, poolId);
if (!DwmHost._nameCache.TryGetValue(key, out num))
{
using (DBAccess dBAccess = new DBAccess())
{
num = dBAccess.ExecuteScalarInt(Localization.Format("select id from hv_host where name='{0}' and poolid={1}", name.Replace("'", "''"), poolId));
if (num != 0)
{
object nameCacheLock = DwmHost._nameCacheLock;
Monitor.Enter(nameCacheLock);
try
{
if (!DwmHost._nameCache.ContainsKey(key))
{
DwmHost._nameCache.Add(key, num);
}
}
finally
{
Monitor.Exit(nameCacheLock);
}
}
}
}
}
return num;
}
public static string UuidToName(string uuid, int poolId)
{
string text = string.Empty;
if (!string.IsNullOrEmpty(uuid))
{
string key = Localization.Format("{0}|{1}", uuid, poolId);
if (!DwmHost._uuidNameCache.TryGetValue(key, out text))
{
using (DBAccess dBAccess = new DBAccess())
{
text = dBAccess.ExecuteScalarString(Localization.Format("select name from hv_host where uuid='{0}' and poolid={1}", uuid, poolId));
if (string.IsNullOrEmpty(text))
{
object uuidNameCacheLock = DwmHost._uuidNameCacheLock;
Monitor.Enter(uuidNameCacheLock);
try
{
if (!DwmHost._uuidNameCache.ContainsKey(key))
{
DwmHost._uuidNameCache.Add(key, text);
}
}
finally
{
Monitor.Exit(uuidNameCacheLock);
}
}
}
}
}
return text;
}
public DwmHost Copy()
{
return new DwmHost(base.Uuid, base.Name, base.PoolId)
{
Id = base.Id,
CpuSpeed = this.CpuSpeed,
Description = base.Description,
IsPoolMaster = this.IsPoolMaster,
Name = base.Name,
NumCpus = this.NumCpus,
NumVCpus = this.NumVCpus,
NumNics = this.NumNics,
ParticipatesInPowerManagement = this.ParticipatesInPowerManagement,
ExcludeFromPlacementRecommendations = this.ExcludeFromPlacementRecommendations,
ExcludeFromEvacuationRecommendations = this.ExcludeFromEvacuationRecommendations,
ExcludeFromPoolOptimizationAcceptVMs = this.ExcludeFromPoolOptimizationAcceptVMs,
PowerState = this.PowerState,
MemoryOverhead = this.MemoryOverhead,
Metrics = this.Metrics.Copy(),
AvailableStorage = this.AvailableStorage.Copy(),
VirtualMachines = this.VirtualMachines.Copy()
};
}
internal static void SetOtherConfig(int hostId, string name, string value)
{
DwmHost dwmHost = new DwmHost(hostId);
dwmHost.SetOtherConfig(name, value);
}
public void SetOtherConfig(string name, string value)
{
base.SetOtherConfig("hv_host_config_update", "@host_id", name, value);
if (Localization.Compare(name, "ParticipatesInPowerManagement", true) == 0)
{
DwmPool.GenerateFillOrder(base.PoolId);
}
}
public void SetOtherConfig(Dictionary<string, string> config)
{
base.SetOtherConfig("hv_host_config_update", "@host_id", config);
if (config.ContainsKey("ParticipatesInPowerManagement"))
{
DwmPool.GenerateFillOrder(base.PoolId);
}
}
public string GetOtherConfigItem(string itemName)
{
return base.GetOtherConfigItem("hv_host_config_get_item", "@host_id", itemName);
}
public Dictionary<string, string> GetOtherConfig()
{
return base.GetOtherConfig("hv_host_config_get", "@host_id");
}
public static void SetEnabled(string hostUuid, string poolUuid, bool enabled)
{
string sqlStatement = "hv_host_set_enabled";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_uuid", hostUuid));
storedProcParamCollection.Add(new StoredProcParam("@pool_uuid", poolUuid));
storedProcParamCollection.Add(new StoredProcParam("@enabled", enabled));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal static void SetStatus(int hostId, DwmStatus status)
{
string sqlStatement = "set_host_status";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
storedProcParamCollection.Add(new StoredProcParam("@status", (int)status));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal static void SetLastResult(int hostId, DwmStatus result)
{
string sqlStatement = "set_host_last_result";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
storedProcParamCollection.Add(new StoredProcParam("@last_result", (int)result));
storedProcParamCollection.Add(new StoredProcParam("@last_result_time", DateTime.UtcNow));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
public static void SetPoweredOffByWlb(int hostId, bool poweredOffByWlb)
{
string sqlStatement = "set_host_powered_off_by_wlb";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@host_id", hostId));
if (poweredOffByWlb)
{
storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 1));
}
else
{
storedProcParamCollection.Add(new StoredProcParam("@powered_off_by_wlb", 0));
}
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
internal bool HasRequiredStorage(DwmStorageRepositoryCollection requiredSRs)
{
bool result = true;
int num = 0;
while (requiredSRs != null && num < requiredSRs.Count)
{
if (!this.AvailableStorage.ContainsKey(requiredSRs[num].Id))
{
result = false;
break;
}
num++;
}
return result;
}
public static void DeleteHost(string hostUuid, string poolUuid)
{
if (!string.IsNullOrEmpty(hostUuid) && !string.IsNullOrEmpty(poolUuid))
{
Logger.Trace("Deleting host {0} by setting active to false", new object[]
{
hostUuid
});
int num = DwmPoolBase.UuidToId(poolUuid);
int num2 = DwmHost.UuidToId(hostUuid, num);
string sqlStatement = "delete_hv_host";
StoredProcParamCollection storedProcParamCollection = new StoredProcParamCollection();
storedProcParamCollection.Add(new StoredProcParam("@pool_id", num));
storedProcParamCollection.Add(new StoredProcParam("@host_id", num2));
storedProcParamCollection.Add(new StoredProcParam("@tstamp", DateTime.UtcNow));
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.ExecuteNonQuery(sqlStatement, storedProcParamCollection);
}
}
}
internal static DwmHost LoadWithMetrics(IDataReader reader)
{
string @string = DBAccess.GetString(reader, "uuid");
string string2 = DBAccess.GetString(reader, "name");
int @int = DBAccess.GetInt(reader, "poolid");
return new DwmHost(@string, string2, @int)
{
Id = DBAccess.GetInt(reader, "id"),
NumCpus = DBAccess.GetInt(reader, "num_cpus"),
NumVCpus = DBAccess.GetInt(reader, "num_vcpus"),
CpuSpeed = DBAccess.GetInt(reader, "cpu_speed"),
NumNics = DBAccess.GetInt(reader, "num_pifs"),
IsPoolMaster = DBAccess.GetBool(reader, "is_pool_master"),
PowerState = (PowerStatus)DBAccess.GetInt(reader, "power_state"),
ParticipatesInPowerManagement = DBAccess.GetBool(reader, "can_power"),
ExcludeFromPlacementRecommendations = DBAccess.GetBool(reader, "exclude_placements"),
ExcludeFromEvacuationRecommendations = DBAccess.GetBool(reader, "exclude_evacuations"),
Metrics =
{
FreeCPUs = DBAccess.GetInt(reader, "free_cpus"),
PotentialFreeMemory = DBAccess.GetInt64(reader, "potential_free_memory"),
FillOrder = DBAccess.GetInt(reader, "fill_order"),
TotalMemory = DBAccess.GetInt64(reader, "total_mem"),
FreeMemory = DBAccess.GetInt64(reader, "free_mem"),
NumHighFullContentionVCpus = DBAccess.GetInt(reader, "full_contention_count"),
NumHighConcurrencyHazardVCpus = DBAccess.GetInt(reader, "concurrency_hazard_count"),
NumHighPartialContentionVCpus = DBAccess.GetInt(reader, "partial_contention_count"),
NumHighFullrunVCpus = DBAccess.GetInt(reader, "fullrun_count"),
NumHighPartialRunVCpus = DBAccess.GetInt(reader, "partial_run_count"),
NumHighBlockedVCpus = DBAccess.GetInt(reader, "blocked_count"),
MetricsNow =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_now", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_now", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_now", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_now", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_now", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_now", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_now", 0.0)
},
MetricsLast30Minutes =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_30", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_30", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_30", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_30", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_30", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_30", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_30", 0.0)
},
MetricsYesterday =
{
AverageFreeMemory = DBAccess.GetInt64(reader, "avg_free_mem_yesterday", 0L),
AverageCpuUtilization = DBAccess.GetDouble(reader, "avg_cpu_yesterday", 0.0),
AveragePifReadsPerSecond = DBAccess.GetDouble(reader, "avg_pif_read_yesterday", 0.0),
AveragePifWritesPerSecond = DBAccess.GetDouble(reader, "avg_pif_write_yesterday", 0.0),
AveragePbdReadsPerSecond = DBAccess.GetDouble(reader, "avg_pbd_read_yesterday", 0.0),
AveragePbdWritesPerSecond = DBAccess.GetDouble(reader, "avg_pbd_write_yesterday", 0.0),
AverageLoadAverage = DBAccess.GetDouble(reader, "avg_load_average_yesterday", 0.0)
}
}
};
}
internal void LoadPif(IDataReader reader)
{
int @int = DBAccess.GetInt(reader, "pif_id");
string @string = DBAccess.GetString(reader, "pif_uuid");
string string2 = DBAccess.GetString(reader, "pif_name");
int int2 = DBAccess.GetInt(reader, "networkid");
int int3 = DBAccess.GetInt(reader, "poolid");
bool @bool = DBAccess.GetBool(reader, "is_management_interface");
DwmPif dwmPif = new DwmPif(@string, string2, int2, int3);
dwmPif.Id = @int;
dwmPif.IsManagementInterface = @bool;
this.PIFs.Add(dwmPif);
}
public void Save()
{
using (DBAccess dBAccess = new DBAccess())
{
this.Save(dBAccess);
}
}
public void Save(DBAccess db)
{
if (db != null)
{
try
{
string sqlStatement = "add_update_hv_host";
base.Id = db.ExecuteScalarInt(sqlStatement, new StoredProcParamCollection
{
new StoredProcParam("@uuid", base.Uuid),
new StoredProcParam("@name", (base.Name == null) ? string.Empty : base.Name),
new StoredProcParam("@pool_id", base.PoolId),
new StoredProcParam("@description", (base.Description == null) ? string.Empty : base.Description),
new StoredProcParam("@num_cpus", this._numCpus),
new StoredProcParam("@cpu_speed", this._cpuSpeed),
new StoredProcParam("@num_nics", this._numNics),
new StoredProcParam("@is_pool_master", this._isPoolMaster),
new StoredProcParam("@ip_address", this._ipAddress),
new StoredProcParam("@memory_overhead", this._memOverhead),
new StoredProcParam("@enabled", this._enabled),
new StoredProcParam("@power_state", (int)this._powerState)
});
StringBuilder stringBuilder = new StringBuilder();
string value = "BEGIN;\n";
string value2 = "COMMIT;\n";
stringBuilder.Append(value);
stringBuilder.Append(this.SaveHostStorageRelationships());
stringBuilder.Append(this.SaveHostVmRelationships());
stringBuilder.Append(this.SaveHostPifRelationships());
stringBuilder.Append(this.SaveHostPbdRelationships());
stringBuilder.Append(value2);
DwmBase.WriteData(db, stringBuilder);
}
catch (Exception ex)
{
Logger.Trace("Caught exception saving host {0} uuid={1}", new object[]
{
base.Name,
base.Uuid
});
Logger.LogException(ex);
}
return;
}
throw new DwmException("Cannot pass null DBAccess instance to Save", DwmErrorCode.NullReference, null);
}
private StringBuilder SaveHostStorageRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._availableStorage != null && this._availableStorage.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._availableStorage.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_storage_repository (host_id, sr_id) select {0}, {1}\nwhere not exists (select id from hv_host_storage_repository where host_id={0} and sr_id={1});\n", base.Id, this._availableStorage[i].Id);
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._availableStorage[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0} and sr_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_storage_repository where host_id={0};\n", base.Id);
}
return stringBuilder;
}
private StringBuilder SaveHostVmRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listVMs != null && this._listVMs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listVMs.Count; i++)
{
stringBuilder.AppendFormat("select * from add_update_host_vm( {0}, {1}, '{2}');\n", base.Id, this._listVMs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listVMs[i].Id);
}
stringBuilder.AppendFormat("delete from host_vm where hostid={0} and vmid not in ({1});\nupdate host_vm_history set end_time='{2}' \nwhere host_id={0}\n and end_time is null\n and vm_id not in ({1});\n", base.Id, stringBuilder2.ToString(), Localization.DateTimeToSqlString(DateTime.UtcNow));
}
else
{
stringBuilder.AppendFormat("delete from host_vm where hostid={0};\nupdate host_vm_history set end_time='{1}' \nwhere host_id={0} and end_time is null;\n", base.Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
}
return stringBuilder;
}
private StringBuilder SaveHostPifRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listPIFs != null && this._listPIFs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listPIFs.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_pif (hostid, pif_id, tstamp) select {0}, {1},'{2}'\nwhere not exists (select id from hv_host_pif where hostid={0} and pif_id={1});\n", base.Id, this._listPIFs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPIFs[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0} and pif_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_pif where hostid={0};\n", base.Id);
}
return stringBuilder;
}
private StringBuilder SaveHostPbdRelationships()
{
StringBuilder stringBuilder = new StringBuilder();
if (this._listPBDs != null && this._listPBDs.Count > 0)
{
StringBuilder stringBuilder2 = new StringBuilder();
for (int i = 0; i < this._listPBDs.Count; i++)
{
stringBuilder.AppendFormat("insert into hv_host_pbd (hostid, pbd_id, tstamp) select {0}, {1}, '{2}'\nwhere not exists (select id from hv_host_pbd where hostid={0} and pbd_id={1});\n", base.Id, this._listPBDs[i].Id, Localization.DateTimeToSqlString(DateTime.UtcNow));
stringBuilder2.AppendFormat("{0}{1}", (i == 0) ? string.Empty : ",", this._listPBDs[i].Id);
}
stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0} and pbd_id not in ({1});\n", base.Id, stringBuilder2.ToString());
}
else
{
stringBuilder.AppendFormat("delete from hv_host_pbd where hostid={0};\n", base.Id);
}
return stringBuilder;
}
public void Load()
{
string sql = "load_host_by_id";
this.InternalLoad(sql, new StoredProcParamCollection
{
new StoredProcParam("@host_id", base.Id)
});
}
internal void SimpleLoad()
{
string sql = "load_host_simple_by_id";
this.InternalLoad(sql, new StoredProcParamCollection
{
new StoredProcParam("@host_id", base.Id)
});
}
private void InternalLoad(string sql, StoredProcParamCollection parms)
{
using (DBAccess dBAccess = new DBAccess())
{
dBAccess.UseTransaction = true;
using (IDataReader dataReader = dBAccess.ExecuteReader(sql, parms))
{
if (dataReader.Read())
{
if (string.IsNullOrEmpty(base.Uuid))
{
base.Uuid = DBAccess.GetString(dataReader, "uuid");
}
if (base.PoolId <= 0)
{
base.PoolId = DBAccess.GetInt(dataReader, "poolid");
}
base.Name = DBAccess.GetString(dataReader, "name");
base.Description = DBAccess.GetString(dataReader, "description");
this.NumCpus = DBAccess.GetInt(dataReader, "num_cpus");
this.CpuSpeed = DBAccess.GetInt(dataReader, "cpu_speed");
this.NumNics = DBAccess.GetInt(dataReader, "num_pifs");
this.IsPoolMaster = DBAccess.GetBool(dataReader, "is_pool_master");
this.Enabled = DBAccess.GetBool(dataReader, "enabled");
this.Metrics.FillOrder = DBAccess.GetInt(dataReader, "fill_order");
this.IPAddress = DBAccess.GetString(dataReader, "ip_address");
this.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead");
base.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status");
base.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result");
base.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time");
this.Metrics.TotalMemory = DBAccess.GetInt64(dataReader, "total_mem");
if (dataReader.NextResult())
{
while (dataReader.Read())
{
int @int = DBAccess.GetInt(dataReader, "hostid");
int int2 = DBAccess.GetInt(dataReader, "vmid");
string @string = DBAccess.GetString(dataReader, "name");
string string2 = DBAccess.GetString(dataReader, "uuid");
int int3 = DBAccess.GetInt(dataReader, "poolid");
DwmVirtualMachine dwmVirtualMachine = new DwmVirtualMachine(string2, @string, int3);
dwmVirtualMachine.Id = int2;
dwmVirtualMachine.Description = DBAccess.GetString(dataReader, "description");
dwmVirtualMachine.MinimumDynamicMemory = DBAccess.GetInt64(dataReader, "min_dynamic_memory");
dwmVirtualMachine.MaximumDynamicMemory = DBAccess.GetInt64(dataReader, "max_dynamic_memory");
dwmVirtualMachine.MinimumStaticMemory = DBAccess.GetInt64(dataReader, "min_static_memory");
dwmVirtualMachine.MaximumStaticMemory = DBAccess.GetInt64(dataReader, "max_static_memory");
dwmVirtualMachine.TargetMemory = DBAccess.GetInt64(dataReader, "target_memory");
dwmVirtualMachine.MemoryOverhead = DBAccess.GetInt64(dataReader, "memory_overhead");
dwmVirtualMachine.MinimumCpus = DBAccess.GetInt(dataReader, "min_cpus");
dwmVirtualMachine.HvMemoryMultiplier = DBAccess.GetDouble(dataReader, "hv_memory_multiplier");
dwmVirtualMachine.RequiredMemory = DBAccess.GetInt64(dataReader, "required_memory");
dwmVirtualMachine.IsControlDomain = DBAccess.GetBool(dataReader, "is_control_domain");
dwmVirtualMachine.IsAgile = DBAccess.GetBool(dataReader, "is_agile");
dwmVirtualMachine.DriversUpToDate = DBAccess.GetBool(dataReader, "drivers_up_to_date");
dwmVirtualMachine.Status = (DwmStatus)DBAccess.GetInt(dataReader, "status");
dwmVirtualMachine.LastResult = (DwmStatus)DBAccess.GetInt(dataReader, "last_result");
dwmVirtualMachine.LastResultTime = DBAccess.GetDateTime(dataReader, "last_result_time");
this.VirtualMachines.Add(dwmVirtualMachine);
}
}
}
}
}
}
public static DwmHost Load(string hostUuid, string poolUuid)
{
int poolId = DwmPoolBase.UuidToId(poolUuid);
int num = DwmHost.UuidToId(hostUuid, poolId);
if (num <= 0)
{
throw new DwmException("Invalid Host uuid", DwmErrorCode.InvalidParameter, null);
}
return DwmHost.Load(num);
}
public static DwmHost Load(int hostId)
{
if (hostId > 0)
{
DwmHost dwmHost = new DwmHost(hostId);
dwmHost.Load();
return dwmHost;
}
throw new DwmException("Invalid host ID", DwmErrorCode.InvalidParameter, null);
}
}
}
| Java |
#include "Converter.h"
#include <TFormula.h>
#include <iomanip>
#include <sstream>
std::string Converter::doubleToString(double x,int precision,bool scientifiStyle)
{
std::stringstream xs;
if(scientifiStyle)
xs<<std::scientific;
else
xs<<std::fixed;
xs<<std::setprecision(precision)<<x;
return xs.str();
};
std::string Converter::intToString(int x)
{
return doubleToString(x,0);
};
double Converter::stringToDouble(std::string formula)
{
TFormula myf("myf",formula.c_str());
return myf.Eval(0);
}
int Converter::stringToInt(std::string formula)
{
return (int)(stringToDouble(formula));
}
| Java |
#include <algorithm>
#include <bitset>
#include <cassert>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <deque>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <utility>
#include <vector>
// #pragma GCC optimize("Ofast")
// #pragma GCC optimize("inline")
// #pragma GCC optimize("-fgcse")
// #pragma GCC optimize("-fgcse-lm")
// #pragma GCC optimize("-fipa-sra")
// #pragma GCC optimize("-ftree-pre")
// #pragma GCC optimize("-ftree-vrp")
// #pragma GCC optimize("-fpeephole2")
// #pragma GCC optimize("-ffast-math")
// #pragma GCC optimize("-fsched-spec")
// #pragma GCC optimize("unroll-loops")
// #pragma GCC optimize("-falign-jumps")
// #pragma GCC optimize("-falign-loops")
// #pragma GCC optimize("-falign-labels")
// #pragma GCC optimize("-fdevirtualize")
// #pragma GCC optimize("-fcaller-saves")
// #pragma GCC optimize("-fcrossjumping")
// #pragma GCC optimize("-fthread-jumps")
// #pragma GCC optimize("-funroll-loops")
// #pragma GCC optimize("-fwhole-program")
// #pragma GCC optimize("-freorder-blocks")
// #pragma GCC optimize("-fschedule-insns")
// #pragma GCC optimize("inline-functions")
// #pragma GCC optimize("-ftree-tail-merge")
// #pragma GCC optimize("-fschedule-insns2")
// #pragma GCC optimize("-fstrict-aliasing")
// #pragma GCC optimize("-fstrict-overflow")
// #pragma GCC optimize("-falign-functions")
// #pragma GCC optimize("-fcse-skip-blocks")
// #pragma GCC optimize("-fcse-follow-jumps")
// #pragma GCC optimize("-fsched-interblock")
// #pragma GCC optimize("-fpartial-inlining")
// #pragma GCC optimize("no-stack-protector")
// #pragma GCC optimize("-freorder-functions")
// #pragma GCC optimize("-findirect-inlining")
// #pragma GCC optimize("-fhoist-adjacent-loads")
// #pragma GCC optimize("-frerun-cse-after-loop")
// #pragma GCC optimize("inline-small-functions")
// #pragma GCC optimize("-finline-small-functions")
// #pragma GCC optimize("-ftree-switch-conversion")
// #pragma GCC optimize("-foptimize-sibling-calls")
// #pragma GCC optimize("-fexpensive-optimizations")
// #pragma GCC optimize("-funsafe-loop-optimizations")
// #pragma GCC optimize("inline-functions-called-once")
// #pragma GCC optimize("-fdelete-null-pointer-checks")
#define rep(i, l, r) for (int i = (l); i <= (r); ++i)
#define per(i, l, r) for (int i = (l); i >= (r); --i)
using std::cerr;
using std::endl;
using std::make_pair;
using std::pair;
typedef pair<int, int> pii;
typedef long long ll;
typedef unsigned int ui;
typedef unsigned long long ull;
// #define DEBUG 1 //调试开关
struct IO {
#define MAXSIZE (1 << 20)
#define isdigit(x) (x >= '0' && x <= '9')
char buf[MAXSIZE], *p1, *p2;
char pbuf[MAXSIZE], *pp;
#if DEBUG
#else
IO() : p1(buf), p2(buf), pp(pbuf) {}
~IO() { fwrite(pbuf, 1, pp - pbuf, stdout); }
#endif
inline char gc() {
#if DEBUG //调试,可显示字符
return getchar();
#endif
if (p1 == p2) p2 = (p1 = buf) + fread(buf, 1, MAXSIZE, stdin);
return p1 == p2 ? -1 : *p1++;
}
inline bool blank(char ch) { return ch == ' ' || ch == '\n' || ch == '\r' || ch == '\t'; }
template <class T>
inline void read(T &x) {
register double tmp = 1;
register bool sign = 0;
x = 0;
register char ch = gc();
for (; !isdigit(ch); ch = gc())
if (ch == '-') sign = 1;
for (; isdigit(ch); ch = gc()) x = x * 10 + (ch - '0');
if (ch == '.')
for (ch = gc(); isdigit(ch); ch = gc()) tmp /= 10.0, x += tmp * (ch - '0');
if (sign) x = -x;
}
inline void read(char *s) {
register char ch = gc();
for (; blank(ch); ch = gc())
;
for (; !blank(ch); ch = gc()) *s++ = ch;
*s = 0;
}
inline void read(char &c) {
for (c = gc(); blank(c); c = gc())
;
}
inline void push(const char &c) {
#if DEBUG //调试,可显示字符
putchar(c);
#else
if (pp - pbuf == MAXSIZE) fwrite(pbuf, 1, MAXSIZE, stdout), pp = pbuf;
*pp++ = c;
#endif
}
template <class T>
inline void write(T x) {
if (x < 0) x = -x, push('-'); // 负数输出
static T sta[35];
T top = 0;
do {
sta[top++] = x % 10, x /= 10;
} while (x);
while (top) push(sta[--top] + '0');
}
inline void write(const char *s) {
while (*s != '\0') push(*(s++));
}
template <class T>
inline void write(T x, char lastChar) {
write(x), push(lastChar);
}
} io;
int a[510][510];
int main() {
#ifdef LOCAL
freopen("input", "r", stdin);
#endif
int n;
io.read(n);
rep(i, 1, n) {
rep(j, i + 1, n) {
io.read(a[i][j]);
a[j][i] = a[i][j];
}
}
int ans = 0;
rep(i, 1, n) {
std::sort(a[i] + 1, a[i] + 1 + n);
ans = std::max(ans, a[i][n - 1]);
}
io.write("1\n");
io.write(ans);
return 0;
} | Java |
<?
if (!defined("_GNUBOARD_")) exit; // °³º° ÆäÀÌÁö Á¢±Ù ºÒ°¡
if ($is_dhtml_editor) {
include_once("$g4[path]/lib/cheditor.lib.php");
echo "<script src='$g4[editor_path]/cheditor.js'></script>";
echo cheditor1('wr_content', $content);
}
?>
<script language="javascript">
// ±ÛÀÚ¼ö Á¦ÇÑ
var char_min = parseInt(<?=$write_min?>); // ÃÖ¼Ò
var char_max = parseInt(<?=$write_max?>); // ÃÖ´ë
</script>
<form name="fwrite" method="post" action="javascript:fwrite_check(document.fwrite);" enctype="multipart/form-data" style="margin:0px;">
<input type=hidden name=null>
<input type=hidden name=w value="<?=$w?>">
<input type=hidden name=bo_table value="<?=$bo_table?>">
<input type=hidden name=wr_id value="<?=$wr_id?>">
<input type=hidden name=sca value="<?=$sca?>">
<input type=hidden name=sfl value="<?=$sfl?>">
<input type=hidden name=stx value="<?=$stx?>">
<input type=hidden name=spt value="<?=$spt?>">
<input type=hidden name=sst value="<?=$sst?>">
<input type=hidden name=sod value="<?=$sod?>">
<input type=hidden name=page value="<?=$page?>">
<table width="<?=$width?>" align=center cellpadding=0 cellspacing=0><tr><td>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<colgroup width=100>
<colgroup width=''>
<tr><td colspan=2 height=2 bgcolor=#b0adf5></td></tr>
<tr><td style='padding-left:20px' colspan=2 height=38 bgcolor=#f8f8f9><strong><?=$title_msg?></strong></td></tr>
<? if ($is_name) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ À̸§</td>
<td><input class=ed maxlength=20 size=15 name=wr_name itemname="À̸§" required value="<?=$name?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_password) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ÆÐ½º¿öµå</td>
<td><input class=ed type=password maxlength=20 size=15 name=wr_password itemname="ÆÐ½º¿öµå" <?=$password_required?>></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_email) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ À̸ÞÀÏ</td>
<td><input class=ed maxlength=100 size=50 name=wr_email email itemname="À̸ÞÀÏ" value="<?=$email?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_homepage) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ȨÆäÀÌÁö</td>
<td><input class=ed size=50 name=wr_homepage itemname="ȨÆäÀÌÁö" value="<?=$homepage?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_notice || $is_html || $is_secret || $is_mail) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ¿É¼Ç</td>
<td><? if ($is_notice) { ?><input type=checkbox name=notice value="1" <?=$notice_checked?>>°øÁö <? } ?>
<? if ($is_html) { ?>
<? if ($is_dhtml_editor) { ?>
<input type=hidden value="html1" name="html">
<? } else { ?>
<input onclick="html_auto_br(this);" type=checkbox value="<?=$html_value?>" name="html" <?=$html_checked?>><span class=w_title>html</span>
<? } ?>
<? } ?>
<? if ($is_secret) { ?>
<? if ($is_admin || $is_secret==1) { ?>
<input type=checkbox value="secret" name="secret" <?=$secret_checked?>><span class=w_title>ºñ¹Ð±Û</span>
<? } else { ?>
<input type=hidden value="secret" name="secret">
<? } ?>
<? } ?>
<? if ($is_mail) { ?><input type=checkbox value="mail" name="mail" <?=$recv_email_checked?>>´äº¯¸ÞÀϹޱâ <? } ?></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_category) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ºÐ·ù</td>
<td><select name=ca_name required itemname="ºÐ·ù"><option value="">¼±ÅÃÇϼ¼¿ä<?=$category_option?></select></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ Á¦¸ñ</td>
<td><input class=ed style="width:100%;" name=wr_subject itemname="Á¦¸ñ" required value="<?=$subject?>"></td></tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<tr>
<td style='padding-left:20px;'>¡¤ ³»¿ë</td>
<td style='padding:5 0 5 0;'>
<? if ($is_dhtml_editor) { ?>
<?=cheditor2('fwrite', 'wr_content', '100%', '350');?>
<? } else { ?>
<table width=100% cellpadding=0 cellspacing=0>
<tr>
<td width=50% align=left valign=bottom>
<span style="cursor: pointer;" onclick="textarea_decrease('wr_content', 10);"><img src="<?=$board_skin_path?>/img/up.gif"></span>
<span style="cursor: pointer;" onclick="textarea_original('wr_content', 10);"><img src="<?=$board_skin_path?>/img/start.gif"></span>
<span style="cursor: pointer;" onclick="textarea_increase('wr_content', 10);"><img src="<?=$board_skin_path?>/img/down.gif"></span></td>
<td width=50% align=right><? if ($write_min || $write_max) { ?><span id=char_count></span>±ÛÀÚ<?}?></td>
</tr>
</table>
<textarea id=wr_content name=wr_content class=tx style='width:100%; word-break:break-all;' rows=10 itemname="³»¿ë" required
<? if ($write_min || $write_max) { ?>onkeyup="check_byte('wr_content', 'char_count');"<?}?>><?=$content?></textarea>
<? if ($write_min || $write_max) { ?><script language="javascript"> check_byte('wr_content', 'char_count'); </script><?}?>
<? } ?>
</td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? if ($is_link) { ?>
<? for ($i=1; $i<=$g4[link_count]; $i++) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ ¸µÅ© #<?=$i?></td>
<td><input type='text' class=ed size=50 name='wr_link<?=$i?>' itemname='¸µÅ© #<?=$i?>' value='<?=$write["wr_link{$i}"]?>'></td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? } ?>
<? if ($is_file) { ?>
<tr>
<td style='padding-left:20px; height:30px;'><table cellpadding=0 cellspacing=0><tr><td style=" padding-top: 10px;">¡¤ ÆÄÀÏ <span onclick="add_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>+</span> <span onclick="del_file();" style='cursor:pointer; font-family:tahoma; font-size:12pt;'>-</span></td></tr></table></td>
<td style='padding:5 0 5 0;'><table id="variableFiles" cellpadding=0 cellspacing=0></table><?// print_r2($file); ?>
<script language="JavaScript">
var flen = 0;
function add_file(delete_code)
{
var upload_count = <?=(int)$board[bo_upload_count]?>;
if (upload_count && flen >= upload_count)
{
alert("ÀÌ °Ô½ÃÆÇÀº "+upload_count+"°³ ±îÁö¸¸ ÆÄÀÏ ¾÷·Îµå°¡ °¡´ÉÇÕ´Ï´Ù.");
return;
}
var objTbl;
var objRow;
var objCell;
if (document.getElementById)
objTbl = document.getElementById("variableFiles");
else
objTbl = document.all["variableFiles"];
objRow = objTbl.insertRow(objTbl.rows.length);
objCell = objRow.insertCell(0);
objCell.innerHTML = "<input type='file' class=ed size=32 name='bf_file[]' title='ÆÄÀÏ ¿ë·® <?=$upload_max_filesize?> ÀÌÇϸ¸ ¾÷·Îµå °¡´É'>";
if (delete_code)
objCell.innerHTML += delete_code;
else
{
<? if ($is_file_content) { ?>
objCell.innerHTML += "<br><input type='text' class=ed size=50 name='bf_content[]' title='¾÷·Îµå À̹ÌÁö ÆÄÀÏ¿¡ ÇØ´ç µÇ´Â ³»¿ëÀ» ÀÔ·ÂÇϼ¼¿ä.'>";
<? } ?>
;
}
flen++;
}
<?=$file_script; //¼öÁ¤½Ã¿¡ ÇÊ¿äÇÑ ½ºÅ©¸³Æ®?>
function del_file()
{
// file_length ÀÌÇϷδ Çʵ尡 »èÁ¦µÇÁö ¾Ê¾Æ¾ß ÇÕ´Ï´Ù.
var file_length = <?=(int)$file_length?>;
var objTbl = document.getElementById("variableFiles");
if (objTbl.rows.length - 1 > file_length)
{
objTbl.deleteRow(objTbl.rows.length - 1);
flen--;
}
}
</script></td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_trackback) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ Æ®·¢¹éÁÖ¼Ò</td>
<td><input class=ed size=50 name=wr_trackback itemname="Æ®·¢¹é" value="<?=$trackback?>">
<? if ($w=="u") { ?><input type=checkbox name="re_trackback" value="1">ÇÎ º¸³¿<? } ?></td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<? if ($is_norobot) { ?>
<tr>
<td style='padding-left:20px; height:30px;'>¡¤ <?=$norobot_str?></td>
<td><input class=ed type=input size=10 name=wr_key itemname="ÀÚµ¿µî·Ï¹æÁö" required> * ¿ÞÂÊÀÇ ±ÛÀÚÁß <font color="red">»¡°£±ÛÀÚ¸¸</font> ¼ø¼´ë·Î ÀÔ·ÂÇϼ¼¿ä.</td>
</tr>
<tr><td colspan=2 height=1 bgcolor=#e7e7e7></td></tr>
<? } ?>
<tr><td colspan=2 height=1 bgcolor=#000000></td></tr>
</table>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" height="30" background="<?=$board_skin_path?>/img/write_down_bg.gif"></td>
</tr>
<tr>
<td width="100%" align="center" valign="top">
<input type=image id="btn_submit" src="<?=$board_skin_path?>/img/btn_write.gif" border=0 accesskey='s'>
<a href="./board.php?bo_table=<?=$bo_table?>"><img id="btn_list" src="<?=$board_skin_path?>/img/btn_list.gif" border=0></a></td>
</tr>
</table>
</td></tr></table>
</form>
<script language="javascript">
<?
// °ü¸®ÀÚ¶ó¸é ºÐ·ù ¼±Åÿ¡ '°øÁö' ¿É¼ÇÀ» Ãß°¡ÇÔ
if ($is_admin)
{
echo "
if (typeof(document.fwrite.ca_name) != 'undefined')
{
document.fwrite.ca_name.options.length += 1;
document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].value = '°øÁö';
document.fwrite.ca_name.options[document.fwrite.ca_name.options.length-1].text = '°øÁö';
}";
}
?>
with (document.fwrite) {
if (typeof(wr_name) != "undefined")
wr_name.focus();
else if (typeof(wr_subject) != "undefined")
wr_subject.focus();
else if (typeof(wr_content) != "undefined")
wr_content.focus();
if (typeof(ca_name) != "undefined")
if (w.value == "u")
ca_name.value = "<?=$write[ca_name]?>";
}
function html_auto_br(obj) {
if (obj.checked) {
result = confirm("ÀÚµ¿ ÁٹٲÞÀ» ÇϽðڽÀ´Ï±î?\n\nÀÚµ¿ ÁٹٲÞÀº °Ô½Ã¹° ³»¿ëÁß ÁÙ¹Ù²ï °÷À»<br>ű׷Πº¯È¯ÇÏ´Â ±â´ÉÀÔ´Ï´Ù.");
if (result)
obj.value = "html2";
else
obj.value = "html1";
}
else
obj.value = "";
}
function fwrite_check(f) {
var s = "";
if (s = word_filter_check(f.wr_subject.value)) {
alert("Á¦¸ñ¿¡ ±ÝÁö´Ü¾î('"+s+"')°¡ Æ÷ÇԵǾîÀÖ½À´Ï´Ù");
return;
}
if (s = word_filter_check(f.wr_content.value)) {
alert("³»¿ë¿¡ ±ÝÁö´Ü¾î('"+s+"')°¡ Æ÷ÇԵǾîÀÖ½À´Ï´Ù");
return;
}
if (char_min > 0 || char_max > 0) {
var cnt = parseInt(document.getElementById('char_count').innerHTML);
if (char_min > 0 && char_min > cnt) {
alert("³»¿ëÀº "+char_min+"±ÛÀÚ ÀÌ»ó ¾²¼Å¾ß ÇÕ´Ï´Ù.");
return;
}
else if (char_max > 0 && char_max < cnt) {
alert("³»¿ëÀº "+char_max+"±ÛÀÚ ÀÌÇÏ·Î ¾²¼Å¾ß ÇÕ´Ï´Ù.");
return;
}
}
if (typeof(f.wr_key) != "undefined") {
if (hex_md5(f.wr_key.value) != md5_norobot_key) {
alert("ÀÚµ¿µî·Ï¹æÁö¿ë »¡°£±ÛÀÚ°¡ ¼ø¼´ë·Î ÀԷµÇÁö ¾Ê¾Ò½À´Ï´Ù.");
f.wr_key.focus();
return;
}
}
<?
if ($is_dhtml_editor) {
echo cheditor3('wr_content');
echo "if (!document.getElementById('wr_content').value) { alert('³»¿ëÀ» ÀÔ·ÂÇϽʽÿÀ.'); return; } ";
}
?>
document.getElementById('btn_submit').disabled = true;
document.getElementById('btn_list').disabled = true;
f.action = "./write_update.php";
f.submit();
}
</script> | Java |
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: boss_lord_marrowgar
SD%Complete: 0%
SDComment:
SDCategory: Icecrown Citadel
EndScriptData */
#include "precompiled.h"
enum
{
SAY_INTRO = -1631001,
SAY_AGGRO = -1631002,
SAY_BONE_STORM = -1631003,
SAY_BONE_SPIKE_1 = -1631004,
SAY_BONE_SPIKE_2 = -1631005,
SAY_BONE_SPIKE_3 = -1631006,
SAY_SLAY_1 = -1631007,
SAY_SLAY_2 = -1631008,
SAY_DEATH = -1631009,
SAY_BERSERK = -1631010,
};
void AddSC_boss_lord_marrowgar()
{
}
| Java |
var wocs_loading_first_time = true;//simply flag var
jQuery(function () {
if (woocs_drop_down_view == 'chosen') {
try {
if (jQuery("select.woocommerce-currency-switcher").length) {
jQuery("select.woocommerce-currency-switcher").chosen({
disable_search_threshold: 10
});
jQuery.each(jQuery('.woocommerce-currency-switcher-form .chosen-container'), function (index, obj) {
jQuery(obj).css({'width': jQuery(this).prev('select').data('width')});
});
}
} catch (e) {
console.log(e);
}
}
if (woocs_drop_down_view == 'ddslick') {
try {
jQuery.each(jQuery('select.woocommerce-currency-switcher'), function (index, obj) {
var width = jQuery(obj).data('width');
var flag_position = jQuery(obj).data('flag-position');
jQuery(obj).ddslick({
//data: ddData,
width: width,
imagePosition: flag_position,
selectText: "Select currency",
//background:'#ff0000',
onSelected: function (data) {
if (!wocs_loading_first_time) {
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').find('input[name="woocommerce-currency-switcher"]').eq(0).val(data.selectedData.value);
jQuery(data.selectedItem).closest('form.woocommerce-currency-switcher-form').submit();
}
}
});
});
} catch (e) {
console.log(e);
}
}
//for flags view instead of drop-down
jQuery('.woocs_flag_view_item').click(function () {
if (jQuery(this).hasClass('woocs_flag_view_item_current')) {
return false;
}
//***
if (woocs_is_get_empty) {
window.location = window.location.href + '?currency=' + jQuery(this).data('currency');
} else {
var l = window.location.href;
l = l.replace(/(\?currency=[a-zA-Z]+)/g, '?');
l = l.replace(/(¤cy=[a-zA-Z]+)/g, '');
window.location = l + '¤cy=' + jQuery(this).data('currency');
}
return false;
});
wocs_loading_first_time = false;
});
| Java |
# -*- coding: utf-8 -*-
#
from rest_framework import viewsets
from rest_framework.exceptions import ValidationError
from django.db import transaction
from django.utils.translation import ugettext as _
from django.conf import settings
from orgs.mixins.api import RootOrgViewMixin
from common.permissions import IsValidUser
from perms.utils import AssetPermissionUtil
from ..models import CommandExecution
from ..serializers import CommandExecutionSerializer
from ..tasks import run_command_execution
class CommandExecutionViewSet(RootOrgViewMixin, viewsets.ModelViewSet):
serializer_class = CommandExecutionSerializer
permission_classes = (IsValidUser,)
def get_queryset(self):
return CommandExecution.objects.filter(
user_id=str(self.request.user.id)
)
def check_hosts(self, serializer):
data = serializer.validated_data
assets = data["hosts"]
system_user = data["run_as"]
util = AssetPermissionUtil(self.request.user)
util.filter_permissions(system_users=system_user.id)
permed_assets = util.get_assets().filter(id__in=[a.id for a in assets])
invalid_assets = set(assets) - set(permed_assets)
if invalid_assets:
msg = _("Not has host {} permission").format(
[str(a.id) for a in invalid_assets]
)
raise ValidationError({"hosts": msg})
def check_permissions(self, request):
if not settings.SECURITY_COMMAND_EXECUTION and request.user.is_common_user:
return self.permission_denied(request, "Command execution disabled")
return super().check_permissions(request)
def perform_create(self, serializer):
self.check_hosts(serializer)
instance = serializer.save()
instance.user = self.request.user
instance.save()
cols = self.request.query_params.get("cols", '80')
rows = self.request.query_params.get("rows", '24')
transaction.on_commit(lambda: run_command_execution.apply_async(
args=(instance.id,), kwargs={"cols": cols, "rows": rows},
task_id=str(instance.id)
))
| Java |
package main
import (
"bytes"
"fmt"
"regexp"
)
func main() {
match, _ := regexp.MatchString("p([a-z]+)ch", "peach")
fmt.Println(match)
r, _ := regexp.Compile("p([a-z]+)ch")
fmt.Println(r.MatchString("peach"))
fmt.Println(r.FindString("peach punch"))
fmt.Println(r.FindStringIndex("peach punch"))
fmt.Println(r.FindStringSubmatch("peach punch"))
fmt.Println(r.FindStringSubmatchIndex("peach punch"))
fmt.Println(r.FindAllString("peach punch pinch", -1))
fmt.Println(r.FindAllStringSubmatchIndex("peach punch pinch", -1))
fmt.Println(r.FindAllString("peach punch pinch", 2))
fmt.Println(r.Match([]byte("peach")))
r = regexp.MustCompile("p([a+z])ch")
fmt.Println(r)
fmt.Println(r.ReplaceAllString("a peach", "<fruit>"))
in := []byte("a peach")
out := r.ReplaceAllFunc(in, bytes.ToUpper)
fmt.Println(string(out))
}
| Java |
<?php
namespace Sidus\EAVDataGridBundle\Model;
use Sidus\DataGridBundle\Model\DataGrid as BaseDataGrid;
use Sidus\EAVFilterBundle\Configuration\EAVFilterConfigurationHandler;
use Sidus\EAVModelBundle\Model\FamilyInterface;
use Sidus\EAVModelBundle\Translator\TranslatableTrait;
use Symfony\Component\Translation\TranslatorInterface;
/**
* Extended datagrid configuration for EAV entities
*/
class DataGrid extends BaseDataGrid
{
use TranslatableTrait;
/** @var FamilyInterface */
protected $family;
/**
* DataGrid constructor.
*
* @param string $code
* @param array $configuration
* @param TranslatorInterface $translator
*
* @throws \Exception
*/
public function __construct($code, array $configuration, TranslatorInterface $translator = null)
{
$this->translator = $translator;
parent::__construct($code, $configuration);
}
/**
* @return FamilyInterface
*/
public function getFamily()
{
return $this->family;
}
/**
* @param FamilyInterface $family
*
* @return DataGrid
*/
public function setFamily($family)
{
$this->family = $family;
$filterConfig = $this->getFilterConfig();
if ($filterConfig instanceof EAVFilterConfigurationHandler) {
$filterConfig->setFamily($family);
}
return $this;
}
/**
* @param string $key
* @param array $columnConfiguration
*
* @throws \Exception
*/
protected function createColumn($key, array $columnConfiguration)
{
if ($this->translator) {
$columnConfiguration['translator'] = $this->translator;
}
$this->columns[] = new Column($key, $this, $columnConfiguration);
}
}
| Java |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Struct template is_interval_container<icl::interval_set< DomainT, Compare, Interval, Alloc >></title>
<link rel="stylesheet" href="../../../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.79.1">
<link rel="home" href="../../index.html" title="Chapter 1. Boost.Icl">
<link rel="up" href="../../header/boost/icl/interval_set_hpp.html" title="Header <boost/icl/interval_set.hpp>">
<link rel="prev" href="is_set_i_idm44994781476752.html" title="Struct template is_set<icl::interval_set< DomainT, Compare, Interval, Alloc >>">
<link rel="next" href="is_inter_idm44994781457776.html" title="Struct template is_interval_joiner<icl::interval_set< DomainT, Compare, Interval, Alloc >>">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../../../boost.png"></td>
<td align="center"><a href="../../../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../../libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="is_set_i_idm44994781476752.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/icl/interval_set_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="is_inter_idm44994781457776.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
<div class="refentry">
<a name="boost.icl.is_inter_idm44994781467264"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template is_interval_container<icl::interval_set< DomainT, Compare, Interval, Alloc >></span></h2>
<p>boost::icl::is_interval_container<icl::interval_set< DomainT, Compare, Interval, Alloc >></p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: <<a class="link" href="../../header/boost/icl/interval_set_hpp.html" title="Header <boost/icl/interval_set.hpp>">boost/icl/interval_set.hpp</a>>
</span><span class="keyword">template</span><span class="special"><</span><span class="keyword">typename</span> DomainT<span class="special">,</span> <span class="identifier">ICL_COMPARE</span> Compare<span class="special">,</span>
<span class="identifier">ICL_INTERVAL</span><span class="special">(</span><span class="identifier">ICL_COMPARE</span><span class="special">)</span> Interval<span class="special">,</span> <span class="identifier">ICL_ALLOC</span> Alloc<span class="special">></span>
<span class="keyword">struct</span> <a class="link" href="is_inter_idm44994781467264.html" title="Struct template is_interval_container<icl::interval_set< DomainT, Compare, Interval, Alloc >>">is_interval_container</a><span class="special"><</span><span class="identifier">icl</span><span class="special">::</span><span class="identifier">interval_set</span><span class="special"><</span> <span class="identifier">DomainT</span><span class="special">,</span> <span class="identifier">Compare</span><span class="special">,</span> <span class="identifier">Interval</span><span class="special">,</span> <span class="identifier">Alloc</span> <span class="special">></span><span class="special">></span> <span class="special">{</span>
<span class="comment">// types</span>
<span class="keyword">typedef</span> <span class="identifier">is_interval_container</span><span class="special"><</span> <a class="link" href="interval_set.html" title="Class template interval_set">icl::interval_set</a><span class="special"><</span> <span class="identifier">DomainT</span><span class="special">,</span> <span class="identifier">Compare</span><span class="special">,</span> <span class="identifier">Interval</span><span class="special">,</span> <span class="identifier">Alloc</span> <span class="special">></span> <span class="special">></span> <a name="boost.icl.is_inter_idm44994781467264.type"></a><span class="identifier">type</span><span class="special">;</span>
<span class="comment">// <a class="link" href="is_inter_idm44994781467264.html#idm44994781460848-bb">public member functions</a></span>
<a class="link" href="is_inter_idm44994781467264.html#idm44994781460288-bb"><span class="identifier">BOOST_STATIC_CONSTANT</span></a><span class="special">(</span><span class="keyword">bool</span><span class="special">,</span> <span class="identifier">value</span> <span class="special">=</span> <span class="keyword">true</span><span class="special">)</span><span class="special">;</span>
<span class="special">}</span><span class="special">;</span></pre></div>
<div class="refsect1">
<a name="idm46161810876816"></a><h2>Description</h2>
<div class="refsect2">
<a name="idm46161810876400"></a><h3>
<a name="idm44994781460848-bb"></a><code class="computeroutput">is_interval_container</code> public member functions</h3>
<div class="orderedlist"><ol class="orderedlist" type="1"><li class="listitem"><pre class="literallayout"> <a name="idm44994781460288-bb"></a><span class="identifier">BOOST_STATIC_CONSTANT</span><span class="special">(</span><span class="keyword">bool</span><span class="special">,</span> <span class="identifier">value</span> <span class="special">=</span> <span class="keyword">true</span><span class="special">)</span><span class="special">;</span></pre></li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007-2010 Joachim
Faulhaber<br>Copyright © 1999-2006 Cortex Software
GmbH<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="is_set_i_idm44994781476752.html"><img src="../../../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../header/boost/icl/interval_set_hpp.html"><img src="../../../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="is_inter_idm44994781457776.html"><img src="../../../../../../doc/src/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>food blogging | Introduction to New Media</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="shortcut icon" href="../../misc/favicon.ico" type="image/x-icon" />
<style type="text/css" media="all">@import "../../modules/node/node.css";</style>
<style type="text/css" media="all">@import "../../modules/poll/poll.css";</style>
<style type="text/css" media="all">@import "../../modules/system/defaults.css";</style>
<style type="text/css" media="all">@import "../../modules/system/system.css";</style>
<style type="text/css" media="all">@import "../../modules/user/user.css";</style>
<style type="text/css" media="all">@import "../../sites/all/modules/tagadelic/tagadelic.css";</style>
<style type="text/css" media="all">@import "../../modules/comment/comment.css";</style>
<style type="text/css" media="all">@import "../../sites/all/themes/newmedia/style.css";</style>
<!--[if IE 6]>
<style type="text/css" media="all">@import "../../sites/all/themes/newmedia/ie-fixes/ie6.css";</style>
<![endif]-->
<!--[if lt IE 7.]>
<script defer type="text/javascript" src="../../sites/all/themes/newmedia/ie-fixes/pngfix.js"></script>
<![endif]-->
</head>
<body>
<div id="page">
<!-- begin wrapper -->
<div id="container">
<!-- primary links -->
<!-- begin header -->
<div id="header">
<!-- site logo -->
<!-- end site logo -->
<!-- site name -->
<h1>
<a href="../../index.html" title="Home">
Introduction to New Media </a>
</h1>
<!-- end site name -->
<!-- site slogan -->
<!-- end site slogan -->
<div id="menu">
<ul class="links-menu">
<li><a href="http://machines.plannedobsolescence.net" title="associate professor of english and media studies">kathleen fitzpatrick</a></li>
<li><a href="http://www.pomona.edu" title="in claremont, california">pomona college</a></li>
</ul> </div><!-- end primary links -->
</div><!-- end header -->
<!-- search box in nowhere land - NEEDS WORK-->
<!-- end search box -->
<!-- content -->
<!-- <div id="main">-->
<!-- begin main content -->
<div id="mainContent" style="width: 530px;">
<div class="breadcrumb"><div class="breadcrumb"><a href="../../index.html">Home</a> » <a href="../../blog/index.html">Blogs</a> » <a href="../../blog/17/index.html">ColoradoGirl's blog</a></div></div> <h1 class="pageTitle">food blogging</h1> <div class="node">
<div class="submitted">By ColoradoGirl - Posted on 4 February 2007 - 2:06pm.</div>
<div class="taxonomy">Tagged: <ul class="links inline"><li class="first taxonomy_term_2"><a href="../../taxonomy/term/2/index.html" rel="tag" title="" class="taxonomy_term_2">blogging</a></li>
<li class="last taxonomy_term_39"><a href="../../taxonomy/term/39/index.html" rel="tag" title="" class="taxonomy_term_39">food critics</a></li>
</ul></div> <div class="content"><p>I love to eat. Ok, let me clarify that – I love to eat good food. Today while savoring the Sunday NY Times Style section, I saw an article of blogging interest, <a href="http://www.nytimes.com/2007/02/04/fashion/04bloggers.html?_r=1&oref=slogin"> Sharp Bites.</a> Exploring how restaurant critics (or the more likely case on blogs, people like me who just love to eat out and sample new venues) are blogging their way into internet fame; "hundreds of thousands of hits" it what one blog got after it started posting a comical <a href="http://www.amateurgourmet.com/the_amateur_gourmet/2004/02/janet_jackson_b.html"> recipe </a> for cupcakes that resembled Janet Jackson's bare breast at the Super Bowl. </p>
<p>I am interested in how the blogs critiquing food and restaurants are able to be more open, more honest, and more vicious (??) with their comments. We talked about the emergence of more opinionated political writing in the blogosphere, and I think you'll agree with me that food critiques on blogs are la même chose. </p>
<p>What does this upsurge in food bloggers do to reputation of restaurants? I recently dined at a hole-in-the wall sushi place outside L.A. . . . I consider myself to be a sushi expert (having traveled to Japan and consumed mass amounts of the delicious food there and at good sushi joints elsewhere) and what I tasted at this particular restaurant was absolutely sickening. However, a blog I found congratulated this very restaurant on serving "sushi that even sushi haters will love." Hmmm, where's the truth there?!</p>
</div>
<div class="links"><ul class="links inline"><li class="first last blog_usernames_blog"><a href="../../blog/17/index.html" title="Read ColoradoGirl's latest blog entries." class="blog_usernames_blog">ColoradoGirl's blog</a></li>
</ul></div> </div>
<div id="comments"><a id="comment-38"></a>
<div class="comment">
<div class="commentTitle"><a href="index.html#comment-38" class="active">Not Only Good But Healthy</a></div>
<div class="submitted">Submitted by Bumpkins on 4 February 2007 - 7:14pm.</div>
<div class="content"><p><a href="http://www.tsl.pomona.edu/index.php?article=2071">See</a>.</p>
<p>- If this takes away your anonymity feel free to delete it.</p>
</div>
<div class="links"></div>
</div>
</div>
</div>
<!-- Begin Sidebars -->
<div id="sideBars-bg" style="width: 415px;">
<div id="sideBars" style="width: 415px;">
<!-- left sidebar -->
<div id="leftSidebar">
<div class="block block-block" id="block-block-1">
<h2 class="title"></h2>
<div class="content"><p><a href="../../index.html">introduction to new media</a> is the spring 2007 course website for media studies 51 at pomona college in claremont, california.</p>
<p><a href="http://machines.plannedobsolescence.net">the professor</a><br />
<a href="../../syllabus/index.html">the syllabus</a><br />
<a href="../../wiki/index.html">the wiki</a><br />
<a href="https://sakai.claremont.edu/portal/site/CX_mtg_26747">the sakai site</a><br />
<a href="../../taxonomy/term/1/index.html">more information</a></p>
</div>
</div>
<div class="block block-tagadelic" id="block-tagadelic-1">
<h2 class="title">tags</h2>
<div class="content"><a href="../../taxonomy/term/56/index.html" class="tagadelic level2" rel="tag">Artificial Intelligence</a>
<a href="../../taxonomy/term/14/index.html" class="tagadelic level2" rel="tag">blog</a>
<a href="../../taxonomy/term/2/index.html" class="tagadelic level10" rel="tag">blogging</a>
<a href="../../taxonomy/term/42/index.html" class="tagadelic level8" rel="tag">class discussion</a>
<a href="../../taxonomy/term/4/index.html" class="tagadelic level10" rel="tag">class reading</a>
<a href="../../taxonomy/term/8/index.html" class="tagadelic level1" rel="tag">community</a>
<a href="../../taxonomy/term/1/index.html" class="tagadelic level2" rel="tag">course information</a>
<a href="../../taxonomy/term/106/index.html" class="tagadelic level2" rel="tag">cyborg</a>
<a href="../../taxonomy/term/77/index.html" class="tagadelic level3" rel="tag">Facade</a>
<a href="../../taxonomy/term/119/index.html" class="tagadelic level3" rel="tag">final project</a>
<a href="../../taxonomy/term/7/index.html" class="tagadelic level3" rel="tag">first blog</a>
<a href="../../taxonomy/term/36/index.html" class="tagadelic level2" rel="tag">Future</a>
<a href="../../taxonomy/term/64/index.html" class="tagadelic level2" rel="tag">Machines</a>
<a href="../../taxonomy/term/79/index.html" class="tagadelic level2" rel="tag">midterm project</a>
<a href="../../taxonomy/term/13/index.html" class="tagadelic level1" rel="tag">Music</a>
<a href="../../taxonomy/term/20/index.html" class="tagadelic level3" rel="tag">new generation</a>
<a href="../../taxonomy/term/31/index.html" class="tagadelic level6" rel="tag">new media</a>
<a href="../../taxonomy/term/70/index.html" class="tagadelic level8" rel="tag">Proposal</a>
<a href="../../taxonomy/term/112/index.html" class="tagadelic level2" rel="tag">sight machine</a>
<a href="../../taxonomy/term/22/index.html" class="tagadelic level2" rel="tag">social networking</a>
<a href="../../taxonomy/term/98/index.html" class="tagadelic level7" rel="tag">term project</a>
<a href="../../taxonomy/term/19/index.html" class="tagadelic level7" rel="tag">web 2.0</a>
<a href="../../taxonomy/term/24/index.html" class="tagadelic level8" rel="tag">wiki</a>
<a href="../../taxonomy/term/18/index.html" class="tagadelic level6" rel="tag">Wikipedia</a>
<a href="../../taxonomy/term/34/index.html" class="tagadelic level6" rel="tag">YouTube</a>
<div class='more-link'><a href="../../tagadelic/chunk/1/index.html">more tags</a></div></div>
</div>
<div class="block block-user" id="block-user-1">
<h2 class="title">Navigation</h2>
<div class="content">
<ul class="menu">
<li class="leaf"><a href="../../tracker/index.html">Recent posts</a></li>
</ul>
</div>
</div>
</div>
<!-- right sidebar -->
<div id="rightSidebar">
<div class="block block-comment" id="block-comment-0">
<h2 class="title">Recent comments</h2>
<div class="content"><div class="item-list"><ul><li><a href="../247/index.html#comment-440">resistance</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-439">20 hours of source</a><br />3 years 51 weeks ago</li><li><a href="../262/index.html#comment-438">used?</a><br />3 years 51 weeks ago</li><li><a href="../261/index.html#comment-437">it's everywhere</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-436">Really good! I liked how you</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-435">nice!</a><br />3 years 51 weeks ago</li><li><a href="../251/index.html#comment-434">Linux Parody</a><br />3 years 51 weeks ago</li><li><a href="../259/index.html#comment-433">Me Too!</a><br />3 years 51 weeks ago</li><li><a href="../261/index.html#comment-432">McDonald's</a><br />3 years 51 weeks ago</li><li><a href="../264/index.html#comment-431">Slash Fan Vid</a><br />3 years 51 weeks ago</li></ul></div></div>
</div>
<div class="block block-block" id="block-block-2">
<h2 class="title"></h2>
<div class="content"><h3>social software tools</h3>
<ul>
<li><a href="http://technorati.com/" target="_blank">Technorati</a></li>
<li><a href="http://del.icio.us/" target="_blank">del.icio.us</a></li>
<li><a href="http://www.flickr.com/" target="_blank">Flickr</a></li>
<li><a href="http://www.bloglines.com/" target="_blank">Bloglines</a></li>
<li><a href="http://www.youtube.com/" target="_blank">YouTube</a></li>
</ul>
<h3>new media studies sites</h3>
<ul>
<li><a href="http://www.digitalhumanities.org/companion/" target="_blank">A Companion to Digital Humanities</a></li>
</ul>
</div>
</div>
</div>
</div><!-- end sidebars -->
</div><!-- end sideBars-bg -->
<!-- footer -->
<div id="footer">
</div><!-- end footer -->
</div><!-- end container -->
</div><!-- end page -->
<!-- Start of StatCounter Code -->
<script type="text/javascript">
var sc_project=3034095;
var sc_invisible=1;
var sc_partition=33;
var sc_security="ec028fa0";
</script>
<script type="text/javascript" src="http://www.statcounter.com/counter/counter_xhtml.js"></script><noscript><div class="statcounter"><a class="statcounter" href="http://www.statcounter.com/"><img class="statcounter" src="http://c34.statcounter.com/3034095/0/ec028fa0/1/" alt="blog stats" /></a></div></noscript>
<!-- End of StatCounter Code -->
</body>
</html>
<!-- Localized --> | Java |
CREATE USER 'iasst'@'localhost' IDENTIFIED BY '123456';
GRANT SELECT ON *.* TO 'iasst'@'localhost';
GRANT SELECT, INSERT, UPDATE, REFERENCES, DELETE, CREATE, DROP, ALTER, INDEX, TRIGGER, CREATE VIEW, SHOW VIEW, EXECUTE, ALTER ROUTINE, CREATE ROUTINE, CREATE TEMPORARY TABLES, LOCK TABLES, EVENT ON `iasst`.* TO 'iasst'@'localhost';
GRANT GRANT OPTION ON `iasst`.* TO 'iasst'@'localhost'; | Java |
/*
MobileRobots Advanced Robotics Interface for Applications (ARIA)
Copyright (C) 2004, 2005 ActivMedia Robotics LLC
Copyright (C) 2006, 2007, 2008, 2009 MobileRobots Inc.
Copyright (C) 2010, 2011 Adept Technology, Inc.
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
If you wish to redistribute ARIA under different terms, contact
Adept MobileRobots for information about a commercial version of ARIA at
robots@mobilerobots.com or
Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; 800-639-9481
*/
/* ----------------------------------------------------------------------------
* This file was automatically generated by SWIG (http://www.swig.org).
* Version 1.3.36
*
* Do not make changes to this file unless you know what you are doing--modify
* the SWIG interface file instead.
* ----------------------------------------------------------------------------- */
package com.mobilerobots.Aria;
public class ArDPPTU extends ArPTZ {
/* (begin code from javabody_derived typemap) */
private long swigCPtr;
/* for internal use by swig only */
public ArDPPTU(long cPtr, boolean cMemoryOwn) {
super(AriaJavaJNI.SWIGArDPPTUUpcast(cPtr), cMemoryOwn);
swigCPtr = cPtr;
}
/* for internal use by swig only */
public static long getCPtr(ArDPPTU obj) {
return (obj == null) ? 0 : obj.swigCPtr;
}
/* (end code from javabody_derived typemap) */
protected void finalize() {
delete();
}
public synchronized void delete() {
if(swigCPtr != 0 && swigCMemOwn) {
swigCMemOwn = false;
AriaJavaJNI.delete_ArDPPTU(swigCPtr);
}
swigCPtr = 0;
super.delete();
}
public ArDPPTU(ArRobot robot, ArDPPTU.DeviceType deviceType) {
this(AriaJavaJNI.new_ArDPPTU__SWIG_0(ArRobot.getCPtr(robot), robot, deviceType.swigValue()), true);
}
public ArDPPTU(ArRobot robot) {
this(AriaJavaJNI.new_ArDPPTU__SWIG_1(ArRobot.getCPtr(robot), robot), true);
}
public boolean init() {
return AriaJavaJNI.ArDPPTU_init(swigCPtr, this);
}
public boolean canZoom() {
return AriaJavaJNI.ArDPPTU_canZoom(swigCPtr, this);
}
public boolean blank() {
return AriaJavaJNI.ArDPPTU_blank(swigCPtr, this);
}
public boolean resetCalib() {
return AriaJavaJNI.ArDPPTU_resetCalib(swigCPtr, this);
}
public boolean disableReset() {
return AriaJavaJNI.ArDPPTU_disableReset(swigCPtr, this);
}
public boolean resetTilt() {
return AriaJavaJNI.ArDPPTU_resetTilt(swigCPtr, this);
}
public boolean resetPan() {
return AriaJavaJNI.ArDPPTU_resetPan(swigCPtr, this);
}
public boolean resetAll() {
return AriaJavaJNI.ArDPPTU_resetAll(swigCPtr, this);
}
public boolean saveSet() {
return AriaJavaJNI.ArDPPTU_saveSet(swigCPtr, this);
}
public boolean restoreSet() {
return AriaJavaJNI.ArDPPTU_restoreSet(swigCPtr, this);
}
public boolean factorySet() {
return AriaJavaJNI.ArDPPTU_factorySet(swigCPtr, this);
}
public boolean panTilt(double pdeg, double tdeg) {
return AriaJavaJNI.ArDPPTU_panTilt(swigCPtr, this, pdeg, tdeg);
}
public boolean pan(double deg) {
return AriaJavaJNI.ArDPPTU_pan(swigCPtr, this, deg);
}
public boolean panRel(double deg) {
return AriaJavaJNI.ArDPPTU_panRel(swigCPtr, this, deg);
}
public boolean tilt(double deg) {
return AriaJavaJNI.ArDPPTU_tilt(swigCPtr, this, deg);
}
public boolean tiltRel(double deg) {
return AriaJavaJNI.ArDPPTU_tiltRel(swigCPtr, this, deg);
}
public boolean panTiltRel(double pdeg, double tdeg) {
return AriaJavaJNI.ArDPPTU_panTiltRel(swigCPtr, this, pdeg, tdeg);
}
public boolean limitEnforce(boolean val) {
return AriaJavaJNI.ArDPPTU_limitEnforce(swigCPtr, this, val);
}
public boolean immedExec() {
return AriaJavaJNI.ArDPPTU_immedExec(swigCPtr, this);
}
public boolean slaveExec() {
return AriaJavaJNI.ArDPPTU_slaveExec(swigCPtr, this);
}
public boolean awaitExec() {
return AriaJavaJNI.ArDPPTU_awaitExec(swigCPtr, this);
}
public boolean haltAll() {
return AriaJavaJNI.ArDPPTU_haltAll(swigCPtr, this);
}
public boolean haltPan() {
return AriaJavaJNI.ArDPPTU_haltPan(swigCPtr, this);
}
public boolean haltTilt() {
return AriaJavaJNI.ArDPPTU_haltTilt(swigCPtr, this);
}
public double getMaxPosPan() {
return AriaJavaJNI.ArDPPTU_getMaxPosPan(swigCPtr, this);
}
public double getMaxNegPan() {
return AriaJavaJNI.ArDPPTU_getMaxNegPan(swigCPtr, this);
}
public double getMaxPosTilt() {
return AriaJavaJNI.ArDPPTU_getMaxPosTilt(swigCPtr, this);
}
public double getMaxNegTilt() {
return AriaJavaJNI.ArDPPTU_getMaxNegTilt(swigCPtr, this);
}
public double getMaxPanSlew() {
return AriaJavaJNI.ArDPPTU_getMaxPanSlew(swigCPtr, this);
}
public double getMinPanSlew() {
return AriaJavaJNI.ArDPPTU_getMinPanSlew(swigCPtr, this);
}
public double getMaxTiltSlew() {
return AriaJavaJNI.ArDPPTU_getMaxTiltSlew(swigCPtr, this);
}
public double getMinTiltSlew() {
return AriaJavaJNI.ArDPPTU_getMinTiltSlew(swigCPtr, this);
}
public double getMaxPanAccel() {
return AriaJavaJNI.ArDPPTU_getMaxPanAccel(swigCPtr, this);
}
public double getMinPanAccel() {
return AriaJavaJNI.ArDPPTU_getMinPanAccel(swigCPtr, this);
}
public double getMaxTiltAccel() {
return AriaJavaJNI.ArDPPTU_getMaxTiltAccel(swigCPtr, this);
}
public double getMinTiltAccel() {
return AriaJavaJNI.ArDPPTU_getMinTiltAccel(swigCPtr, this);
}
public boolean initMon(double deg1, double deg2, double deg3, double deg4) {
return AriaJavaJNI.ArDPPTU_initMon(swigCPtr, this, deg1, deg2, deg3, deg4);
}
public boolean enMon() {
return AriaJavaJNI.ArDPPTU_enMon(swigCPtr, this);
}
public boolean disMon() {
return AriaJavaJNI.ArDPPTU_disMon(swigCPtr, this);
}
public boolean offStatPower() {
return AriaJavaJNI.ArDPPTU_offStatPower(swigCPtr, this);
}
public boolean regStatPower() {
return AriaJavaJNI.ArDPPTU_regStatPower(swigCPtr, this);
}
public boolean lowStatPower() {
return AriaJavaJNI.ArDPPTU_lowStatPower(swigCPtr, this);
}
public boolean highMotPower() {
return AriaJavaJNI.ArDPPTU_highMotPower(swigCPtr, this);
}
public boolean regMotPower() {
return AriaJavaJNI.ArDPPTU_regMotPower(swigCPtr, this);
}
public boolean lowMotPower() {
return AriaJavaJNI.ArDPPTU_lowMotPower(swigCPtr, this);
}
public boolean panAccel(double deg) {
return AriaJavaJNI.ArDPPTU_panAccel(swigCPtr, this, deg);
}
public boolean tiltAccel(double deg) {
return AriaJavaJNI.ArDPPTU_tiltAccel(swigCPtr, this, deg);
}
public boolean basePanSlew(double deg) {
return AriaJavaJNI.ArDPPTU_basePanSlew(swigCPtr, this, deg);
}
public boolean baseTiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_baseTiltSlew(swigCPtr, this, deg);
}
public boolean upperPanSlew(double deg) {
return AriaJavaJNI.ArDPPTU_upperPanSlew(swigCPtr, this, deg);
}
public boolean lowerPanSlew(double deg) {
return AriaJavaJNI.ArDPPTU_lowerPanSlew(swigCPtr, this, deg);
}
public boolean upperTiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_upperTiltSlew(swigCPtr, this, deg);
}
public boolean lowerTiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_lowerTiltSlew(swigCPtr, this, deg);
}
public boolean indepMove() {
return AriaJavaJNI.ArDPPTU_indepMove(swigCPtr, this);
}
public boolean velMove() {
return AriaJavaJNI.ArDPPTU_velMove(swigCPtr, this);
}
public boolean panSlew(double deg) {
return AriaJavaJNI.ArDPPTU_panSlew(swigCPtr, this, deg);
}
public boolean tiltSlew(double deg) {
return AriaJavaJNI.ArDPPTU_tiltSlew(swigCPtr, this, deg);
}
public boolean panSlewRel(double deg) {
return AriaJavaJNI.ArDPPTU_panSlewRel(swigCPtr, this, deg);
}
public boolean tiltSlewRel(double deg) {
return AriaJavaJNI.ArDPPTU_tiltSlewRel(swigCPtr, this, deg);
}
public double getPan() {
return AriaJavaJNI.ArDPPTU_getPan(swigCPtr, this);
}
public double getTilt() {
return AriaJavaJNI.ArDPPTU_getTilt(swigCPtr, this);
}
public double getPanSlew() {
return AriaJavaJNI.ArDPPTU_getPanSlew(swigCPtr, this);
}
public double getTiltSlew() {
return AriaJavaJNI.ArDPPTU_getTiltSlew(swigCPtr, this);
}
public double getBasePanSlew() {
return AriaJavaJNI.ArDPPTU_getBasePanSlew(swigCPtr, this);
}
public double getBaseTiltSlew() {
return AriaJavaJNI.ArDPPTU_getBaseTiltSlew(swigCPtr, this);
}
public double getPanAccel() {
return AriaJavaJNI.ArDPPTU_getPanAccel(swigCPtr, this);
}
public double getTiltAccel() {
return AriaJavaJNI.ArDPPTU_getTiltAccel(swigCPtr, this);
}
public final static class DeviceType {
public final static DeviceType PANTILT_DEFAULT = new DeviceType("PANTILT_DEFAULT");
public final static DeviceType PANTILT_PTUD47 = new DeviceType("PANTILT_PTUD47");
public final int swigValue() {
return swigValue;
}
public String toString() {
return swigName;
}
public static DeviceType swigToEnum(int swigValue) {
if (swigValue < swigValues.length && swigValue >= 0 && swigValues[swigValue].swigValue == swigValue)
return swigValues[swigValue];
for (int i = 0; i < swigValues.length; i++)
if (swigValues[i].swigValue == swigValue)
return swigValues[i];
throw new IllegalArgumentException("No enum " + DeviceType.class + " with value " + swigValue);
}
private DeviceType(String swigName) {
this.swigName = swigName;
this.swigValue = swigNext++;
}
private DeviceType(String swigName, int swigValue) {
this.swigName = swigName;
this.swigValue = swigValue;
swigNext = swigValue+1;
}
private DeviceType(String swigName, DeviceType swigEnum) {
this.swigName = swigName;
this.swigValue = swigEnum.swigValue;
swigNext = this.swigValue+1;
}
private static DeviceType[] swigValues = { PANTILT_DEFAULT, PANTILT_PTUD47 };
private static int swigNext = 0;
private final int swigValue;
private final String swigName;
}
}
| Java |
<?php
/**********************************************************************************
*
* #####
* # # ##### ## ##### # # #### ###### # # #### # # # ######
* # # # # # # # # # ## # # # # ## # #
* ##### # # # # # # #### ##### # # # # # # # # #####
* # # ###### # # # # # # # # # ### # # # # #
* # # # # # # # # # # # # ## # # # # ## #
* ##### # # # # #### #### ###### # # #### # # # ######
*
* the missing event broker
* Perfdata Backend Extension for Rrdtool
*
* --------------------------------------------------------------------------------
*
* Copyright (c) 2014 - present Daniel Ziegler <daniel@statusengine.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 in version 2
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 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.
*
* --------------------------------------------------------------------------------
*
* This extension for statusengine uses the parsed performance data and
* saves performance data to graphite
* So you dont need to install any additional software to get this job done
*
**********************************************************************************/
class GraphiteBackendTask extends AppShell{
public $Config = [];
private $host;
private $port;
private $prefix;
private $socket;
private $lastErrNo;
private $hostnameCache = [];
private $servicenameCache = [];
public function init($Config){
$this->Config = $Config;
$this->host = $this->Config['host'];
$this->port = $this->Config['port'];
$this->prefix = $this->Config['prefix'];
}
/**
* @param array $parsedPerfdata
* @param string $hostname
* @param string $servicedesc
* @param int $timestamp
*/
public function save($parsedPerfdata, $hostname, $servicedesc, $timestamp){
if($this->connect()){
foreach($parsedPerfdata as $ds => $_data){
$data = $this->buildString($ds, $_data, $hostname, $servicedesc, $timestamp);
$this->write($data);
}
}
$this->disconnect();
}
private function write($message){
$message .= PHP_EOL;
$this->lastErrNo = null;
if(!@socket_send($this->socket, $message, strlen($message), 0)){
CakeLog::error(sprintf(
'Graphite save error: %s %s',
$this->getLastErrNo(),
$this->getLastError()
));
return false;
}
return true;
}
private function connect(){
$this->socket = socket_create(AF_INET, SOCK_STREAM, IPPROTO_IP);
if(!@socket_connect($this->socket, $this->host, $this->port)){
CakeLog::error(sprintf(
'Graphite connection error: %s %s',
$this->getLastErrNo(),
$this->getLastError()
));
return false;
}
return true;
}
private function disconnect(){
if(is_resource($this->socket)){
socket_close($this->socket);
}
$this->socket = null;
}
private function getLastErrNo(){
if(is_resource($this->socket)){
$this->lastErrNo = socket_last_error($this->socket);
return $this->lastErrNo;
}
return false;
}
private function getLastError(){
return socket_strerror($this->lastErrNo);
}
private function buildString($datasource, $data, $hostname, $servicedesc, $timestamp){
$datasource = $this->replaceCharacters($datasource);
$hostname = $this->replaceCharacters($hostname);
$servicedesc = $this->replaceCharacters($servicedesc);
return sprintf(
'%s.%s.%s.%s %s %s',
$this->prefix,
$hostname,
$servicedesc,
$datasource,
$data['current'],
$timestamp
);
}
public function replaceCharacters($str){
return preg_replace($this->Config['replace_characters'], '_', $str);
}
public function requireHostNameCaching(){
if($this->Config['use_host_display_name'] === true){
return true;
}
return false;
}
public function requireServiceNameCaching(){
if($this->Config['use_service_display_name'] === true){
return true;
}
return false;
}
public function requireNameCaching(){
if($this->requireHostNameCaching() === true){
return true;
}
if($this->requireServiceNameCaching() === true){
return true;
}
return false;
}
public function addHostdisplayNameToCache($hostname, $hostdisplayname){
$this->hostnameCache[md5($hostname)] = $hostdisplayname;
}
public function getHostdisplayNameFromCache($hostname){
if(isset($this->hostnameCache[md5($hostname)])){
return $this->hostnameCache[md5($hostname)];
}
return null;
}
public function addServicedisplayNameToCache($hostname, $servicedesc, $servicedisplayname){
if(!isset($this->servicenameCache[md5($hostname)])){
$this->servicenameCache[md5($hostname)] = [];
}
$this->servicenameCache[md5($hostname)][md5($servicedesc)] = $servicedisplayname;
}
public function getServicedisplayNameFromCache($hostname, $servicedesc){
if(isset($this->servicenameCache[md5($hostname)][md5($servicedesc)])){
return $this->servicenameCache[md5($hostname)][md5($servicedesc)];
}
return null;
}
public function clearCache(){
$this->hostnameCache = [];
$this->servicenameCache = [];
}
}
| Java |
<?php
// Global variables
global $map_count, $ish_options;
$map_count++;
// Default SC attributes
$defaults = array(
'color' => '',
'zoom' => '15',
'invert_colors' => '',
'height' => '',
);
// Extract all attributes
$sc_atts = $this->extract_sc_attributes( $defaults, $atts );
// Add ID if empty as it is necessary for Google Maps to work
if ( empty( $sc_atts['id'] ) ){
$sc_atts['id'] = 'ish-gmap-' . $map_count;
}
// Make sure to include the scripts for Google Maps and the Generation of the marker infoboxes on click
wp_enqueue_script( 'ish-gmaps' );
// Convert color class to color value
if ( isset( $ish_options[ $sc_atts['color'] ] ) ){
$sc_atts['color'] = $ish_options[ $sc_atts['color'] ];
}
// SHORTCODE BEGIN
$return = '';
$return .= '<div class="' . apply_filters( 'ish_sc_classes', 'ish-sc_map_container', $tag ) . '"><div class="';
// CLASSES
$class = 'ish-sc_map';
$class .= ( '' != $sc_atts['css_class'] ) ? ' ' . esc_attr( $sc_atts['css_class'] ) : '' ;
$class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_color'] ) ? ' ish-tooltip-' . esc_attr( $sc_atts['tooltip_color'] ) : '';
$class .= ( '' != $sc_atts['tooltip'] && '' != $sc_atts['tooltip_text_color'] ) ? ' ish-tooltip-text-' . esc_attr( $sc_atts['tooltip_text_color'] ) : '';
//$return .= apply_filters( 'ish_sc_classes', $class, $tag );
$return .= $class;
$return .= '"' ;
// ID
$return .= ( '' != $sc_atts['id'] ) ? ' id="' . esc_attr( $sc_atts['id'] ) . '"' : '';
// STYLE
if ( '' != $sc_atts['style'] || '' != $sc_atts['height'] ){
$return .= ' style="';
$return .= ( '' != $sc_atts['height'] ) ? ' height: ' . esc_attr( $sc_atts['height'] ) . 'px;' : '';
$return .= ( '' != $sc_atts['style'] ) ? ' ' . esc_attr( $sc_atts['style'] ) : '';
$return .= '"';
}
// TOOLTIP
$return .= ( '' != $sc_atts['tooltip'] ) ? ' data-type="tooltip" title="' . esc_attr( $sc_atts['tooltip'] ) . '"' : '' ;
$return .= ( '' != $sc_atts['zoom'] ) ? ' data-zoom="' . esc_attr( $sc_atts['zoom'] ) . '"' : '' ;
$return .= ( 'yes' == $sc_atts['invert_colors'] ) ? ' data-invert="' . esc_attr( $sc_atts['invert_colors'] ) . '"' : '' ;
$return .= ( '' != $sc_atts['color'] ) ? ' data-color="' . esc_attr( $sc_atts['color'] ) . '"' : '' ;
$return .= '>';
$content = wpb_js_remove_wpautop($content, true);
// CONTENT
$return .= do_shortcode( $content );
// SHORTCODE END
$return .= '</div></div>';
echo $return; | Java |
<?php
class acf_Wysiwyg extends acf_Field
{
/*--------------------------------------------------------------------------------------
*
* Constructor
*
* @author Elliot Condon
* @since 1.0.0
* @updated 2.2.0
*
*-------------------------------------------------------------------------------------*/
function __construct($parent)
{
parent::__construct($parent);
$this->name = 'wysiwyg';
$this->title = __("Wysiwyg Editor",'acf');
add_action( 'acf_head-input', array( $this, 'acf_head') );
add_filter( 'acf/fields/wysiwyg/toolbars', array( $this, 'toolbars'), 1, 1 );
}
/*
* get_toolbars
*
* @description:
* @since: 3.5.7
* @created: 10/01/13
*/
function toolbars( $toolbars )
{
$editor_id = 'acf_settings';
// Full
$toolbars['Full'] = array();
$toolbars['Full'][1] = apply_filters('mce_buttons', array('bold', 'italic', 'strikethrough', 'bullist', 'numlist', 'blockquote', 'justifyleft', 'justifycenter', 'justifyright', 'link', 'unlink', 'wp_more', 'spellchecker', 'fullscreen', 'wp_adv' ), $editor_id);
$toolbars['Full'][2] = apply_filters('mce_buttons_2', array( 'formatselect', 'underline', 'justifyfull', 'forecolor', 'pastetext', 'pasteword', 'removeformat', 'charmap', 'outdent', 'indent', 'undo', 'redo', 'wp_help', 'code' ), $editor_id);
$toolbars['Full'][3] = apply_filters('mce_buttons_3', array(), $editor_id);
$toolbars['Full'][4] = apply_filters('mce_buttons_4', array(), $editor_id);
// Basic
$toolbars['Basic'] = array();
$toolbars['Basic'][1] = apply_filters( 'teeny_mce_buttons', array('bold', 'italic', 'underline', 'blockquote', 'strikethrough', 'bullist', 'numlist', 'justifyleft', 'justifycenter', 'justifyright', 'undo', 'redo', 'link', 'unlink', 'fullscreen'), $editor_id );
// Custom - can be added with acf/fields/wysiwyg/toolbars filter
return $toolbars;
}
/*--------------------------------------------------------------------------------------
*
* admin_head
* - Add the settings for a WYSIWYG editor (as used in wp_editor / wp_tiny_mce)
*
* @author Elliot Condon
* @since 3.2.3
*
*-------------------------------------------------------------------------------------*/
function acf_head()
{
add_action( 'admin_footer', array( $this, 'admin_footer') );
}
function admin_footer()
{
?>
<div style="display:none;">
<?php wp_editor( '', 'acf_settings' ); ?>
</div>
<?php
}
/*--------------------------------------------------------------------------------------
*
* create_options
*
* @author Elliot Condon
* @since 2.0.6
* @updated 2.2.0
*
*-------------------------------------------------------------------------------------*/
function create_options($key, $field)
{
// vars
$defaults = array(
'toolbar' => 'full',
'media_upload' => 'yes',
'the_content' => 'yes',
'default_value' => '',
);
$field = array_merge($defaults, $field);
?>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Default Value",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'textarea',
'name' => 'fields['.$key.'][default_value]',
'value' => $field['default_value'],
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Toolbar",'acf'); ?></label>
</td>
<td>
<?php
$toolbars = apply_filters( 'acf/fields/wysiwyg/toolbars', array() );
$choices = array();
if( is_array($toolbars) )
{
foreach( $toolbars as $k => $v )
{
$label = $k;
$name = sanitize_title( $label );
$name = str_replace('-', '_', $name);
$choices[ $name ] = $label;
}
}
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][toolbar]',
'value' => $field['toolbar'],
'layout' => 'horizontal',
'choices' => $choices
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Show Media Upload Buttons?",'acf'); ?></label>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][media_upload]',
'value' => $field['media_upload'],
'layout' => 'horizontal',
'choices' => array(
'yes' => __("Yes",'acf'),
'no' => __("No",'acf'),
)
));
?>
</td>
</tr>
<tr class="field_option field_option_<?php echo $this->name; ?>">
<td class="label">
<label><?php _e("Run filter \"the_content\"?",'acf'); ?></label>
<p class="description"><?php _e("Enable this filter to use shortcodes within the WYSIWYG field",'acf'); ?></p>
<p class="description"><?php _e("Disable this filter if you encounter recursive template problems with plugins / themes",'acf'); ?></p>
</td>
<td>
<?php
do_action('acf/create_field', array(
'type' => 'radio',
'name' => 'fields['.$key.'][the_content]',
'value' => $field['the_content'],
'layout' => 'horizontal',
'choices' => array(
'yes' => __("Yes",'acf'),
'no' => __("No",'acf'),
)
));
?>
</td>
</tr>
<?php
}
/*--------------------------------------------------------------------------------------
*
* create_field
*
* @author Elliot Condon
* @since 2.0.5
* @updated 2.2.0
*
*-------------------------------------------------------------------------------------*/
function create_field($field)
{
global $wp_version;
// vars
$defaults = array(
'toolbar' => 'full',
'media_upload' => 'yes',
);
$field = array_merge($defaults, $field);
$id = 'wysiwyg-' . $field['id'];
?>
<div id="wp-<?php echo $id; ?>-wrap" class="acf_wysiwyg wp-editor-wrap" data-toolbar="<?php echo $field['toolbar']; ?>" data-upload="<?php echo $field['media_upload']; ?>">
<?php if($field['media_upload'] == 'yes'): ?>
<?php if( version_compare($wp_version, '3.3', '<') ): ?>
<div id="editor-toolbar">
<div id="media-buttons" class="hide-if-no-js">
<?php do_action( 'media_buttons' ); ?>
</div>
</div>
<?php else: ?>
<div id="wp-<?php echo $id; ?>-editor-tools" class="wp-editor-tools">
<div id="wp-<?php echo $id; ?>-media-buttons" class="hide-if-no-js wp-media-buttons">
<?php do_action( 'media_buttons' ); ?>
</div>
</div>
<?php endif; ?>
<?php endif; ?>
<div id="wp-<?php echo $id; ?>-editor-container" class="wp-editor-container">
<textarea id="<?php echo $id; ?>" class="wp-editor-area" name="<?php echo $field['name']; ?>" ><?php echo wp_richedit_pre($field['value']); ?></textarea>
</div>
</div>
<?php
}
/*--------------------------------------------------------------------------------------
*
* get_value_for_api
*
* @author Elliot Condon
* @since 3.0.0
*
*-------------------------------------------------------------------------------------*/
function get_value_for_api($post_id, $field)
{
// vars
$defaults = array(
'the_content' => 'yes',
);
$field = array_merge($defaults, $field);
$value = parent::get_value($post_id, $field);
// filter
if( $field['the_content'] == 'yes' )
{
$value = apply_filters('the_content',$value);
}
else
{
$value = wpautop( $value );
}
return $value;
}
}
?> | Java |
<HTML>
<!-- Mirrored from www.w3schools.com/php/showphpcode.asp?source=demo_func_simplexml_addchild by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:12 GMT -->
<HEAD></HEAD>
<FONT FACE="'Courier New',Verdana, Arial, Helvetica" SIZE=2>
<!DOCTYPE html><br><html><br><body><br><br><FONT COLOR=#ff0000><?php<br>$note=<<<XML<br><note><br><to>Tove</to><br><from>Jani</from><br><heading>Reminder</heading><br><body>Don't forget me this weekend!</body><br></note><br>XML;<br><br>$xml=new SimpleXMLElement($note);<br><br>// Add a child element to the body element<br>$xml->body->addChild("date","2014-01-01");<br><br>// Add a child element after the last element inside note<br>$footer=$xml->addChild("footer","Some footer text");<br> <br>echo $xml->asXML();<br>?></FONT><br><br><p>Select View Source to see the added date element (inside the body element) and the new footer element.</p><br><br></body><br></html><br>
<!-- Mirrored from www.w3schools.com/php/showphpcode.asp?source=demo_func_simplexml_addchild by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:36:12 GMT -->
</HTML>
| Java |
/***************************************************************
* Name: RectShape.h
* Purpose: Defines rectangular shape class
* Author: Michal Bližňák (michal.bliznak@tiscali.cz)
* Created: 2007-07-22
* Copyright: Michal Bližňák
* License: wxWidgets license (www.wxwidgets.org)
* Notes:
**************************************************************/
#ifndef _WXSFRECTSHAPE_H
#define _WXSFRECTSHAPE_H
#include <wx/wxsf/ShapeBase.h>
// default values
/*! \brief Default value of wxSFRectShape::m_nRectSize data member. */
#define sfdvRECTSHAPE_SIZE wxRealPoint(100, 50)
/*! \brief Default value of wxSFRectShape::m_Fill data member. */
#define sfdvRECTSHAPE_FILL wxBrush(*wxWHITE)
/*! \brief Default value of wxSFRectShape::m_Border data member. */
#define sfdvRECTSHAPE_BORDER wxPen(*wxBLACK)
/*!
* \brief Class encapsulates basic rectangle shape which is used as a base class
* for many other shapes that can be bounded by a simple rectangle. The class
* provides all functionality needed for manipulating the rectangle's (bounding box)
* size and position.
*/
class WXDLLIMPEXP_SF wxSFRectShape : public wxSFShapeBase
{
public:
XS_DECLARE_CLONABLE_CLASS(wxSFRectShape);
/*! \brief Default constructor. */
wxSFRectShape(void);
/*!
* \brief User constructor.
* \param pos Initial position
* \param size Initial size
* \param manager Pointer to parent diagram manager
*/
wxSFRectShape(const wxRealPoint& pos, const wxRealPoint& size, wxSFDiagramManager* manager);
/*!
* \brief Copy constructor.
* \param obj Reference to the source object
*/
wxSFRectShape(const wxSFRectShape& obj);
/*! \brief Destructor. */
virtual ~wxSFRectShape(void);
// public virtual functions
/*!
* \brief Get shapes's bounding box. The function can be overrided if neccessary.
* \return Bounding rectangle
*/
virtual wxRect GetBoundingBox();
/*!
* \brief Get intersection point of the shape border and a line leading from
* 'start' point to 'end' point. The function can be overrided if neccessary.
* \param start Starting point of the virtual intersection line
* \param end Ending point of the virtual intersection line
* \return Intersection point
*/
virtual wxRealPoint GetBorderPoint(const wxRealPoint& start, const wxRealPoint& end);
/*!
* \brief Function called by the framework responsible for creation of shape handles
* at the creation time. The function can be overrided if neccesary.
*/
virtual void CreateHandles();
/*!
* \brief Event handler called during dragging of the shape handle.
* The function can be overrided if necessary.
*
* The function is called by the framework (by the shape canvas).
* \param handle Reference to dragged handle
*/
virtual void OnHandle(wxSFShapeHandle& handle);
/*!
* \brief Event handler called when the user started to drag the shape handle.
* The function can be overrided if necessary.
*
* The function is called by the framework (by the shape canvas).
* \param handle Reference to dragged handle
*/
virtual void OnBeginHandle(wxSFShapeHandle& handle);
/*! \brief Resize the shape to bound all child shapes. The function can be overrided if neccessary. */
virtual void FitToChildren();
/*!
* \brief Scale the shape size by in both directions. The function can be overrided if necessary
* (new implementation should call default one ore scale shape's children manualy if neccesary).
* \param x Horizontal scale factor
* \param y Vertical scale factor
* \param children TRUE if the shape's children shoould be scaled as well, otherwise the shape will be updated after scaling via Update() function.
*/
virtual void Scale(double x, double y, bool children = sfWITHCHILDREN);
// public data accessors
/*!
* \brief Set rectangle's fill style.
* \param brush Refernce to a brush object
*/
void SetFill(const wxBrush& brush){m_Fill = brush;}
/*!
* \brief Get current fill style.
* \return Current brush
*/
wxBrush GetFill() const {return m_Fill;}
/*!
* \brief Set rectangle's border style.
* \param pen Reference to a pen object
*/
void SetBorder(const wxPen& pen){m_Border = pen;}
/*!
* \brief Get current border style.
* \return Current pen
*/
wxPen GetBorder() const {return m_Border;}
/*!
* \brief Set the rectangle size.
* \param size New size
*/
void SetRectSize(const wxRealPoint& size){m_nRectSize = size;}
/*!
* \brief Set the rectangle size.
* \param x Horizontal size
* \param y Verical size
*/
void SetRectSize(double x, double y){m_nRectSize.x = x; m_nRectSize.y = y;}
/*!
* \brief Get the rectangle size.
* \return Current size
*/
wxRealPoint GetRectSize() const {return m_nRectSize;}
protected:
// protected data members
/*! \brief Pen object used for drawing of the rectangle border. */
wxPen m_Border;
/*! \brief Brush object used for drawing of the rectangle body. */
wxBrush m_Fill;
/*! \brief The rectangle size. */
wxRealPoint m_nRectSize;
// protected virtual functions
/*!
* \brief Draw the shape in the normal way. The function can be overrided if neccessary.
* \param dc Reference to device context where the shape will be drawn to
*/
virtual void DrawNormal(wxDC& dc);
/*!
* \brief Draw the shape in the hower mode (the mouse cursor is above the shape).
* The function can be overrided if neccessary.
* \param dc Reference to device context where the shape will be drawn to
*/
virtual void DrawHover(wxDC& dc);
/*!
* \brief Draw the shape in the highlighted mode (another shape is dragged over this
* shape and this shape will accept the dragged one if it will be dropped on it).
* The function can be overrided if neccessary.
* \param dc Reference to device context where the shape will be drawn to
*/
virtual void DrawHighlighted(wxDC& dc);
/*!
* \brief Draw shadow under the shape. The function can be overrided if neccessary.
* \param dc Reference to device context where the shadow will be drawn to
*/
virtual void DrawShadow(wxDC& dc);
/*!
* \brief Event handler called during dragging of the right shape handle.
* The function can be overrided if neccessary.
* \param handle Reference to dragged shape handle
*/
virtual void OnRightHandle(wxSFShapeHandle& handle);
/*!
* \brief Event handler called during dragging of the left shape handle.
* The function can be overrided if neccessary.
* \param handle Reference to dragged shape handle
*/
virtual void OnLeftHandle(wxSFShapeHandle& handle);
/*!
* \brief Event handler called during dragging of the top shape handle.
* The function can be overrided if neccessary.
* \param handle Reference to dragged shape handle
*/
virtual void OnTopHandle(wxSFShapeHandle& handle);
/*!
* \brief Event handler called during dragging of the bottom shape handle.
* The function can be overrided if neccessary.
* \param handle Reference to dragged shape handle
*/
virtual void OnBottomHandle(wxSFShapeHandle& handle);
private:
// private functions
/*! \brief Initialize serializable properties. */
void MarkSerializableDataMembers();
/*! \brief Auxiliary data member. */
wxRealPoint m_nPrevSize;
/*! \brief Auxiliary data member. */
wxRealPoint m_nPrevPosition;
};
#endif //_WXSFRECTSHAPE_H
| Java |
// File: $Id: opbranch.h,v 1.1 2001/10/27 22:34:09 ses6442 Exp p334-70f $
// Author: Benjamin Meyer
// Contributor: Sean Sicher
// Discription: Branch module for
// Revisions:
// $Log: opbranch.h,v $
// Revision 1.1 2001/10/27 22:34:09 ses6442
// Initial revision
//
//
#ifndef OPBRANCH_H
#define OPBRANCH_H
#include "operation.h"
class OpBranch : public Operation {
public:
OpBranch();
// Discription: process this instruction and dump if there are any errors.
virtual bool process();
};
#endif
| Java |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ESPSharp.Enums
{
public enum PackageScheduleDays : sbyte
{
Any = -1,
Sunday,
Monday,
Tuesday,
Wednesday,
Thursday,
Friday,
Saturday,
Weekdays,
Weekends,
Mon_Wed_Fri,
Tue_Thur
}
}
| Java |
# zoomzoomzoom.js
Simple zoom tool for images inside of DIVs. A very small script that is heavily dependent on its HTML structure. Designed to only work in Chrome.
| Java |
<?php
/**
* @package Adminimize
* @subpackage Backend Options
* @author Frank Bültge
*/
if ( ! function_exists( 'add_action' ) ) {
echo "Hi there! I'm just a part of plugin, not much I can do when called directly.";
exit;
}
?>
<div id="poststuff" class="ui-sortable meta-box-sortables">
<div class="postbox">
<div class="handlediv" title="<?php _e('Click to toggle'); ?>"><br/></div>
<h3 class="hndle" id="backend_options"><?php _e('Backend Options', FB_ADMINIMIZE_TEXTDOMAIN ); ?></h3>
<div class="inside">
<?php wp_nonce_field('mw_adminimize_nonce'); ?>
<br class="clear" />
<table summary="config" class="widefat">
<tbody>
<?php if ( function_exists('is_super_admin') ) { ?>
<!--
<tr valign="top" class="form-invalid">
<td><?php _e( 'Use Global Settings', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php
$mw_adminimize_use_global = '0';
$select_active = '';
$message = '';
if ( is_multisite() && is_plugin_active_for_network( MW_ADMIN_FILE ) ) {
$mw_adminimize_use_global = 1;
$select_active = ' disabled="disabled"';
$message = __( 'The plugin is active in multiste.', FB_ADMINIMIZE_TEXTDOMAIN );
}
$mw_adminimize_use_global = get_option( 'mw_adminimize_use_global' ); ?>
<select name="_mw_adminimize_use_global"<?php echo $select_active; ?>>
<option value="0"<?php if ( '0' === $mw_adminimize_use_global ) { echo ' selected="selected"'; } ?>><?php _e( 'False', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ( '1' === $mw_adminimize_use_global ) { echo ' selected="selected"'; } ?>><?php _e('True', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Use the settings global in your Multisite network.', FB_ADMINIMIZE_TEXTDOMAIN ); echo ' ' . $message; ?>
</td>
</tr>
-->
<tr valign="top" class="form-invalid">
<td><?php _e('Exclude Super Admin', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_exclude_super_admin = _mw_adminimize_get_option_value('_mw_adminimize_exclude_super_admin'); ?>
<select name="_mw_adminimize_exclude_super_admin">
<option value="0"<?php if ($_mw_adminimize_exclude_super_admin == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_exclude_super_admin == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Exclude the Super Admin on a WP Multisite Install from all limitations of this plugin.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php } ?>
<tr valign="top">
<td><?php _e('User-Info', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_user_info = _mw_adminimize_get_option_value('_mw_adminimize_user_info'); ?>
<select name="_mw_adminimize_user_info">
<option value="0"<?php if ($_mw_adminimize_user_info == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_user_info == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="2"<?php if ($_mw_adminimize_user_info == '2') { echo ' selected="selected"'; } ?>><?php _e('Only logout', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="3"<?php if ($_mw_adminimize_user_info == '3') { echo ' selected="selected"'; } ?>><?php _e('User & Logout', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('The "User-Info-area" is on the top right side of the backend. You can hide or reduced show.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php if ( ($_mw_adminimize_user_info == '') || ($_mw_adminimize_user_info == '1') || ($_mw_adminimize_user_info == '0') ) $disabled_item = ' disabled="disabled"' ?>
<tr valign="top" class="form-invalid">
<td><?php _e('Change User-Info, redirect to', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_ui_redirect = _mw_adminimize_get_option_value('_mw_adminimize_ui_redirect'); ?>
<select name="_mw_adminimize_ui_redirect" <?php if ( isset($disabled_item) ) echo $disabled_item; ?>>
<option value="0"<?php if ($_mw_adminimize_ui_redirect == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_ui_redirect == '1') { echo ' selected="selected"'; } ?>><?php _e('Frontpage of the Blog', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</select> <?php _e('When the "User-Info-area" change it, then it is possible to change the redirect.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Footer', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_footer = _mw_adminimize_get_option_value('_mw_adminimize_footer'); ?>
<select name="_mw_adminimize_footer">
<option value="0"<?php if ($_mw_adminimize_footer == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_footer == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('The Footer-area can hide, include all links and details.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Header', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_header = _mw_adminimize_get_option_value('_mw_adminimize_header'); ?>
<select name="_mw_adminimize_header">
<option value="0"<?php if ($_mw_adminimize_header == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_header == '1') { echo ' selected="selected"'; } ?>><?php _e('Hide', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('The Header-area can hide, include all links and details.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Timestamp', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_timestamp = _mw_adminimize_get_option_value('_mw_adminimize_timestamp'); ?>
<select name="_mw_adminimize_timestamp">
<option value="0"<?php if ($_mw_adminimize_timestamp == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_timestamp == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Opens the post timestamp editing fields without you having to click the "Edit" link every time.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Thickbox FullScreen', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_tb_window = _mw_adminimize_get_option_value('_mw_adminimize_tb_window'); ?>
<select name="_mw_adminimize_tb_window">
<option value="0"<?php if ($_mw_adminimize_tb_window == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_tb_window == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('All Thickbox-function use the full area of the browser. Thickbox is for example in upload media-files.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Flashuploader', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_control_flashloader = _mw_adminimize_get_option_value('_mw_adminimize_control_flashloader'); ?>
<select name="_mw_adminimize_control_flashloader">
<option value="0"<?php if ($_mw_adminimize_control_flashloader == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_control_flashloader == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('Disable the flashuploader and users use only the standard uploader.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Category Height', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_cat_full = _mw_adminimize_get_option_value('_mw_adminimize_cat_full'); ?>
<select name="_mw_adminimize_cat_full">
<option value="0"<?php if ($_mw_adminimize_cat_full == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_cat_full == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select> <?php _e('View the Meta Box with Categories in the full height, no scrollbar or whitespace.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<tr valign="top">
<td><?php _e('Advice in Footer', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_advice = _mw_adminimize_get_option_value('_mw_adminimize_advice'); ?>
<select name="_mw_adminimize_advice">
<option value="0"<?php if ($_mw_adminimize_advice == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
<option value="1"<?php if ($_mw_adminimize_advice == '1') { echo ' selected="selected"'; } ?>><?php _e('Activate', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select>
<textarea style="width: 85%;" class="code" rows="1" cols="60" name="_mw_adminimize_advice_txt" id="_mw_adminimize_advice_txt" ><?php echo htmlspecialchars(stripslashes(_mw_adminimize_get_option_value('_mw_adminimize_advice_txt'))); ?></textarea><br /><?php _e('In the Footer you can display an advice for changing the Default-design, (x)HTML is possible.', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php
// when remove dashboard
foreach ($user_roles as $role) {
$disabled_menu_[$role] = _mw_adminimize_get_option_value('mw_adminimize_disabled_menu_'. $role .'_items');
$disabled_submenu_[$role] = _mw_adminimize_get_option_value('mw_adminimize_disabled_submenu_'. $role .'_items');
}
$disabled_menu_all = array();
foreach ($user_roles as $role) {
array_push($disabled_menu_all, $disabled_menu_[$role]);
array_push($disabled_menu_all, $disabled_submenu_[$role]);
}
if ( '' != $disabled_menu_all ) {
if ( ! _mw_adminimize_recursive_in_array('index.php', $disabled_menu_all) ) {
$disabled_item2 = ' disabled="disabled"';
}
?>
<tr valign="top" class="form-invalid">
<td><?php _e('Dashboard deactivate, redirect to', FB_ADMINIMIZE_TEXTDOMAIN ); ?></td>
<td>
<?php $_mw_adminimize_db_redirect = _mw_adminimize_get_option_value('_mw_adminimize_db_redirect'); ?>
<select name="_mw_adminimize_db_redirect"<?php if ( isset($disabled_item2) ) echo $disabled_item2; ?>>
<option value="0"<?php if ($_mw_adminimize_db_redirect == '0') { echo ' selected="selected"'; } ?>><?php _e('Default', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (profile.php)</option>
<option value="1"<?php if ($_mw_adminimize_db_redirect == '1') { echo ' selected="selected"'; } ?>><?php _e('Manage Posts', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit.php)</option>
<option value="2"<?php if ($_mw_adminimize_db_redirect == '2') { echo ' selected="selected"'; } ?>><?php _e('Manage Pages', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit-pages.php)</option>
<option value="3"<?php if ($_mw_adminimize_db_redirect == '3') { echo ' selected="selected"'; } ?>><?php _e('Write Post', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (post-new.php)</option>
<option value="4"<?php if ($_mw_adminimize_db_redirect == '4') { echo ' selected="selected"'; } ?>><?php _e('Write Page', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (page-new.php)</option>
<option value="5"<?php if ($_mw_adminimize_db_redirect == '5') { echo ' selected="selected"'; } ?>><?php _e('Comments', FB_ADMINIMIZE_TEXTDOMAIN ); ?> (edit-comments.php)</option>
<option value="6"<?php if ($_mw_adminimize_db_redirect == '6') { echo ' selected="selected"'; } ?>><?php _e('other Page', FB_ADMINIMIZE_TEXTDOMAIN ); ?></option>
</select>
<textarea style="width: 85%;" class="code" rows="1" cols="60" name="_mw_adminimize_db_redirect_txt" id="_mw_adminimize_db_redirect_txt" ><?php echo htmlspecialchars(stripslashes(_mw_adminimize_get_option_value('_mw_adminimize_db_redirect_txt'))); ?></textarea>
<br /><?php _e('You have deactivated the Dashboard, please select a page for redirection or define custom url, include http://?', FB_ADMINIMIZE_TEXTDOMAIN ); ?>
</td>
</tr>
<?php
}
?>
</tbody>
</table>
<p id="submitbutton">
<input class="button button-primary" type="submit" name="_mw_adminimize_save" value="<?php _e('Update Options', FB_ADMINIMIZE_TEXTDOMAIN ); ?> »" /><input type="hidden" name="page_options" value="'dofollow_timeout'" />
</p>
<p><a class="alignright button" href="javascript:void(0);" onclick="window.scrollTo(0,0);" style="margin:3px 0 0 30px;"><?php _e('scroll to top', FB_ADMINIMIZE_TEXTDOMAIN); ?></a><br class="clear" /></p>
</div>
</div>
</div>
| Java |
<?php
/**
* Footer functions.
*
* @package Sento
*/
/* ----------------------------------------------------------------------------------
FOOTER WIDGETS LAYOUT
---------------------------------------------------------------------------------- */
/* Assign function for widget area 1 */
function thinkup_input_footerw1() {
echo '<div id="footer-col1" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w1' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 1.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 2 */
function thinkup_input_footerw2() {
echo '<div id="footer-col2" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w2' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 2.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 3 */
function thinkup_input_footerw3() {
echo '<div id="footer-col3" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w3' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 3.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 4 */
function thinkup_input_footerw4() {
echo '<div id="footer-col4" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w4' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 4.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 5 */
function thinkup_input_footerw5() {
echo '<div id="footer-col5" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w5' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 5.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Assign function for widget area 6 */
function thinkup_input_footerw6() {
echo '<div id="footer-col6" class="widget-area">';
if ( ! dynamic_sidebar( 'footer-w6' ) ) {
echo '<h3 class="widget-title">' . __( 'Please Add Widgets', 'sento') . '</h3>',
'<div class="error-icon">',
'<p>' . __( 'Remove this message by adding widgets to Footer Widget Area 6.', 'sento') . '</p>',
'<a href="' . esc_url( admin_url( 'widgets.php' ) ) . '" title="' . __( 'No Widgets Selected', 'sento' ) . '">' . __( 'Click here to go to Widget area.', 'sento') . '</a>',
'</div>';
};
echo '</div>';
}
/* Add Custom Footer Layout */
function thinkup_input_footerlayout() {
global $thinkup_footer_layout;
global $thinkup_footer_widgetswitch;
if ( $thinkup_footer_widgetswitch !== "1" and ! empty( $thinkup_footer_layout ) ) {
echo '<div id="footer">';
if ( $thinkup_footer_layout == "option1" ) {
echo '<div id="footer-core" class="option1">';
thinkup_input_footerw1();
echo '</div>';
} else if ( $thinkup_footer_layout == "option2" ) {
echo '<div id="footer-core" class="option2">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option3" ) {
echo '<div id="footer-core" class="option3">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
echo '</div>';
} else if ( $thinkup_footer_layout == "option4" ) {
echo '<div id="footer-core" class="option4">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
echo '</div>';
} else if ( $thinkup_footer_layout == "option5" ) {
echo '<div id="footer-core" class="option5">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
echo '</div>';
} else if ( $thinkup_footer_layout == "option6" ) {
echo '<div id="footer-core" class="option6">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
thinkup_input_footerw6();
echo '</div>';
} else if ( $thinkup_footer_layout == "option7" ) {
echo '<div id="footer-core" class="option7">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option8" ) {
echo '<div id="footer-core" class="option8">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option9" ) {
echo '<div id="footer-core" class="option9">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option10" ) {
echo '<div id="footer-core" class="option10">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option11" ) {
echo '<div id="footer-core" class="option11">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option12" ) {
echo '<div id="footer-core" class="option12">';
thinkup_input_footerw1();
thinkup_input_footerw2();
echo '</div>';
} else if ( $thinkup_footer_layout == "option13" ) {
echo '<div id="footer-core" class="option13">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
echo '</div>';
} else if ( $thinkup_footer_layout == "option14" ) {
echo '<div id="footer-core" class="option14">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
echo '</div>';
} else if ( $thinkup_footer_layout == "option15" ) {
echo '<div id="footer-core" class="option15">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
echo '</div>';
} else if ( $thinkup_footer_layout == "option16" ) {
echo '<div id="footer-core" class="option16">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
echo '</div>';
} else if ( $thinkup_footer_layout == "option17" ) {
echo '<div id="footer-core" class="option17">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
echo '</div>';
} else if ( $thinkup_footer_layout == "option18" ) {
echo '<div id="footer-core" class="option18">';
thinkup_input_footerw1();
thinkup_input_footerw2();
thinkup_input_footerw3();
thinkup_input_footerw4();
thinkup_input_footerw5();
echo '</div>';
}
echo '</div>';
}
}
/* ----------------------------------------------------------------------------------
COPYRIGHT TEXT
---------------------------------------------------------------------------------- */
function thinkup_input_copyright() {
printf( __( 'Developed by %1$s. Powered by %2$s.', 'sento' ) , '<a href="//www.thinkupthemes.com/" target="_blank">Think Up Themes Ltd</a>', '<a href="//www.wordpress.org/" target="_blank">WordPress</a>');
}
?> | Java |
<script>
var panels = new Array();
function addcattab(id, text, title)
{
var ccc = document.getElementById('categories');
var tab_id = id + '-tab';
var tab_title = (title) ? (' title="' + title + '"') : '';
var _li = document.createElement('li');
_li.id = tab_id;
_li.className = 'tab';
_li.innerHTML = '<a href="' + "#tabs" + '" class="cattab" data-subpanel="' + id + '" role="tab" aria-controls="' + id + '"' + tab_title + '><span>' + text + "</span></a>";
ccc.appendChild(_li);
}
function is_in_array(elem, array)
{
for (var i = 0, length = array.length; i < length; i++) {
// === is correct (IE)
if (array[i] === elem) {
return i;
}
}
return -1;
}
function nextTag(node) {
var node = node.nextSibling;
return (node && node.nodeType != 1) ? nextTag(node) : node;
}
</script>
<div id="tabs" class="sub-panels" role="tablist">
<ul id="categories" class="tabs"></ul>
</div> | Java |
/*
Copyright (C) 2005 Michael K. McCarty & Fritz Bronner
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
*/
/** \file future.c This is responsible for Future Mission planning screen.
*
*/
#include <Buzz_inc.h>
#include <externs.h>
#include <assert.h>
#include <logging.h>
//Used to read steps from missStep.dat
FILE* MSteps;
char missStep[1024];
static inline char B_Mis(char x) {return missStep[x]-0x30;}
/*missStep.dat is plain text, with:
Mission Number (2 first bytes of each line)
A Coded letter, each drawing a different line (1105-1127 for all possible letters)
Numbers following each letter, which are the parameters of the function
Each line must finish with a Z, so the game stops reading
Any other char is ignored, but it's easier to read for a human that way */
LOG_DEFAULT_CATEGORY(future)
char status[5],lck[5],F1,F2,F3,F4,FMen,F5,Pad;
char JointFlag,MarFlag,JupFlag,SatFlag,MisType;
GXHEADER vh;
struct StepInfo {
i16 x_cor;
i16 y_cor;
} StepBub[MAXBUB];
struct Parameter {
char A; /**< DOCKING */
char B; /**< EVA */
char C; /**< LEM */
char D; /**< JOINT */
char E; /**< MANNED/UNMANNED/Duration 0==unmanned 1-6==duration */
char X; /**< the type of mission for assign crew and hardware */
char Z; /**< A duration mission only */
} V[62];
extern int Bub_Count;
extern struct mStr Mis;
extern struct MisEval Mev[60];
extern int SEG;
void Load_FUT_BUT(void)
{
FILE *fin;
unsigned i;
fin=sOpen("NFUTBUT.BUT","rb",0);
i=fread(screen,1,MAX_X*MAX_Y,fin);
fclose(fin);
RLED_img((char *)screen,(char *)vh.vptr,(unsigned)i,vh.w,vh.h);
return;
}
void DrawFuture(char plr,int mis,char pad)
{
int i,j;
FILE *fin;
unsigned sz;
strcpy(IKEY,"k011");strcpy(IDT,"i011");
JointFlag=0; // initialize joint flag
F1=F2=F3=F4=FMen=F5=0;
for (i=0;i<5;i++) lck[i]=status[i]=0;
FadeOut(2,pal,10,0,0);
Load_FUT_BUT();
fin=sOpen("FMIN.IMG","rb",0);
fread(&pal[0],768,1,fin);
sz=fread(screen,1,MAX_X*MAX_Y,fin);
fclose(fin);
RLED_img((char *)screen,(char *)vhptr.vptr,sz,vhptr.w,vhptr.h);
gxClearDisplay(0,0);
gr_sync ();
if (pad==2) JointFlag=0; // third pad automatic no joint mission
else
if (Data->P[plr].LaunchFacility[pad+1] == 1)
{
if (Data->P[plr].Future[pad+1].MissionCode==0) JointFlag=1; // if no mission then set joint flag
else if (Data->P[plr].Future[pad+1].part==1) // check if the part of that second mission is set
{
JointFlag=1;
Data->P[plr].Future[pad+1].MissionCode=0; // clear mission
Data->P[plr].Future[pad+1].part=0;
};
};
if (pad==1 || pad==0) {
if (Data->P[plr].LaunchFacility[pad+1]==1) JointFlag=1;
}
i=Data->Year;j=Data->Season;
TRACE3("--- Setting i=Year (%d), j=Season (%d)", i, j);
if ((i==60 && j==0) || (i==62 && j==0) || (i==64 && j==0) ||
(i==66 && j==0) || (i==69 && j==1) || (i==71 && j==1) ||
(i==73 && j==1)) {
gxVirtualVirtual(&vhptr,1,2,12,11,&vhptr,198,153,gxSET); /* Mars */
MarFlag=1; } else MarFlag=0;
if ((i==60 || i==64 || i==68 || i==72 || i==73 || i==77)) {
gxVirtualVirtual(&vhptr,14,2,64,54,&vhptr,214,130,gxSET); /* Jup */
JupFlag=1; } else JupFlag=0;
if (i==61 || i==66 || i==72) {
gxVirtualVirtual(&vhptr,66,2,114,53,&vhptr,266,135,gxSET); /* Sat */
SatFlag=1; } else SatFlag=0;
RectFill(1,1,318,21,3);RectFill(317,22,318,198,3);RectFill(1,197,316,198,3);
RectFill(1,22,2,196,3);OutBox(0,0,319,199);InBox(3,3,30,19);
InBox(3,22,316,196);
IOBox(242,3,315,19);
ShBox(5,24,183,47);
ShBox(5,24,201,47); //name box
ShBox(5,74,41,82); // RESET
ShBox(5,49,53,72); //dur/man
ShBox(43,74,53,82); // lock
ShBox(80,74,90,82);
ShBox(117,74,127,82);
ShBox(154,74,164,82);
ShBox(191,74,201,82);
ShBox(5,84,16,130); //arrows up
ShBox(5,132,16,146); //middle box
ShBox(5,148,16,194); // down
ShBox(203,24,238,31); // new right boxes
RectFill(206,36,235,44,7);
ShBox(203,33,238,47);
InBox(205,35,236,45);
UPArrow(8,95);DNArrow(8,157);
gxVirtualDisplay(&vh,140,5,5,132,15,146,0);
Toggle(5,1);draw_Pie(0);OutBox(5,49,53,72);
Toggle(1,1);TogBox(55,49,0);
Toggle(2,1);TogBox(92,49,0);
Toggle(3,1);TogBox(129,49,0);
FMen=F1=F2=F3=F4=F5=0;
for (i=1;i<4;i++){
if (status[i]!=0) {
Toggle(i,1);
}
};
if (JointFlag==0) {
F4=2;lck[4]=1;
Toggle(4,1);
InBox(191,74,201,82);
PlaceRX(5);
TogBox(166,49,1);
}
else {
F4=0; lck[4]=0;
status[4]=0;
Toggle(4,1);
OutBox(191,74,201,82);
ClearRX(5);
TogBox(166,49,0);
};
gr_sync ();
Missions(plr,8,37,mis,1);
GetMinus(plr);
grSetColor(5);
/* lines of text are 1:8,30 2:8,37 3:8,44 */
switch(pad) { // These used to say Pad 1, 2, 3 -Leon
case 0: PrintAt(8,30,"PAD A:");break;
case 1: PrintAt(8,30,"PAD B:");break;
case 2: PrintAt(8,30,"PAD C:");break;
default:break;
};
grSetColor(1);
PrintAt(9,80,"RESET");
PrintAt(256,13,"CONTINUE");
grSetColor(11);
if (Data->Season==0) PrintAt(200,9,"SPRING");
else PrintAt(205,9,"FALL");
PrintAt(206,16,"19");
DispNum(0,0,Data->Year);
grSetColor(1);
FlagSm(plr,4,4);
DispBig(40,5,"FUTURE MISSIONS",0,-1);
FadeIn(2,pal,10,0,0);
return;
}
void ClearDisplay(void)
{
gxVirtualDisplay(&vhptr,202,48,202,48,241,82,0);
gxVirtualDisplay(&vhptr,17,83,17,83,241,195,0);
gxVirtualDisplay(&vhptr,242,23,242,23,315,195,0);
grSetColor(1);
return;
}
int GetMinus(char plr)
{
char i;int u;
i=PrestMin(plr);
RectFill(206,36,235,44,7);
if (i<3) u=1; //ok
else if (i<9) u=10; //caution
else u=19; //danger
gxVirtualDisplay(&vh,203,u,203,24,238,31,0);
grSetColor(11);
if (i>0) PrintAt(210,42,"-");
else grMoveTo(210,42);
DispNum(0,0,i);
grSetColor(1);
return 0;
}
void SetParameters(void)
{
int i;
FILE *fin;
fin=sOpen("MISSION.DAT","rb",0);
for (i=0;i<62;i++) {
fread(&Mis,sizeof Mis,1,fin);
V[i].A=Mis.Doc; V[i].B=Mis.EVA;
V[i].C=Mis.LM; V[i].D=Mis.Jt;
V[i].E=Mis.Days; V[i].X=Mis.mCrew;
V[i].Z=Mis.Dur;
}
fclose(fin);
return;
}
void DrawLocks(void)
{
int i;
for (i=0;i<5;i++)
if (lck[i]==1) PlaceRX(i+1);
else ClearRX(i+1);
return;
}
/** set the toggles???
*
* \param wh the button
* \param i in or out
*/
void Toggle(int wh,int i)
{
TRACE3("->Toggle(wh %d, i %d)", wh, i);
switch(wh)
{
case 1:if (i==1) gxVirtualDisplay(&vh,1,21,55,49,89,81,0);else
gxVirtualDisplay(&vh,1,56,55,49,89,81,0); break;
case 2:if(i==1) gxVirtualDisplay(&vh,38,21,92,49,127,81,0);else
gxVirtualDisplay(&vh,38,56,92,49,127,81,0); break;
case 3:if(i==1) gxVirtualDisplay(&vh,75,21,129,49,163,81,0);else
gxVirtualDisplay(&vh,75,56,129,49,163,81,0); break;
case 4:if(i==1) gxVirtualDisplay(&vh,112,21,166,49,200,81,0);else
gxVirtualDisplay(&vh,112,56,166,49,200,81,0); break;
case 5:if (i==1) gxVirtualDisplay(&vh,153,1,5,49,52,71,0);
else gxVirtualDisplay(&vh,153,26,5,49,52,71,0); break;
default:break;
}
TRACE1("<-Toggle()");
return;
}
void TogBox(int x,int y,int st)
{
TRACE4("->TogBox(x %d, y %d, st %d)", x, y, st);
char sta[2][2]={{2,4},{4,2}};
grSetColor(sta[st][0]);
grMoveTo(0+x,y+32);grLineTo(0+x,y+0);grLineTo(34+x,y+0);
grSetColor(sta[st][1]);
grMoveTo(x+0,y+33);grLineTo(23+x,y+33);grLineTo(23+x,y+23);
grLineTo(x+35,y+23);grLineTo(x+35,y+0);
TRACE1("<-TogBox()");
return;
}
void PianoKey(int X)
{
TRACE2("->PianoKey(X %d)", X);
int t;
if (F1==0) {
if (V[X].A==1) {Toggle(1,1);status[1]=1;}
else {Toggle(1,0);PlaceRX(1);status[1]=0;}}
if (F2==0) {
if (V[X].B==1) {Toggle(2,1);status[2]=1;}
else {Toggle(2,0);PlaceRX(2);status[2]=0;}}
if (F3==0) {
if (V[X].C==1) {Toggle(3,1);status[3]=1;}
else {Toggle(3,0);PlaceRX(3);status[3]=0;}}
if (F4==0) {
if (V[X].D==1) {Toggle(4,0);status[4]=1;}
else {Toggle(4,1);status[4]=0; }}
if (F5==-1 || (F5==0 && V[X].E==0))
{
Toggle(5,0);
status[0]=0;
}
else
{
Toggle(5,1);
t=(F5==0) ? V[X].E : F5;
assert(0 <= t);
draw_Pie(t);
status[0]=t;
}
DrawLocks();
TRACE1("<-PianoKey()");
return;
}
/** draw a piechart
*
* The piechart is indicating the number of astronauts on this mission.
*
* \param s something of an offset...
*/
void draw_Pie(int s)
{
int off;
if (s==0) off=1;
else off=s*20;
gxVirtualDisplay(&vh,off,1,7,51,25,69,0);
return;
}
void PlaceRX(int s)
{
switch(s)
{
case 1: RectFill(44,75,52,81,8);break;
case 2: RectFill(81,75,89,81,8);break;
case 3: RectFill(118,75,126,81,8);break;
case 4: RectFill(155,75,163,81,8);break;
case 5: RectFill(192,75,200,81,8);break;
default:break;
}
return;
}
void ClearRX(int s)
{
switch(s)
{
case 1: RectFill(44,75,52,81,3);break;
case 2: RectFill(81,75,89,81,3);break;
case 3: RectFill(118,75,126,81,3);break;
case 4: RectFill(155,75,163,81,3);break;
case 5: RectFill(192,75,200,81,3);break;
default:break;
}
return;
}
int UpSearchRout(int num,char plr)
{
int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1;
orig=num;
if (num >= 56+plr) num=0;
else num++;
while (found==0)
{
c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1;
if (F1==V[num].A) c1=1; /* condition one is true */
if (F1==0 && V[num].A==1) c1=1;
if (F1==2 && V[num].A==0) c1=1;
if (F2==V[num].B) c2=1; /* condition two is true */
if (F2==0 && V[num].B==1) c2=1;
if (F2==2 && V[num].B==0) c2=1;
if (F3==V[num].C) c3=1; /* condition three is true */
if (F3==0 && V[num].C==1) c3=1;
if (F3==2 && V[num].C==0) c3=1;
if (F4==V[num].D) c4=1; /* condition four is true */
if (F4==0 && V[num].D==1) c4=1;
if (F4==2 && V[num].D==0) c4=1;
if (num==0) c5=1;
else {
if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1;
if (F5==0) c5=1;
if (F5>1 && V[num].Z==1) c5=1;
if (F5==V[num].E) c5=1;
};
if ((num==32 || num==36) && F5==2) c5=0;
// planet check
if (num==10 && MarFlag==0) c6=0;
if (num==12 && JupFlag==0) c7=0;
if (num==13 && SatFlag==0) c8=0;
if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1;
if (num==orig) return(0);
if (found==0) {
if (num==56+plr) num=0;
else ++num;
}
}; /* end while */
return(num);
}
int DownSearchRout(int num,char plr)
{
int found=0,orig,c1=0,c2=0,c3=0,c4=0,c5=0,c6=1,c7=1,c8=1;
orig=num;
if (num<=0) num=56+plr;
else --num;
while (found==0)
{
c1=0;c2=0;c3=0;c4=0;c5=0;c6=1;c7=1;c8=1;
if (F1==V[num].A) c1=1;
if (F1==0 && V[num].A==1) c1=1; /* condition one is true */
if (F1==2 && V[num].A==0) c1=1;
if (F2==V[num].B) c2=1; /* condition two is true */
if (F2==0 && V[num].B==1) c2=1; /* condition one is true */
if (F2==2 && V[num].B==0) c2=1;
if (F3==V[num].C) c3=1; /* condition three is true */
if (F3==0 && V[num].C==1) c3=1; /* condition one is true */
if (F3==2 && V[num].C==0) c3=1;
if (F4==V[num].D) c4=1; /* condition four is true */
if (F4==0 && V[num].D==1) c4=1; /* condition one is true */
if (F4==2 && V[num].D==0) c4=1;
if (num==0) c5=1;
else {
if (F5==-1 && V[num].Z==0 && V[num].E==0) c5=1; // locked on zero duration
if (F5==0) c5=1; // nothing set
if (F5>1 && V[num].Z==1) c5=1; // set duration with duration mission
if (F5==V[num].E) c5=1; // the duration is equal to what is preset
};
if ((num==32 || num==36) && F5==2) c5=0;
// planet check
if (num==10 && MarFlag==0) c6=0;
if (num==12 && JupFlag==0) c7=0;
if (num==13 && SatFlag==0) c8=0;
if (c1 && c2 && c3 && c4 && c5 && c6 && c7 && c8) found=1;
if (num==orig) return(0);
if (found==0) {
if (num==0) num=56+plr;
else --num;
}
}; /* end while */
return(num);
}
void
Future(char plr)
{
/** \todo the whole Future()-function is 500 >lines and unreadable */
TRACE1("->Future(plr)");
int MisNum = 0, DuraType = 0, MaxDur = 6, i, ii;
int setting = -1, prev_setting = -1;
int Ok, NewType;
GXHEADER local, local2;
GV(&local, 166, 9);
GV(&local2, 177, 197);
GV(&vh,240,90); /* global variable */
begfut:
MisNum = FutureCheck(plr, 0);
if (MisNum == 5)
{
DV(&local);
DV(&local2);
DV(&vh);
return;
}
F1 = F2 = F3 = F4 = FMen = F5 = 0;
// memset(buffer, 0x00, 20000);
for (i = 0; i < 5; i++)
lck[i] = status[i] = 0;
SetParameters();
strcpy(IDT, "i011");
Pad = MisNum;
DuraType = FMen = MisType = 0;
ClrFut(plr, MisNum);
DrawFuture(plr, MisType, MisNum);
begfut_noredraw:
// for (i=0;i<5;i++) ClearRX(i+1);
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
while (1)
{
GetMouse();
prev_setting = setting;
setting = -1;
if (key == '-' && SEG > 1)
SEG--;
if (key == '+' && SEG < 500)
SEG++;
if (key >= 65 && key < Bub_Count + 65)
setting = key - 65;
for (ii = 0; ii < Bub_Count; ii++)
{
if (x >= StepBub[ii].x_cor && x <= StepBub[ii].x_cor + 7
&& y >= StepBub[ii].y_cor && y <= StepBub[ii].y_cor + 7)
setting = ii;
}
if (setting >= 0)
{
if (prev_setting < 0)
gxGetImage(&local, 18, 186, 183, 194, 0);
if (prev_setting != setting)
{
ShBox(18, 186, 183, 194);
grSetColor(1);
MisStep(21, 192, Mev[setting].loc);
}
}
else if (setting < 0 && prev_setting >= 0)
{
gxPutImage(&local, gxSET, 18, 186, 0);
}
if (Mis.Dur <= V[MisType].E && ((x >= 244 && y >= 5 && x <= 313
&& y <= 17 && mousebuttons > 0) || key == K_ENTER))
{
InBox(244, 5, 313, 17);
WaitForMouseUp();
if (key > 0)
delay(300);
key = 0;
OutBox(244, 5, 313, 17);
gxGetImage(&local2, 74, 3, 250, 199, 0);
NewType = V[MisType].X;
Data->P[plr].Future[MisNum].Duration = DuraType;
Ok = HardCrewAssign(plr, Pad, MisType, NewType);
gxPutImage(&local2, gxSET, 74, 3, 0);
// DV(&local2);
if (Ok == 1)
{
Data->P[plr].Future[MisNum].Duration = DuraType;
goto begfut; // return to loop
}
else
{
ClrFut(plr, MisNum);
// DuraType = FMen = MisType = 0;
key = 0;
goto begfut_noredraw;
// DrawFuture(plr, MisType, MisNum);
}
key = 0;
};
// continue
if ((((x >= 5 && y >= 49 && x <= 53 && y <= 72) || (x >= 43
&& y >= 74 && x <= 53 && y <= 82))
&& mousebuttons > 0) || (key == '!' || key == '1'))
{
if ((x >= 43 && y >= 74 && x <= 53 && y <= 82) || key == '!')
{
lck[0] = abs(lck[0] - 1);
if (lck[0] == 1)
InBox(43, 74, 53, 82);
else
OutBox(43, 74, 53, 82);
if (lck[0] == 1)
F5 = (status[0] == 0) ? -1 : status[0];
if (lck[0] == 1)
PlaceRX(1);
else
ClearRX(1);
if (lck[0] == 0)
{
F5 = 0;
status[0] = 0;
}
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
}
else if (lck[0] != 1)
{
InBox(5, 49, 53, 72);
if (DuraType == MaxDur)
DuraType = 0;
else
DuraType++;
Data->P[plr].Future[MisNum].Duration = DuraType;
if (DuraType == 0)
Toggle(5, 0);
else if (DuraType == 1)
Toggle(5, 1);
if (DuraType != 0)
draw_Pie(DuraType);
status[0] = DuraType;
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
grSetColor(34);
OutBox(5, 49, 53, 72);
};
key = 0;
/* Duration */
};
if ((x >= 5 && y >= 74 && x <= 41 && y <= 82 && mousebuttons > 0)
|| (key == K_ESCAPE))
{
InBox(5, 74, 41, 82);
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
MisType = 0;
if (DuraType != 0)
Toggle(5, 0);
FMen = DuraType = F1 = F2 = F3 = F4 = F5 = 0;
for (i = 1; i < 4; i++)
if (status[i] != 0)
Toggle(i, 1);
if (JointFlag == 0)
{
F4 = 2;
lck[4] = 1;
Toggle(4, 1);
InBox(191, 74, 201, 82);
PlaceRX(5);
TogBox(166, 49, 1);
}
else
{
F4 = 0;
lck[4] = 0;
status[4] = 0;
Toggle(4, 1);
OutBox(191, 74, 201, 82);
ClearRX(5);
TogBox(166, 49, 0);
};
for (i = 0; i < 4; i++)
{
lck[i] = status[i] = 0;
}
OutBox(5, 49, 53, 72);
OutBox(43, 74, 53, 82);
TogBox(55, 49, 0);
OutBox(80, 74, 90, 82);
TogBox(92, 49, 0);
OutBox(117, 74, 127, 82);
TogBox(129, 49, 0);
OutBox(154, 74, 164, 82);
ClrFut(plr, MisNum);
Data->P[plr].Future[MisNum].Duration = 0;
Missions(plr, 8, 37, MisType, 1);
GetMinus(plr);
OutBox(5, 74, 41, 82);
key = 0;
/* Reset */
};
if ((x >= 55 && y >= 49 && x <= 90 && y <= 82 && mousebuttons > 0)
|| (key == '2' || key == '@'))
{
if ((x >= 80 && y >= 74 && x <= 90 && y <= 82) || (key == '@'))
{
if (lck[1] == 0)
InBox(80, 74, 90, 82);
else
OutBox(80, 74, 90, 82);
lck[1] = abs(lck[1] - 1);
if (lck[1] == 1)
PlaceRX(2);
else
ClearRX(2);
if ((status[1] == 0) && (lck[1] == 1))
F1 = 2;
else if ((status[1] == 1) && (lck[1] == 1))
F1 = 1;
else
F1 = 0;
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
}
else if (lck[1] != 1)
{
TogBox(55, 49, 1);
if (status[1] == 0)
Toggle(1, 1);
else
Toggle(1, 0);
status[1] = abs(status[1] - 1);
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
TogBox(55, 49, 0);
}; /* Docking */
key = 0;
};
if ((x >= 92 && y >= 49 && x <= 127 && y <= 82 && mousebuttons > 0)
|| (key == '3' || key == '#'))
{
if ((x >= 117 && y >= 74 && x <= 127 && y <= 82) || (key == '#'))
{
if (lck[2] == 0)
InBox(117, 74, 127, 82);
else
OutBox(117, 74, 127, 82);
lck[2] = abs(lck[2] - 1);
if (lck[2] == 1)
PlaceRX(3);
else
ClearRX(3);
if ((status[2] == 0) && (lck[2] == 1))
F2 = 2;
else if ((status[2] == 1) && (lck[2] == 1))
F2 = 1;
else
F2 = 0;
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
}
else if (lck[2] != 1)
{
TogBox(92, 49, 1);
if (status[2] == 0)
Toggle(2, 1);
else
{
Toggle(2, 0);
};
status[2] = abs(status[2] - 1);
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
TogBox(92, 49, 0);
}; /* EVA */
key = 0;
};
if ((x >= 129 && y >= 49 && x <= 164 && y <= 82 && mousebuttons > 0)
|| (key == '4' || key == '$'))
{
if ((x >= 154 && y >= 74 && x <= 164 && y <= 82) || (key == '$'))
{
if (lck[3] == 0)
InBox(154, 74, 164, 82);
else
OutBox(154, 74, 164, 82);
lck[3] = abs(lck[3] - 1); // F3=lck[3];
if (lck[3] == 1)
PlaceRX(4);
else
ClearRX(4);
if ((status[3] == 0) && (lck[3] == 1))
F3 = 2;
else if ((status[3] == 1) && (lck[3] == 1))
F3 = 1;
else
F3 = 0;
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
}
else if (lck[3] != 1)
{
TogBox(129, 49, 1);
if (status[3] == 0)
Toggle(3, 1);
else
{
Toggle(3, 0);
};
status[3] = abs(status[3] - 1);
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
TogBox(129, 49, 0);
}; /* LEM */
key = 0;
};
if (((x >= 166 && y >= 49 && x <= 201 && y <= 82 && mousebuttons > 0)
|| (key == '5' || key == '%')) && (JointFlag == 1))
{
if ((x > 191 && y >= 74 && x <= 201 && y <= 82) || (key == '%'))
{
if (lck[4] == 0)
InBox(191, 74, 201, 82);
else
OutBox(191, 74, 201, 82);
lck[4] = abs(lck[4] - 1);
if (lck[4] == 1)
PlaceRX(5);
else
ClearRX(5);
if ((status[4] == 0) && (lck[4] == 1))
F4 = 2;
else if ((status[4] == 1) && (lck[4] == 1))
F4 = 1;
else
F4 = 0;
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
}
else if (lck[4] != 1)
{
TogBox(166, 49, 1);
status[4] = abs(status[4] - 1);
if (status[4] == 0)
{
Toggle(4, 1);
}
else
{
Toggle(4, 0);
}
while (1)
{
GetMouse();
if (mousebuttons == 0)
break;
}
TogBox(166, 49, 0);
}; /* Joint Launch */
key = 0;
};
if ((x >= 5 && y >= 84 && x <= 16 && y <= 130 && mousebuttons > 0)
|| (key == UP_ARROW))
{
InBox(5, 84, 16, 130);
for (i = 0; i < 50; i++)
{
key = 0;
GetMouse();
delay(10);
if (mousebuttons == 0)
{
MisType = UpSearchRout(MisType, plr);
Data->P[plr].Future[MisNum].MissionCode = MisType;
i = 51;
}
}
while (mousebuttons == 1 || key == UP_ARROW)
{
MisType = UpSearchRout(MisType, plr);
Data->P[plr].Future[MisNum].MissionCode = MisType;
Missions(plr, 8, 37, MisType, 3);
DuraType = status[0];
delay(100);
key = 0;
GetMouse();
}
Missions(plr, 8, 37, MisType, 3);
DuraType = status[0];
OutBox(5, 84, 16, 130);
key = 0;
/* Mission Type plus */
};
if ((x >= 5 && y >= 132 && x < 16 && y <= 146 && mousebuttons > 0)
|| (key == K_SPACE))
{
InBox(5, 132, 16, 146);
WaitForMouseUp();
delay(50);
MisType = Data->P[plr].Future[MisNum].MissionCode;
assert(0 <= MisType);
if (MisType != 0){
Missions(plr, 8, 37, MisType, 1);
}
else{
Missions(plr, 8, 37, MisType, 3);
}
OutBox(5, 132, 16, 146);
key = 0;
}
if ((x >= 5 && y >= 148 && x <= 16 && y <= 194 && mousebuttons > 0)
|| (key == DN_ARROW))
{
InBox(5, 148, 16, 194);
for (i = 0; i < 50; i++)
{
key = 0;
GetMouse();
delay(10);
if (mousebuttons == 0)
{
MisType = DownSearchRout(MisType, plr);
Data->P[plr].Future[MisNum].MissionCode = MisType;
i = 51;
}
key = 0;
}
while (mousebuttons == 1 || key == DN_ARROW)
{
MisType = DownSearchRout(MisType, plr);
Data->P[plr].Future[MisNum].MissionCode = MisType;
Missions(plr, 8, 37, MisType, 3);
DuraType = status[0];
delay(100);
key = 0;
GetMouse();
}
Missions(plr, 8, 37, MisType, 3);
DuraType = status[0];
OutBox(5, 148, 16, 194);
key = 0;
/* Mission Type minus */
};
} // while
TRACE1("<-Future()");
}
/** draws the bubble on the screen,
* starts with upper left coor
*
* \param x x-coord of the upper left corner of the bubble
* \param y y-coord of the upper left corner of the bubble
*/
void Bd(int x,int y)
{
int x1,y1,x2,y2;
x1=x-2; y1=y; x2=x-1; y2=y-1;
RectFill(x1,y1,x1+8,y1+4,21);
RectFill(x2,y2,x2+6,y2+6,21);
grSetColor(1);
grMoveTo(x,y+4);
/** \note references Bub_Count to determine the number of the character to draw in the bubble */
DispChr(65+Bub_Count);
StepBub[Bub_Count].x_cor=x1;
StepBub[Bub_Count].y_cor=y1;
++Bub_Count;
return;
}
/** Print the duration of a mission
*
* \param x duration code
*
* \todo Link this at whatever place the duration is actually defined
*/
void DurPri(int x)
{
grSetColor(5);
switch(x)
{
case -1:PrintAt(112,30,"NO DURATION");break;
case 0:PrintAt(112,30,"NO DURATION");break;
case 1:PrintAt(112,30,"1 - 2 DAYS");break;
case 2:PrintAt(112,30,"3 - 5 DAYS");break;
case 3:PrintAt(112,30,"6 - 7 DAYS");break;
case 4:PrintAt(112,30,"8 - 12 DAYS");break;
case 5:PrintAt(112,30,"13 - 16 DAYS");break;
case 6:PrintAt(112,30,"17 - 20 DAYS");break;
default:break;
};
return;
}
void MissionName(int val,int xx,int yy,int len)
{
TRACE5("->MissionName(val %d, xx %d, yy %d, len %d)", val, xx, yy, len);
int i,j=0;
GetMisType(val);
grMoveTo(xx,yy);
for (i=0;i<50;i++) {
if (j>len && Mis.Name[i]==' ') {yy+=7;j=0;grMoveTo(xx,yy);}
else DispChr(Mis.Name[i]);
j++;if (Mis.Name[i]=='\0') break;
};
TRACE1("<-MissionName");
return;
}
/** Missions() will draw the future missions among other things
*
* \param plr Player
* \param X screen coord for mission name string
* \param Y screen coord for mission name string
* \param val mission number
* \param bub if set to 0 or 3 the function will not draw stuff
*/
void Missions(char plr,int X,int Y,int val,char bub)
{
TRACE5("->Missions(plr, X %d, Y %d, val %d, bub %c)", X, Y, val, bub);
if (bub==1 || bub==3) {
PianoKey(val);
Bub_Count=0; // set the initial bub_count
ClearDisplay();
RectFill(6,31,182,46,3);
RectFill(80,25,175,30,3);grSetColor(5);
PrintAt(55,30,"TYPE: ");DispNum(0,0,val);
grSetColor(5);
if (V[val].E>0) {
if (F5 > V[val].E && Mis.Dur==1) DurPri(F5);
else DurPri(V[val].E);}
else DurPri(F5);
} else grSetColor(1);
MissionName(val,X,Y,24);
if (bub==3) GetMinus(plr);
if (bub==0 || bub==3) {return;}
MSteps=sOpen("missSteps.dat","r",FT_DATA);
if (fgets(missStep, 1024, MSteps) == NULL)
memset (missStep, 0, sizeof missStep);
while (!feof(MSteps)&&((missStep[0]-0x30)*10+(missStep[1]-0x30))!=val) {
if (fgets(missStep, 1024, MSteps) == NULL)
break;
}
fclose(MSteps);
int n;
for (n=2;missStep[n]!='Z';n++)
switch (missStep[n]) {
case 'A': Draw_IJ (B_Mis(++n)); break;
case 'B': Draw_IJV (B_Mis(++n)); break;
case 'C': OrbOut (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break;
case 'D': LefEarth (B_Mis(n+1),B_Mis(n+2)); n+=2; break;
case 'E': OrbIn (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break;
case 'F': OrbMid (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break;
case 'G': LefOrb (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break;
case 'H': Draw_LowS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6)); n+=6; break;
case 'I': Fly_By (); break;
case 'J': VenMarMerc (B_Mis(++n)); break;
case 'K': Draw_PQR (); break;
case 'L': Draw_PST (); break;
case 'M': Draw_GH (B_Mis(n+1),B_Mis(n+2)); n+=2; break;
case 'N': Q_Patch (); break;
case 'O': RghtMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break;
case 'P': DrawLunPas (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break;
case 'Q': DrawLefMoon (B_Mis(n+1),B_Mis(n+2)); n+=2; break;
case 'R': DrawSTUV (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4)); n+=4; break;
case 'S': Draw_HighS (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3)); n+=3; break;
case 'T': DrawMoon (B_Mis(n+1),B_Mis(n+2),B_Mis(n+3),B_Mis(n+4),B_Mis(n+5),B_Mis(n+6),B_Mis(n+7)); n+=7; break;
case 'U': LefGap (B_Mis(++n)); break;
case 'V': S_Patch (B_Mis(++n)); break;
case 'W': DrawZ (); break;
default : break;
}
gr_sync ();
MissionCodes(plr,MisType,Pad);
TRACE1("<-Missions()");
} // end function missions
#ifdef DEAD_CODE
/** Draws stuff about choosing a program and having < 2 groups available
*
* \deprecated This function appears to be deprecated.
*/
char FutBad(void)
{
char i;
grSetColor(0);
ShBox(84,41,232,128);
InBox(91,47,225,103);
IOBox(91,107,225,123);
grSetColor(1);
PrintAt(150,117,"EXIT");
grSetColor(11);
PrintAt(96,60,"YOU HAVE SELECTED A");
PrintAt(96,70,"PROGRAM WITH LESS THAN");
PrintAt(96,80,"TWO GROUPS AVAILABLE.");
WaitForMouseUp();
i=0;
while(i==0) {
GetMouse();
if (mousebuttons!=0) {
if (x>=93 && y>=109 && x<=223 && y<=121) {
InBox(93,109,223,123);i=3;
delay(50);
};
};
}; /* End while */
return (i);
}
#endif
/* vim: set noet ts=4 sw=4 tw=77: */
| Java |
# SSClusterViewer/app
This folder contains the javascript files for the application.
# SSClusterViewer/resources
This folder contains static resources (typically an `"images"` folder as well).
# SSClusterViewer/overrides
This folder contains override classes. All overrides in this folder will be
automatically included in application builds if the target class of the override
is loaded.
# SSClusterViewer/sass/etc
This folder contains misc. support code for sass builds (global functions,
mixins, etc.)
# SSClusterViewer/sass/src
This folder contains sass files defining css rules corresponding to classes
included in the application's javascript code build. By default, files in this
folder are mapped to the application's root namespace, 'SSClusterViewer'. The
namespace to which files in this directory are matched is controlled by the
app.sass.namespace property in SSClusterViewer/.sencha/app/sencha.cfg.
# SSClusterViewer/sass/var
This folder contains sass files defining sass variables corresponding to classes
included in the application's javascript code build. By default, files in this
folder are mapped to the application's root namespace, 'SSClusterViewer'. The
namespace to which files in this directory are matched is controlled by the
app.sass.namespace property in SSClusterViewer/.sencha/app/sencha.cfg.
| Java |
---
layout: post
title: Objectify and strange errors with GWT serializations
date: '2013-04-04T09:15:00.003-07:00'
author: David Hatanian
tags:
modified_time: '2013-04-04T09:15:34.396-07:00'
blogger_id: tag:blogger.com,1999:blog-5219665179084602082.post-7455732729975892877
blogger_orig_url: http://david-codes.blogspot.com/2013/04/objectify-and-strange-errors-with-gwt.html
---
<div style="text-align: justify;">OK, so it turns out Objectify returns non-serializable lists when using the
<i>list()</i> method. Using the following method :
</div>
<div style="text-align: justify;"><br/></div>
<div style="text-align: justify;"><br/></div><br/>
<pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;">ofy.load().type(Plant.class).list();<br/></pre>
<pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;"><br/></pre>
<pre style="background-color: white; font-size: 12px; max-width: 80em; padding-left: 0.7em; text-align: start; white-space: pre-wrap;"><br/></pre>And directly returning the value to GWT client side throws a cryptic serialization exception, where the class that raises the problem is called
<i>Proxy$XX </i>where XX are digits.<br/>
<br/>That problem is going to be fixed in GWT next version, but meanwhile we have to use the workaround provided in the
<a href="https://code.google.com/p/objectify-appengine/issues/detail?id=120">bug report</a>. | Java |
TARGET = rlm_utf8
SRCS = rlm_utf8.c
HEADERS =
RLM_CFLAGS =
RLM_LIBS =
include ../rules.mak
$(STATIC_OBJS): $(HEADERS)
$(DYNAMIC_OBJS): $(HEADERS)
| Java |
// Copyright (C) 1999-2000 Id Software, Inc.
//
#include "ui_local.h"
/*********************************************************************************
SPECIFY SERVER
*********************************************************************************/
#define MAX_LISTBOXITEMS 128
#define MAX_LISTBOXWIDTH 40
#define MAX_LEAGUENAME 80
#define SPECIFYLEAGUE_FRAMEL "menu/art/frame2_l"
#define SPECIFYLEAGUE_FRAMER "menu/art/frame1_r"
#define SPECIFYLEAGUE_BACK0 "menu/art/back_0"
#define SPECIFYLEAGUE_BACK1 "menu/art/back_1"
#define SPECIFYLEAGUE_ARROWS0 "menu/art/arrows_vert_0"
#define SPECIFYLEAGUE_UP "menu/art/arrows_vert_top"
#define SPECIFYLEAGUE_DOWN "menu/art/arrows_vert_bot"
#define GLOBALRANKINGS_LOGO "menu/art/gr/grlogo"
#define GLOBALRANKINGS_LETTERS "menu/art/gr/grletters"
#define ID_SPECIFYLEAGUENAME 100
#define ID_SPECIFYLEAGUELIST 101
#define ID_SPECIFYLEAGUEUP 102
#define ID_SPECIFYLEAGUEDOWN 103
#define ID_SPECIFYLEAGUEBACK 104
static char* specifyleague_artlist[] =
{
SPECIFYLEAGUE_FRAMEL,
SPECIFYLEAGUE_FRAMER,
SPECIFYLEAGUE_ARROWS0,
SPECIFYLEAGUE_UP,
SPECIFYLEAGUE_DOWN,
SPECIFYLEAGUE_BACK0,
SPECIFYLEAGUE_BACK1,
GLOBALRANKINGS_LOGO,
GLOBALRANKINGS_LETTERS,
NULL
};
static char playername[80];
typedef struct
{
menuframework_s menu;
menutext_s banner;
menubitmap_s framel;
menubitmap_s framer;
menufield_s rankname;
menulist_s list;
menubitmap_s arrows;
menubitmap_s up;
menubitmap_s down;
menubitmap_s back;
menubitmap_s grlogo;
menubitmap_s grletters;
} specifyleague_t;
static specifyleague_t s_specifyleague;
typedef struct {
char buff[MAX_LISTBOXWIDTH];
char leaguename[MAX_LEAGUENAME];
} table_t;
table_t league_table[MAX_LISTBOXITEMS];
char *leaguename_items[MAX_LISTBOXITEMS];
static void SpecifyLeague_GetList()
{
int count = 0;
int i;
/* The Player Name has changed. We need to perform another search */
Q_strncpyz( playername,
s_specifyleague.rankname.field.buffer,
sizeof(playername) );
count = trap_CL_UI_RankGetLeauges( playername );
for(i = 0; i < count; i++)
{
char s[MAX_LEAGUENAME];
const char *var;
var = va( "leaguename%i", i+1 );
trap_Cvar_VariableStringBuffer( var, s, sizeof(s) );
Q_strncpyz(league_table[i].leaguename, s, sizeof(league_table[i].leaguename) );
Q_strncpyz(league_table[i].buff, league_table[i].leaguename, sizeof(league_table[i].buff) );
}
s_specifyleague.list.numitems = count;
}
/*
=================
SpecifyLeague_Event
=================
*/
static void SpecifyLeague_Event( void* ptr, int event )
{
int id;
id = ((menucommon_s*)ptr)->id;
//if( event != QM_ACTIVATED && id != ID_SPECIFYLEAGUELIST ) {
// return;
//}
switch (id)
{
case ID_SPECIFYLEAGUELIST:
if( event == QM_GOTFOCUS ) {
//ArenaServers_UpdatePicture();
}
break;
case ID_SPECIFYLEAGUEUP:
if( event == QM_ACTIVATED )
ScrollList_Key( &s_specifyleague.list, K_UPARROW );
break;
case ID_SPECIFYLEAGUEDOWN:
if( event == QM_ACTIVATED )
ScrollList_Key( &s_specifyleague.list, K_DOWNARROW );
break;
case ID_SPECIFYLEAGUENAME:
if( (event == QM_LOSTFOCUS) &&
(Q_strncmp(playername,
s_specifyleague.rankname.field.buffer,
strlen(s_specifyleague.rankname.field.buffer)) != 0))
{
SpecifyLeague_GetList();
}
break;
case ID_SPECIFYLEAGUEBACK:
if( event == QM_ACTIVATED )
{
trap_Cvar_Set( "sv_leagueName", league_table[s_specifyleague.list.curvalue].leaguename);
UI_PopMenu();
}
break;
}
}
/*
=================
SpecifyLeague_MenuInit
=================
*/
void SpecifyLeague_MenuInit( void )
{
int i;
// zero set all our globals
memset( &s_specifyleague, 0 ,sizeof(specifyleague_t) );
SpecifyLeague_Cache();
s_specifyleague.menu.wrapAround = qtrue;
s_specifyleague.menu.fullscreen = qtrue;
s_specifyleague.banner.generic.type = MTYPE_BTEXT;
s_specifyleague.banner.generic.x = 320;
s_specifyleague.banner.generic.y = 16;
s_specifyleague.banner.string = "CHOOSE LEAGUE";
s_specifyleague.banner.color = color_white;
s_specifyleague.banner.style = UI_CENTER;
s_specifyleague.framel.generic.type = MTYPE_BITMAP;
s_specifyleague.framel.generic.name = SPECIFYLEAGUE_FRAMEL;
s_specifyleague.framel.generic.flags = QMF_INACTIVE;
s_specifyleague.framel.generic.x = 0;
s_specifyleague.framel.generic.y = 78;
s_specifyleague.framel.width = 256;
s_specifyleague.framel.height = 334;
s_specifyleague.framer.generic.type = MTYPE_BITMAP;
s_specifyleague.framer.generic.name = SPECIFYLEAGUE_FRAMER;
s_specifyleague.framer.generic.flags = QMF_INACTIVE;
s_specifyleague.framer.generic.x = 376;
s_specifyleague.framer.generic.y = 76;
s_specifyleague.framer.width = 256;
s_specifyleague.framer.height = 334;
s_specifyleague.grlogo.generic.type = MTYPE_BITMAP;
s_specifyleague.grlogo.generic.name = GLOBALRANKINGS_LOGO;
s_specifyleague.grlogo.generic.flags = QMF_INACTIVE;
s_specifyleague.grlogo.generic.x = 0;
s_specifyleague.grlogo.generic.y = 0;
s_specifyleague.grlogo.width = 64;
s_specifyleague.grlogo.height = 128;
s_specifyleague.rankname.generic.type = MTYPE_FIELD;
s_specifyleague.rankname.generic.name = "Player Name:";
s_specifyleague.rankname.generic.flags = QMF_PULSEIFFOCUS|QMF_SMALLFONT;
s_specifyleague.rankname.generic.callback = SpecifyLeague_Event;
s_specifyleague.rankname.generic.id = ID_SPECIFYLEAGUENAME;
s_specifyleague.rankname.generic.x = 226;
s_specifyleague.rankname.generic.y = 128;
s_specifyleague.rankname.field.widthInChars = 32;
s_specifyleague.rankname.field.maxchars = 80;
s_specifyleague.list.generic.type = MTYPE_SCROLLLIST;
s_specifyleague.list.generic.flags = QMF_HIGHLIGHT_IF_FOCUS;
s_specifyleague.list.generic.id = ID_SPECIFYLEAGUELIST;
s_specifyleague.list.generic.callback = SpecifyLeague_Event;
s_specifyleague.list.generic.x = 160;
s_specifyleague.list.generic.y = 200;
s_specifyleague.list.width = MAX_LISTBOXWIDTH;
s_specifyleague.list.height = 8;
s_specifyleague.list.itemnames = (const char **)leaguename_items;
s_specifyleague.list.numitems = 0;
for( i = 0; i < MAX_LISTBOXITEMS; i++ ) {
league_table[i].buff[0] = 0;
league_table[i].leaguename[0] = 0;
leaguename_items[i] = league_table[i].buff;
}
s_specifyleague.arrows.generic.type = MTYPE_BITMAP;
s_specifyleague.arrows.generic.name = SPECIFYLEAGUE_ARROWS0;
s_specifyleague.arrows.generic.flags = QMF_LEFT_JUSTIFY|QMF_INACTIVE;
s_specifyleague.arrows.generic.callback = SpecifyLeague_Event;
s_specifyleague.arrows.generic.x = 512;
s_specifyleague.arrows.generic.y = 240-64+16;
s_specifyleague.arrows.width = 64;
s_specifyleague.arrows.height = 128;
s_specifyleague.up.generic.type = MTYPE_BITMAP;
s_specifyleague.up.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
s_specifyleague.up.generic.callback = SpecifyLeague_Event;
s_specifyleague.up.generic.id = ID_SPECIFYLEAGUEUP;
s_specifyleague.up.generic.x = 512;
s_specifyleague.up.generic.y = 240-64+16;
s_specifyleague.up.width = 64;
s_specifyleague.up.height = 64;
s_specifyleague.up.focuspic = SPECIFYLEAGUE_UP;
s_specifyleague.down.generic.type = MTYPE_BITMAP;
s_specifyleague.down.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS|QMF_MOUSEONLY;
s_specifyleague.down.generic.callback = SpecifyLeague_Event;
s_specifyleague.down.generic.id = ID_SPECIFYLEAGUEDOWN;
s_specifyleague.down.generic.x = 512;
s_specifyleague.down.generic.y = 240+16;
s_specifyleague.down.width = 64;
s_specifyleague.down.height = 64;
s_specifyleague.down.focuspic = SPECIFYLEAGUE_DOWN;
s_specifyleague.back.generic.type = MTYPE_BITMAP;
s_specifyleague.back.generic.name = SPECIFYLEAGUE_BACK0;
s_specifyleague.back.generic.flags = QMF_LEFT_JUSTIFY|QMF_PULSEIFFOCUS;
s_specifyleague.back.generic.callback = SpecifyLeague_Event;
s_specifyleague.back.generic.id = ID_SPECIFYLEAGUEBACK;
s_specifyleague.back.generic.x = 0;
s_specifyleague.back.generic.y = 480-64;
s_specifyleague.back.width = 128;
s_specifyleague.back.height = 64;
s_specifyleague.back.focuspic = SPECIFYLEAGUE_BACK1;
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.banner );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framel );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.framer );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.grlogo );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.rankname );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.list );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.arrows );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.up );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.down );
Menu_AddItem( &s_specifyleague.menu, &s_specifyleague.back );
// initialize any menu variables
Q_strncpyz( s_specifyleague.rankname.field.buffer,
UI_Cvar_VariableString("name"),
sizeof(s_specifyleague.rankname.field.buffer) );
Q_strncpyz( playername,
UI_Cvar_VariableString("name"),
sizeof(playername) );
SpecifyLeague_GetList();
}
/*
=================
SpecifyLeague_Cache
=================
*/
void SpecifyLeague_Cache( void )
{
int i;
// touch all our pics
for (i=0; ;i++)
{
if (!specifyleague_artlist[i])
break;
trap_R_RegisterShaderNoMip(specifyleague_artlist[i]);
}
}
/*
=================
UI_SpecifyLeagueMenu
=================
*/
void UI_SpecifyLeagueMenu( void )
{
SpecifyLeague_MenuInit();
UI_PushMenu( &s_specifyleague.menu );
}
| Java |
<div class="tx-test-extension">
<f:render section="main" />
</div> | Java |
/*
* Copyright 2010, Intel Corporation
*
* This file is part of PowerTOP
*
* This program file 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 in a file named COPYING; if not, write to the
* Free Software Foundation, Inc,
* 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA
* or just google for it.
*
* Authors:
* Arjan van de Ven <arjan@linux.intel.com>
*/
#include <iostream>
#include <fstream>
#include <algorithm>
#include "calibrate.h"
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <math.h>
#include <sys/types.h>
#include <dirent.h>
#include "../parameters/parameters.h"
extern "C" {
#include "../tuning/iw.h"
}
#include <map>
#include <vector>
#include <string>
using namespace std;
static vector<string> usb_devices;
static vector<string> rfkill_devices;
static vector<string> backlight_devices;
static vector<string> scsi_link_devices;
static int blmax;
static map<string, string> saved_sysfs;
static volatile int stop_measurement;
static int wireless_PS;
static void save_sysfs(const char *filename)
{
char line[4096];
ifstream file;
file.open(filename, ios::in);
if (!file)
return;
file.getline(line, 4096);
file.close();
saved_sysfs[filename] = line;
}
static void restore_all_sysfs(void)
{
map<string, string>::iterator it;
for (it = saved_sysfs.begin(); it != saved_sysfs.end(); it++)
write_sysfs(it->first, it->second);
set_wifi_power_saving("wlan0", wireless_PS);
}
static void find_all_usb(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/bus/usb/devices/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/bus/usb/devices/%s/power/active_duration", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
sprintf(filename, "/sys/bus/usb/devices/%s/power/idVendor", entry->d_name);
file.open(filename, ios::in);
if (file) {
file.getline(filename, 4096);
file.close();
if (strcmp(filename, "1d6b")==0)
continue;
}
sprintf(filename, "/sys/bus/usb/devices/%s/power/control", entry->d_name);
save_sysfs(filename);
usb_devices.push_back(filename);
}
closedir(dir);
}
static void suspend_all_usb_devices(void)
{
unsigned int i;
for (i = 0; i < usb_devices.size(); i++)
write_sysfs(usb_devices[i], "auto\n");
}
static void find_all_rfkill(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/class/rfkill/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/class/rfkill/%s/soft", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
save_sysfs(filename);
rfkill_devices.push_back(filename);
}
closedir(dir);
}
static void rfkill_all_radios(void)
{
unsigned int i;
for (i = 0; i < rfkill_devices.size(); i++)
write_sysfs(rfkill_devices[i], "1\n");
}
static void unrfkill_all_radios(void)
{
unsigned int i;
for (i = 0; i < rfkill_devices.size(); i++)
write_sysfs(rfkill_devices[i], "0\n");
}
static void find_backlight(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/class/backlight/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/class/backlight/%s/brightness", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
save_sysfs(filename);
backlight_devices.push_back(filename);
sprintf(filename, "/sys/class/backlight/%s/max_brightness", entry->d_name);
blmax = read_sysfs(filename);
}
closedir(dir);
}
static void lower_backlight(void)
{
unsigned int i;
for (i = 0; i < backlight_devices.size(); i++)
write_sysfs(backlight_devices[i], "0\n");
}
static void find_scsi_link(void)
{
struct dirent *entry;
DIR *dir;
char filename[4096];
dir = opendir("/sys/class/scsi_host/");
if (!dir)
return;
while (1) {
ifstream file;
entry = readdir(dir);
if (!entry)
break;
if (entry->d_name[0] == '.')
continue;
sprintf(filename, "/sys/class/scsi_host/%s/link_power_management_policy", entry->d_name);
if (access(filename, R_OK)!=0)
continue;
save_sysfs(filename);
scsi_link_devices.push_back(filename);
}
closedir(dir);
}
static void set_scsi_link(const char *state)
{
unsigned int i;
for (i = 0; i < scsi_link_devices.size(); i++)
write_sysfs(scsi_link_devices[i], state);
}
static void *burn_cpu(void *dummy)
{
volatile double d = 1.1;
while (!stop_measurement) {
d = pow(d, 1.0001);
}
return NULL;
}
static void *burn_cpu_wakeups(void *dummy)
{
struct timespec tm;
while (!stop_measurement) {
tm.tv_sec = 0;
tm.tv_nsec = (unsigned long)dummy;
nanosleep(&tm, NULL);
}
return NULL;
}
static void *burn_disk(void *dummy)
{
int fd;
char buffer[64*1024];
char filename[256];
strcpy(filename ,"/tmp/powertop.XXXXXX");
fd = mkstemp(filename);
if (fd < 0) {
printf(_("Cannot create temp file\n"));
return NULL;
}
while (!stop_measurement) {
lseek(fd, 0, SEEK_SET);
write(fd, buffer, 64*1024);
fdatasync(fd);
}
close(fd);
return NULL;
}
static void cpu_calibration(int threads)
{
int i;
pthread_t thr;
printf(_("Calibrating: CPU usage on %i threads\n"), threads);
stop_measurement = 0;
for (i = 0; i < threads; i++)
pthread_create(&thr, NULL, burn_cpu, NULL);
one_measurement(15);
stop_measurement = 1;
sleep(1);
}
static void wakeup_calibration(unsigned long interval)
{
pthread_t thr;
printf(_("Calibrating: CPU wakeup power consumption\n"));
stop_measurement = 0;
pthread_create(&thr, NULL, burn_cpu_wakeups, (void *)interval);
one_measurement(15);
stop_measurement = 1;
sleep(1);
}
static void usb_calibration(void)
{
unsigned int i;
/* chances are one of the USB devices is bluetooth; unrfkill first */
unrfkill_all_radios();
printf(_("Calibrating USB devices\n"));
for (i = 0; i < usb_devices.size(); i++) {
printf(_(".... device %s \n"), usb_devices[i].c_str());
suspend_all_usb_devices();
write_sysfs(usb_devices[i], "on\n");
one_measurement(15);
suspend_all_usb_devices();
sleep(3);
}
rfkill_all_radios();
sleep(4);
}
static void rfkill_calibration(void)
{
unsigned int i;
printf(_("Calibrating radio devices\n"));
for (i = 0; i < rfkill_devices.size(); i++) {
printf(_(".... device %s \n"), rfkill_devices[i].c_str());
rfkill_all_radios();
write_sysfs(rfkill_devices[i], "0\n");
one_measurement(15);
rfkill_all_radios();
sleep(3);
}
for (i = 0; i < rfkill_devices.size(); i++) {
printf(_(".... device %s \n"), rfkill_devices[i].c_str());
unrfkill_all_radios();
write_sysfs(rfkill_devices[i], "1\n");
one_measurement(15);
unrfkill_all_radios();
sleep(3);
}
rfkill_all_radios();
}
static void backlight_calibration(void)
{
unsigned int i;
printf(_("Calibrating backlight\n"));
for (i = 0; i < backlight_devices.size(); i++) {
char str[4096];
printf(_(".... device %s \n"), backlight_devices[i].c_str());
lower_backlight();
one_measurement(15);
sprintf(str, "%i\n", blmax / 4);
write_sysfs(backlight_devices[i], str);
one_measurement(15);
sprintf(str, "%i\n", blmax / 2);
write_sysfs(backlight_devices[i], str);
one_measurement(15);
sprintf(str, "%i\n", 3 * blmax / 4 );
write_sysfs(backlight_devices[i], str);
one_measurement(15);
sprintf(str, "%i\n", blmax);
write_sysfs(backlight_devices[i], str);
one_measurement(15);
lower_backlight();
sleep(1);
}
printf(_("Calibrating idle\n"));
system("DISPLAY=:0 /usr/bin/xset dpms force off");
one_measurement(15);
system("DISPLAY=:0 /usr/bin/xset dpms force on");
}
static void idle_calibration(void)
{
printf(_("Calibrating idle\n"));
system("DISPLAY=:0 /usr/bin/xset dpms force off");
one_measurement(15);
system("DISPLAY=:0 /usr/bin/xset dpms force on");
}
static void disk_calibration(void)
{
pthread_t thr;
printf(_("Calibrating: disk usage \n"));
set_scsi_link("min_power");
stop_measurement = 0;
pthread_create(&thr, NULL, burn_disk, NULL);
one_measurement(15);
stop_measurement = 1;
sleep(1);
}
void calibrate(void)
{
find_all_usb();
find_all_rfkill();
find_backlight();
find_scsi_link();
wireless_PS = get_wifi_power_saving("wlan0");
save_sysfs("/sys/module/snd_hda_intel/parameters/power_save");
cout << _("Starting PowerTOP power estimate calibration \n");
suspend_all_usb_devices();
rfkill_all_radios();
lower_backlight();
set_wifi_power_saving("wlan0", 1);
sleep(4);
idle_calibration();
disk_calibration();
backlight_calibration();
write_sysfs("/sys/module/snd_hda_intel/parameters/power_save", "1\n");
cpu_calibration(1);
cpu_calibration(4);
wakeup_calibration(10000);
wakeup_calibration(100000);
wakeup_calibration(1000000);
set_wifi_power_saving("wlan0", 0);
usb_calibration();
rfkill_calibration();
cout << _("Finishing PowerTOP power estimate calibration \n");
restore_all_sysfs();
learn_parameters(300, 1);
printf(_("Parameters after calibration:\n"));
dump_parameter_bundle();
save_parameters("saved_parameters.powertop");
save_all_results("saved_results.powertop");
}
| Java |
/* This file is part of the KDE project
Copyright (C) 2007, 2012 Dag Andersen danders@get2net>
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; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "kptdocumentseditor.h"
#include "kptcommand.h"
#include "kptitemmodelbase.h"
#include "kptduration.h"
#include "kptnode.h"
#include "kptproject.h"
#include "kpttask.h"
#include "kptdocuments.h"
#include "kptdatetime.h"
#include "kptitemviewsettup.h"
#include "kptdebug.h"
#include <QMenu>
#include <QList>
#include <QVBoxLayout>
#include <kaction.h>
#include <kicon.h>
#include <kglobal.h>
#include <klocale.h>
#include <kactioncollection.h>
#include <kdebug.h>
#include <KoDocument.h>
namespace KPlato
{
//--------------------
DocumentTreeView::DocumentTreeView( QWidget *parent )
: TreeViewBase( parent )
{
// header()->setContextMenuPolicy( Qt::CustomContextMenu );
setStretchLastSection( true );
DocumentItemModel *m = new DocumentItemModel();
setModel( m );
setRootIsDecorated ( false );
setSelectionBehavior( QAbstractItemView::SelectRows );
setSelectionMode( QAbstractItemView::SingleSelection );
createItemDelegates( m );
setAcceptDrops( true );
setDropIndicatorShown( true );
connect( selectionModel(), SIGNAL( selectionChanged ( const QItemSelection&, const QItemSelection& ) ), SLOT( slotSelectionChanged( const QItemSelection& ) ) );
setColumnHidden( DocumentModel::Property_Status, true ); // not used atm
}
Document *DocumentTreeView::currentDocument() const
{
return model()->document( selectionModel()->currentIndex() );
}
QModelIndexList DocumentTreeView::selectedRows() const
{
return selectionModel()->selectedRows();
}
void DocumentTreeView::slotSelectionChanged( const QItemSelection &selected )
{
emit selectionChanged( selected.indexes() );
}
QList<Document*> DocumentTreeView::selectedDocuments() const
{
QList<Document*> lst;
foreach ( const QModelIndex &i, selectionModel()->selectedRows() ) {
Document *doc = model()->document( i );
if ( doc ) {
lst << doc;
}
}
return lst;
}
//-----------------------------------
DocumentsEditor::DocumentsEditor( KoDocument *part, QWidget *parent )
: ViewBase( part, parent )
{
setupGui();
QVBoxLayout * l = new QVBoxLayout( this );
l->setMargin( 0 );
m_view = new DocumentTreeView( this );
l->addWidget( m_view );
m_view->setEditTriggers( m_view->editTriggers() | QAbstractItemView::EditKeyPressed );
connect( model(), SIGNAL( executeCommand( KUndo2Command* ) ), part, SLOT( addCommand( KUndo2Command* ) ) );
connect( m_view, SIGNAL( currentChanged( const QModelIndex &, const QModelIndex & ) ), this, SLOT( slotCurrentChanged( const QModelIndex & ) ) );
connect( m_view, SIGNAL( selectionChanged( const QModelIndexList ) ), this, SLOT( slotSelectionChanged( const QModelIndexList ) ) );
connect( m_view, SIGNAL( contextMenuRequested( QModelIndex, const QPoint& ) ), this, SLOT( slotContextMenuRequested( QModelIndex, const QPoint& ) ) );
connect( m_view, SIGNAL( headerContextMenuRequested( const QPoint& ) ), SLOT( slotHeaderContextMenuRequested( const QPoint& ) ) );
}
void DocumentsEditor::updateReadWrite( bool readwrite )
{
kDebug(planDbg())<<isReadWrite()<<"->"<<readwrite;
ViewBase::updateReadWrite( readwrite );
m_view->setReadWrite( readwrite );
updateActionsEnabled( readwrite );
}
void DocumentsEditor::draw( Documents &docs )
{
m_view->setDocuments( &docs );
}
void DocumentsEditor::draw()
{
}
void DocumentsEditor::setGuiActive( bool activate )
{
kDebug(planDbg())<<activate;
updateActionsEnabled( true );
ViewBase::setGuiActive( activate );
if ( activate && !m_view->selectionModel()->currentIndex().isValid() ) {
m_view->selectionModel()->setCurrentIndex(m_view->model()->index( 0, 0 ), QItemSelectionModel::NoUpdate);
}
}
void DocumentsEditor::slotContextMenuRequested( QModelIndex index, const QPoint& pos )
{
//kDebug(planDbg())<<index.row()<<","<<index.column()<<":"<<pos;
QString name;
if ( index.isValid() ) {
Document *obj = m_view->model()->document( index );
if ( obj ) {
name = "documentseditor_popup";
}
}
emit requestPopupMenu( name, pos );
}
void DocumentsEditor::slotHeaderContextMenuRequested( const QPoint &pos )
{
kDebug(planDbg());
QList<QAction*> lst = contextActionList();
if ( ! lst.isEmpty() ) {
QMenu::exec( lst, pos, lst.first() );
}
}
Document *DocumentsEditor::currentDocument() const
{
return m_view->currentDocument();
}
void DocumentsEditor::slotCurrentChanged( const QModelIndex & )
{
//kDebug(planDbg())<<curr.row()<<","<<curr.column();
// slotEnableActions();
}
void DocumentsEditor::slotSelectionChanged( const QModelIndexList list )
{
kDebug(planDbg())<<list.count();
updateActionsEnabled( true );
}
void DocumentsEditor::slotEnableActions( bool on )
{
updateActionsEnabled( on );
}
void DocumentsEditor::updateActionsEnabled( bool on )
{
QList<Document*> lst = m_view->selectedDocuments();
if ( lst.isEmpty() || lst.count() > 1 ) {
actionEditDocument->setEnabled( false );
actionViewDocument->setEnabled( false );
return;
}
Document *doc = lst.first();
actionViewDocument->setEnabled( on );
actionEditDocument->setEnabled( on && doc->type() == Document::Type_Product && isReadWrite() );
}
void DocumentsEditor::setupGui()
{
QString name = "documentseditor_edit_list";
actionEditDocument = new KAction(KIcon( "document-properties" ), i18n("Edit..."), this);
actionCollection()->addAction("edit_documents", actionEditDocument );
// actionEditDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) );
connect( actionEditDocument, SIGNAL( triggered( bool ) ), SLOT( slotEditDocument() ) );
addAction( name, actionEditDocument );
actionViewDocument = new KAction(KIcon( "document-preview" ), i18nc("@action View a document", "View..."), this);
actionCollection()->addAction("view_documents", actionViewDocument );
// actionViewDocument->setShortcut( KShortcut( Qt::CTRL + Qt::SHIFT + Qt::Key_I ) );
connect( actionViewDocument, SIGNAL( triggered( bool ) ), SLOT( slotViewDocument() ) );
addAction( name, actionViewDocument );
/* actionDeleteSelection = new KAction(KIcon( "edit-delete" ), i18n("Delete"), this);
actionCollection()->addAction("delete_selection", actionDeleteSelection );
actionDeleteSelection->setShortcut( KShortcut( Qt::Key_Delete ) );
connect( actionDeleteSelection, SIGNAL( triggered( bool ) ), SLOT( slotDeleteSelection() ) );
addAction( name, actionDeleteSelection );*/
// Add the context menu actions for the view options
createOptionAction();
}
void DocumentsEditor::slotOptions()
{
kDebug(planDbg());
ItemViewSettupDialog dlg( this, m_view/*->masterView()*/ );
dlg.exec();
}
void DocumentsEditor::slotEditDocument()
{
QList<Document*> dl = m_view->selectedDocuments();
if ( dl.isEmpty() ) {
return;
}
kDebug(planDbg())<<dl;
emit editDocument( dl.first() );
}
void DocumentsEditor::slotViewDocument()
{
QList<Document*> dl = m_view->selectedDocuments();
if ( dl.isEmpty() ) {
return;
}
kDebug(planDbg())<<dl;
emit viewDocument( dl.first() );
}
void DocumentsEditor::slotAddDocument()
{
//kDebug(planDbg());
QList<Document*> dl = m_view->selectedDocuments();
Document *after = 0;
if ( dl.count() > 0 ) {
after = dl.last();
}
Document *doc = new Document();
QModelIndex i = m_view->model()->insertDocument( doc, after );
if ( i.isValid() ) {
m_view->selectionModel()->setCurrentIndex( i, QItemSelectionModel::NoUpdate );
m_view->edit( i );
}
}
void DocumentsEditor::slotDeleteSelection()
{
QList<Document*> lst = m_view->selectedDocuments();
//kDebug(planDbg())<<lst.count()<<" objects";
if ( ! lst.isEmpty() ) {
emit deleteDocumentList( lst );
}
}
bool DocumentsEditor::loadContext( const KoXmlElement &context )
{
return m_view->loadContext( m_view->model()->columnMap(), context );
}
void DocumentsEditor::saveContext( QDomElement &context ) const
{
m_view->saveContext( m_view->model()->columnMap(), context );
}
} // namespace KPlato
#include "kptdocumentseditor.moc"
| Java |
#ifndef GRAPHICS_FX_H
#define GRAPHICS_FX_H
#include "video/video.h" // PlayerVisual
#include "game/game_data.h" // Player
#include "game/camera.h" // Camera
#include "video/nebu_video_types.h" // Visual
void drawImpact(int player);
void drawGlow(PlayerVisual *pV, Player *pTarget, float dim);
#endif
| Java |
/**
* Copyright (C) 2004 - 2012 Nils Asmussen
*
* 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 bbcodeeditor.control.actions;
import bbcodeeditor.control.Controller;
import bbcodeeditor.control.SecImage;
import bbcodeeditor.control.SecSmiley;
/**
* @author Assi Nilsmussen
*
*/
public final class AddImageAction extends HistoryAction {
/**
* the image to add
*/
private final SecImage _image;
/**
* constructor
*
* @param con the controller of the text-field
* @param start the start-position of this action
* @param end the end-position of this action
* @param image the image
*/
public AddImageAction(Controller con,int start,int end,SecImage image) {
super(con,start,end);
_image = image;
}
public void performAction() {
switch(_actionType) {
case UNDO:
_con.removeText(_start,_end,false);
_actionType = REDO;
break;
case REDO:
_con.addImage(_image,_start);
_con.goToPosition(_start + 1);
_actionType = UNDO;
break;
}
}
public String getName() {
String imgName;
if(_image instanceof SecSmiley)
imgName = "smiley '" + ((SecSmiley)_image).getPrimaryCode() + "'";
else
imgName = "image";
String res;
if(_actionType == UNDO)
res = "Remove " + imgName;
else
res = "Add " + imgName;
return res + " [" + _start + "," + _end + "]";
}
public String toString() {
return getName();
}
} | Java |
<?php
/**
*
*/
# Define namespace
namespace WCFE\Modules\Editor\View\Editor\Templates\Tabs\Tabs;
# Imports
use WCFE\Modules\Editor\View\Editor\Templates\Tabs\FieldsTab;
/**
*
*/
class MultiSiteOptionsTab extends FieldsTab {
/**
* put your comment there...
*
* @var mixed
*/
protected $fieldsPluggableFilterName = \WCFE\Hooks::FILTER_VIEW_TABS_TAB_MULTISITE_FIELDS;
/**
* put your comment there...
*
* @var mixed
*/
protected $fields = array
(
'WCFE\Modules\Editor\View\Editor\Templates\Fields' => array
(
'MultiSiteAllow',
'MultiSite',
'MultiSiteSubDomainInstall',
'MultiSiteDomainCurrentSite',
'MultiSitePathCurrentSite',
'MultiSiteSiteId',
'MultiSiteBlogId',
'MultiSitePrimaryNetworkId',
)
);
/**
* put your comment there...
*
*/
protected function initialize()
{
$this->title = $this->_( 'Multi Sites' );
$this->fields = $this->bcCreateFieldsList( $this->fields );
}
} | Java |
<?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; either version 2 of the License, or
* (at your option) any later version.
*
* Portions of this program are derived from publicly licensed software
* projects including, but not limited to phpBB, Magelo Clone,
* EQEmulator, EQEditor, and Allakhazam Clone.
*
* Author:
* Maudigan(Airwalking)
*
* November 24, 2013 - Maudigan
* Updated query to be compatible with the new way factions are stored in
* the database
* General code/comment/whitespace cleanup
* September 26, 2014 - Maudigan
* Updated character table name
* September 28, 2014 - Maudigan
* added code to monitor database performance
* altered character profile initialization to remove redundant query
* May 24, 2016 - Maudigan
* general code cleanup, whitespace correction, removed old comments,
* organized some code. A lot has changed, but not much functionally
* do a compare to 2.41 to see the differences.
* Implemented new database wrapper.
* October 3, 2016 - Maudigan
* Made the faction links customizable
* January 7, 2018 - Maudigan
* Modified database to use a class.
* March 9, 2020 - Maudigan
* modularized the profile menu output
* March 22, 2020 - Maudigan
* impemented common.php
* April 25, 2020 - Maudigan
* implement multi-tenancy
* May 4, 2020 - Maudigan
* clean up of the content/character data join
*
***************************************************************************/
/*********************************************
INCLUDES
*********************************************/
define('INCHARBROWSER', true);
include_once(__DIR__ . "/include/common.php");
include_once(__DIR__ . "/include/profile.php");
include_once(__DIR__ . "/include/db.php");
/*********************************************
SUPPORT FUNCTIONS
*********************************************/
//converts faction values into a the string from the language file.
function FactionToString($character_value) {
global $language;
if($character_value >= 1101) return $language['FACTION_ALLY'];
if($character_value >= 701 && $character_value <= 1100) return $language['FACTION_WARMLY'];
if($character_value >= 401 && $character_value <= 700) return $language['FACTION_KINDLY'];
if($character_value >= 101 && $character_value <= 400) return $language['FACTION_AMIABLE'];
if($character_value >= 0 && $character_value <= 100) return $language['FACTION_INDIFF'];
if($character_value >= -100 && $character_value <= -1) return $language['FACTION_APPR'];
if($character_value >= -700 && $character_value <= -101) return $language['FACTION_DUBIOUS'];
if($character_value >= -999 && $character_value <= -701) return $language['FACTION_THREAT'];
if($character_value <= -1000) return $language['FACTION_SCOWLS'];
return $language['FACTION_INDIFF'];
}
/*********************************************
SETUP PROFILE/PERMISSIONS
*********************************************/
if(!$_GET['char']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_NO_CHAR']);
else $charName = $_GET['char'];
//character initializations
$char = new profile($charName, $cbsql, $cbsql_content, $language, $showsoftdelete, $charbrowser_is_admin_page); //the profile class will sanitize the character name
$charID = $char->char_id();
$name = $char->GetValue('name');
$mypermission = GetPermissions($char->GetValue('gm'), $char->GetValue('anon'), $char->char_id());
//block view if user level doesnt have permission
if ($mypermission['factions']) cb_message_die($language['MESSAGE_ERROR'],$language['MESSAGE_ITEM_NO_VIEW']);
/*********************************************
GATHER RELEVANT PAGE DATA
*********************************************/
//get content factions from the content db
$tpl = <<<TPL
SELECT fl.id,
fl.name,
IFNULL(fl.base, 0) AS base,
IFNULL(flmc.mod, 0) AS classmod,
IFNULL(flmr.mod, 0) AS racemod,
IFNULL(flmd.mod, 0) AS deitymod
FROM faction_list AS fl
LEFT JOIN faction_list_mod AS flmc
ON fl.id = flmc.faction_id
AND (flmc.mod_name = 'c%d')
LEFT JOIN faction_list_mod AS flmr
ON fl.id = flmr.faction_id
AND (flmr.mod_name = 'r%d')
LEFT JOIN faction_list_mod AS flmd
ON fl.id = flmd.faction_id
AND (flmd.mod_name = 'd%d')
ORDER BY name ASC
TPL;
$query = sprintf(
$tpl,
$char->GetValue('class'),
$char->GetValue('race'),
($char->GetValue('deity') == 396) ? "140" : $char->GetValue('deity')
);
$result = $cbsql_content->query($query);
$content_factions = $cbsql_content->fetch_all($result);
//get the characters factions from the player db
$tpl = <<<TPL
SELECT current_value,
faction_ID
FROM faction_values
WHERE char_id = '%s'
TPL;
$query = sprintf($tpl, $charID);
$result = $cbsql->query($query);
$character_factions = $cbsql->fetch_all($result);
//DO A MANUAL JOIN OF THE RESULTS
$joined_factions = manual_join($content_factions, 'id', $character_factions, 'faction_ID', 'left');
/*********************************************
DROP HEADER
*********************************************/
$d_title = " - ".$name.$language['PAGE_TITLES_FACTIONS'];
include(__DIR__ . "/include/header.php");
/*********************************************
DROP PROFILE MENU
*********************************************/
output_profile_menu($name, 'factions');
/*********************************************
POPULATE BODY
*********************************************/
if (!$mypermission['advfactions']) {
$cb_template->set_filenames(array(
'factions' => 'factions_advanced_body.tpl')
);
}
else {
$cb_template->set_filenames(array(
'factions' => 'factions_basic_body.tpl')
);
}
$cb_template->assign_both_vars(array(
'NAME' => $name)
);
$cb_template->assign_vars(array(
'L_FACTIONS' => $language['FACTION_FACTIONS'],
'L_NAME' => $language['FACTION_NAME'],
'L_FACTION' => $language['FACTION_FACTION'],
'L_BASE' => $language['FACTION_BASE'],
'L_CHAR' => $language['FACTION_CHAR'],
'L_CLASS' => $language['FACTION_CLASS'],
'L_RACE' => $language['FACTION_RACE'],
'L_DEITY' => $language['FACTION_DEITY'],
'L_TOTAL' => $language['FACTION_TOTAL'],
'L_DONE' => $language['BUTTON_DONE'])
);
foreach($joined_factions as $faction) {
$charmod = intval($faction['current_value']);
$total = $faction['base'] + $charmod + $faction['classmod'] + $faction['racemod'] + $faction['deitymod'];
$cb_template->assign_both_block_vars("factions", array(
'ID' => $faction['id'],
'LINK' => QuickTemplate($link_faction, array('FACTION_ID' => $faction['id'])),
'NAME' => $faction['name'],
'FACTION' => FactionToString($total),
'BASE' => $faction['base'],
'CHAR' => $charmod,
'CLASS' => $faction['classmod'],
'RACE' => $faction['racemod'],
'DEITY' => $faction['deitymod'],
'TOTAL' => $total)
);
}
/*********************************************
OUTPUT BODY AND FOOTER
*********************************************/
$cb_template->pparse('factions');
$cb_template->destroy;
include(__DIR__ . "/include/footer.php");
?>
| Java |
var elixir = require('laravel-elixir');
var gulp = require("gulp");
require('laravel-elixir-wiredep');
/*
|--------------------------------------------------------------------------
| Elixir Asset Management
|--------------------------------------------------------------------------
|
| Elixir provides a clean, fluent API for defining some basic Gulp tasks
| for your Laravel application. By default, we are compiling the Less
| file for our application, as well as publishing vendor resources.
|
*/
var bowerDir = "public/vendor/";
var lessPaths = [
bowerDir + "bootstrap/less/"
]
var templatePaths = [
"resources/assets/js/app/components/*/*.html",
];
elixir.extend("templates", function(src, base, dest) {
gulp.task("templates", function () {
// the base option sets the relative root for the set of files,
// preserving the folder structure
gulp.src(src, {base: base})
.pipe(gulp.dest(dest));
});
// Watch each glob in src
for (idx in src){
var glob = src[idx];
this.registerWatcher("templates", glob);
}
return this.queueTask("templates");
});
elixir(function(mix) {
// Complile LESS into CSS
mix.less("main.less", "public/css/", {paths: lessPaths});
// Inject dependencies into layout (except bootstrap css, since that is compiled into main css)
mix.wiredep({src: "master.blade.php"}, {exclude: "vendor/bootstrap/dist/css/bootstrap.css"});
// Combine app js into one file
mix.scriptsIn("resources/assets/js/", "public/js/main.js");
// Copy angular templates to public folder
mix.templates(templatePaths, "resources/assets/js/app/components/", "public");
});
| Java |
package com.onkiup.minedroid;
import com.onkiup.minedroid.gui.resources.*;
import com.onkiup.minedroid.gui.MineDroid;
/**
* This class is auto generated.
* Manually made changes will be discarded.
**/
public final class R {
final static String MODID = "minedroid";
public final static class id {
public final static int message = 268435456;
public final static int hint = 268435457;
public final static int test = 268435458;
public final static int text = 268435459;
public final static int debug = 268435460;
public final static int close = 268435461;
public final static int edit = 268435462;
public final static int edit_multiline = 268435463;
public final static int progress = 268435464;
public final static int list = 268435465;
}
public final static class string {
public final static ValueLink cancel = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Cancel") });
public final static ValueLink test_window = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Minedroid Test") });
public final static ValueLink test = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "test") });
public final static ValueLink alert_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "click or press Y to dismiss") });
public final static ValueLink confirm_hint = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "press Y/N to respond") });
public final static ValueLink ok = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "Ok") });
public final static ValueLink close = new ValueLink(new EnvValue[] { new EnvValue(null, null, null, null, "close") });
}
public final static class layout {
public final static ResourceLink minedroid_test = new ResourceLink(MODID, "layouts", "minedroid_test.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink alert = new ResourceLink(MODID, "layouts", "alert.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink holder_string = new ResourceLink(MODID, "layouts", "holder_string.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink config_main = new ResourceLink(MODID, "layouts", "config_main.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink confirm = new ResourceLink(MODID, "layouts", "confirm.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
}
public final static class drawable {
public final static ResourceLink shadow = new ResourceLink(MODID, "drawables", "shadow.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink check = new ResourceLink(MODID, "drawables", "check.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink scroll = new ResourceLink(MODID, "drawables", "scroll.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_overlay = new ResourceLink(MODID, "drawables", "bg_overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_checkbox = new ResourceLink(MODID, "drawables", "bg_checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink fg_progress_view = new ResourceLink(MODID, "drawables", "fg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_edit_text = new ResourceLink(MODID, "drawables", "bg_edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink overlay = new ResourceLink(MODID, "drawables", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_button = new ResourceLink(MODID, "drawables", "bg_button.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
public final static ResourceLink bg_progress_view = new ResourceLink(MODID, "drawables", "bg_progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)});
}
public final static class ninepatch {
public final static ResourceLink panel = new ResourceLink(MODID, "ninepatches", "panel", new EnvParams[] { new EnvParams(null, null, null, null)});
}
public final static class style {
public final static Style focus = new Style(new ResourceLink(MODID, "styles", "focus.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout");
public final static Style content_view = new Style(new ResourceLink(MODID, "styles", "content_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view");
public final static Style relative_layout = new Style(new ResourceLink(MODID, "styles", "relative_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group");
public final static Style checkbox = new Style(new ResourceLink(MODID, "styles", "checkbox.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style entity_view = new Style(new ResourceLink(MODID, "styles", "entity_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style edit_text = new Style(new ResourceLink(MODID, "styles", "edit_text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view");
public final static Style view_group = new Style(new ResourceLink(MODID, "styles", "view_group.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style scroll_view = new Style(new ResourceLink(MODID, "styles", "scroll_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style overlay = new Style(new ResourceLink(MODID, "styles", "overlay.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style progress_view = new Style(new ResourceLink(MODID, "styles", "progress_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style text = new Style(new ResourceLink(MODID, "styles", "text.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style theme = new Style(new ResourceLink(MODID, "styles", "theme.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style text_view = new Style(new ResourceLink(MODID, "styles", "text_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/content_view");
public final static Style list_view = new Style(new ResourceLink(MODID, "styles", "list_view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/linear_layout");
public final static Style button = new Style(new ResourceLink(MODID, "styles", "button.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/text_view");
public final static Style view = new Style(new ResourceLink(MODID, "styles", "view.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class);
public final static Style linear_layout = new Style(new ResourceLink(MODID, "styles", "linear_layout.xml", new EnvParams[] { new EnvParams(null, null, null, null)}), R.class, "@minedroid:style/view_group");
}
} | Java |
package thesis;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import termo.component.Compound;
import termo.eos.Cubic;
import termo.eos.EquationsOfState;
import termo.eos.alpha.Alphas;
import termo.matter.Mixture;
import termo.matter.Substance;
import termo.phase.Phase;
import compounds.CompoundReader;
public class CubicFileGenerator extends FileGenerator {
Substance substance;
public CubicFileGenerator(){
CompoundReader reader = new CompoundReader();
Compound heptane = reader.getCompoundByExactName("N-heptane");
substance = new Substance(EquationsOfState.vanDerWaals()
,Alphas.getVanDerWaalsIndependent()
,heptane,Phase.VAPOR);
}
public void cubicEquationPressureVolumeTemperatureFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion Temperatura");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 60;
double pass = (max_volume- min_volume)/n;
int nt =20;
double min_temperature = 150;
double max_temperature = 400;
double tempPass = (max_temperature - min_temperature)/nt;
for(int j = 0; j < nt; j++){
double temperature = min_temperature + tempPass *j ;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure = calculatePressure(volume, temperature);
writer.println(" "+ volume + " " + temperature + " " + pressure);
}
writer.println();
}
writer.close();
}
public double calculatePressure(double volume, double temperature){
return substance.calculatePressure(temperature,volume);
//parametros de van der waals para el heptano
// double a = 3107000.0;
//double b = 0.2049;
// return cubic.calculatePressure(temperature, volume,a,b);
}
public void cubicEquationPressureVolumeFile(String fileName) throws FileNotFoundException, UnsupportedEncodingException{
PrintWriter writer = new PrintWriter(fileName, "UTF-8");
writer.println(" Volumen Presion");
double min_volume = 0.245;
double max_volume = 1.2;
int n = 100;
double pass = (max_volume- min_volume)/n;
for(int i=0;i < n; i++){
double volume = min_volume + pass*i;
double pressure =calculatePressure(volume, 300);
writer.println(" "+ volume + " " + pressure);
}
writer.close();
}
public void cubicEquationCompresibilitiFactorFiles(String folderName) throws FileNotFoundException, UnsupportedEncodingException{
File directory = new File(folderName);
if(!directory.exists()){
directory.mkdir();
}
Cubic cubic = EquationsOfState.vanDerWaals();
double min_reducedPressure = 0.1;
double max_reducedPressure= 7;
double pressurepass =( max_reducedPressure- min_reducedPressure)/ 100;
double min_reducedTemperature= 1 ;
double max_reducedTemperature=2;
double criticalTemperature = 540.2;
double criticalPressure = 2.74000E+06;
double a = 3107000.0;
double b = 0.2049;
PrintWriter writer= new PrintWriter(folderName + "pz_temp.dat", "UTF-8");
writer.println(" p z rt");
for(double reducedTemperature = min_reducedTemperature; reducedTemperature <= max_reducedTemperature; reducedTemperature +=0.1){
for(double reducedPressure = min_reducedPressure ; reducedPressure <= max_reducedPressure; reducedPressure+= pressurepass){
double temperature = criticalTemperature * reducedTemperature;
double pressure = criticalPressure * reducedPressure;
// double A =cubic.get_A(temperature, pressure, a);
// double B = cubic.get_B(temperature, pressure, b);
substance.setPressure(pressure);
substance.setTemperature(temperature);
double z = substance.calculateCompresibilityFactor();
//double z =cubic.calculateCompresibilityFactor(A, B, Phase.LIQUID);
writer.println(" " + reducedPressure + " " + z + " " + reducedTemperature);
}
writer.println();
}
writer.close();
}
}
| Java |
/*
* FileBrowser.cpp - implementation of the project-, preset- and
* sample-file-browser
*
* Copyright (c) 2004-2014 Tobias Doerffel <tobydox/at/users.sourceforge.net>
*
* This file is part of LMMS - http://lmms.io
*
* 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 (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include <QHBoxLayout>
#include <QKeyEvent>
#include <QLineEdit>
#include <QMenu>
#include <QPushButton>
#include <QMdiArea>
#include <QMdiSubWindow>
#include "FileBrowser.h"
#include "BBTrackContainer.h"
#include "ConfigManager.h"
#include "debug.h"
#include "embed.h"
#include "Engine.h"
#include "gui_templates.h"
#include "ImportFilter.h"
#include "Instrument.h"
#include "InstrumentTrack.h"
#include "MainWindow.h"
#include "DataFile.h"
#include "PresetPreviewPlayHandle.h"
#include "SamplePlayHandle.h"
#include "Song.h"
#include "StringPairDrag.h"
#include "TextFloat.h"
enum TreeWidgetItemTypes
{
TypeFileItem = QTreeWidgetItem::UserType,
TypeDirectoryItem
} ;
FileBrowser::FileBrowser(const QString & directories, const QString & filter,
const QString & title, const QPixmap & pm,
QWidget * parent, bool dirs_as_items ) :
SideBarWidget( title, pm, parent ),
m_directories( directories ),
m_filter( filter ),
m_dirsAsItems( dirs_as_items )
{
setWindowTitle( tr( "Browser" ) );
m_l = new FileBrowserTreeWidget( contentParent() );
addContentWidget( m_l );
QWidget * ops = new QWidget( contentParent() );
ops->setFixedHeight( 24 );
QHBoxLayout * opl = new QHBoxLayout( ops );
opl->setMargin( 0 );
opl->setSpacing( 0 );
m_filterEdit = new QLineEdit( ops );
connect( m_filterEdit, SIGNAL( textEdited( const QString & ) ),
this, SLOT( filterItems( const QString & ) ) );
QPushButton * reload_btn = new QPushButton(
embed::getIconPixmap( "reload" ),
QString::null, ops );
connect( reload_btn, SIGNAL( clicked() ), this, SLOT( reloadTree() ) );
opl->addWidget( m_filterEdit );
opl->addSpacing( 5 );
opl->addWidget( reload_btn );
addContentWidget( ops );
reloadTree();
show();
}
FileBrowser::~FileBrowser()
{
}
void FileBrowser::filterItems( const QString & filter )
{
const bool show_all = filter.isEmpty();
for( int i = 0; i < m_l->topLevelItemCount(); ++i )
{
QTreeWidgetItem * it = m_l->topLevelItem( i );
// show all items if filter is empty
if( show_all )
{
it->setHidden( false );
if( it->childCount() )
{
filterItems( it, filter );
}
}
// is directory?
else if( it->childCount() )
{
// matches filter?
if( it->text( 0 ).
contains( filter, Qt::CaseInsensitive ) )
{
// yes, then show everything below
it->setHidden( false );
filterItems( it, QString::null );
}
else
{
// only show if item below matches filter
it->setHidden( !filterItems( it, filter ) );
}
}
// a standard item (i.e. no file or directory item?)
else if( it->type() == QTreeWidgetItem::Type )
{
// hide in every case when filtering
it->setHidden( true );
}
else
{
// file matches filter?
it->setHidden( !it->text( 0 ).
contains( filter, Qt::CaseInsensitive ) );
}
}
}
bool FileBrowser::filterItems(QTreeWidgetItem * item, const QString & filter )
{
const bool show_all = filter.isEmpty();
bool matched = false;
for( int i = 0; i < item->childCount(); ++i )
{
QTreeWidgetItem * it = item->child( i );
bool cm = false; // whether current item matched
// show all items if filter is empty
if( show_all )
{
it->setHidden( false );
if( it->childCount() )
{
filterItems( it, filter );
}
}
// is directory?
else if( it->childCount() )
{
// matches filter?
if( it->text( 0 ).
contains( filter, Qt::CaseInsensitive ) )
{
// yes, then show everything below
it->setHidden( false );
filterItems( it, QString::null );
cm = true;
}
else
{
// only show if item below matches filter
cm = filterItems( it, filter );
it->setHidden( !cm );
}
}
// a standard item (i.e. no file or directory item?)
else if( it->type() == QTreeWidgetItem::Type )
{
// hide in every case when filtering
it->setHidden( true );
}
else
{
// file matches filter?
cm = it->text( 0 ).
contains( filter, Qt::CaseInsensitive );
it->setHidden( !cm );
}
if( cm )
{
matched = true;
}
}
return matched;
}
void FileBrowser::reloadTree( void )
{
const QString text = m_filterEdit->text();
m_filterEdit->clear();
m_l->clear();
QStringList paths = m_directories.split( '*' );
for( QStringList::iterator it = paths.begin(); it != paths.end(); ++it )
{
addItems( *it );
}
m_filterEdit->setText( text );
filterItems( text );
}
void FileBrowser::addItems(const QString & path )
{
if( m_dirsAsItems )
{
m_l->addTopLevelItem( new Directory( path,
QString::null, m_filter ) );
return;
}
QDir cdir( path );
QStringList files = cdir.entryList( QDir::Dirs, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' )
{
bool orphan = true;
for( int i = 0; i < m_l->topLevelItemCount(); ++i )
{
Directory * d = dynamic_cast<Directory *>(
m_l->topLevelItem( i ) );
if( d == NULL || cur_file < d->text( 0 ) )
{
m_l->insertTopLevelItem( i,
new Directory( cur_file, path,
m_filter ) );
orphan = false;
break;
}
else if( cur_file == d->text( 0 ) )
{
d->addDirectory( path );
orphan = false;
break;
}
}
if( orphan )
{
m_l->addTopLevelItem( new Directory( cur_file,
path, m_filter ) );
}
}
}
files = cdir.entryList( QDir::Files, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' )
{
// TODO: don't insert instead of removing, order changed
// remove existing file-items
QList<QTreeWidgetItem *> existing = m_l->findItems(
cur_file, Qt::MatchFixedString );
if( !existing.empty() )
{
delete existing.front();
}
(void) new FileItem( m_l, cur_file, path );
}
}
}
void FileBrowser::keyPressEvent(QKeyEvent * ke )
{
if( ke->key() == Qt::Key_F5 )
{
reloadTree();
}
else
{
ke->ignore();
}
}
FileBrowserTreeWidget::FileBrowserTreeWidget(QWidget * parent ) :
QTreeWidget( parent ),
m_mousePressed( false ),
m_pressPos(),
m_previewPlayHandle( NULL ),
m_pphMutex( QMutex::Recursive ),
m_contextMenuItem( NULL )
{
setColumnCount( 1 );
headerItem()->setHidden( true );
setSortingEnabled( false );
setFont( pointSizeF( font(), 7.5f ) );
connect( this, SIGNAL( itemDoubleClicked( QTreeWidgetItem *, int ) ),
SLOT( activateListItem( QTreeWidgetItem *, int ) ) );
connect( this, SIGNAL( itemCollapsed( QTreeWidgetItem * ) ),
SLOT( updateDirectory( QTreeWidgetItem * ) ) );
connect( this, SIGNAL( itemExpanded( QTreeWidgetItem * ) ),
SLOT( updateDirectory( QTreeWidgetItem * ) ) );
}
FileBrowserTreeWidget::~FileBrowserTreeWidget()
{
}
void FileBrowserTreeWidget::contextMenuEvent(QContextMenuEvent * e )
{
FileItem * f = dynamic_cast<FileItem *>( itemAt( e->pos() ) );
if( f != NULL && ( f->handling() == FileItem::LoadAsPreset ||
f->handling() == FileItem::LoadByPlugin ) )
{
m_contextMenuItem = f;
QMenu contextMenu( this );
contextMenu.addAction( tr( "Send to active instrument-track" ),
this,
SLOT( sendToActiveInstrumentTrack() ) );
contextMenu.addAction( tr( "Open in new instrument-track/"
"Song-Editor" ),
this,
SLOT( openInNewInstrumentTrackSE() ) );
contextMenu.addAction( tr( "Open in new instrument-track/"
"B+B Editor" ),
this,
SLOT( openInNewInstrumentTrackBBE() ) );
contextMenu.exec( e->globalPos() );
m_contextMenuItem = NULL;
}
}
void FileBrowserTreeWidget::mousePressEvent(QMouseEvent * me )
{
QTreeWidget::mousePressEvent( me );
if( me->button() != Qt::LeftButton )
{
return;
}
QTreeWidgetItem * i = itemAt( me->pos() );
if ( i )
{
// TODO: Restrict to visible selection
// if ( _me->x() > header()->cellPos( header()->mapToActual( 0 ) )
// + treeStepSize() * ( i->depth() + ( rootIsDecorated() ?
// 1 : 0 ) ) + itemMargin() ||
// _me->x() < header()->cellPos(
// header()->mapToActual( 0 ) ) )
// {
m_pressPos = me->pos();
m_mousePressed = true;
// }
}
FileItem * f = dynamic_cast<FileItem *>( i );
if( f != NULL )
{
m_pphMutex.lock();
if( m_previewPlayHandle != NULL )
{
Engine::mixer()->removePlayHandle(
m_previewPlayHandle );
m_previewPlayHandle = NULL;
}
// in special case of sample-files we do not care about
// handling() rather than directly creating a SamplePlayHandle
if( f->type() == FileItem::SampleFile )
{
TextFloat * tf = TextFloat::displayMessage(
tr( "Loading sample" ),
tr( "Please wait, loading sample for "
"preview..." ),
embed::getIconPixmap( "sample_file",
24, 24 ), 0 );
qApp->processEvents(
QEventLoop::ExcludeUserInputEvents );
SamplePlayHandle * s = new SamplePlayHandle(
f->fullName() );
s->setDoneMayReturnTrue( false );
m_previewPlayHandle = s;
delete tf;
}
else if( f->type() != FileItem::VstPluginFile &&
( f->handling() == FileItem::LoadAsPreset ||
f->handling() == FileItem::LoadByPlugin ) )
{
m_previewPlayHandle = new PresetPreviewPlayHandle( f->fullName(), f->handling() == FileItem::LoadByPlugin );
}
if( m_previewPlayHandle != NULL )
{
if( !Engine::mixer()->addPlayHandle(
m_previewPlayHandle ) )
{
m_previewPlayHandle = NULL;
}
}
m_pphMutex.unlock();
}
}
void FileBrowserTreeWidget::mouseMoveEvent( QMouseEvent * me )
{
if( m_mousePressed == true &&
( m_pressPos - me->pos() ).manhattanLength() >
QApplication::startDragDistance() )
{
// make sure any playback is stopped
mouseReleaseEvent( NULL );
FileItem * f = dynamic_cast<FileItem *>( itemAt( m_pressPos ) );
if( f != NULL )
{
switch( f->type() )
{
case FileItem::PresetFile:
new StringPairDrag( f->handling() == FileItem::LoadAsPreset ?
"presetfile" : "pluginpresetfile",
f->fullName(),
embed::getIconPixmap( "preset_file" ), this );
break;
case FileItem::SampleFile:
new StringPairDrag( "samplefile", f->fullName(),
embed::getIconPixmap( "sample_file" ), this );
break;
case FileItem::SoundFontFile:
new StringPairDrag( "soundfontfile", f->fullName(),
embed::getIconPixmap( "soundfont_file" ), this );
break;
case FileItem::VstPluginFile:
new StringPairDrag( "vstpluginfile", f->fullName(),
embed::getIconPixmap( "vst_plugin_file" ), this );
break;
case FileItem::MidiFile:
// don't allow dragging FLP-files as FLP import filter clears project
// without asking
// case fileItem::FlpFile:
new StringPairDrag( "importedproject", f->fullName(),
embed::getIconPixmap( "midi_file" ), this );
break;
default:
break;
}
}
}
}
void FileBrowserTreeWidget::mouseReleaseEvent(QMouseEvent * me )
{
m_mousePressed = false;
m_pphMutex.lock();
if( m_previewPlayHandle != NULL )
{
// if there're samples shorter than 3 seconds, we don't
// stop them if the user releases mouse-button...
if( m_previewPlayHandle->type() == PlayHandle::TypeSamplePlayHandle )
{
SamplePlayHandle * s = dynamic_cast<SamplePlayHandle *>(
m_previewPlayHandle );
if( s && s->totalFrames() - s->framesDone() <=
static_cast<f_cnt_t>( Engine::mixer()->
processingSampleRate() * 3 ) )
{
s->setDoneMayReturnTrue( true );
m_previewPlayHandle = NULL;
m_pphMutex.unlock();
return;
}
}
Engine::mixer()->removePlayHandle( m_previewPlayHandle );
m_previewPlayHandle = NULL;
}
m_pphMutex.unlock();
}
void FileBrowserTreeWidget::handleFile(FileItem * f, InstrumentTrack * it )
{
Engine::mixer()->lock();
switch( f->handling() )
{
case FileItem::LoadAsProject:
if( Engine::mainWindow()->mayChangeProject() )
{
Engine::getSong()->loadProject( f->fullName() );
}
break;
case FileItem::LoadByPlugin:
{
const QString e = f->extension();
Instrument * i = it->instrument();
if( i == NULL ||
!i->descriptor()->supportsFileType( e ) )
{
i = it->loadInstrument(
Engine::pluginFileHandling()[e] );
}
i->loadFile( f->fullName() );
break;
}
case FileItem::LoadAsPreset:
{
DataFile dataFile( f->fullName() );
InstrumentTrack::removeMidiPortNode( dataFile );
it->setSimpleSerializing();
it->loadSettings( dataFile.content().toElement() );
break;
}
case FileItem::ImportAsProject:
if( f->type() == FileItem::FlpFile &&
!Engine::mainWindow()->mayChangeProject() )
{
break;
}
ImportFilter::import( f->fullName(),
Engine::getSong() );
break;
case FileItem::NotSupported:
default:
break;
}
Engine::mixer()->unlock();
}
void FileBrowserTreeWidget::activateListItem(QTreeWidgetItem * item,
int column )
{
FileItem * f = dynamic_cast<FileItem *>( item );
if( f == NULL )
{
return;
}
if( f->handling() == FileItem::LoadAsProject ||
f->handling() == FileItem::ImportAsProject )
{
handleFile( f, NULL );
}
else if( f->handling() != FileItem::NotSupported )
{
// engine::mixer()->lock();
InstrumentTrack * it = dynamic_cast<InstrumentTrack *>(
Track::create( Track::InstrumentTrack,
Engine::getBBTrackContainer() ) );
handleFile( f, it );
// engine::mixer()->unlock();
}
}
void FileBrowserTreeWidget::openInNewInstrumentTrack( TrackContainer* tc )
{
if( m_contextMenuItem->handling() == FileItem::LoadAsPreset ||
m_contextMenuItem->handling() == FileItem::LoadByPlugin )
{
// engine::mixer()->lock();
InstrumentTrack * it = dynamic_cast<InstrumentTrack *>(
Track::create( Track::InstrumentTrack, tc ) );
handleFile( m_contextMenuItem, it );
// engine::mixer()->unlock();
}
}
void FileBrowserTreeWidget::openInNewInstrumentTrackBBE( void )
{
openInNewInstrumentTrack( Engine::getBBTrackContainer() );
}
void FileBrowserTreeWidget::openInNewInstrumentTrackSE( void )
{
openInNewInstrumentTrack( Engine::getSong() );
}
void FileBrowserTreeWidget::sendToActiveInstrumentTrack( void )
{
// get all windows opened in the workspace
QList<QMdiSubWindow*> pl =
Engine::mainWindow()->workspace()->
subWindowList( QMdiArea::StackingOrder );
QListIterator<QMdiSubWindow *> w( pl );
w.toBack();
// now we travel through the window-list until we find an
// instrument-track
while( w.hasPrevious() )
{
InstrumentTrackWindow * itw =
dynamic_cast<InstrumentTrackWindow *>(
w.previous()->widget() );
if( itw != NULL && itw->isHidden() == false )
{
handleFile( m_contextMenuItem, itw->model() );
break;
}
}
}
void FileBrowserTreeWidget::updateDirectory(QTreeWidgetItem * item )
{
Directory * dir = dynamic_cast<Directory *>( item );
if( dir != NULL )
{
dir->update();
}
}
QPixmap * Directory::s_folderPixmap = NULL;
QPixmap * Directory::s_folderOpenedPixmap = NULL;
QPixmap * Directory::s_folderLockedPixmap = NULL;
Directory::Directory(const QString & filename, const QString & path,
const QString & filter ) :
QTreeWidgetItem( QStringList( filename ), TypeDirectoryItem ),
m_directories( path ),
m_filter( filter )
{
initPixmaps();
setChildIndicatorPolicy( QTreeWidgetItem::ShowIndicator );
if( !QDir( fullName() ).isReadable() )
{
setIcon( 0, *s_folderLockedPixmap );
}
else
{
setIcon( 0, *s_folderPixmap );
}
}
void Directory::initPixmaps( void )
{
if( s_folderPixmap == NULL )
{
s_folderPixmap = new QPixmap(
embed::getIconPixmap( "folder" ) );
}
if( s_folderOpenedPixmap == NULL )
{
s_folderOpenedPixmap = new QPixmap(
embed::getIconPixmap( "folder_opened" ) );
}
if( s_folderLockedPixmap == NULL )
{
s_folderLockedPixmap = new QPixmap(
embed::getIconPixmap( "folder_locked" ) );
}
}
void Directory::update( void )
{
if( !isExpanded() )
{
setIcon( 0, *s_folderPixmap );
return;
}
setIcon( 0, *s_folderOpenedPixmap );
if( !childCount() )
{
for( QStringList::iterator it = m_directories.begin();
it != m_directories.end(); ++it )
{
int top_index = childCount();
if( addItems( fullName( *it ) ) &&
( *it ).contains(
ConfigManager::inst()->dataDir() ) )
{
QTreeWidgetItem * sep = new QTreeWidgetItem;
sep->setText( 0,
FileBrowserTreeWidget::tr(
"--- Factory files ---" ) );
sep->setIcon( 0, embed::getIconPixmap(
"factory_files" ) );
insertChild( top_index, sep );
}
}
}
}
bool Directory::addItems(const QString & path )
{
QDir thisDir( path );
if( !thisDir.isReadable() )
{
return false;
}
treeWidget()->setUpdatesEnabled( false );
bool added_something = false;
QStringList files = thisDir.entryList( QDir::Dirs, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' )
{
bool orphan = true;
for( int i = 0; i < childCount(); ++i )
{
Directory * d = dynamic_cast<Directory *>(
child( i ) );
if( d == NULL || cur_file < d->text( 0 ) )
{
insertChild( i, new Directory( cur_file,
path, m_filter ) );
orphan = false;
break;
}
else if( cur_file == d->text( 0 ) )
{
d->addDirectory( path );
orphan = false;
break;
}
}
if( orphan )
{
addChild( new Directory( cur_file, path,
m_filter ) );
}
added_something = true;
}
}
QList<QTreeWidgetItem*> items;
files = thisDir.entryList( QDir::Files, QDir::Name );
for( QStringList::const_iterator it = files.constBegin();
it != files.constEnd(); ++it )
{
QString cur_file = *it;
if( cur_file[0] != '.' &&
thisDir.match( m_filter, cur_file.toLower() ) )
{
items << new FileItem( cur_file, path );
added_something = true;
}
}
addChildren( items );
treeWidget()->setUpdatesEnabled( true );
return added_something;
}
QPixmap * FileItem::s_projectFilePixmap = NULL;
QPixmap * FileItem::s_presetFilePixmap = NULL;
QPixmap * FileItem::s_sampleFilePixmap = NULL;
QPixmap * FileItem::s_soundfontFilePixmap = NULL;
QPixmap * FileItem::s_vstPluginFilePixmap = NULL;
QPixmap * FileItem::s_midiFilePixmap = NULL;
QPixmap * FileItem::s_flpFilePixmap = NULL;
QPixmap * FileItem::s_unknownFilePixmap = NULL;
FileItem::FileItem(QTreeWidget * parent, const QString & name,
const QString & path ) :
QTreeWidgetItem( parent, QStringList( name) , TypeFileItem ),
m_path( path )
{
determineFileType();
initPixmaps();
}
FileItem::FileItem(const QString & name, const QString & path ) :
QTreeWidgetItem( QStringList( name ), TypeFileItem ),
m_path( path )
{
determineFileType();
initPixmaps();
}
void FileItem::initPixmaps( void )
{
if( s_projectFilePixmap == NULL )
{
s_projectFilePixmap = new QPixmap( embed::getIconPixmap(
"project_file", 16, 16 ) );
}
if( s_presetFilePixmap == NULL )
{
s_presetFilePixmap = new QPixmap( embed::getIconPixmap(
"preset_file", 16, 16 ) );
}
if( s_sampleFilePixmap == NULL )
{
s_sampleFilePixmap = new QPixmap( embed::getIconPixmap(
"sample_file", 16, 16 ) );
}
if ( s_soundfontFilePixmap == NULL )
{
s_soundfontFilePixmap = new QPixmap( embed::getIconPixmap(
"soundfont_file", 16, 16 ) );
}
if ( s_vstPluginFilePixmap == NULL )
{
s_vstPluginFilePixmap = new QPixmap( embed::getIconPixmap(
"vst_plugin_file", 16, 16 ) );
}
if( s_midiFilePixmap == NULL )
{
s_midiFilePixmap = new QPixmap( embed::getIconPixmap(
"midi_file", 16, 16 ) );
}
if( s_flpFilePixmap == NULL )
{
s_flpFilePixmap = new QPixmap( embed::getIconPixmap(
"midi_file", 16, 16 ) );
}
if( s_unknownFilePixmap == NULL )
{
s_unknownFilePixmap = new QPixmap( embed::getIconPixmap(
"unknown_file" ) );
}
switch( m_type )
{
case ProjectFile:
setIcon( 0, *s_projectFilePixmap );
break;
case PresetFile:
setIcon( 0, *s_presetFilePixmap );
break;
case SoundFontFile:
setIcon( 0, *s_soundfontFilePixmap );
break;
case VstPluginFile:
setIcon( 0, *s_vstPluginFilePixmap );
break;
case SampleFile:
case PatchFile: // TODO
setIcon( 0, *s_sampleFilePixmap );
break;
case MidiFile:
setIcon( 0, *s_midiFilePixmap );
break;
case FlpFile:
setIcon( 0, *s_flpFilePixmap );
break;
case UnknownFile:
default:
setIcon( 0, *s_unknownFilePixmap );
break;
}
}
void FileItem::determineFileType( void )
{
m_handling = NotSupported;
const QString ext = extension();
if( ext == "mmp" || ext == "mpt" || ext == "mmpz" )
{
m_type = ProjectFile;
m_handling = LoadAsProject;
}
else if( ext == "xpf" || ext == "xml" )
{
m_type = PresetFile;
m_handling = LoadAsPreset;
}
else if( ext == "xiz" && Engine::pluginFileHandling().contains( ext ) )
{
m_type = PresetFile;
m_handling = LoadByPlugin;
}
else if( ext == "sf2" )
{
m_type = SoundFontFile;
}
else if( ext == "pat" )
{
m_type = PatchFile;
}
else if( ext == "mid" )
{
m_type = MidiFile;
m_handling = ImportAsProject;
}
else if( ext == "flp" )
{
m_type = FlpFile;
m_handling = ImportAsProject;
}
else if( ext == "dll" )
{
m_type = VstPluginFile;
m_handling = LoadByPlugin;
}
else
{
m_type = UnknownFile;
}
if( m_handling == NotSupported &&
!ext.isEmpty() && Engine::pluginFileHandling().contains( ext ) )
{
m_handling = LoadByPlugin;
// classify as sample if not classified by anything yet but can
// be handled by a certain plugin
if( m_type == UnknownFile )
{
m_type = SampleFile;
}
}
}
QString FileItem::extension( void )
{
return extension( fullName() );
}
QString FileItem::extension(const QString & file )
{
return QFileInfo( file ).suffix().toLower();
}
| Java |
/*
* Copyright (c) 2002-2009 BalaBit IT Ltd, Budapest, Hungary
*
* 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.
*
* Note that this permission is granted for only version 2 of the GPL.
*
* As an additional exemption you are allowed to compile & link against the
* OpenSSL libraries as published by the OpenSSL project. See the file
* COPYING for details.
*
* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "gprocess.h"
#include "misc.h"
#include "messages.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <time.h>
#include <sys/resource.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <fcntl.h>
#include <termios.h>
#include <signal.h>
#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>
#if ENABLE_LINUX_CAPS
# include <sys/capability.h>
# include <sys/prctl.h>
#endif
/*
* NOTES:
*
* * pidfile is created and removed by the daemon (e.g. the child) itself,
* the parent does not touch that
*
* * we communicate with the user using stderr (using fprintf) as long as it
* is available and using syslog() afterwards
*
* * there are 3 processes involved in safe_background mode (e.g. auto-restart)
* - startup process which was started by the user (zorpctl)
* - supervisor process which automatically restarts the daemon when it exits abnormally
* - daemon processes which perform the actual task at hand
*
* The startup process delivers the result of the first startup to its
* caller, if we can deliver a failure in this case then restarts will not
* be performed (e.g. if the first startup fails, the daemon will not be
* restarted even if auto-restart was enabled). After the first successful
* start, the startup process exits (delivering that startup was
* successful) and the supervisor process wait()s for the daemon processes
* to exit. If they exit prematurely (e.g. they crash) they will be
* restarted, if the startup is not successful in this case the restart
* will be attempted again just as if they crashed.
*
* The processes communicate with two pairs of pipes, startup_result_pipe
* is used to indicate success/failure to the startup process,
* init_result_pipe (as in "initialization") is used to deliver success
* reports from the daemon to the supervisor.
*/
typedef enum
{
G_PK_STARTUP,
G_PK_SUPERVISOR,
G_PK_DAEMON,
} GProcessKind;
#define G_PROCESS_FD_LIMIT_RESERVE 64
#define G_PROCESS_FAILURE_NOTIFICATION PATH_PREFIX "/sbin/syslog-ng-failure"
/* pipe used to deliver the initialization result to the calling process */
static gint startup_result_pipe[2] = { -1, -1 };
/* pipe used to deliver initialization result to the supervisor */
static gint init_result_pipe[2] = { -1, -1 };
static GProcessKind process_kind = G_PK_STARTUP;
static gboolean stderr_present = TRUE;
/* global variables */
static struct
{
GProcessMode mode;
const gchar *name;
const gchar *user;
gint uid;
const gchar *group;
gint gid;
const gchar *chroot_dir;
const gchar *pidfile;
const gchar *pidfile_dir;
const gchar *cwd;
const gchar *caps;
gint argc;
gchar **argv;
gchar *argv_start;
size_t argv_env_len;
gchar *argv_orig;
gboolean core;
gint fd_limit_min;
gint check_period;
gboolean (*check_fn)(void);
} process_opts =
{
.mode = G_PM_SAFE_BACKGROUND,
.argc = 0,
.argv = NULL,
.argv_start = NULL,
.argv_env_len = 0,
#ifdef __CYGWIN__
.fd_limit_min = 256,
#else
.fd_limit_min = 4096,
#endif
.check_period = -1,
.check_fn = NULL,
.uid = -1,
.gid = -1
};
#if ENABLE_LINUX_CAPS
/**
* g_process_cap_modify:
* @capability: capability to turn off or on
* @onoff: specifies whether the capability should be enabled or disabled
*
* This function modifies the current permitted set of capabilities by
* enabling or disabling the capability specified in @capability.
*
* Returns: whether the operation was successful.
**/
gboolean
g_process_cap_modify(int capability, int onoff)
{
cap_t caps;
if (!process_opts.caps)
return TRUE;
caps = cap_get_proc();
if (!caps)
return FALSE;
if (cap_set_flag(caps, CAP_EFFECTIVE, 1, &capability, onoff) == -1)
{
msg_error("Error managing capability set, cap_set_flag returned an error",
evt_tag_errno("error", errno),
NULL);
cap_free(caps);
return FALSE;
}
if (cap_set_proc(caps) == -1)
{
gchar *cap_text;
cap_text = cap_to_text(caps, NULL);
msg_error("Error managing capability set, cap_set_proc returned an error",
evt_tag_str("caps", cap_text),
evt_tag_errno("error", errno),
NULL);
cap_free(cap_text);
cap_free(caps);
return FALSE;
}
cap_free(caps);
return TRUE;
}
/**
* g_process_cap_save:
*
* Save the set of current capabilities and return it. The caller might
* restore the saved set of capabilities by using cap_restore().
*
* Returns: the current set of capabilities
**/
cap_t
g_process_cap_save(void)
{
if (!process_opts.caps)
return NULL;
return cap_get_proc();
}
/**
* cap_restore:
* @r: capability set saved by cap_save()
*
* Restore the set of current capabilities specified by @r.
*
* Returns: whether the operation was successful.
**/
void
g_process_cap_restore(cap_t r)
{
gboolean rc;
if (!process_opts.caps)
return;
rc = cap_set_proc(r) != -1;
cap_free(r);
if (!rc)
{
gchar *cap_text;
cap_text = cap_to_text(r, NULL);
msg_error("Error managing capability set, cap_set_proc returned an error",
evt_tag_str("caps", cap_text),
evt_tag_errno("error", errno),
NULL);
cap_free(cap_text);
return;
}
return;
}
#endif
/**
* g_process_set_mode:
* @mode: an element from ZProcessMode
*
* This function should be called by the daemon to set the processing mode
* as specified by @mode.
**/
void
g_process_set_mode(GProcessMode mode)
{
process_opts.mode = mode;
}
/**
* g_process_set_name:
* @name: the name of the process to be reported as program name
*
* This function should be called by the daemon to set the program name
* which is present in various error message and might influence the PID
* file if not overridden by g_process_set_pidfile().
**/
void
g_process_set_name(const gchar *name)
{
process_opts.name = name;
}
/**
* g_process_set_user:
* @user: the name of the user the process should switch to during startup
*
* This function should be called by the daemon to set the user name.
**/
void
g_process_set_user(const gchar *user)
{
if (!process_opts.user)
process_opts.user = user;
}
/**
* g_process_set_group:
* @group: the name of the group the process should switch to during startup
*
* This function should be called by the daemon to set the group name.
**/
void
g_process_set_group(const gchar *group)
{
if (!process_opts.group)
process_opts.group = group;
}
/**
* g_process_set_chroot:
* @chroot_dir: the name of the chroot directory the process should switch to during startup
*
* This function should be called by the daemon to set the chroot directory
**/
void
g_process_set_chroot(const gchar *chroot_dir)
{
if (!process_opts.chroot_dir)
process_opts.chroot_dir = chroot_dir;
}
/**
* g_process_set_pidfile:
* @pidfile: the name of the complete pid file with full path
*
* This function should be called by the daemon to set the PID file name to
* store the pid of the process. This value will be used as the pidfile
* directly, neither name nor pidfile_dir influences the pidfile location if
* this is set.
**/
void
g_process_set_pidfile(const gchar *pidfile)
{
if (!process_opts.pidfile)
process_opts.pidfile = pidfile;
}
/**
* g_process_set_pidfile_dir:
* @pidfile_dir: name of the pidfile directory
*
* This function should be called by the daemon to set the PID file
* directory. This value is not used if set_pidfile() was called.
**/
void
g_process_set_pidfile_dir(const gchar *pidfile_dir)
{
if (!process_opts.pidfile_dir)
process_opts.pidfile_dir = pidfile_dir;
}
/**
* g_process_set_working_dir:
* @working_dir: name of the working directory
*
* This function should be called by the daemon to set the working
* directory. The process will change its current directory to this value or
* to pidfile_dir if it is unset.
**/
void
g_process_set_working_dir(const gchar *cwd)
{
if (!process_opts.cwd)
process_opts.cwd = cwd;
}
/**
* g_process_set_caps:
* @caps: capability specification in text form
*
* This function should be called by the daemon to set the initial
* capability set. The process will change its capabilities to this value
* during startup, provided it has enough permissions to do so.
**/
void
g_process_set_caps(const gchar *caps)
{
if (!process_opts.caps)
process_opts.caps = caps;
}
/**
* g_process_set_argv_space:
* @argc: Original argc, as received by the main function in it's first parameter
* @argv: Original argv, as received by the main function in it's second parameter
*
* This function should be called by the daemon if it wants to enable
* process title manipulation in the supervisor process.
**/
void
g_process_set_argv_space(gint argc, gchar **argv)
{
extern char **environ;
gchar *lastargv = NULL;
gchar **envp = environ;
gint i;
if (process_opts.argv)
return;
process_opts.argv = argv;
process_opts.argc = argc;
for (i = 0; envp[i] != NULL; i++)
;
environ = g_new(char *, i + 1);
/*
* Find the last argv string or environment variable within
* our process memory area.
*/
for (i = 0; i < process_opts.argc; i++)
{
if (lastargv == NULL || lastargv + 1 == process_opts.argv[i])
lastargv = process_opts.argv[i] + strlen(process_opts.argv[i]);
}
for (i = 0; envp[i] != NULL; i++)
{
if (lastargv + 1 == envp[i])
lastargv = envp[i] + strlen(envp[i]);
}
process_opts.argv_start = process_opts.argv[0];
process_opts.argv_env_len = lastargv - process_opts.argv[0] - 1;
process_opts.argv_orig = malloc(sizeof(gchar) * process_opts.argv_env_len);
memcpy(process_opts.argv_orig, process_opts.argv_start, process_opts.argv_env_len);
/*
* Copy environment
* XXX - will truncate env on strdup fail
*/
for (i = 0; envp[i] != NULL; i++)
environ[i] = g_strdup(envp[i]);
environ[i] = NULL;
}
/**
* g_process_set_check:
* @check_period: check period in seconds
* @check_fn: checker function
*
* Installs a checker function that is called at the specified rate.
* The checked process is allowed to run as long as this function
* returns TRUE.
*/
void
g_process_set_check(gint check_period, gboolean (*check_fn)(void))
{
process_opts.check_period = check_period;
process_opts.check_fn = check_fn;
}
/**
* g_process_message:
* @fmt: format string
* @...: arguments to @fmt
*
* This function sends a message to the client preferring to use the stderr
* channel as long as it is available and switching to using syslog() if it
* isn't. Generally the stderr channell will be available in the startup
* process and in the beginning of the first startup in the
* supervisor/daemon processes. Later on the stderr fd will be closed and we
* have to fall back to using the system log.
**/
void
g_process_message(const gchar *fmt, ...)
{
gchar buf[2048];
va_list ap;
va_start(ap, fmt);
g_vsnprintf(buf, sizeof(buf), fmt, ap);
va_end(ap);
if (stderr_present)
fprintf(stderr, "%s: %s\n", process_opts.name, buf);
else
{
gchar name[32];
g_snprintf(name, sizeof(name), "%s/%s", process_kind == G_PK_SUPERVISOR ? "supervise" : "daemon", process_opts.name);
openlog(name, LOG_PID, LOG_DAEMON);
syslog(LOG_CRIT, "%s\n", buf);
closelog();
}
}
/**
* g_process_detach_tty:
*
* This function is called from g_process_start() to detach from the
* controlling tty.
**/
static void
g_process_detach_tty(void)
{
if (process_opts.mode != G_PM_FOREGROUND)
{
/* detach ourselves from the tty when not staying in the foreground */
if (isatty(STDIN_FILENO))
{
#ifdef TIOCNOTTY
ioctl(STDIN_FILENO, TIOCNOTTY, 0);
#endif
setsid();
}
}
}
/**
* g_process_change_limits:
*
* Set fd limit.
*
**/
static void
g_process_change_limits(void)
{
struct rlimit limit;
limit.rlim_cur = limit.rlim_max = process_opts.fd_limit_min;
if (setrlimit(RLIMIT_NOFILE, &limit) < 0)
g_process_message("Error setting file number limit; limit='%d'; error='%s'", process_opts.fd_limit_min, g_strerror(errno));
}
/**
* g_process_detach_stdio:
*
* Use /dev/null as input/output/error. This function is idempotent, can be
* called any number of times without harm.
**/
static void
g_process_detach_stdio(void)
{
gint devnull_fd;
if (process_opts.mode != G_PM_FOREGROUND && stderr_present)
{
devnull_fd = open("/dev/null", O_RDONLY);
if (devnull_fd >= 0)
{
dup2(devnull_fd, STDIN_FILENO);
close(devnull_fd);
}
devnull_fd = open("/dev/null", O_WRONLY);
if (devnull_fd >= 0)
{
dup2(devnull_fd, STDOUT_FILENO);
dup2(devnull_fd, STDERR_FILENO);
close(devnull_fd);
}
stderr_present = FALSE;
}
}
/**
* g_process_enable_core:
*
* Enable core file dumping by setting PR_DUMPABLE and changing the core
* file limit to infinity.
**/
static void
g_process_enable_core(void)
{
struct rlimit limit;
if (process_opts.core)
{
#if ENABLE_LINUX_CAPS
if (!prctl(PR_GET_DUMPABLE, 0, 0, 0, 0))
{
gint rc;
rc = prctl(PR_SET_DUMPABLE, 1, 0, 0, 0);
if (rc < 0)
g_process_message("Cannot set process to be dumpable; error='%s'", g_strerror(errno));
}
#endif
limit.rlim_cur = limit.rlim_max = RLIM_INFINITY;
if (setrlimit(RLIMIT_CORE, &limit) < 0)
g_process_message("Error setting core limit to infinity; error='%s'", g_strerror(errno));
}
}
/**
* g_process_format_pidfile_name:
* @buf: buffer to store the pidfile name
* @buflen: size of @buf
*
* Format the pid file name according to the settings specified by the
* process.
**/
static const gchar *
g_process_format_pidfile_name(gchar *buf, gsize buflen)
{
const gchar *pidfile = process_opts.pidfile;
if (pidfile == NULL)
{
g_snprintf(buf, buflen, "%s/%s.pid", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, process_opts.name);
pidfile = buf;
}
else if (pidfile[0] != '/')
{
/* complete path to pidfile not specified, assume it is a relative path to pidfile_dir */
g_snprintf(buf, buflen, "%s/%s", process_opts.pidfile_dir ? process_opts.pidfile_dir : PATH_PIDFILEDIR, pidfile);
pidfile = buf;
}
return pidfile;
}
/**
* g_process_write_pidfile:
* @pid: pid to write into the pidfile
*
* Write the pid to the pidfile.
**/
static void
g_process_write_pidfile(pid_t pid)
{
gchar buf[256];
const gchar *pidfile;
FILE *fd;
pidfile = g_process_format_pidfile_name(buf, sizeof(buf));
fd = fopen(pidfile, "w");
if (fd != NULL)
{
fprintf(fd, "%d\n", (int) pid);
fclose(fd);
}
else
{
g_process_message("Error creating pid file; file='%s', error='%s'", pidfile, g_strerror(errno));
}
}
/**
* g_process_remove_pidfile:
*
* Remove the pidfile.
**/
static void
g_process_remove_pidfile(void)
{
gchar buf[256];
const gchar *pidfile;
pidfile = g_process_format_pidfile_name(buf, sizeof(buf));
if (unlink(pidfile) < 0)
{
g_process_message("Error removing pid file; file='%s', error='%s'", pidfile, g_strerror(errno));
}
}
/**
* g_process_change_root:
*
* Change the current root to the value specified by the user, causes the
* startup process to fail if this function returns FALSE. (e.g. the user
* specified a chroot but we could not change to that directory)
*
* Returns: TRUE to indicate success
**/
static gboolean
g_process_change_root(void)
{
if (process_opts.chroot_dir)
{
if (chroot(process_opts.chroot_dir) < 0)
{
g_process_message("Error in chroot(); chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno));
return FALSE;
}
if (chdir("/") < 0)
{
g_process_message("Error in chdir() after chroot; chroot='%s', error='%s'\n", process_opts.chroot_dir, g_strerror(errno));
return FALSE;
}
}
return TRUE;
}
/**
* g_process_change_user:
*
* Change the current user/group/groups to the value specified by the user.
* causes the startup process to fail if this function returns FALSE. (e.g.
* the user requested the uid/gid to change we could not change to that uid)
*
* Returns: TRUE to indicate success
**/
static gboolean
g_process_change_user(void)
{
#if ENABLE_LINUX_CAPS
if (process_opts.caps)
prctl(PR_SET_KEEPCAPS, 1, 0, 0, 0);
#endif
if (process_opts.gid >= 0)
{
if (setgid((gid_t) process_opts.gid) < 0)
{
g_process_message("Error in setgid(); group='%s', gid='%d', error='%s'", process_opts.group, process_opts.gid, g_strerror(errno));
if (getuid() == 0)
return FALSE;
}
if (process_opts.user && initgroups(process_opts.user, (gid_t) process_opts.gid) < 0)
{
g_process_message("Error in initgroups(); user='%s', error='%s'", process_opts.user, g_strerror(errno));
if (getuid() == 0)
return FALSE;
}
}
if (process_opts.uid >= 0)
{
if (setuid((uid_t) process_opts.uid) < 0)
{
g_process_message("Error in setuid(); user='%s', uid='%d', error='%s'", process_opts.user, process_opts.uid, g_strerror(errno));
if (getuid() == 0)
return FALSE;
}
}
return TRUE;
}
#if ENABLE_LINUX_CAPS
/**
* g_process_change_caps:
*
* Change the current capset to the value specified by the user. causes the
* startup process to fail if this function returns FALSE, but we only do
* this if the capset cannot be parsed, otherwise a failure changing the
* capabilities will not result in failure
*
* Returns: TRUE to indicate success
**/
static gboolean
g_process_change_caps(void)
{
if (process_opts.caps)
{
cap_t cap = cap_from_text(process_opts.caps);
if (cap == NULL)
{
g_process_message("Error parsing capabilities: %s", process_opts.caps);
process_opts.caps = NULL;
return FALSE;
}
else
{
if (cap_set_proc(cap) == -1)
{
g_process_message("Error setting capabilities, capability management disabled; error='%s'", g_strerror(errno));
process_opts.caps = NULL;
}
cap_free(cap);
}
}
return TRUE;
}
#else
static gboolean
g_process_change_caps(void)
{
return TRUE;
}
#endif
static void
g_process_resolve_names(void)
{
if (process_opts.user && !resolve_user(process_opts.user, &process_opts.uid))
{
g_process_message("Error resolving user; user='%s'", process_opts.user);
process_opts.uid = -1;
}
if (process_opts.group && !resolve_group(process_opts.group, &process_opts.gid))
{
g_process_message("Error resolving group; group='%s'", process_opts.group);
process_opts.gid = -1;
}
}
/**
* g_process_change_dir:
*
* Change the current working directory to the value specified by the user
* and verify that the daemon would be able to dump core to that directory
* if that is requested.
**/
static void
g_process_change_dir(void)
{
const gchar *cwd = NULL;
if (process_opts.mode != G_PM_FOREGROUND)
{
if (process_opts.cwd)
cwd = process_opts.cwd;
else if (process_opts.pidfile_dir)
cwd = process_opts.pidfile_dir;
if (!cwd)
cwd = PATH_PIDFILEDIR;
if (cwd)
chdir(cwd);
}
/* this check is here to avoid having to change directory early in the startup process */
if ((process_opts.core) && access(".", W_OK) < 0)
{
gchar buf[256];
getcwd(buf, sizeof(buf));
g_process_message("Unable to write to current directory, core dumps will not be generated; dir='%s', error='%s'", buf, g_strerror(errno));
}
}
/**
* g_process_send_result:
* @ret_num: exit code of the process
*
* This function is called to notify our parent process (which is the same
* executable process but separated with a fork()) about the result of the
* process startup phase. Specifying ret_num == 0 means that everything was
* dandy, all other values mean that the initialization failed and the
* parent should exit using ret_num as the exit code. The function behaves
* differently depending on which process it was called from, determined by
* the value of the process_kind global variable. In the daemon process it
* writes to init_result_pipe, in the startup process it writes to the
* startup_result_pipe.
*
* This function can only be called once, further invocations will do nothing.
**/
static void
g_process_send_result(guint ret_num)
{
gchar buf[10];
guint buf_len;
gint *fd;
if (process_kind == G_PK_SUPERVISOR)
fd = &startup_result_pipe[1];
else if (process_kind == G_PK_DAEMON)
fd = &init_result_pipe[1];
else
g_assert_not_reached();
if (*fd != -1)
{
buf_len = g_snprintf(buf, sizeof(buf), "%d\n", ret_num);
write(*fd, buf, buf_len);
close(*fd);
*fd = -1;
}
}
/**
* g_process_recv_result:
*
* Retrieves an exit code value from one of the result pipes depending on
* which process the function was called from. This function can be called
* only once, further invocations will return non-zero result code.
**/
static gint
g_process_recv_result(void)
{
gchar ret_buf[6];
gint ret_num = 1;
gint *fd;
/* FIXME: use a timer */
if (process_kind == G_PK_SUPERVISOR)
fd = &init_result_pipe[0];
else if (process_kind == G_PK_STARTUP)
fd = &startup_result_pipe[0];
else
g_assert_not_reached();
if (*fd != -1)
{
memset(ret_buf, 0, sizeof(ret_buf));
if (read(*fd, ret_buf, sizeof(ret_buf)) > 0)
{
ret_num = atoi(ret_buf);
}
else
{
/* the process probably crashed without telling a proper exit code */
ret_num = 1;
}
close(*fd);
*fd = -1;
}
return ret_num;
}
/**
* g_process_perform_startup:
*
* This function is the startup process, never returns, the startup process exits here.
**/
static void
g_process_perform_startup(void)
{
/* startup process */
exit(g_process_recv_result());
}
#define SPT_PADCHAR '\0'
static void
g_process_setproctitle(const gchar* proc_title)
{
size_t len;
g_assert(process_opts.argv_start != NULL);
len = g_strlcpy(process_opts.argv_start, proc_title, process_opts.argv_env_len);
for (; len < process_opts.argv_env_len; ++len)
process_opts.argv_start[len] = SPT_PADCHAR;
}
#define PROC_TITLE_SPACE 1024
/**
* g_process_perform_supervise:
*
* Supervise process, returns only in the context of the daemon process, the
* supervisor process exits here.
**/
static void
g_process_perform_supervise(void)
{
pid_t pid;
gboolean first = TRUE, exited = FALSE;
gchar proc_title[PROC_TITLE_SPACE];
g_snprintf(proc_title, PROC_TITLE_SPACE, "supervising %s", process_opts.name);
g_process_setproctitle(proc_title);
while (1)
{
if (pipe(init_result_pipe) != 0)
{
g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno));
g_process_startup_failed(1, TRUE);
}
/* fork off a child process */
if ((pid = fork()) < 0)
{
g_process_message("Error forking child process; error='%s'", g_strerror(errno));
g_process_startup_failed(1, TRUE);
}
else if (pid != 0)
{
gint rc;
gboolean deadlock = FALSE;
/* this is the supervisor process */
/* shut down init_result_pipe write side */
close(init_result_pipe[1]);
init_result_pipe[1] = -1;
rc = g_process_recv_result();
if (first)
{
/* first time encounter, we have a chance to report back, do it */
g_process_send_result(rc);
if (rc != 0)
break;
g_process_detach_stdio();
}
first = FALSE;
if (rc != 0)
{
gint i = 0;
/* initialization failed in daemon, it will probably exit soon, wait and restart */
while (i < 6 && waitpid(pid, &rc, WNOHANG) == 0)
{
if (i > 3)
kill(pid, i > 4 ? SIGKILL : SIGTERM);
sleep(1);
i++;
}
if (i == 6)
g_process_message("Initialization failed but the daemon did not exit, even when forced to, trying to recover; pid='%d'", pid);
continue;
}
if (process_opts.check_fn && (process_opts.check_period >= 0))
{
gint i = 1;
while (!(exited = waitpid(pid, &rc, WNOHANG)))
{
if (i >= process_opts.check_period)
{
if (!process_opts.check_fn())
break;
i = 0;
}
sleep(1);
i++;
}
if (!exited)
{
gint j = 0;
g_process_message("Daemon deadlock detected, killing process;");
deadlock = TRUE;
while (j < 6 && waitpid(pid, &rc, WNOHANG) == 0)
{
if (j > 3)
kill(pid, j > 4 ? SIGKILL : SIGABRT);
sleep(1);
j++;
}
if (j == 6)
g_process_message("The daemon did not exit after deadlock, even when forced to, trying to recover; pid='%d'", pid);
}
}
else
{
waitpid(pid, &rc, 0);
}
if (deadlock || WIFSIGNALED(rc) || (WIFEXITED(rc) && WEXITSTATUS(rc) != 0))
{
gchar argbuf[64];
if (!access(G_PROCESS_FAILURE_NOTIFICATION, R_OK | X_OK))
{
const gchar *notify_reason;
pid_t npid = fork();
gint nrc;
switch (npid)
{
case -1:
g_process_message("Could not fork for external notification; reason='%s'", strerror(errno));
break;
case 0:
switch(fork())
{
case -1:
g_process_message("Could not fork for external notification; reason='%s'", strerror(errno));
exit(1);
break;
case 0:
if (deadlock)
{
notify_reason = "deadlock detected";
argbuf[0] = 0;
}
else
{
snprintf(argbuf, sizeof(argbuf), "%d", WIFSIGNALED(rc) ? WTERMSIG(rc) : WEXITSTATUS(rc));
if (WIFSIGNALED(rc))
notify_reason = "signalled";
else
notify_reason = "non-zero exit code";
}
execlp(G_PROCESS_FAILURE_NOTIFICATION, G_PROCESS_FAILURE_NOTIFICATION,
SAFE_STRING(process_opts.name),
SAFE_STRING(process_opts.chroot_dir),
SAFE_STRING(process_opts.pidfile_dir),
SAFE_STRING(process_opts.pidfile),
SAFE_STRING(process_opts.cwd),
SAFE_STRING(process_opts.caps),
notify_reason,
argbuf,
(deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL) ? "restarting" : "not-restarting",
(gchar*) NULL);
g_process_message("Could not execute external notification; reason='%s'", strerror(errno));
break;
default:
exit(0);
break;
} /* child process */
default:
waitpid(npid, &nrc, 0);
break;
}
}
if (deadlock || !WIFSIGNALED(rc) || WTERMSIG(rc) != SIGKILL)
{
g_process_message("Daemon exited due to a deadlock/signal/failure, restarting; exitcode='%d'", rc);
sleep(1);
}
else
{
g_process_message("Daemon was killed, not restarting; exitcode='%d'", rc);
break;
}
}
else
{
g_process_message("Daemon exited gracefully, not restarting; exitcode='%d'", rc);
break;
}
}
else
{
/* this is the daemon process, thus we should return to the caller of g_process_start() */
/* shut down init_result_pipe read side */
process_kind = G_PK_DAEMON;
close(init_result_pipe[0]);
init_result_pipe[0] = -1;
memcpy(process_opts.argv_start, process_opts.argv_orig, process_opts.argv_env_len);
return;
}
}
exit(0);
}
/**
* g_process_start:
*
* Start the process as directed by the options set by various
* g_process_set_*() functions.
**/
void
g_process_start(void)
{
pid_t pid;
g_process_detach_tty();
g_process_change_limits();
g_process_resolve_names();
if (process_opts.mode == G_PM_BACKGROUND)
{
/* no supervisor, sends result to startup process directly */
if (pipe(init_result_pipe) != 0)
{
g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno));
exit(1);
}
if ((pid = fork()) < 0)
{
g_process_message("Error forking child process; error='%s'", g_strerror(errno));
exit(1);
}
else if (pid != 0)
{
/* shut down init_result_pipe write side */
close(init_result_pipe[1]);
/* connect startup_result_pipe with init_result_pipe */
startup_result_pipe[0] = init_result_pipe[0];
init_result_pipe[0] = -1;
g_process_perform_startup();
/* NOTE: never returns */
g_assert_not_reached();
}
process_kind = G_PK_DAEMON;
/* shut down init_result_pipe read side */
close(init_result_pipe[0]);
init_result_pipe[0] = -1;
}
else if (process_opts.mode == G_PM_SAFE_BACKGROUND)
{
/* full blown startup/supervisor/daemon */
if (pipe(startup_result_pipe) != 0)
{
g_process_message("Error daemonizing process, cannot open pipe; error='%s'", g_strerror(errno));
exit(1);
}
/* first fork off supervisor process */
if ((pid = fork()) < 0)
{
g_process_message("Error forking child process; error='%s'", g_strerror(errno));
exit(1);
}
else if (pid != 0)
{
/* this is the startup process */
/* shut down startup_result_pipe write side */
close(startup_result_pipe[1]);
startup_result_pipe[1] = -1;
/* NOTE: never returns */
g_process_perform_startup();
g_assert_not_reached();
}
/* this is the supervisor process */
/* shut down startup_result_pipe read side */
close(startup_result_pipe[0]);
startup_result_pipe[0] = -1;
process_kind = G_PK_SUPERVISOR;
g_process_perform_supervise();
/* we only return in the daamon process here */
}
else if (process_opts.mode == G_PM_FOREGROUND)
{
process_kind = G_PK_DAEMON;
}
else
{
g_assert_not_reached();
}
/* daemon process, we should return to the caller to perform work */
setsid();
/* NOTE: we need to signal the parent in case of errors from this point.
* This is accomplished by writing the appropriate exit code to
* init_result_pipe, the easiest way doing so is calling g_process_startup_failed.
* */
if (!g_process_change_root() ||
!g_process_change_user() ||
!g_process_change_caps())
{
g_process_startup_failed(1, TRUE);
}
g_process_enable_core();
g_process_change_dir();
}
/**
* g_process_startup_failed:
* @ret_num: exit code
* @may_exit: whether to exit the process
*
* This is a public API function to be called by the user code when
* initialization failed.
**/
void
g_process_startup_failed(guint ret_num, gboolean may_exit)
{
if (process_kind != G_PK_STARTUP)
g_process_send_result(ret_num);
if (may_exit)
{
exit(ret_num);
}
else
{
g_process_detach_stdio();
}
}
/**
* g_process_startup_ok:
*
* This is a public API function to be called by the user code when
* initialization was successful, we can report back to the user.
**/
void
g_process_startup_ok(void)
{
g_process_write_pidfile(getpid());
g_process_send_result(0);
g_process_detach_stdio();
}
/**
* g_process_finish:
*
* This is a public API function to be called by the user code when the
* daemon exits after properly initialized (e.g. when it terminates because
* of SIGTERM). This function currently only removes the PID file.
**/
void
g_process_finish(void)
{
g_process_remove_pidfile();
}
static gboolean
g_process_process_mode_arg(const gchar *option_name G_GNUC_UNUSED, const gchar *value, gpointer data G_GNUC_UNUSED, GError **error)
{
if (strcmp(value, "foreground") == 0)
{
process_opts.mode = G_PM_FOREGROUND;
}
else if (strcmp(value, "background") == 0)
{
process_opts.mode = G_PM_BACKGROUND;
}
else if (strcmp(value, "safe-background") == 0)
{
process_opts.mode = G_PM_SAFE_BACKGROUND;
}
else
{
g_set_error(error, G_OPTION_ERROR, G_OPTION_ERROR_BAD_VALUE, "Error parsing process-mode argument");
return FALSE;
}
return TRUE;
}
static GOptionEntry g_process_option_entries[] =
{
{ "foreground", 'F', G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &process_opts.mode, "Do not go into the background after initialization", NULL },
{ "process-mode", 0, 0, G_OPTION_ARG_CALLBACK, g_process_process_mode_arg , "Set process running mode", "<foreground|background|safe-background>" },
{ "user", 'u', 0, G_OPTION_ARG_STRING, &process_opts.user, "Set the user to run as", "<user>" },
{ "uid", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &process_opts.user, NULL, NULL },
{ "group", 'g', 0, G_OPTION_ARG_STRING, &process_opts.group, "Set the group to run as", "<group>" },
{ "gid", 0, G_OPTION_FLAG_HIDDEN, G_OPTION_ARG_STRING, &process_opts.group, NULL, NULL },
{ "chroot", 'C', 0, G_OPTION_ARG_STRING, &process_opts.chroot_dir, "Chroot to this directory", "<dir>" },
{ "caps", 0, 0, G_OPTION_ARG_STRING, &process_opts.caps, "Set default capability set", "<capspec>" },
{ "no-caps", 0, G_OPTION_FLAG_REVERSE, G_OPTION_ARG_NONE, &process_opts.caps, "Disable managing Linux capabilities", NULL },
{ "pidfile", 'p', 0, G_OPTION_ARG_STRING, &process_opts.pidfile, "Set path to pid file", "<pidfile>" },
{ "enable-core", 0, 0, G_OPTION_ARG_NONE, &process_opts.core, "Enable dumping core files", NULL },
{ "fd-limit", 0, 0, G_OPTION_ARG_INT, &process_opts.fd_limit_min, "The minimum required number of fds", NULL },
{ NULL, 0, 0, 0, NULL, NULL, NULL },
};
void
g_process_add_option_group(GOptionContext *ctx)
{
GOptionGroup *group;
group = g_option_group_new("process", "Process options", "Process options", NULL, NULL);
g_option_group_add_entries(group, g_process_option_entries);
g_option_context_add_group(ctx, group);
}
| Java |
<div id="forum_points_options">
<fieldset>
<legend>{{ lang('FORUM_POINT_SETTINGS') }}</legend>
<p>{{ lang('FORUM_POINT_SETTINGS_EXPLAIN') }}</p>
<dl>
<dt><label>{{ lang('FORUM_PERTOPIC') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_PERTOPIC_EXPLAIN') }}</span>
</dt>
<dd><input type="text" id="forum_pertopic" maxlength="6" size="5" name="forum_pertopic"
value="{{ FORUM_PERTOPIC }}"/></dd>
</dl>
<dl>
<dt><label>{{ lang('FORUM_PERPOST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_PERPOST_EXPLAIN') }}</span>
</dt>
<dd><input type="text" id="forum_perpost" maxlength="6" size="5" name="forum_perpost"
value="{{ FORUM_PERPOST }}"/></dd>
</dl>
<dl>
<dt><label>{{ lang('FORUM_PEREDIT') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_PEREDIT_EXPLAIN') }}</span>
</dt>
<dd><input type="text" id="forum_peredit" maxlength="6" size="5" name="forum_peredit"
value="{{ FORUM_PEREDIT }}"/></dd>
</dl>
<dl>
<dt><label>{{ lang('FORUM_COST') }}{{ lang('COLON')
}}</label><br/><span>{{ lang('FORUM_COST_EXPLAIN') }}</span></dt>
<dd><input type="text" id="forum_cost" maxlength="6" size="5" name="forum_cost" value="{{ FORUM_COST }}"/>
</dd>
</dl>
<dl>
<dt><label>{{ lang('FORUM_COST_TOPIC') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_COST_TOPIC_EXPLAIN') }}</span>
</dt>
<dd><input type="text" id="forum_cost_topic" maxlength="6" size="5" name="forum_cost_topic"
value="{{ FORUM_COST_TOPIC }}"/></dd>
</dl>
<dl>
<dt><label>{{ lang('FORUM_COST_POST') }}{{ lang('COLON') }}</label><br/><span>{{ lang('FORUM_COST_POST_EXPLAIN') }}</span>
</dt>
<dd><input type="text" id="forum_cost_post" maxlength="6" size="5" name="forum_cost_post"
value="{{ FORUM_COST_POST }}"/></dd>
</dl>
</fieldset>
</div> | Java |
# -*- coding: utf-8 -*-
"""
Created on Tue May 28 12:20:59 2013
=== MAYAXES (v1.1) ===
Generates a set of MayaVI axes using the mayavi.mlab.axes() object with a
white background, small black text and a centred title. Designed to better
mimic MATLAB style plots.
Unspecified arguments will be set to default values when mayaxes is called
(note that default settings are configured for a figure measuring 1024 x 768
pixels and may not display correctly on plots that are significantly larger
or smaller).
=== Inputs ===
'title' Figure title text (default = 'VOID')
'xlabel' X axis label text (default = 'X')
'ylabel' Y axis label text (default = 'Y')
'zlabel' Z axis label text (default = 'Z')
'handle' Graphics handle of object (if bounding box is to be plotted)
'title_size' Font size of the title text (default = 25)
'ticks' Number of divisions on each axis (default = 7)
'font_scaling' Font scaling factor for axis text (default = 0.7)
'background' Background colour (can be 'b' (black) or 'w' (white))
=== Notes ===
Disbaling figure title: specify title_string='void' OR title_string='Void' OR
title_string='VOID' to disable figure title.
Disabling bounding box: specify handle='void' OR handle='Void' OR handle='VOID'
to disable figure bounding box.
=== Usage ===
from mayaxes import mayaxes
mayaxes('Figure title','X axis label','Y axis label','Z axis label')
OR
mayaxes(title_string='TITLE',xlabel='X',ylabel='Y',zlabel='Z',title_size=25,ticks=7,font_scaling=0.7)
=== Example ===
from mayaxes import test_mayaxes
test_mayaxes()
@author: Nathan Donaldson
"""
def mayaxes(title_string='VOID', xlabel='VOID', ylabel='VOID', zlabel='VOID', handle='VOID', \
title_size=25, ticks=7, font_scaling=0.7, background='w'):
if type(title_string) != str or type(xlabel) != str or type(ylabel) != str or type(zlabel) != str:
print('ERROR: label inputs must all be strings')
return
elif type(ticks) != int:
print('ERROR: number of ticks must be an integer')
return
elif type(font_scaling) != float and type(font_scaling) != int:
print('Error: font scaling factor must be an integer or a float')
return
from mayavi.mlab import axes,title,gcf,outline
# Create axes object
ax = axes()
# Font factor globally adjusts figure text size
ax.axes.font_factor = font_scaling
# Number of ticks along each axis
ax.axes.number_of_labels = ticks
# Set axis labels to input strings
# (spaces are included for padding so that labels do not intersect with axes)
if xlabel=='void' or xlabel=='Void' or xlabel=='VOID':
print 'X axis label title disabled'
else:
ax.axes.x_label = ' ' + xlabel
if ylabel=='void' or ylabel=='Void' or ylabel=='VOID':
print 'Y axis label disabled'
else:
ax.axes.y_label = ylabel + ' '
if zlabel=='void' or zlabel=='Void' or zlabel=='VOID':
print 'Z axis label disabled'
else:
ax.axes.z_label = zlabel + ' '
# Create figure title
if title_string=='void' or title_string=='Void' or title_string=='VOID':
print 'Figure title disabled'
else:
text_title = title(title_string)
text_title.x_position = 0.5
text_title.y_position = 0.9
text_title.property.color = (0.0, 0.0, 0.0)
text_title.actor.text_scale_mode = 'none'
text_title.property.font_size = title_size
text_title.property.justification = 'centered'
# Create bounding box
if handle=='void' or handle=='Void' or handle=='VOID':
print 'Bounding box disabled'
else:
if background == 'w':
bounding_box = outline(handle, color=(0.0, 0.0, 0.0), opacity=0.2)
elif background == 'b':
bounding_box = outline(handle, color=(1.0, 1.0, 1.0), opacity=0.2)
# Set axis, labels and titles to neat black text
#ax.property.color = (0.0, 0.0, 0.0)
#ax.title_text_property.color = (0.0, 0.0, 0.0)
#ax.label_text_property.color = (0.0, 0.0, 0.0)
ax.label_text_property.bold = False
ax.label_text_property.italic = False
ax.title_text_property.italic = False
ax.title_text_property.bold = False
# Reset axis range
ax.axes.use_ranges = True
# Set scene background, axis and text colours
fig = gcf()
if background == 'w':
fig.scene.background = (1.0, 1.0, 1.0)
ax.label_text_property.color = (0.0, 0.0, 0.0)
ax.property.color = (0.0, 0.0, 0.0)
ax.title_text_property.color = (0.0, 0.0, 0.0)
elif background == 'b':
fig.scene.background = (0.0, 0.0, 0.0)
ax.label_text_property.color = (1.0, 1.0, 1.0)
ax.property.color = (1.0, 1.0, 1.0)
ax.title_text_property.color = (1.0, 1.0, 1.0)
fig.scene.parallel_projection = True
def test_mayaxes():
from mayaxes import mayaxes
from scipy import sqrt,sin,meshgrid,linspace,pi
import mayavi.mlab as mlab
resolution = 200
lambda_var = 3
theta = linspace(-lambda_var*2*pi,lambda_var*2*pi,resolution)
x, y = meshgrid(theta, theta)
r = sqrt(x**2 + y**2)
z = sin(r)/r
fig = mlab.figure(size=(1024,768))
surf = mlab.surf(theta,theta,z,colormap='jet',opacity=1.0,warp_scale='auto')
mayaxes(title_string='Figure 1: Diminishing polar cosine series', \
xlabel='X data',ylabel='Y data',zlabel='Z data',handle=surf)
fig.scene.camera.position = [435.4093863309094, 434.1268937227623, 315.90311468125287]
fig.scene.camera.focal_point = [94.434632665253829, 93.152140057106593, -25.071638984402856]
fig.scene.camera.view_angle = 30.0
fig.scene.camera.view_up = [0.0, 0.0, 1.0]
fig.scene.camera.clipping_range = [287.45231734040635, 973.59247058049255]
fig.scene.camera.compute_view_plane_normal()
fig.scene.render()
mlab.show()
| Java |
/*
This file is a part of the Depecher (Telegram client)
Copyright (C) 2017 Alexandr Akulich <akulichalexander@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.
*/
#include <QGuiApplication>
#include <QQuickView>
#include <sailfishapp.h>
int main(int argc, char *argv[])
{
QScopedPointer<QGuiApplication> application(SailfishApp::application(argc, argv));
application->setApplicationName(QStringLiteral("depecher"));
application->setApplicationDisplayName(QStringLiteral("Depecher"));
QScopedPointer<QQuickView> view(SailfishApp::createView());
view->setSource(SailfishApp::pathTo(QStringLiteral("qml/main.qml")));
view->setTitle(application->applicationDisplayName());
view->setResizeMode(QQuickView::SizeRootObjectToView);
view->show();
return application->exec();
}
| Java |
<?php
/**
* @version 1.0.0
* @package com_farmapp
* @copyright Copyright (C) 2012. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
* @author Created by com_combuilder - http://www.notwebdesign.com
*/
// No direct access.
defined('_JEXEC') or die;
/**
* Items list controller class.
*/
class CropsControllerFarmapp extends FarmappController
{
/**
* Constructor.
*
* @param array $config An optional associative array of configuration settings.
* @see JController
* @since 1.6
*/
public function __construct($config = array())
{
parent::__construct($config);
}
function display()
{
$model=$this->getModel('crops');
$items=$model->getItems();
$pagination = $model->getPagination();
$state = $model->getState();
$view=$this->getView('crops','html');
$view->assign('items',$items);
$view->assign('pagination',$pagination);
$view->assign('state',$state);
$view->display();
}
function edit()
{
$id = JRequest::getVar('cid','0');
$model=$this->getModel('crop');
// get the Data
$item = $model->getItem($id[0]);
$form = $model->getForm($id[0]);
$view=$this->getView('crop','html');
$view->assign('form',$form);
$view->assign('item',$item);
$view->setLayout('edit');
$view->display();
}
/*
* Method for save data from farm-form......
*
*/
function save()
{
$task = $this->getTask();
$data=JRequest::get('post');
$bed_ids = $data['bed_id'];
$bed_id = implode(',',$bed_ids);
$data['bed_id'] = $bed_id;
$model=$this->getModel('crop');
$id=$model->save($data);
if($id!=='')
{
switch ( $task )
{
case 'save2new':
$link = 'index.php?option=com_farmapp&view=crops&task=add';
$this->setRedirect($link, $msg);
break;
case 'save':
$msg = JText::_( 'Crop save successfully' );
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
break;
case 'apply':
$msg = JText::_( 'Crop save successfully' );
$link = 'index.php?option=com_farmapp&view=crops&task=edit&cid[]='.$id;
$this->setRedirect($link, $msg);
break;
}
}
}
/*
* Method for deleting single/multiple crops......
*
*/
function delete()
{
$model = $this->getModel('crops');
if(!$model->delete()) {
$msg = JText::_( 'Error: One or More crop Could not be Deleted' );
}else{
$msg = JText::_( 'crop(s) Deleted' );
}
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
}
/*
* Method for publish single/multiple farms......
*
*/
function multiplepublish()
{
$model = $this->getModel('crops');
if(!$model->multiplepublish()) {
$msg = JText::_( 'Error: One or More crops Could not be published' );
} else {
$msg = JText::_( 'crop(s) Published.' );
}
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
}
/*
* Method for unpublish single/multiple farms......
*
*/
function multipleunpublish()
{
$model = $this->getModel('crops');
if(!$model->multipleunpublish()){
$msg = JText::_( 'Error: One or More crop Could not be unpublished' );
}else{
$msg = JText::_( 'crop(s) UnPublished.' );
}
$link = 'index.php?option=com_farmapp&view=crops';
$this->setRedirect($link, $msg);
}
/*method single row publish and unpublish on click on tick mark*/
function publish(){
// Initialise variables.
$ids = JRequest::getVar('cid', array(), '', 'array');
$values = array('publish' => 1, 'unpublish' => 0);
$task = $this->getTask();
$value = JArrayHelper::getValue($values, $task, 0, 'int');
if (empty($ids)) {
JError::raiseWarning(500, JText::_('JERROR_NO_ITEMS_SELECTED'));
}
else {
// Get the model.
$model = $this->getModel('crops');
// Publish the items.
if (!$model->publish($ids, $value)) {
JError::raiseWarning(500, $model->getError());
}
}
$this->setRedirect('index.php?option=com_farmapp&view=crops');
}
/*
*
* Method to get the beds according to the farm/zones........
*/
function findbeds()
{
$model=$this->getModel('crops');
$farmzoneid = JRequest::getVar('val');
$cropid = JRequest::getVar('cropid');
$bedslist = $model->getbedslist($farmzoneid, $cropid);
echo $bedslist;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.