code
stringlengths 3
1.01M
| repo_name
stringlengths 5
116
| path
stringlengths 3
311
| language
stringclasses 30
values | license
stringclasses 15
values | size
int64 3
1.01M
|
|---|---|---|---|---|---|
/* Copyright (C) 2000-2008 by George Williams */
/*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef _GRESOURCE_H
#define _GRESOURCE_H
#include "gdraw.h"
enum res_type { rt_int, rt_double, rt_bool/* int */, rt_color, rt_string };
typedef struct gresstruct {
char *resname;
enum res_type type;
void *val;
void *(*cvt)(char *,void *); /* converts a string into a whatever */
int found;
} GResStruct;
extern char *GResourceProgramName, *GResourceFullProgram, *GResourceProgramDir;
extern int local_encoding;
#if HAVE_ICONV_H
# include <iconv.h>
extern char *iconv_local_encoding_name;
#endif
void GResourceSetProg(char *prog);
void GResourceAddResourceFile(char *filename,char *prog);
void GResourceAddResourceString(char *string,char *prog);
void GResourceFind( GResStruct *info, char *prefix);
char *GResourceFindString(char *name);
int GResourceFindBool(char *name, int def);
long GResourceFindInt(char *name, long def);
Color GResourceFindColor(char *name, Color def);
GImage *GResourceFindImage(char *name, GImage *def);
#endif
|
genesi/luatex
|
source/texk/web2c/luatexdir/luafontloader/fontforge/inc/gresource.h
|
C
|
gpl-2.0
| 2,394
|
#ifndef GUI_WINDOW_ABOUT_H_
#define GUI_WINDOW_ABOUT_H_
#include <QDialog>
#include "../../common.h"
namespace gui {
namespace window {
class about : public QDialog {
Q_OBJECT
public:
about(QWidget *parent);
};
} // ns window
} // ns gui
#endif //GUI_WINDOW_ABOUT_H_
|
ajalkane/rvhouse
|
src/gui/window/about.h
|
C
|
gpl-2.0
| 316
|
# encoding: utf-8
# Author: Zhang Huangbin <zhb@iredmail.org>
import os
import glob
import web
langmaps = {
'en_US': u'English (US)',
'sq_AL': u'Albanian',
'ar_SA': u'Arabic',
'hy_AM': u'Armenian',
'az_AZ': u'Azerbaijani',
'bs_BA': u'Bosnian (Serbian Latin)',
'bg_BG': u'Bulgarian',
'ca_ES': u'Català',
'cy_GB': u'Cymraeg',
'hr_HR': u'Croatian (Hrvatski)',
'cs_CZ': u'Čeština',
'da_DK': u'Dansk',
'de_DE': u'Deutsch (Deutsch)',
'de_CH': u'Deutsch (Schweiz)',
'en_GB': u'English (GB)',
'es_ES': u'Español',
'eo': u'Esperanto',
'et_EE': u'Estonian',
'eu_ES': u'Euskara (Basque)',
'fi_FI': u'Finnish (Suomi)',
'nl_BE': u'Flemish',
'fr_FR': u'Français',
'gl_ES': u'Galego (Galician)',
'ka_GE': u'Georgian (Kartuli)',
'el_GR': u'Greek',
'he_IL': u'Hebrew',
'hi_IN': u'Hindi',
'hu_HU': u'Hungarian',
'is_IS': u'Icelandic',
'id_ID': u'Indonesian',
'ga_IE': u'Irish',
'it_IT': u'Italiano',
'ja_JP': u'Japanese (日本語)',
'ko_KR': u'Korean',
'ku': u'Kurdish (Kurmancî)',
'lv_LV': u'Latvian',
'lt_LT': u'Lithuanian',
'mk_MK': u'Macedonian',
'ms_MY': u'Malay',
'nl_NL': u'Netherlands',
'ne_NP': u'Nepali',
'nb_NO': u'Norsk (Bokmål)',
'nn_NO': u'Norsk (Nynorsk)',
'fa': u'Persian (Farsi)',
'pl_PL': u'Polski',
'pt_BR': u'Portuguese (Brazilian)',
'pt_PT': u'Portuguese (Standard)',
'ro_RO': u'Romanian',
'ru_RU': u'Русский',
'sr_CS': u'Serbian (Cyrillic)',
'si_LK': u'Sinhala',
'sk_SK': u'Slovak',
'sl_SI': u'Slovenian',
'sv_SE': u'Swedish (Svenska)',
'th_TH': u'Thai',
'tr_TR': u'Türkçe',
'uk_UA': u'Ukrainian',
'vi_VN': u'Vietnamese',
'zh_CN': u'简体中文',
'zh_TW': u'繁體中文',
}
# All available timezone names and time offsets (in minutes).
allTimezonesOffsets = {
'GMT-12:00': -720,
'GMT-11:00': -660,
'GMT-10:00': -600,
'GMT-09:30': -570,
'GMT-09:00': -540,
'GMT-08:00': -480,
'GMT-07:00': -420,
'GMT-06:00': -360,
'GMT-05:00': -300,
'GMT-04:30': -270,
'GMT-04:00': -240,
'GMT-03:30': -210,
'GMT-03:00': -180,
'GMT-02:00': -120,
'GMT-01:00': -60,
'GMT': 0,
'GMT+01:00': 60,
'GMT+02:00': 120,
'GMT+03:00': 180,
'GMT+03:30': 210,
'GMT+04:00': 240,
'GMT+04:30': 270,
'GMT+05:00': 300,
'GMT+05:30': 330,
'GMT+05:45': 345,
'GMT+06:00': 360,
'GMT+06:30': 390,
'GMT+07:00': 420,
'GMT+08:00': 480,
'GMT+08:45': 525,
'GMT+09:00': 540,
'GMT+09:30': 570,
'GMT+10:00': 600,
'GMT+10:30': 630,
'GMT+11:00': 660,
'GMT+11:30': 690,
'GMT+12:00': 720,
'GMT+12:45': 765,
'GMT+13:00': 780,
'GMT+14:00': 840,
}
# Get available languages.
def get_language_maps():
# Get available languages.
rootdir = os.path.abspath(os.path.dirname(__file__)) + '/../'
available_langs = [
web.safestr(os.path.basename(v))
for v in glob.glob(rootdir + 'i18n/[a-z][a-z]_[A-Z][A-Z]')
if os.path.basename(v) in langmaps]
available_langs += [
web.safestr(os.path.basename(v))
for v in glob.glob(rootdir + 'i18n/[a-z][a-z]')
if os.path.basename(v) in langmaps]
available_langs.sort()
# Get language maps.
languagemaps = {}
for i in available_langs:
if i in langmaps:
languagemaps.update({i: langmaps[i]})
return languagemaps
|
villaverde/iredadmin
|
libs/languages.py
|
Python
|
gpl-2.0
| 3,515
|
function icl_content_lang_propagate(lang, speed) {
var id = '#icl-content-translate-' + lang;
$('#icl-content').show('slow');
$('#icl-content fieldset').hide();
if ( $('#edit-minor-edit')) {
if($('#edit-minor-edit').attr('checked')) {
$(id).hide(speed);
} else {
$(id).show(speed);
}
}
else {
$(id).show(speed);
}
if ($('#edit-icl-content-skip').val() == 'not') {
$('#icl-content fieldset').hide();
}
if (lang.length == 0) {
$('#edit-icl-content-skip').attr('disabled','disabled');
$('#no_language_error').show('fast');
} else {
if($(id).html()!=null){
$('#edit-icl-content-skip').removeAttr('disabled');
}else{
$('#edit-icl-content-skip').attr('disabled','disabled');
}
$('#no_language_error').hide('fast');
}
}
$(document).ready( function() {
$('#edit-icl-content-skip').change( function() {
if (this.value == 'not') {
$('#icl-content fieldset').hide('slow');
} else {
icl_content_lang_propagate($('#edit-language').val(), 'slow');
}
});
$('#edit-language').change( function() {
icl_content_lang_propagate(this.value, '');
});
$('#edit-minor-edit').change( function() {
if($('#edit-minor-edit').attr('checked')) {
$('#edit-icl-content-skip-wrapper').hide('slow');
icl_content_lang_propagate($('#edit-language').val(), 'slow');
} else {
$('#edit-icl-content-skip-wrapper').show('fast');
icl_content_lang_propagate($('#edit-language').val(), 'fast');
}
});
icl_content_lang_propagate($('#edit-language').val(), '');
});
|
rmontero/dla_ecommerce_site
|
sites/all/modules/contrib/translation_management/icl_content/js/icl_content.js
|
JavaScript
|
gpl-2.0
| 1,828
|
# Copyright (C) 2009, 2010 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
from __future__ import absolute_import
import os
import time
from bzrlib import (
controldir,
errors,
osutils,
registry,
trace,
)
from bzrlib.i18n import gettext
from bzrlib.branch import (
Branch,
)
from bzrlib.revision import (
NULL_REVISION,
)
format_registry = registry.Registry()
def send(target_branch, revision, public_branch, remember,
format, no_bundle, no_patch, output, from_, mail_to, message, body,
to_file, strict=None):
possible_transports = []
tree, branch = controldir.ControlDir.open_containing_tree_or_branch(
from_, possible_transports=possible_transports)[:2]
# we may need to write data into branch's repository to calculate
# the data to send.
branch.lock_write()
try:
if output is None:
config_stack = branch.get_config_stack()
if mail_to is None:
mail_to = config_stack.get('submit_to')
mail_client = config_stack.get('mail_client')(config_stack)
if (not getattr(mail_client, 'supports_body', False)
and body is not None):
raise errors.BzrCommandError(gettext(
'Mail client "%s" does not support specifying body') %
mail_client.__class__.__name__)
if remember and target_branch is None:
raise errors.BzrCommandError(gettext(
'--remember requires a branch to be specified.'))
stored_target_branch = branch.get_submit_branch()
remembered_target_branch = None
if target_branch is None:
target_branch = stored_target_branch
remembered_target_branch = "submit"
else:
# Remembers if asked explicitly or no previous location is set
if remember or (
remember is None and stored_target_branch is None):
branch.set_submit_branch(target_branch)
if target_branch is None:
target_branch = branch.get_parent()
remembered_target_branch = "parent"
if target_branch is None:
raise errors.BzrCommandError(gettext('No submit branch known or'
' specified'))
if remembered_target_branch is not None:
trace.note(gettext('Using saved {0} location "{1}" to determine '
'what changes to submit.').format(
remembered_target_branch,
target_branch))
submit_branch = Branch.open(target_branch,
possible_transports=possible_transports)
possible_transports.append(submit_branch.bzrdir.root_transport)
if mail_to is None or format is None:
if mail_to is None:
mail_to = submit_branch.get_config_stack().get(
'child_submit_to')
if format is None:
formatname = submit_branch.get_child_submit_format()
try:
format = format_registry.get(formatname)
except KeyError:
raise errors.BzrCommandError(
gettext("No such send format '%s'.") % formatname)
stored_public_branch = branch.get_public_branch()
if public_branch is None:
public_branch = stored_public_branch
# Remembers if asked explicitly or no previous location is set
elif (remember
or (remember is None and stored_public_branch is None)):
branch.set_public_branch(public_branch)
if no_bundle and public_branch is None:
raise errors.BzrCommandError(gettext('No public branch specified or'
' known'))
base_revision_id = None
revision_id = None
if revision is not None:
if len(revision) > 2:
raise errors.BzrCommandError(gettext('bzr send takes '
'at most two one revision identifiers'))
revision_id = revision[-1].as_revision_id(branch)
if len(revision) == 2:
base_revision_id = revision[0].as_revision_id(branch)
if revision_id is None:
if tree is not None:
tree.check_changed_or_out_of_date(
strict, 'send_strict',
more_error='Use --no-strict to force the send.',
more_warning='Uncommitted changes will not be sent.')
revision_id = branch.last_revision()
if revision_id == NULL_REVISION:
raise errors.BzrCommandError(gettext('No revisions to submit.'))
if format is None:
format = format_registry.get()
directive = format(branch, revision_id, target_branch,
public_branch, no_patch, no_bundle, message, base_revision_id,
submit_branch)
if output is None:
directive.compose_merge_request(mail_client, mail_to, body,
branch, tree)
else:
if directive.multiple_output_files:
if output == '-':
raise errors.BzrCommandError(gettext('- not supported for '
'merge directives that use more than one output file.'))
if not os.path.exists(output):
os.mkdir(output, 0755)
for (filename, lines) in directive.to_files():
path = os.path.join(output, filename)
outfile = open(path, 'wb')
try:
outfile.writelines(lines)
finally:
outfile.close()
else:
if output == '-':
outfile = to_file
else:
outfile = open(output, 'wb')
try:
outfile.writelines(directive.to_lines())
finally:
if outfile is not to_file:
outfile.close()
finally:
branch.unlock()
def _send_4(branch, revision_id, target_branch, public_branch,
no_patch, no_bundle, message,
base_revision_id, local_target_branch=None):
from bzrlib import merge_directive
return merge_directive.MergeDirective2.from_objects(
branch.repository, revision_id, time.time(),
osutils.local_time_offset(), target_branch,
public_branch=public_branch,
include_patch=not no_patch,
include_bundle=not no_bundle, message=message,
base_revision_id=base_revision_id,
local_target_branch=local_target_branch)
def _send_0_9(branch, revision_id, submit_branch, public_branch,
no_patch, no_bundle, message,
base_revision_id, local_target_branch=None):
if not no_bundle:
if not no_patch:
patch_type = 'bundle'
else:
raise errors.BzrCommandError(gettext('Format 0.9 does not'
' permit bundle with no patch'))
else:
if not no_patch:
patch_type = 'diff'
else:
patch_type = None
from bzrlib import merge_directive
return merge_directive.MergeDirective.from_objects(
branch.repository, revision_id, time.time(),
osutils.local_time_offset(), submit_branch,
public_branch=public_branch, patch_type=patch_type,
message=message, local_target_branch=local_target_branch)
format_registry.register('4',
_send_4, 'Bundle format 4, Merge Directive 2 (default)')
format_registry.register('0.9',
_send_0_9, 'Bundle format 0.9, Merge Directive 1')
format_registry.default_key = '4'
|
Distrotech/bzr
|
bzrlib/send.py
|
Python
|
gpl-2.0
| 8,490
|
<div xmlns:ext="http://www.extjs.com" class="body-wrap"><h1>Class <a href="source/DataField.html#cls-Ext.data.Field">Ext.data.Field</a></h1><table cellspacing="0"><tr><td class="label">Package:</td><td class="hd-info">Ext.data</td></tr><tr><td class="label">Defined In:</td><td class="hd-info">DataField.js</td></tr><tr><td class="label">Class:</td><td class="hd-info"><a href="source/DataField.html#cls-Ext.data.Field">Field</a></td></tr><tr><td class="label">Extends:</td><td class="hd-info">Object</td></tr></table><div class="description"><p>This class encapsulates the field definition information specified in the field definition objects
passed to <a href="output/Ext.data.Record.html#Ext.data.Record-create" ext:member="create" ext:cls="Ext.data.Record">Ext.data.Record.create</a>.</p>
<p>Developers do not need to instantiate this class. Instances are created by <a href="output/Ext.data.Record.create.html" ext:cls="Ext.data.Record.create">Ext.data.Record.create</a>
and cached in the <a href="output/Ext.data.Record.html#Ext.data.Record-fields" ext:member="fields" ext:cls="Ext.data.Record">fields</a> property of the created Record constructor's <b>prototype.</b></p></div><div class="hr"></div><a id="Ext.data.Field-configs"></a><h2>Config Options</h2><table cellspacing="0" class="member-table"><tbody><tr><th colspan="2" class="sig-header">Config Options</th><th class="msource-header">Defined By</th></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-allowBlank"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-allowBlank">allowBlank</a></b> : Boolean<div class="mdesc"><div class="short">Used for validating a record, defaults to true.
An empty value here will cause Ext.data.Record.isValid
to evaluate to...</div><div class="long">Used for validating a <a href="output/Ext.data.Record.html" ext:cls="Ext.data.Record">record</a>, defaults to <tt>true</tt>.
An empty value here will cause <a href="output/Ext.data.Record.html" ext:cls="Ext.data.Record">Ext.data.Record</a>.<a href="output/Ext.data.Record.html#Ext.data.Record-isValid" ext:member="isValid" ext:cls="Ext.data.Record">isValid</a>
to evaluate to <tt>false</tt>.</div></div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-convert"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-convert">convert</a></b> : Function<div class="mdesc"><div class="short">A function which converts the value provided by the Reader into an object that will be stored
in the Record. It is pa...</div><div class="long">A function which converts the value provided by the Reader into an object that will be stored
in the Record. It is passed the following parameters:<div class="mdetail-params"><ul>
<li><b>v</b> : Mixed<div class="sub-desc">The data value as read by the Reader, if undefined will use
the configured <tt><a href="output/Ext.data.Field.html#Ext.data.Field-defaultValue" ext:member="defaultValue" ext:cls="Ext.data.Field">defaultValue</a></tt>.</div></li>
<li><b>rec</b> : Mixed<div class="sub-desc">The data object containing the row as read by the Reader.
Depending on the Reader type, this could be an Array (<a href="output/Ext.data.ArrayReader.html" ext:cls="Ext.data.ArrayReader">ArrayReader</a>), an object
(<a href="output/Ext.data.JsonReader.html" ext:cls="Ext.data.JsonReader">JsonReader</a>), or an XML element (<a href="output/Ext.data.XMLReader.html" ext:cls="Ext.data.XMLReader">XMLReader</a>).</div></li>
</ul></div>
<pre><code><i>// example of convert <b>function</b></i>
<b>function</b> fullName(v, record){
<b>return</b> record.name.last + <em>', '</em> + record.name.first;
}
<b>function</b> location(v, record){
<b>return</b> !record.city ? <em>''</em> : (record.city + <em>', '</em> + record.state);
}
<b>var</b> Dude = Ext.data.Record.create([
{name: <em>'fullname'</em>, convert: fullName},
{name: <em>'firstname'</em>, mapping: <em>'name.first'</em>},
{name: <em>'lastname'</em>, mapping: <em>'name.last'</em>},
{name: <em>'city'</em>, defaultValue: <em>'homeless'</em>},
<em>'state'</em>,
{name: <em>'location'</em>, convert: location}
]);
<i>// create the data store</i>
<b>var</b> store = <b>new</b> Ext.data.Store({
reader: <b>new</b> Ext.data.JsonReader(
{
idProperty: <em>'key'</em>,
root: <em>'daRoot'</em>,
totalProperty: <em>'total'</em>
},
Dude <i>// recordType</i>
)
});
<b>var</b> myData = [
{ key: 1,
name: { first: <em>'Fat'</em>, last: <em>'Albert'</em> }
<i>// notice no city, state provided <b>in</b> data object</i>
},
{ key: 2,
name: { first: <em>'Barney'</em>, last: <em>'Rubble'</em> },
city: <em>'Bedrock'</em>, state: <em>'Stoneridge'</em>
},
{ key: 3,
name: { first: <em>'Cliff'</em>, last: <em>'Claven'</em> },
city: <em>'Boston'</em>, state: <em>'MA'</em>
}
];</code></pre></div></div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-dateFormat"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-dateFormat">dateFormat</a></b> : String<div class="mdesc"><div class="short">A format string for the Date.parseDate function, or "timestamp" if the
value provided by the Reader is a UNIX timesta...</div><div class="long">A format string for the <a href="output/Date.html#Date-parseDate" ext:member="parseDate" ext:cls="Date">Date.parseDate</a> function, or "timestamp" if the
value provided by the Reader is a UNIX timestamp, or "time" if the value provided by the Reader is a
javascript millisecond timestamp.</div></div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-defaultValue"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-defaultValue">defaultValue</a></b> : Mixed<div class="mdesc"><div class="short">The default value used when a Record is being created by a Reader
when the item referenced by the mapping does not ex...</div><div class="long">The default value used <b>when a Record is being created by a <a href="output/Ext.data.Reader.html" ext:cls="Ext.data.Reader">Reader</a></b>
when the item referenced by the <tt><a href="output/Ext.data.Field.html#Ext.data.Field-mapping" ext:member="mapping" ext:cls="Ext.data.Field">mapping</a></tt> does not exist in the data
object (i.e. undefined). (defaults to "")</div></div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-mapping"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-mapping">mapping</a></b> : String/Number<div class="mdesc"><div class="short">(Optional) A path expression for use by the Ext.data.DataReader implementation
that is creating the Record to extract...</div><div class="long"><p>(Optional) A path expression for use by the <a href="output/Ext.data.DataReader.html" ext:cls="Ext.data.DataReader">Ext.data.DataReader</a> implementation
that is creating the <a href="output/Ext.data.Record.html" ext:cls="Ext.data.Record">Record</a> to extract the Field value from the data object.
If the path expression is the same as the field name, the mapping may be omitted.</p>
<p>The form of the mapping expression depends on the Reader being used.</p>
<div class="mdetail-params"><ul>
<li><a href="output/Ext.data.JsonReader.html" ext:cls="Ext.data.JsonReader">Ext.data.JsonReader</a><div class="sub-desc">The mapping is a string containing the javascript
expression to reference the data from an element of the data item's <a href="output/Ext.data.JsonReader.html#Ext.data.JsonReader-root" ext:member="root" ext:cls="Ext.data.JsonReader">root</a> Array. Defaults to the field name.</div></li>
<li><a href="output/Ext.data.XmlReader.html" ext:cls="Ext.data.XmlReader">Ext.data.XmlReader</a><div class="sub-desc">The mapping is an <a href="output/Ext.DomQuery.html" ext:cls="Ext.DomQuery">Ext.DomQuery</a> path to the data
item relative to the DOM element that represents the <a href="output/Ext.data.XmlReader.html#Ext.data.XmlReader-record" ext:member="record" ext:cls="Ext.data.XmlReader">record</a>. Defaults to the field name.</div></li>
<li><a href="output/Ext.data.ArrayReader.html" ext:cls="Ext.data.ArrayReader">Ext.data.ArrayReader</a><div class="sub-desc">The mapping is a number indicating the Array index
of the field's value. Defaults to the field specification's Array position.</div></li>
</ul></div>
<p>If a more complex value extraction strategy is required, then configure the Field with a <a href="output/Ext.data.Field.html#Ext.data.Field-convert" ext:member="convert" ext:cls="Ext.data.Field">convert</a>
function. This is passed the whole row object, and may interrogate it in whatever way is necessary in order to
return the desired data.</p></div></div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-name"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-name">name</a></b> : String<div class="mdesc"><div class="short">The name by which the field is referenced within the Record. This is referenced by, for example,
the dataIndex proper...</div><div class="long">The name by which the field is referenced within the Record. This is referenced by, for example,
the <tt>dataIndex</tt> property in column definition objects passed to <a href="output/Ext.grid.ColumnModel.html" ext:cls="Ext.grid.ColumnModel">Ext.grid.ColumnModel</a>.
<p>Note: In the simplest case, if no properties other than <tt>name</tt> are required, a field
definition may consist of just a String for the field name.</p></div></div></td><td class="msource">Field</td></tr><tr class="config-row "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-sortDir"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-sortDir">sortDir</a></b> : String<div class="mdesc">Initial direction to sort (<tt>"ASC"</tt> or <tt>"DESC"</tt>). Defaults to
<tt>"ASC"</tt>.</div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-sortType"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-sortType">sortType</a></b> : Function<div class="mdesc"><div class="short">A function which converts a Field's value to a comparable value in order to ensure
correct sort ordering. Predefined ...</div><div class="long">A function which converts a Field's value to a comparable value in order to ensure
correct sort ordering. Predefined functions are provided in <a href="output/Ext.data.SortTypes.html" ext:cls="Ext.data.SortTypes">Ext.data.SortTypes</a>. A custom
sort example:<pre><code><i>// current sort after sort we want</i>
<i>// +-+------+ +-+------+</i>
<i>// |1|First | |1|First |</i>
<i>// |2|Last | |3|Second|</i>
<i>// |3|Second| |2|Last |</i>
<i>// +-+------+ +-+------+</i>
sortType: <b>function</b>(value) {
<b>switch</b> (value.toLowerCase()) <i>// native toLowerCase():</i>
{
<b>case</b> <em>'first'</em>: <b>return</b> 1;
<b>case</b> <em>'second'</em>: <b>return</b> 2;
<b>default</b>: <b>return</b> 3;
}
}</code></pre></div></div></td><td class="msource">Field</td></tr><tr class="config-row expandable "><td class="micon"><a href="#expand" class="exi"> </a></td><td class="sig"><a id="Ext.data.Field-type"></a><b><a href="source/DataField.html#cfg-Ext.data.Field-type">type</a></b> : String<div class="mdesc"><div class="short">The data type for conversion to displayable value if convert
has not been specified. Possible values are
<div class="...</div><div class="long">The data type for conversion to displayable value if <tt><a href="output/Ext.data.Field.html#Ext.data.Field-convert" ext:member="convert" ext:cls="Ext.data.Field">convert</a></tt>
has not been specified. Possible values are
<div class="mdetail-params"><ul>
<li>auto (Default, implies no conversion)</li>
<li>string</li>
<li>int</li>
<li>float</li>
<li>boolean</li>
<li>date</li></ul></div></div></div></td><td class="msource">Field</td></tr></tbody></table><a id="Ext.data.Field-props"></a><h2>Public Properties</h2><div class="no-members">This class has no public properties.</div><a id="Ext.data.Field-methods"></a><h2>Public Methods</h2><div class="no-members">This class has no public methods.</div><a id="Ext.data.Field-events"></a><h2>Public Events</h2><div class="no-members">This class has no public events.</div></div>
|
alibama/rapid-prototyping-ecommerce-drupal
|
sites/all/libraries/extjs/3.1.0/docs/output/Ext.data.Field.html
|
HTML
|
gpl-2.0
| 13,016
|
/**
* @plugin leanerModal
* @author Finely Sliced <finelysliced.com.au>
* @author Edward Hotchkiss <edwardhotchkiss@me.com>
* @description originally from http://leanmodal.finelysliced.com.au/
*
* @modified by AJ Clarke for the Total WordPress theme
**/
(function($) {
$.fn.extend({
leanerModal: function(options) {
function close_modal(modal_id) {
$(modal_id).removeClass( 'active' );
$("#lean_overlay").fadeOut();
$(modal_id).css({
display: "none"
});
}
var defaults = {
overlay: .5,
closeButton: ".modal_close"
};
var overlay = $('<div id="lean_overlay"></div>');
if (!$("#lean_overlay").length) {
$("body").append(overlay);
}
options = $.extend(defaults, options);
return this.each(function() {
var _options = options;
$(this).live("click", function(e) {
var modal_id = _options.id;
$("#lean_overlay").live("click", function() {
close_modal(modal_id)
});
$(_options.closeButton).live("click", function() {
close_modal(modal_id)
});
var modal_height = $(modal_id).outerHeight();
var modal_width = $(modal_id).outerWidth();
$("#lean_overlay").css({
display: "block",
opacity: 0
});
$("#lean_overlay").stop( true, true ).fadeTo(200, _options.overlay);
$(modal_id).css({
display: "block",
position: "fixed",
opacity: 0,
"z-index": 11e3,
left: 50 + "%",
"margin-left": -(modal_width / 2) + "px"
});
$(modal_id).stop( true, true ).fadeTo(200, 1).addClass( 'active' );
return false;
});
});
}
});
})(jQuery);
|
iq007/MadScape
|
wp-content/themes/Total/js/lib/leanner-modal.js
|
JavaScript
|
gpl-2.0
| 1,671
|
/* ============================================================
*
* This file is a part of digiKam project
* http://www.digikam.org
*
* Date : 2012-10-03
* Description : kipi loader implementation
*
* Copyright (C) 2004-2012 by Gilles Caulier <caulier dot gilles at gmail dot com>
* Copyright (C) 2012 by Victor Dodon <dodonvictor at gmail dot 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, 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.
*
* ============================================================ */
#ifndef KIPIPLUGINLOADER_H
#define KIPIPLUGINLOADER_H
// Qt includes
#include <QObject>
#include <QList>
// LibKIPI includes
#include <libkipi/plugin.h>
class QAction;
class KActionCollection;
using namespace KIPI;
namespace Digikam
{
class SplashScreen;
class KipiPluginLoader : public QObject
{
Q_OBJECT
public:
/** Standard constructor. Pass parent object instance and splashscreen
* instance. This last one can be null.
*/
KipiPluginLoader(QObject* const parent, SplashScreen* const splash);
/** Return a list of all plugin actions accordingly of plugin category.
* See Category enum for details.
*/
QList<QAction*> kipiActionsByCategory(Category cat) const;
/** Return the instance of action collection for all KIPI plugins.
*/
KActionCollection* pluginsActionCollection() const;
/** Return the instance of this singleton plugin loader.
*/
static KipiPluginLoader* instance();
private Q_SLOTS:
/** Called by PluginLoader when plugins list must be re-loaded in application.
*/
void slotKipiPluginPlug();
private:
/** Disabled destructor.
*/
~KipiPluginLoader();
private:
static KipiPluginLoader* m_instance;
class Private;
Private* const d;
};
} // namespace Digikam
#endif // KIPIPLUGINLOADER_H
|
centic9/digikam-ppa
|
core/utilities/kipiiface/kipipluginloader.h
|
C
|
gpl-2.0
| 2,264
|
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2013 Live Networks, Inc. All rights reserved.
// A simple RTP sink that packs frames into each outgoing
// packet, without any fragmentation or special headers.
// Implementation
#include "SimpleRTPSink.hh"
SimpleRTPSink::SimpleRTPSink(UsageEnvironment& env, Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency,
char const* sdpMediaTypeString,
char const* rtpPayloadFormatName,
unsigned numChannels,
Boolean allowMultipleFramesPerPacket,
Boolean doNormalMBitRule)
: MultiFramedRTPSink(env, RTPgs, rtpPayloadFormat,
rtpTimestampFrequency, rtpPayloadFormatName,
numChannels),
fAllowMultipleFramesPerPacket(allowMultipleFramesPerPacket) {
fSDPMediaTypeString
= strDup(sdpMediaTypeString == NULL ? "unknown" : sdpMediaTypeString);
fSetMBitOnLastFrames = doNormalMBitRule && strcmp(fSDPMediaTypeString, "audio") != 0;
}
SimpleRTPSink::~SimpleRTPSink() {
delete[] (char*)fSDPMediaTypeString;
}
SimpleRTPSink*
SimpleRTPSink::createNew(UsageEnvironment& env, Groupsock* RTPgs,
unsigned char rtpPayloadFormat,
unsigned rtpTimestampFrequency,
char const* sdpMediaTypeString,
char const* rtpPayloadFormatName,
unsigned numChannels,
Boolean allowMultipleFramesPerPacket,
Boolean doNormalMBitRule) {
return new SimpleRTPSink(env, RTPgs,
rtpPayloadFormat, rtpTimestampFrequency,
sdpMediaTypeString, rtpPayloadFormatName,
numChannels,
allowMultipleFramesPerPacket,
doNormalMBitRule);
}
void SimpleRTPSink::doSpecialFrameHandling(unsigned fragmentationOffset,
unsigned char* frameStart,
unsigned numBytesInFrame,
struct timeval framePresentationTime,
unsigned numRemainingBytes) {
if (numRemainingBytes == 0) {
// This packet contains the last (or only) fragment of the frame.
// Set the RTP 'M' ('marker') bit, if appropriate:
if (fSetMBitOnLastFrames) setMarkerBit();
}
// Important: Also call our base class's doSpecialFrameHandling(),
// to set the packet's timestamp:
MultiFramedRTPSink::doSpecialFrameHandling(fragmentationOffset,
frameStart, numBytesInFrame,
framePresentationTime,
numRemainingBytes);
}
Boolean SimpleRTPSink::
frameCanAppearAfterPacketStart(unsigned char const* /*frameStart*/,
unsigned /*numBytesInFrame*/) const {
return fAllowMultipleFramesPerPacket;
}
char const* SimpleRTPSink::sdpMediaType() const {
return fSDPMediaTypeString;
}
|
DDTChen/CookieVLC
|
vlc/contrib/android/live555/liveMedia/SimpleRTPSink.cpp
|
C++
|
gpl-2.0
| 3,348
|
<!DOCTYPE html>
<html lang="en">
<head>
<title>All Units</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<link rel="StyleSheet" type="text/css" href="pasdoc.css">
</head>
<body>
<div class="container"><div class="navigation">
<ul><li><a href="AllUnits.html">Units</a></li><li><a href="ClassHierarchy.html">Class Hierarchy</a></li><li><a href="AllClasses.html">Classes, Interfaces, Objects and Records</a></li><li><a href="AllTypes.html">Types</a></li><li><a href="AllVariables.html">Variables</a></li><li><a href="AllConstants.html">Constants</a></li><li><a href="AllFunctions.html">Functions and Procedures</a></li><li><a href="AllIdentifiers.html">Identifiers</a></li></ul></div><div class="content">
<h1 class="allitems">All Units</h1>
<table class="unitstable wide_list">
<tr class="listheader">
<th class="itemname">Name</th>
<th class="itemdesc">Description</th>
</tr>
<tr class="list">
<td class="itemname"><a class="bold" href="warning_back_comment_class.html">warning_back_comment_class</a></td>
<td class="itemdesc"><p> </p></td>
</tr>
</table>
</div></div></body></html>
|
pasdoc/pasdoc
|
tests/testcases_output/html/warning_back_comment_class/index.html
|
HTML
|
gpl-2.0
| 1,184
|
/*-
* Copyright (c) 1991 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Kenneth Almquist.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* from: @(#)input.h 5.1 (Berkeley) 3/7/91
* input.h,v 1.4 1993/08/01 18:58:27 mycroft Exp
*/
/* PEOF (the end of file marker) is defined in syntax.h */
/*
* The input line number. Input.c just defines this variable, and saves
* and restores it when files are pushed and popped. The user of this
* package must set its value.
*/
extern int plinno;
extern int parsenleft; /* number of characters left in input buffer */
extern char *parsenextc; /* next character in input buffer */
#ifdef __STDC__
char *pfgets(char *, int);
int pgetc(void);
int preadbuffer(void);
void pungetc(void);
void ppushback(char *, int);
void setinputfile(char *, int);
void setinputfd(int, int);
void setinputstring(char *, int);
void popfile(void);
void popallfiles(void);
void closescript(void);
#else
char *pfgets();
int pgetc();
int preadbuffer();
void pungetc();
void ppushback();
void setinputfile();
void setinputfd();
void setinputstring();
void popfile();
void popallfiles();
void closescript();
#endif
#define pgetc_macro() (--parsenleft >= 0? *parsenextc++ : preadbuffer())
|
vandys/vsta
|
src/bin/ash/input.h
|
C
|
gpl-2.0
| 2,988
|
/*
* Copyright (c) 2007, 2011, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package com.sun.max.jdwp.vm.proxy;
/**
* Listener interface for anybody who wants to be informed about VM events.
*
*/
public interface VMListener {
/**
* This method is called when the VM is started.
*/
void vmStarted();
/**
* This method is called when the VM is shutdown.
*/
void vmDied();
/**
* Informs about the start of a thread.
*
* @param thread the thread that has recently been started
*/
void threadStarted(ThreadProvider thread);
/**
* Informs about the death of a thread.
*
* @param thread the thread that has recently died
*/
void threadDied(ThreadProvider thread);
/**
* Informs about the preparation of a newly loaded class.
*
* @param thread the thread that loaded the class
* @param klass the class that was loaded
*/
void classPrepared(ThreadProvider thread, ClassProvider klass);
/**
* Informs about unloading a class.
*
* @param thread the thread that unloaded the class
* @param klass the class that was unloaded
*/
void classUnloaded(ThreadProvider thread, ClassProvider klass);
/**
* This method is called whenever a breakpoint is hit.
*
* @param thread the thread that hit the breakpoint
* @param location the code location identifying the breakpoint
*/
void breakpointHit(ThreadProvider thread, JdwpCodeLocation location);
/**
* This method is called from the VM whenever a single step is made.
*
* @param thread the thread that performed the single step
* @param location the code location specifying the current instruction pointer of the thread, i.e. the code location after the single step was made
*/
void singleStepMade(ThreadProvider thread, JdwpCodeLocation location);
}
|
arodchen/MaxSim
|
maxine/com.oracle.max.vmdi/src/com/sun/max/jdwp/vm/proxy/VMListener.java
|
Java
|
gpl-2.0
| 2,898
|
<?php
/**
* Advanced comunications
*
* Adds email features to Orders edit, allowing to send, and saved, predefined emails
*
* @package TheCartPress
* @subpackage Modules
*/
/**
* This file is part of TheCartPress.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) exit;
if ( ! class_exists( 'TCPAdvancedCommunication' ) ) :
define( 'TCP_EMAIL_POST_TYPE', 'tcp_email' );
class TCPAdvancedCommunication {
static $order_id = false;
static $order = false;
static function init() {
//add_action( 'init' , array( __CLASS__, 'register_post_type' ) );
if ( is_admin() ) {
add_action( 'admin_init' , array( __CLASS__, 'admin_init' ) );
add_action( 'tcp_order_edit_metaboxes' , array( __CLASS__, 'tcp_order_edit_metaboxes' ), 10, 2 );
}
}
/*static function register_post_type() {
$labels = array(
'name' => __( 'Emails', 'tcp' ),
'singular_name' => __( 'Email', 'tcp' ),
'add_new' => __( 'Add New', 'tcp' ),
'add_new_item' => __( 'Add New Email', 'tcp' ),
'edit_item' => __( 'Edit Email', 'tcp' ),
'new_item' => __( 'New Email', 'tcp' ),
'all_items' => __( 'All Emails', 'tcp' ),
'view_item' => __( 'View Email', 'tcp' ),
'search_items' => __( 'Search Emails', 'tcp' ),
'not_found' => __( 'No Emails found', 'tcp' ),
'not_found_in_trash' => __( 'No Emails found in Trash', 'tcp' ),
'parent_item_colon' => '',
'menu_name' => __( 'Emails', 'tcp' ),
);
$args = array(
'labels' => $labels,
'public' => false,
'publicly_queryable' => false,
'show_ui' => false,
'show_in_menu' => false,
'query_var' => true,
'rewrite' => false,
'capability_type' => 'page',
'exclude_from_search' => true,
'has_archive' => false,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail' ),
);
register_post_type( TCP_EMAIL_POST_TYPE, $args );
}*/
static function admin_init() {
add_action( 'wp_ajax_tcp_advanced_comm', array( __CLASS__, 'tcp_advanced_comm' ) );
// Adds "Subject" field to tcp_templates
if ( ! tcp_exists_custom_field_def( 'tcp_template', 'tcp_subject' ) ) {
tcp_add_custom_field_def( 'tcp_template', 'tcp_subject', __( 'Subject', 'tcp' ), TCP_CUSTOM_FIELD_TYPE_TEXT, 0, __( 'This field will be used if the notice is used as email', 'tcp' ) );
}
}
static function tcp_advanced_comm() {
switch( $_REQUEST['to_do'] ) {
case 'tcp_get_email_text' :
TCPAdvancedCommunication::tcp_get_email_text();
break;
case 'tcp_send_email' :
TCPAdvancedCommunication::tcp_send_email();
break;
case 'tcp_save_email' :
TCPAdvancedCommunication::tcp_save_email();
break;
case 'tcp_get_notices' :
TCPAdvancedCommunication::tcp_get_notices();
break;
case 'tcp_remove_notice' :
TCPAdvancedCommunication::tcp_remove_notice();
break;
}
}
static function tcp_order_edit_metaboxes( $order_id, $order ) {
TCPAdvancedCommunication::$order_id = $order_id;
TCPAdvancedCommunication::$order = $order;
add_meta_box( 'tcp_order_notification_metabox' , __( 'Notice Manager', 'tcp' ), array( __CLASS__, 'tcp_orders_notificaton_metabox' ) , 'tcp-order-edit', 'normal', 'default' );
add_meta_box( 'tcp_order_notifications_metabox' , __( 'Notifications', 'tcp' ), array( __CLASS__, 'tcp_orders_notificatons_metabox' ) , 'tcp-order-edit', 'side', 'default' );
}
static function tcp_orders_notificaton_metabox() {
$order_id = TCPAdvancedCommunication::$order_id;
$order = TCPAdvancedCommunication::$order; ?>
<p>
<label for="tcp_email_to_send"><?php _e( 'Emails', 'tcp' ); ?>: </label>
<?php $emails = get_posts( array( 'post_type' => 'tcp_template', 'numberposts' => -1, 'fields' => 'ids' ) );
if ( is_array( $emails ) && count( $emails ) > 0 ) : ?>
<select id="tcp-email-to-send">
<option value=""><?php _e( 'Free text', 'tcp-advanced' ); ?></option>
<?php foreach( $emails as $post_id ) : ?>
<option value="<?php echo $post_id; ?>"><?php echo get_the_title( $post_id); ?></option>
<?php endforeach; ?>
</select><?php tcp_the_feedback_image( 'tcp-load-text-feedback' ); ?>
<span class="description"><?php _e( 'Create more notices visiting ', 'tcp' ); ?> <a href="edit.php?post_type=tcp_template"><?php _e( 'Notices administrator', 'tcp' ); ?></a></span>
<script>
jQuery( '#tcp-email-to-send' ).change( function ( event ) {
var feedback = jQuery( '.tcp-load-text-feedback' );
feedback.show();
jQuery.ajax( {
async : true,
type : "POST",
url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data : {
action : 'tcp_advanced_comm',
to_do : 'tcp_get_email_text',
order_id : '<?php echo $order_id; ?>',
post_id : jQuery( '#tcp-email-to-send' ).val(),
},
success : function(response) {
feedback.hide();
if ( typeof( tinymce ) == 'object' ) {
data = JSON.parse( response );
jQuery( '#tcp_notice_subject' ).val( data.subject || '' );
tinyMCE.activeEditor.setContent( data.content || '');
}
},
error : function(response) {
feedback.hide();
},
});
event.stopPropagation();
return false;
} );
</script>
<div class="tcp-email-subject">
<label><?php _e( 'Subject', 'tcp' ); ?>: <input type="text" name="tcp_notice_subject" id="tcp_notice_subject" maxlength="255" class="widefat" value="<?php printf( __( 'Order from %s, Order ID: %s', 'tcp' ), htmlentities( get_bloginfo( 'name' ) ), $order_id ); ?>" />
<label><?php _e( 'Send a copy to me', 'tcp' ); ?> <input type="checkbox" name="tcp_copy_to_me" id="tcp_copy_to_me" value="yes"/></label>
</div>
<div class="tcp-email-modify-text">
<?php wp_editor( '', 'tcp-text-to-send' ); ?>
</div><!-- .tcp_email_modify_text -->
<p>
<input type="button" name="tcp-send-email" id="tcp-send-email" value="<?php _e( 'Save & Send', 'tcp' ); ?>" class="button-primary"/>
<?php tcp_the_feedback_image( 'tcp-send-email-feedback' ); ?>
<span id="tcp-sending" style="display: none;"><?php _e( 'Sending...', 'tcp' ); ?></span>
<span id="tcp-error-sending" style="display: none;"><?php _e( 'Error sending', 'tcp' ); ?></span>
<input type="button" name="tcp-save-email" id="tcp-save-email" value="<?php _e( 'Save', 'tcp' ); ?>" class="button-primary"/>
<?php tcp_the_feedback_image( 'tcp-save-email-feedback' ); ?>
<span id="tcp-saved" style="display: none;"><?php _e( 'Saved...', 'tcp' ); ?></span>
</p>
<script>
jQuery( '#tcp-send-email' ).click( function ( event ) {
var feedback = jQuery( '.tcp-send-email-feedback' );
var tcp_copy_to_me = jQuery( '#tcp_copy_to_me' ).attr( 'checked' );
feedback.show();
jQuery.ajax( {
async : true,
type : "POST",
url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data : {
action : 'tcp_advanced_comm',
to_do : 'tcp_send_email',
order_id : '<?php echo $order_id; ?>',
subject : jQuery( '#tcp_notice_subject' ).val(),
copy_to_me : tcp_copy_to_me,
text : tinymce.activeEditor.getContent(),
},
success : function( response ) {
feedback.hide();
if ( response == 'OK' ) {
jQuery( '#tcp-sending' ).show( 800).delay( 2000 ).hide( 800 );
} else {
jQuery( '#tcp-error-sending' ).show( 400 ).delay( 1000 ).hide( 400 );
}
tcp_load_notices( <?php echo $order_id; ?> );
},
error : function( response ) {
feedback.hide();
},
} );
event.stopPropagation();
return false;
} );
jQuery( '#tcp-save-email' ).click( function( event ) {
var feedback = jQuery( '.tcp-save-email-feedback' );
feedback.show();
jQuery.ajax( {
async : true,
type : "POST",
url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data : {
action : 'tcp_advanced_comm',
to_do : 'tcp_save_email',
order_id : '<?php echo $order_id; ?>',
subject : jQuery( '#tcp_notice_subject' ).val(),
text : tinymce.activeEditor.getContent(),
},
success : function( response ) {
feedback.hide();
jQuery( '#tcp-saved' ).show( 800).delay( 2000 ).hide( 800 );
tcp_load_notices( <?php echo $order_id; ?> );
},
error : function( response ) {
feedback.hide();
},
} );
event.stopPropagation();
return false;
} );
</script>
<?php else : ?>
<p class="description"><?php _e( 'No Notices/Emails templates.', 'tcp' ); ?> <a href="edit.php?post_type=tcp_template"><?php _e( 'Create Notices', 'tcp' ); ?></a></p>
<?php endif; ?>
</p>
<?php }
static function tcp_send_email() {
$text = isset( $_REQUEST['text'] ) ? stripslashes( $_REQUEST['text'] ) : false;
$order_id = isset( $_REQUEST['order_id'] ) ? $_REQUEST['order_id'] : false;
$subject = isset( $_REQUEST['subject'] ) ? stripslashes( $_REQUEST['subject'] ) : sprintf( __( 'Order ID: %s', 'tcp' ), $order_id );
$copy_to_me = isset( $_REQUEST['copy_to_me'] ) ? $_REQUEST['copy_to_me'] : false;
require_once( TCP_DAOS_FOLDER . 'Orders.class.php' );
$order = Orders::get( $order_id );
$to = isset( $_REQUEST['to'] ) ? $_REQUEST['to'] : $order->billing_email;
global $thecartpress;
$from = $thecartpress->get_setting( 'from_email', 'no-response@thecartpress.com' );
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
$headers .= 'From: ' . get_bloginfo( 'name' ) . ' <' . $from . ">\r\n";
if ( $copy_to_me ) {
global $thecartpress;
$bcc = $thecartpress->get_setting( 'emails', false );
if ( $bcc !== false ) $headers .= 'Bcc: ' . $bcc . "\r\n";
}
TCPAdvancedCommunication::tcp_save_email( $subject );
if ( wp_mail( $to, $subject, $text, $headers ) ) {
die( 'OK' );
} else {
die( 'error sending' );
}
}
static function tcp_save_email( $title = '' ) {
$text = isset( $_REQUEST['text'] ) ? stripslashes( $_REQUEST['text'] ) : false;
$order_id = isset( $_REQUEST['order_id'] ) ? $_REQUEST['order_id'] : false;
$created_at = current_time( 'mysql' );
$subject = isset( $_REQUEST['subject'] ) ? stripslashes( $_REQUEST['subject'] ) : $title;
$notice = array(
'post_type' => TCP_EMAIL_POST_TYPE,
'post_title' => $subject,
'post_content' => $text,
'post_status' => 'publish',
'post_parent' => $order_id,
);
$post_id = wp_insert_post( $notice );
return $post_id;
}
static function tcp_remove_notice() {
$post_id = isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : false;
if ( $post_id === false ) die( 'Error, no post id param' );
if ( wp_delete_post( $post_id, true ) ) die( 'OK' );
else die( 'Error deleting notice' );
}
static function tcp_get_email_text() {
$post_id = isset( $_REQUEST['post_id'] ) ? $_REQUEST['post_id'] : false;
$order_id = isset( $_REQUEST['order_id'] ) ? $_REQUEST['order_id'] : false;
if ( $post_id !== false && $order_id !== false ) {
require_once( TCP_DAOS_FOLDER . 'Orders.class.php' );
TCPAdvancedCommunication::$order_id = $order_id;
TCPAdvancedCommunication::$order = Orders::get( $order_id );
$content = apply_filters( 'the_content', get_post_field( 'post_content', $post_id ) );
$content = preg_replace_callback( '/\{(.*?)\}/', array( __CLASS__, 'tcp_email_get_value' ), $content );
$subject = get_post_meta( $post_id, 'tcp_subject', true );
$subject = preg_replace_callback( '/\{(.*?)\}/', array( __CLASS__, 'tcp_email_get_value' ), $subject );
die( json_encode( array(
'subject' => $subject,
'content' => $content,
) ) );
} else {
die( 'error:' . $post_id . ',' . $order_id );
}
}
static function tcp_email_get_value( $keys ) {
if ( isset( TCPAdvancedCommunication::$order->$keys[1] ) ) {
return TCPAdvancedCommunication::$order->$keys[1];
} elseif ( $keys[1] == 'site-title' ) {
return get_bloginfo();
} elseif ( $keys[1] == 'site-url' ) {
return home_url();
} elseif ( $keys[1] == 'total' ) {
return tcp_format_the_price( Orders::getTotal( TCPAdvancedCommunication::$order_id ) );
} else {
return sprintf( '(unknow %s)', $keys[1] );
}
}
static function tcp_orders_notificatons_metabox() {
$order_id = TCPAdvancedCommunication::$order_id;
$order = TCPAdvancedCommunication::$order; ?>
<ul id="tcp-notifications">
</ul>
<li id="tcp-notification" style="display: none">
<a href="#" class="tcp-saved-notice-title"></a> | <a href="#" class="tcp-saved-notice-remove"><span><?php _e( 'remove', 'tcp' ); ?></span></a>
<div class="tcp-saved-notice-content" style="display: none"></div>
</li>
<script>
function tcp_load_notices( order_id ) {
var ul = jQuery( '#tcp-notifications' );
var feedback = jQuery( '.tcp-get-notices-feedback' );
feedback.show();
jQuery.ajax( {
async : true,
type : "POST",
url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data : {
action : 'tcp_advanced_comm',
to_do : 'tcp_get_notices',
order_id : order_id,
},
success : function( response ) {
feedback.hide();
ul.empty();
var alternate = false;
var notices = jQuery.parseJSON( response );
for( var i in notices ) {
var notice = notices[i];
var item = jQuery( 'li#tcp-notification' ).clone().attr( 'id', '' );
item.find( '.tcp-saved-notice-title' ).attr( 'title', notice['created_at'] ).html( notice['title'] );
item.find( '.tcp-saved-notice-remove' ).attr( 'rel-data', notice['post_id'] );
item.find( '.tcp-saved-notice-content' ).html( notice['content'] );
if ( alternate ) item.addClass( 'alternate' );
alternate = ! alternate;
ul.append( item.show() );
}
},
error : function( response ) {
feedback.hide();
},
} );
}
jQuery().ready( function () {
jQuery( '#tcp-notifications' ).on( 'click', '.tcp-saved-notice-title', function( event ) {
jQuery( this ).parent().find( '.tcp-saved-notice-content' ).toggle( 200 );
event.stopPropagation();
return false;
} );
jQuery( '#tcp-notifications' ).on( 'click', '.tcp-saved-notice-remove', function( event ) {
if ( confirm( '<?php _e( 'Do you really want to remove this notice?', 'tcp' ); ?>' ) ) {
var remove = jQuery( this );
var post_id = remove.attr( 'rel-data');
var feedback = jQuery( '.tcp-get-notices-feedback' );
feedback.show();
jQuery.ajax( {
async : true,
type : "POST",
url : "<?php echo admin_url( 'admin-ajax.php' ); ?>",
data : {
action : 'tcp_advanced_comm',
to_do : 'tcp_remove_notice',
post_id : post_id,
},
success : function( response ) {
feedback.hide();
if ( response == 'OK' ) remove.parent().remove();
},
error : function( response ) {
feedback.hide();
},
} );
}
event.stopPropagation();
return false;
} );
tcp_load_notices( <?php echo $order_id; ?> );
} );
</script>
<?php }
static function tcp_get_notices() {
$order_id = isset( $_REQUEST['order_id'] ) ? $_REQUEST['order_id'] : false;
if ( $order_id === false ) die( 'Error, no order id.' );
$results = array();
$args = array(
'post_type' => TCP_EMAIL_POST_TYPE,
'post_parent' => $order_id,
'posts_per_page'=> -1,
'fields' => 'ids',
);
$posts = get_posts( $args );
foreach( $posts as $post_id ) {
$post = get_post( $post_id );
$results[$post_id] = array(
'post_id' => $post_id,
'title' => $post->post_title,
'created_at' => $post->post_date,
'author' => $post->post_author,
'content' => $post->post_content,
);
}
die( json_encode( $results ) );
}
}
TCPAdvancedCommunication::init();
endif; // class_exists check
|
hassankbrian/LoveItLocal
|
wp-content/plugins/thecartpress/modules/AdvancedCommunication.class.php
|
PHP
|
gpl-2.0
| 16,146
|
{- |
Module : ./CASL_DL/Parse_AS.hs
Description : Parser for CASL_DL
Copyright : (c) Klaus Luettich, Uni Bremen 2004
License : similar to LGPL, see HetCATS/LICENSE.txt or LIZENZ.txt
Maintainer : luecke@informatik.uni-bremen.de
Stability : provisional
Portability : portable
Parser for CASL_DL logic
-}
module CASL_DL.Parse_AS where
import Common.AnnoState
import Common.Id
import Common.Lexer
import Common.Parsec
import Common.Token
import CASL_DL.AS_CASL_DL
import CASL.Formula
import CASL.AS_Basic_CASL
import Text.ParserCombinators.Parsec
dlFormula :: AParser st DL_FORMULA
dlFormula = do
(ct, ctp) <- cardKeyword
o <- oBracketT
p <- parsePredSymb
c <- cBracketT
op <- oParenT
t1 <- term casl_DL_reserved_words
co <- anComma
t2 <- term casl_DL_reserved_words
t3 <- optionMaybe $ anComma >> formula casl_DL_reserved_words
cp <- cParenT
return $ Cardinality ct p t1 t2 t3
$ appRange ctp $ concatMapRange tokPos [o, c, op, co, cp]
parsePredSymb :: AParser st PRED_SYMB
parsePredSymb = fmap Pred_name (parseId casl_DL_reserved_words)
<|> do
o <- oParenT << addAnnos
Mixfix_qual_pred qpred <- qualPredName casl_DL_reserved_words o
return qpred
<?> "a PRED_SYMB"
cardKeyword :: AParser st (CardType, Range)
cardKeyword = choice $ map ( \ v -> do
kw <- asKey $ show v
return (v, tokPos kw)) caslDLCardTypes
instance TermParser DL_FORMULA where
termParser = aToTermParser dlFormula
|
spechub/Hets
|
CASL_DL/Parse_AS.hs
|
Haskell
|
gpl-2.0
| 1,535
|
-- ============================================================================
-- Copyright (C) 2005-2007 Laurent Destailleur <eldy@users.sourceforge.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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
--
-- $Id: llx_socpeople.key.sql,v 1.1 2009/10/07 18:18:05 eldy Exp $
-- ============================================================================
ALTER TABLE llx_socpeople ADD INDEX idx_socpeople_fk_soc (fk_soc);
ALTER TABLE llx_socpeople ADD INDEX idx_socpeople_fk_user_creat (fk_user_creat);
ALTER TABLE llx_socpeople ADD CONSTRAINT fk_socpeople_fk_soc FOREIGN KEY (fk_soc) REFERENCES llx_societe (rowid);
ALTER TABLE llx_socpeople ADD CONSTRAINT fk_socpeople_user_creat_user_rowid FOREIGN KEY (fk_user_creat) REFERENCES llx_user (rowid);
|
ricsistemas/dolibarr
|
install_change_folder_name_back_to_install_when_needed/mysql/tables/llx_socpeople.key.sql
|
SQL
|
gpl-2.0
| 1,429
|
/*
* Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP.
* 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
*
* HP designates this particular file as subject to the "Classpath" exception
* as provided by HP in the LICENSE.txt file that accompanied this code.
*/
// Tests the cost of L3 cache miss using child processes.
// Each NUMA node is spawned as a child process via fork(2).
// This one uses mmap() even for 2MB pages (otherwise we can't share), so
// make sure you have non-transparent hugepages.
// sudo sh -c 'echo 196608 > /proc/sys/vm/nr_hugepages'
#include <numa.h>
#include <numaif.h>
#include <unistd.h>
#include <sys/wait.h>
#include <atomic>
#include <chrono>
#include <cstdlib>
#include <iostream>
#include <sstream>
#include <string>
#include <thread>
#include <vector>
#include "foedus/assorted/assorted_func.hpp"
#include "foedus/assorted/uniform_random.hpp"
#include "foedus/debugging/stop_watch.hpp"
#include "foedus/memory/memory_id.hpp"
#include "foedus/memory/shared_memory.hpp"
#include "foedus/thread/numa_thread_scope.hpp"
const uint32_t kRep = 1ULL << 26;
int nodes;
int cores_per_node;
uint64_t mb_per_core;
struct ProcessChannel {
std::atomic<int> initialized_count;
std::atomic<bool> experiment_started;
std::atomic<int> exit_count;
};
foedus::memory::SharedMemory process_channel_memory;
ProcessChannel* process_channel;
foedus::memory::SharedMemory* data_memories;
uint64_t run(const char* blocks, foedus::assorted::UniformRandom* rands) {
uint64_t memory_per_core = mb_per_core << 20;
uint64_t ret = 0;
for (uint32_t i = 0; i < kRep; ++i) {
const char* block = blocks + ((rands->next_uint32() % (memory_per_core >> 6)) << 6);
block += ret % (1 << 6);
ret += *block;
}
return ret;
}
void main_impl(int id, int node) {
foedus::thread::NumaThreadScope scope(node);
uint64_t memory_per_core = mb_per_core << 20;
char* memory = data_memories[node].get_block();
memory += (memory_per_core * id);
foedus::assorted::UniformRandom uniform_random(id);
++process_channel->initialized_count;
while (process_channel->experiment_started.load() == false) {
continue;
}
{
foedus::debugging::StopWatch stop_watch;
uint64_t ret = run(memory, &uniform_random);
stop_watch.stop();
std::stringstream str;
str << "Done " << node << "-" << id
<< " (ret=" << ret << ") in " << stop_watch.elapsed_ms() << " ms. "
<< "On average, " << (static_cast<double>(stop_watch.elapsed_ns()) / kRep)
<< " ns/miss" << std::endl;
std::cout << str.str();
}
}
int process_main(int node) {
std::cout << "Node-" << node << " started working on pid-" << ::getpid() << std::endl;
foedus::thread::NumaThreadScope scope(node);
std::vector<std::thread> threads;
for (auto i = 0; i < cores_per_node; ++i) {
threads.emplace_back(std::thread(main_impl, i, node));
}
std::cout << "Node-" << node << " launched " << cores_per_node << " threads" << std::endl;
for (auto& t : threads) {
t.join();
}
std::cout << "Node-" << node << " ended normally" << std::endl;
++process_channel->exit_count;
return 0;
}
void data_alloc(int node) {
std::stringstream meta_path;
meta_path << "/tmp/foedus_l3miss_multip_experiment_" << ::getpid() << "_node_" << node;
COERCE_ERROR(data_memories[node].alloc(
meta_path.str(),
(mb_per_core << 20) * cores_per_node,
node,
true));
std::cout << "Allocated memory for node-" << node << ":"
<< data_memories[node].get_block() << std::endl;
}
int main(int argc, char **argv) {
if (argc < 4) {
std::cerr << "Usage: ./l3miss_multip_experiment <nodes> <cores_per_node> <mb_per_core>"
<< std::endl;
return 1;
}
nodes = std::atoi(argv[1]);
if (nodes == 0 || nodes > ::numa_num_configured_nodes()) {
std::cerr << "Invalid <nodes>:" << argv[1] << std::endl;
return 1;
}
cores_per_node = std::atoi(argv[2]);
if (cores_per_node == 0 ||
cores_per_node > (::numa_num_configured_cpus() / ::numa_num_configured_nodes())) {
std::cerr << "Invalid <cores_per_node>:" << argv[2] << std::endl;
return 1;
}
mb_per_core = std::atoi(argv[3]);
std::cout << "Allocating data memory.." << std::endl;
data_memories = new foedus::memory::SharedMemory[nodes];
{
std::vector<std::thread> alloc_threads;
for (auto node = 0; node < nodes; ++node) {
alloc_threads.emplace_back(data_alloc, node);
}
for (auto& t : alloc_threads) {
t.join();
}
}
std::cout << "Allocated all data memory." << std::endl;
std::stringstream meta_path;
meta_path << "/tmp/foedus_l3miss_multip_experiment_" << ::getpid() << "_channel";
COERCE_ERROR(process_channel_memory.alloc(meta_path.str(), 1 << 21, 0, true));
process_channel = reinterpret_cast<ProcessChannel*>(process_channel_memory.get_block());
process_channel->initialized_count = 0;
process_channel->experiment_started = false;
process_channel->exit_count = 0;
std::cout << "Allocated channel memory:" << process_channel_memory << std::endl;
std::vector<pid_t> pids;
std::vector<bool> exitted;
for (auto node = 0; node < nodes; ++node) {
pid_t pid = ::fork();
if (pid == -1) {
std::cerr << "fork() failed, error=" << foedus::assorted::os_error() << std::endl;
return 1;
}
if (pid == 0) {
return process_main(node);
} else {
// parent
std::cout << "child process-" << pid << " has been forked" << std::endl;
pids.push_back(pid);
exitted.push_back(false);
}
}
while (process_channel->initialized_count < (nodes * cores_per_node)) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
std::cout << "Child initialization done! Starts the experiment..." << std::endl;
process_channel->experiment_started.store(true);
while (process_channel->exit_count < nodes) {
std::this_thread::sleep_for(std::chrono::seconds(1));
std::cout << "Waiting for end... exit_count=" << process_channel->exit_count << std::endl;
for (uint16_t i = 0; i < pids.size(); ++i) {
if (exitted[i]) {
continue;
}
pid_t pid = pids[i];
int status;
pid_t result = ::waitpid(pid, &status, WNOHANG);
if (result == 0) {
std::cout << " pid-" << pid << " is still alive.." << std::endl;
} else if (result == -1) {
std::cout << " pid-" << pid << " had an error! quit" << std::endl;
return 1;
} else {
std::cout << " pid-" << pid << " has exit with status code " << status << std::endl;
exitted[i] = true;
}
}
}
std::cout << "All done!" << std::endl;
delete[] data_memories;
return 0;
}
|
wangtzh/foedus_code
|
experiments-core/src/foedus/assorted/l3miss_multip_experiment.cpp
|
C++
|
gpl-2.0
| 7,328
|
package Tie::SubstrHash;
=head1 NAME
Tie::SubstrHash - Fixed-table-size, fixed-key-length hashing
=head1 SYNOPSIS
require Tie::SubstrHash;
tie %myhash, 'Tie::SubstrHash', $key_len, $value_len, $table_size;
=head1 DESCRIPTION
The B<Tie::SubstrHash> package provides a hash-table-like interface to
an array of determinate size, with constant key size and record size.
Upon tying a new hash to this package, the developer must specify the
size of the keys that will be used, the size of the value fields that the
keys will index, and the size of the overall table (in terms of key-value
pairs, not size in hard memory). I<These values will not change for the
duration of the tied hash>. The newly-allocated hash table may now have
data stored and retrieved. Efforts to store more than C<$table_size>
elements will result in a fatal error, as will efforts to store a value
not exactly C<$value_len> characters in length, or reference through a
key not exactly C<$key_len> characters in length. While these constraints
may seem excessive, the result is a hash table using much less internal
memory than an equivalent freely-allocated hash table.
=head1 CAVEATS
Because the current implementation uses the table and key sizes for the
hashing algorithm, there is no means by which to dynamically change the
value of any of the initialization parameters.
The hash does not support exists().
=cut
use Carp;
sub TIEHASH {
my $pack = shift;
my ($klen, $vlen, $tsize) = @_;
my $rlen = 1 + $klen + $vlen;
$tsize = [$tsize,
findgteprime($tsize * 1.1)]; # Allow 10% empty.
$self = bless ["\0", $klen, $vlen, $tsize, $rlen, 0, -1];
$$self[0] x= $rlen * $tsize->[1];
$self;
}
sub CLEAR {
local($self) = @_;
$$self[0] = "\0" x ($$self[4] * $$self[3]->[1]);
$$self[5] = 0;
$$self[6] = -1;
}
sub FETCH {
local($self,$key) = @_;
local($klen, $vlen, $tsize, $rlen) = @$self[1..4];
&hashkey;
for (;;) {
$offset = $hash * $rlen;
$record = substr($$self[0], $offset, $rlen);
if (ord($record) == 0) {
return undef;
}
elsif (ord($record) == 1) {
}
elsif (substr($record, 1, $klen) eq $key) {
return substr($record, 1+$klen, $vlen);
}
&rehash;
}
}
sub STORE {
local($self,$key,$val) = @_;
local($klen, $vlen, $tsize, $rlen) = @$self[1..4];
croak("Table is full ($tsize->[0] elements)") if $$self[5] > $tsize->[0];
croak(qq/Value "$val" is not $vlen characters long/)
if length($val) != $vlen;
my $writeoffset;
&hashkey;
for (;;) {
$offset = $hash * $rlen;
$record = substr($$self[0], $offset, $rlen);
if (ord($record) == 0) {
$record = "\2". $key . $val;
die "panic" unless length($record) == $rlen;
$writeoffset = $offset unless defined $writeoffset;
substr($$self[0], $writeoffset, $rlen) = $record;
++$$self[5];
return;
}
elsif (ord($record) == 1) {
$writeoffset = $offset unless defined $writeoffset;
}
elsif (substr($record, 1, $klen) eq $key) {
$record = "\2". $key . $val;
die "panic" unless length($record) == $rlen;
substr($$self[0], $offset, $rlen) = $record;
return;
}
&rehash;
}
}
sub DELETE {
local($self,$key) = @_;
local($klen, $vlen, $tsize, $rlen) = @$self[1..4];
&hashkey;
for (;;) {
$offset = $hash * $rlen;
$record = substr($$self[0], $offset, $rlen);
if (ord($record) == 0) {
return undef;
}
elsif (ord($record) == 1) {
}
elsif (substr($record, 1, $klen) eq $key) {
substr($$self[0], $offset, 1) = "\1";
return substr($record, 1+$klen, $vlen);
--$$self[5];
}
&rehash;
}
}
sub FIRSTKEY {
local($self) = @_;
$$self[6] = -1;
&NEXTKEY;
}
sub NEXTKEY {
local($self) = @_;
local($klen, $vlen, $tsize, $rlen, $entries, $iterix) = @$self[1..6];
for (++$iterix; $iterix < $tsize->[1]; ++$iterix) {
next unless substr($$self[0], $iterix * $rlen, 1) eq "\2";
$$self[6] = $iterix;
return substr($$self[0], $iterix * $rlen + 1, $klen);
}
$$self[6] = -1;
undef;
}
sub EXISTS {
croak "Tie::SubstrHash does not support exists()";
}
sub hashkey {
croak(qq/Key "$key" is not $klen characters long/)
if length($key) != $klen;
$hash = 2;
for (unpack('C*', $key)) {
$hash = $hash * 33 + $_;
&_hashwrap if $hash >= 1e13;
}
&_hashwrap if $hash >= $tsize->[1];
$hash = 1 unless $hash;
$hashbase = $hash;
}
sub _hashwrap {
$hash -= int($hash / $tsize->[1]) * $tsize->[1];
}
sub rehash {
$hash += $hashbase;
$hash -= $tsize->[1] if $hash >= $tsize->[1];
}
# using POSIX::ceil() would be too heavy, and not all platforms have it.
sub ceil {
my $num = shift;
$num = int($num + 1) unless $num == int $num;
return $num;
}
# See:
#
# http://www-groups.dcs.st-andrews.ac.uk/~history/HistTopics/Prime_numbers.html
#
sub findgteprime { # find the smallest prime integer greater than or equal to
use integer;
my $num = ceil(shift);
return 2 if $num <= 2;
$num++ unless $num % 2;
my $i;
my $sqrtnum = int sqrt $num;
my $sqrtnumsquared = $sqrtnum * $sqrtnum;
NUM:
for (;; $num += 2) {
if ($sqrtnumsquared < $num) {
$sqrtnum++;
$sqrtnumsquared = $sqrtnum * $sqrtnum;
}
for ($i = 3; $i <= $sqrtnum; $i += 2) {
next NUM unless $num % $i;
}
return $num;
}
}
1;
|
atmark-techno/atmark-dist
|
user/perl/lib/Tie/SubstrHash.pm
|
Perl
|
gpl-2.0
| 5,374
|
# Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d _build/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml pickle json htmlhelp qthelp latex changes linkcheck doctest
help:
@echo "Please use \`make <target>' where <target> is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf _build/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) _build/html
@echo
@echo "Build finished. The HTML pages are in _build/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) _build/dirhtml
@echo
@echo "Build finished. The HTML pages are in _build/dirhtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) _build/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) _build/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) _build/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in _build/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) _build/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in _build/qthelp, like this:"
@echo "# qcollectiongenerator _build/qthelp/BananaScrum.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile _build/qthelp/BananaScrum.qhc"
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) _build/latex
@echo
@echo "Build finished; the LaTeX files are in _build/latex."
@echo "Run \`make all-pdf' or \`make all-ps' in that directory to" \
"run these through (pdf)latex."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) _build/changes
@echo
@echo "The overview file is in _build/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) _build/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in _build/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) _build/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in _build/doctest/output.txt."
txt:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) _build/txt
@echo
@echo "Build finished. The text files are in _build/txt."
|
Dreyerized/bananascrum
|
doc/Makefile
|
Makefile
|
gpl-2.0
| 3,127
|
/***************************************************************************
* Copyright (C) 2005 by Dominic Rath *
* Dominic.Rath@gmx.de *
* *
* Copyright (C) 2007,2008 Øyvind Harboe *
* oyvind.harboe@zylin.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. *
***************************************************************************/
#ifndef COMMAND_H
#define COMMAND_H
#include <helper/types.h>
/* Integrate the JIM TCL interpretor into the command processing. */
#if BUILD_ECOSBOARD
#include <stdio.h>
#include <stdarg.h>
#endif
#include <jim.h>
#include <jim-nvp.h>
/* To achieve C99 printf compatibility in MinGW, gnu_printf should be
* used for __attribute__((format( ... ))), with GCC v4.4 or later
*/
#if (defined(IS_MINGW) && (((__GNUC__ << 16) + __GNUC_MINOR__) >= 0x00040004))
#define PRINTF_ATTRIBUTE_FORMAT gnu_printf
#else
#define PRINTF_ATTRIBUTE_FORMAT printf
#endif
enum command_mode
{
COMMAND_EXEC,
COMMAND_CONFIG,
COMMAND_ANY,
};
struct command_context;
/// The type signature for command context's output handler.
typedef int (*command_output_handler_t)(struct command_context *context,
const char* line);
struct command_context
{
Jim_Interp *interp;
enum command_mode mode;
struct command *commands;
int current_target;
command_output_handler_t output_handler;
void *output_handler_priv;
};
struct command;
/**
* When run_command is called, a new instance will be created on the
* stack, filled with the proper values, and passed by reference to the
* required COMMAND_HANDLER routine.
*/
struct command_invocation {
struct command_context *ctx;
struct command *current;
const char *name;
unsigned argc;
const char **argv;
};
/**
* Command handlers may be defined with more parameters than the base
* set provided by command.c. This macro uses C99 magic to allow
* defining all such derivative types using this macro.
*/
#define __COMMAND_HANDLER(name, extra...) \
int name(struct command_invocation *cmd, ##extra)
/**
* Use this to macro to call a command helper (or a nested handler).
* It provides command handler authors protection against reordering or
* removal of unused parameters.
*
* @b Note: This macro uses lexical capture to provide some arguments.
* As a result, this macro should be used @b only within functions
* defined by the COMMAND_HANDLER or COMMAND_HELPER macros. Those
* macros provide the expected lexical context captured by this macro.
* Furthermore, it should be used only from the top-level of handler or
* helper function, or care must be taken to avoid redefining the same
* variables in intervening scope(s) by accident.
*/
#define CALL_COMMAND_HANDLER(name, extra...) \
name(cmd, ##extra)
/**
* Always use this macro to define new command handler functions.
* It ensures the parameters are ordered, typed, and named properly, so
* they be can be used by other macros (e.g. COMMAND_PARSE_NUMBER).
* All command handler functions must be defined as static in scope.
*/
#define COMMAND_HANDLER(name) static __COMMAND_HANDLER(name)
/**
* Similar to COMMAND_HANDLER, except some parameters are expected.
* A helper is globally-scoped because it may be shared between several
* source files (e.g. the s3c24xx device command helper).
*/
#define COMMAND_HELPER(name, extra...) __COMMAND_HANDLER(name, extra)
/**
* Use this macro to access the context of the command being handled,
* rather than accessing the variable directly. It may be moved.
*/
#define CMD_CTX cmd->ctx
/**
* Use this macro to access the number of arguments for the command being
* handled, rather than accessing the variable directly. It may be moved.
*/
#define CMD_ARGC cmd->argc
/**
* Use this macro to access the arguments for the command being handled,
* rather than accessing the variable directly. It may be moved.
*/
#define CMD_ARGV cmd->argv
/**
* Use this macro to access the name of the command being handled,
* rather than accessing the variable directly. It may be moved.
*/
#define CMD_NAME cmd->name
/**
* Use this macro to access the current command being handled,
* rather than accessing the variable directly. It may be moved.
*/
#define CMD_CURRENT cmd->current
/**
* Use this macro to access the invoked command handler's data pointer,
* rather than accessing the variable directly. It may be moved.
*/
#define CMD_DATA CMD_CURRENT->jim_handler_data
/**
* The type signature for command handling functions. They are
* usually registered as part of command_registration, providing
* a high-level means for executing a command.
*
* If the command fails, it *MUST* return a value != ERROR_OK
* (many commands break this rule, patches welcome!)
*
* This is *especially* important for commands such as writing
* to flash or verifying memory. The reason is that those commands
* can be used by programs to determine if the operation succeded
* or not. If the operation failed, then a program can try
* an alternative approach.
*
* Returning ERROR_COMMAND_SYNTAX_ERROR will have the effect of
* printing out the syntax of the command.
*/
typedef __COMMAND_HANDLER((*command_handler_t));
struct command
{
char *name;
const char *help;
const char *usage;
struct command *parent;
struct command *children;
command_handler_t handler;
Jim_CmdProc jim_handler;
void *jim_handler_data;
enum command_mode mode;
struct command *next;
};
/**
* @param c The command to be named.
* @param delim The character to place between command names.
* @returns A malloc'd string containing the full command name,
* which may include one or more ancestor components. Multiple names
* are separated by single spaces. The caller must free() the string
* when done with it.
*/
char *command_name(struct command *c, char delim);
/*
* Commands should be registered by filling in one or more of these
* structures and passing them to register_command().
*
* A conventioal format should be used for help strings, to provide both
* usage and basic information:
* @code
* "@<options@> ... - some explanation text"
* @endcode
*
* @param name The name of the command to register, which must not have
* been registered previously in the intended context.
* @param handler The callback function that will be called. If NULL,
* then the command serves as a placeholder for its children or a script.
* @param mode The command mode(s) in which this command may be run.
* @param help The help text that will be displayed to the user.
*/
struct command_registration {
const char *name;
command_handler_t handler;
Jim_CmdProc jim_handler;
void *jim_handler_data;
enum command_mode mode;
const char *help;
/// a string listing the options and arguments, required or optional
const char *usage;
/**
* If non-NULL, the commands in @c chain will be registered in
* the same context and scope of this registration record.
* This allows modules to inherit lists commands from other
* modules.
*/
const struct command_registration *chain;
};
/// Use this as the last entry in an array of command_registration records.
#define COMMAND_REGISTRATION_DONE { .name = NULL, .chain = NULL }
/**
* Register a command @c handler that can be called from scripts during
* the execution @c mode specified.
*
* If @c parent is non-NULL, the new command will be registered as a
* sub-command under it; otherwise, it will be available as a top-level
* command.
*
* @param cmd_ctx The command_context in which to register the command.
* @param parent Register this command as a child of this, or NULL to
* register a top-level command.
* @param rec A command_registration record that contains the desired
* command parameters.
* @returns The new command, if successful; otherwise, NULL.
*/
struct command* register_command(struct command_context *cmd_ctx,
struct command *parent, const struct command_registration *rec);
/**
* Register one or more commands in the specified context, as children
* of @c parent (or top-level commends, if NULL). In a registration's
* record contains a non-NULL @c chain member and name is NULL, the
* commands on the chain will be registered in the same context.
* Otherwise, the chained commands are added as children of the command.
*
* @param cmd_ctx The command_context in which to register the command.
* @param parent Register this command as a child of this, or NULL to
* register a top-level command.
* @param cmds Pointer to an array of command_registration records that
* contains the desired command parameters. The last record must have
* NULL for all fields.
* @returns ERROR_OK on success; ERROR_FAIL if any registration fails.
*/
int register_commands(struct command_context *cmd_ctx, struct command *parent,
const struct command_registration *cmds);
/**
* Unregisters command @c name from the given context, @c cmd_ctx.
* @param cmd_ctx The context of the registered command.
* @param parent The parent of the given command, or NULL.
* @param name The name of the command to unregister.
* @returns ERROR_OK on success, or an error code.
*/
int unregister_command(struct command_context *cmd_ctx,
struct command *parent, const char *name);
/**
* Unregisters all commands from the specfied context.
* @param cmd_ctx The context that will be cleared of registered commands.
* @param parent If given, only clear commands from under this one command.
* @returns ERROR_OK on success, or an error code.
*/
int unregister_all_commands(struct command_context *cmd_ctx,
struct command *parent);
struct command *command_find_in_context(struct command_context *cmd_ctx,
const char *name);
struct command *command_find_in_parent(struct command *parent,
const char *name);
/**
* Update the private command data field for a command and all descendents.
* This is used when creating a new heirarchy of commands that depends
* on obtaining a dynamically created context. The value will be available
* in command handlers by using the CMD_DATA macro.
* @param c The command (group) whose data pointer(s) will be updated.
* @param p The new data pointer to use for the command or its descendents.
*/
void command_set_handler_data(struct command *c, void *p);
void command_set_output_handler(struct command_context* context,
command_output_handler_t output_handler, void *priv);
int command_context_mode(struct command_context *context, enum command_mode mode);
/* Return the current command context associated with the Jim interpreter or
* alternatively the global default command interpreter
*/
struct command_context *current_command_context(Jim_Interp *interp);
/**
* Creates a new command context using the startup TCL provided and
* the existing Jim interpreter, if any. If interp == NULL, then command_init
* creates a command interpreter.
*/
struct command_context* command_init(const char *startup_tcl, Jim_Interp *interp);
/**
* Creates a copy of an existing command context. This does not create
* a deep copy of the command list, so modifications in one context will
* affect all shared contexts. The caller must track reference counting
* and ensure the commands are freed before destroying the last instance.
* @param cmd_ctx The command_context that will be copied.
* @returns A new command_context with the same state as the original.
*/
struct command_context* copy_command_context(struct command_context* cmd_ctx);
/**
* Frees the resources associated with a command context. The commands
* are not removed, so unregister_all_commands() must be called first.
* @param context The command_context that will be destroyed.
*/
void command_done(struct command_context *context);
void command_print(struct command_context *context, const char *format, ...)
__attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)));
void command_print_sameline(struct command_context *context, const char *format, ...)
__attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)));
int command_run_line(struct command_context *context, char *line);
int command_run_linef(struct command_context *context, const char *format, ...)
__attribute__ ((format (PRINTF_ATTRIBUTE_FORMAT, 2, 3)));
void command_output_text(struct command_context *context, const char *data);
void process_jim_events(struct command_context *cmd_ctx);
#define ERROR_COMMAND_CLOSE_CONNECTION (-600)
#define ERROR_COMMAND_SYNTAX_ERROR (-601)
#define ERROR_COMMAND_NOTFOUND (-602)
#define ERROR_COMMAND_ARGUMENT_INVALID (-603)
#define ERROR_COMMAND_ARGUMENT_OVERFLOW (-604)
#define ERROR_COMMAND_ARGUMENT_UNDERFLOW (-605)
int parse_ulong(const char *str, unsigned long *ul);
int parse_ullong(const char *str, unsigned long long *ul);
int parse_long(const char *str, long *ul);
int parse_llong(const char *str, long long *ul);
#define DECLARE_PARSE_WRAPPER(name, type) \
int parse##name(const char *str, type *ul)
DECLARE_PARSE_WRAPPER(_uint, unsigned);
DECLARE_PARSE_WRAPPER(_u32, uint32_t);
DECLARE_PARSE_WRAPPER(_u16, uint16_t);
DECLARE_PARSE_WRAPPER(_u8, uint8_t);
DECLARE_PARSE_WRAPPER(_int, int);
DECLARE_PARSE_WRAPPER(_s32, int32_t);
DECLARE_PARSE_WRAPPER(_s16, int16_t);
DECLARE_PARSE_WRAPPER(_s8, int8_t);
/**
* @brief parses the string @a in into @a out as a @a type, or prints
* a command error and passes the error code to the caller. If an error
* does occur, the calling function will return the error code produced
* by the parsing function (one of ERROR_COMMAND_ARGUMENT_*).
*
* This function may cause the calling function to return immediately,
* so it should be used carefully to avoid leaking resources. In most
* situations, parsing should be completed in full before proceding
* to allocate resources, and this strategy will most prevents leaks.
*/
#define COMMAND_PARSE_NUMBER(type, in, out) \
do { \
int retval_macro_tmp = parse_##type(in, &(out)); \
if (ERROR_OK != retval_macro_tmp) { \
command_print(CMD_CTX, stringify(out) \
" option value ('%s') is not valid", in); \
return retval_macro_tmp; \
} \
} while (0)
/**
* Parse the string @c as a binary parameter, storing the boolean value
* in @c out. The strings @c on and @c off are used to match different
* strings for true and false options (e.g. "on" and "off" or
* "enable" and "disable").
*/
#define COMMAND_PARSE_BOOL(in, out, on, off) \
do { \
bool value; \
int retval_macro_tmp = command_parse_bool_arg(in, &value); \
if (ERROR_OK != retval_macro_tmp) { \
command_print(CMD_CTX, stringify(out) \
" option value ('%s') is not valid", in); \
command_print(CMD_CTX, " choices are '%s' or '%s'", \
on, off); \
return retval_macro_tmp; \
} \
out = value; \
} while (0)
int command_parse_bool_arg(const char *in, bool *out);
COMMAND_HELPER(handle_command_parse_bool, bool *out, const char *label);
/// parses an on/off command argument
#define COMMAND_PARSE_ON_OFF(in, out) \
COMMAND_PARSE_BOOL(in, out, "on", "off")
/// parses an enable/disable command argument
#define COMMAND_PARSE_ENABLE(in, out) \
COMMAND_PARSE_BOOL(in, out, "enable", "disable")
void script_debug(Jim_Interp *interp, const char *cmd,
unsigned argc, Jim_Obj *const *argv);
#endif /* COMMAND_H */
|
ensc/openocd
|
src/helper/command.h
|
C
|
gpl-2.0
| 16,535
|
#undef CONFIG_APM_IGNORE_USER_SUSPEND
|
rohankataria/linuxScheduler
|
include/config/apm/ignore/user/suspend.h
|
C
|
gpl-2.0
| 39
|
/* $Header: /usr/local/dslrepos/uClinux-dist/user/tcsh/patchlevel.h,v 1.1.1.1 2003/08/18 05:40:15 kaohj Exp $ */
/*
* patchlevel.h: Our life story.
*/
#ifndef _h_patchlevel
#define _h_patchlevel
#define ORIGIN "Astron"
#define REV 6
#define VERS 10
#define PATCHLEVEL 0
#define DATE "2000-11-19"
#endif /* _h_patchlevel */
|
ysleu/RTL8685
|
uClinux-dist/user/tcsh/patchlevel.h
|
C
|
gpl-2.0
| 327
|
/*
* Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.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, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_GAMEOBJECTAI_H
#define TRINITY_GAMEOBJECTAI_H
#include "Define.h"
#include "ObjectGuid.h"
#include "QuestDef.h"
class GameObject;
class Unit;
class SpellInfo;
class TC_GAME_API GameObjectAI
{
protected:
GameObject* const me;
public:
explicit GameObjectAI(GameObject* g) : me(g) { }
virtual ~GameObjectAI() { }
virtual void UpdateAI(uint32 /*diff*/) { }
virtual void InitializeAI() { Reset(); }
virtual void Reset() { }
// Pass parameters between AI
virtual void DoAction(int32 /*param = 0 */) { }
virtual void SetGUID(ObjectGuid const& /*guid*/, int32 /*id = 0 */) { }
virtual ObjectGuid GetGUID(int32 /*id = 0 */) const { return ObjectGuid::Empty; }
static int32 Permissible(GameObject const* go);
// Called when a player opens a gossip dialog with the gameobject.
virtual bool GossipHello(Player* /*player*/) { return false; }
// Called when a player selects a gossip item in the gameobject's gossip menu.
virtual bool GossipSelect(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/) { return false; }
// Called when a player selects a gossip with a code in the gameobject's gossip menu.
virtual bool GossipSelectCode(Player* /*player*/, uint32 /*menuId*/, uint32 /*gossipListId*/, char const* /*code*/) { return false; }
// Called when a player accepts a quest from the gameobject.
virtual void QuestAccept(Player* /*player*/, Quest const* /*quest*/) { }
// Called when a player completes a quest and is rewarded, opt is the selected item's index or 0
virtual void QuestReward(Player* /*player*/, Quest const* /*quest*/, uint32 /*opt*/) { }
// Called when the dialog status between a player and the gameobject is requested.
virtual uint32 GetDialogStatus(Player* /*player*/) { return DIALOG_STATUS_SCRIPTED_NO_STATUS; }
// Called when a Player clicks a GameObject, before GossipHello
// prevents achievement tracking if returning true
virtual bool OnReportUse(Player* /*player*/) { return false; }
virtual void Destroyed(Player* /*player*/, uint32 /*eventId*/) { }
virtual void Damaged(Player* /*player*/, uint32 /*eventId*/) { }
virtual uint32 GetData(uint32 /*id*/) const { return 0; }
virtual void SetData64(uint32 /*id*/, uint64 /*value*/) { }
virtual uint64 GetData64(uint32 /*id*/) const { return 0; }
virtual void SetData(uint32 /*id*/, uint32 /*value*/) { }
virtual void OnGameEvent(bool /*start*/, uint16 /*eventId*/) { }
virtual void OnLootStateChanged(uint32 /*state*/, Unit* /*unit*/) { }
virtual void OnStateChanged(uint32 /*state*/) { }
virtual void EventInform(uint32 /*eventId*/) { }
virtual void SpellHit(Unit* /*unit*/, SpellInfo const* /*spellInfo*/) { }
};
class TC_GAME_API NullGameObjectAI : public GameObjectAI
{
public:
explicit NullGameObjectAI(GameObject* g);
void UpdateAI(uint32 /*diff*/) override { }
static int32 Permissible(GameObject const* go);
};
#endif
|
Aokromes/TrinityCore
|
src/server/game/AI/CoreAI/GameObjectAI.h
|
C
|
gpl-2.0
| 3,955
|
BUILD_DIR := $(shell pwd)/v4l
TMP ?= /tmp
ifeq ($(EDITOR),)
ifeq ($(VISUAL),)
EDITOR := vi
else
EDITOR := $(VISUAL) -w
endif
endif
all:
install:
$(MAKE) -C $(BUILD_DIR) install
# Hmm, .PHONY does not work with wildcard rules :-(
SPECS = media-specs
.PHONY: $(SPECS)
$(SPECS):
$(MAKE) -C $(BUILD_DIR) $(MAKECMDGOALS)
%::
$(MAKE) -C $(BUILD_DIR) $(MAKECMDGOALS)
download untar::
$(MAKE) -C linux/ $(MAKECMDGOALS)
dir::
$(MAKE) -C linux/ $(MAKECMDGOALS) DIR="../$(DIR)"
|
ljalves/linux-tbs-drivers
|
Makefile
|
Makefile
|
gpl-2.0
| 489
|
<HTML>
<HEAD>
<TITLE>TCAS</TITLE>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<!-- JS addition for GIP & PVSio -->
<script type="text/javascript" src="scripts/require.js" data-main='scripts/pvsio_utils.js'></script>
<STYLE TYPE="text/css">
#topMargin {
margin-top: 100px;
}
<!--
#pvsio_commands_log {
position:absolute;
left:2px;
top:1351px;
width:2007px;
height:200px;
overflow: scroll;
color: lime;
background: black;
padding: 10px;
font-size: small;
display: none;
}
#TCAS_console {
position:relative;
left:2px;
top:24px;
width:1997px;
height:197px;
overflow: scroll;
color: lime;
background: black;
padding-left: 4px;
padding-top: 4px;
font-family: Arial, Helvetica, sans-serif;
font-size: small;
}
#console {
position:absolute;
left:1039px;
top:21px;
width:390px;
height:106px;
color: lime;
background:black ;
overflow:scroll ;
padding-top: 4px;
padding-left: 4px;
font: 10px Arial;
background-color: black;
z-index: 10;
}
canvas {
position:absolute;
border-radius:64px;
left:333px;
top:133px;
width:237px;
height:216px;
}
.style3 {color: #00FF00}
-->
</STYLE>
<BODY>
<img src="Tcas-image.png" alt="Tcas" width="1024" height="455" vspace="4" border="0" usemap="#Map">
<div id='TCAS_Display' style="position:absolute; top:0; left:0; z-index:1">
<!-- <canvas id="canvas_tcas" width="10000" height="10000" style="border:1px solid #000000;"></canvas> -->
<canvas id="canvas_tcas" width="10000" height="10000"></canvas>
</div>
<p>
<input id="start_demo_button" name="start_demo_button" type="button" onClick="start_TCAS_demo();" value="Start TCAS demo"; style="visibility:visible" />
<input id="pause_demo_button" name="pause_demo_button" type="button" onClick="pause_TCAS_demo();" value="Pause TCAS demo"; style="visibility:visible" />
<input id="resume_demo_button" name="resume_demo_button" type="button" onClick="start_TCAS_demo();" value="Resume TCAS demo"; style="visibility:visible" />
</p>
<p></br>
<div id='console'>
<p>The TCAS-Demo backend is off-line.<br><br>
Please start the TCAS-Demo backend by executing <em>pvsio-web</em> in a Terminal window (<a href="screenshots/pvsio-web.png" target="_blank" class="style3">see screenshot</a>).<br><br>
When the TCAS-Demo backend is on-line, reload this page to start the TCAS-Demo.</p>
</div>
<div id="TCAS_console"> </div>
<div id='pvsio_commands_log'></div>
<script type="text/javascript" src="scripts/UI_mappings.js">
</script>
</BODY>
</HTML>
|
PaoloMasci/PVS
|
pvsio-web/examples/demos/TCAS/pvs/index.html
|
HTML
|
gpl-2.0
| 2,641
|
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Dimitry Polivaev
*
* This file author is Dimitry Polivaev
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.view.swing.map.attribute;
import java.awt.Color;
import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.net.URI;
import javax.swing.Icon;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableCellRenderer;
import org.freeplane.core.util.HtmlUtils;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.attribute.IAttributeTableModel;
import org.freeplane.features.text.HighlightedTransformedObject;
import org.freeplane.features.text.TextController;
class AttributeTableCellRenderer extends DefaultTableCellRenderer {
/**
*
*/
private static final long serialVersionUID = 1L;
static final float ZOOM_CORRECTION_FACTOR = 0.97F;
private boolean isPainting;
private float zoom;
private Color borderColor;
/*
* (non-Javadoc)
* @see javax.swing.JComponent#getHeight()
*/
@Override
public int getHeight() {
if (isPainting) {
if (zoom != 1F) {
return (int) (super.getHeight() / zoom);
}
}
return super.getHeight();
}
@Override
public Component getTableCellRendererComponent(final JTable table, final Object value, final boolean isSelected,
final boolean hasFocus, final int row, final int column) {
final Component rendererComponent = super.getTableCellRendererComponent(table, value, hasFocus, isSelected, row,
column);
if (hasFocus) {
setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
}
zoom = ((AttributeTable) table).getZoom();
final IAttributeTableModel attributeTableModel = (IAttributeTableModel) table.getModel();
final String originalText = value == null ? null : value.toString();
String text = originalText;
borderColor = null;
Icon icon;
if (column == 1 && value != null) {
try {
// evaluate values only
final TextController textController = TextController.getController();
Object transformedObject = textController.getTransformedObject(value, attributeTableModel.getNode(), null);
text = transformedObject.toString();
if (transformedObject instanceof HighlightedTransformedObject && TextController.isMarkTransformedTextSet()) {
borderColor = Color.GREEN;
}
}
catch (Exception e) {
text = TextUtils.format("MainView.errorUpdateText", originalText, e.getLocalizedMessage());
borderColor = Color.RED;
}
if(value instanceof URI){
icon = ((AttributeTable)table).getLinkIcon((URI) value);
}
else{
icon = null;
}
}
else{
icon = null;
}
if(icon != getIcon()){
setIcon(icon);
}
setText(text);
if(text != originalText){
final String toolTip = HtmlUtils.isHtmlNode(originalText) ? text : HtmlUtils.plainToHTML(originalText);
setToolTipText(toolTip);
}
else{
final int prefWidth = getPreferredSize().width;
final int width = table.getColumnModel().getColumn(column).getWidth();
if (prefWidth > width) {
final String toolTip = HtmlUtils.isHtmlNode(text) ? text : HtmlUtils.plainToHTML(text);
setToolTipText(toolTip);
}
else {
setToolTipText(null);
}
}
return rendererComponent;
}
/*
* (non-Javadoc)
* @see javax.swing.JComponent#getWidth()
*/
@Override
public int getWidth() {
if (isPainting) {
if (zoom != 1F) {
return (int) (0.99f + super.getWidth() / zoom);
}
}
return super.getWidth();
}
@Override
public void paint(final Graphics g) {
final Graphics2D g2 = (Graphics2D) g;
if (zoom != 1F) {
zoom *= AttributeTableCellRenderer.ZOOM_CORRECTION_FACTOR;
final AffineTransform transform = g2.getTransform();
g2.scale(zoom, zoom);
isPainting = true;
super.paint(g);
isPainting = false;
g2.setTransform(transform);
}
else {
super.paint(g);
}
if(borderColor != null){
final Color color = g.getColor();
g.setColor(borderColor);
g.drawRect(0, 0, getWidth()-1, getHeight()-1);
g.setColor(color);
}
}
}
|
lcrees/freeplane
|
freeplane/src/main/java/org/freeplane/view/swing/map/attribute/AttributeTableCellRenderer.java
|
Java
|
gpl-2.0
| 4,795
|
<?php
namespace TYPO3\CMS\Core\Utility;
/**
* This file is part of the TYPO3 CMS project.
*
* It is free software; you can redistribute it and/or modify it under
* the terms of the GNU General Public License, either version 2
* of the License, or any later version.
*
* For the full copyright and license information, please read the
* LICENSE.txt file that was distributed with this source code.
*
* The TYPO3 project - inspiring people to share!
*/
/**
* Class with helper functions for array handling
*
* @author Susanne Moog <typo3@susanne-moog.de>
*/
class ArrayUtility {
/**
* Reduce an array by a search value and keep the array structure.
*
* Comparison is type strict:
* - For a given needle of type string, integer, array or boolean,
* value and value type must match to occur in result array
* - For a given object, a object within the array must be a reference to
* the same object to match (not just different instance of same class)
*
* Example:
* - Needle: 'findMe'
* - Given array:
* array(
* 'foo' => 'noMatch',
* 'bar' => 'findMe',
* 'foobar => array(
* 'foo' => 'findMe',
* ),
* );
* - Result:
* array(
* 'bar' => 'findMe',
* 'foobar' => array(
* 'foo' => findMe',
* ),
* );
*
* See the unit tests for more examples and expected behaviour
*
* @param mixed $needle The value to search for
* @param array $haystack The array in which to search
* @return array $haystack array reduced matching $needle values
*/
static public function filterByValueRecursive($needle = '', array $haystack = array()) {
$resultArray = array();
// Define a lambda function to be applied to all members of this array dimension
// Call recursive if current value is of type array
// Write to $resultArray (by reference!) if types and value match
$callback = function (&$value, $key) use($needle, &$resultArray) {
if ($value === $needle) {
($resultArray[$key] = $value);
} elseif (is_array($value)) {
($subArrayMatches = \TYPO3\CMS\Core\Utility\ArrayUtility::filterByValueRecursive($needle, $value));
if (count($subArrayMatches) > 0) {
($resultArray[$key] = $subArrayMatches);
}
}
};
// array_walk() is not affected by the internal pointers, no need to reset
array_walk($haystack, $callback);
// Pointers to result array are reset internally
return $resultArray;
}
/**
* Checks if a given path exists in array
*
* Example:
* - array:
* array(
* 'foo' => array(
* 'bar' = 'test',
* )
* );
* - path: 'foo/bar'
* - return: TRUE
*
* @param array $array Given array
* @param string $path Path to test, 'foo/bar/foobar'
* @param string $delimiter Delimeter for path, default /
* @return boolean TRUE if path exists in array
*/
static public function isValidPath(array $array, $path, $delimiter = '/') {
$isValid = TRUE;
try {
// Use late static binding to enable mocking of this call in unit tests
static::getValueByPath($array, $path, $delimiter);
} catch (\RuntimeException $e) {
$isValid = FALSE;
}
return $isValid;
}
/**
* Returns a value by given path
*
* Example
* - array:
* array(
* 'foo' => array(
* 'bar' => array(
* 'baz' => 42
* )
* )
* );
* - path: foo/bar/baz
* - return: 42
*
* If a path segments contains a delimiter character, the path segment
* must be enclosed by " (double quote), see unit tests for details
*
* @param array $array Input array
* @param string $path Path within the array
* @param string $delimiter Defined path delimiter, default /
* @return mixed
* @throws \RuntimeException
*/
static public function getValueByPath(array $array, $path, $delimiter = '/') {
if (empty($path)) {
throw new \RuntimeException('Path must not be empty', 1341397767);
}
// Extract parts of the path
$path = str_getcsv($path, $delimiter);
// Loop through each part and extract its value
$value = $array;
foreach ($path as $segment) {
if (array_key_exists($segment, $value)) {
// Replace current value with child
$value = $value[$segment];
} else {
// Fail if key does not exist
throw new \RuntimeException('Path does not exist in array', 1341397869);
}
}
return $value;
}
/**
* Modifies or sets a new value in an array by given path
*
* Example:
* - array:
* array(
* 'foo' => array(
* 'bar' => 42,
* ),
* );
* - path: foo/bar
* - value: 23
* - return:
* array(
* 'foo' => array(
* 'bar' => 23,
* ),
* );
*
* @param array $array Input array to manipulate
* @param string $path Path in array to search for
* @param mixed $value Value to set at path location in array
* @param string $delimiter Path delimiter
* @return array Modified array
* @throws \RuntimeException
*/
static public function setValueByPath(array $array, $path, $value, $delimiter = '/') {
if (empty($path)) {
throw new \RuntimeException('Path must not be empty', 1341406194);
}
if (!is_string($path)) {
throw new \RuntimeException('Path must be a string', 1341406402);
}
// Extract parts of the path
$path = str_getcsv($path, $delimiter);
// Point to the root of the array
$pointer = &$array;
// Find path in given array
foreach ($path as $segment) {
// Fail if the part is empty
if (empty($segment)) {
throw new \RuntimeException('Invalid path segment specified', 1341406846);
}
// Create cell if it doesn't exist
if (!array_key_exists($segment, $pointer)) {
$pointer[$segment] = array();
}
// Set pointer to new cell
$pointer = &$pointer[$segment];
}
// Set value of target cell
$pointer = $value;
return $array;
}
/**
* Remove a sub part from an array specified by path
*
* @param array $array Input array to manipulate
* @param string $path Path to remove from array
* @param string $delimiter Path delimiter
* @return array Modified array
* @throws \RuntimeException
*/
static public function removeByPath(array $array, $path, $delimiter = '/') {
if (empty($path)) {
throw new \RuntimeException('Path must not be empty', 1371757718);
}
if (!is_string($path)) {
throw new \RuntimeException('Path must be a string', 1371757719);
}
// Extract parts of the path
$path = str_getcsv($path, $delimiter);
$pathDepth = count($path);
$currentDepth = 0;
$pointer = &$array;
// Find path in given array
foreach ($path as $segment) {
$currentDepth++;
// Fail if the part is empty
if (empty($segment)) {
throw new \RuntimeException('Invalid path segment specified', 1371757720);
}
if (!array_key_exists($segment, $pointer)) {
throw new \RuntimeException('Path segment ' . $segment . ' does not exist in array', 1371758436);
}
if ($currentDepth === $pathDepth) {
unset($pointer[$segment]);
} else {
$pointer = &$pointer[$segment];
}
}
return $array;
}
/**
* Sorts an array recursively by key
*
* @param $array Array to sort recursively by key
* @return array Sorted array
*/
static public function sortByKeyRecursive(array $array) {
ksort($array);
foreach ($array as $key => $value) {
if (is_array($value) && !empty($value)) {
$array[$key] = self::sortByKeyRecursive($value);
}
}
return $array;
}
/**
* Sort an array of arrays by a given key using uasort
*
* @param array $arrays Array of arrays to sort
* @param string $key Key to sort after
* @param bool $ascending Set to TRUE for ascending order, FALSE for descending order
* @return array Array of sorted arrays
* @throws \RuntimeException
*/
static public function sortArraysByKey(array $arrays, $key, $ascending = TRUE) {
if (empty($arrays)) {
return $arrays;
}
// @ operator used: Some PHP versions like 5.4.4-14+deb7u8 (debian wheezy) are
// affected by PHP bug https://bugs.php.net/bug.php?id=50688 and trigger a warning.
// The code itself is ok and covered by unit tests, so the @ operator is used to
// suppress output of the PHP bug. This can be removed if the core does not
// support PHP version affected by this issue anymore.
$sortResult = @uasort($arrays, function (array $a, array $b) use ($key, $ascending) {
if (!isset($a[$key]) || !isset($b[$key])) {
throw new \RuntimeException('The specified sorting key "' . $key . '" is not available in the given array.', 1373727309);
}
return ($ascending) ? strcasecmp($a[$key], $b[$key]) : strcasecmp($b[$key], $a[$key]);
});
if (!$sortResult) {
throw new \RuntimeException('The function uasort() failed for unknown reasons.', 1373727329);
}
return $arrays;
}
/**
* Exports an array as string.
* Similar to var_export(), but representation follows the TYPO3 core CGL.
*
* See unit tests for detailed examples
*
* @param array $array Array to export
* @param integer $level Internal level used for recursion, do *not* set from outside!
* @return string String representation of array
* @throws \RuntimeException
*/
static public function arrayExport(array $array = array(), $level = 0) {
$lines = 'array(' . LF;
$level++;
$writeKeyIndex = FALSE;
$expectedKeyIndex = 0;
foreach ($array as $key => $value) {
if ($key === $expectedKeyIndex) {
$expectedKeyIndex++;
} else {
// Found a non integer or non consecutive key, so we can break here
$writeKeyIndex = TRUE;
break;
}
}
foreach ($array as $key => $value) {
// Indention
$lines .= str_repeat(TAB, $level);
if ($writeKeyIndex) {
// Numeric / string keys
$lines .= is_int($key) ? $key . ' => ' : '\'' . $key . '\' => ';
}
if (is_array($value)) {
if (count($value) > 0) {
$lines .= self::arrayExport($value, $level);
} else {
$lines .= 'array(),' . LF;
}
} elseif (is_int($value) || is_float($value)) {
$lines .= $value . ',' . LF;
} elseif (is_null($value)) {
$lines .= 'NULL' . ',' . LF;
} elseif (is_bool($value)) {
$lines .= $value ? 'TRUE' : 'FALSE';
$lines .= ',' . LF;
} elseif (is_string($value)) {
// Quote \ to \\
$stringContent = str_replace('\\', '\\\\', $value);
// Quote ' to \'
$stringContent = str_replace('\'', '\\\'', $stringContent);
$lines .= '\'' . $stringContent . '\'' . ',' . LF;
} else {
throw new \RuntimeException('Objects are not supported', 1342294987);
}
}
$lines .= str_repeat(TAB, ($level - 1)) . ')' . ($level - 1 == 0 ? '' : ',' . LF);
return $lines;
}
/**
* Converts a multidimensional array to a flat representation.
*
* See unit tests for more details
*
* Example:
* - array:
* array(
* 'first.' => array(
* 'second' => 1
* )
* )
* - result:
* array(
* 'first.second' => 1
* )
*
* Example:
* - array:
* array(
* 'first' => array(
* 'second' => 1
* )
* )
* - result:
* array(
* 'first.second' => 1
* )
*
* @param array $array The (relative) array to be converted
* @param string $prefix The (relative) prefix to be used (e.g. 'section.')
* @return array
*/
static public function flatten(array $array, $prefix = '') {
$flatArray = array();
foreach ($array as $key => $value) {
// Ensure there is no trailling dot:
$key = rtrim($key, '.');
if (!is_array($value)) {
$flatArray[$prefix . $key] = $value;
} else {
$flatArray = array_merge($flatArray, self::flatten($value, $prefix . $key . '.'));
}
}
return $flatArray;
}
/**
* Determine the intersections between two arrays, recursively comparing keys
* A complete sub array of $source will be preserved, if the key exists in $mask.
*
* See unit tests for more examples and edge cases.
*
* Example:
* - source:
* array(
* 'key1' => 'bar',
* 'key2' => array(
* 'subkey1' => 'sub1',
* 'subkey2' => 'sub2',
* ),
* 'key3' => 'baz',
* )
* - mask:
* array(
* 'key1' => NULL,
* 'key2' => array(
* 'subkey1' => exists',
* ),
* )
* - return:
* array(
* 'key1' => 'bar',
* 'key2' => array(
* 'subkey1' => 'sub1',
* ),
* )
*
* @param array $source Source array
* @param array $mask Array that has the keys which should be kept in the source array
* @return array Keys which are present in both arrays with values of the source array
*/
public static function intersectRecursive(array $source, array $mask = array()) {
$intersection = array();
foreach ($source as $key => $_) {
if (!array_key_exists($key, $mask)) {
continue;
}
if (is_array($source[$key]) && is_array($mask[$key])) {
$value = self::intersectRecursive($source[$key], $mask[$key]);
if (!empty($value)) {
$intersection[$key] = $value;
}
} else {
$intersection[$key] = $source[$key];
}
}
return $intersection;
}
/**
* Renumber the keys of an array to avoid leaps if keys are all numeric.
*
* Is called recursively for nested arrays.
*
* Example:
*
* Given
* array(0 => 'Zero' 1 => 'One', 2 => 'Two', 4 => 'Three')
* as input, it will return
* array(0 => 'Zero' 1 => 'One', 2 => 'Two', 3 => 'Three')
*
* Will treat keys string representations of number (ie. '1') equal to the
* numeric value (ie. 1).
*
* Example:
* Given
* array('0' => 'Zero', '1' => 'One' )
* it will return
* array(0 => 'Zero', 1 => 'One')
*
* @param array $array Input array
* @param integer $level Internal level used for recursion, do *not* set from outside!
* @return array
*/
static public function renumberKeysToAvoidLeapsIfKeysAreAllNumeric(array $array = array(), $level = 0) {
$level++;
$allKeysAreNumeric = TRUE;
foreach ($array as $key => $_) {
if (is_numeric($key) === FALSE) {
$allKeysAreNumeric = FALSE;
break;
}
}
$renumberedArray = $array;
if ($allKeysAreNumeric === TRUE) {
$renumberedArray = array_values($array);
}
foreach ($renumberedArray as $key => $value) {
if (is_array($value)) {
$renumberedArray[$key] = self::renumberKeysToAvoidLeapsIfKeysAreAllNumeric($value, $level);
}
}
return $renumberedArray;
}
/**
* Merges two arrays recursively and "binary safe" (integer keys are
* overridden as well), overruling similar values in the original array
* with the values of the overrule array.
* In case of identical keys, ie. keeping the values of the overrule array.
*
* This method takes the original array by reference for speed optimization with large arrays
*
* The differences to the existing PHP function array_merge_recursive() are:
* * Keys of the original array can be unset via the overrule array. ($enableUnsetFeature)
* * Much more control over what is actually merged. ($addKeys, $includeEmptyValues)
* * Elements or the original array get overwritten if the same key is present in the overrule array.
*
* @param array $original Original array. It will be *modified* by this method and contains the result afterwards!
* @param array $overrule Overrule array, overruling the original array
* @param boolean $addKeys If set to FALSE, keys that are NOT found in $original will not be set. Thus only existing value can/will be overruled from overrule array.
* @param boolean $includeEmptyValues If set, values from $overrule will overrule if they are empty or zero.
* @param boolean $enableUnsetFeature If set, special values "__UNSET" can be used in the overrule array in order to unset array keys in the original array.
* @return void
*/
static public function mergeRecursiveWithOverrule(array &$original, array $overrule, $addKeys = TRUE, $includeEmptyValues = TRUE, $enableUnsetFeature = TRUE) {
foreach ($overrule as $key => $_) {
if ($enableUnsetFeature && $overrule[$key] === '__UNSET') {
unset($original[$key]);
continue;
}
if (isset($original[$key]) && is_array($original[$key])) {
if (is_array($overrule[$key])) {
self::mergeRecursiveWithOverrule($original[$key], $overrule[$key], $addKeys, $includeEmptyValues, $enableUnsetFeature);
}
} elseif (
($addKeys || isset($original[$key])) &&
($includeEmptyValues || $overrule[$key])
) {
$original[$key] = $overrule[$key];
}
}
// This line is kept for backward compatibility reasons.
reset($original);
}
}
|
demonege/sutogo
|
typo3/sysext/core/Classes/Utility/ArrayUtility.php
|
PHP
|
gpl-2.0
| 16,326
|
<?php
/**
* @package AdminTools
* @copyright Copyright (c)2010-2011 Nicholas K. Dionysopoulos
* @license GNU General Public License version 3, or later
* @version $Id: seoandlink.php 178 2011-02-16 08:43:23Z nikosdion $
*/
// Protect from unauthorized access
defined('_JEXEC') or die();
jimport('joomla.application.component.model');
class AdmintoolsModelStorage extends JModel
{
/** @var JRegistry */
private $config = null;
public function __construct($config = array()) {
parent::__construct($config);
// Check for FOF
if(!defined('FOF_INCLUDED')) {
require_once JPATH_ADMINISTRATOR.'/components/com_admintools/fof/include.php';
}
}
public function getValue($key, $default = null)
{
if(is_null($this->config)) $this->load();
return $this->config->getValue($key, $default);
}
public function setValue($key, $value, $save = false)
{
if(is_null($this->config)) {
$this->load();
}
$x = $this->config->setValue($key, $value);
if($save) $this->save();
return $x;
}
public function load()
{
$db = JFactory::getDBO();
$query = FOFQueryAbstract::getNew($db)
->select($db->nameQuote('value'))
->from($db->nameQuote('#__admintools_storage'))
->where($db->nameQuote('key').' = '.$db->quote('cparams'));
$db->setQuery($query);
$res = $db->loadResult();
$this->config = new JRegistry('admintools');
if(!empty($res)) {
$res = json_decode($res, true);
$this->config->loadArray($res);
}
}
public function save()
{
if(is_null($this->config)) {
$this->load();
}
$db = JFactory::getDBO();
$data = $this->config->toArray();
$data = json_encode($data);
$query = FOFQueryAbstract::getNew($db)
->delete($db->nameQuote('#__admintools_storage'))
->where($db->nameQuote('key').' = '.$db->quote('cparams'));
$db->setQuery($query);
$db->query();
$object = (object)array(
'key' => 'cparams',
'value' => $data
);
$db->insertObject('#__admintools_storage', $object);
}
}
|
back1992/ticool15
|
administrator/components/com_admintools/models/storage.php
|
PHP
|
gpl-2.0
| 1,996
|
//
// DataBackupView.h
// PUER
//
// Created by admin on 14-9-12.
// Copyright (c) 2014年 com.dieshang.PUER. All rights reserved.
//
#import <UIKit/UIKit.h>
@class DataBackupView;
@protocol DataBackupViewDelegate <NSObject>
- (UIView *)overlayView:(DataBackupView *)view didHitTest:(CGPoint)point withEvent:(UIEvent *)event;
@end
@interface DataBackupView : UIView
@property (weak, nonatomic) id<DataBackupViewDelegate> delegate;
@end
|
daqiangge/PUER
|
PUER/ViewController/DataBackup/DataBackupView.h
|
C
|
gpl-2.0
| 450
|
/*
* OMAP3 MMC/SD/SDIO interface emulation
*
* Copyright (C) 2008 yajin <yajin@vm-kernel.org>
* Copyright (C) 2009 Nokia Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 or
* (at your option) version 3 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include "hw/hw.h"
#include "hw/arm/omap.h"
#include "hw/sd.h"
#include "hw/sysbus.h"
/* debug levels:
0 - no debug
1 - print non-fatal errors
2 - print out all commands in processing order
3 - dump all register accesses and buffer management */
#define MMC_DEBUG_LEVEL 0
#if MMC_DEBUG_LEVEL>0
#define TRACE(fmt,...) fprintf(stderr, "%s: " fmt "\n", \
__FUNCTION__, ##__VA_ARGS__)
#else
#define TRACE(...)
#endif
#if MMC_DEBUG_LEVEL>1
#define TRACE1(...) TRACE(__VA_ARGS__)
#else
#define TRACE1(...)
#endif
#if MMC_DEBUG_LEVEL>2
#define TRACE2(...) TRACE(__VA_ARGS__)
#else
#define TRACE2(...)
#endif
struct omap3_mmc_s
{
SysBusDevice busdev;
MemoryRegion iomem;
qemu_irq irq;
qemu_irq dma[2];
qemu_irq coverswitch;
omap_clk clk;
SDState *card;
uint32_t sysconfig;
uint32_t sysstatus;
uint32_t csre;
uint32_t systest;
uint32_t con;
uint32_t pwcnt;
uint32_t blk;
uint32_t arg;
uint32_t cmd;
uint32_t rsp10;
uint32_t rsp32;
uint32_t rsp54;
uint32_t rsp76;
uint32_t data;
uint32_t pstate;
uint32_t hctl;
uint32_t sysctl;
uint32_t stat;
uint32_t ie;
uint32_t ise;
uint32_t ac12;
uint32_t capa;
uint32_t cur_capa;
uint32_t rev;
uint16_t blen_counter;
uint16_t nblk_counter;
uint32_t fifo[256];
int fifo_start;
int fifo_len;
int ddir;
int transfer;
int stop;
};
/* Bit names for STAT/IC/IE registers */
#define STAT_CC (1 << 0)
#define STAT_TC (1 << 1)
#define STAT_BGE (1 << 2)
#define STAT_BWR (1 << 4)
#define STAT_BRR (1 << 5)
#define STAT_CIRQ (1 << 8)
#define STAT_OBI (1 << 9)
#define STAT_ERRI (1 << 15)
#define STAT_CTO (1 << 16)
#define STAT_CCRC (1 << 17)
#define STAT_CEB (1 << 18)
#define STAT_CIE (1 << 19)
#define STAT_DTO (1 << 20)
#define STAT_DCRC (1 << 21)
#define STAT_DEB (1 << 22)
#define STAT_ACE (1 << 24)
#define STAT_CERR (1 << 28)
#define STAT_BADA (1 << 29)
#define STAT_MASK \
(STAT_CC|STAT_TC|STAT_BGE| \
STAT_BWR|STAT_BRR| \
STAT_CIRQ|STAT_OBI| \
STAT_ERRI| \
STAT_CTO|STAT_CCRC|STAT_CEB|STAT_CIE| \
STAT_DTO|STAT_DCRC|STAT_DEB| \
STAT_ACE|STAT_CERR|STAT_BADA)
static void omap3_mmc_reset(DeviceState *dev)
{
struct omap3_mmc_s *s = FROM_SYSBUS(struct omap3_mmc_s,
SYS_BUS_DEVICE(dev));
s->sysconfig = 0x00000015;
s->sysstatus = 0;
s->csre = 0;
s->systest = 0;
s->con = 0x00000500;
s->pwcnt = 0;
s->blk = 0;
s->arg = 0;
s->cmd = 0;
s->rsp10 = 0;
s->rsp32 = 0;
s->rsp54 = 0;
s->rsp76 = 0;
s->data = 0;
s->pstate = 0x00040000;
s->hctl = 0;
s->sysctl = 0;
s->stat = 0;
s->ie = 0;
s->ise = 0;
s->ac12 = 0;
s->capa = 0x00e10080;
s->cur_capa = 0;
s->rev = 0x26000000;
s->blen_counter = 0;
s->nblk_counter = 0;
memset(s->fifo, 0, sizeof(s->fifo));
s->fifo_start = 0;
s->fifo_len = 0;
s->ddir = 0;
s->transfer = 0;
s->stop = 0;
if (s->card) {
sd_reset(s->card);
}
}
typedef enum
{
sd_nore = 0, /* no response */
sd_136_bits = 1, /* response length 136 bits */
sd_48_bits = 2, /* response length 48 bits */
sd_48b_bits = 3, /* response length 48 bits with busy after response */
} omap3_sd_rsp_type_t;
static void omap3_mmc_command(struct omap3_mmc_s *host);
static void omap3_mmc_interrupts_update(struct omap3_mmc_s *s)
{
qemu_set_irq(s->irq, !!(s->stat & s->ie & s->ise));
}
static void omap3_mmc_fifolevel_update(struct omap3_mmc_s *host)
{
enum { ongoing, ready, aborted } state = ongoing;
if ((host->cmd & (1 << 21))) { /* DP */
if (host->ddir) {
TRACE2("receive, dma=%d, fifo_len=%d bytes",
host->cmd & 1, host->fifo_len * 4);
/* omap3_mmc_transfer ensures we always have data in FIFO
during receive as long as all data has not been transferred -
NOTE that the actual transfer may be finished already (i.e.
host->transfer is cleared) but not all data has been read out
from FIFO yet */
if (host->fifo_len) {
if (host->cmd & 1) { /* DE */
if (host->fifo_len * 4 == (host->blk & 0x7ff)) { /* BLEN */
if (host->stop)
state = aborted;
else
qemu_irq_raise(host->dma[1]);
} else
qemu_irq_lower(host->dma[1]);
} else {
if (host->stop
&& host->fifo_len * 4 == (host->blk & 0x7ff))
state = aborted;
else {
host->pstate |= 0x0800; /* BRE */
host->stat |= STAT_BRR;
}
}
}
else
state = host->stop ? aborted : ready;
} else {
/* omap3_mmc_transfer keeps FIFO empty during transmit so
we just check all blocks have been transferred or not */
if (host->transfer) {
if (host->cmd & 1) { /* DE */
if (host->blen_counter == (host->blk & 0x7ff)) { /* BLEN */
if (host->stop)
state = aborted;
else
qemu_irq_raise(host->dma[0]);
} else
qemu_irq_lower(host->dma[0]);
} else {
if (host->stop
&& host->blen_counter == (host->blk & 0x7ff))
state = aborted;
else {
host->pstate |= 0x0400; /* BWE */
host->stat |= STAT_BWR;
}
}
} else
state = host->stop ? aborted : ready;
}
if ((host->cmd & 1) || state != ongoing) { /* DE */
host->pstate &= ~0x0c00; /* BRE | BWE */
host->stat &= ~(STAT_BRR | STAT_BWR);
if (state != ongoing) {
TRACE2("transfer %s",
state == ready
? "complete"
: "aborted --> complete");
host->stat |= STAT_TC;
if (host->cmd & 0x04) { /* ACEN */
host->stop = 0x0cc30000;
state = aborted;
}
if (state == aborted) {
host->cmd = host->stop;
host->stop = 0;
omap3_mmc_command(host);
}
}
}
}
}
static void omap3_mmc_transfer(struct omap3_mmc_s *host)
{
int i;
uint32_t x;
#if MMC_DEBUG_LEVEL>1
int j;
uint8_t c, sym[17];
#endif
/* IF data transfer is inactive
OR block count enabled with zero block count
OR in receive mode and we have unread data in FIFO
OR in transmit mode and we have no data in FIFO,
THEN don't do anything */
if (!host->transfer
|| ((host->cmd & 2) && !host->nblk_counter)
|| (host->ddir && host->fifo_len)
|| (!host->ddir && !host->fifo_len))
return;
if (host->ddir) {
TRACE2("begin, %d blocks (%d bytes/block) left to receive, %d bytes in FIFO",
(host->cmd & 2) ? host->nblk_counter : 1,
host->blk & 0x7ff,
host->fifo_len * 4);
while (host->blen_counter && host->fifo_len < 255) {
for (i = 0, x = 0; i < 32 && host->blen_counter; i += 8, host->blen_counter--)
x |= sd_read_data(host->card) << i;
host->fifo[(host->fifo_start + host->fifo_len) & 0xff] = x;
host->fifo_len++;
}
TRACE2("end, %d bytes in FIFO:", host->fifo_len * 4);
#if MMC_DEBUG_LEVEL>1
for (i = 0; i < host->fifo_len; ) {
fprintf(stderr, "%s: [0x%03x] ", __FUNCTION__, i * 4);
do {
x = host->fifo[(host->fifo_start + i) & 0xff];
for (j = 0; j < 4; j++) {
c = (x >> (j * 8)) & 0xff;
fprintf(stderr, "%02x ", c);
sym[(i & 3) * 4 + j] = (c < 32 || c > 126) ? '.' : c;
}
} while (((++i) & 3));
sym[16] = 0;
fprintf(stderr, "%s\n", sym);
}
#endif
} else {
TRACE2("%d bytes left to transmit in current block", host->blen_counter);
while (host->blen_counter && host->fifo_len) {
for (i = 0; i < 32 && host->blen_counter; i += 8, host->blen_counter--)
sd_write_data(host->card, (host->fifo[host->fifo_start] >> i) & 0xff);
host->fifo_start++;
host->fifo_len--;
host->fifo_start &= 0xff;
}
}
if (!host->blen_counter) {
if (host->cmd & 2) /* BCE */
host->nblk_counter--;
TRACE2("block done, %d blocks left",
(host->cmd & (1 << 5)) ? host->nblk_counter : 0);
host->blen_counter = host->blk & 0x7ff;
if (!(host->cmd & (1 << 5)) /* MSBS */
|| !host->nblk_counter) {
host->nblk_counter = (host->blk >> 16) & 0xffff;
host->transfer = 0;
host->pstate &= ~0x0306; /* RTA | WTA | DLA | DATI */
}
}
}
static void omap3_mmc_command(struct omap3_mmc_s *s)
{
uint32_t rspstatus, mask;
int rsplen, timeout;
SDRequest request;
uint8_t response[16];
int cmd = (s->cmd >> 24) & 0x3f; /* INDX */
int rsptype = (s->cmd >> 16) & 3;
int dp = s->cmd & (1 << 21);
TRACE1("%d type=%d rsp=%d arg=0x%08x blk=0x%08x, fifo=%d/%d",
cmd, (s->cmd >> 22) & 3, (s->cmd >> 16) & 3, s->arg,
s->blk, s->fifo_start, s->fifo_len);
if ((s->con & 2) && !cmd) { /* INIT and CMD0 */
s->stat |= STAT_CC;
s->pstate &= 0xfffffffe;
return;
}
if (dp) {
s->fifo_start = 0;
s->fifo_len = 0;
s->transfer = 1;
s->ddir = (s->cmd >> 4) & 1;
/* DLA | DATI | (RTA/WTA) */
s->pstate |= 0x6 | (s->ddir ? 0x200 : 0x100);
} else {
s->transfer = 0;
s->pstate &= ~0x306; /* RTA | WTA | DLA | DATI */
}
timeout = 0;
mask = 0;
rspstatus = 0;
request.cmd = cmd;
request.arg = s->arg;
request.crc = 0; /* FIXME */
rsplen = sd_do_command(s->card, &request, response);
switch (rsptype) {
case sd_nore:
rsplen = 0;
break;
case sd_136_bits:
if (rsplen < 16) {
timeout = 1;
break;
}
rsplen = 16;
s->rsp76 = (response[0] << 24) | (response[1] << 16) |
(response[2] << 8) | (response[3] << 0);
s->rsp54 = (response[4] << 24) | (response[5] << 16) |
(response[6] << 8) | (response[7] << 0);
s->rsp32 = (response[8] << 24) | (response[9] << 16) |
(response[10] << 8) | (response[11] << 0);
s->rsp10 = (response[12] << 24) | (response[13] << 16) |
(response[14] << 8) | (response[15] << 0);
break;
case sd_48_bits:
case sd_48b_bits:
if (rsplen < 4) {
timeout = 1;
break;
}
rsplen = 4;
s->rsp10 = (response[0] << 24) | (response[1] << 16) |
(response[2] << 8) | (response[3] << 0);
switch (cmd) {
case 41: /* r3 */
break;
case 3: /* r6 */
mask = 0xe00;
rspstatus = (response[2] << 8) | response[3];
break;
default:
if (cmd == 8 && !sd_is_mmc(s->card)) {
/* r7 */
break;
}
mask = OUT_OF_RANGE | ADDRESS_ERROR | BLOCK_LEN_ERROR |
ERASE_SEQ_ERROR | ERASE_PARAM | WP_VIOLATION |
LOCK_UNLOCK_FAILED | COM_CRC_ERROR | ILLEGAL_COMMAND |
CARD_ECC_FAILED | CC_ERROR | SD_ERROR |
CID_CSD_OVERWRITE | WP_ERASE_SKIP;
rspstatus = (response[0] << 24) | (response[1] << 16) |
(response[2] << 8) | (response[3] << 0);
break;
}
default:
break;
}
if (cmd == 12 || cmd == 52) { /* stop transfer commands */
/*s->fifo_start = 0;*/
/*s->fifo_len = 0;*/
s->transfer = 0;
s->pstate &= ~0x0f06; /* BRE | BWE | RTA | WTA | DLA | DATI */
s->stat &= ~(STAT_BRR | STAT_BWR);
s->stat |= STAT_TC;
qemu_irq_lower(s->dma[0]);
qemu_irq_lower(s->dma[1]);
}
if (rspstatus & mask & s->csre) {
s->stat |= STAT_CERR;
s->pstate &= ~0x306; /* RTA | WTA | DLA | DATI */
s->transfer = 0;
} else {
s->stat &= ~STAT_CERR;
/* If this is an R1b command with no data transfer and
* there wasn't an error, then we have effectively
* emulated the command as having a zero length "busy"
* response. Set TC to tell the driver the "busy" period
* is over.
*/
if (!timeout && !dp && rsptype == sd_48b_bits) {
s->stat |= STAT_TC;
}
}
s->stat |= timeout ? STAT_CTO : STAT_CC;
}
static uint32_t omap3_mmc_read(void *opaque, hwaddr addr)
{
struct omap3_mmc_s *s = (struct omap3_mmc_s *) opaque;
uint32_t i ;
switch (addr) {
case 0x10:
TRACE2("SYSCONFIG = %08x", s->sysconfig);
return s->sysconfig;
case 0x14:
TRACE2("SYSSTATUS = %08x", s->sysstatus | 0x1);
return s->sysstatus | 0x1; /*reset completed */
case 0x24:
TRACE2("CSRE = %08x", s->csre);
return s->csre;
case 0x28:
TRACE2("SYSTEST = %08x", s->systest);
return s->systest;
case 0x2c: /* MMCHS_CON */
TRACE2("CON = %08x", s->con);
return s->con;
case 0x30:
TRACE2("PWCNT = %08x", s->pwcnt);
return s->pwcnt;
case 0x104: /* MMCHS_BLK */
TRACE2("BLK = %08x", s->blk);
return s->blk;
case 0x108: /* MMCHS_ARG */
TRACE2("ARG = %08x", s->arg);
return s->arg;
case 0x10c:
TRACE2("CMD = %08x", s->cmd);
return s->cmd;
case 0x110:
TRACE2("RSP10 = %08x", s->rsp10);
return s->rsp10;
case 0x114:
TRACE2("RSP32 = %08x", s->rsp32);
return s->rsp32;
case 0x118:
TRACE2("RSP54 = %08x", s->rsp54);
return s->rsp54;
case 0x11c:
TRACE2("RSP76 = %08x", s->rsp76);
return s->rsp76;
case 0x120:
/* in PIO mode, access allowed only when BRE is set */
if (!(s->cmd & 1) && !(s->pstate & 0x0800)) {
s->stat |= STAT_BADA;
i = 0;
} else {
i = s->fifo[s->fifo_start];
s->fifo[s->fifo_start] = 0;
if (s->fifo_len == 0) {
TRACE("FIFO underrun");
return i;
}
s->fifo_start++;
s->fifo_len--;
s->fifo_start &= 255;
omap3_mmc_transfer(s);
omap3_mmc_fifolevel_update(s);
}
omap3_mmc_interrupts_update(s);
return i;
case 0x124: /* MMCHS_PSTATE */
TRACE2("PSTATE = %08x", s->pstate);
return s->pstate;
case 0x128:
TRACE2("HCTL = %08x", s->hctl);
return s->hctl;
case 0x12c: /* MMCHS_SYSCTL */
TRACE2("SYSCTL = %08x", s->sysctl);
return s->sysctl;
case 0x130: /* MMCHS_STAT */
if (s->stat & 0xffff0000)
s->stat |= STAT_ERRI;
else
s->stat &= ~STAT_ERRI;
TRACE2("STAT = %08x", s->stat);
return s->stat;
case 0x134:
TRACE2("IE = %08x", s->ie);
return s->ie;
case 0x138:
TRACE2("ISE = %08x", s->ise);
return s->ise;
case 0x13c:
TRACE2("AC12 = %08x", s->ac12);
return s->ac12;
case 0x140: /* MMCHS_CAPA */
TRACE2("CAPA = %08x", s->capa);
return s->capa;
case 0x148:
TRACE2("CUR_CAPA = %08x", s->cur_capa);
return s->cur_capa;
case 0x1fc:
TRACE2("REV = %08x", s->rev);
return s->rev;
default:
OMAP_BAD_REG(addr);
exit(-1);
return 0;
}
}
static void omap3_mmc_write(void *opaque, hwaddr addr,
uint32_t value)
{
struct omap3_mmc_s *s = (struct omap3_mmc_s *) opaque;
switch (addr) {
case 0x014:
case 0x110:
case 0x114:
case 0x118:
case 0x11c:
case 0x124:
case 0x13c:
case 0x1fc:
OMAP_RO_REG(addr);
break;
case 0x010:
TRACE2("SYSCONFIG = %08x", value);
if (value & 2)
omap3_mmc_reset(&s->busdev.qdev);
s->sysconfig = value & 0x31d;
break;
case 0x024:
TRACE2("CSRE = %08x", value);
s->csre = value;
break;
case 0x028:
TRACE2("SYSTEST = %08x", value);
s->systest = value;
break;
case 0x02c: /* MMCHS_CON */
TRACE2("CON = %08x", value);
if (value & 0x10) { /* MODE */
TRACE("SYSTEST mode is not supported");
}
if ((value & 0x20) && !sd_is_mmc(s->card)) { /* DW8 */
TRACE("8-bit data width is not supported for SD cards");
}
if (value & 0x1000) { /* CEATA */
TRACE("CE-ATA control mode not supported");
}
s->con = value & 0x1ffff;
break;
case 0x030:
TRACE2("PWCNT = %08x", value);
s->pwcnt = value;
break;
case 0x104: /* MMCHS_BLK */
TRACE2("BLK = %08x", value);
s->blk = value & 0xffff07ff;
s->blen_counter = value & 0x7ff;
s->nblk_counter = (value >> 16) & 0xffff;
break;
case 0x108: /* MMCHS_ARG */
TRACE2("ARG = %08x", value);
s->arg = value;
break;
case 0x10c: /* MMCHS_CMD */
TRACE2("CMD = %08x", value);
if (!s->card) {
s->stat |= STAT_CTO;
} else {
/* TODO: writing to bits 0-15 should have no effect during
an active data transfer */
if (s->transfer && !s->stop
&& (((value >> 24) & 0x3f) == 12
|| ((value >> 24) & 0x3f) == 52)) {
s->stop = value & 0x3ffb0037;
} else {
s->cmd = value & 0x3ffb0037;
omap3_mmc_command(s);
}
omap3_mmc_transfer(s);
omap3_mmc_fifolevel_update(s);
}
omap3_mmc_interrupts_update(s);
break;
case 0x120:
/* in PIO mode, access allowed only when BWE is set */
if (!(s->cmd & 1) && !(s->pstate & 0x0400)) {
s->stat |= STAT_BADA;
} else {
if (s->fifo_len == 256) {
TRACE("FIFO overrun");
break;
}
s->fifo[(s->fifo_start + s->fifo_len) & 255] = value;
s->fifo_len++;
omap3_mmc_transfer(s);
omap3_mmc_fifolevel_update(s);
}
omap3_mmc_interrupts_update(s);
break;
case 0x128: /* MMCHS_HCTL */
TRACE2("HCTL = %08x", value);
s->hctl = value & 0xf0f0f02;
if (s->hctl & (1 << 16)) { /* SBGR */
TRACE("Stop at block gap feature not implemented!");
}
break;
case 0x12c: /* MMCHS_SYSCTL */
TRACE2("SYSCTL = %08x", value);
if (value & 0x04000000) { /* SRD */
s->data = 0;
s->pstate &= ~0x00000f06; /* BRE, BWE, RTA, WTA, DLA, DATI */
s->hctl &= ~0x00030000; /* SGBR, CR */
s->stat &= ~(STAT_BRR|STAT_BWR|STAT_BGE);
s->fifo_start = 0;
s->fifo_len = 0;
}
if (value & 0x02000000) { /* SRC */
s->pstate &= ~0x00000001; /* CMDI */
}
if (value & 0x01000000) { /* SRA */
uint32_t capa = s->capa;
uint32_t cur_capa = s->cur_capa;
omap3_mmc_reset(&s->busdev.qdev);
s->capa = capa;
s->cur_capa = cur_capa;
}
value = (value & ~2) | ((value & 1) << 1); /* copy ICE directly to ICS */
s->sysctl = value & 0x000fffc7;
break;
case 0x130:
TRACE2("STAT = %08x", value);
/* STAT_CIRQ and STAT_ERRI are write-ignored */
value = value & (STAT_MASK & ~(STAT_CIRQ|STAT_ERRI));
s->stat &= ~value;
omap3_mmc_interrupts_update(s);
break;
case 0x134: /* MMCHS_IE */
TRACE2("IE = %08x", value);
if (!(s->con & 0x4000)) {
/* if CON:OBIE is clear, ignore write to OBI_ENABLE */
value = (value & ~STAT_OBI) | (s->ie & STAT_OBI);
}
s->ie = value & (STAT_MASK & ~STAT_ERRI);
if (!(s->ie & STAT_CIRQ)) {
s->stat &= ~STAT_CIRQ;
}
omap3_mmc_interrupts_update(s);
break;
case 0x138:
TRACE2("ISE = %08x", value);
s->ise = value & (STAT_MASK & ~STAT_ERRI);
omap3_mmc_interrupts_update(s);
break;
case 0x140: /* MMCHS_CAPA */
TRACE2("CAPA = %08x", value);
s->capa &= ~0x07000000;
s->capa |= value & 0x07000000;
break;
case 0x148:
TRACE2("CUR_CAPA = %08x", value);
s->cur_capa = value & 0xffffff;
break;
default:
OMAP_BAD_REG(addr);
exit(-1);
}
}
static const MemoryRegionOps omap3_mmc_ops = {
.old_mmio = {
.read = {
omap_badwidth_read32,
omap_badwidth_read32,
omap3_mmc_read,
},
.write = {
omap_badwidth_write32,
omap_badwidth_write32,
omap3_mmc_write,
},
},
.endianness = DEVICE_NATIVE_ENDIAN,
};
static int omap3_mmc_init(SysBusDevice *dev)
{
struct omap3_mmc_s *s = FROM_SYSBUS(struct omap3_mmc_s, dev);
sysbus_init_irq(dev, &s->irq);
sysbus_init_irq(dev, &s->dma[0]);
sysbus_init_irq(dev, &s->dma[1]);
memory_region_init_io(&s->iomem, &omap3_mmc_ops, s,
"omap3_mmc", 0x1000);
sysbus_init_mmio(dev, &s->iomem);
return 0;
}
static void omap3_mmc_class_init(ObjectClass *klass, void *data)
{
DeviceClass *dc = DEVICE_CLASS(klass);
SysBusDeviceClass *k = SYS_BUS_DEVICE_CLASS(klass);
k->init = omap3_mmc_init;
dc->reset = omap3_mmc_reset;
}
static TypeInfo omap3_mmc_info = {
.name = "omap3_mmc",
.parent = TYPE_SYS_BUS_DEVICE,
.instance_size = sizeof(struct omap3_mmc_s),
.class_init = omap3_mmc_class_init,
};
static void omap3_mmc_register_types(void)
{
type_register_static(&omap3_mmc_info);
}
void omap3_mmc_attach(DeviceState *dev, BlockDriverState *bs,
int is_spi, int is_mmc)
{
struct omap3_mmc_s *s = FROM_SYSBUS(struct omap3_mmc_s,
SYS_BUS_DEVICE(dev));
if (s->card) {
hw_error("%s: card already attached!", __FUNCTION__);
}
s->card = sd_init(bs, is_spi, is_mmc);
}
type_init(omap3_mmc_register_types)
|
flexiant/qemu-1.5.0-dfsg
|
hw/sd/omap3_mmc.c
|
C
|
gpl-2.0
| 25,630
|
# Attributes
# 0 Reset all attributes
# 1 Bright
# 2 Dim
# 4 Underscore
# 5 Blink
# 7 Reverse
# 8 Hidden
#
# Foreground Colours
# 30 Black
# 31 Red
# 32 Green
# 33 Yellow
# 34 Blue
# 35 Magenta
# 36 Cyan
# 37 White
#
# Background Colours
# 40 Black
# 41 Red
# 42 Green
# 43 Yellow
# 44 Blue
# 45 Magenta
# 46 Cyan
# 47 White
RED="\[\033[1;31m\]"
GREEN="\[\033[1;32m\]"
YELLOW="\[\033[1;33m\]"
DARK_GREEN="\[\033[2;32m\]"
DARK_YELLOW="\[\033[2;33m\]"
DARK_CYAN="\[\033[2;36m\]"
NO_COLOR="\[\033[0m\]"
#
# NOTE: dircolors is sensitive to the setting of the TERM environment variable
#
eval `dircolors --sh ~/.dircolors`
|
ptLong/linux-code-collections
|
bash/dot-startup.d/04-colors.sh
|
Shell
|
gpl-2.0
| 624
|
#!/bin/bash
################################################################################
#
# Stack library generator script for Altera Nios II
#
# Copyright (c) 2014, Bernecker+Rainer Industrie-Elektronik Ges.m.b.H. (B&R)
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in the
# documentation and/or other materials provided with the distribution.
# * Neither the name of the copyright holders nor the
# names of its contributors may be used to endorse or promote products
# derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
################################################################################
BSP_PATH=$1
CFLAGS="-Wall -Wextra -pedantic -std=c99"
if [ -z "${OPLK_BASE_DIR}" ];
then
# Find oplk root path
SCRIPTDIR=$(dirname $(readlink -f "${0}"))
OPLK_BASE_DIR=$(readlink -f "${SCRIPTDIR}/../..")
fi
# process arguments
DEBUG=
OUT_PATH=.
while [ $# -gt 0 ]
do
case "$1" in
--debug)
DEBUG=1
;;
--out)
shift
OUT_PATH=$1
;;
--help)
echo "$ stack.sh [BSP] [OPTIONS]"
echo "BSP ... Path to generated BSP (settings.bsp, public.mk, Makefile)"
echo "OPTIONS ... :"
echo " --debug ... Lib is generated with O0"
echo " --out ... Path to directory where Lib is generated to"
exit 1
;;
*)
;;
esac
shift
done
if [ -z "${BSP_PATH}" ];
then
echo "ERROR: No BSP path is given!"
fi
# Get path to sopcinfo
SOPCINFO_FILE=$(nios2-bsp-query-settings --settings ${BSP_PATH}/settings.bsp \
--cmd puts [get_sopcinfo_file] | grep sopcinfo)
if [ "$(expr substr $(uname -s) 1 6)" == "CYGWIN" ];
then
# In cygwin convert returned path to posix style
SOPCINFO_FILE=$(cygpath -u "${SOPCINFO_FILE}")
fi
if [ ! -f ${SOPCINFO_FILE} ];
then
echo "ERROR: SOPCINFO file not found!"
exit 1
fi
# Get path to board
HW_PATH=$(readlink -f "$(dirname ${SOPCINFO_FILE})/..")
if [ ! -d "${HW_PATH}" ];
then
echo "ERROR: Path to SOPCINFO file does not exist (${HW_PATH})!"
exit 1
fi
# Get path to common board directory
HW_COMMON_PATH=$(readlink -f "${HW_PATH}/../common")
if [ ! -d "${HW_COMMON_PATH}" ];
then
echo "ERROR: Path to common board directory does not exist (${HW_COMMON_PATH})!"
exit 1
fi
# Get bsp's cpu name
CPU_NAME=$(nios2-bsp-query-settings --settings ${BSP_PATH}/settings.bsp \
--cmd puts [get_cpu_name])
# Let's source the board.settings (null.settings before)
BOARD_SETTINGS_FILE=${HW_PATH}/board.settings
CFG_APP_CPU_NAME=
CFG_DRV_CPU_NAME=
CFG_OPENMAC=
CFG_HOSTINTERFACE=
CFG_NODE=
if [ -f ${BOARD_SETTINGS_FILE} ]; then
source ${BOARD_SETTINGS_FILE}
else
echo "ERROR: ${BOARD_SETTINGS_FILE} not found!"
exit 1
fi
# Let's find the stack library that fits best...
LIB_NAME=
LIB_SOURCES=
LIB_INCLUDES=
CFG_LIB_CFLAGS=
CFG_LIB_ARGS=
CFG_TCI_MEM_NAME=
if [ "${CPU_NAME}" == "${CFG_APP_CPU_NAME}" ]; then
# The bsp's cpu matches to the app part
CFG_TCI_MEM_NAME=${CFG_APP_TCI_MEM_NAME}
if [ "${CFG_NODE}" == "CN" ] && [ -n "${CFG_OPENMAC}" ]; then
LIB_NAME=oplkcn
LIB_SOURCES=${HW_COMMON_PATH}/drivers/openmac/omethlib_phycfg.c
elif [ "${CFG_NODE}" == "MN" ] && [ -n "${CFG_HOSTINTERFACE}" ]; then
LIB_NAME=oplkmnapp-hostif
LIB_SOURCES=
fi
elif [ "${CPU_NAME}" == "${CFG_DRV_CPU_NAME}" ]; then
# The bsp's cpu matches to the drv part
CFG_TCI_MEM_NAME=${CFG_DRV_TCI_MEM_NAME}
if [ "${CFG_NODE}" == "MN" ] && [ -n "${CFG_OPENMAC}" ] && [ -n "${CFG_HOSTINTERFACE}" ]; then
LIB_NAME=oplkmndrv-hostif
LIB_SOURCES=${HW_COMMON_PATH}/drivers/openmac/omethlib_phycfg.c
fi
else
echo "ERROR: Please specify CFG_XXX_CPU_NAME in board.settings!"
exit 1
fi
# Set TCI memory size
TCI_MEM_SIZE=$(nios2-bsp-query-settings --settings ${BSP_PATH}/settings.bsp \
--cmd puts [get_addr_span ${CFG_TCI_MEM_NAME}])
if [ -z "$TCI_MEM_SIZE" ]; then
TCI_MEM_SIZE=0
fi
# Let's source the stack library settings file
LIB_SETTINGS_FILE=${OPLK_BASE_DIR}/stack/build/altera-nios2/lib${LIB_NAME}/lib.settings
if [ -f ${LIB_SETTINGS_FILE} ]; then
source ${LIB_SETTINGS_FILE}
else
echo "ERROR: ${LIB_SETTINGS_FILE} not found!"
fi
LIB_SOURCES+=" ${CFG_LIB_SOURCES}"
LIB_INCLUDES+=" ${CFG_LIB_INCLUDES}"
if [ -n "${DEBUG}" ]; then
LIB_OPT_LEVEL=-O0
DEBUG_MODE=_DEBUG
else
LIB_OPT_LEVEL=${CFG_LIB_OPT_LEVEL}
DEBUG_MODE=NDEBUG
fi
OUT_PATH+=/lib${LIB_NAME}
LIB_GEN_ARGS="--lib-name ${LIB_NAME} --lib-dir ${OUT_PATH} \
--bsp-dir ${BSP_PATH} \
--src-files ${LIB_SOURCES} \
--set CFLAGS=${CFLAGS} ${CFG_LIB_CFLAGS} -D${DEBUG_MODE} -DCONFIG_${CFG_NODE} \
-DALT_TCIMEM_SIZE=${TCI_MEM_SIZE} \
--set LIB_CFLAGS_OPTIMIZATION=${LIB_OPT_LEVEL} \
${CFG_LIB_ARGS} \
"
for i in ${LIB_INCLUDES}
do
LIB_GEN_ARGS+="--inc-dir ${i} "
done
nios2-lib-generate-makefile ${LIB_GEN_ARGS}
exit $?
|
Kalycito-open-automation/openPOWERLINK_V2_old_25-06-2014
|
tools/altera-nios2/stack.sh
|
Shell
|
gpl-2.0
| 6,286
|
/* Definitions for Linux-based GNU systems with ELF format
Copyright (C) 1995, 1996, 1997, 1998, 1999, 2000, 2003, 2004
Free Software Foundation, Inc.
Contributed by Eric Youngdale.
Modified for stabs-in-ELF by H.J. Lu (hjl@lucon.org).
This file is part of GCC.
GCC is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
GCC 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 GCC; see the file COPYING. If not, write to
the Free Software Foundation, 59 Temple Place - Suite 330,
Boston, MA 02111-1307, USA. */
/* Don't assume anything about the header files. */
#define NO_IMPLICIT_EXTERN_C
#undef ASM_APP_ON
#define ASM_APP_ON "#APP\n"
#undef ASM_APP_OFF
#define ASM_APP_OFF "#NO_APP\n"
#undef MD_EXEC_PREFIX
#undef MD_STARTFILE_PREFIX
/* Provide a STARTFILE_SPEC appropriate for GNU/Linux. Here we add
the GNU/Linux magical crtbegin.o file (see crtstuff.c) which
provides part of the support for getting C++ file-scope static
object constructed before entering `main'. */
#undef STARTFILE_SPEC
#if defined HAVE_LD_PIE
#define STARTFILE_SPEC \
"%{!shared: %{pg|p|profile:gcrt1.o%s;pie:Scrt1.o%s;:crt1.o%s}} \
crti.o%s %{static:crtbeginT.o%s;shared|pie:crtbeginS.o%s;:crtbegin.o%s}"
#else
#define STARTFILE_SPEC \
"%{!shared: %{pg|p|profile:gcrt1.o%s;:crt1.o%s}} \
crti.o%s %{static:crtbeginT.o%s;shared|pie:crtbeginS.o%s;:crtbegin.o%s}"
#endif
/* Provide a ENDFILE_SPEC appropriate for GNU/Linux. Here we tack on
the GNU/Linux magical crtend.o file (see crtstuff.c) which
provides part of the support for getting C++ file-scope static
object constructed before entering `main', followed by a normal
GNU/Linux "finalizer" file, `crtn.o'. */
#undef ENDFILE_SPEC
#define ENDFILE_SPEC \
"%{shared|pie:crtendS.o%s;:crtend.o%s} crtn.o%s"
/* This is for -profile to use -lc_p instead of -lc. */
#ifndef CC1_SPEC
#define CC1_SPEC "%{profile:-p}"
#endif
/* The GNU C++ standard library requires that these macros be defined. */
#undef CPLUSPLUS_CPP_SPEC
#define CPLUSPLUS_CPP_SPEC "-D_GNU_SOURCE %(cpp)"
#undef LIB_SPEC
#define LIB_SPEC \
"%{pthread:-lpthread} \
%{shared:-lc} \
%{!shared:%{mieee-fp:-lieee} %{profile:-lc_p}%{!profile:-lc}}"
#define LINUX_TARGET_OS_CPP_BUILTINS() \
do { \
builtin_define ("__gnu_linux__"); \
builtin_define_std ("linux"); \
builtin_define_std ("unix"); \
builtin_assert ("system=linux"); \
builtin_assert ("system=unix"); \
builtin_assert ("system=posix"); \
} while (0)
#if defined(HAVE_LD_EH_FRAME_HDR)
#define LINK_EH_SPEC "%{!static:--eh-frame-hdr} "
#endif
/* Define this so we can compile MS code for use with WINE. */
#define HANDLE_PRAGMA_PACK_PUSH_POP
#define LINK_GCC_C_SEQUENCE_SPEC \
"%{static:--start-group} %G %L %{static:--end-group}%{!static:%G}"
/* Use --as-needed -lgcc_s for eh support. */
#ifdef HAVE_LD_AS_NEEDED
#define USE_LD_AS_NEEDED 1
#endif
/* Determine whether the the entire c99 runtime
is present in the runtime library. */
#define TARGET_C99_FUNCTIONS 1
#define TARGET_HAS_F_SETLKW
|
unofficial-opensource-apple/gcc_40
|
gcc/config/linux.h
|
C
|
gpl-2.0
| 3,476
|
/* Load firmware into Core B on a BF561
*
* Copyright 2004-2009 Analog Devices Inc.
* Licensed under the GPL-2 or later.
*/
/* The Core B reset func requires code in the application that is loaded into
* Core B. In order to reset, the application needs to install an interrupt
* handler for Supplemental Interrupt 0, that sets RETI to 0xff600000 and
* writes bit 11 of SICB_SYSCR when bit 5 of SICA_SYSCR is 0. This causes Core
* B to stall when Supplemental Interrupt 0 is set, and will reset PC to
* 0xff600000 when COREB_SRAM_INIT is cleared.
*/
#include <linux/device.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#define CMD_COREB_START _IO('b', 0)
#define CMD_COREB_STOP _IO('b', 1)
#define CMD_COREB_RESET _IO('b', 2)
static long
coreb_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int ret = 0;
switch (cmd) {
case CMD_COREB_START:
bfin_write_SYSCR(bfin_read_SYSCR() & ~0x0020);
break;
case CMD_COREB_STOP:
bfin_write_SYSCR(bfin_read_SYSCR() | 0x0020);
bfin_write_SICB_SYSCR(bfin_read_SICB_SYSCR() | 0x0080);
break;
case CMD_COREB_RESET:
bfin_write_SICB_SYSCR(bfin_read_SICB_SYSCR() | 0x0080);
break;
default:
ret = -EINVAL;
break;
}
CSYNC();
return ret;
}
static const struct file_operations coreb_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = coreb_ioctl,
.llseek = noop_llseek,
};
static struct miscdevice coreb_dev = {
.minor = MISC_DYNAMIC_MINOR,
.name = "coreb",
.fops = &coreb_fops,
};
static int __init bf561_coreb_init(void)
{
return misc_register(&coreb_dev);
}
module_init(bf561_coreb_init);
static void __exit bf561_coreb_exit(void)
{
misc_deregister(&coreb_dev);
}
module_exit(bf561_coreb_exit);
MODULE_AUTHOR("Bas Vermeulen <bvermeul@blackstar.xs4all.nl>");
MODULE_DESCRIPTION("BF561 Core B Support");
MODULE_LICENSE("GPL");
|
jeffegg/beaglebone
|
arch/blackfin/mach-bf561/coreb.c
|
C
|
gpl-2.0
| 1,979
|
/***************************************************************************
qgswkbtypes.h
-----------------------
begin : January 2015
copyright : (C) 2015 by Marco Hugentobler
email : marco at sourcepole dot ch
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#ifndef QGSWKBTYPES_H
#define QGSWKBTYPES_H
#include <QMap>
#include <QString>
/***************************************************************************
* This class is considered CRITICAL and any change MUST be accompanied with
* full unit tests in testqgsstatisticalsummary.cpp.
* See details in QEP #17
****************************************************************************/
/** \ingroup core
* \class QgsWkbTypes
* \brief Handles storage of information regarding WKB types and their properties.
* \note Added in version 2.10
*/
class CORE_EXPORT QgsWkbTypes
{
public:
enum Type
{
Unknown = 0,
Point = 1,
LineString = 2,
Polygon = 3,
MultiPoint = 4,
MultiLineString = 5,
MultiPolygon = 6,
GeometryCollection = 7,
CircularString = 8,
CompoundCurve = 9,
CurvePolygon = 10, //13, //should be 10. Seems to be correct in newer postgis versions
MultiCurve = 11,
MultiSurface = 12,
NoGeometry = 100, //attributes only
PointZ = 1001,
LineStringZ = 1002,
PolygonZ = 1003,
MultiPointZ = 1004,
MultiLineStringZ = 1005,
MultiPolygonZ = 1006,
GeometryCollectionZ = 1007,
CircularStringZ = 1008,
CompoundCurveZ = 1009,
CurvePolygonZ = 1010,
MultiCurveZ = 1011,
MultiSurfaceZ = 1012,
PointM = 2001,
LineStringM = 2002,
PolygonM = 2003,
MultiPointM = 2004,
MultiLineStringM = 2005,
MultiPolygonM = 2006,
GeometryCollectionM = 2007,
CircularStringM = 2008,
CompoundCurveM = 2009,
CurvePolygonM = 2010,
MultiCurveM = 2011,
MultiSurfaceM = 2012,
PointZM = 3001,
LineStringZM = 3002,
PolygonZM = 3003,
MultiPointZM = 3004,
MultiLineStringZM = 3005,
MultiPolygonZM = 3006,
GeometryCollectionZM = 3007,
CircularStringZM = 3008,
CompoundCurveZM = 3009,
CurvePolygonZM = 3010,
MultiCurveZM = 3011,
MultiSurfaceZM = 3012,
Point25D = 0x80000001,
LineString25D,
Polygon25D,
MultiPoint25D,
MultiLineString25D,
MultiPolygon25D
};
enum GeometryType
{
PointGeometry,
LineGeometry,
PolygonGeometry,
UnknownGeometry,
NullGeometry
};
/** Returns the single type for a WKB type. Eg, for MultiPolygon WKB types the single type would be Polygon.
* @see isSingleType()
* @see multiType()
* @see flatType()
*/
static Type singleType( Type type )
{
switch ( type )
{
case Unknown:
case GeometryCollection:
case GeometryCollectionZ:
case GeometryCollectionM:
case GeometryCollectionZM:
return Unknown;
case Point:
case MultiPoint:
return Point;
case PointZ:
case MultiPointZ:
return PointZ;
case PointM:
case MultiPointM:
return PointM;
case PointZM:
case MultiPointZM:
return PointZM;
case LineString:
case MultiLineString:
return LineString;
case LineStringZ:
case MultiLineStringZ:
return LineStringZ;
case LineStringM:
case MultiLineStringM:
return LineStringM;
case LineStringZM:
case MultiLineStringZM:
return LineStringZM;
case Polygon:
case MultiPolygon:
return Polygon;
case PolygonZ:
case MultiPolygonZ:
return PolygonZ;
case PolygonM:
case MultiPolygonM:
return PolygonM;
case PolygonZM:
case MultiPolygonZM:
return PolygonZM;
case CircularString:
return CircularString;
case CircularStringZ:
return CircularStringZ;
case CircularStringM:
return CircularStringM;
case CircularStringZM:
return CircularStringZM;
case CompoundCurve:
case MultiCurve:
return CompoundCurve;
case CompoundCurveZ:
case MultiCurveZ:
return CompoundCurveZ;
case CompoundCurveM:
case MultiCurveM:
return CompoundCurveM;
case CompoundCurveZM:
case MultiCurveZM:
return CompoundCurveZM;
case CurvePolygon:
case MultiSurface:
return CurvePolygon;
case CurvePolygonZ:
case MultiSurfaceZ:
return CurvePolygonZ;
case CurvePolygonM:
case MultiSurfaceM:
return CurvePolygonM;
case CurvePolygonZM:
case MultiSurfaceZM:
return CurvePolygonZM;
case NoGeometry:
return NoGeometry;
case Point25D:
case MultiPoint25D:
return Point25D;
case LineString25D:
case MultiLineString25D:
return LineString25D;
case Polygon25D:
case MultiPolygon25D:
return Polygon25D;
}
return Unknown;
}
/** Returns the multi type for a WKB type. Eg, for Polygon WKB types the multi type would be MultiPolygon.
* @see isMultiType()
* @see singleType()
* @see flatType()
*/
static Type multiType( Type type )
{
switch ( type )
{
case Unknown:
return Unknown;
case GeometryCollection:
return GeometryCollection;
case GeometryCollectionZ:
return GeometryCollectionZ;
case GeometryCollectionM:
return GeometryCollectionM;
case GeometryCollectionZM:
return GeometryCollectionZM;
case Point:
case MultiPoint:
return MultiPoint;
case PointZ:
case MultiPointZ:
return MultiPointZ;
case PointM:
case MultiPointM:
return MultiPointM;
case PointZM:
case MultiPointZM:
return MultiPointZM;
case LineString:
case MultiLineString:
return MultiLineString;
case LineStringZ:
case MultiLineStringZ:
return MultiLineStringZ;
case LineStringM:
case MultiLineStringM:
return MultiLineStringM;
case LineStringZM:
case MultiLineStringZM:
return MultiLineStringZM;
case Polygon:
case MultiPolygon:
return MultiPolygon;
case PolygonZ:
case MultiPolygonZ:
return MultiPolygonZ;
case PolygonM:
case MultiPolygonM:
return MultiPolygonM;
case PolygonZM:
case MultiPolygonZM:
return MultiPolygonZM;
case CompoundCurve:
case CircularString:
case MultiCurve:
return MultiCurve;
case CompoundCurveZ:
case CircularStringZ:
case MultiCurveZ:
return MultiCurveZ;
case CompoundCurveM:
case CircularStringM:
case MultiCurveM:
return MultiCurveM;
case CompoundCurveZM:
case CircularStringZM:
case MultiCurveZM:
return MultiCurveZM;
case CurvePolygon:
case MultiSurface:
return MultiSurface;
case CurvePolygonZ:
case MultiSurfaceZ:
return MultiSurfaceZ;
case CurvePolygonM:
case MultiSurfaceM:
return MultiSurfaceM;
case CurvePolygonZM:
case MultiSurfaceZM:
return MultiSurfaceZM;
case NoGeometry:
return NoGeometry;
case Point25D:
case MultiPoint25D:
return MultiPoint25D;
case LineString25D:
case MultiLineString25D:
return MultiLineString25D;
case Polygon25D:
case MultiPolygon25D:
return MultiPolygon25D;
}
return Unknown;
}
/** Returns the flat type for a WKB type. This is the WKB type minus any Z or M dimensions.
* Eg, for PolygonZM WKB types the single type would be Polygon.
* @see singleType()
* @see multiType()
*/
static Type flatType( Type type )
{
switch ( type )
{
case Unknown:
return Unknown;
case Point:
case PointZ:
case PointM:
case PointZM:
case Point25D:
return Point;
case LineString:
case LineStringZ:
case LineStringM:
case LineStringZM:
case LineString25D:
return LineString;
case Polygon:
case PolygonZ:
case PolygonM:
case PolygonZM:
case Polygon25D:
return Polygon;
case MultiPoint:
case MultiPointZ:
case MultiPointM:
case MultiPointZM:
case MultiPoint25D:
return MultiPoint;
case MultiLineString:
case MultiLineStringZ:
case MultiLineStringM:
case MultiLineStringZM:
case MultiLineString25D:
return MultiLineString;
case MultiPolygon:
case MultiPolygonZ:
case MultiPolygonM:
case MultiPolygonZM:
case MultiPolygon25D:
return MultiPolygon;
case GeometryCollection:
case GeometryCollectionZ:
case GeometryCollectionM:
case GeometryCollectionZM:
return GeometryCollection;
case CircularString:
case CircularStringZ:
case CircularStringM:
case CircularStringZM:
return CircularString;
case CompoundCurve:
case CompoundCurveZ:
case CompoundCurveM:
case CompoundCurveZM:
return CompoundCurve;
case MultiCurve:
case MultiCurveZ:
case MultiCurveM:
case MultiCurveZM:
return MultiCurve;
case CurvePolygon:
case CurvePolygonZ:
case CurvePolygonM:
case CurvePolygonZM:
return CurvePolygon;
case MultiSurface:
case MultiSurfaceZ:
case MultiSurfaceM:
case MultiSurfaceZM:
return MultiSurface;
case NoGeometry:
return NoGeometry;
}
return Unknown;
}
//! Returns the modified input geometry type according to hasZ / hasM
static Type zmType( Type type, bool hasZ, bool hasM )
{
type = flatType( type );
if ( hasZ )
type = static_cast<QgsWkbTypes::Type>( static_cast<quint32>( type ) + 1000 );
if ( hasM )
type = static_cast<QgsWkbTypes::Type>( static_cast<quint32>( type ) + 2000 );
return type;
}
/** Attempts to extract the WKB type from a WKT string.
* @param wktStr a valid WKT string
*/
static Type parseType( const QString& wktStr );
/** Returns true if the WKB type is a single type.
* @see isMultiType()
* @see singleType()
*/
static bool isSingleType( Type type )
{
return ( type != Unknown && !isMultiType( type ) );
}
/** Returns true if the WKB type is a multi type.
* @see isSingleType()
* @see multiType()
*/
static bool isMultiType( Type type )
{
switch ( type )
{
case Unknown:
case Point:
case LineString:
case Polygon:
case CircularString:
case CompoundCurve:
case CurvePolygon:
case NoGeometry:
case PointZ:
case LineStringZ:
case PolygonZ:
case CircularStringZ:
case CompoundCurveZ:
case CurvePolygonZ:
case PointM:
case LineStringM:
case PolygonM:
case CircularStringM:
case CompoundCurveM:
case CurvePolygonM:
case PointZM:
case LineStringZM:
case PolygonZM:
case CircularStringZM:
case CompoundCurveZM:
case CurvePolygonZM:
case Point25D:
case LineString25D:
case Polygon25D:
return false;
default:
return true;
}
}
/** Returns true if the WKB type is a curved type or can contain curved geometries.
* @note added in QGIS 2.14
*/
static bool isCurvedType( Type type )
{
switch ( flatType( type ) )
{
case CircularString:
case CompoundCurve:
case CurvePolygon:
case MultiCurve:
case MultiSurface:
return true;
default:
return false;
}
}
/** Returns the inherent dimension of the geometry type as an integer. Returned value will
* always be less than or equal to the coordinate dimension.
* @returns 0 for point geometries, 1 for line geometries, 2 for polygon geometries
* Invalid geometry types will return a dimension of 0.
* @see coordDimensions()
*/
static int wkbDimensions( Type type )
{
GeometryType gtype = geometryType( type );
switch ( gtype )
{
case LineGeometry:
return 1;
case PolygonGeometry:
return 2;
default: //point, no geometry, unknown geometry
return 0;
}
}
/** Returns the coordinate dimension of the geometry type as an integer. Returned value will
* be between 2-4, depending on whether the geometry type contains the Z or M dimensions.
* Invalid geometry types will return a dimension of 0.
* @note added in QGIS 2.14
* @see wkbDimensions()
*/
static int coordDimensions( Type type )
{
if ( type == Unknown || type == NoGeometry )
return 0;
return 2 + hasZ( type ) + hasM( type );
}
/** Returns the geometry type for a WKB type, eg both MultiPolygon and CurvePolygon would have a
* PolygonGeometry geometry type.
*/
static GeometryType geometryType( Type type )
{
switch ( type )
{
case Unknown:
case GeometryCollection:
case GeometryCollectionZ:
case GeometryCollectionM:
case GeometryCollectionZM:
return UnknownGeometry;
case Point:
case MultiPoint:
case PointZ:
case MultiPointZ:
case PointM:
case MultiPointM:
case PointZM:
case MultiPointZM:
case Point25D:
case MultiPoint25D:
return PointGeometry;
case LineString:
case MultiLineString:
case LineStringZ:
case MultiLineStringZ:
case LineStringM:
case MultiLineStringM:
case LineStringZM:
case MultiLineStringZM:
case LineString25D:
case MultiLineString25D:
case CircularString:
case CompoundCurve:
case MultiCurve:
case CircularStringZ:
case CompoundCurveZ:
case MultiCurveZ:
case CircularStringM:
case CompoundCurveM:
case MultiCurveM:
case CircularStringZM:
case CompoundCurveZM:
case MultiCurveZM:
return LineGeometry;
case Polygon:
case MultiPolygon:
case PolygonZ:
case MultiPolygonZ:
case PolygonM:
case MultiPolygonM:
case PolygonZM:
case MultiPolygonZM:
case Polygon25D:
case MultiPolygon25D:
case CurvePolygon:
case MultiSurface:
case CurvePolygonZ:
case MultiSurfaceZ:
case CurvePolygonM:
case MultiSurfaceM:
case CurvePolygonZM:
case MultiSurfaceZM:
return PolygonGeometry;
case NoGeometry:
return NullGeometry;
}
return UnknownGeometry;
}
/** Returns a display string type for a WKB type, eg the geometry name used in WKT geometry representations.
*/
static QString displayString( Type type );
/**
* Return a display string for a geometry type.
*
* This will return one of the following strings:
*
* - Point
* - Line
* - Polygon
* - Unknown Geometry
* - No Geometry
* - Invalid Geometry
*
* @note added in QGIS 3.0
*/
static QString geometryDisplayString( GeometryType type );
/** Tests whether a WKB type contains the z-dimension.
* @returns true if type has z values
* @see addZ()
* @see hasM()
*/
static bool hasZ( Type type )
{
switch ( type )
{
case PointZ:
case LineStringZ:
case PolygonZ:
case MultiPointZ:
case MultiLineStringZ:
case MultiPolygonZ:
case GeometryCollectionZ:
case CircularStringZ:
case CompoundCurveZ:
case CurvePolygonZ:
case MultiCurveZ:
case MultiSurfaceZ:
case PointZM:
case LineStringZM:
case PolygonZM:
case MultiPointZM:
case MultiLineStringZM:
case MultiPolygonZM:
case GeometryCollectionZM:
case CircularStringZM:
case CompoundCurveZM:
case CurvePolygonZM:
case MultiCurveZM:
case MultiSurfaceZM:
case Point25D:
case LineString25D:
case Polygon25D:
case MultiPoint25D:
case MultiLineString25D:
case MultiPolygon25D:
return true;
default:
return false;
}
}
/** Tests whether a WKB type contains m values.
* @returns true if type has m values
* @see addM()
* @see hasZ()
*/
static bool hasM( Type type )
{
switch ( type )
{
case PointM:
case LineStringM:
case PolygonM:
case MultiPointM:
case MultiLineStringM:
case MultiPolygonM:
case GeometryCollectionM:
case CircularStringM:
case CompoundCurveM:
case CurvePolygonM:
case MultiCurveM:
case MultiSurfaceM:
case PointZM:
case LineStringZM:
case PolygonZM:
case MultiPointZM:
case MultiLineStringZM:
case MultiPolygonZM:
case GeometryCollectionZM:
case CircularStringZM:
case CompoundCurveZM:
case CurvePolygonZM:
case MultiCurveZM:
case MultiSurfaceZM:
return true;
default:
return false;
}
}
/** Adds the z dimension to a WKB type and returns the new type
* @param type original type
* @note added in QGIS 2.12
* @see addM()
* @see dropZ()
* @see hasZ()
*/
static Type addZ( Type type )
{
if ( hasZ( type ) )
return type;
else if ( type == Unknown )
return Unknown;
else if ( type == NoGeometry )
return NoGeometry;
//upgrade with z dimension
Type flat = flatType( type );
if ( hasM( type ) )
return static_cast< QgsWkbTypes::Type >( flat + 3000 );
else
return static_cast< QgsWkbTypes::Type >( flat + 1000 );
}
/** Adds the m dimension to a WKB type and returns the new type
* @param type original type
* @note added in QGIS 2.12
* @see addZ()
* @see dropM()
* @see hasM()
*/
static Type addM( Type type )
{
if ( hasM( type ) )
return type;
else if ( type == Unknown )
return Unknown;
else if ( type == NoGeometry )
return NoGeometry;
else if ( type == Point25D ||
type == LineString25D ||
type == Polygon25D ||
type == MultiPoint25D ||
type == MultiLineString25D ||
type == MultiPolygon25D )
return type; //can't add M dimension to these types
//upgrade with m dimension
Type flat = flatType( type );
if ( hasZ( type ) )
return static_cast< QgsWkbTypes::Type >( flat + 3000 );
else
return static_cast< QgsWkbTypes::Type >( flat + 2000 );
}
/** Drops the z dimension (if present) for a WKB type and returns the new type.
* @param type original type
* @note added in QGIS 2.14
* @see dropM()
* @see addZ()
*/
static Type dropZ( Type type )
{
if ( !hasZ( type ) )
return type;
QgsWkbTypes::Type returnType = flatType( type );
if ( hasM( type ) )
returnType = addM( returnType );
return returnType;
}
/** Drops the m dimension (if present) for a WKB type and returns the new type.
* @param type original type
* @note added in QGIS 2.14
* @see dropZ()
* @see addM()
*/
static Type dropM( Type type )
{
if ( !hasM( type ) )
return type;
QgsWkbTypes::Type returnType = flatType( type );
if ( hasZ( type ) )
returnType = addZ( returnType );
return returnType;
}
/**
* Will convert the 25D version of the flat type if supported or Unknown if not supported.
* @param type The type to convert
* @return the 25D version of the type or Unknown
*/
static Type to25D( Type type )
{
QgsWkbTypes::Type flat = flatType( type );
if ( flat >= Point && flat <= MultiPolygon )
return static_cast< QgsWkbTypes::Type >( flat + 0x80000000 );
else if ( type == QgsWkbTypes::NoGeometry )
return QgsWkbTypes::NoGeometry;
else
return Unknown;
}
private:
struct wkbEntry
{
wkbEntry( const QString& name, bool isMultiType, Type multiType, Type singleType, Type flatType, GeometryType geometryType,
bool hasZ, bool hasM )
: mName( name )
, mIsMultiType( isMultiType )
, mMultiType( multiType )
, mSingleType( singleType )
, mFlatType( flatType )
, mGeometryType( geometryType )
, mHasZ( hasZ )
, mHasM( hasM )
{}
QString mName;
bool mIsMultiType;
Type mMultiType;
Type mSingleType;
Type mFlatType;
GeometryType mGeometryType;
bool mHasZ;
bool mHasM;
};
static QMap<Type, wkbEntry> registerTypes();
static QMap<Type, wkbEntry>* entries();
};
#endif // QGSWKBTYPES_H
|
wonder-sk/QGIS
|
src/core/geometry/qgswkbtypes.h
|
C
|
gpl-2.0
| 23,021
|
/*lint --e{537} */
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/platform_device.h>
#include <linux/io.h>
#include <linux/err.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <hi_dsp.h>
#include <hi_onoff.h>
#include <ptable_com.h>
#include <bsp_om.h>
#include <bsp_dsp.h>
#include <bsp_ipc.h>
#include <bsp_icc.h>
#include <bsp_sec.h>
#include <bsp_sram.h>
#include <bsp_nandc.h>
#include <bsp_shared_ddr.h>
#include <drv_mailbox.h>
#include <drv_nv_id.h>
#include <drv_nv_def.h>
#include <bsp_nvim.h>
#include <product_config.h>
#ifdef __cplusplus
extern "C" {
#endif
int bsp_dsp_is_hifi_exist(void)
{
int ret = 0;
DRV_MODULE_SUPPORT_STRU stSupportNv = {0};
ret = (int)bsp_nvm_read(NV_ID_DRV_MODULE_SUPPORT, (u8*)&stSupportNv, sizeof(DRV_MODULE_SUPPORT_STRU));
if (ret)
ret = 0;
else
ret = (int)stSupportNv.hifi;
return ret;
}
#ifdef CONFIG_HIFI
static void bsp_hifi_init_share_memory(struct drv_hifi_sec_load_info *section_info)
{
writel(HIFI_MEM_BEGIN_CHECK32_DATA, (u32)section_info);
writel(HIFI_MEM_BEGIN_CHECK32_DATA, (u32)section_info + HIFI_SHARE_MEMORY_SIZE - sizeof(u32));
}
static int bsp_hifi_check_sections(struct drv_hifi_image_head *img_head,
struct drv_hifi_image_sec *img_sec)
{
if ((img_sec->sn >= img_head->sections_num)
|| (img_sec->src_offset + img_sec->size > img_head->image_size)
|| (img_sec->type >= (unsigned char)DRV_HIFI_IMAGE_SEC_TYPE_BUTT)
|| (img_sec->load_attib >= (unsigned char)DRV_HIFI_IMAGE_SEC_LOAD_BUTT)) {
return -1;
}
return 0;
}
int bsp_hifi_load_sections(void *hifi_image)
{
int ret = 0;
u32 i = 0, dynamic_section_num = 0, dynamic_section_data_offset = 0;
void *section_virtual_addr = NULL;
struct drv_hifi_sec_load_info *section_info = NULL;
struct drv_hifi_image_head *hifi_head = (struct drv_hifi_image_head *)hifi_image;
section_info = (struct drv_hifi_sec_load_info *)HIFI_SHARE_MEMORY_ADDR;
bsp_hifi_init_share_memory(section_info);
for (i = 0; i < hifi_head->sections_num; i++)
{
if (bsp_hifi_check_sections(hifi_head, &(hifi_head->sections[i])))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "error hifi image section, index: %d\r\n", i);
ret = -1;
goto err_unmap;
}
if (DRV_HIFI_IMAGE_SEC_LOAD_STATIC == hifi_head->sections[i].load_attib)
{
/* ¾²Ì¬¼ÓÔØ */
if ((hifi_head->sections[i].des_addr < DDR_HIFI_ADDR) ||
((hifi_head->sections[i].des_addr + hifi_head->sections[i].size) > (DDR_HIFI_ADDR + DDR_HIFI_SIZE)))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP,
"error hifi address, %x \r\n", hifi_head->sections[i].des_addr);
return -1;
}
/* Ö¸Ïò¾µÏñ´æ·ÅµÄddr µØÖ· */
section_virtual_addr = (void*)ioremap_nocache(hifi_head->sections[i].des_addr,
hifi_head->sections[i].size);
if (NULL == section_virtual_addr)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to io remap, %d \r\n", __LINE__);
return -ENOMEM;
}
/* ¾µÏñ¿½±´(Ô´-> Ä¿µÄ) */
memcpy(section_virtual_addr,
(void*)((char*)hifi_head + hifi_head->sections[i].src_offset),
hifi_head->sections[i].size);
iounmap(section_virtual_addr);
}
else if (DRV_HIFI_IMAGE_SEC_LOAD_DYNAMIC == hifi_head->sections[i].load_attib)
{
/* ¶¯Ì¬¼ÓÔØ */
if (dynamic_section_data_offset + hifi_head->sections[i].size > HIFI_SEC_DATA_LENGTH)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP,
"hifi dynamic section too large\r\n");
return -1;
}
/* copy data to share addr */
/* ½«¾µÏñ¿½±´µ½¶ÎÐÅÏ¢½á¹¹Ì壬¹©ÆäËû»úÖÆ¼ÓÔØ */
memcpy((void*)&(section_info->sec_data[dynamic_section_data_offset]),
(void*)((char*)hifi_head + hifi_head->sections[i].src_offset),
hifi_head->sections[i].size);
/* update section info */
/* ¸üжεØÖ· */
section_info->sec_addr_info[dynamic_section_num].sec_source_addr
= SHD_DDR_V2P((u32)&(section_info->sec_data[dynamic_section_data_offset]));
/* ¸üÐ¶γ¤¶È */
section_info->sec_addr_info[dynamic_section_num].sec_length
= hifi_head->sections[i].size;
/* ¸üжÎÄ¿µÄµØÖ· £¬DDR µØÖ·*/
section_info->sec_addr_info[dynamic_section_num].sec_dest_addr
= hifi_head->sections[i].des_addr;
dynamic_section_data_offset += hifi_head->sections[i].size;
dynamic_section_num++;
}
else if (DRV_HIFI_IMAGE_SEC_UNLOAD == hifi_head->sections[i].load_attib)
{
/* ÎÞÐëµ×Èí¼ÓÔØ */
section_virtual_addr = (void*)ioremap_nocache(hifi_head->sections[i].des_addr,
hifi_head->sections[i].size);
if (NULL == section_virtual_addr)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to io remap, %d \r\n", __LINE__);
return -ENOMEM;
}
/* ½«ÐÅÏ¢·ÅÈëÓÊÏäÖÐ */
drv_hifi_fill_mb_info((unsigned int*)section_virtual_addr);
iounmap(section_virtual_addr);
}
else
{
/* ¼ÓÔØ·½Ê½ÓÐÎó */
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP,
"unknown section attribute %d\r\n", hifi_head->sections[i].load_attib);
ret = -1;
goto err_unmap;
}
}
section_info->sec_num = dynamic_section_num;
ret = bsp_ipc_int_send(IPC_CORE_MCORE, IPC_MCU_INT_SRC_HIFI_PU);
if (ret)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP,
"send hifi pu ipc error %d\r\n", ret);
goto err_unmap;
}
err_unmap:
return ret;
}
#endif
static int bsp_dsp_load_image(char* part_name)
{
int ret = 0;
u32 offset = 0;
u32 skip_len = 0;
void *bbe_ddr_addr = NULL;
void *tds_data_addr = NULL;
/*coverity[var_decl] */
struct image_head head;
#ifdef CONFIG_HIFI
struct drv_hifi_image_head *hifi_head = NULL;
void *hifi_image = NULL;
#endif
/* clean ok flag */
writel(0, (void*)SHM_MEM_DSP_FLAG_ADDR);
/* Ö¸ÏòÒ»¿éDDR ¿Õ¼äÓÃÓÚ´æ·Å¾µÏñºÍÅäÖÃÊý¾Ý */
bbe_ddr_addr = (void*)ioremap_nocache(DDR_TLPHY_IMAGE_ADDR, DDR_TLPHY_IMAGE_SIZE);
tds_data_addr = (void*)ioremap_nocache(DDR_LPHY_SDR_ADDR + 0x1C0000, 0x40000);
if ((NULL == bbe_ddr_addr) || (NULL == tds_data_addr))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to io remap, %d \r\n", __LINE__);
ret = -ENOMEM;
goto err_unmap;
}
/* »ñµÃÔÚnand ÖеÄbbe ¾µÏñÍ· */
if (NAND_OK != bsp_nand_read(part_name, 0, (char*)&head, sizeof(struct image_head), &skip_len))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to load dsp image head\r\n");
ret = NAND_ERROR;
goto err_unmap;
}
/*coverity[uninit_use_in_call] */
/* ÅжÏÊÇ·ñÕÒµ½dsp ¾µÏñ */
if (memcmp(head.image_name, DSP_IMAGE_NAME, sizeof(DSP_IMAGE_NAME)))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "dsp image not found\r\n");
goto err_unmap;
}
#if 0
if (head.load_addr != DDR_TLPHY_IMAGE_ADDR)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP,
"dsp image not match, ddr addr asume to 0x%x\r\n",
DDR_TLPHY_IMAGE_ADDR);
goto err_no_part;
}
#endif
offset += LPHY_BBE16_MUTI_IMAGE_OFFSET + sizeof(struct image_head) + skip_len;
/* ½«¾µÏñ´Ónand ¶ÁÈëÉêÇëµÄddr ÖÐ */
if (NAND_OK == bsp_nand_read(part_name, offset, (char*)bbe_ddr_addr, LPHY_BBE16_MUTI_IMAGE_SIZE, &skip_len))
{
printk(KERN_INFO"succeed to load dsp image, address: 0x%x, size: 0x%x\r\n",
DDR_TLPHY_IMAGE_ADDR, DDR_TLPHY_IMAGE_SIZE);
}
else
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to load dsp image\r\n");
ret = NAND_ERROR;
goto err_unmap;
}
offset += LPHY_BBE16_MUTI_IMAGE_SIZE + skip_len;
/* ½«td ÅäÖÃÐÅÏ¢´Ónand ¶ÁÈëÉêÇëµÄddr ÖÐ */
if (NAND_OK == bsp_nand_read(part_name, offset, (char*)tds_data_addr, TPHY_BBE16_CFG_DATA_SIZE, &skip_len))
{
printk(KERN_INFO"succeed to load TD config data, address: 0x%x, size: 0x%x\n",
DDR_LPHY_SDR_ADDR + 0x1C0000, 0x40000);
}
else
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to load TD config data\n");
ret = NAND_ERROR;
goto err_unmap;
}
#ifdef CONFIG_HIFI
if (bsp_dsp_is_hifi_exist())
{
/* Ö¸Ïòhifi ¾µÏñÍ· */
hifi_head = (struct drv_hifi_image_head *)kmalloc(sizeof(struct drv_hifi_image_head), GFP_KERNEL);
if (NULL == (void *)hifi_head)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to malloc hifi head space\n");
ret = -1;
goto err_hifi;
}
offset += TPHY_BBE16_CFG_DATA_SIZE + skip_len;
/* ´Ónand ÖжÁÈ¡hifi_head */
if (NAND_OK != bsp_nand_read(part_name, offset, (char*)hifi_head,
sizeof(struct drv_hifi_image_head), &skip_len))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to load hifi image\n");
ret = NAND_ERROR;
goto err_hifi;
}
if (hifi_head->sections_num > HIFI_SEC_MAX_NUM)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "hifi image head error\n");
kfree(hifi_head);
ret = -1;
goto err_hifi;
}
hifi_image = vmalloc(hifi_head->image_size);
if (NULL == (void *)hifi_image)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to malloc hifi image space, size: 0x%x\n", hifi_head->image_size);
kfree(hifi_head);
ret = -1;
goto err_hifi;
}
/* ´Ónand ÖжÁÈ¡hifi ¾µÏñµ½hifi_image */
if (NAND_OK != bsp_nand_read(part_name, offset, (char*)hifi_image, hifi_head->image_size, &skip_len))
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "fail to load hifi image\n");
kfree(hifi_head);
vfree(hifi_image);
ret = NAND_ERROR;
goto err_hifi;
}
/* ÊÍ·Å */
kfree(hifi_head);
if (bsp_hifi_load_sections(hifi_image))
{
vfree(hifi_image);
ret = -1;
goto err_hifi;
}
vfree(hifi_image);
}
err_hifi:
#endif
/* set the ok flag of dsp image */
writel(DSP_IMAGE_STATE_OK, (void*)SHM_MEM_DSP_FLAG_ADDR);
err_unmap:
if (NULL != bbe_ddr_addr)
iounmap(bbe_ddr_addr);
if (NULL != tds_data_addr)
iounmap(tds_data_addr);
return ret;
}
#ifdef HI_ONOFF_PHONE
#ifdef HI3630_FASTBOOT_MODEM
#define PARTITION_MODEM_DSP_NAME "block2mtd: /dev/block/mmcblk0p27"
#else
#define PARTITION_MODEM_DSP_NAME "block2mtd: /dev/block/mmcblk0p31"
#endif
int bsp_load_modem_dsp(void)
{
return bsp_dsp_load_image(PARTITION_MODEM_DSP_NAME);
}
#else
int __init bsp_dsp_probe(struct platform_device *pdev)
{
int ret = 0;
#ifndef HI_ONOFF_PHONE
struct ST_PART_TBL* dsp_part = NULL;
/* ͨ¹ýÄ£¿éÃûÀ´²éÕÒÏàӦģ¿éµÄ¾µÏñ */
dsp_part = find_partition_by_name(PTABLE_DSP_NM);
if(NULL == dsp_part)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "load ccore image succeed\r\n");
ret = -EAGAIN;
goto err_no_part;
}
/* ͨ¹ý¾µÏñÃûÀ´¼ÓÔØdsp ¾µÏñ */
ret = bsp_dsp_load_image(dsp_part->name);
err_no_part:
#endif
return ret;
}
static struct platform_device bsp_dsp_device = {
.name = "bsp_dsp",
.id = 0,
.dev = {
.init_name = "bsp_dsp",
},
};
static struct platform_driver bsp_dsp_drv = {
.probe = bsp_dsp_probe,
.driver = {
.name = "bsp_dsp",
.owner = THIS_MODULE,
},
};
static int bsp_dsp_acore_init(void);
static void bsp_dsp_acore_exit(void);
static int __init bsp_dsp_acore_init(void)
{
int ret = 0;
ret = platform_device_register(&bsp_dsp_device);
if(ret)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "register his_modem device failed\r\n");
return ret;
}
ret = platform_driver_register(&bsp_dsp_drv);
if(ret)
{
bsp_trace(BSP_LOG_LEVEL_ERROR, BSP_MODU_DSP, "register his_modem driver failed\r\n");
platform_device_unregister(&bsp_dsp_device);
}
return ret;
}
static void __exit bsp_dsp_acore_exit(void)
{
platform_driver_unregister(&bsp_dsp_drv);
platform_device_unregister(&bsp_dsp_device);
}
module_init(bsp_dsp_acore_init);
module_exit(bsp_dsp_acore_exit);
MODULE_AUTHOR("z00227143@huawei.com");
MODULE_DESCRIPTION("HIS Balong V7R2 DSP load");
MODULE_LICENSE("GPL");
#endif
#ifdef __cplusplus
}
#endif
|
wbrambley/Grace-kernel
|
drivers/vendor/hisi/modem/drv/acore/kernel/drivers/modem/dsp/bsp_dsp.c
|
C
|
gpl-2.0
| 13,558
|
/**
* WARNING: WHILE THERE ARE TWO VERSIONS OF SPECIAL:CONTACT... THIS WILL BE THE MASTER FILE, AND THE OTHER /extensions/wikia/SpecialContact/SpecialContact.js
* IS A COPY OF THIS FUNCTIONALITY.
*/
var SpecialContact = {
init: function() {
$( '#picker_grid' ).find( 'td > a' ).click( function () {
var trackLabel = $( this ).attr( 'class' ).substr( 23 ),
trackUrl = $( this ).attr( 'href' );
SpecialContact.trackClick( trackLabel, trackUrl );
} );
$( '#SpecialContactFooterPicker a' ).click( function (e) {
var trackLabel = 'footer-picker',
trackUrl = $( this ).attr( 'href' );
SpecialContact.trackClick( trackLabel, trackUrl, e );
} );
$( '#SpecialContactFooterNoForm a' ).click( function (e) {
var trackLabel = 'footer-noform',
trackUrl = $( this ).attr( 'href' );
SpecialContact.trackClick( trackLabel, trackUrl, e );
} );
$( '#SpecialContactIntroNoForm a' ).click( function (e) {
var trackLabel = 'intro-noform',
trackUrl = $( this ).attr( 'href' );
SpecialContact.trackClick( trackLabel, trackUrl, e );
} );
$( '#SpecialContactIntroForm a' ).click( function (e) {
var trackLabel = 'intro-form',
trackUrl = $( this ).attr( 'href' );
SpecialContact.trackClick( trackLabel, trackUrl, e );
} );
$('input[type=file]').change(function() {
$(this).closest('p').next().show();
});
},
trackClick: function ( trackLabel, trackUrl, event ) {
Wikia.Tracker.track({
action: Wikia.Tracker.ACTIONS.CLICK_LINK_TEXT,
category: 'specialcontact',
label: trackLabel,
href: trackUrl,
trackingMethod: 'internal'
});
}
};
// If this user has javascript, they can be part of the A/B tests, so we'll
// embed what groups they're in (and whether that's the control group or not).
(function( window, $, undefined ) {
var AbTest = window.Wikia.AbTest;
if ( AbTest ) {
var abString = '', abTests;
abTests = AbTest.getExperiments();
if ( abTests.length == 0 ) {
abString = 'No active experiments.';
} else {
// Make a single entry for each experiment.
$.each( abTests, function( i, exp ) {
if ( abString != '' ) {
abString += ', ';
}
abString += '[ ' + exp.name + ': ' + exp.group.name + ' ]';
});
}
// Inject this debug-data into a hidden element in the form.
$(function() {
$( '#wpAbTesting' ).val( abString );
});
}
})( window, jQuery );
|
SuriyaaKudoIsc/wikia-app-test
|
extensions/wikia/SpecialContact2/SpecialContact.js
|
JavaScript
|
gpl-2.0
| 2,380
|
{%- extends 'base-react.html' -%}
{%- block title -%}Recent listens - ListenBrainz{%- endblock -%}
{% block scripts %}
{{ super() }}
<script src="{{ get_static_path('main.js') }}" type="text/javascript"></script>
{% endblock %}
|
paramsingh/listenbrainz-server
|
listenbrainz/webserver/templates/index/recent.html
|
HTML
|
gpl-2.0
| 233
|
<link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ui-style.css" />
<?php /*?><?php
$this->breadcrumbs=array(
'Courses'=>array('index'),
$model->id=>array('view','id'=>$model->id),
'Update',
);
$this->menu=array(
array('label'=>'List Courses', 'url'=>array('index')),
array('label'=>'Create Courses', 'url'=>array('create')),
array('label'=>'View Courses', 'url'=>array('view', 'id'=>$model->id)),
array('label'=>'Manage Courses', 'url'=>array('admin')),
);
?>
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="247" valign="top">
<?php $this->renderPartial('left_side');?>
</td>
<td valign="top">
<div class="cont_right formWrapper">
<h1>Update Courses <?php echo $model->id; ?></h1><?php */?>
<?php
$this->beginWidget('zii.widgets.jui.CJuiDialog',array(
'id'=>'jobDialog11',
'options'=>array(
'title'=>Yii::t('job','Update'),
'autoOpen'=>true,
'modal'=>'true',
'width'=>'auto',
'height'=>'auto',
'resizable'=>false,
),
));
?>
<?php echo $this->renderPartial('_form1', array('model'=>$model,'val1'=>$val1)); ?>
<?php $this->endWidget('zii.widgets.jui.CJuiDialog');?>
<?php /*?> </div>
</td>
</tr>
</table><?php */?>
|
napoleon789/love_qlkh
|
osv/protected/modules/courses/views/courses/update.php
|
PHP
|
gpl-2.0
| 1,410
|
/**
* ScriptDev2 is an extension for mangos-one providing enhanced features for
* area triggers, creatures, game objects, instances, items, and spells beyond
* the default database scripting in mangos-one.
*
* Copyright (C) 2006-2013 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
*
* World of Warcraft, and all World of Warcraft or Warcraft art, images,
* and lore are copyrighted by Blizzard Entertainment, Inc.
*/
/* ScriptData
SDName: Boss_Chromaggus
SD%Complete: 95
SDComment: Chromatic Mutation disabled due to lack of core support
SDCategory: Blackwing Lair
EndScriptData */
#include "precompiled.h"
#include "blackwing_lair.h"
enum
{
EMOTE_GENERIC_FRENZY_KILL = -1000001,
EMOTE_SHIMMER = -1469003,
// These spells are actually called elemental shield
// What they do is decrease all damage by 75% then they increase
// One school of damage by 1100%
SPELL_FIRE_VULNERABILITY = 22277,
SPELL_FROST_VULNERABILITY = 22278,
SPELL_SHADOW_VULNERABILITY = 22279,
SPELL_NATURE_VULNERABILITY = 22280,
SPELL_ARCANE_VULNERABILITY = 22281,
MAX_BREATHS = 5,
SPELL_INCINERATE = 23308, // Incinerate 23308,23309
SPELL_TIME_LAPSE = 23310, // Time lapse 23310, 23311(old threat mod that was removed in 2.01)
SPELL_CORROSIVE_ACID = 23313, // Corrosive Acid 23313, 23314
SPELL_IGNITE_FLESH = 23315, // Ignite Flesh 23315,23316
SPELL_FROST_BURN = 23187, // Frost burn 23187, 23189
// Brood Affliction 23173 - Scripted Spell that cycles through all targets within 100 yards and has a chance to cast one of the afflictions on them
// Since Scripted spells arn't coded I'll just write a function that does the same thing
SPELL_BROODAF_BLUE = 23153, // Blue affliction 23153
SPELL_BROODAF_BLACK = 23154, // Black affliction 23154
SPELL_BROODAF_RED = 23155, // Red affliction 23155 (23168 on death)
SPELL_BROODAF_BRONZE = 23170, // Bronze Affliction 23170
SPELL_BROODAF_GREEN = 23169, // Brood Affliction Green 23169
SPELL_CHROMATIC_MUT_1 = 23174, // Spell cast on player if they get all 5 debuffs
SPELL_FRENZY = 28371, // The frenzy spell may be wrong
SPELL_ENRAGE = 28747
};
static const uint32 aPossibleBreaths[MAX_BREATHS] = {SPELL_INCINERATE, SPELL_TIME_LAPSE, SPELL_CORROSIVE_ACID, SPELL_IGNITE_FLESH, SPELL_FROST_BURN};
struct MANGOS_DLL_DECL boss_chromaggusAI : public ScriptedAI
{
boss_chromaggusAI(Creature* pCreature) : ScriptedAI(pCreature)
{
// Select the 2 different breaths that we are going to use until despawned
// 5 possiblities for the first breath, 4 for the second, 20 total possiblites
// select two different numbers between 0..MAX_BREATHS-1
uint8 uiPos1 = urand(0, MAX_BREATHS - 1);
uint8 uiPos2 = (uiPos1 + urand(1, MAX_BREATHS - 1)) % MAX_BREATHS;
m_uiBreathOneSpell = aPossibleBreaths[uiPos1];
m_uiBreathTwoSpell = aPossibleBreaths[uiPos2];
m_pInstance = (ScriptedInstance*)pCreature->GetInstanceData();
Reset();
}
ScriptedInstance* m_pInstance;
uint32 m_uiBreathOneSpell;
uint32 m_uiBreathTwoSpell;
uint32 m_uiCurrentVulnerabilitySpell;
uint32 m_uiShimmerTimer;
uint32 m_uiBreathOneTimer;
uint32 m_uiBreathTwoTimer;
uint32 m_uiAfflictionTimer;
uint32 m_uiFrenzyTimer;
bool m_bEnraged;
void Reset() override
{
m_uiCurrentVulnerabilitySpell = 0; // We use this to store our last vulnerability spell so we can remove it later
m_uiShimmerTimer = 0; // Time till we change vurlnerabilites
m_uiBreathOneTimer = 30000; // First breath is 30 seconds
m_uiBreathTwoTimer = 60000; // Second is 1 minute so that we can alternate
m_uiAfflictionTimer = 10000; // This is special - 5 seconds means that we cast this on 1 pPlayer every 5 sconds
m_uiFrenzyTimer = 15000;
m_bEnraged = false;
}
void Aggro(Unit* /*pWho*/) override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_CHROMAGGUS, IN_PROGRESS);
}
void JustDied(Unit* /*pKiller*/) override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_CHROMAGGUS, DONE);
}
void JustReachedHome() override
{
if (m_pInstance)
m_pInstance->SetData(TYPE_CHROMAGGUS, FAIL);
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
// Shimmer Timer Timer
if (m_uiShimmerTimer < uiDiff)
{
// Remove old vulnerability spell
if (m_uiCurrentVulnerabilitySpell)
m_creature->RemoveAurasDueToSpell(m_uiCurrentVulnerabilitySpell);
// Cast new random vurlnabilty on self
uint32 aSpellId[] = {SPELL_FIRE_VULNERABILITY, SPELL_FROST_VULNERABILITY, SPELL_SHADOW_VULNERABILITY, SPELL_NATURE_VULNERABILITY, SPELL_ARCANE_VULNERABILITY};
uint32 uiSpell = aSpellId[urand(0, 4)];
if (DoCastSpellIfCan(m_creature, uiSpell) == CAST_OK)
{
m_uiCurrentVulnerabilitySpell = uiSpell;
DoScriptText(EMOTE_SHIMMER, m_creature);
m_uiShimmerTimer = 45000;
}
}
else
m_uiShimmerTimer -= uiDiff;
// Breath One Timer
if (m_uiBreathOneTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, m_uiBreathOneSpell) == CAST_OK)
m_uiBreathOneTimer = 60000;
}
else
m_uiBreathOneTimer -= uiDiff;
// Breath Two Timer
if (m_uiBreathTwoTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, m_uiBreathTwoSpell) == CAST_OK)
m_uiBreathTwoTimer = 60000;
}
else
m_uiBreathTwoTimer -= uiDiff;
// Affliction Timer
if (m_uiAfflictionTimer < uiDiff)
{
uint32 m_uiSpellAfflict = 0;
switch (urand(0, 4))
{
case 0: m_uiSpellAfflict = SPELL_BROODAF_BLUE; break;
case 1: m_uiSpellAfflict = SPELL_BROODAF_BLACK; break;
case 2: m_uiSpellAfflict = SPELL_BROODAF_RED; break;
case 3: m_uiSpellAfflict = SPELL_BROODAF_BRONZE; break;
case 4: m_uiSpellAfflict = SPELL_BROODAF_GREEN; break;
}
GuidVector vGuids;
m_creature->FillGuidsListFromThreatList(vGuids);
for (GuidVector::const_iterator i = vGuids.begin(); i != vGuids.end(); ++i)
{
Unit* pUnit = m_creature->GetMap()->GetUnit(*i);
if (pUnit)
{
// Cast affliction
DoCastSpellIfCan(pUnit, m_uiSpellAfflict, CAST_TRIGGERED);
// Chromatic mutation if target is effected by all afflictions
if (pUnit->HasAura(SPELL_BROODAF_BLUE, EFFECT_INDEX_0)
&& pUnit->HasAura(SPELL_BROODAF_BLACK, EFFECT_INDEX_0)
&& pUnit->HasAura(SPELL_BROODAF_RED, EFFECT_INDEX_0)
&& pUnit->HasAura(SPELL_BROODAF_BRONZE, EFFECT_INDEX_0)
&& pUnit->HasAura(SPELL_BROODAF_GREEN, EFFECT_INDEX_0))
{
// target->RemoveAllAuras();
// DoCastSpellIfCan(target,SPELL_CHROMATIC_MUT_1);
// Chromatic mutation is causing issues
// Assuming it is caused by a lack of core support for Charm
// So instead we instant kill our target
// WORKAROUND
if (pUnit->GetTypeId() == TYPEID_PLAYER)
m_creature->CastSpell(pUnit, 5, false);
}
}
}
m_uiAfflictionTimer = 10000;
}
else
m_uiAfflictionTimer -= uiDiff;
// Frenzy Timer
if (m_uiFrenzyTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_FRENZY) == CAST_OK)
{
DoScriptText(EMOTE_GENERIC_FRENZY_KILL, m_creature);
m_uiFrenzyTimer = urand(10000, 15000);
}
}
else
m_uiFrenzyTimer -= uiDiff;
// Enrage if not already enraged and below 20%
if (!m_bEnraged && m_creature->GetHealthPercent() < 20.0f)
{
DoCastSpellIfCan(m_creature, SPELL_ENRAGE);
m_bEnraged = true;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_boss_chromaggus(Creature* pCreature)
{
return new boss_chromaggusAI(pCreature);
}
void AddSC_boss_chromaggus()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_chromaggus";
pNewScript->GetAI = &GetAI_boss_chromaggus;
pNewScript->RegisterSelf();
}
|
mangosArchives/serverOneRel18
|
src/scripts/scripts/eastern_kingdoms/blackwing_lair/boss_chromaggus.cpp
|
C++
|
gpl-2.0
| 10,186
|
/*
* memtest.c
*
* Copyright (C) 2013 Alexander Aring <aar@pengutronix.de>, Pengutronix
*
* (C) Copyright 2000
* Wolfgang Denk, DENX Software Engineering, wd@denx.de.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#include <progress.h>
#include <common.h>
#include <memory.h>
#include <types.h>
#include <linux/sizes.h>
#include <errno.h>
#include <memtest.h>
static const resource_size_t bitpattern[] = {
0x00000001, /* single bit */
0x00000003, /* two adjacent bits */
0x00000007, /* three adjacent bits */
0x0000000F, /* four adjacent bits */
0x00000005, /* two non-adjacent bits */
0x00000015, /* three non-adjacent bits */
0x00000055, /* four non-adjacent bits */
0xAAAAAAAA, /* alternating 1/0 */
};
/*
* Perform a memory test. The complete test
* loops until interrupted by ctrl-c.
*
* Prameters:
* start: start address for memory test.
* end: end address of memory test.
* bus_only: skip integrity check and do only a address/data bus
* testing.
*
* Return value can be -EINVAL for invalid parameter or -EINTR
* if memory test was interrupted.
*/
int mem_test(resource_size_t _start,
resource_size_t _end, int bus_only)
{
volatile resource_size_t *start, *dummy, val, readback, offset,
offset2, pattern, temp, anti_pattern, num_words;
int i;
_start = ALIGN(_start, sizeof(resource_size_t));
_end = ALIGN_DOWN(_end, sizeof(resource_size_t)) - 1;
if (_end <= _start)
return -EINVAL;
start = (resource_size_t *)_start;
/*
* Point the dummy to start[1]
*/
dummy = start + 1;
num_words = (_end - _start + 1)/sizeof(resource_size_t);
printf("Starting data line test.\n");
/*
* Data line test: write a pattern to the first
* location, write the 1's complement to a 'parking'
* address (changes the state of the data bus so a
* floating bus doen't give a false OK), and then
* read the value back. Note that we read it back
* into a variable because the next time we read it,
* it might be right (been there, tough to explain to
* the quality guys why it prints a failure when the
* "is" and "should be" are obviously the same in the
* error message).
*
* Rather than exhaustively testing, we test some
* patterns by shifting '1' bits through a field of
* '0's and '0' bits through a field of '1's (i.e.
* pattern and ~pattern).
*/
for (i = 0; i < ARRAY_SIZE(bitpattern)/
sizeof(resource_size_t); i++) {
val = bitpattern[i];
for (; val != 0; val <<= 1) {
*start = val;
/* clear the test data off of the bus */
*dummy = ~val;
readback = *start;
if (readback != val) {
printf("FAILURE (data line): "
"expected 0x%08x, actual 0x%08x at address 0x%08x.\n",
val, readback, (resource_size_t)start);
return -EIO;
}
*start = ~val;
*dummy = val;
readback = *start;
if (readback != ~val) {
printf("FAILURE (data line): "
"Is 0x%08x, should be 0x%08x at address 0x%08x.\n",
readback,
~val, (resource_size_t)start);
return -EIO;
}
}
}
/*
* Based on code whose Original Author and Copyright
* information follows: Copyright (c) 1998 by Michael
* Barr. This software is placed into the public
* domain and may be used for any purpose. However,
* this notice must not be changed or removed and no
* warranty is either expressed or implied by its
* publication or distribution.
*/
/*
* Address line test
*
* Description: Test the address bus wiring in a
* memory region by performing a walking
* 1's test on the relevant bits of the
* address and checking for aliasing.
* This test will find single-bit
* address failures such as stuck -high,
* stuck-low, and shorted pins. The base
* address and size of the region are
* selected by the caller.
*
* Notes: For best results, the selected base
* address should have enough LSB 0's to
* guarantee single address bit changes.
* For example, to test a 64-Kbyte
* region, select a base address on a
* 64-Kbyte boundary. Also, select the
* region size as a power-of-two if at
* all possible.
*
* ## NOTE ## Be sure to specify start and end
* addresses such that num_words has
* lots of bits set. For example an
* address range of 01000000 02000000 is
* bad while a range of 01000000
* 01ffffff is perfect.
*/
pattern = 0xAAAAAAAA;
anti_pattern = 0x55555555;
/*
* Write the default pattern at each of the
* power-of-two offsets.
*/
for (offset = 1; offset <= num_words; offset <<= 1)
start[offset] = pattern;
printf("Check for address bits stuck high.\n");
/*
* Check for address bits stuck high.
*/
for (offset = 1; offset <= num_words; offset <<= 1) {
temp = start[offset];
if (temp != pattern) {
printf("FAILURE: Address bit "
"stuck high @ 0x%08x:"
" expected 0x%08x, actual 0x%08x.\n",
(resource_size_t)&start[offset],
pattern, temp);
return -EIO;
}
}
printf("Check for address bits stuck "
"low or shorted.\n");
/*
* Check for address bits stuck low or shorted.
*/
for (offset2 = 1; offset2 <= num_words; offset2 <<= 1) {
start[offset2] = anti_pattern;
for (offset = 1; offset <= num_words; offset <<= 1) {
temp = start[offset];
if ((temp != pattern) &&
(offset != offset2)) {
printf("FAILURE: Address bit stuck"
" low or shorted @"
" 0x%08x: expected 0x%08x, actual 0x%08x.\n",
(resource_size_t)&start[offset],
pattern, temp);
return -EIO;
}
}
start[offset2] = pattern;
}
/*
* We tested only the bus if != 0
* leaving here
*/
if (bus_only)
return 0;
printf("Starting integrity check of physicaly ram.\n"
"Filling ram with patterns...\n");
/*
* Description: Test the integrity of a physical
* memory device by performing an
* increment/decrement test over the
* entire region. In the process every
* storage bit in the device is tested
* as a zero and a one. The base address
* and the size of the region are
* selected by the caller.
*/
/*
* Fill memory with a known pattern.
*/
init_progression_bar(num_words);
for (offset = 0; offset < num_words; offset++) {
/*
* Every 4K we update the progressbar.
*/
if (!(offset & (SZ_4K - 1))) {
if (ctrlc())
return -EINTR;
show_progress(offset);
}
start[offset] = offset + 1;
}
show_progress(offset);
printf("\nCompare written patterns...\n");
/*
* Check each location and invert it for the second pass.
*/
init_progression_bar(num_words - 1);
for (offset = 0; offset < num_words; offset++) {
if (!(offset & (SZ_4K - 1))) {
if (ctrlc())
return -EINTR;
show_progress(offset);
}
temp = start[offset];
if (temp != (offset + 1)) {
printf("\nFAILURE (read/write) @ 0x%08x:"
" expected 0x%08x, actual 0x%08x.\n",
(resource_size_t)&start[offset],
(offset + 1), temp);
return -EIO;
}
anti_pattern = ~(offset + 1);
start[offset] = anti_pattern;
}
show_progress(offset);
printf("\nFilling ram with inverted pattern and compare it...\n");
/*
* Check each location for the inverted pattern and zero it.
*/
init_progression_bar(num_words - 1);
for (offset = 0; offset < num_words; offset++) {
if (!(offset & (SZ_4K - 1))) {
if (ctrlc())
return -EINTR;
show_progress(offset);
}
anti_pattern = ~(offset + 1);
temp = start[offset];
if (temp != anti_pattern) {
printf("\nFAILURE (read/write): @ 0x%08x:"
" expected 0x%08x, actual 0x%08x.\n",
(resource_size_t)&start[offset],
anti_pattern, temp);
return -EIO;
}
start[offset] = 0;
}
show_progress(offset);
/*
* end of progressbar
*/
printf("\n");
return 0;
}
|
zhang3/barebox
|
common/memtest.c
|
C
|
gpl-2.0
| 8,394
|
package net.fina.auditlog.client;
import java.util.Date;
import java.util.List;
import net.fina.auditlog.shared.AuditLog;
import com.google.gwt.cell.client.DateCell;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.cellview.client.CellTable;
import com.google.gwt.user.cellview.client.Column;
import com.google.gwt.user.cellview.client.SimplePager;
import com.google.gwt.user.cellview.client.TextColumn;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.datepicker.client.DateBox;
import com.google.gwt.view.client.AsyncDataProvider;
import com.google.gwt.view.client.HasData;
/**
* Entry point classes define <code>onModuleLoad()</code>.
*/
public class App implements EntryPoint {
private final Messages messages = GWT.create(Messages.class);
/**
* This is the entry point method.
*/
public void onModuleLoad() {
// Create a CellTable.
final CellTable<AuditLog> table = new CellTable<AuditLog>();
table.setPageSize(20);
// Add a text column to show the name.
TextColumn<AuditLog> id = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getId() + "";
}
};
table.addColumn(id, "id");
DateTimeFormat format = DateTimeFormat
.getFormat("dd.MM.yyyy-hh:mm:ss.SSS");
DateCell dateCell = new DateCell(format);
Column<AuditLog, Date> revelenceTime = new Column<AuditLog, Date>(
dateCell) {
@Override
public Date getValue(AuditLog object) {
return object.getRelevanceTime();
}
};
table.addColumn(revelenceTime, "Revelence Time");
TextColumn<AuditLog> actorId = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getActorId();
}
};
table.addColumn(actorId, "Actor Id");
TextColumn<AuditLog> entityId = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getEntityId();
}
};
table.addColumn(entityId, "Entity Id");
TextColumn<AuditLog> entityName = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getEntityName();
}
};
table.addColumn(entityName, "Entity Name");
TextColumn<AuditLog> entityProperty = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getEntityProperty();
}
};
table.addColumn(entityProperty, "Entity Property");
TextColumn<AuditLog> entityPropertyNewValue = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getEntityPropertyNewValue();
}
};
table.addColumn(entityPropertyNewValue, "Entity Property New Value");
TextColumn<AuditLog> entityPropertyOldValue = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getEntityPropertyOldValue();
}
};
table.addColumn(entityPropertyOldValue, "Entity Property Old Value");
TextColumn<AuditLog> operationType = new TextColumn<AuditLog>() {
@Override
public String getValue(AuditLog object) {
return object.getOperationType() + "";
}
};
table.addColumn(operationType, "Operation Type");
final AsyncDataProvider<AuditLog> provider = new AsyncDataProvider<AuditLog>() {
@Override
protected void onRangeChanged(HasData<AuditLog> display) {
final int start = display.getVisibleRange().getStart();
int length = display.getVisibleRange().getLength();
AsyncCallback<List<AuditLog>> callback = new AsyncCallback<List<AuditLog>>() {
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(List<AuditLog> result) {
updateRowData(start, result);
}
};
GreetingServiceAsync.Util.getInstance()
.fetchPage(
start,
length,
actorIdTextBox == null ? "" : actorIdTextBox
.getValue(),
startDateBox == null ? null : startDateBox
.getValue(),
endDateBox == null ? null : endDateBox
.getValue(), callback);
}
};
provider.addDataDisplay(table);
updateRowCount(provider);
final SimplePager pager = new SimplePager();
pager.setDisplay(table);
HorizontalPanel hPanel = new HorizontalPanel();
hPanel.setSpacing(5);
// Add some content to the panel
Label actorIdLabel = new Label("Actor Id");
hPanel.add(actorIdLabel);
hPanel.add(actorIdTextBox);
// Create a DateBox
startDateBox.setFormat(new DateBox.DefaultFormat(format));
startDateBox.getDatePicker().setYearArrowsVisible(true);
// Create a DateBox
endDateBox.setFormat(new DateBox.DefaultFormat(format));
endDateBox.getDatePicker().setYearArrowsVisible(true);
hPanel.add(new Label("Start"));
hPanel.add(startDateBox);
hPanel.add(new Label("End"));
hPanel.add(endDateBox);
final Button filterButton = new Button("Filter");
filterButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
filterButton.setEnabled(false);
try {
if (pager.getPage() > 0) {
pager.nextPage();
pager.setPage(pager.getPage() - 1);
}
updateRowCount(provider);
table.redraw();
} finally {
filterButton.setEnabled(true);
}
}
});
hPanel.add(filterButton);
VerticalPanel vp = new VerticalPanel();
vp.add(hPanel);
vp.add(table);
vp.add(pager);
// Add it to the root panel.
RootPanel.get().add(vp);
}
private void updateRowCount(final AsyncDataProvider<AuditLog> provider) {
GreetingServiceAsync.Util.getInstance().count(
actorIdTextBox == null ? "" : actorIdTextBox.getValue(),
startDateBox == null ? null : startDateBox.getValue(),
endDateBox == null ? null : endDateBox.getValue(),
new AsyncCallback<Long>() {
@Override
public void onFailure(Throwable caught) {
Window.alert(caught.getMessage());
}
@Override
public void onSuccess(Long result) {
provider.updateRowCount((int) ((long) result), true);
}
});
}
private TextBox actorIdTextBox = new TextBox();
private DateBox startDateBox = new DateBox();
private DateBox endDateBox = new DateBox();
}
|
nikoloz90/logs
|
fina-auditlog-simple3/src/main/java/net/fina/auditlog/client/App.java
|
Java
|
gpl-2.0
| 6,821
|
/* bender-tags: editor,unit,pastefromword */
/* bender-ckeditor-plugins: clipboard,pastefromword,format,ajax */
( function() {
'use strict';
bender.editor = true;
var compat = bender.tools.compatHtml;
function testWordFilter( editor ) {
return function( input, output ) {
assertPasteEvent( editor, { dataValue: compat( input, 1 ) }, function( data, msg ) {
assert.areSame( compat( output ), compat( data.dataValue ) );
}, 'tc1', true );
}
}
bender.test( {
'test list transformation': function() {
bender.tools.testInputOut( 'list_1', testWordFilter( this.editor ) );
}
} );
} )();
|
tuxun/smw-funwiki
|
extensions/WYSIWYG/ckeditor/_source/tests/tickets/9456/1.js
|
JavaScript
|
gpl-2.0
| 614
|
FROM centos:centos6
MAINTAINER SoftwareCollections.org <sclorg@redhat.com>
RUN yum -y --setopt=tsflags=nodocs install https://www.softwarecollections.org/en/scls/rhscl/devtoolset-3/epel-6-x86_64/download/rhscl-devtoolset-3-epel-6-x86_64.noarch.rpm && \
yum clean all
RUN yum install -y --setopt=tsflags=nodocs devtoolset-3 && yum clean all
ENV BASH_ENV=/etc/profile.d/cont-env.sh
ADD ./enabledevtoolset-3.sh /usr/share/cont-layer/common/env/enabledevtoolset-3.sh
ADD ./usr /usr
ADD ./etc /etc
ADD ./root /root
ENV HOME /home/default
RUN groupadd -r default -f -g 1001 && \
useradd -u 1001 -r -g default -d ${HOME} -s /sbin/nologin \
-c "Default Application User" default
USER 1001
ENTRYPOINT ["/usr/bin/container-entrypoint"]
CMD ["container-usage"]
|
sclorg/rhscl-dockerfiles
|
centos6.devtoolset-3/Dockerfile
|
Dockerfile
|
gpl-2.0
| 803
|
-- phpMyAdmin SQL Dump
-- version 2.8.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jun 04, 2007 at 01:18 PM
-- Server version: 5.0.21
-- PHP Version: 5.1.4
--
-- Database: `caredb`
--
-- --------------------------------------------------------
-- DROP TABLE IF EXISTS `care_tz_pricelist`
DROP TABLE IF EXISTS `care_tz_pricelist_accounts`;
DROP TABLE IF EXISTS `care_tz_drugsandservices_description`;
--
-- Adding price description table
--
CREATE TABLE IF NOT EXISTS `care_tz_drugsandservices_description` (
`ID` bigint(20) NOT NULL auto_increment,
`last_change` bigint(20) NOT NULL,
`UID` varchar(50) NOT NULL,
`Fieldname` varchar(50) NOT NULL,
`ShowDescription` varchar(50) NOT NULL,
`FullDescription` varchar(255) NOT NULL,
`is_insurance_price` tinyint(4) NOT NULL default '0',
PRIMARY KEY (`ID`)
) ENGINE=MyISAM AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;
--
-- Dumping data for table `care_tz_drugsandservices_description`
--
INSERT INTO `care_tz_drugsandservices_description` (`ID`, `last_change`, `UID`, `Fieldname`, `ShowDescription`, `FullDescription`, `is_insurance_price`) VALUES (1, 1183382556, 'Robert', 'unit_price', 'Selians price ', 'TSH (e.g. 12000,00 or 1200) - Standard price for item ', 1),
(2, 1183382556, 'Robert', 'unit_price_1', 'Insured price ', 'TSH (e.g. 1200,00 or 1200) - price for insured people', 0),
(3, 1183382556, 'Robert', 'unit_price_2', 'Private ', 'TSH (e.g. 1200,00 or 1200) - price for self paying people', 0),
(4, 1183382556, 'Robert', 'unit_price_3', 'Company ', 'TSH (e.g. 1200,00 or 1200) - price for Companies', 0);
-- ALTER TABLE `care_tz_drugsandservices` ADD `unit_price_1` VARCHAR( 50 ) NULL AFTER `unit_price` ,
-- ADD `partcode` VCHAR( 255 ) NULL AFTER `item_number`,
-- ADD `unit_price_2` VARCHAR( 50 ) NULL AFTER `unit_price_1` ,
-- ADD `unit_price_3` VARCHAR( 50 ) NULL AFTER `unit_price_2` ;
-- added by RM
-- ALTER TABLE `care_tz_drugsandservices_description` ADD `is_insurance_price` TINYINT NOT NULL DEFAULT '0';
-- ALTER TABLE `care_tz_drugsandservices_description` ADD `last_change` BIGINT NOT NULL AFTER `ID` , ADD `UID` VARCHAR( 50 ) NOT NULL AFTER `last_change` ;
|
timschofield/care2x
|
install/mysql/db_updates/mergedWithInstaller-caredb/care_tz_pricelist.sql
|
SQL
|
gpl-2.0
| 2,177
|
/***********************************************************************
Freeciv - Copyright (C) 1996 - A Kjeldberg, L Gregersen, P Unold
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2, or (at your option)
any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
***********************************************************************/
#ifdef HAVE_CONFIG_H
#include <fc_config.h>
#endif
#include <stdlib.h>
#include <string.h>
#include <gtk/gtk.h>
#include <gdk/gdkkeysyms.h>
/* utility */
#include "fcintl.h"
#include "log.h"
#include "mem.h"
#include "support.h"
/* common */
#include "city.h"
#include "packets.h"
#include "worklist.h"
/* client */
#include "citydlg_common.h"
#include "client_main.h"
#include "climisc.h"
#include "global_worklist.h"
#include "options.h"
#include "tilespec.h"
/* gui-gtk-2.0 */
#include "canvas.h"
#include "citydlg.h"
#include "graphics.h"
#include "gui_main.h"
#include "gui_stuff.h"
#include "helpdlg.h"
#include "inputdlg.h"
#include "wldlg.h"
static GtkWidget *worklists_shell;
static GtkWidget *worklists_list;
enum {
WORKLISTS_NEW,
WORKLISTS_DELETE,
WORKLISTS_PROPERTIES,
WORKLISTS_CLOSE
};
static GtkListStore *worklists_store;
static int max_unit_height = -1, max_unit_width = -1;
static void reset_global_worklist(GtkWidget *editor,
struct global_worklist *pgwl);
static void popup_worklist(struct global_worklist *pgwl);
static void popdown_worklist(struct global_worklist *pgwl);
static void dst_row_callback(GtkTreeView *view, GtkTreePath *path,
GtkTreeViewColumn *col, gpointer data);
/****************************************************************
Illegal initialization value for max unit size variables
*****************************************************************/
void blank_max_unit_size(void)
{
max_unit_height = -1;
max_unit_width = -1;
}
/****************************************************************
Setup max unit sprite size.
*****************************************************************/
static void update_max_unit_size(void)
{
max_unit_height = 0;
max_unit_width = 0;
unit_type_iterate(i) {
int x1, x2, y1, y2;
struct sprite *sprite = get_unittype_sprite(tileset, i,
direction8_invalid(), TRUE);
sprite_get_bounding_box(sprite, &x1, &y1, &x2, &y2);
max_unit_width = MAX(max_unit_width, x2 - x1);
max_unit_height = MAX(max_unit_height, y2 - y1);
} unit_type_iterate_end;
}
/****************************************************************
Worklists dialog being destroyed
*****************************************************************/
static void worklists_destroy_callback(GtkWidget *w, gpointer data)
{
worklists_shell = NULL;
}
/****************************************************************
Refresh global worklists list
*****************************************************************/
void update_worklist_report_dialog(void)
{
GtkTreeIter it;
gtk_list_store_clear(worklists_store);
global_worklists_iterate(pgwl) {
gtk_list_store_append(worklists_store, &it);
gtk_list_store_set(worklists_store, &it,
0, global_worklist_name(pgwl),
1, global_worklist_id(pgwl),
-1);
} global_worklists_iterate_end;
}
/****************************************************************
User has responded to worklist report
*****************************************************************/
static void worklists_response(GtkWidget *w, gint response)
{
struct global_worklist *pgwl;
int id;
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter it;
selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(worklists_list));
if (gtk_tree_selection_get_selected(selection, &model, &it)) {
gtk_tree_model_get(model, &it, 1, &id, -1);
pgwl = global_worklist_by_id(id);
} else {
pgwl = NULL;
id = -1;
}
switch (response) {
case WORKLISTS_NEW:
global_worklist_new(_("new"));
update_worklist_report_dialog();
return;
case WORKLISTS_DELETE:
if (!pgwl) {
return;
}
popdown_worklist(pgwl);
global_worklist_destroy(pgwl);
update_worklist_report_dialog();
return;
case WORKLISTS_PROPERTIES:
if (!pgwl) {
return;
}
popup_worklist(pgwl);
return;
default:
gtk_widget_destroy(worklists_shell);
return;
}
}
/****************************************************************
Worklist cell edited
*****************************************************************/
static void cell_edited(GtkCellRendererText *cell,
const gchar *spath,
const gchar *text, gpointer data)
{
GtkTreePath *path;
GtkTreeIter it;
struct global_worklist *pgwl;
int id;
path = gtk_tree_path_new_from_string(spath);
gtk_tree_model_get_iter(GTK_TREE_MODEL(worklists_store), &it, path);
gtk_tree_path_free(path);
gtk_tree_model_get(GTK_TREE_MODEL(worklists_store), &it, 1, &id, -1);
pgwl = global_worklist_by_id(id);
if (!pgwl) {
gtk_list_store_remove(worklists_store, &it);
return;
}
global_worklist_set_name(pgwl, text);
gtk_list_store_set(worklists_store, &it, 0, text, -1);
}
/****************************************************************
Bring up the global worklist report.
*****************************************************************/
static GtkWidget *create_worklists_report(void)
{
GtkWidget *shell, *list;
GtkWidget *vbox, *label, *sw;
GtkCellRenderer *rend;
shell = gtk_dialog_new_with_buttons(_("Edit worklists"),
NULL,
0,
GTK_STOCK_NEW,
WORKLISTS_NEW,
GTK_STOCK_DELETE,
WORKLISTS_DELETE,
GTK_STOCK_PROPERTIES,
WORKLISTS_PROPERTIES,
GTK_STOCK_CLOSE,
WORKLISTS_CLOSE,
NULL);
setup_dialog(shell, toplevel);
gtk_window_set_position(GTK_WINDOW(shell), GTK_WIN_POS_MOUSE);
g_signal_connect(shell, "response",
G_CALLBACK(worklists_response), NULL);
g_signal_connect(shell, "destroy",
G_CALLBACK(worklists_destroy_callback), NULL);
vbox = gtk_vbox_new(FALSE, 2);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(shell)->vbox), vbox);
worklists_store = gtk_list_store_new(2, G_TYPE_STRING, G_TYPE_INT);
list = gtk_tree_view_new_with_model(GTK_TREE_MODEL(worklists_store));
g_object_unref(worklists_store);
gtk_tree_view_set_headers_visible(GTK_TREE_VIEW(list), FALSE);
worklists_list = list;
rend = gtk_cell_renderer_text_new();
g_object_set(rend, "editable", TRUE, NULL);
g_signal_connect(rend, "edited",
G_CALLBACK(cell_edited), NULL);
gtk_tree_view_insert_column_with_attributes(GTK_TREE_VIEW(list), -1, NULL,
rend, "text", 0, NULL);
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw),
GTK_SHADOW_ETCHED_IN);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_NEVER, GTK_POLICY_ALWAYS);
gtk_container_add(GTK_CONTAINER(sw), list);
gtk_widget_set_size_request(sw, -1, 200);
label = g_object_new(GTK_TYPE_LABEL,
"use-underline", TRUE,
"mnemonic-widget", list,
"label", _("_Worklists:"),
"xalign", 0.0, "yalign", 0.5, NULL);
gtk_box_pack_start(GTK_BOX(vbox), label, FALSE, FALSE, 0);
gtk_box_pack_start(GTK_BOX(vbox), sw, TRUE, TRUE, 0);
gtk_widget_show_all(vbox);
return shell;
}
/****************************************************************
Open worklists report
*****************************************************************/
void popup_worklists_report(void)
{
if (!worklists_shell) {
worklists_shell = create_worklists_report();
update_worklist_report_dialog();
}
gtk_window_present(GTK_WINDOW(worklists_shell));
}
/****************************************************************
...
*****************************************************************/
struct worklist_data {
int global_worklist_id;
struct city *pcity;
GtkWidget *editor;
GtkListStore *src, *dst;
GtkWidget *src_view, *dst_view;
GtkTreeSelection *src_selection, *dst_selection;
GtkTreeViewColumn *src_col, *dst_col;
GtkWidget *add_cmd, *change_cmd, *help_cmd;
GtkWidget *up_cmd, *down_cmd, *prepend_cmd, *append_cmd, *remove_cmd;
bool future;
};
static GHashTable *hash;
static void commit_worklist(struct worklist_data *ptr);
enum {
TARGET_GTK_TREE_MODEL_ROW
};
static GtkTargetEntry wl_dnd_targets[] = {
{ "GTK_TREE_MODEL_ROW", GTK_TARGET_SAME_APP, TARGET_GTK_TREE_MODEL_ROW },
};
/****************************************************************
Add drag&drop target
*****************************************************************/
void add_worklist_dnd_target(GtkWidget *w)
{
gtk_drag_dest_set(w, GTK_DEST_DEFAULT_ALL,
wl_dnd_targets, G_N_ELEMENTS(wl_dnd_targets),
GDK_ACTION_COPY);
}
/****************************************************************
Get worklist by id
*****************************************************************/
static GtkWidget *get_worklist(int global_worklist_id)
{
if (hash) {
gpointer ret;
ret = g_hash_table_lookup(hash, GINT_TO_POINTER(global_worklist_id));
return ret;
} else {
return NULL;
}
}
/****************************************************************
Insert worklist to editor
*****************************************************************/
static void insert_worklist(int global_worklist_id, GtkWidget *editor)
{
if (!hash) {
hash = g_hash_table_new(g_direct_hash, g_direct_equal);
}
g_hash_table_insert(hash, GINT_TO_POINTER(global_worklist_id), editor);
}
/****************************************************************
Remove worklist from hash
*****************************************************************/
static void delete_worklist(int global_worklist_id)
{
if (hash) {
g_hash_table_remove(hash, GINT_TO_POINTER(global_worklist_id));
}
}
/****************************************************************
User responded to worklist report
*****************************************************************/
static void worklist_response(GtkWidget *shell, gint response)
{
gtk_widget_destroy(shell);
}
/****************************************************************
Worklist editor window used by the global worklist report.
*****************************************************************/
static void popup_worklist(struct global_worklist *pgwl)
{
GtkWidget *shell;
if (!(shell = get_worklist(global_worklist_id(pgwl)))) {
GtkWidget *editor;
shell = gtk_dialog_new_with_buttons(global_worklist_name(pgwl),
GTK_WINDOW(worklists_shell),
GTK_DIALOG_DESTROY_WITH_PARENT,
GTK_STOCK_CLOSE,
GTK_RESPONSE_CLOSE,
NULL);
gtk_window_set_role(GTK_WINDOW(shell), "worklist");
gtk_window_set_position(GTK_WINDOW(shell), GTK_WIN_POS_MOUSE);
g_signal_connect(shell, "response", G_CALLBACK(worklist_response), NULL);
gtk_window_set_default_size(GTK_WINDOW(shell), 500, 400);
editor = create_worklist();
reset_global_worklist(editor, pgwl);
insert_worklist(global_worklist_id(pgwl), editor);
gtk_container_add(GTK_CONTAINER(GTK_DIALOG(shell)->vbox), editor);
gtk_widget_show(editor);
refresh_worklist(editor);
}
gtk_window_present(GTK_WINDOW(shell));
}
/****************************************************************
Close worklist
*****************************************************************/
static void popdown_worklist(struct global_worklist *pgwl)
{
GtkWidget *shell;
if ((shell = get_worklist(global_worklist_id(pgwl)))) {
GtkWidget *parent;
parent = gtk_widget_get_toplevel(shell);
gtk_widget_destroy(parent);
}
}
/****************************************************************
Destroy worklist
*****************************************************************/
static void worklist_destroy(GtkWidget *editor, gpointer data)
{
struct worklist_data *ptr;
ptr = data;
if (ptr->global_worklist_id != -1) {
delete_worklist(ptr->global_worklist_id);
}
free(ptr);
}
/****************************************************************
Item activated from menu
*****************************************************************/
static void menu_item_callback(GtkMenuItem *item, struct worklist_data *ptr)
{
struct global_worklist *pgwl;
const struct worklist *pwl;
size_t i;
if (NULL == client.conn.playing) {
return;
}
pgwl = global_worklist_by_id(GPOINTER_TO_INT
(g_object_get_data(G_OBJECT(item), "id")));
if (!pgwl) {
return;
}
pwl = global_worklist_get(pgwl);
for (i = 0; i < worklist_length(pwl); i++) {
GtkTreeIter it;
cid cid;
cid = cid_encode(pwl->entries[i]);
gtk_list_store_append(ptr->dst, &it);
gtk_list_store_set(ptr->dst, &it, 0, (gint) cid, -1);
}
commit_worklist(ptr);
}
/****************************************************************
Open menu for adding items to worklist
*****************************************************************/
static void popup_add_menu(GtkMenuShell *menu, gpointer data)
{
GtkWidget *item;
gtk_container_foreach(GTK_CONTAINER(menu),
(GtkCallback) gtk_widget_destroy, NULL);
global_worklists_iterate(pgwl) {
item = gtk_menu_item_new_with_label(global_worklist_name(pgwl));
g_object_set_data(G_OBJECT(item), "id",
GINT_TO_POINTER(global_worklist_id(pgwl)));
gtk_widget_show(item);
gtk_container_add(GTK_CONTAINER(menu), item);
g_signal_connect(item, "activate",
G_CALLBACK(menu_item_callback), data);
} global_worklists_iterate_end;
item = gtk_separator_menu_item_new();
gtk_widget_show(item);
gtk_container_add(GTK_CONTAINER(menu), item);
item = gtk_menu_item_new_with_mnemonic(_("Edit Global _Worklists"));
gtk_widget_show(item);
gtk_container_add(GTK_CONTAINER(menu), item);
g_signal_connect(item, "activate",
G_CALLBACK(popup_worklists_report), NULL);
}
/****************************************************************
Help button clicked
*****************************************************************/
static void help_callback(GtkWidget *w, gpointer data)
{
struct worklist_data *ptr;
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter it;
ptr = data;
selection = ptr->src_selection;
if (gtk_tree_selection_get_selected(selection, &model, &it)) {
gint cid;
struct universal target;
gtk_tree_model_get(model, &it, 0, &cid, -1);
target = cid_decode(cid);
if (VUT_UTYPE == target.kind) {
popup_help_dialog_typed(utype_name_translation(target.value.utype),
HELP_UNIT);
} else if (is_great_wonder(target.value.building)) {
popup_help_dialog_typed(improvement_name_translation(target.value.building),
HELP_WONDER);
} else {
popup_help_dialog_typed(improvement_name_translation(target.value.building),
HELP_IMPROVEMENT);
}
} else {
popup_help_dialog_string(HELP_WORKLIST_EDITOR_ITEM);
}
}
/****************************************************************
"Change Production" clicked
*****************************************************************/
static void change_callback(GtkWidget *w, gpointer data)
{
struct worklist_data *ptr;
GtkTreeSelection *selection;
GtkTreeModel *model;
GtkTreeIter it;
ptr = data;
selection = ptr->src_selection;
if (gtk_tree_selection_get_selected(selection, &model, &it)) {
gint cid;
gtk_tree_model_get(model, &it, 0, &cid, -1);
city_change_production(ptr->pcity, cid_production(cid));
}
}
/****************************************************************
Showing of future targets toggled
*****************************************************************/
static void future_callback(GtkToggleButton *toggle, gpointer data)
{
struct worklist_data *ptr;
ptr = data;
ptr->future = !ptr->future;
refresh_worklist(ptr->editor);
}
/****************************************************************
Move item up in worklist
*****************************************************************/
static void queue_bubble_up(struct worklist_data *ptr)
{
GtkTreePath *path;
GtkTreeViewColumn *col;
GtkTreeModel *model;
if (!GTK_WIDGET_IS_SENSITIVE(ptr->dst_view)) {
return;
}
model = GTK_TREE_MODEL(ptr->dst);
gtk_tree_view_get_cursor(GTK_TREE_VIEW(ptr->dst_view), &path, &col);
if (path) {
GtkTreeIter it, it_prev;
if (gtk_tree_path_prev(path)) {
gtk_tree_model_get_iter(model, &it_prev, path);
it = it_prev;
gtk_tree_model_iter_next(model, &it);
gtk_list_store_swap(GTK_LIST_STORE(model), &it, &it_prev);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(ptr->dst_view), path, col, FALSE);
commit_worklist(ptr);
}
}
gtk_tree_path_free(path);
}
/****************************************************************
Removal of the item requested
*****************************************************************/
static void queue_remove(struct worklist_data *ptr)
{
GtkTreePath *path;
GtkTreeViewColumn *col;
gtk_tree_view_get_cursor(GTK_TREE_VIEW(ptr->dst_view), &path, &col);
if (path) {
dst_row_callback(GTK_TREE_VIEW(ptr->dst_view), path, col, ptr);
gtk_tree_path_free(path);
}
}
/****************************************************************
Move item down in queue
*****************************************************************/
static void queue_bubble_down(struct worklist_data *ptr)
{
GtkTreePath *path;
GtkTreeViewColumn *col;
GtkTreeModel *model;
if (!GTK_WIDGET_IS_SENSITIVE(ptr->dst_view)) {
return;
}
model = GTK_TREE_MODEL(ptr->dst);
gtk_tree_view_get_cursor(GTK_TREE_VIEW(ptr->dst_view), &path, &col);
if (path) {
GtkTreeIter it, it_next;
gtk_tree_model_get_iter(model, &it, path);
it_next = it;
if (gtk_tree_model_iter_next(model, &it_next)) {
gtk_list_store_swap(GTK_LIST_STORE(model), &it, &it_next);
gtk_tree_path_next(path);
gtk_tree_view_set_cursor(GTK_TREE_VIEW(ptr->dst_view), path, col, FALSE);
commit_worklist(ptr);
}
}
gtk_tree_path_free(path);
}
/****************************************************************
Insert item to queue
*****************************************************************/
static void queue_insert(struct worklist_data *ptr, bool prepend)
{
GtkTreeModel *model;
GtkTreeIter it;
GtkTreePath *path;
GtkTreeModel *src_model, *dst_model;
GtkTreeIter src_it, dst_it;
gint i, ncols;
if (!GTK_WIDGET_IS_SENSITIVE(ptr->dst_view)) {
return;
}
if (!gtk_tree_selection_get_selected(ptr->src_selection, &model, &it)) {
return;
}
path = gtk_tree_model_get_path(model, &it);
src_model = GTK_TREE_MODEL(ptr->src);
dst_model = GTK_TREE_MODEL(ptr->dst);
gtk_tree_model_get_iter(src_model, &src_it, path);
if (prepend) {
gtk_list_store_prepend(GTK_LIST_STORE(dst_model), &dst_it);
} else {
gtk_list_store_append(GTK_LIST_STORE(dst_model), &dst_it);
}
ncols = gtk_tree_model_get_n_columns(src_model);
for (i = 0; i < ncols; i++) {
GValue value = { 0, };
gtk_tree_model_get_value(src_model, &src_it, i, &value);
gtk_list_store_set_value(GTK_LIST_STORE(dst_model), &dst_it, i, &value);
}
commit_worklist(ptr);
gtk_tree_path_free(path);
}
/****************************************************************
Prepend item to worklist
*****************************************************************/
static void queue_prepend(struct worklist_data *ptr)
{
queue_insert(ptr, TRUE);
}
/****************************************************************
Append item to worklist
*****************************************************************/
static void queue_append(struct worklist_data *ptr)
{
queue_insert(ptr, FALSE);
}
/****************************************************************
Source row activated
*****************************************************************/
static void src_row_callback(GtkTreeView *view, GtkTreePath *path,
GtkTreeViewColumn *col, gpointer data)
{
struct worklist_data *ptr;
GtkTreeModel *src_model, *dst_model;
GtkTreeIter src_it, dst_it;
gint i, ncols;
ptr = data;
if (!GTK_WIDGET_IS_SENSITIVE(ptr->dst_view)) {
return;
}
src_model = GTK_TREE_MODEL(ptr->src);
dst_model = GTK_TREE_MODEL(ptr->dst);
gtk_tree_model_get_iter(src_model, &src_it, path);
gtk_list_store_append(GTK_LIST_STORE(dst_model), &dst_it);
ncols = gtk_tree_model_get_n_columns(src_model);
for (i = 0; i < ncols; i++) {
GValue value = { 0, };
gtk_tree_model_get_value(src_model, &src_it, i, &value);
gtk_list_store_set_value(GTK_LIST_STORE(dst_model), &dst_it, i, &value);
}
commit_worklist(ptr);
}
/****************************************************************
Destination row activated
*****************************************************************/
static void dst_row_callback(GtkTreeView *view, GtkTreePath *path,
GtkTreeViewColumn *col, gpointer data)
{
struct worklist_data *ptr;
GtkTreeModel *dst_model;
GtkTreeIter it;
ptr = data;
dst_model = GTK_TREE_MODEL(ptr->dst);
gtk_tree_model_get_iter(dst_model, &it, path);
gtk_list_store_remove(GTK_LIST_STORE(dst_model), &it);
commit_worklist(ptr);
}
/****************************************************************
Key press for source
*****************************************************************/
static gboolean src_key_press_callback(GtkWidget *w, GdkEventKey *ev,
gpointer data)
{
struct worklist_data *ptr;
ptr = data;
if (!GTK_WIDGET_IS_SENSITIVE(ptr->dst_view)) {
return FALSE;
}
if ((ev->state & GDK_SHIFT_MASK) && ev->keyval == GDK_Insert) {
queue_prepend(ptr);
return TRUE;
} else if (ev->keyval == GDK_Insert) {
queue_append(ptr);
return TRUE;
} else {
return FALSE;
}
}
/****************************************************************
Key press for destination
*****************************************************************/
static gboolean dst_key_press_callback(GtkWidget *w, GdkEventKey *ev,
gpointer data)
{
GtkTreeModel *model;
struct worklist_data *ptr;
ptr = data;
model = GTK_TREE_MODEL(ptr->dst);
if (ev->keyval == GDK_Delete) {
GtkTreeIter it, it_next;
bool deleted = FALSE;
if (gtk_tree_model_get_iter_first(model, &it)) {
bool more;
do {
it_next = it;
more = gtk_tree_model_iter_next(model, &it_next);
if (gtk_tree_selection_iter_is_selected(ptr->dst_selection, &it)) {
gtk_list_store_remove(GTK_LIST_STORE(model), &it);
deleted = TRUE;
}
it = it_next;
} while (more);
}
if (deleted) {
commit_worklist(ptr);
}
return TRUE;
} else if ((ev->state & GDK_MOD1_MASK) && ev->keyval == GDK_Up) {
queue_bubble_up(ptr);
return TRUE;
} else if ((ev->state & GDK_MOD1_MASK) && ev->keyval == GDK_Down) {
queue_bubble_down(ptr);
return TRUE;
} else {
return FALSE;
}
}
/****************************************************************
Selection from source
*****************************************************************/
static void src_selection_callback(GtkTreeSelection *selection, gpointer data)
{
struct worklist_data *ptr;
ptr = data;
/* update widget sensitivity. */
if (gtk_tree_selection_get_selected(selection, NULL, NULL)) {
if (can_client_issue_orders()
&& (!ptr->pcity || city_owner(ptr->pcity) == client.conn.playing)) {
/* if ptr->pcity is NULL, this is a global worklist */
gtk_widget_set_sensitive(ptr->change_cmd, TRUE);
gtk_widget_set_sensitive(ptr->prepend_cmd, TRUE);
gtk_widget_set_sensitive(ptr->append_cmd, TRUE);
} else {
gtk_widget_set_sensitive(ptr->change_cmd, FALSE);
gtk_widget_set_sensitive(ptr->prepend_cmd, FALSE);
gtk_widget_set_sensitive(ptr->append_cmd, FALSE);
}
gtk_widget_set_sensitive(ptr->help_cmd, TRUE);
} else {
gtk_widget_set_sensitive(ptr->change_cmd, FALSE);
gtk_widget_set_sensitive(ptr->help_cmd, FALSE);
gtk_widget_set_sensitive(ptr->prepend_cmd, FALSE);
gtk_widget_set_sensitive(ptr->append_cmd, FALSE);
}
}
/****************************************************************
Selection from destination
*****************************************************************/
static void dst_selection_callback(GtkTreeSelection *selection, gpointer data)
{
struct worklist_data *ptr;
ptr = data;
/* update widget sensitivity. */
if (gtk_tree_selection_count_selected_rows(selection) > 0) {
int num_rows = 0;
GtkTreeIter it;
gtk_widget_set_sensitive(ptr->up_cmd, TRUE);
gtk_widget_set_sensitive(ptr->down_cmd, TRUE);
if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(ptr->dst), &it)) {
do {
num_rows++;
} while (gtk_tree_model_iter_next(GTK_TREE_MODEL(ptr->dst), &it));
}
if (num_rows > 1) {
gtk_widget_set_sensitive(ptr->remove_cmd, TRUE);
} else {
gtk_widget_set_sensitive(ptr->remove_cmd, FALSE);
}
} else {
gtk_widget_set_sensitive(ptr->up_cmd, FALSE);
gtk_widget_set_sensitive(ptr->down_cmd, FALSE);
gtk_widget_set_sensitive(ptr->remove_cmd, FALSE);
}
}
/****************************************************************
Drag&drop to destination
*****************************************************************/
static gboolean dst_dnd_callback(GtkWidget *w, GdkDragContext *context,
struct worklist_data *ptr)
{
commit_worklist(ptr);
return FALSE;
}
/****************************************************************
Render worklist cell
*****************************************************************/
static void cell_render_func(GtkTreeViewColumn *col, GtkCellRenderer *rend,
GtkTreeModel *model, GtkTreeIter *it,
gpointer data)
{
gint cid;
struct universal target;
gtk_tree_model_get(model, it, 0, &cid, -1);
target = cid_production(cid);
if (GTK_IS_CELL_RENDERER_PIXBUF(rend)) {
GdkPixbuf *pix;
if (VUT_UTYPE == target.kind) {
struct canvas store;
pix = gdk_pixbuf_new(GDK_COLORSPACE_RGB, TRUE, 8,
max_unit_width, max_unit_height);
store.type = CANVAS_PIXBUF;
store.v.pixbuf = pix;
create_overlay_unit(&store, target.value.utype, DIR8_SOUTH);
g_object_set(rend, "pixbuf", pix, NULL);
g_object_unref(pix);
} else {
struct sprite *sprite = get_building_sprite(tileset, target.value.building);
pix = sprite_get_pixbuf(sprite);
g_object_set(rend, "pixbuf", pix, NULL);
}
} else {
struct city **pcity = data;
gint column;
char *row[4];
char buf[4][64];
int i;
gboolean useless;
for (i = 0; i < ARRAY_SIZE(row); i++) {
row[i] = buf[i];
}
column = GPOINTER_TO_INT(g_object_get_data(G_OBJECT(rend), "column"));
get_city_dialog_production_row(row, sizeof(buf[0]), target, *pcity);
g_object_set(rend, "text", row[column], NULL);
if (NULL != *pcity && VUT_IMPROVEMENT == target.kind) {
useless = is_improvement_redundant(*pcity, target.value.building);
/* Mark building redundant if we are really certain that there is
* no use for it. */
g_object_set(rend, "strikethrough", useless, NULL);
} else {
g_object_set(rend, "strikethrough", FALSE, NULL);
}
}
}
/****************************************************************
Populate view with buildable item information
*****************************************************************/
static void populate_view(GtkTreeView *view, struct city **ppcity,
GtkTreeViewColumn **pcol)
{
static const char *titles[] =
{ N_("Type"), N_("Name"), N_("Info"), N_("Cost"), N_("Turns") };
static bool titles_done;
gint i;
GtkCellRenderer *rend;
GtkTreeViewColumn *col;
intl_slist(ARRAY_SIZE(titles), titles, &titles_done);
/* Case i == 0 taken out of the loop to workaround gcc-4.2.1 bug
* http://gcc.gnu.org/PR33381
* Some values would 'stick' from i == 0 round. */
i = 0;
rend = gtk_cell_renderer_pixbuf_new();
gtk_tree_view_insert_column_with_data_func(view,
i, titles[i], rend, cell_render_func, ppcity, NULL);
col = gtk_tree_view_get_column(view, i);
if (gui_gtk2_show_task_icons) {
if (max_unit_width == -1 || max_unit_height == -1) {
update_max_unit_size();
}
} else {
g_object_set(col, "visible", FALSE, NULL);
}
if (gui_gtk2_show_task_icons) {
g_object_set(rend, "height", max_unit_height, NULL);
}
for (i = 1; i < ARRAY_SIZE(titles); i++) {
gint pos = i-1;
rend = gtk_cell_renderer_text_new();
g_object_set_data(G_OBJECT(rend), "column", GINT_TO_POINTER(pos));
gtk_tree_view_insert_column_with_data_func(view,
i, titles[i], rend, cell_render_func, ppcity, NULL);
col = gtk_tree_view_get_column(view, i);
if (pos >= 2) {
g_object_set(G_OBJECT(rend), "xalign", 1.0, NULL);
gtk_tree_view_column_set_alignment(col, 1.0);
}
if (pos == 3) {
*pcol = col;
}
if (gui_gtk2_show_task_icons) {
g_object_set(rend, "height", max_unit_height, NULL);
}
}
}
/****************************************************************
Worklist editor shell.
*****************************************************************/
GtkWidget *create_worklist(void)
{
GtkWidget *editor, *table, *sw, *bbox;
GtkWidget *src_view, *dst_view, *label, *button;
GtkWidget *menubar, *item, *menu, *image;
GtkWidget *table2, *arrow, *check;
GtkSizeGroup *group;
GtkListStore *src_store, *dst_store;
struct worklist_data *ptr;
ptr = fc_malloc(sizeof(*ptr));
src_store = gtk_list_store_new(1, G_TYPE_INT);
dst_store = gtk_list_store_new(1, G_TYPE_INT);
ptr->global_worklist_id = -1;
ptr->pcity = NULL;
ptr->src = src_store;
ptr->dst = dst_store;
ptr->future = FALSE;
/* create shell. */
editor = gtk_vbox_new(FALSE, 6);
g_signal_connect(editor, "destroy", G_CALLBACK(worklist_destroy), ptr);
g_object_set_data(G_OBJECT(editor), "data", ptr);
ptr->editor = editor;
/* add source and target lists. */
table = gtk_table_new(2, 5, FALSE);
gtk_box_pack_start(GTK_BOX(editor), table, TRUE, TRUE, 0);
group = gtk_size_group_new(GTK_SIZE_GROUP_HORIZONTAL);
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw),
GTK_SHADOW_ETCHED_IN);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
gtk_table_attach(GTK_TABLE(table), sw, 3, 5, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0);
src_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(src_store));
g_object_unref(src_store);
gtk_size_group_add_widget(group, src_view);
gtk_widget_set_name(src_view, "small_font");
populate_view(GTK_TREE_VIEW(src_view), &ptr->pcity, &ptr->src_col);
gtk_container_add(GTK_CONTAINER(sw), src_view);
label = g_object_new(GTK_TYPE_LABEL,
"use-underline", TRUE,
"mnemonic-widget", src_view,
"label", _("Source _Tasks:"),
"xalign", 0.0, "yalign", 0.5, NULL);
gtk_table_attach(GTK_TABLE(table), label, 3, 4, 0, 1,
GTK_FILL, GTK_FILL, 0, 0);
check = gtk_check_button_new_with_mnemonic(_("Show _Future Targets"));
gtk_table_attach(GTK_TABLE(table), check, 4, 5, 0, 1,
0, GTK_FILL, 0, 0);
g_signal_connect(check, "toggled", G_CALLBACK(future_callback), ptr);
table2 = gtk_table_new(5, 1, FALSE);
gtk_table_attach(GTK_TABLE(table), table2, 2, 3, 1, 2,
GTK_FILL, GTK_FILL, 0, 0);
button = gtk_button_new();
ptr->prepend_cmd = button;
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
gtk_table_attach(GTK_TABLE(table2), button, 0, 1, 0, 1,
0, GTK_EXPAND|GTK_FILL, 0, 24);
arrow = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_NONE);
gtk_container_add(GTK_CONTAINER(button), arrow);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(queue_prepend), ptr);
gtk_widget_set_sensitive(ptr->prepend_cmd, FALSE);
button = gtk_button_new();
ptr->up_cmd = button;
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
gtk_table_attach(GTK_TABLE(table2), button, 0, 1, 1, 2, 0, 0, 0, 0);
arrow = gtk_arrow_new(GTK_ARROW_UP, GTK_SHADOW_NONE);
gtk_container_add(GTK_CONTAINER(button), arrow);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(queue_bubble_up), ptr);
gtk_widget_set_sensitive(ptr->up_cmd, FALSE);
button = gtk_button_new();
ptr->down_cmd = button;
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
gtk_table_attach(GTK_TABLE(table2), button, 0, 1, 2, 3, 0, 0, 0, 0);
arrow = gtk_arrow_new(GTK_ARROW_DOWN, GTK_SHADOW_IN);
gtk_container_add(GTK_CONTAINER(button), arrow);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(queue_bubble_down), ptr);
gtk_widget_set_sensitive(ptr->down_cmd, FALSE);
button = gtk_button_new();
ptr->append_cmd = button;
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
gtk_table_attach(GTK_TABLE(table2), button, 0, 1, 3, 4,
0, GTK_EXPAND|GTK_FILL, 0, 24);
arrow = gtk_arrow_new(GTK_ARROW_LEFT, GTK_SHADOW_NONE);
gtk_container_add(GTK_CONTAINER(button), arrow);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(queue_append), ptr);
gtk_widget_set_sensitive(ptr->append_cmd, FALSE);
button = gtk_button_new();
ptr->remove_cmd = button;
gtk_button_set_relief(GTK_BUTTON(button), GTK_RELIEF_NONE);
gtk_table_attach(GTK_TABLE(table2), button, 0, 1, 4, 5,
0, GTK_EXPAND|GTK_FILL, 0, 24);
arrow = gtk_arrow_new(GTK_ARROW_RIGHT, GTK_SHADOW_IN);
gtk_container_add(GTK_CONTAINER(button), arrow);
g_signal_connect_swapped(button, "clicked",
G_CALLBACK(queue_remove), ptr);
gtk_widget_set_sensitive(ptr->remove_cmd, FALSE);
sw = gtk_scrolled_window_new(NULL, NULL);
gtk_scrolled_window_set_shadow_type(GTK_SCROLLED_WINDOW(sw),
GTK_SHADOW_ETCHED_IN);
gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(sw),
GTK_POLICY_NEVER, GTK_POLICY_AUTOMATIC);
gtk_table_attach(GTK_TABLE(table), sw, 0, 2, 1, 2,
GTK_EXPAND | GTK_FILL, GTK_EXPAND | GTK_FILL, 0, 0);
dst_view = gtk_tree_view_new_with_model(GTK_TREE_MODEL(dst_store));
g_object_unref(dst_store);
gtk_size_group_add_widget(group, dst_view);
gtk_widget_set_name(dst_view, "small_font");
populate_view(GTK_TREE_VIEW(dst_view), &ptr->pcity, &ptr->dst_col);
gtk_container_add(GTK_CONTAINER(sw), dst_view);
label = g_object_new(GTK_TYPE_LABEL,
"use-underline", TRUE,
"mnemonic-widget", dst_view,
"label", _("Target _Worklist:"),
"xalign", 0.0, "yalign", 0.5, NULL);
gtk_table_attach(GTK_TABLE(table), label, 0, 1, 0, 1,
GTK_FILL, GTK_FILL, 0, 0);
/* add bottom menu and buttons. */
bbox = gtk_hbutton_box_new();
gtk_button_box_set_layout(GTK_BUTTON_BOX(bbox), GTK_BUTTONBOX_END);
gtk_box_set_spacing(GTK_BOX(bbox), 10);
gtk_box_pack_start(GTK_BOX(editor), bbox, FALSE, FALSE, 0);
menubar = gtk_aux_menu_bar_new();
gtk_container_add(GTK_CONTAINER(bbox), menubar);
gtk_button_box_set_child_secondary(GTK_BUTTON_BOX(bbox), menubar, TRUE);
menu = gtk_menu_new();
image = gtk_image_new_from_stock(GTK_STOCK_ADD, GTK_ICON_SIZE_MENU);
item = gtk_image_menu_item_new_with_mnemonic(_("_Add Global Worklist"));
gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(item), image);
gtk_menu_item_set_submenu(GTK_MENU_ITEM(item), menu);
gtk_menu_shell_append(GTK_MENU_SHELL(menubar), item);
g_signal_connect(menu, "show",
G_CALLBACK(popup_add_menu), ptr);
ptr->add_cmd = item;
gtk_widget_set_sensitive(ptr->add_cmd, FALSE);
button = gtk_button_new_from_stock(GTK_STOCK_HELP);
gtk_container_add(GTK_CONTAINER(bbox), button);
g_signal_connect(button, "clicked",
G_CALLBACK(help_callback), ptr);
ptr->help_cmd = button;
gtk_widget_set_sensitive(ptr->help_cmd, FALSE);
button = gtk_button_new_with_mnemonic(_("Change Prod_uction"));
gtk_container_add(GTK_CONTAINER(bbox), button);
g_signal_connect(button, "clicked",
G_CALLBACK(change_callback), ptr);
ptr->change_cmd = button;
gtk_widget_set_sensitive(ptr->change_cmd, FALSE);
ptr->src_view = src_view;
ptr->dst_view = dst_view;
ptr->src_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(src_view));
ptr->dst_selection = gtk_tree_view_get_selection(GTK_TREE_VIEW(dst_view));
gtk_tree_selection_set_mode(ptr->dst_selection, GTK_SELECTION_MULTIPLE);
/* DND and other state changing callbacks. */
gtk_tree_view_set_reorderable(GTK_TREE_VIEW(dst_view), TRUE);
g_signal_connect(dst_view, "drag_end",
G_CALLBACK(dst_dnd_callback), ptr);
g_signal_connect(src_view, "row_activated",
G_CALLBACK(src_row_callback), ptr);
g_signal_connect(src_view, "key_press_event",
G_CALLBACK(src_key_press_callback), ptr);
g_signal_connect(dst_view, "row_activated",
G_CALLBACK(dst_row_callback), ptr);
g_signal_connect(dst_view, "key_press_event",
G_CALLBACK(dst_key_press_callback), ptr);
g_signal_connect(ptr->src_selection, "changed",
G_CALLBACK(src_selection_callback), ptr);
g_signal_connect(ptr->dst_selection, "changed",
G_CALLBACK(dst_selection_callback), ptr);
gtk_widget_show_all(table);
gtk_widget_show_all(bbox);
return editor;
}
/****************************************************************
Reset worklist for city
*****************************************************************/
void reset_city_worklist(GtkWidget *editor, struct city *pcity)
{
struct worklist_data *ptr;
ptr = g_object_get_data(G_OBJECT(editor), "data");
ptr->global_worklist_id = -1;
ptr->pcity = pcity;
gtk_list_store_clear(ptr->src);
gtk_list_store_clear(ptr->dst);
g_object_set(ptr->src_col, "visible", TRUE, NULL);
g_object_set(ptr->dst_col, "visible", TRUE, NULL);
gtk_tree_view_enable_model_drag_source(GTK_TREE_VIEW(ptr->src_view),
GDK_BUTTON1_MASK,
wl_dnd_targets,
G_N_ELEMENTS(wl_dnd_targets),
GDK_ACTION_COPY);
}
/****************************************************************
Reset one of the global worklists
*****************************************************************/
static void reset_global_worklist(GtkWidget *editor,
struct global_worklist *pgwl)
{
struct worklist_data *ptr;
ptr = g_object_get_data(G_OBJECT(editor), "data");
ptr->global_worklist_id = global_worklist_id(pgwl);
ptr->pcity = NULL;
gtk_list_store_clear(ptr->src);
gtk_list_store_clear(ptr->dst);
gtk_widget_hide(ptr->change_cmd);
g_object_set(ptr->src_col, "visible", FALSE, NULL);
g_object_set(ptr->dst_col, "visible", FALSE, NULL);
gtk_tree_view_unset_rows_drag_source(GTK_TREE_VIEW(ptr->src_view));
}
/****************************************************************
Refresh worklist info
*****************************************************************/
void refresh_worklist(GtkWidget *editor)
{
struct worklist_data *ptr;
const struct global_worklist *pgwl = NULL;
struct worklist queue;
struct universal targets[MAX_NUM_PRODUCTION_TARGETS];
int i, targets_used;
struct item items[MAX_NUM_PRODUCTION_TARGETS];
bool selected;
gint id;
GtkTreeIter it;
GtkTreePath *path;
GtkTreeModel *model;
gboolean exists;
ptr = g_object_get_data(G_OBJECT(editor), "data");
if (!ptr->pcity
&& !(pgwl = global_worklist_by_id(ptr->global_worklist_id))) {
}
/* refresh source tasks. */
if (gtk_tree_selection_get_selected(ptr->src_selection, NULL, &it)) {
gtk_tree_model_get(GTK_TREE_MODEL(ptr->src), &it, 0, &id, -1);
selected = TRUE;
} else {
selected = FALSE;
}
gtk_list_store_clear(ptr->src);
targets_used = collect_eventually_buildable_targets(targets, ptr->pcity,
ptr->future);
name_and_sort_items(targets, targets_used, items, FALSE, ptr->pcity);
path = NULL;
for (i = 0; i < targets_used; i++) {
gtk_list_store_append(ptr->src, &it);
gtk_list_store_set(ptr->src, &it, 0, (gint) cid_encode(items[i].item), -1);
if (selected && cid_encode(items[i].item) == id) {
path = gtk_tree_model_get_path(GTK_TREE_MODEL(ptr->src), &it);
}
}
if (path) {
gtk_tree_view_set_cursor(GTK_TREE_VIEW(ptr->src_view), path, NULL, FALSE);
gtk_tree_path_free(path);
}
/* refresh target worklist. */
model = GTK_TREE_MODEL(ptr->dst);
exists = gtk_tree_model_get_iter_first(model, &it);
/* dance around worklist braindamage. */
if (ptr->pcity) {
city_get_queue(ptr->pcity, &queue);
} else {
fc_assert(NULL != pgwl);
worklist_copy(&queue, global_worklist_get(pgwl));
}
for (i = 0; i < worklist_length(&queue); i++) {
struct universal target = queue.entries[i];
if (!exists) {
gtk_list_store_append(ptr->dst, &it);
}
gtk_list_store_set(ptr->dst, &it, 0, (gint) cid_encode(target), -1);
if (exists) {
exists = gtk_tree_model_iter_next(model, &it);
}
}
if (exists) {
GtkTreeIter it_next;
bool more;
do {
it_next = it;
more = gtk_tree_model_iter_next(model, &it_next);
gtk_list_store_remove(ptr->dst, &it);
it = it_next;
} while (more);
}
/* update widget sensitivity. */
if (ptr->pcity) {
if ((can_client_issue_orders() &&
city_owner(ptr->pcity) == client.conn.playing)) {
gtk_widget_set_sensitive(ptr->add_cmd, TRUE);
gtk_widget_set_sensitive(ptr->dst_view, TRUE);
} else {
gtk_widget_set_sensitive(ptr->add_cmd, FALSE);
gtk_widget_set_sensitive(ptr->dst_view, FALSE);
}
} else {
gtk_widget_set_sensitive(ptr->add_cmd, TRUE);
gtk_widget_set_sensitive(ptr->dst_view, TRUE);
}
}
/****************************************************************
Commit worklist data to worklist
*****************************************************************/
static void commit_worklist(struct worklist_data *ptr)
{
struct worklist queue;
GtkTreeModel *model;
GtkTreeIter it;
size_t i;
model = GTK_TREE_MODEL(ptr->dst);
worklist_init(&queue);
i = 0;
if (gtk_tree_model_get_iter_first(model, &it)) {
do {
gint cid;
/* oops, the player has a worklist longer than what we can store. */
if (i >= MAX_LEN_WORKLIST) {
break;
}
gtk_tree_model_get(model, &it, 0, &cid, -1);
worklist_append(&queue, cid_production(cid));
i++;
} while (gtk_tree_model_iter_next(model, &it));
}
/* dance around worklist braindamage. */
if (ptr->pcity) {
if (!city_set_queue(ptr->pcity, &queue)) {
/* Failed to change worklist. This means worklist visible
* on screen is not true. */
refresh_worklist(ptr->editor);
}
} else {
struct global_worklist *pgwl;
pgwl = global_worklist_by_id(ptr->global_worklist_id);
if (pgwl) {
global_worklist_set(pgwl, &queue);
}
}
}
|
longturn/freeciv-S2_5
|
client/gui-gtk-2.0/wldlg.c
|
C
|
gpl-2.0
| 43,940
|
/* $Header: /roq/tiff/tif_dumpmode.c 1 11/02/99 4:39p Zaphod $ */
/*
* Copyright (c) 1988-1996 Sam Leffler
* Copyright (c) 1991-1996 Silicon Graphics, Inc.
*
* Permission to use, copy, modify, distribute, and sell this software and
* its documentation for any purpose is hereby granted without fee, provided
* that (i) the above copyright notices and this permission notice appear in
* all copies of the software and related documentation, and (ii) the names of
* Sam Leffler and Silicon Graphics may not be used in any advertising or
* publicity relating to the software without the specific, prior written
* permission of Sam Leffler and Silicon Graphics.
*
* THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND,
* EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY
* WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
*
* IN NO EVENT SHALL SAM LEFFLER OR SILICON GRAPHICS BE LIABLE FOR
* ANY SPECIAL, INCIDENTAL, INDIRECT OR CONSEQUENTIAL DAMAGES OF ANY KIND,
* OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER OR NOT ADVISED OF THE POSSIBILITY OF DAMAGE, AND ON ANY THEORY OF
* LIABILITY, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
* OF THIS SOFTWARE.
*/
/*
* TIFF Library.
*
* "Null" Compression Algorithm Support.
*/
#include "tiffiop.h"
/*
* Encode a hunk of pixels.
*/
static int
DumpModeEncode(TIFF* tif, tidata_t pp, tsize_t cc, tsample_t s)
{
(void) s;
while (cc > 0) {
tsize_t n;
n = cc;
if (tif->tif_rawcc + n > tif->tif_rawdatasize)
n = tif->tif_rawdatasize - tif->tif_rawcc;
/*
* Avoid copy if client has setup raw
* data buffer to avoid extra copy.
*/
if (tif->tif_rawcp != pp)
_TIFFmemcpy(tif->tif_rawcp, pp, n);
tif->tif_rawcp += n;
tif->tif_rawcc += n;
pp += n;
cc -= n;
if (tif->tif_rawcc >= tif->tif_rawdatasize &&
!TIFFFlushData1(tif))
return (-1);
}
return (1);
}
/*
* Decode a hunk of pixels.
*/
static int
DumpModeDecode(TIFF* tif, tidata_t buf, tsize_t cc, tsample_t s)
{
(void) s;
if (tif->tif_rawcc < cc) {
TIFFError(tif->tif_name,
"DumpModeDecode: Not enough data for scanline %d",
tif->tif_row);
return (0);
}
/*
* Avoid copy if client has setup raw
* data buffer to avoid extra copy.
*/
if (tif->tif_rawcp != buf)
_TIFFmemcpy(buf, tif->tif_rawcp, cc);
tif->tif_rawcp += cc;
tif->tif_rawcc -= cc;
return (1);
}
/*
* Seek forwards nrows in the current strip.
*/
static int
DumpModeSeek(TIFF* tif, uint32 nrows)
{
tif->tif_rawcp += nrows * tif->tif_scanlinesize;
tif->tif_rawcc -= nrows * tif->tif_scanlinesize;
return (1);
}
/*
* Initialize dump mode.
*/
int
TIFFInitDumpMode(TIFF* tif, int scheme)
{
(void) scheme;
tif->tif_decoderow = DumpModeDecode;
tif->tif_decodestrip = DumpModeDecode;
tif->tif_decodetile = DumpModeDecode;
tif->tif_encoderow = DumpModeEncode;
tif->tif_encodestrip = DumpModeEncode;
tif->tif_encodetile = DumpModeEncode;
tif->tif_seek = DumpModeSeek;
return (1);
}
|
ioquake/jedi-outcast
|
utils/roq2/tiff/tif_dumpmode.c
|
C
|
gpl-2.0
| 3,168
|
/******************************************************************************
* problem_factory.cpp
* *
* Source of KaHIP -- Karlsruhe High Quality Partitioning.
* Christian Schulz <christian.schulz.phone@gmail.com>
*****************************************************************************/
#include "problem_factory.h"
problem_factory::problem_factory() {
}
problem_factory::~problem_factory() {
}
|
sebalamm/KaMIS
|
wmis/extern/KaHIP/lib/partition/uncoarsening/refinement/cycle_improvements/problem_factory.cpp
|
C++
|
gpl-2.0
| 449
|
/**
* @file mosync.resource.js
* @author Ali Sarrafi
*
* The library for loading Image resources into Mosync program from Javascript.
* This library only supports image resources and used together with the
* NativeUI library.
*/
/**
* The Resource handler submodule of the bridge module.
*/
mosync.resource = {};
/**
* A Hash containing all registered callback functions for
* loadImage function.
*/
mosync.resource.imageCallBackTable = {};
mosync.resource.imageIDTable = {};
mosync.resource.imageDownloadQueue = [];
/**
* Loads images into image handles for use in MoSync UI systems.
*
* @param imagePath relative path to the image file.
* @param imageID a custom ID used for refering to the image in JavaScript
* @param callBackFunction a function that will be called when the image is ready.
*/
mosync.resource.loadImage = function(imagePath, imageID, successCallback) {
mosync.resource.imageCallBackTable[imageID] = successCallback;
mosync.bridge.send(
[
"Resource",
"loadImage",
imagePath,
imageID
], null);
};
/**
* A function that is called by C++ to pass the loaded image information.
*
* @param imageID JavaScript ID of the image
* @param imageHandle C++ handle of the imge which can be used for refering to the loaded image
*/
mosync.resource.imageLoaded = function(imageID, imageHandle) {
var callbackFun = mosync.resource.imageCallBackTable[imageID];
if (undefined != callbackFun)
{
var args = Array.prototype.slice.call(arguments);
// Call the function.
callbackFun.apply(null, args);
}
};
/**
* Loads images into image handles from a remote URL for use in MoSync UI systems.
*
* @param imageURL URL to the image file.
* @param imageID a custom ID used for refering to the image in JavaScript
* @param callBackFunction a function that will be called when the image is ready.
*/
mosync.resource.loadRemoteImage = function(imageURL, imageID, callBackFunction) {
mosync.resource.imageCallBackTable[imageID] = callBackFunction;
var message = [
"Resource",
"loadRemoteImage",
imageURL,
imageID
];
// Add message to queue.
mosync.resource.imageDownloadQueue.push(message);
if (1 == mosync.resource.imageDownloadQueue.length)
{
mosync.bridge.send(message, null);
}
};
mosync.resource.imageDownloadStarted = function(imageID, imageHandle)
{
mosync.resource.imageIDTable[imageHandle] = imageID;
};
mosync.resource.imageDownloadFinished = function(imageHandle)
{
var imageID = mosync.resource.imageIDTable[imageHandle];
var callbackFun = mosync.resource.imageCallBackTable[imageID];
if (undefined != callbackFun)
{
// Call the function.
callbackFun(imageID, imageHandle);
}
// Remove first message.
if (mosync.resource.imageDownloadQueue.length > 0)
{
mosync.resource.imageDownloadQueue.shift();
}
// If there are more messages, send the next
// message in the queue.
if (mosync.resource.imageDownloadQueue.length > 0)
{
mosync.bridge.send(
mosync.resource.imageDownloadQueue[0],
null);
}
};
|
MoSync/MoSync
|
examples/cpp/JSNativeUI/LocalFiles/js/mosync-resource.js
|
JavaScript
|
gpl-2.0
| 3,029
|
namespace Codartis.SoftVis.VisualStudioIntegration.Modeling
{
/// <summary>
/// Enumerates the possible sources of model information.
/// </summary>
public enum ModelOrigin
{
Unknown,
SourceCode,
Metadata
}
}
|
realvizu/QuickDiagram
|
source/Codartis.SoftVis.VisualStudioIntegration/Modeling/ModelOrigin.cs
|
C#
|
gpl-2.0
| 260
|
<?php
namespace Test\Ease\TWB;
/**
* Generated by PHPUnit_SkeletonGenerator on 2016-10-23 at 14:07:12.
*/
class CarouselTest extends \Test\Ease\Html\DivTagTest
{
/**
* @var Carousel
*/
protected $object;
/**
* Sets up the fixture, for example, opens a network connection.
* This method is called before a test is executed.
*/
protected function setUp(): void
{
$this->object = new \Ease\TWB\Carousel();
$this->rendered = '<div id="'.$this->object->getTagId().'" class="carousel slide"><ol class="carousel-indicators"></ol><div class="carousel-inner" role="listbox"></div></div>';
}
/**
* Tears down the fixture, for example, closes a network connection.
* This method is called after a test is executed.
*/
protected function tearDown(): void
{
}
/**
* @covers Ease\TWB\Carousel::addSlide
* @todo Implement testAddSlide().
*/
public function testAddSlide()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
/**
* @covers Ease\TWB\Carousel::finalize
* @todo Implement testFinalize().
*/
public function testFinalize()
{
// Remove the following lines when you implement this test.
$this->markTestIncomplete(
'This test has not been implemented yet.'
);
}
}
|
VitexSoftware/EaseFramework
|
tests/src/Ease/TWB/CarouselTest.php
|
PHP
|
gpl-2.0
| 1,494
|
<?php
require_once getabspath('classes/controls/TextControl.php');
class TextField extends TextControl
{
function TextField($field, $pageObject, $id)
{
parent::EditControl($field, $pageObject, $id);
$this->format = EDIT_FORMAT_TEXT_FIELD;
}
function buildControl($value, $mode, $fieldNum = 0, $validate, $additionalCtrlParams, $data)
{
parent::buildControl($value, $mode, $fieldNum, $validate, $additionalCtrlParams, $data);
echo '<input id="'.$this->cfield.'" '.$this->inputStyle.' type="text" '
.($mode == MODE_SEARCH ? 'autocomplete="off" ' : '')
.(($mode==MODE_INLINE_EDIT || $mode==MODE_INLINE_ADD) && $this->is508==true ? 'alt="'.$this->strLabel.'" ' : '')
.'name="'.$this->cfield.'" '.$this->pageObject->pSetEdit->getEditParams($this->field).' value="'
.htmlspecialchars($value).'">';
$this->buildControlEnd($validate);
}
}
?>
|
LewisSoftwareDevelopment/Headwaters
|
output/classes/controls/TextField.php
|
PHP
|
gpl-2.0
| 864
|
<?php
defined( 'MVC_FRAMEWORK') or die( 'Direct Access to this location is not allowed.' );
$package_info['jreviews'] = array
(
'version'=>'2.3.19.213',
'min_s2_version_required'=>'1.4.14.72',
'is_beta'=>0
);
|
Jcook894/Travel_Insurance_Ratings
|
components/com_jreviews_bak/jreviews.info.php
|
PHP
|
gpl-2.0
| 249
|
<!-- Generator: GNU source-highlight 3.1.7
by Lorenzo Bettini
http://www.lorenzobettini.it
http://www.gnu.org/software/src-highlite -->
<pre><tt><i><font color="#9A1900">// Test/demo for the <a href="spi.h.html">spi.h</a> interface.</font></i>
<i><font color="#9A1900">//</font></i>
<i><font color="#9A1900">// This test driver requires an Analog Devices AD5206 connected as follows:</font></i>
<i><font color="#9A1900">//</font></i>
<i><font color="#9A1900">// * A6 pin (of AD5206) connected to +5V</font></i>
<i><font color="#9A1900">// * B6 of AD5206 connected to ground</font></i>
<i><font color="#9A1900">// * /CS to digital pin 10 (SS pin)</font></i>
<i><font color="#9A1900">// * SDI to digital pin 11 (MOSI pin)</font></i>
<i><font color="#9A1900">// * CLK - to digital pin 13 (SCK pin)</font></i>
<i><font color="#9A1900">//</font></i>
<i><font color="#9A1900">// This program starts with the wiper pin W6 connected to ground (SPI data</font></i>
<i><font color="#9A1900">// input 0x00). It then moves the wiper 1/4 of the way up the scale every</font></i>
<i><font color="#9A1900">// 5 seconds. If things are working correctly, this will produce a voltage</font></i>
<i><font color="#9A1900">// output sequence of ~0V, ~1/4 Vcc, ~1/2 Vcc, ~3/4 Vcc, and ~Vcc at wiper</font></i>
<i><font color="#9A1900">// pin W6. It then repeats this sequence using all the different clock</font></i>
<i><font color="#9A1900">// divider frequencies (of which there are a total of 7).</font></i>
<b><font color="#000080">#include</font></b> <font color="#FF0000"><assert.h></font>
<b><font color="#000080">#include</font></b> <font color="#FF0000"><stdlib.h></font> <i><font color="#9A1900">// FIXME: remove this once assert.h is fixed (new avrlibc)</font></i>
<b><font color="#000080">#include</font></b> <font color="#FF0000"><util/delay.h></font>
<b><font color="#000080">#include</font></b> <font color="#FF0000">"<a href="spi.h.html">spi.h</a>"</font>
<b><font color="#000080">#if</font></b> <font color="#990000">!</font> <font color="#990000">(</font><b><font color="#000000">defined</font></b> <font color="#990000">(</font>MY_SPI_SLAVE_1_SELECT_INIT<font color="#990000">)</font> <font color="#990000">&&</font> <font color="#990000">\</font>
<b><font color="#000000">defined</font></b> <font color="#990000">(</font>MY_SPI_SLAVE_1_SELECT_SET_LOW<font color="#990000">)</font> <font color="#990000">&&</font> <font color="#990000">\</font>
<b><font color="#000000">defined</font></b> <font color="#990000">(</font>MY_SPI_SLAVE_1_SELECT_SET_HIGH<font color="#990000">))</font>
<b><font color="#000080"># </font></b><b><font color="#000080"><a href="sd_card.c.html#114">error</a></font></b> The macros which specify which pin should be used <b><font color="#0000FF">for</font></b> <font color="#008080">SPI</font> slave <font color="#990000">\</font>
selection are <font color="#008080">not</font> set<font color="#990000">.</font> Please see the example in <font color="#008080">the</font> Makefile <font color="#990000">\</font>
in the spi <font color="#008080">module</font> directory<font color="#990000">.</font>
<b><font color="#000080">#endif</font></b>
<i><font color="#9A1900">// SPI communication uses PB5, so we rewire the blinky macros to use a LED</font></i>
<i><font color="#9A1900">// on a different pin.</font></i>
<b><font color="#000080">#ifdef</font></b> CHKP
<a href="accelerometer_test.c.html#26">CHKP -> accelerometer_test.c:26</a>
<a href="accelerometer_test.c.html#27">CHKP -> accelerometer_test.c:27</a>
<a href="lis331dlh_driver_private.c.html#49">CHKP -> lis331dlh_driver_private.c:49</a>
<a href="lis331dlh_driver_private.c.html#50">CHKP -> lis331dlh_driver_private.c:50</a>
<a href="spi_test.c.html#35">CHKP -> spi_test.c:35</a>
<a href="spi_test.c.html#36">CHKP -> spi_test.c:36</a>
<a href="util.h.html#99">CHKP -> util.h:99</a>
<b><font color="#000080"># undef</font></b> <a name="35">CHKP</a>
<b><font color="#000080"># define</font></b> <b><font color="#000000"><a name="36">CHKP</a></font></b><font color="#990000">()</font> <b><font color="#000000"><a href="util.h.html#72">CHKP_USING</a></font></b><font color="#990000">(</font>DDRD<font color="#990000">,</font> DDD2<font color="#990000">,</font> PORTD<font color="#990000">,</font> PORTD2<font color="#990000">,</font> <font color="#993399">300.0</font><font color="#990000">,</font> <font color="#993399">3</font><font color="#990000">)</font>
<b><font color="#000080">#endif</font></b>
<b><font color="#000080">#ifdef</font></b> BTRAP
<a href="accelerometer_test.c.html#30">BTRAP -> accelerometer_test.c:30</a>
<a href="accelerometer_test.c.html#31">BTRAP -> accelerometer_test.c:31</a>
<a href="lis331dlh_driver_private.c.html#53">BTRAP -> lis331dlh_driver_private.c:53</a>
<a href="lis331dlh_driver_private.c.html#54">BTRAP -> lis331dlh_driver_private.c:54</a>
<a href="spi_test.c.html#39">BTRAP -> spi_test.c:39</a>
<a href="spi_test.c.html#40">BTRAP -> spi_test.c:40</a>
<a href="util.h.html#102">BTRAP -> util.h:102</a>
<a href="wireless_xbee.c.html#23">BTRAP -> wireless_xbee.c:23</a>
<a href="wireless_xbee.c.html#24">BTRAP -> wireless_xbee.c:24</a>
<a href="wireless_xbee_test.c.html#59">BTRAP -> wireless_xbee_test.c:59</a>
<a href="wireless_xbee_test.c.html#60">BTRAP -> wireless_xbee_test.c:60</a>
<b><font color="#000080"># undef</font></b> <a name="39">BTRAP</a>
<b><font color="#000080"># define</font></b> <b><font color="#000000"><a name="40">BTRAP</a></font></b><font color="#990000">()</font> <b><font color="#000000"><a href="util.h.html#86">BTRAP_USING</a></font></b><font color="#990000">(</font>DDRD<font color="#990000">,</font> DDD2<font color="#990000">,</font> PORTD<font color="#990000">,</font> PORTD2<font color="#990000">,</font> <font color="#993399">100.0</font><font color="#990000">)</font>
<b><font color="#000080">#endif</font></b>
<i><font color="#9A1900">// WARNING: This module not fully tested. These tests test output with</font></i>
<i><font color="#9A1900">// SPI_BIT_ORDER_MSB_FIRST and SPI_DATA_MODE_0 with all SPI_CLOCK_DIVIDER_*</font></i>
<i><font color="#9A1900">// settings. The <a href="sd_card.h.html">sd_card.h</a> interface exercises input. The other data</font></i>
<i><font color="#9A1900">// orders and modes are only trivially different and should work fine,</font></i>
<i><font color="#9A1900">// but I have not personally tried them. Remove this warning trap and try it!</font></i>
<font color="#009900">int</font>
<b><font color="#000000"><a name="50">main</a></font></b> <font color="#990000">(</font><font color="#009900">void</font><font color="#990000">)</font>
<font color="#FF0000">{</font>
<b><font color="#000000">MY_SPI_SLAVE_1_SELECT_INIT</font></b> <font color="#990000">();</font>
<b><font color="#000000"><a href="spi.c.html#22">spi_init</a></font></b> <font color="#990000">();</font>
<b><font color="#000000"><a href="spi.c.html#62">spi_set_data_order</a></font></b> <font color="#990000">(</font><a href="spi.h.html#110">SPI_DATA_ORDER_MSB_FIRST</a><font color="#990000">);</font>
<b><font color="#000000"><a href="spi.c.html#80">spi_set_data_mode</a></font></b> <font color="#990000">(</font><a href="spi.h.html#130">SPI_DATA_MODE_0</a><font color="#990000">);</font>
<i><font color="#9A1900">// We're going to use a loop over the clock divider settings, so here we</font></i>
<i><font color="#9A1900">// verify that the interface gives them the the endpoint values we expect.</font></i>
<b><font color="#000000">assert</font></b> <font color="#990000">(</font><a href="spi.h.html#115">SPI_CLOCK_DIVIDER_DIV4</a> <font color="#990000">==</font> <font color="#993399">0x00</font><font color="#990000">);</font>
<b><font color="#000000">assert</font></b> <font color="#990000">(</font><a href="spi.h.html#121">SPI_CLOCK_DIVIDER_DIV32</a> <font color="#990000">==</font> <font color="#993399">0x06</font><font color="#990000">);</font>
<i><font color="#9A1900">// Smallest, Largest Clock divider Setting</font></i>
<font color="#008080">uint8_t</font> scs <font color="#990000">=</font> <a href="spi.h.html#115">SPI_CLOCK_DIVIDER_DIV4</a><font color="#990000">,</font> lcs <font color="#990000">=</font> <a href="spi.h.html#121">SPI_CLOCK_DIVIDER_DIV32</a><font color="#990000">;</font>
<i><font color="#9A1900">// For each clock divider setting...</font></i>
<b><font color="#0000FF">for</font></b> <font color="#990000">(</font> <font color="#008080">uint8_t</font> cds <font color="#990000">=</font> scs <font color="#990000">;</font> cds <font color="#990000"><=</font> lcs <font color="#990000">;</font> cds<font color="#990000">++</font> <font color="#990000">)</font> <font color="#FF0000">{</font>
<b><font color="#000000"><a href="spi.c.html#89">spi_set_clock_divider</a></font></b> <font color="#990000">(</font>cds<font color="#990000">);</font>
<i><font color="#9A1900">// Number of different resistor settings we test</font></i>
<font color="#009900">int</font> <b><font color="#0000FF">const</font></b> test_steps <font color="#990000">=</font> <font color="#993399">5</font><font color="#990000">;</font>
<i><font color="#9A1900">// For each different resistance setting we want to test...</font></i>
<b><font color="#0000FF">for</font></b> <font color="#990000">(</font> <font color="#009900">int</font> ii <font color="#990000">=</font> <font color="#993399">0</font> <font color="#990000">;</font> ii <font color="#990000"><</font> test_steps <font color="#990000">;</font> ii<font color="#990000">++</font> <font color="#990000">)</font> <font color="#FF0000">{</font>
<b><font color="#000000">MY_SPI_SLAVE_1_SELECT_SET_LOW</font></b> <font color="#990000">();</font>
uint8_t <font color="#008080">const</font> channel_six_address <font color="#990000">=</font> <font color="#993399">0x05</font><font color="#990000">;</font> <i><font color="#9A1900">// From AD5206 datasheet</font></i>
<b><font color="#000000"><a href="spi.c.html#97">spi_transfer</a></font></b> <font color="#990000">(</font>channel_six_address<font color="#990000">);</font>
<b><font color="#000000"><a href="spi.c.html#97">spi_transfer</a></font></b> <font color="#990000">(</font>ii <font color="#990000">*</font> <font color="#993399">255</font> <font color="#990000">/</font> <font color="#993399">4</font><font color="#990000">);</font>
<b><font color="#000000">MY_SPI_SLAVE_1_SELECT_SET_HIGH</font></b> <font color="#990000">();</font>
<font color="#009900">double</font> <b><font color="#0000FF">const</font></b> seconds_per_step <font color="#990000">=</font> <font color="#993399">5.0</font><font color="#990000">;</font>
<b><font color="#000000">_delay_ms</font></b> <font color="#990000">(</font><font color="#993399">1000.0</font> <font color="#990000">*</font> seconds_per_step<font color="#990000">);</font>
<font color="#FF0000">}</font>
<font color="#FF0000">}</font>
<font color="#FF0000">}</font>
</tt></pre>
|
rktrlng/avrm
|
cduino-1.2.0/xlinked_source_html/spi_test.c.html
|
HTML
|
gpl-2.0
| 11,097
|
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Linq;
using Server.Commands;
namespace Server.Gumps.Compendium
{
public static class LinqHelper
{
/// Taken from: http://stackoverflow.com/questions/2471588/how-to-get-index-using-linq
///<summary>Finds the index of the first item matching an expression in an enumerable.</summary>
///<param name="items">The enumerable to search.</param>
///<param name="predicate">The expression to test the items against.</param>
///<returns>The index of the first matching item, or -1 if no items match.</returns>
public static int FindIndex<T>(this IEnumerable<T> items, Func<T, bool> predicate)
{
if (items == null) throw new ArgumentNullException("items");
if (predicate == null) throw new ArgumentNullException("predicate");
int retVal = 0;
foreach (var item in items)
{
if (predicate(item)) return retVal;
retVal++;
}
return -1;
}
}
public class Compendium
{
public const AccessLevel ACCESS_LEVEL_REQUIRED_TO_EDIT_ARTICLES = AccessLevel.Developer;
public const string COMPENDIUM_ROOT_FOLDER_NAME = "Compendium";
public const string YELLOW_TEXT_WEB_COLOR = "#FDBF3E";
public const string CONTENT_TEXT_WEB_COLOR = "#111111";
public const bool LOG_MESSAGES = false;
public const bool LOG_ERRORS = true;
public static Dictionary<string, CompendiumPageRenderer> g_CompendiumRenderers = new Dictionary<string, CompendiumPageRenderer>();
public static void Configure()
{
EventSink.WorldLoad += new WorldLoadEventHandler(EventSink_WorldLoad);
}
public static void EventSink_WorldLoad()
{
Console.WriteLine("Loading Compendium Page Renderers");
if (!Directory.Exists(CompendiumRootPath))
{
Directory.CreateDirectory(CompendiumRootPath);
return;
}
string[] availableFiles = Directory.GetFiles(CompendiumRootPath, "*.xml");
foreach (string filename in availableFiles)
{
try
{
XDocument document = XDocument.Load(Path.Combine(CompendiumRootPath, filename));
CompendiumPageRenderer renderer = CompendiumPageRenderer.Deserialize(document);
g_CompendiumRenderers.Add(renderer.Name, renderer);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
public static string CompendiumRootPath
{
get
{
return Path.Combine(Core.BaseDirectory, COMPENDIUM_ROOT_FOLDER_NAME);
}
}
public static void Initialize()
{
CommandSystem.Register("ViewPage", AccessLevel.GameMaster, new CommandEventHandler(ViewPage_OnCommand));
}
[Usage("ViewPage <pagename>")]
[Description("Open the <pagename> gump from the Compendium")]
public static void ViewPage_OnCommand(CommandEventArgs e)
{
Mobile caller = e.Mobile;
if (caller.HasGump(typeof(CompendiumPageRenderer)))
caller.CloseGump(typeof(CompendiumPageRenderer));
if (e.Arguments.Length > 0)
{
if (e.Arguments[0].IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) >= 0)
{
caller.SendMessage("That page name has illegal characters in it.");
return;
}
if (g_CompendiumRenderers.ContainsKey(e.Arguments[0]))
{
CompendiumPageGump gump = new CompendiumPageGump(caller, g_CompendiumRenderers[e.Arguments[0]]);
gump.Send();
}
else
{
caller.SendMessage("That page does not exist.");
}
}
else
caller.SendMessage("You must specify a page name to view.");
}
}
}
|
Ultima-Lokai/ServUO-Lokai
|
Scripts/Custom Systems/Compendium/Compendium.cs
|
C#
|
gpl-2.0
| 4,269
|
!=====================================================================
!
! S p e c f e m 3 D G l o b e V e r s i o n 7 . 0
! --------------------------------------------------
!
! Main historical authors: Dimitri Komatitsch and Jeroen Tromp
! Princeton University, USA
! and CNRS / University of Marseille, France
! (there are currently many more authors!)
! (c) Princeton University and CNRS / University of Marseille, April 2014
!
! 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.
!
!=====================================================================
!--------------------------------------------------------------------------------------------------
! 1066A
!
! Spherically symmetric earth model 1066A [Gilbert and Dziewonski, 1975].
!
! When ATTENUATION is on, it uses an unpublished 1D attenuation model from Scripps.
!--------------------------------------------------------------------------------------------------
module model_1066a_par
! number of layers in DATA/1066a/1066a.dat
integer, parameter :: NR_1066A = 160
! model_1066a_variables
double precision, dimension(:),allocatable :: &
M1066a_V_radius_1066a,M1066a_V_density_1066a, &
M1066a_V_vp_1066a,M1066a_V_vs_1066a, &
M1066a_V_Qkappa_1066a,M1066a_V_Qmu_1066a
end module model_1066a_par
!
!--------------------------------------------------------------------------------------------------
!
subroutine model_1066a_broadcast(CRUSTAL)
! standard routine to setup model
use constants, only: myrank
use model_1066a_par
implicit none
logical :: CRUSTAL
! local parameters
integer :: ier
! allocates model arrays
allocate(M1066a_V_radius_1066a(NR_1066A), &
M1066a_V_density_1066a(NR_1066A), &
M1066a_V_vp_1066a(NR_1066A), &
M1066a_V_vs_1066a(NR_1066A), &
M1066a_V_Qkappa_1066a(NR_1066A), &
M1066a_V_Qmu_1066a(NR_1066A), &
stat=ier)
if (ier /= 0 ) call exit_MPI(myrank,'Error allocating M1066a_V arrays')
! all processes will define same parameters
call define_model_1066a(CRUSTAL)
end subroutine model_1066a_broadcast
!
!-------------------------------------------------------------------------------------------------
!
subroutine model_1066a(x,rho,vp,vs,Qkappa,Qmu,iregion_code)
use constants
use model_1066a_par
implicit none
! input:
! radius r: meters
! output:
! density rho: kg/m^3
! compressional wave speed vp: km/s
! shear wave speed vs: km/s
double precision :: x,rho,vp,vs,Qmu,Qkappa
integer :: iregion_code
! local parameters
double precision :: r,frac,scaleval
integer :: i
! compute real physical radius in meters
r = x * R_EARTH
i = 1
do while(r >= M1066a_V_radius_1066a(i) .and. i /= NR_1066A)
i = i + 1
enddo
! make sure we stay in the right region and never take a point above
! and a point below the ICB or the CMB and interpolate between them,
! which would lead to a wrong value (keeping in mind that we interpolate
! between points i-1 and i below)
if (iregion_code == IREGION_INNER_CORE .and. i > 33) i = 33
if (iregion_code == IREGION_OUTER_CORE .and. i < 35) i = 35
if (iregion_code == IREGION_OUTER_CORE .and. i > 66) i = 66
if (iregion_code == IREGION_CRUST_MANTLE .and. i < 68) i = 68
if (i == 1) then
rho = M1066a_V_density_1066a(i)
vp = M1066a_V_vp_1066a(i)
vs = M1066a_V_vs_1066a(i)
Qmu = M1066a_V_Qmu_1066a(i)
Qkappa = M1066a_V_Qkappa_1066a(i)
else
! interpolate from radius_1066a(i-1) to r using the values at i-1 and i
frac = (r-M1066a_V_radius_1066a(i-1))/(M1066a_V_radius_1066a(i)-M1066a_V_radius_1066a(i-1))
rho = M1066a_V_density_1066a(i-1) + frac * (M1066a_V_density_1066a(i)-M1066a_V_density_1066a(i-1))
vp = M1066a_V_vp_1066a(i-1) + frac * (M1066a_V_vp_1066a(i)-M1066a_V_vp_1066a(i-1))
vs = M1066a_V_vs_1066a(i-1) + frac * (M1066a_V_vs_1066a(i)-M1066a_V_vs_1066a(i-1))
Qmu = M1066a_V_Qmu_1066a(i-1) + frac * (M1066a_V_Qmu_1066a(i)-M1066a_V_Qmu_1066a(i-1))
Qkappa = M1066a_V_Qkappa_1066a(i-1) + frac * (M1066a_V_Qkappa_1066a(i)-M1066a_V_Qkappa_1066a(i-1))
endif
! make sure Vs is zero in the outer core even if roundoff errors on depth
! also set fictitious attenuation to a very high value (attenuation is not used in the fluid)
if (iregion_code == IREGION_OUTER_CORE) then
vs = 0.d0
Qkappa = 3000.d0
Qmu = 3000.d0
endif
! non-dimensionalize
! time scaling (s^{-1}) is done with scaleval
scaleval=dsqrt(PI*GRAV*RHOAV)
rho=rho*1000.0d0/RHOAV
vp=vp*1000.0d0/(R_EARTH*scaleval)
vs=vs*1000.0d0/(R_EARTH*scaleval)
end subroutine model_1066a
!-------------------
subroutine define_model_1066a(USE_EXTERNAL_CRUSTAL_MODEL)
use constants
use model_1066a_par
implicit none
logical :: USE_EXTERNAL_CRUSTAL_MODEL
! local parameters
integer :: i
! define all the values in the model
M1066a_V_radius_1066a( 1) = 0.d0
M1066a_V_radius_1066a( 2) = 38400.d0
M1066a_V_radius_1066a( 3) = 76810.d0
M1066a_V_radius_1066a( 4) = 115210.d0
M1066a_V_radius_1066a( 5) = 153610.d0
M1066a_V_radius_1066a( 6) = 192020.d0
M1066a_V_radius_1066a( 7) = 230420.d0
M1066a_V_radius_1066a( 8) = 268820.d0
M1066a_V_radius_1066a( 9) = 307220.d0
M1066a_V_radius_1066a( 10) = 345630.d0
M1066a_V_radius_1066a( 11) = 384030.d0
M1066a_V_radius_1066a( 12) = 422430.d0
M1066a_V_radius_1066a( 13) = 460840.d0
M1066a_V_radius_1066a( 14) = 499240.d0
M1066a_V_radius_1066a( 15) = 537640.d0
M1066a_V_radius_1066a( 16) = 576050.d0
M1066a_V_radius_1066a( 17) = 614450.d0
M1066a_V_radius_1066a( 18) = 652850.d0
M1066a_V_radius_1066a( 19) = 691260.d0
M1066a_V_radius_1066a( 20) = 729660.d0
M1066a_V_radius_1066a( 21) = 768060.d0
M1066a_V_radius_1066a( 22) = 806460.d0
M1066a_V_radius_1066a( 23) = 844870.d0
M1066a_V_radius_1066a( 24) = 883270.d0
M1066a_V_radius_1066a( 25) = 921670.d0
M1066a_V_radius_1066a( 26) = 960080.d0
M1066a_V_radius_1066a( 27) = 998480.d0
M1066a_V_radius_1066a( 28) = 1036880.d0
M1066a_V_radius_1066a( 29) = 1075290.d0
M1066a_V_radius_1066a( 30) = 1113690.d0
M1066a_V_radius_1066a( 31) = 1152090.d0
M1066a_V_radius_1066a( 32) = 1190500.d0
M1066a_V_radius_1066a( 33) = 1229480.d0
M1066a_V_radius_1066a( 34) = 1229480.d0
M1066a_V_radius_1066a( 35) = 1299360.d0
M1066a_V_radius_1066a( 36) = 1369820.d0
M1066a_V_radius_1066a( 37) = 1440280.d0
M1066a_V_radius_1066a( 38) = 1510740.d0
M1066a_V_radius_1066a( 39) = 1581190.d0
M1066a_V_radius_1066a( 40) = 1651650.d0
M1066a_V_radius_1066a( 41) = 1722110.d0
M1066a_V_radius_1066a( 42) = 1792570.d0
M1066a_V_radius_1066a( 43) = 1863030.d0
M1066a_V_radius_1066a( 44) = 1933490.d0
M1066a_V_radius_1066a( 45) = 2003950.d0
M1066a_V_radius_1066a( 46) = 2074410.d0
M1066a_V_radius_1066a( 47) = 2144870.d0
M1066a_V_radius_1066a( 48) = 2215330.d0
M1066a_V_radius_1066a( 49) = 2285790.d0
M1066a_V_radius_1066a( 50) = 2356240.d0
M1066a_V_radius_1066a( 51) = 2426700.d0
M1066a_V_radius_1066a( 52) = 2497160.d0
M1066a_V_radius_1066a( 53) = 2567620.d0
M1066a_V_radius_1066a( 54) = 2638080.d0
M1066a_V_radius_1066a( 55) = 2708540.d0
M1066a_V_radius_1066a( 56) = 2779000.d0
M1066a_V_radius_1066a( 57) = 2849460.d0
M1066a_V_radius_1066a( 58) = 2919920.d0
M1066a_V_radius_1066a( 59) = 2990380.d0
M1066a_V_radius_1066a( 60) = 3060840.d0
M1066a_V_radius_1066a( 61) = 3131300.d0
M1066a_V_radius_1066a( 62) = 3201750.d0
M1066a_V_radius_1066a( 63) = 3272210.d0
M1066a_V_radius_1066a( 64) = 3342670.d0
M1066a_V_radius_1066a( 65) = 3413130.d0
M1066a_V_radius_1066a( 66) = 3484300.d0
M1066a_V_radius_1066a( 67) = 3484300.d0
M1066a_V_radius_1066a( 68) = 3518220.d0
M1066a_V_radius_1066a( 69) = 3552850.d0
M1066a_V_radius_1066a( 70) = 3587490.d0
M1066a_V_radius_1066a( 71) = 3622120.d0
M1066a_V_radius_1066a( 72) = 3656750.d0
M1066a_V_radius_1066a( 73) = 3691380.d0
M1066a_V_radius_1066a( 74) = 3726010.d0
M1066a_V_radius_1066a( 75) = 3760640.d0
M1066a_V_radius_1066a( 76) = 3795270.d0
M1066a_V_radius_1066a( 77) = 3829910.d0
M1066a_V_radius_1066a( 78) = 3864540.d0
M1066a_V_radius_1066a( 79) = 3899170.d0
M1066a_V_radius_1066a( 80) = 3933800.d0
M1066a_V_radius_1066a( 81) = 3968430.d0
M1066a_V_radius_1066a( 82) = 4003060.d0
M1066a_V_radius_1066a( 83) = 4037690.d0
M1066a_V_radius_1066a( 84) = 4072330.d0
M1066a_V_radius_1066a( 85) = 4106960.d0
M1066a_V_radius_1066a( 86) = 4141590.d0
M1066a_V_radius_1066a( 87) = 4176220.d0
M1066a_V_radius_1066a( 88) = 4210850.d0
M1066a_V_radius_1066a( 89) = 4245480.d0
M1066a_V_radius_1066a( 90) = 4280110.d0
M1066a_V_radius_1066a( 91) = 4314740.d0
M1066a_V_radius_1066a( 92) = 4349380.d0
M1066a_V_radius_1066a( 93) = 4384010.d0
M1066a_V_radius_1066a( 94) = 4418640.d0
M1066a_V_radius_1066a( 95) = 4453270.d0
M1066a_V_radius_1066a( 96) = 4487900.d0
M1066a_V_radius_1066a( 97) = 4522530.d0
M1066a_V_radius_1066a( 98) = 4557160.d0
M1066a_V_radius_1066a( 99) = 4591800.d0
M1066a_V_radius_1066a(100) = 4626430.d0
M1066a_V_radius_1066a(101) = 4661060.d0
M1066a_V_radius_1066a(102) = 4695690.d0
M1066a_V_radius_1066a(103) = 4730320.d0
M1066a_V_radius_1066a(104) = 4764950.d0
M1066a_V_radius_1066a(105) = 4799580.d0
M1066a_V_radius_1066a(106) = 4834220.d0
M1066a_V_radius_1066a(107) = 4868850.d0
M1066a_V_radius_1066a(108) = 4903480.d0
M1066a_V_radius_1066a(109) = 4938110.d0
M1066a_V_radius_1066a(110) = 4972740.d0
M1066a_V_radius_1066a(111) = 5007370.d0
M1066a_V_radius_1066a(112) = 5042000.d0
M1066a_V_radius_1066a(113) = 5076640.d0
M1066a_V_radius_1066a(114) = 5111270.d0
M1066a_V_radius_1066a(115) = 5145900.d0
M1066a_V_radius_1066a(116) = 5180530.d0
M1066a_V_radius_1066a(117) = 5215160.d0
M1066a_V_radius_1066a(118) = 5249790.d0
M1066a_V_radius_1066a(119) = 5284420.d0
M1066a_V_radius_1066a(120) = 5319060.d0
M1066a_V_radius_1066a(121) = 5353690.d0
M1066a_V_radius_1066a(122) = 5388320.d0
M1066a_V_radius_1066a(123) = 5422950.d0
M1066a_V_radius_1066a(124) = 5457580.d0
M1066a_V_radius_1066a(125) = 5492210.d0
M1066a_V_radius_1066a(126) = 5526840.d0
M1066a_V_radius_1066a(127) = 5561470.d0
M1066a_V_radius_1066a(128) = 5596110.d0
M1066a_V_radius_1066a(129) = 5630740.d0
M1066a_V_radius_1066a(130) = 5665370.d0
M1066a_V_radius_1066a(131) = 5700000.d0
M1066a_V_radius_1066a(132) = 5700000.d0
M1066a_V_radius_1066a(133) = 5731250.d0
M1066a_V_radius_1066a(134) = 5762500.d0
M1066a_V_radius_1066a(135) = 5793750.d0
M1066a_V_radius_1066a(136) = 5825000.d0
M1066a_V_radius_1066a(137) = 5856250.d0
M1066a_V_radius_1066a(138) = 5887500.d0
M1066a_V_radius_1066a(139) = 5918750.d0
M1066a_V_radius_1066a(140) = 5950000.d0
M1066a_V_radius_1066a(141) = 5950000.d0
M1066a_V_radius_1066a(142) = 5975630.d0
M1066a_V_radius_1066a(143) = 6001250.d0
M1066a_V_radius_1066a(144) = 6026880.d0
M1066a_V_radius_1066a(145) = 6052500.d0
M1066a_V_radius_1066a(146) = 6078130.d0
M1066a_V_radius_1066a(147) = 6103750.d0
M1066a_V_radius_1066a(148) = 6129380.d0
M1066a_V_radius_1066a(149) = 6155000.d0
M1066a_V_radius_1066a(150) = 6180630.d0
M1066a_V_radius_1066a(151) = 6206250.d0
M1066a_V_radius_1066a(152) = 6231880.d0
M1066a_V_radius_1066a(153) = 6257500.d0
M1066a_V_radius_1066a(154) = 6283130.d0
M1066a_V_radius_1066a(155) = 6308750.d0
M1066a_V_radius_1066a(156) = 6334380.d0
M1066a_V_radius_1066a(157) = 6360000.d0
M1066a_V_radius_1066a(158) = 6360000.d0
M1066a_V_radius_1066a(159) = 6365500.d0
M1066a_V_radius_1066a(160) = 6371000.d0
M1066a_V_density_1066a( 1) = 13.42903d0
M1066a_V_density_1066a( 2) = 13.42563d0
M1066a_V_density_1066a( 3) = 13.41913d0
M1066a_V_density_1066a( 4) = 13.41353d0
M1066a_V_density_1066a( 5) = 13.40723d0
M1066a_V_density_1066a( 6) = 13.40032d0
M1066a_V_density_1066a( 7) = 13.39292d0
M1066a_V_density_1066a( 8) = 13.38471d0
M1066a_V_density_1066a( 9) = 13.3754d0
M1066a_V_density_1066a( 10) = 13.3649d0
M1066a_V_density_1066a( 11) = 13.35279d0
M1066a_V_density_1066a( 12) = 13.33898d0
M1066a_V_density_1066a( 13) = 13.32387d0
M1066a_V_density_1066a( 14) = 13.30785d0
M1066a_V_density_1066a( 15) = 13.29144d0
M1066a_V_density_1066a( 16) = 13.27503d0
M1066a_V_density_1066a( 17) = 13.25891d0
M1066a_V_density_1066a( 18) = 13.2431d0
M1066a_V_density_1066a( 19) = 13.22758d0
M1066a_V_density_1066a( 20) = 13.21236d0
M1066a_V_density_1066a( 21) = 13.19725d0
M1066a_V_density_1066a( 22) = 13.18233d0
M1066a_V_density_1066a( 23) = 13.16751d0
M1066a_V_density_1066a( 24) = 13.15278d0
M1066a_V_density_1066a( 25) = 13.13826d0
M1066a_V_density_1066a( 26) = 13.12394d0
M1066a_V_density_1066a( 27) = 13.10952d0
M1066a_V_density_1066a( 28) = 13.09539d0
M1066a_V_density_1066a( 29) = 13.08116d0
M1066a_V_density_1066a( 30) = 13.06704d0
M1066a_V_density_1066a( 31) = 13.05251d0
M1066a_V_density_1066a( 32) = 13.03858d0
M1066a_V_density_1066a( 33) = 13.02875d0
M1066a_V_density_1066a( 34) = 12.16065d0
M1066a_V_density_1066a( 35) = 12.11699d0
M1066a_V_density_1066a( 36) = 12.07483d0
M1066a_V_density_1066a( 37) = 12.03307d0
M1066a_V_density_1066a( 38) = 11.9916d0
M1066a_V_density_1066a( 39) = 11.95073d0
M1066a_V_density_1066a( 40) = 11.91046d0
M1066a_V_density_1066a( 41) = 11.86938d0
M1066a_V_density_1066a( 42) = 11.82481d0
M1066a_V_density_1066a( 43) = 11.77532d0
M1066a_V_density_1066a( 44) = 11.72204d0
M1066a_V_density_1066a( 45) = 11.66655d0
M1066a_V_density_1066a( 46) = 11.60856d0
M1066a_V_density_1066a( 47) = 11.54696d0
M1066a_V_density_1066a( 48) = 11.48096d0
M1066a_V_density_1066a( 49) = 11.41166d0
M1066a_V_density_1066a( 50) = 11.34116d0
M1066a_V_density_1066a( 51) = 11.27055d0
M1066a_V_density_1066a( 52) = 11.19824d0
M1066a_V_density_1066a( 53) = 11.12142d0
M1066a_V_density_1066a( 54) = 11.03841d0
M1066a_V_density_1066a( 55) = 10.95119d0
M1066a_V_density_1066a( 56) = 10.86316d0
M1066a_V_density_1066a( 57) = 10.77703d0
M1066a_V_density_1066a( 58) = 10.6925d0
M1066a_V_density_1066a( 59) = 10.60767d0
M1066a_V_density_1066a( 60) = 10.52073d0
M1066a_V_density_1066a( 61) = 10.4312d0
M1066a_V_density_1066a( 62) = 10.33775d0
M1066a_V_density_1066a( 63) = 10.23961d0
M1066a_V_density_1066a( 64) = 10.13786d0
M1066a_V_density_1066a( 65) = 10.0323d0
M1066a_V_density_1066a( 66) = 9.91745d0
M1066a_V_density_1066a( 67) = 5.53205d0
M1066a_V_density_1066a( 68) = 5.52147d0
M1066a_V_density_1066a( 69) = 5.50959d0
M1066a_V_density_1066a( 70) = 5.49821d0
M1066a_V_density_1066a( 71) = 5.48673d0
M1066a_V_density_1066a( 72) = 5.47495d0
M1066a_V_density_1066a( 73) = 5.46297d0
M1066a_V_density_1066a( 74) = 5.45049d0
M1066a_V_density_1066a( 75) = 5.43741d0
M1066a_V_density_1066a( 76) = 5.42382d0
M1066a_V_density_1066a( 77) = 5.40934d0
M1066a_V_density_1066a( 78) = 5.39375d0
M1066a_V_density_1066a( 79) = 5.37717d0
M1066a_V_density_1066a( 80) = 5.35958d0
M1066a_V_density_1066a( 81) = 5.34079d0
M1066a_V_density_1066a( 82) = 5.321d0
M1066a_V_density_1066a( 83) = 5.30031d0
M1066a_V_density_1066a( 84) = 5.27902d0
M1066a_V_density_1066a( 85) = 5.25733d0
M1066a_V_density_1066a( 86) = 5.23554d0
M1066a_V_density_1066a( 87) = 5.21375d0
M1066a_V_density_1066a( 88) = 5.19196d0
M1066a_V_density_1066a( 89) = 5.17056d0
M1066a_V_density_1066a( 90) = 5.14937d0
M1066a_V_density_1066a( 91) = 5.12827d0
M1066a_V_density_1066a( 92) = 5.10758d0
M1066a_V_density_1066a( 93) = 5.08728d0
M1066a_V_density_1066a( 94) = 5.06738d0
M1066a_V_density_1066a( 95) = 5.04769d0
M1066a_V_density_1066a( 96) = 5.02809d0
M1066a_V_density_1066a( 97) = 5.00869d0
M1066a_V_density_1066a( 98) = 4.98929d0
M1066a_V_density_1066a( 99) = 4.96968d0
M1066a_V_density_1066a(100) = 4.95008d0
M1066a_V_density_1066a(101) = 4.93048d0
M1066a_V_density_1066a(102) = 4.91128d0
M1066a_V_density_1066a(103) = 4.89257d0
M1066a_V_density_1066a(104) = 4.87447d0
M1066a_V_density_1066a(105) = 4.85716d0
M1066a_V_density_1066a(106) = 4.84095d0
M1066a_V_density_1066a(107) = 4.82554d0
M1066a_V_density_1066a(108) = 4.81084d0
M1066a_V_density_1066a(109) = 4.79683d0
M1066a_V_density_1066a(110) = 4.78312d0
M1066a_V_density_1066a(111) = 4.76951d0
M1066a_V_density_1066a(112) = 4.7553d0
M1066a_V_density_1066a(113) = 4.74008d0
M1066a_V_density_1066a(114) = 4.72317d0
M1066a_V_density_1066a(115) = 4.70426d0
M1066a_V_density_1066a(116) = 4.68264d0
M1066a_V_density_1066a(117) = 4.65863d0
M1066a_V_density_1066a(118) = 4.63351d0
M1066a_V_density_1066a(119) = 4.60859d0
M1066a_V_density_1066a(120) = 4.58538d0
M1066a_V_density_1066a(121) = 4.56536d0
M1066a_V_density_1066a(122) = 4.55044d0
M1066a_V_density_1066a(123) = 4.54072d0
M1066a_V_density_1066a(124) = 4.5348d0
M1066a_V_density_1066a(125) = 4.53478d0
M1066a_V_density_1066a(126) = 4.53275d0
M1066a_V_density_1066a(127) = 4.50893d0
M1066a_V_density_1066a(128) = 4.46541d0
M1066a_V_density_1066a(129) = 4.40098d0
M1066a_V_density_1066a(130) = 4.31686d0
M1066a_V_density_1066a(131) = 4.20553d0
M1066a_V_density_1066a(132) = 4.20553d0
M1066a_V_density_1066a(133) = 4.10272d0
M1066a_V_density_1066a(134) = 4.0225d0
M1066a_V_density_1066a(135) = 3.95789d0
M1066a_V_density_1066a(136) = 3.89997d0
M1066a_V_density_1066a(137) = 3.84675d0
M1066a_V_density_1066a(138) = 3.80144d0
M1066a_V_density_1066a(139) = 3.76072d0
M1066a_V_density_1066a(140) = 3.7084d0
M1066a_V_density_1066a(141) = 3.7084d0
M1066a_V_density_1066a(142) = 3.6537d0
M1066a_V_density_1066a(143) = 3.5964d0
M1066a_V_density_1066a(144) = 3.54731d0
M1066a_V_density_1066a(145) = 3.50511d0
M1066a_V_density_1066a(146) = 3.46861d0
M1066a_V_density_1066a(147) = 3.43851d0
M1066a_V_density_1066a(148) = 3.41471d0
M1066a_V_density_1066a(149) = 3.39751d0
M1066a_V_density_1066a(150) = 3.3882d0
M1066a_V_density_1066a(151) = 3.382d0
M1066a_V_density_1066a(152) = 3.3745d0
M1066a_V_density_1066a(153) = 3.3671d0
M1066a_V_density_1066a(154) = 3.3598d0
M1066a_V_density_1066a(155) = 3.35259d0
M1066a_V_density_1066a(156) = 3.34549d0
M1066a_V_density_1066a(157) = 3.33828d0
M1066a_V_density_1066a(158) = 2.17798d0
M1066a_V_density_1066a(159) = 2.17766d0
M1066a_V_density_1066a(160) = 2.17734d0
M1066a_V_vp_1066a( 1) = 11.3383d0
M1066a_V_vp_1066a( 2) = 11.3374d0
M1066a_V_vp_1066a( 3) = 11.3347d0
M1066a_V_vp_1066a( 4) = 11.3301d0
M1066a_V_vp_1066a( 5) = 11.3237d0
M1066a_V_vp_1066a( 6) = 11.3155d0
M1066a_V_vp_1066a( 7) = 11.3056d0
M1066a_V_vp_1066a( 8) = 11.294d0
M1066a_V_vp_1066a( 9) = 11.281d0
M1066a_V_vp_1066a( 10) = 11.2666d0
M1066a_V_vp_1066a( 11) = 11.2512d0
M1066a_V_vp_1066a( 12) = 11.2349d0
M1066a_V_vp_1066a( 13) = 11.2181d0
M1066a_V_vp_1066a( 14) = 11.201d0
M1066a_V_vp_1066a( 15) = 11.184d0
M1066a_V_vp_1066a( 16) = 11.1672d0
M1066a_V_vp_1066a( 17) = 11.1508d0
M1066a_V_vp_1066a( 18) = 11.1351d0
M1066a_V_vp_1066a( 19) = 11.1201d0
M1066a_V_vp_1066a( 20) = 11.1059d0
M1066a_V_vp_1066a( 21) = 11.0924d0
M1066a_V_vp_1066a( 22) = 11.0798d0
M1066a_V_vp_1066a( 23) = 11.0678d0
M1066a_V_vp_1066a( 24) = 11.0564d0
M1066a_V_vp_1066a( 25) = 11.0455d0
M1066a_V_vp_1066a( 26) = 11.035d0
M1066a_V_vp_1066a( 27) = 11.0248d0
M1066a_V_vp_1066a( 28) = 11.0149d0
M1066a_V_vp_1066a( 29) = 11.0051d0
M1066a_V_vp_1066a( 30) = 10.9953d0
M1066a_V_vp_1066a( 31) = 10.9857d0
M1066a_V_vp_1066a( 32) = 10.9756d0
M1066a_V_vp_1066a( 33) = 10.9687d0
M1066a_V_vp_1066a( 34) = 10.414d0
M1066a_V_vp_1066a( 35) = 10.3518d0
M1066a_V_vp_1066a( 36) = 10.2922d0
M1066a_V_vp_1066a( 37) = 10.2351d0
M1066a_V_vp_1066a( 38) = 10.1808d0
M1066a_V_vp_1066a( 39) = 10.1297d0
M1066a_V_vp_1066a( 40) = 10.0788d0
M1066a_V_vp_1066a( 41) = 10.0284d0
M1066a_V_vp_1066a( 42) = 9.9788d0
M1066a_V_vp_1066a( 43) = 9.9307d0
M1066a_V_vp_1066a( 44) = 9.8836d0
M1066a_V_vp_1066a( 45) = 9.8353d0
M1066a_V_vp_1066a( 46) = 9.7825d0
M1066a_V_vp_1066a( 47) = 9.7211d0
M1066a_V_vp_1066a( 48) = 9.6521d0
M1066a_V_vp_1066a( 49) = 9.5806d0
M1066a_V_vp_1066a( 50) = 9.5115d0
M1066a_V_vp_1066a( 51) = 9.4465d0
M1066a_V_vp_1066a( 52) = 9.3828d0
M1066a_V_vp_1066a( 53) = 9.3166d0
M1066a_V_vp_1066a( 54) = 9.2442d0
M1066a_V_vp_1066a( 55) = 9.1658d0
M1066a_V_vp_1066a( 56) = 9.0833d0
M1066a_V_vp_1066a( 57) = 8.9987d0
M1066a_V_vp_1066a( 58) = 8.9116d0
M1066a_V_vp_1066a( 59) = 8.8201d0
M1066a_V_vp_1066a( 60) = 8.7223d0
M1066a_V_vp_1066a( 61) = 8.6171d0
M1066a_V_vp_1066a( 62) = 8.503d0
M1066a_V_vp_1066a( 63) = 8.3807d0
M1066a_V_vp_1066a( 64) = 8.2556d0
M1066a_V_vp_1066a( 65) = 8.1318d0
M1066a_V_vp_1066a( 66) = 8.0112d0
M1066a_V_vp_1066a( 67) = 13.7172d0
M1066a_V_vp_1066a( 68) = 13.7134d0
M1066a_V_vp_1066a( 69) = 13.7089d0
M1066a_V_vp_1066a( 70) = 13.6806d0
M1066a_V_vp_1066a( 71) = 13.6517d0
M1066a_V_vp_1066a( 72) = 13.6251d0
M1066a_V_vp_1066a( 73) = 13.5916d0
M1066a_V_vp_1066a( 74) = 13.5564d0
M1066a_V_vp_1066a( 75) = 13.5165d0
M1066a_V_vp_1066a( 76) = 13.4725d0
M1066a_V_vp_1066a( 77) = 13.4248d0
M1066a_V_vp_1066a( 78) = 13.3742d0
M1066a_V_vp_1066a( 79) = 13.3216d0
M1066a_V_vp_1066a( 80) = 13.2679d0
M1066a_V_vp_1066a( 81) = 13.2142d0
M1066a_V_vp_1066a( 82) = 13.1619d0
M1066a_V_vp_1066a( 83) = 13.1114d0
M1066a_V_vp_1066a( 84) = 13.0631d0
M1066a_V_vp_1066a( 85) = 13.0174d0
M1066a_V_vp_1066a( 86) = 12.9745d0
M1066a_V_vp_1066a( 87) = 12.9346d0
M1066a_V_vp_1066a( 88) = 12.8977d0
M1066a_V_vp_1066a( 89) = 12.8635d0
M1066a_V_vp_1066a( 90) = 12.8318d0
M1066a_V_vp_1066a( 91) = 12.8022d0
M1066a_V_vp_1066a( 92) = 12.7739d0
M1066a_V_vp_1066a( 93) = 12.7463d0
M1066a_V_vp_1066a( 94) = 12.7186d0
M1066a_V_vp_1066a( 95) = 12.6903d0
M1066a_V_vp_1066a( 96) = 12.661d0
M1066a_V_vp_1066a( 97) = 12.6302d0
M1066a_V_vp_1066a( 98) = 12.5978d0
M1066a_V_vp_1066a( 99) = 12.5637d0
M1066a_V_vp_1066a(100) = 12.5276d0
M1066a_V_vp_1066a(101) = 12.4893d0
M1066a_V_vp_1066a(102) = 12.4485d0
M1066a_V_vp_1066a(103) = 12.4052d0
M1066a_V_vp_1066a(104) = 12.3592d0
M1066a_V_vp_1066a(105) = 12.3105d0
M1066a_V_vp_1066a(106) = 12.2596d0
M1066a_V_vp_1066a(107) = 12.2072d0
M1066a_V_vp_1066a(108) = 12.1538d0
M1066a_V_vp_1066a(109) = 12.0998d0
M1066a_V_vp_1066a(110) = 12.0458d0
M1066a_V_vp_1066a(111) = 11.992d0
M1066a_V_vp_1066a(112) = 11.9373d0
M1066a_V_vp_1066a(113) = 11.8804d0
M1066a_V_vp_1066a(114) = 11.82d0
M1066a_V_vp_1066a(115) = 11.7554d0
M1066a_V_vp_1066a(116) = 11.6844d0
M1066a_V_vp_1066a(117) = 11.6079d0
M1066a_V_vp_1066a(118) = 11.5308d0
M1066a_V_vp_1066a(119) = 11.4579d0
M1066a_V_vp_1066a(120) = 11.3935d0
M1066a_V_vp_1066a(121) = 11.3418d0
M1066a_V_vp_1066a(122) = 11.3085d0
M1066a_V_vp_1066a(123) = 11.2938d0
M1066a_V_vp_1066a(124) = 11.2915d0
M1066a_V_vp_1066a(125) = 11.3049d0
M1066a_V_vp_1066a(126) = 11.3123d0
M1066a_V_vp_1066a(127) = 11.2643d0
M1066a_V_vp_1066a(128) = 11.1635d0
M1066a_V_vp_1066a(129) = 11.0063d0
M1066a_V_vp_1066a(130) = 10.7959d0
M1066a_V_vp_1066a(131) = 10.5143d0
M1066a_V_vp_1066a(132) = 10.5143d0
M1066a_V_vp_1066a(133) = 10.2513d0
M1066a_V_vp_1066a(134) = 10.0402d0
M1066a_V_vp_1066a(135) = 9.8648d0
M1066a_V_vp_1066a(136) = 9.7086d0
M1066a_V_vp_1066a(137) = 9.5681d0
M1066a_V_vp_1066a(138) = 9.4512d0
M1066a_V_vp_1066a(139) = 9.351d0
M1066a_V_vp_1066a(140) = 9.2283d0
M1066a_V_vp_1066a(141) = 9.2283d0
M1066a_V_vp_1066a(142) = 9.1087d0
M1066a_V_vp_1066a(143) = 8.9823d0
M1066a_V_vp_1066a(144) = 8.8592d0
M1066a_V_vp_1066a(145) = 8.7386d0
M1066a_V_vp_1066a(146) = 8.6193d0
M1066a_V_vp_1066a(147) = 8.5018d0
M1066a_V_vp_1066a(148) = 8.3871d0
M1066a_V_vp_1066a(149) = 8.2736d0
M1066a_V_vp_1066a(150) = 8.1585d0
M1066a_V_vp_1066a(151) = 8.054d0
M1066a_V_vp_1066a(152) = 7.9652d0
M1066a_V_vp_1066a(153) = 7.8734d0
M1066a_V_vp_1066a(154) = 7.7972d0
M1066a_V_vp_1066a(155) = 7.7391d0
M1066a_V_vp_1066a(156) = 7.7134d0
M1066a_V_vp_1066a(157) = 7.7046d0
M1066a_V_vp_1066a(158) = 4.7022d0
M1066a_V_vp_1066a(159) = 4.7001d0
M1066a_V_vp_1066a(160) = 4.6979d0
M1066a_V_vs_1066a( 1) = 3.6298d0
M1066a_V_vs_1066a( 2) = 3.6297d0
M1066a_V_vs_1066a( 3) = 3.6294d0
M1066a_V_vs_1066a( 4) = 3.6288d0
M1066a_V_vs_1066a( 5) = 3.6281d0
M1066a_V_vs_1066a( 6) = 3.6271d0
M1066a_V_vs_1066a( 7) = 3.6259d0
M1066a_V_vs_1066a( 8) = 3.6244d0
M1066a_V_vs_1066a( 9) = 3.6228d0
M1066a_V_vs_1066a( 10) = 3.6209d0
M1066a_V_vs_1066a( 11) = 3.6187d0
M1066a_V_vs_1066a( 12) = 3.6163d0
M1066a_V_vs_1066a( 13) = 3.6137d0
M1066a_V_vs_1066a( 14) = 3.6108d0
M1066a_V_vs_1066a( 15) = 3.6076d0
M1066a_V_vs_1066a( 16) = 3.6042d0
M1066a_V_vs_1066a( 17) = 3.6004d0
M1066a_V_vs_1066a( 18) = 3.5965d0
M1066a_V_vs_1066a( 19) = 3.5922d0
M1066a_V_vs_1066a( 20) = 3.5876d0
M1066a_V_vs_1066a( 21) = 3.5828d0
M1066a_V_vs_1066a( 22) = 3.5777d0
M1066a_V_vs_1066a( 23) = 3.5724d0
M1066a_V_vs_1066a( 24) = 3.5668d0
M1066a_V_vs_1066a( 25) = 3.561d0
M1066a_V_vs_1066a( 26) = 3.5551d0
M1066a_V_vs_1066a( 27) = 3.549d0
M1066a_V_vs_1066a( 28) = 3.5428d0
M1066a_V_vs_1066a( 29) = 3.5365d0
M1066a_V_vs_1066a( 30) = 3.5301d0
M1066a_V_vs_1066a( 31) = 3.5238d0
M1066a_V_vs_1066a( 32) = 3.5172d0
M1066a_V_vs_1066a( 33) = 3.5118d0
M1066a_V_vs_1066a( 34) = 0.d0
M1066a_V_vs_1066a( 35) = 0.d0
M1066a_V_vs_1066a( 36) = 0.d0
M1066a_V_vs_1066a( 37) = 0.d0
M1066a_V_vs_1066a( 38) = 0.d0
M1066a_V_vs_1066a( 39) = 0.d0
M1066a_V_vs_1066a( 40) = 0.d0
M1066a_V_vs_1066a( 41) = 0.d0
M1066a_V_vs_1066a( 42) = 0.d0
M1066a_V_vs_1066a( 43) = 0.d0
M1066a_V_vs_1066a( 44) = 0.d0
M1066a_V_vs_1066a( 45) = 0.d0
M1066a_V_vs_1066a( 46) = 0.d0
M1066a_V_vs_1066a( 47) = 0.d0
M1066a_V_vs_1066a( 48) = 0.d0
M1066a_V_vs_1066a( 49) = 0.d0
M1066a_V_vs_1066a( 50) = 0.d0
M1066a_V_vs_1066a( 51) = 0.d0
M1066a_V_vs_1066a( 52) = 0.d0
M1066a_V_vs_1066a( 53) = 0.d0
M1066a_V_vs_1066a( 54) = 0.d0
M1066a_V_vs_1066a( 55) = 0.d0
M1066a_V_vs_1066a( 56) = 0.d0
M1066a_V_vs_1066a( 57) = 0.d0
M1066a_V_vs_1066a( 58) = 0.d0
M1066a_V_vs_1066a( 59) = 0.d0
M1066a_V_vs_1066a( 60) = 0.d0
M1066a_V_vs_1066a( 61) = 0.d0
M1066a_V_vs_1066a( 62) = 0.d0
M1066a_V_vs_1066a( 63) = 0.d0
M1066a_V_vs_1066a( 64) = 0.d0
M1066a_V_vs_1066a( 65) = 0.d0
M1066a_V_vs_1066a( 66) = 0.d0
M1066a_V_vs_1066a( 67) = 7.2498d0
M1066a_V_vs_1066a( 68) = 7.2376d0
M1066a_V_vs_1066a( 69) = 7.2239d0
M1066a_V_vs_1066a( 70) = 7.21d0
M1066a_V_vs_1066a( 71) = 7.1964d0
M1066a_V_vs_1066a( 72) = 7.183d0
M1066a_V_vs_1066a( 73) = 7.1699d0
M1066a_V_vs_1066a( 74) = 7.1571d0
M1066a_V_vs_1066a( 75) = 7.1445d0
M1066a_V_vs_1066a( 76) = 7.132d0
M1066a_V_vs_1066a( 77) = 7.1196d0
M1066a_V_vs_1066a( 78) = 7.1074d0
M1066a_V_vs_1066a( 79) = 7.0953d0
M1066a_V_vs_1066a( 80) = 7.0832d0
M1066a_V_vs_1066a( 81) = 7.0712d0
M1066a_V_vs_1066a( 82) = 7.0592d0
M1066a_V_vs_1066a( 83) = 7.0471d0
M1066a_V_vs_1066a( 84) = 7.0347d0
M1066a_V_vs_1066a( 85) = 7.0219d0
M1066a_V_vs_1066a( 86) = 7.0086d0
M1066a_V_vs_1066a( 87) = 6.9947d0
M1066a_V_vs_1066a( 88) = 6.9803d0
M1066a_V_vs_1066a( 89) = 6.9651d0
M1066a_V_vs_1066a( 90) = 6.9493d0
M1066a_V_vs_1066a( 91) = 6.9329d0
M1066a_V_vs_1066a( 92) = 6.9162d0
M1066a_V_vs_1066a( 93) = 6.8991d0
M1066a_V_vs_1066a( 94) = 6.882d0
M1066a_V_vs_1066a( 95) = 6.8652d0
M1066a_V_vs_1066a( 96) = 6.849d0
M1066a_V_vs_1066a( 97) = 6.8334d0
M1066a_V_vs_1066a( 98) = 6.8182d0
M1066a_V_vs_1066a( 99) = 6.8036d0
M1066a_V_vs_1066a(100) = 6.7891d0
M1066a_V_vs_1066a(101) = 6.7744d0
M1066a_V_vs_1066a(102) = 6.7589d0
M1066a_V_vs_1066a(103) = 6.7427d0
M1066a_V_vs_1066a(104) = 6.7255d0
M1066a_V_vs_1066a(105) = 6.7073d0
M1066a_V_vs_1066a(106) = 6.6881d0
M1066a_V_vs_1066a(107) = 6.6684d0
M1066a_V_vs_1066a(108) = 6.6485d0
M1066a_V_vs_1066a(109) = 6.6288d0
M1066a_V_vs_1066a(110) = 6.6095d0
M1066a_V_vs_1066a(111) = 6.5911d0
M1066a_V_vs_1066a(112) = 6.5731d0
M1066a_V_vs_1066a(113) = 6.5548d0
M1066a_V_vs_1066a(114) = 6.5351d0
M1066a_V_vs_1066a(115) = 6.5133d0
M1066a_V_vs_1066a(116) = 6.4881d0
M1066a_V_vs_1066a(117) = 6.4594d0
M1066a_V_vs_1066a(118) = 6.4286d0
M1066a_V_vs_1066a(119) = 6.3976d0
M1066a_V_vs_1066a(120) = 6.3684d0
M1066a_V_vs_1066a(121) = 6.3428d0
M1066a_V_vs_1066a(122) = 6.3235d0
M1066a_V_vs_1066a(123) = 6.3114d0
M1066a_V_vs_1066a(124) = 6.3041d0
M1066a_V_vs_1066a(125) = 6.3052d0
M1066a_V_vs_1066a(126) = 6.3021d0
M1066a_V_vs_1066a(127) = 6.2643d0
M1066a_V_vs_1066a(128) = 6.1947d0
M1066a_V_vs_1066a(129) = 6.0912d0
M1066a_V_vs_1066a(130) = 5.9555d0
M1066a_V_vs_1066a(131) = 5.7755d0
M1066a_V_vs_1066a(132) = 5.7755d0
M1066a_V_vs_1066a(133) = 5.6083d0
M1066a_V_vs_1066a(134) = 5.4752d0
M1066a_V_vs_1066a(135) = 5.3653d0
M1066a_V_vs_1066a(136) = 5.2665d0
M1066a_V_vs_1066a(137) = 5.1762d0
M1066a_V_vs_1066a(138) = 5.0996d0
M1066a_V_vs_1066a(139) = 5.0322d0
M1066a_V_vs_1066a(140) = 4.9488d0
M1066a_V_vs_1066a(141) = 4.9488d0
M1066a_V_vs_1066a(142) = 4.8667d0
M1066a_V_vs_1066a(143) = 4.7806d0
M1066a_V_vs_1066a(144) = 4.6995d0
M1066a_V_vs_1066a(145) = 4.6211d0
M1066a_V_vs_1066a(146) = 4.5479d0
M1066a_V_vs_1066a(147) = 4.4882d0
M1066a_V_vs_1066a(148) = 4.4421d0
M1066a_V_vs_1066a(149) = 4.4084d0
M1066a_V_vs_1066a(150) = 4.3874d0
M1066a_V_vs_1066a(151) = 4.3795d0
M1066a_V_vs_1066a(152) = 4.3904d0
M1066a_V_vs_1066a(153) = 4.4331d0
M1066a_V_vs_1066a(154) = 4.483d0
M1066a_V_vs_1066a(155) = 4.5389d0
M1066a_V_vs_1066a(156) = 4.604d0
M1066a_V_vs_1066a(157) = 4.6487d0
M1066a_V_vs_1066a(158) = 2.5806d0
M1066a_V_vs_1066a(159) = 2.5814d0
M1066a_V_vs_1066a(160) = 2.5822d0
if (SUPPRESS_CRUSTAL_MESH) then
M1066a_V_vp_1066a(158:160) = M1066a_V_vp_1066a(157)
M1066a_V_vs_1066a(158:160) = M1066a_V_vs_1066a(157)
M1066a_V_density_1066a(158:160) = M1066a_V_density_1066a(157)
endif
M1066a_V_Qkappa_1066a( 1) = 156900.d0
M1066a_V_Qkappa_1066a( 2) = 156900.d0
M1066a_V_Qkappa_1066a( 3) = 156900.d0
M1066a_V_Qkappa_1066a( 4) = 156900.d0
M1066a_V_Qkappa_1066a( 5) = 156900.d0
M1066a_V_Qkappa_1066a( 6) = 156900.d0
M1066a_V_Qkappa_1066a( 7) = 156900.d0
M1066a_V_Qkappa_1066a( 8) = 156900.d0
M1066a_V_Qkappa_1066a( 9) = 156900.d0
M1066a_V_Qkappa_1066a( 10) = 156900.d0
M1066a_V_Qkappa_1066a( 11) = 156900.d0
M1066a_V_Qkappa_1066a( 12) = 156900.d0
M1066a_V_Qkappa_1066a( 13) = 156900.d0
M1066a_V_Qkappa_1066a( 14) = 156900.d0
M1066a_V_Qkappa_1066a( 15) = 156900.d0
M1066a_V_Qkappa_1066a( 16) = 156900.d0
M1066a_V_Qkappa_1066a( 17) = 156900.d0
M1066a_V_Qkappa_1066a( 18) = 156900.d0
M1066a_V_Qkappa_1066a( 19) = 156900.d0
M1066a_V_Qkappa_1066a( 20) = 156900.d0
M1066a_V_Qkappa_1066a( 21) = 156900.d0
M1066a_V_Qkappa_1066a( 22) = 156900.d0
M1066a_V_Qkappa_1066a( 23) = 156900.d0
M1066a_V_Qkappa_1066a( 24) = 156900.d0
M1066a_V_Qkappa_1066a( 25) = 156900.d0
M1066a_V_Qkappa_1066a( 26) = 156900.d0
M1066a_V_Qkappa_1066a( 27) = 156900.d0
M1066a_V_Qkappa_1066a( 28) = 156900.d0
M1066a_V_Qkappa_1066a( 29) = 156900.d0
M1066a_V_Qkappa_1066a( 30) = 156900.d0
M1066a_V_Qkappa_1066a( 31) = 156900.d0
M1066a_V_Qkappa_1066a( 32) = 156900.d0
M1066a_V_Qkappa_1066a( 33) = 156900.d0
M1066a_V_Qkappa_1066a( 34) = 0.d0
M1066a_V_Qkappa_1066a( 35) = 0.d0
M1066a_V_Qkappa_1066a( 36) = 0.d0
M1066a_V_Qkappa_1066a( 37) = 0.d0
M1066a_V_Qkappa_1066a( 38) = 0.d0
M1066a_V_Qkappa_1066a( 39) = 0.d0
M1066a_V_Qkappa_1066a( 40) = 0.d0
M1066a_V_Qkappa_1066a( 41) = 0.d0
M1066a_V_Qkappa_1066a( 42) = 0.d0
M1066a_V_Qkappa_1066a( 43) = 0.d0
M1066a_V_Qkappa_1066a( 44) = 0.d0
M1066a_V_Qkappa_1066a( 45) = 0.d0
M1066a_V_Qkappa_1066a( 46) = 0.d0
M1066a_V_Qkappa_1066a( 47) = 0.d0
M1066a_V_Qkappa_1066a( 48) = 0.d0
M1066a_V_Qkappa_1066a( 49) = 0.d0
M1066a_V_Qkappa_1066a( 50) = 0.d0
M1066a_V_Qkappa_1066a( 51) = 0.d0
M1066a_V_Qkappa_1066a( 52) = 0.d0
M1066a_V_Qkappa_1066a( 53) = 0.d0
M1066a_V_Qkappa_1066a( 54) = 0.d0
M1066a_V_Qkappa_1066a( 55) = 0.d0
M1066a_V_Qkappa_1066a( 56) = 0.d0
M1066a_V_Qkappa_1066a( 57) = 0.d0
M1066a_V_Qkappa_1066a( 58) = 0.d0
M1066a_V_Qkappa_1066a( 59) = 0.d0
M1066a_V_Qkappa_1066a( 60) = 0.d0
M1066a_V_Qkappa_1066a( 61) = 0.d0
M1066a_V_Qkappa_1066a( 62) = 0.d0
M1066a_V_Qkappa_1066a( 63) = 0.d0
M1066a_V_Qkappa_1066a( 64) = 0.d0
M1066a_V_Qkappa_1066a( 65) = 0.d0
M1066a_V_Qkappa_1066a( 66) = 0.d0
M1066a_V_Qkappa_1066a( 67) = 16600.d0
M1066a_V_Qkappa_1066a( 68) = 16600.d0
M1066a_V_Qkappa_1066a( 69) = 16600.d0
M1066a_V_Qkappa_1066a( 70) = 16600.d0
M1066a_V_Qkappa_1066a( 71) = 16600.d0
M1066a_V_Qkappa_1066a( 72) = 16600.d0
M1066a_V_Qkappa_1066a( 73) = 16600.d0
M1066a_V_Qkappa_1066a( 74) = 16600.d0
M1066a_V_Qkappa_1066a( 75) = 16600.d0
M1066a_V_Qkappa_1066a( 76) = 16600.d0
M1066a_V_Qkappa_1066a( 77) = 16600.d0
M1066a_V_Qkappa_1066a( 78) = 16600.d0
M1066a_V_Qkappa_1066a( 79) = 16600.d0
M1066a_V_Qkappa_1066a( 80) = 16600.d0
M1066a_V_Qkappa_1066a( 81) = 16600.d0
M1066a_V_Qkappa_1066a( 82) = 16600.d0
M1066a_V_Qkappa_1066a( 83) = 16600.d0
M1066a_V_Qkappa_1066a( 84) = 16600.d0
M1066a_V_Qkappa_1066a( 85) = 16600.d0
M1066a_V_Qkappa_1066a( 86) = 16600.d0
M1066a_V_Qkappa_1066a( 87) = 16600.d0
M1066a_V_Qkappa_1066a( 88) = 16600.d0
M1066a_V_Qkappa_1066a( 89) = 16600.d0
M1066a_V_Qkappa_1066a( 90) = 16600.d0
M1066a_V_Qkappa_1066a( 91) = 16600.d0
M1066a_V_Qkappa_1066a( 92) = 16600.d0
M1066a_V_Qkappa_1066a( 93) = 16600.d0
M1066a_V_Qkappa_1066a( 94) = 16600.d0
M1066a_V_Qkappa_1066a( 95) = 16600.d0
M1066a_V_Qkappa_1066a( 96) = 16600.d0
M1066a_V_Qkappa_1066a( 97) = 16600.d0
M1066a_V_Qkappa_1066a( 98) = 16600.d0
M1066a_V_Qkappa_1066a( 99) = 16600.d0
M1066a_V_Qkappa_1066a(100) = 16600.d0
M1066a_V_Qkappa_1066a(101) = 16600.d0
M1066a_V_Qkappa_1066a(102) = 16600.d0
M1066a_V_Qkappa_1066a(103) = 16600.d0
M1066a_V_Qkappa_1066a(104) = 16600.d0
M1066a_V_Qkappa_1066a(105) = 16600.d0
M1066a_V_Qkappa_1066a(106) = 16600.d0
M1066a_V_Qkappa_1066a(107) = 16600.d0
M1066a_V_Qkappa_1066a(108) = 16600.d0
M1066a_V_Qkappa_1066a(109) = 16600.d0
M1066a_V_Qkappa_1066a(110) = 16600.d0
M1066a_V_Qkappa_1066a(111) = 16600.d0
M1066a_V_Qkappa_1066a(112) = 16600.d0
M1066a_V_Qkappa_1066a(113) = 16600.d0
M1066a_V_Qkappa_1066a(114) = 16600.d0
M1066a_V_Qkappa_1066a(115) = 16600.d0
M1066a_V_Qkappa_1066a(116) = 16600.d0
M1066a_V_Qkappa_1066a(117) = 16600.d0
M1066a_V_Qkappa_1066a(118) = 16600.d0
M1066a_V_Qkappa_1066a(119) = 16600.d0
M1066a_V_Qkappa_1066a(120) = 16600.d0
M1066a_V_Qkappa_1066a(121) = 16600.d0
M1066a_V_Qkappa_1066a(122) = 16600.d0
M1066a_V_Qkappa_1066a(123) = 16600.d0
M1066a_V_Qkappa_1066a(124) = 16600.d0
M1066a_V_Qkappa_1066a(125) = 16600.d0
M1066a_V_Qkappa_1066a(126) = 16600.d0
M1066a_V_Qkappa_1066a(127) = 16600.d0
M1066a_V_Qkappa_1066a(128) = 16600.d0
M1066a_V_Qkappa_1066a(129) = 16600.d0
M1066a_V_Qkappa_1066a(130) = 16600.d0
M1066a_V_Qkappa_1066a(131) = 16600.d0
M1066a_V_Qkappa_1066a(132) = 13840.d0
M1066a_V_Qkappa_1066a(133) = 13840.d0
M1066a_V_Qkappa_1066a(134) = 13840.d0
M1066a_V_Qkappa_1066a(135) = 13840.d0
M1066a_V_Qkappa_1066a(136) = 13840.d0
M1066a_V_Qkappa_1066a(137) = 13840.d0
M1066a_V_Qkappa_1066a(138) = 13840.d0
M1066a_V_Qkappa_1066a(139) = 13840.d0
M1066a_V_Qkappa_1066a(140) = 13840.d0
M1066a_V_Qkappa_1066a(141) = 5893.d0
M1066a_V_Qkappa_1066a(142) = 5893.d0
M1066a_V_Qkappa_1066a(143) = 5893.d0
M1066a_V_Qkappa_1066a(144) = 5893.d0
M1066a_V_Qkappa_1066a(145) = 5893.d0
M1066a_V_Qkappa_1066a(146) = 5893.d0
M1066a_V_Qkappa_1066a(147) = 5893.d0
M1066a_V_Qkappa_1066a(148) = 5893.d0
M1066a_V_Qkappa_1066a(149) = 5893.d0
M1066a_V_Qkappa_1066a(150) = 5893.d0
M1066a_V_Qkappa_1066a(151) = 5893.d0
M1066a_V_Qkappa_1066a(152) = 5893.d0
M1066a_V_Qkappa_1066a(153) = 5893.d0
M1066a_V_Qkappa_1066a(154) = 5893.d0
M1066a_V_Qkappa_1066a(155) = 5893.d0
M1066a_V_Qkappa_1066a(156) = 5893.d0
M1066a_V_Qkappa_1066a(157) = 5893.d0
M1066a_V_Qkappa_1066a(158) = 5893.d0
M1066a_V_Qkappa_1066a(159) = 5893.d0
M1066a_V_Qkappa_1066a(160) = 5893.d0
M1066a_V_Qmu_1066a( 1) = 3138.d0
M1066a_V_Qmu_1066a( 2) = 3138.d0
M1066a_V_Qmu_1066a( 3) = 3138.d0
M1066a_V_Qmu_1066a( 4) = 3138.d0
M1066a_V_Qmu_1066a( 5) = 3138.d0
M1066a_V_Qmu_1066a( 6) = 3138.d0
M1066a_V_Qmu_1066a( 7) = 3138.d0
M1066a_V_Qmu_1066a( 8) = 3138.d0
M1066a_V_Qmu_1066a( 9) = 3138.d0
M1066a_V_Qmu_1066a( 10) = 3138.d0
M1066a_V_Qmu_1066a( 11) = 3138.d0
M1066a_V_Qmu_1066a( 12) = 3138.d0
M1066a_V_Qmu_1066a( 13) = 3138.d0
M1066a_V_Qmu_1066a( 14) = 3138.d0
M1066a_V_Qmu_1066a( 15) = 3138.d0
M1066a_V_Qmu_1066a( 16) = 3138.d0
M1066a_V_Qmu_1066a( 17) = 3138.d0
M1066a_V_Qmu_1066a( 18) = 3138.d0
M1066a_V_Qmu_1066a( 19) = 3138.d0
M1066a_V_Qmu_1066a( 20) = 3138.d0
M1066a_V_Qmu_1066a( 21) = 3138.d0
M1066a_V_Qmu_1066a( 22) = 3138.d0
M1066a_V_Qmu_1066a( 23) = 3138.d0
M1066a_V_Qmu_1066a( 24) = 3138.d0
M1066a_V_Qmu_1066a( 25) = 3138.d0
M1066a_V_Qmu_1066a( 26) = 3138.d0
M1066a_V_Qmu_1066a( 27) = 3138.d0
M1066a_V_Qmu_1066a( 28) = 3138.d0
M1066a_V_Qmu_1066a( 29) = 3138.d0
M1066a_V_Qmu_1066a( 30) = 3138.d0
M1066a_V_Qmu_1066a( 31) = 3138.d0
M1066a_V_Qmu_1066a( 32) = 3138.d0
M1066a_V_Qmu_1066a( 33) = 3138.d0
M1066a_V_Qmu_1066a( 34) = 0.d0
M1066a_V_Qmu_1066a( 35) = 0.d0
M1066a_V_Qmu_1066a( 36) = 0.d0
M1066a_V_Qmu_1066a( 37) = 0.d0
M1066a_V_Qmu_1066a( 38) = 0.d0
M1066a_V_Qmu_1066a( 39) = 0.d0
M1066a_V_Qmu_1066a( 40) = 0.d0
M1066a_V_Qmu_1066a( 41) = 0.d0
M1066a_V_Qmu_1066a( 42) = 0.d0
M1066a_V_Qmu_1066a( 43) = 0.d0
M1066a_V_Qmu_1066a( 44) = 0.d0
M1066a_V_Qmu_1066a( 45) = 0.d0
M1066a_V_Qmu_1066a( 46) = 0.d0
M1066a_V_Qmu_1066a( 47) = 0.d0
M1066a_V_Qmu_1066a( 48) = 0.d0
M1066a_V_Qmu_1066a( 49) = 0.d0
M1066a_V_Qmu_1066a( 50) = 0.d0
M1066a_V_Qmu_1066a( 51) = 0.d0
M1066a_V_Qmu_1066a( 52) = 0.d0
M1066a_V_Qmu_1066a( 53) = 0.d0
M1066a_V_Qmu_1066a( 54) = 0.d0
M1066a_V_Qmu_1066a( 55) = 0.d0
M1066a_V_Qmu_1066a( 56) = 0.d0
M1066a_V_Qmu_1066a( 57) = 0.d0
M1066a_V_Qmu_1066a( 58) = 0.d0
M1066a_V_Qmu_1066a( 59) = 0.d0
M1066a_V_Qmu_1066a( 60) = 0.d0
M1066a_V_Qmu_1066a( 61) = 0.d0
M1066a_V_Qmu_1066a( 62) = 0.d0
M1066a_V_Qmu_1066a( 63) = 0.d0
M1066a_V_Qmu_1066a( 64) = 0.d0
M1066a_V_Qmu_1066a( 65) = 0.d0
M1066a_V_Qmu_1066a( 66) = 0.d0
M1066a_V_Qmu_1066a( 67) = 332.d0
M1066a_V_Qmu_1066a( 68) = 332.d0
M1066a_V_Qmu_1066a( 69) = 332.d0
M1066a_V_Qmu_1066a( 70) = 332.d0
M1066a_V_Qmu_1066a( 71) = 332.d0
M1066a_V_Qmu_1066a( 72) = 332.d0
M1066a_V_Qmu_1066a( 73) = 332.d0
M1066a_V_Qmu_1066a( 74) = 332.d0
M1066a_V_Qmu_1066a( 75) = 332.d0
M1066a_V_Qmu_1066a( 76) = 332.d0
M1066a_V_Qmu_1066a( 77) = 332.d0
M1066a_V_Qmu_1066a( 78) = 332.d0
M1066a_V_Qmu_1066a( 79) = 332.d0
M1066a_V_Qmu_1066a( 80) = 332.d0
M1066a_V_Qmu_1066a( 81) = 332.d0
M1066a_V_Qmu_1066a( 82) = 332.d0
M1066a_V_Qmu_1066a( 83) = 332.d0
M1066a_V_Qmu_1066a( 84) = 332.d0
M1066a_V_Qmu_1066a( 85) = 332.d0
M1066a_V_Qmu_1066a( 86) = 332.d0
M1066a_V_Qmu_1066a( 87) = 332.d0
M1066a_V_Qmu_1066a( 88) = 332.d0
M1066a_V_Qmu_1066a( 89) = 332.d0
M1066a_V_Qmu_1066a( 90) = 332.d0
M1066a_V_Qmu_1066a( 91) = 332.d0
M1066a_V_Qmu_1066a( 92) = 332.d0
M1066a_V_Qmu_1066a( 93) = 332.d0
M1066a_V_Qmu_1066a( 94) = 332.d0
M1066a_V_Qmu_1066a( 95) = 332.d0
M1066a_V_Qmu_1066a( 96) = 332.d0
M1066a_V_Qmu_1066a( 97) = 332.d0
M1066a_V_Qmu_1066a( 98) = 332.d0
M1066a_V_Qmu_1066a( 99) = 332.d0
M1066a_V_Qmu_1066a(100) = 332.d0
M1066a_V_Qmu_1066a(101) = 332.d0
M1066a_V_Qmu_1066a(102) = 332.d0
M1066a_V_Qmu_1066a(103) = 332.d0
M1066a_V_Qmu_1066a(104) = 332.d0
M1066a_V_Qmu_1066a(105) = 332.d0
M1066a_V_Qmu_1066a(106) = 332.d0
M1066a_V_Qmu_1066a(107) = 332.d0
M1066a_V_Qmu_1066a(108) = 332.d0
M1066a_V_Qmu_1066a(109) = 332.d0
M1066a_V_Qmu_1066a(110) = 332.d0
M1066a_V_Qmu_1066a(111) = 332.d0
M1066a_V_Qmu_1066a(112) = 332.d0
M1066a_V_Qmu_1066a(113) = 332.d0
M1066a_V_Qmu_1066a(114) = 332.d0
M1066a_V_Qmu_1066a(115) = 332.d0
M1066a_V_Qmu_1066a(116) = 332.d0
M1066a_V_Qmu_1066a(117) = 332.d0
M1066a_V_Qmu_1066a(118) = 332.d0
M1066a_V_Qmu_1066a(119) = 332.d0
M1066a_V_Qmu_1066a(120) = 332.d0
M1066a_V_Qmu_1066a(121) = 332.d0
M1066a_V_Qmu_1066a(122) = 332.d0
M1066a_V_Qmu_1066a(123) = 332.d0
M1066a_V_Qmu_1066a(124) = 332.d0
M1066a_V_Qmu_1066a(125) = 332.d0
M1066a_V_Qmu_1066a(126) = 332.d0
M1066a_V_Qmu_1066a(127) = 332.d0
M1066a_V_Qmu_1066a(128) = 332.d0
M1066a_V_Qmu_1066a(129) = 332.d0
M1066a_V_Qmu_1066a(130) = 332.d0
M1066a_V_Qmu_1066a(131) = 332.d0
M1066a_V_Qmu_1066a(132) = 276.8d0
M1066a_V_Qmu_1066a(133) = 276.8d0
M1066a_V_Qmu_1066a(134) = 276.8d0
M1066a_V_Qmu_1066a(135) = 276.8d0
M1066a_V_Qmu_1066a(136) = 276.8d0
M1066a_V_Qmu_1066a(137) = 276.8d0
M1066a_V_Qmu_1066a(138) = 276.8d0
M1066a_V_Qmu_1066a(139) = 276.8d0
M1066a_V_Qmu_1066a(140) = 276.8d0
M1066a_V_Qmu_1066a(141) = 117.9d0
M1066a_V_Qmu_1066a(142) = 117.9d0
M1066a_V_Qmu_1066a(143) = 117.9d0
M1066a_V_Qmu_1066a(144) = 117.9d0
M1066a_V_Qmu_1066a(145) = 117.9d0
M1066a_V_Qmu_1066a(146) = 117.9d0
M1066a_V_Qmu_1066a(147) = 117.9d0
M1066a_V_Qmu_1066a(148) = 117.9d0
M1066a_V_Qmu_1066a(149) = 117.9d0
M1066a_V_Qmu_1066a(150) = 117.9d0
M1066a_V_Qmu_1066a(151) = 117.9d0
M1066a_V_Qmu_1066a(152) = 117.9d0
M1066a_V_Qmu_1066a(153) = 117.9d0
M1066a_V_Qmu_1066a(154) = 117.9d0
M1066a_V_Qmu_1066a(155) = 117.9d0
M1066a_V_Qmu_1066a(156) = 117.9d0
M1066a_V_Qmu_1066a(157) = 117.9d0
M1066a_V_Qmu_1066a(158) = 117.9d0
M1066a_V_Qmu_1066a(159) = 117.9d0
M1066a_V_Qmu_1066a(160) = 117.9d0
! strip the crust and replace it by mantle if we use an external crustal model
if (SUPPRESS_CRUSTAL_MESH .or. USE_EXTERNAL_CRUSTAL_MODEL) then
do i=NR_1066A-3,NR_1066A
M1066a_V_density_1066a(i) = M1066a_V_density_1066a(NR_1066A-4)
M1066a_V_vp_1066a(i) = M1066a_V_vp_1066a(NR_1066A-4)
M1066a_V_vs_1066a(i) = M1066a_V_vs_1066a(NR_1066A-4)
M1066a_V_Qkappa_1066a(i) = M1066a_V_Qkappa_1066a(NR_1066A-4)
M1066a_V_Qmu_1066a(i) = M1066a_V_Qmu_1066a(NR_1066A-4)
enddo
endif
end subroutine define_model_1066a
|
komatits/specfem3d_globe
|
src/meshfem3D/model_1066a.f90
|
FORTRAN
|
gpl-2.0
| 44,983
|
<?php
/**
* Displays popular posts, comments and tags in a tabbed pane.
*/
class Awaken_Tabbed_Widget extends WP_Widget {
/**
* Register widget with WordPress.
*/
function __construct() {
parent::__construct(
'awaken_tabbed_widget', // Base ID
__( 'Awaken: Popular Posts, Tags, Comments', 'awaken' ), // Name
array( 'description' => __( 'Displays popular posts, comments, tags in a tabbed pane.', 'text_domain' ), ) // Args
);
}
/**
* Back-end widget form.
*
* @see WP_Widget::form()
*
* @param array $instance Previously saved values from database.
*/
public function form( $instance ) {
$nop = ! empty( $instance['nop'] ) ? absint( $instance['nop'] ) : 5;
$noc = ! empty( $instance['noc'] ) ? absint( $instance['noc'] ) : 5;
?>
<p>
<label for="<?php echo $this->get_field_id( 'nop' ); ?>"><?php _e( 'Number of popular posts:', 'awaken' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'nop' ); ?>" name="<?php echo $this->get_field_name( 'nop' ); ?>" type="text" value="<?php echo esc_attr( $nop ); ?>">
</p>
<p>
<label for="<?php echo $this->get_field_id( 'noc' ); ?>"><?php _e( 'Number of comments:', 'awaken' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'noc' ); ?>" name="<?php echo $this->get_field_name( 'noc' ); ?>" type="text" value="<?php echo esc_attr( $noc ); ?>">
</p>
<?php
}
/**
* Sanitize widget form values as they are saved.
*
* @see WP_Widget::update()
*
* @param array $new_instance Values just sent to be saved.
* @param array $old_instance Previously saved values from database.
*
* @return array Updated safe values to be saved.
*/
public function update( $new_instance, $old_instance ) {
$instance = array();
$instance['nop'] = ( ! empty( $new_instance['nop'] ) ) ? (int)( $new_instance['nop'] ) : '';
$instance['noc'] = ( ! empty( $new_instance['noc'] ) ) ? (int)( $new_instance['noc'] ) : '';
return $instance;
}
/**
* Front-end display of widget.
*
* @see WP_Widget::widget()
*
* @param array $args Widget arguments.
* @param array $instance Saved values from database.
*/
public function widget( $args, $instance ) {
extract($args);
$nop = ( ! empty( $instance['nop'] ) ) ? (int)( $instance['nop'] ) : 5;
$noc = ( ! empty( $instance['noc'] ) ) ? (int)( $instance['noc'] ) : 5;
echo $before_widget; ?>
<ul class="nav nav-tabs" id="awt-widget">
<li><a href="#awaken-popular" role="tab" data-toggle="tab"><?php _e( 'Popular', 'awaken' ); ?></a></li>
<li><a href="#awaken-comments" role="tab" data-toggle="tab"><?php _e( 'Comments', 'awaken' ); ?></a></li>
<li><a href="#awaken-tags" role="tab" data-toggle="tab"><?php _e( 'Tags', 'awaken' ); ?></a></li>
</ul>
<div class="tab-content">
<div class="tab-pane fade active in" id="awaken-popular">
<?php
$args = array( 'ignore_sticky_posts' => 1, 'posts_per_page' => $nop, 'post_status' => 'publish', 'orderby' => 'comment_count', 'order' => 'desc' );
$popular = new WP_Query( $args );
if ( $popular->have_posts() ) :
while( $popular-> have_posts() ) : $popular->the_post(); ?>
<div class="ams-post">
<div class="ams-thumb">
<?php if ( has_post_thumbnail() ) { ?>
<a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_post_thumbnail( 'small-thumb', array('title' => get_the_title()) ); ?></a>
<?php } else { ?>
<a href="<?php the_permalink(); ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo get_template_directory_uri(); ?>/images/mini-thumbnail-default.jpg" alt="<?php the_title(); ?>" /></a>
<?php } ?>
</div>
<div class="ams-details">
<?php the_title( sprintf( '<h1 class="ams-title"><a href="%s" rel="bookmark">', esc_url( get_permalink() ) ), '</a></h1>' ); ?>
<p class="ams-meta"><?php the_time('F j, Y'); ?></p>
</div>
</div>
<?php
endwhile;
endif;
?>
</div><!-- .tab-pane #awaken-popular -->
<div class="tab-pane fade" id="awaken-comments">
<?php
$avatar_size = 80;
$comment_length = 90;
$args = array(
'number' => $noc,
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
if ( $comments ) {
foreach ( $comments as $comment ) { ?>
<div class="awc-container clearfix">
<figure class="awaken_avatar">
<a href="<?php echo get_comment_link($comment->comment_ID); ?>">
<?php echo get_avatar( $comment->comment_author_email, $avatar_size ); ?>
</a>
</figure>
<span class="awaken_comment_author"><?php echo get_comment_author( $comment->comment_ID ); ?> </span> - <span class="awaken_comment_post"><?php echo get_the_title($comment->comment_post_ID); ?></span>
<?php echo '<p class="acmmnt-body">' . $comment->comment_content . '</p>'; ?>
</div>
<?php }
} else {
echo 'No comments found.';
}
?>
</div><!-- .tab-pane #awaken-comments -->
<div class="tab-pane fade" id="awaken-tags">
<?php
$tags = get_tags(array('get'=>'all'));
if($tags) {
foreach ($tags as $tag): ?>
<span><a href="<?php echo get_term_link($tag); ?>"><?php echo $tag->name; ?></a></span>
<?php
endforeach;
} else {
_e( 'No tags created.', 'awaken');
}
?>
</div><!-- .tab-pane #awaken-tags-->
</div><!-- .tab-content -->
<?php
echo $after_widget;
}
}
//Registster awaken tabbed widget.
function register_awaken_tabbed_widget() {
register_widget( 'Awaken_Tabbed_Widget' );
}
add_action( 'widgets_init', 'register_awaken_tabbed_widget' );
|
anacaet/rd_station_form
|
wp-content/themes/awaken/inc/widgets/popular-tags-comments.php
|
PHP
|
gpl-2.0
| 5,951
|
Changelog
=========
#### 3.1.9 - June 7, 2016
**Fixes**
- Placeholder polyfill wasn't loaded (only in IE8 and below).
**Improvements**
- Don't write to debug log if it is not writable.
- Reset some CSS properties for commonly used class names in Form Editor & Debug Log.
- Do not unnecessarily register styles which are then immediately enqueued.
**Additions**
- Add "is required field" option for dropdown & radio fields in Field Helper.
- Link to [Boxzilla plugin](https://boxzillaplugin.com/) from admin sidebar.
#### 3.1.8 - May 23, 2016
**Fixes**
- Form Preview mode replaced all titles on that page with "Form Preview".
- API class fix for [eCommerce360 functionality](https://mc4wp.com/kb/what-is-ecommerce360/).
**Improvements**
- Show dismissible notice when API key is not set.
- Show empty API key errors in plugin log.
- Friendlier error message for re-subscribe failures.
**Additions**
- Add `form.reset()` method to JS API.
#### 3.1.7 - May 9, 2016
**Fixes**
- Shortcode wasn't accepting `element_id` as a valid attribute.
- Take array style fields into account when checking if a form contains a given field.
**Improvements**
- Nested fields will now be properly validated when they're marked as required.
- If plugin is installed using Composer, autoloader won't be loaded (again).
#### 3.1.6 - April 12, 2016
**Fixes**
- Form event for starting a form was named `start` where it should have been `started`.
**Improvements**
- Some preparations for the upcoming migration to the new MailChimp API (version 3).
- Consistent hook parameters for `mc4wp_form_subscribed` action.
- Improved logic for rendering form response.
**Additions**
- New checkbox position for WooCommerce checkout integration.
#### 3.1.5 - March 22, 2016
**Fixes**
- Response message was shown for unsubmitted forms when using `{response}` in the form mark-up with multiple forms on the same page.
**Improvements**
- Scroll to form after form submission now uses native browser method `scrollIntoView()`.
- Various improvements for right-to-left (RTL) sites.
- The MailChimp API key is now obfuscated on the settings page.
- Contact Form 7 integration now uses an early hook priority to ensure we run before any page redirects.
**Additions**
- Add position option for WooCommerce integration.
- Add `{post}` tag whch can be used in form mark-up to fetch properties of the current page or post.
#### 3.1.4 - February 29, 2016
**Fixes**
- Forms with address fields never passing validation.
**Improvements**
- Perform type checks on global variables to prevent issues with poorly coded plugins.
- Add Interest Category ID to list overview table for easier debugging.
- Updated Russian translations.
#### 3.1.3 - February 17, 2016
**Fixes**
- Issue with API array responses (for the [MailChimp Activity add-on](https://wordpress.org/plugins/mc4wp-activity/), for example).
**Improvements**
- Updated Dutch, Portugese, Spanish and Italian translations.
#### 3.1.2 - February 15, 2016
**Fixes**
- Form JavaScript not working when another plugins loads Dojo framework.
- [ENTER] not submitting form settings or creating new-line.
- Internal fields marked as required not passing form validation.
- Deselecting all MailChimp lists wouldn't persist after saving form settings.
- No sign-up request firing for lists with only an `EMAIL` field.
**Improvements**
- Show accepted choice values for dropdown and radio fields in lists overview.
- Use all MailChimp lists for Lists Choice field, instead of just the selected ones.
- Failsafed JavaScript for when any other script loads RequireJS globally.
**Additions**
- Added support for [Shortcake](https://wordpress.org/plugins/shortcode-ui/) plugin.
- Error message for when no list is selected can now be customized from the form message settings.
#### 3.1.1 - February 1, 2016
**Fixes**
- Field Helper not adding `type` attribute when building forms.
- Field Helper not setting the correct `value` attribute for Hidden Groups.
**Improvements**
- Add sourcemaps to minified JavaScript files.
- Add link to article on how to enable debug logging.
- Field Helper now always shows both placeholder and value fields.
#### 3.1 - January 26, 2016
**Fixes**
- `<input>` fields being stripped from form when saving as a role other than "superadmin" on MultiSite installations.
- Certain actions like "renew lists" not working for users other than admin (if they have explicit access to settings pages).
**Improvements**
- Show Akamai firewall reference number when site's IP address is blocked
- Make sure integrations have a MailChimp list selected before trying to subscribe.
- Move less important settings to "Other" page.
- When a field is required in MailChimp, it has to be required in forms as well now.
- Allow including a `_mc4wp_email_type` field in forms to set an explicit email type.
- Miscellaneous overall performance improvements.
**Additions**
- Added [debug logging](https://mc4wp.com/kb/how-to-enable-log-debugging/), which shows all warnings & errors the plugin encountered in communicating with MailChimp.
- Add `get_lists_for_email( $email )` method to API class.
- Add `MC4WP_Queue` class for better background processing of expensive operations.
#### 3.0.12 - January 15, 2016
**Fixes**
- Incorrect hooks being fired for successful and unsuccessful form sign-ups (which also broke the success redirect).
#### 3.0.11 - January 14, 2016
**Improvements**
- Allow splitting up "birthday" and "date" fields into separate fields with `day`, `month` and `year` index.
- Improved algorithm for finding fields when integrating with Contact Form 7 or other custom forms.
- Ninja Forms integration can now automatically find name-fields.
- Ninja Forms integration can now use `mc4wp-` prefixed admin labels.
**Additions**
- `add_ecommerce_order()` and `delete_ecommerce_order()` methods to API class.
#### 3.0.10 - January 6, 2016
**Fixes**
- 500 server error for "already subscribed" on Windows servers.
- Incorrect HTML being generated for hidden fields.
- Duplicate sign-up request when using CF7 integration.
**Improvements**
- Stop logging "already subscribed" errors to PHP's error log.
- Simplify `pattern` attribute for `date` fields.
- Remove invalid `autofill` attribute from honeypot field.
#### 3.0.9 - December 17, 2015
**Fixes**
Not being able to select a list when creating a new form.
#### 3.0.8 - December 15, 2015
**Fixes**
- Make sure `mc4wp_show_form()` works without passing a form ID.
**Improvements**
- Remove UI for bulk-enabling integrations, as every integration needs specific settings anyway.
- Do not print inline JavaScript for forms until it's surely needed.
- Add `position` key to `mc4wp_admin_menu_items` filter to set a menu position.
- Various minor code improvements.
#### 3.0.7 - December 10, 2015
**Fixes**
Workaround for [SSL certification bug in WordPress 4.4](https://core.trac.wordpress.org/ticket/34935), affecting servers with an older versions of OpenSSL installed.
**Additions**
Added `mc4wp_use_sslverify` filter to disable or explicitly enable SSL certificate verification.
#### 3.0.4 - December 7, 2015
**Fixes**
- Fixes compatibility issues with add-on plugins performing validation, like Goodbye Captcha and BWS Captcha.
**Improvements**
- Now using group ID's for interest grouping fields, so changing the group in MailChimp does not require updating your form code.
- Never load enabled integrations which are not installed.
- Reintroduce support for automatically sending `OPTIN_IP`
**Additions**
- Add filter: `mc4wp_form_data`, filters form data before it is processed.
#### 3.0.3 - November 30, 2015
**Fixes**
- Added backwards compatibility for [Goodbye Captcha](https://wordpress.org/plugins/goodbye-captcha/) integration.
**Improvements**
- Prevented notice when saving Form widget settings for the first time.
- Add `autofill="off"` to honeypot field.
- Remove nonces from forms as they're not really useful for publicly available features.
- Errors returned by MailChimp are now logged for Forms as well.
- Pre-select MailChimp list if there's just one list in the connected account.
- Added missing translation calls for Form Editor.
#### 3.0.2 - November 25, 2015
**Fixes**
- Redirect on success not working.
- Forms overview page redirected to main WP Admin page (edge case).
- Safari was always showing the leave-page confirmation dialog.
**Improvements**
- Add form-specific classes to preview form element. This allows the [Styles Builder](https://mc4wp.com/features/) to work with the Form Preview.
- Form events are now triggered _after_ the page has finished loading, so all scripts are loaded & ready to use.
- Reset background-color in Form Themes stylesheets.
#### 3.0.0 & 3.0.1 - November 23, 2015
Version 3.0 is a total revamp of the plugin. For a quick overview of the changes, please [read this post on our blog](https://mc4wp.com/blog/whats-new-in-mailchimp-for-wordpress-the-big-three-o/).
Before upgrading, please go through the [upgrade guide](https://mc4wp.com/kb/upgrading-to-3-0/) as some things have changed.
**Breaking Changes**
- Captcha fields: `{captcha}` field is now handled by the [Captcha add-on plugin](https://wordpress.org/plugins/mc4wp-captcha/).
- New dynamic content tags syntax: `{data_NAME}` is now `{data key="NAME"}`
- Event binding: `jQuery(document).on('subscribe.mc4wp','.mc4wp-form', function(){ ... })` is now `mc4wp.forms.on('subscribed', function(form) { ... })`
- Removed integrations: MultiSite & bbPress.
**Improvements**
- New form editor with syntax highlighting, more advanced field options & better visual feedback.
- Better support for MailChimp `address` fields.
- Better support for choice fields (eg groupings, list choice & country fields).
- All fields marked as `required` are now validated server-side as well (instead of just MailChimp required fields).
- All integrations have their own settings page now.
- Events Manager: checkbox is now automatically added to booking forms.
- Tons of usability & accessibility improvements.
- Tons of code improvements: improved memory usage, 100+ new unit tests & better usage of various best practices.
- The [premium plugin](https://mc4wp.com/) is now an add-on of this plugin.
**Additions**
- New "Preview Form" option, showing unsaved form changes.
- Integrations can now be "implicit", thus no longer showing a checkbox option to visitors.
- New JavaScript API, replacing jQuery event hooks.
- Ninja Forms integration
- Introduced various new filter & action hooks, please see the new [code reference for developers](http://developer.mc4wp.com/) for more information.
#### 2.3.18 - November 2, 2015
**Fixes**
- Incorrect number of parameters for `error_log` statement in integrations class.
**Improvements**
- Usage tracking is now scheduled once a week (instead of daily).
- Preparations for [the upcoming MailChimp for WordPress version 3.0 release](https://mc4wp.com/blog/breaking-backwards-compatibility-in-version-3-0/).
- Tested compatibility with WordPress 4.4
#### 2.3.17 - October 22, 2015
**Fixes**
- Honeypot field being autofilled in Chrome, causing a form error.
**Improvements**
- Updated Portugese translations.
#### 2.3.16 - October 14, 2015
**Fixes**
- Error in Russian translation, causing a broken link on the MailChimp settings page.
**Improvements**
- Textual improvements to MailChimp settings page.
- Connectivity issues with MailChimp will now _always_ show an error message.
- Renewing MailChimp lists will now also update the output of the `{subscriber_count}` tag.
#### 2.3.15 - October 9, 2015
**Fixes**
- Fixes JS error when form contains no submit button
**Improvements**
- Only prefix `url` fields with `http://` if it is filled.
- Updated Spanish & Catalan translations, thanks to [Xavier Gimeno Torrent](http://www.xaviergimeno.net/).
- Fix `mc4wp_form_before_fields` being applied twice.
- Position honeypot field to the right for Right-To-Left sites.
- `_mc4wp_lists` can now be a comma-separated string of MailChimp list ID's to subscribe to (or an array).
- Minor other defensive coding improvements to prevent clashes with other plugins.
**Additions**
- Added opt-in usage tracking to help us make the plugin better. No sensitive data is tracked.
#### 2.3.14 - September 25
**Fixes**
- Use of undefined constant in previous update.
#### 2.3.13 - September 25, 2015
**Fixes**
- Honeypot causing horizontal scrollbar on RTL sites.
- List choice fields not showing when using one of the default form themes.
**Improvements**
- Minor styling improvements for RTL sites.
- MailChimp list fields of type "website" will now become HTML5 `url` type fields.
- Auto-prefix fields of type `url` with `http://`
#### 2.3.12 - September 21, 2015
**Fixes**
- Issue with interest groupings not being fetched after updating to version 2.3.11
#### 2.3.11 - September 21, 2015
**Fixes**
- Honeypot field being filled by browser's autocomplete.
- Styling issue for submit buttons in Mobile Safari.
- Empty response from MailChimp API
**Improvements**
- Do not query MailChimp API for interest groupings if list has none.
- Integration errors are now logged to PHP's error log for easier debugging.
**Additions**
- You can now use shortcodes in the form content.
#### 2.3.10 - September 7, 2015
**Fixes**
- Showing "not connected" when the plugin was actually connected to MailChimp.
- Issue with `address` fields when `addr1` was not given.
- Comment form checkbox not outputted for some older themes.
**Improvements**
- Do not flush MailChimp cache on every settings save.
- Add default CSS styles for `number` fields.
- Placeholders will now work in older version of IE as well.
#### 2.3.9 - September 1, 2015
**Improvements**
- MailChimp lists cache is now automatically flushed after changing your API key setting.
- Better field population after submitting a form with errors.
- More helpful error message when no list is selected.
- Translate options when installing plugin from a language other than English.
- Add form mark-up to WPML configuration file.
- Sign-up checkbox in comment form is now shown before the "submit comment" button.
- URL-encode variables in "Redirect URL" setting.
- Better error message when connected to MailChimp but account has no lists.
**Additions**
- Add `mc4wp_form_action` filter to set a custom `action` attribute on the form element.
#### 2.3.8 - August 18, 2015
**Fixes**
- Prevented JS error when outputting forms with no submit button.
- Using `0` as a Redirect URL resulted in a blank page.
- Sign-up checkbox was showing twice in the Easy Digital Downloads checkout when showing registration fields, thanks [Daniel Espinoza](https://github.com/growdev).
- Default form was not automatically translated for languages other than English.
**Improvements**
- Better way to hide the honeypot field, which stops bots from subscribing to your lists.
- role="form" is no longer needed, thanks [XhmikosR](https://github.com/XhmikosR)!
- Filter `mc4wp_form_animate_scroll` now disables just the scroll animation, not the scroll itself.
- Revamped UI for MailChimp lists overview
- Updated German & Greek translations.
**Additions**
- Added `mc4wp_form_is_submitted()` and `mc4wp_form_get_response_html()` functions.
#### 2.3.7 - July 13, 2015
**Improvements**
- Use the same order as MailChimp.com, which is useful when you have over 100 MailChimp lists.
- Use `/* ... */` for inline JavaScript comments to prevent errors with minified HTML - props [Ed Gifford](https://github.com/egifford)
**Additions**
- Filter: `mc4wp_form_animate_scroll` to disable animated scroll-to after submitting a form.
- Add `{current_path}` variable to use in form templates.
- Add `default` attribute to `{data_name}` variables, usage: `{data_something default="The default value"}`
#### 2.3.6 - July 6, 2015
**Fixes**
- Undefined index notice when visitor's USER_AGENT is not set.
**Improvements**
- Relayed the browser's Accept-Language header to MailChimp for auto-detecting a subscriber's language.
- Better CSS for form reset
- Updated HTML5 placeholder polyfill
#### 2.3.5 - June 24, 2015
**Fixes**
- Faulty update for v3.0 appearing for people running GitHub updater plugin.
**Improvements**
- Updated language files.
- Now passing the form as a parameter to `mc4wp_form_css_classes` filter.
#### 2.3.4 - May 29, 2015
**Fixes**
- Issue with GROUPINGS not being sent to MailChimp
**Improvements**
- Code preview in Field Builder is now read-only
#### 2.3.3 - May 27, 2015
**Fixes**
- Get correct IP address when using proxy like Cloudflare or Sucuri WAF.
- Use strict type check for printing inline CSS that hides honeypot field
**Improvements**
- Add `contactemail` and `contactname` to field name guesses when integrating with third-party form.
- Re-enable `sslverify`
#### 2.3.2 - May 12, 2015
**Fixes**
- Groupings not being sent to MailChimp
- Issue when using more than one `{data_xx}` replacement
**Improvements**
- IE8 compatibility for honeypot fallback script.
#### 2.3.1 - May 6, 2015
**Fixes**
- PHP notice in `includes/class-tools.php`, introduced by version 2.3.
#### 2.3 - May 6, 2015
**Fixes**
- The email address is no longer automatically added to the Redirect URL as this is against Google Analytics policy. To add it again, use `?email={email}` in your Redirect URL setting.
- Registration type integrations were not correctly picking up on first- and last names.
- JavaScript error in IE8 because of `setAttribute` call on honeypot field.
- API class `subscribe` method now always returns a boolean.
**Improvements**
- Add `role` attribute to form elements
- Major code refactoring for easier unit testing and improved code readability.
- Use Composer for autoloading all plugin classes (PHP 5.2 compatible)
- You can now use [form variables in both forms, messages as checkbox label texts](https://mc4wp.com/kb/using-variables-in-your-form-or-messages/).
**Additions**
- You can now handle unsubscribe calls with our forms too.
- Added Portugese, Indonesian, German (CH) and Spanish (PR) translations.
#### 2.2.9 - April 15, 2015
**Fixes**
- Menu item for settings page not appearing on Google App Engine ([#88](https://github.com/ibericode/mailchimp-for-wordpress/issues/88))
**Improvements**
- Updated Italian, Russian & Turkish translations. [Want to help translate the plugin? Full translations get a free Pro license](https://www.transifex.com/projects/p/mailchimp-for-wordpress/).
#### 2.2.8 - March 24, 2015
**Fixes**
- API key field value was not properly escaped.
- Background images were stripped from submit buttons.
**Improvements**
- Better sanitising of all settings
- Updated all translations
**Additions**
- Added `mc4wp_before_checkbox` and `mc4wp_after_checkbox` filters to easily add more fields to sign-up checkbox integrations.
- Added some helper methods related to interest groupings to `MC4WP_MailChimp` class.
- Allow setting custom MailChimp lists to subscribe to using `lists` attribute on shortcode.
#### 2.2.7 - March 11, 2015
**Fixes**
- Honeypot field was visible for themes or templates not calling `wp_head()` and `wp_footer()`
**Improvements**
- Various minor code improvements
- Updated German, Spanish, Brazilian, French, Hungarian and Russian translations.
**Additions**
- Added [mc4wp_form_success](https://github.com/ibericode/mailchimp-for-wordpress/blob/06f0c833027f347a288d2cb9805e0614767409b6/includes/class-form-request.php#L292-L301) action hook to hook into successful sign-ups
- Added [mc4wp_form_data](https://github.com/ibericode/mailchimp-for-wordpress/blob/06f0c833027f347a288d2cb9805e0614767409b6/includes/class-form-request.php#L138-L142) filter hook to modify all form data before processing
#### 2.2.6 - February 26, 2015
**Fixes**
- CSS reset wasn't working for WooCommerce checkout sign-up checkbox.
- `mc4wp-submitted` class was not added in IE8
- Incorrect `action` attribute on form element for some server configurations
**Improvements**
- Anti-SPAM improvements: a better honeypot field and a timestamp field to prevent instant form submissions.
- Reset `background-image` on submit buttons when using CSS themes
- Smarter email detection when integrating with third-party forms
- Updated all translations
**Additions**
- Custom fallback for browsers not supporting `input[type="date"]`
#### 2.2.5 - February 13, 2015
**Fixed**
- Issue where WooCommerce checkout sign-up was not working for cheque payments.
- Translation were loaded too late to properly translate some strings, like the admin menu items.
**Improvements**
- The presence of required list fields in form mark-up is now checked as you type.
- Number fields will now repopulate if an error occurred.
- Updated all translations.
- Make sure there is only one plugin instance.
- Various other code improvements.
**Additions**
- Added support for [GitHub Updater Plugin](https://github.com/afragen/github-updater).
- You can now specify whether you want to send a welcome email (only with double opt-in disabled).
A huge thank you to [Stefan Oderbolz](http://metaodi.ch/) for various fixed and improvements related to translations in this release.
#### 2.2.4 - February 4, 2015
**Fixed**
- Textual fix as entering "0" for no redirection does not work.
**Improvements**
- Moved third-party scripts to their own directory for easier exclusion
- All code is now adhering to the WP Code Standards
- Updated [Dutch, German, Spanish, Hungarian, French, Italian and Turkish translations](https://www.transifex.com/projects/p/mailchimp-for-wordpress/).
**Additions**
- Now showing a heads up when at limit of 100 MailChimp lists. ([#71](https://github.com/ibericode/mailchimp-for-wordpress/issues/71))
- Added `wpml-config.xml` file for better WPML compatibility
- Added filter `mc4wp_menu_items` for adding & removing menu items from add-ons
#### 2.2.3 - January 24, 2015
Minor improvements and additions for compatibility with the [MailChimp Sync plugin](https://wordpress.org/plugins/mailchimp-sync/).
#### 2.2.2 - January 13, 2015
**Fixes**
- Plugin wasn't connecting to MailChimp for users on MailChimp server `us10` (API keys ending in `-us10`)
#### 2.2.1 - January 12, 2015
**Improvements**
- Use JS object to transfer lists data to Field Wizard.
- Field Wizard strings are now translatable
- Add `is_spam` method to checkbox integration to battle spam sign-ups
- Minor code & code style improvements
- Updated Danish, German, Spanish, French, Italian and Portugese (Brazil) translations
**Additions**
- You can now set `MC_LOCATION`, `MC_NOTES` and `MC_LANGUAGE` from your form HTML
- The submit button now has a default value when generating HTML for it
#### 2.2 - December 9, 2014
**Fixes**
- "Select at least one list" notice appearing when unselecting any MailChimp list in Form settings
- If an error occurs, textareas will no longer lose their value
**Improvements**
- Improved the way form submissions are handled
- Minor code & documentation improvements
- Updated Dutch, French, Portugese and Spanish translations
**Additions**
- Added sign-up checkbox integration for [WooCommerce](https://wordpress.org/plugins/woocommerce/) checkout.
- Added sign-up checkbox integration for [Easy Digital Downloads](https://wordpress.org/plugins/easy-digital-downloads/) checkout.
- The entered email will now be appended to the URL when redirecting to another page
|
andyrobsondesign/accelerate
|
wp-content/plugins/mailchimp-for-wp/CHANGELOG.md
|
Markdown
|
gpl-2.0
| 23,538
|
<!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_67) on Thu Apr 09 10:38:42 MDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.handler.dataimport.DocBuilder (Solr 5.1.0 API)</title>
<meta name="date" content="2015-04-09">
<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="Uses of Class org.apache.solr.handler.dataimport.DocBuilder (Solr 5.1.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><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">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="../../../../../../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?org/apache/solr/handler/dataimport/class-use/DocBuilder.html" target="_top">Frames</a></li>
<li><a href="DocBuilder.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 org.apache.solr.handler.dataimport.DocBuilder" class="title">Uses of Class<br>org.apache.solr.handler.dataimport.DocBuilder</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</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="#org.apache.solr.handler.dataimport">org.apache.solr.handler.dataimport</a></td>
<td class="colLast">
<div class="block"><a href="../../../../../../org/apache/solr/handler/dataimport/DataImportHandler.html" title="class in org.apache.solr.handler.dataimport"><code>DataImportHandler</code></a> and related code.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.solr.handler.dataimport">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a> in <a href="../../../../../../org/apache/solr/handler/dataimport/package-summary.html">org.apache.solr.handler.dataimport</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing fields, and an explanation">
<caption><span>Fields in <a href="../../../../../../org/apache/solr/handler/dataimport/package-summary.html">org.apache.solr.handler.dataimport</a> declared as <a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Field and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a></code></td>
<td class="colLast"><span class="strong">DataImporter.</span><code><strong><a href="../../../../../../org/apache/solr/handler/dataimport/DataImporter.html#docBuilder">docBuilder</a></strong></code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../../org/apache/solr/handler/dataimport/package-summary.html">org.apache.solr.handler.dataimport</a> that return <a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</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="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a></code></td>
<td class="colLast"><span class="strong">DataImporter.</span><code><strong><a href="../../../../../../org/apache/solr/handler/dataimport/DataImporter.html#getDocBuilder()">getDocBuilder</a></strong>()</code> </td>
</tr>
<tr class="rowColor">
<td class="colFirst"><code><a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a></code></td>
<td class="colLast"><span class="strong">DataImporter.</span><code><strong><a href="../../../../../../org/apache/solr/handler/dataimport/DataImporter.html#getDocBuilder(org.apache.solr.handler.dataimport.DIHWriter,%20org.apache.solr.handler.dataimport.RequestInfo)">getDocBuilder</a></strong>(<a href="../../../../../../org/apache/solr/handler/dataimport/DIHWriter.html" title="interface in org.apache.solr.handler.dataimport">DIHWriter</a> writer,
<a href="../../../../../../org/apache/solr/handler/dataimport/RequestInfo.html" title="class in org.apache.solr.handler.dataimport">RequestInfo</a> requestParams)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing constructors, and an explanation">
<caption><span>Constructors in <a href="../../../../../../org/apache/solr/handler/dataimport/package-summary.html">org.apache.solr.handler.dataimport</a> with parameters of type <a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/dataimport/ContextImpl.html#ContextImpl(org.apache.solr.handler.dataimport.EntityProcessorWrapper,%20org.apache.solr.handler.dataimport.VariableResolver,%20org.apache.solr.handler.dataimport.DataSource,%20java.lang.String,%20java.util.Map,%20org.apache.solr.handler.dataimport.ContextImpl,%20org.apache.solr.handler.dataimport.DocBuilder)">ContextImpl</a></strong>(<a href="../../../../../../org/apache/solr/handler/dataimport/EntityProcessorWrapper.html" title="class in org.apache.solr.handler.dataimport">EntityProcessorWrapper</a> epw,
<a href="../../../../../../org/apache/solr/handler/dataimport/VariableResolver.html" title="class in org.apache.solr.handler.dataimport">VariableResolver</a> resolver,
<a href="../../../../../../org/apache/solr/handler/dataimport/DataSource.html" title="class in org.apache.solr.handler.dataimport">DataSource</a> ds,
<a href="http://download.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a> currProcess,
<a href="http://download.oracle.com/javase/7/docs/api/java/util/Map.html?is-external=true" title="class or interface in java.util">Map</a><<a href="http://download.oracle.com/javase/7/docs/api/java/lang/String.html?is-external=true" title="class or interface in java.lang">String</a>,<a href="http://download.oracle.com/javase/7/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang">Object</a>> global,
<a href="../../../../../../org/apache/solr/handler/dataimport/ContextImpl.html" title="class in org.apache.solr.handler.dataimport">ContextImpl</a> parentContext,
<a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a> docBuilder)</code> </td>
</tr>
<tr class="rowColor">
<td class="colLast"><code><strong><a href="../../../../../../org/apache/solr/handler/dataimport/EntityProcessorWrapper.html#EntityProcessorWrapper(org.apache.solr.handler.dataimport.EntityProcessor,%20org.apache.solr.handler.dataimport.config.Entity,%20org.apache.solr.handler.dataimport.DocBuilder)">EntityProcessorWrapper</a></strong>(<a href="../../../../../../org/apache/solr/handler/dataimport/EntityProcessor.html" title="class in org.apache.solr.handler.dataimport">EntityProcessor</a> delegate,
<a href="../../../../../../org/apache/solr/handler/dataimport/config/Entity.html" title="class in org.apache.solr.handler.dataimport.config">Entity</a> entity,
<a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">DocBuilder</a> docBuilder)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</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><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/handler/dataimport/DocBuilder.html" title="class in org.apache.solr.handler.dataimport">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="../../../../../../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?org/apache/solr/handler/dataimport/class-use/DocBuilder.html" target="_top">Frames</a></li>
<li><a href="DocBuilder.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>
|
swsachith/ANDROPHSY
|
solr/docs/solr-dataimporthandler/org/apache/solr/handler/dataimport/class-use/DocBuilder.html
|
HTML
|
gpl-2.0
| 12,663
|
/*
Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
TODO: print the catalog (some USE catalog.db ????).
Standalone program to read a MyBlockchain binary log (or relay log).
Should be able to read any file of these categories, even with
--start-position.
An important fact: the Format_desc event of the log is at most the 3rd event
of the log; if it is the 3rd then there is this combination:
Format_desc_of_slave, Rotate_of_master, Format_desc_of_master.
*/
#define MYBLOCKCHAIN_CLIENT
#undef MYBLOCKCHAIN_SERVER
#include "client_priv.h"
#include "my_default.h"
#include <my_time.h>
#include <sslopt-vars.h>
/* That one is necessary for defines of OPTION_NO_FOREIGN_KEY_CHECKS etc */
#include "query_options.h"
#include <signal.h>
#include <my_dir.h>
#include "prealloced_array.h"
/*
error() is used in macro BINLOG_ERROR which is invoked in
rpl_gtid.h, hence the early forward declaration.
*/
static void error(const char *format, ...)
__attribute__((format(printf, 1, 2)));
static void warning(const char *format, ...)
__attribute__((format(printf, 1, 2)));
#include "rpl_gtid.h"
#include "log_event.h"
#include "log_event_old.h"
#include "sql_common.h"
#include "my_dir.h"
#include <welcome_copyright_notice.h> // ORACLE_WELCOME_COPYRIGHT_NOTICE
#include "sql_string.h"
#include "my_decimal.h"
#include "rpl_constants.h"
#include <algorithm>
#include <utility>
#include <map>
using std::min;
using std::max;
#define PROBE_HEADER_LEN (EVENT_LEN_OFFSET+4)
/*
Map containing the names of blockchains to be rewritten,
to a different one.
*/
static
std::map<std::string, std::string> map_myblockchainbinlog_rewrite_db;
static bool
rewrite_db(char **buf, ulong *buf_size,
uint offset_db, uint offset_len)
{
char* ptr= *buf;
char* old_db= ptr + offset_db;
uint old_db_len= (uint) ptr[offset_len];
std::map<std::string, std::string>::iterator new_db_it=
map_myblockchainbinlog_rewrite_db.find(std::string(old_db, old_db_len));
if (new_db_it == map_myblockchainbinlog_rewrite_db.end())
return false;
const char *new_db=new_db_it->second.c_str();
DBUG_ASSERT(new_db && new_db != old_db);
size_t new_db_len= strlen(new_db);
// Reallocate buffer if needed.
if (new_db_len > old_db_len)
{
char *new_buf= (char *) my_realloc(PSI_NOT_INSTRUMENTED, *buf,
*buf_size + new_db_len - old_db_len, MYF(0));
if (!new_buf)
return true;
*buf= new_buf;
}
// Move the tail of buffer to the correct place.
if (new_db_len != old_db_len)
memmove(*buf + offset_db + new_db_len,
*buf + offset_db + old_db_len,
*buf_size - (offset_db + old_db_len));
// Write new_db and new_db_len.
strncpy((*buf) + offset_db, new_db, new_db_len);
(*buf)[offset_len]= (char) new_db_len;
// Update event length in header.
int4store((*buf) + EVENT_LEN_OFFSET, (*buf_size) - old_db_len + new_db_len);
// finally update the event len argument
*buf_size= (*buf_size) - old_db_len + new_db_len;
return false;
}
/**
Replace the blockchain by another blockchain in the buffer of a
Table_map_log_event.
The TABLE_MAP event buffer structure :
Before Rewriting :
+-------------+-----------+----------+------+----------------+
|common_header|post_header|old_db_len|old_db|event data... |
+-------------+-----------+----------+------+----------------+
After Rewriting :
+-------------+-----------+----------+------+----------------+
|common_header|post_header|new_db_len|new_db|event data... |
+-------------+-----------+----------+------+----------------+
In case the new blockchain name is longer than the old blockchain
length, it will reallocate the buffer.
@param[in,out] buf Pointer to event buffer to be processed
@param[in,out] event_len Length of the event
@param[in] fde The Format_description_log_event
@retval false Success
@retval true Out of memory
*/
bool
Table_map_log_event::rewrite_db_in_buffer(char **buf, ulong *event_len,
const Format_description_log_event *fde)
{
uint headers_len= fde->common_header_len +
fde->post_header_len[binary_log::TABLE_MAP_EVENT - 1];
return rewrite_db(buf, event_len, headers_len+1, headers_len);
}
/**
Replace the blockchain by another blockchain in the buffer of a
Query_log_event.
The QUERY_EVENT buffer structure:
Before Rewriting :
+-------------+-----------+-----------+------+------+
|common_header|post_header|status_vars|old_db|... |
+-------------+-----------+-----------+------+------+
After Rewriting :
+-------------+-----------+-----------+------+------+
|common_header|post_header|status_vars|new_db|... |
+-------------+-----------+-----------+------+------+
The db_len is inside the post header, more specifically:
+---------+---------+------+--------+--------+------+
|thread_id|exec_time|db_len|err_code|status_vars_len|
+---------+---------+------+--------+--------+------+
Thence we need to change the post header and the payload,
which is the one carrying the blockchain name.
In case the new blockchain name is longer than the old blockchain
length, it will reallocate the buffer.
@param[in,out] buf Pointer to event buffer to be processed
@param[in,out] event_len Length of the event
@param[in] fde The Format_description_log_event
@retval false Success
@retval true Out of memory
*/
bool
Query_log_event::rewrite_db_in_buffer(char **buf, ulong *event_len,
const Format_description_log_event *fde)
{
uint8 common_header_len= fde->common_header_len;
uint8 query_header_len= fde->post_header_len[binary_log::QUERY_EVENT-1];
char* ptr= *buf;
uint sv_len= 0;
/* Error if the event content is too small */
if (*event_len < (common_header_len + query_header_len))
return true;
/* Check if there are status variables in the event */
if ((query_header_len - QUERY_HEADER_MINIMAL_LEN) > 0)
{
sv_len= uint2korr(ptr + common_header_len + Q_STATUS_VARS_LEN_OFFSET);
}
/* now we have a pointer to the position where the blockchain is. */
uint offset_len= common_header_len + Q_DB_LEN_OFFSET;
uint offset_db= common_header_len + query_header_len + sv_len;
if ((uint)((*buf)[EVENT_TYPE_OFFSET]) == binary_log::EXECUTE_LOAD_QUERY_EVENT)
offset_db+= Binary_log_event::EXECUTE_LOAD_QUERY_EXTRA_HEADER_LEN;
return rewrite_db(buf, event_len, offset_db, offset_len);
}
static
bool rewrite_db_filter(char **buf, ulong *event_len,
const Format_description_log_event *fde)
{
if (map_myblockchainbinlog_rewrite_db.empty())
return false;
uint event_type= (uint)((*buf)[EVENT_TYPE_OFFSET]);
switch(event_type)
{
case binary_log::TABLE_MAP_EVENT:
return Table_map_log_event::rewrite_db_in_buffer(buf, event_len, fde);
case binary_log::QUERY_EVENT:
case binary_log::EXECUTE_LOAD_QUERY_EVENT:
return Query_log_event::rewrite_db_in_buffer(buf, event_len, fde);
default:
break;
}
return false;
}
/*
The character set used should be equal to the one used in myblockchaind.cc for
server rewrite-db
*/
#define myblockchaind_charset &my_charset_latin1
#define CLIENT_CAPABILITIES (CLIENT_LONG_PASSWORD | CLIENT_LONG_FLAG | CLIENT_LOCAL_FILES)
char server_version[SERVER_VERSION_LENGTH];
ulong filter_server_id = 0;
/*
This strucure is used to store the event and the log postion of the events
which is later used to print the event details from correct log postions.
The Log_event *event is used to store the pointer to the current event and
the event_pos is used to store the current event log postion.
*/
struct buff_event_info
{
Log_event *event;
my_off_t event_pos;
};
/*
One statement can result in a sequence of several events: Intvar_log_events,
User_var_log_events, and Rand_log_events, followed by one
Query_log_event. If statements are filtered out, the filter has to be
checked for the Query_log_event. So we have to buffer the Intvar,
User_var, and Rand events and their corresponding log postions until we see
the Query_log_event. This dynamic array buff_ev is used to buffer a structure
which stores such an event and the corresponding log position.
*/
typedef Prealloced_array<buff_event_info, 16, true> Buff_ev;
Buff_ev *buff_ev(PSI_NOT_INSTRUMENTED);
// needed by net_serv.c
ulong bytes_sent = 0L, bytes_received = 0L;
ulong myblockchaind_net_retry_count = 10L;
ulong open_files_limit;
ulong opt_binlog_rows_event_max_size;
uint test_flags = 0;
static uint opt_protocol= 0;
static FILE *result_file;
#ifndef DBUG_OFF
static const char* default_dbug_option = "d:t:o,/tmp/myblockchainbinlog.trace";
#endif
static const char *load_default_groups[]= { "myblockchainbinlog","client",0 };
static my_bool one_blockchain=0, disable_log_bin= 0;
static my_bool opt_hexdump= 0;
const char *base64_output_mode_names[]=
{"NEVER", "AUTO", "UNSPEC", "DECODE-ROWS", NullS};
TYPELIB base64_output_mode_typelib=
{ array_elements(base64_output_mode_names) - 1, "",
base64_output_mode_names, NULL };
static enum_base64_output_mode opt_base64_output_mode= BASE64_OUTPUT_UNSPEC;
static char *opt_base64_output_mode_str= 0;
static my_bool opt_remote_alias= 0;
const char *remote_proto_names[]=
{"BINLOG-DUMP-NON-GTIDS", "BINLOG-DUMP-GTIDS", NullS};
TYPELIB remote_proto_typelib=
{ array_elements(remote_proto_names) - 1, "",
remote_proto_names, NULL };
static enum enum_remote_proto {
BINLOG_DUMP_NON_GTID= 0,
BINLOG_DUMP_GTID= 1,
BINLOG_LOCAL= 2
} opt_remote_proto= BINLOG_LOCAL;
static char *opt_remote_proto_str= 0;
static char *blockchain= 0;
static char *output_file= 0;
static char *rewrite= 0;
static my_bool force_opt= 0, short_form= 0, idempotent_mode= 0;
static my_bool debug_info_flag, debug_check_flag;
static my_bool force_if_open_opt= 1, raw_mode= 0;
static my_bool to_last_remote_log= 0, stop_never= 0;
static my_bool opt_verify_binlog_checksum= 1;
static ulonglong offset = 0;
static int64 stop_never_slave_server_id= -1;
static int64 connection_server_id= -1;
static char* host = 0;
static int port= 0;
static uint my_end_arg;
static const char* sock= 0;
static char *opt_plugin_dir= 0, *opt_default_auth= 0;
static my_bool opt_secure_auth= TRUE;
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
static char *shared_memory_base_name= 0;
#endif
static char* user = 0;
static char* pass = 0;
static char *opt_bind_addr = NULL;
static char *charset= 0;
static uint verbose= 0;
static ulonglong start_position, stop_position;
#define start_position_mot ((my_off_t)start_position)
#define stop_position_mot ((my_off_t)stop_position)
static char *start_datetime_str, *stop_datetime_str;
static my_time_t start_datetime= 0, stop_datetime= MY_TIME_T_MAX;
static ulonglong rec_count= 0;
static MYBLOCKCHAIN* myblockchain = NULL;
static char* dirname_for_local_load= 0;
static uint opt_server_id_bits = 0;
static ulong opt_server_id_mask = 0;
Sid_map *global_sid_map= NULL;
Checkable_rwlock *global_sid_lock= NULL;
Gtid_set *gtid_set_included= NULL;
Gtid_set *gtid_set_excluded= NULL;
/**
Pointer to the Format_description_log_event of the currently active binlog.
This will be changed each time a new Format_description_log_event is
found in the binlog. It is finally destroyed at program termination.
*/
static Format_description_log_event* glob_description_event= NULL;
/**
Exit status for functions in this file.
*/
enum Exit_status {
/** No error occurred and execution should continue. */
OK_CONTINUE= 0,
/** An error occurred and execution should stop. */
ERROR_STOP,
/** No error occurred but execution should stop. */
OK_STOP
};
/*
Options that will be used to filter out events.
*/
static char *opt_include_gtids_str= NULL,
*opt_exclude_gtids_str= NULL;
static my_bool opt_skip_gtids= 0;
static bool filter_based_on_gtids= false;
static bool in_transaction= false;
static bool seen_gtids= false;
static Exit_status dump_local_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname);
static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname);
static Exit_status dump_single_log(PRINT_EVENT_INFO *print_event_info,
const char* logname);
static Exit_status dump_multiple_logs(int argc, char **argv);
static Exit_status safe_connect();
struct buff_event_info buff_event;
class Load_log_processor
{
char target_dir_name[FN_REFLEN];
size_t target_dir_name_len;
/*
When we see first event corresponding to some LOAD DATA statement in
binlog, we create temporary file to store data to be loaded.
We add name of this file to file_names set using its file_id as index.
If we have Create_file event (i.e. we have binary log in pre-5.0.3
format) we also store save event object to be able which is needed to
emit LOAD DATA statement when we will meet Exec_load_data event.
If we have Begin_load_query event we simply store 0 in
File_name_record::event field.
*/
struct File_name_record
{
char *fname;
Create_file_log_event *event;
};
typedef std::map<uint, File_name_record> File_names;
File_names file_names;
/**
Looks for a non-existing filename by adding a numerical suffix to
the given base name, creates the generated file, and returns the
filename by modifying the filename argument.
@param[in,out] filename Base filename
@param[in,out] file_name_end Pointer to last character of
filename. The numerical suffix will be written to this position.
Note that there must be a least five bytes of allocated memory
after file_name_end.
@retval -1 Error (can't find new filename).
@retval >=0 Found file.
*/
File create_unique_file(char *filename, char *file_name_end)
{
File res;
/* If we have to try more than 1000 times, something is seriously wrong */
for (uint version= 0; version<1000; version++)
{
sprintf(file_name_end,"-%x",version);
if ((res= my_create(filename,0,
O_CREAT|O_EXCL|O_BINARY|O_WRONLY,MYF(0)))!=-1)
return res;
}
return -1;
}
public:
Load_log_processor() : file_names()
{}
~Load_log_processor() {}
void init_by_dir_name(const char *dir)
{
target_dir_name_len= (convert_dirname(target_dir_name, dir, NullS) -
target_dir_name);
}
void init_by_cur_dir()
{
if (my_getwd(target_dir_name,sizeof(target_dir_name),MYF(MY_WME)))
exit(1);
target_dir_name_len= strlen(target_dir_name);
}
void destroy()
{
File_names::iterator iter= file_names.begin();
File_names::iterator end= file_names.end();
for (; iter != end; ++iter)
{
File_name_record *ptr= &iter->second;
if (ptr->fname)
{
my_free(ptr->fname);
delete ptr->event;
memset(ptr, 0, sizeof(File_name_record));
}
}
file_names.clear();
}
/**
Obtain Create_file event for LOAD DATA statement by its file_id
and remove it from this Load_log_processor's list of events.
Checks whether we have already seen a Create_file_log_event with
the given file_id. If yes, returns a pointer to the event and
removes the event from array describing active temporary files.
From this moment, the caller is responsible for freeing the memory
occupied by the event.
@param[in] file_id File id identifying LOAD DATA statement.
@return Pointer to Create_file_log_event, or NULL if we have not
seen any Create_file_log_event with this file_id.
*/
Create_file_log_event *grab_event(uint file_id)
{
File_name_record *ptr;
Create_file_log_event *res;
File_names::iterator it= file_names.find(file_id);
if (it == file_names.end())
return NULL;
ptr= &((*it).second);
if ((res= ptr->event))
memset(ptr, 0, sizeof(File_name_record));
return res;
}
/**
Obtain file name of temporary file for LOAD DATA statement by its
file_id and remove it from this Load_log_processor's list of events.
@param[in] file_id Identifier for the LOAD DATA statement.
Checks whether we have already seen Begin_load_query event for
this file_id. If yes, returns the file name of the corresponding
temporary file and removes the filename from the array of active
temporary files. From this moment, the caller is responsible for
freeing the memory occupied by this name.
@return String with the name of the temporary file, or NULL if we
have not seen any Begin_load_query_event with this file_id.
*/
char *grab_fname(uint file_id)
{
File_name_record *ptr;
char *res= NULL;
File_names::iterator it= file_names.find(file_id);
if (it == file_names.end())
return NULL;
ptr= &((*it).second);
if (!ptr->event)
{
res= ptr->fname;
memset(ptr, 0, sizeof(File_name_record));
}
return res;
}
Exit_status process(Create_file_log_event *ce);
Exit_status process(Begin_load_query_log_event *ce);
Exit_status process(Append_block_log_event *ae);
File prepare_new_file_for_old_format(Load_log_event *le, char *filename);
Exit_status load_old_format_file(NET* net, const char *server_fname,
uint server_fname_len, File file);
Exit_status process_first_event(const char *bname, size_t blen,
const uchar *block,
size_t block_len, uint file_id,
Create_file_log_event *ce);
};
/**
Creates and opens a new temporary file in the directory specified by previous call to init_by_dir_name() or init_by_cur_dir().
@param[in] le The basename of the created file will start with the
basename of the file pointed to by this Load_log_event.
@param[out] filename Buffer to save the filename in.
@return File handle >= 0 on success, -1 on error.
*/
File Load_log_processor::prepare_new_file_for_old_format(Load_log_event *le,
char *filename)
{
size_t len;
char *tail;
File file;
fn_format(filename, le->fname, target_dir_name, "", MY_REPLACE_DIR);
len= strlen(filename);
tail= filename + len;
if ((file= create_unique_file(filename,tail)) < 0)
{
error("Could not construct local filename %s.",filename);
return -1;
}
le->set_fname_outside_temp_buf(filename,len+(uint) strlen(tail));
return file;
}
/**
Reads a file from a server and saves it locally.
@param[in,out] net The server to read from.
@param[in] server_fname The name of the file that the server should
read.
@param[in] server_fname_len The length of server_fname.
@param[in,out] file The file to write to.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::load_old_format_file(NET* net,
const char*server_fname,
uint server_fname_len,
File file)
{
uchar buf[FN_REFLEN+1];
buf[0] = 0;
memcpy(buf + 1, server_fname, server_fname_len + 1);
if (my_net_write(net, buf, server_fname_len +2) || net_flush(net))
{
error("Failed requesting the remote dump of %s.", server_fname);
return ERROR_STOP;
}
for (;;)
{
ulong packet_len = my_net_read(net);
if (packet_len == 0)
{
if (my_net_write(net, (uchar*) "", 0) || net_flush(net))
{
error("Failed sending the ack packet.");
return ERROR_STOP;
}
/*
we just need to send something, as the server will read but
not examine the packet - this is because myblockchain_load() sends
an OK when it is done
*/
break;
}
else if (packet_len == packet_error)
{
error("Failed reading a packet during the dump of %s.", server_fname);
return ERROR_STOP;
}
if (packet_len > UINT_MAX)
{
error("Illegal length of packet read from net.");
return ERROR_STOP;
}
if (my_write(file, (uchar*) net->read_pos,
(uint) packet_len, MYF(MY_WME|MY_NABP)))
return ERROR_STOP;
}
return OK_CONTINUE;
}
/**
Process the first event in the sequence of events representing a
LOAD DATA statement.
Creates a temporary file to be used in LOAD DATA and writes first
block of data to it. Registers its file name (and optional
Create_file event) in the array of active temporary files.
@param bname Base name for temporary file to be created.
@param blen Base name length.
@param block First block of data to be loaded.
@param block_len First block length.
@param file_id Identifies the LOAD DATA statement.
@param ce Pointer to Create_file event object if we are processing
this type of event.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process_first_event(const char *bname,
size_t blen,
const uchar *block,
size_t block_len,
uint file_id,
Create_file_log_event *ce)
{
size_t full_len= target_dir_name_len + blen + 9 + 9 + 1;
Exit_status retval= OK_CONTINUE;
char *fname, *ptr;
File file;
File_name_record rec;
DBUG_ENTER("Load_log_processor::process_first_event");
if (!(fname= (char*) my_malloc(PSI_NOT_INSTRUMENTED,
full_len,MYF(MY_WME))))
{
error("Out of memory.");
delete ce;
DBUG_RETURN(ERROR_STOP);
}
memcpy(fname, target_dir_name, target_dir_name_len);
ptr= fname + target_dir_name_len;
memcpy(ptr,bname,blen);
ptr+= blen;
ptr+= sprintf(ptr, "-%x", file_id);
if ((file= create_unique_file(fname,ptr)) < 0)
{
error("Could not construct local filename %s%s.",
target_dir_name,bname);
my_free(fname);
delete ce;
DBUG_RETURN(ERROR_STOP);
}
rec.fname= fname;
rec.event= ce;
/*
fname is freed in process_event()
after Execute_load_query_log_event or Execute_load_log_event
will have been processed, otherwise in Load_log_processor::destroy()
*/
file_names[file_id]= rec;
if (ce)
ce->set_fname_outside_temp_buf(fname, (uint) strlen(fname));
if (my_write(file, (uchar*)block, block_len, MYF(MY_WME|MY_NABP)))
{
error("Failed writing to file.");
retval= ERROR_STOP;
}
if (my_close(file, MYF(MY_WME)))
{
error("Failed closing file.");
retval= ERROR_STOP;
}
DBUG_RETURN(retval);
}
/**
Process the given Create_file_log_event.
@see Load_log_processor::process_first_event(const char*,uint,const char*,uint,uint,Create_file_log_event*)
@param ce Create_file_log_event to process.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process(Create_file_log_event *ce)
{
const char *bname= ce->fname + dirname_length(ce->fname);
size_t blen= ce->fname_len - (bname-ce->fname);
return process_first_event(bname, blen, ce->block, ce->block_len,
ce->file_id, ce);
}
/**
Process the given Begin_load_query_log_event.
@see Load_log_processor::process_first_event(const char*,uint,const char*,uint,uint,Create_file_log_event*)
@param ce Begin_load_query_log_event to process.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process(Begin_load_query_log_event *blqe)
{
return process_first_event("SQL_LOAD_MB", 11, blqe->block, blqe->block_len,
blqe->file_id, 0);
}
/**
Process the given Append_block_log_event.
Appends the chunk of the file contents specified by the event to the
file created by a previous Begin_load_query_log_event or
Create_file_log_event.
If the file_id for the event does not correspond to any file
previously registered through a Begin_load_query_log_event or
Create_file_log_event, this member function will print a warning and
return OK_CONTINUE. It is safe to return OK_CONTINUE, because no
query will be written for this event. We should not print an error
and fail, since the missing file_id could be because a (valid)
--start-position has been specified after the Begin/Create event but
before this Append event.
@param ae Append_block_log_event to process.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
Exit_status Load_log_processor::process(Append_block_log_event *ae)
{
DBUG_ENTER("Load_log_processor::process");
File_names::iterator it= file_names.find(ae->file_id);
const char *fname= ((it != file_names.end()) ?
(*it).second.fname : NULL);
if (fname)
{
File file;
Exit_status retval= OK_CONTINUE;
if (((file= my_open(fname,
O_APPEND|O_BINARY|O_WRONLY,MYF(MY_WME))) < 0))
{
error("Failed opening file %s", fname);
DBUG_RETURN(ERROR_STOP);
}
if (my_write(file,(uchar*)ae->block,ae->block_len,MYF(MY_WME|MY_NABP)))
{
error("Failed writing to file %s", fname);
retval= ERROR_STOP;
}
if (my_close(file,MYF(MY_WME)))
{
error("Failed closing file %s", fname);
retval= ERROR_STOP;
}
DBUG_RETURN(retval);
}
/*
There is no Create_file event (a bad binlog or a big
--start-position). Assuming it's a big --start-position, we just do
nothing and print a warning.
*/
warning("Ignoring Append_block as there is no "
"Create_file event for file_id: %u", ae->file_id);
DBUG_RETURN(OK_CONTINUE);
}
static Load_log_processor load_processor;
/**
Replace windows-style backslashes by forward slashes so it can be
consumed by the myblockchain client, which requires Unix path.
@todo This is only useful under windows, so may be ifdef'ed out on
other systems. /Sven
@todo If a Create_file_log_event contains a filename with a
backslash (valid under unix), then we have problems under windows.
/Sven
@param[in,out] fname Filename to modify. The filename is modified
in-place.
*/
static void convert_path_to_forward_slashes(char *fname)
{
while (*fname)
{
if (*fname == '\\')
*fname= '/';
fname++;
}
}
/**
Indicates whether the given blockchain should be filtered out,
according to the --blockchain=X option.
@param log_dbname Name of blockchain.
@return nonzero if the blockchain with the given name should be
filtered out, 0 otherwise.
*/
static bool shall_skip_blockchain(const char *log_dbname)
{
return one_blockchain &&
(log_dbname != NULL) &&
strcmp(log_dbname, blockchain);
}
/**
Checks whether the given event should be filtered out,
according to the include-gtids, exclude-gtids and
skip-gtids options.
@param ev Pointer to the event to be checked.
@return true if the event should be filtered out,
false, otherwise.
*/
static bool shall_skip_gtids(Log_event* ev)
{
bool filtered= false;
switch (ev->get_type_code())
{
case binary_log::GTID_LOG_EVENT:
case binary_log::ANONYMOUS_GTID_LOG_EVENT:
{
Gtid_log_event *gtid= (Gtid_log_event *) ev;
if (opt_include_gtids_str != NULL)
{
filtered= filtered ||
!gtid_set_included->contains_gtid(gtid->get_sidno(true),
gtid->get_gno());
}
if (opt_exclude_gtids_str != NULL)
{
filtered= filtered ||
gtid_set_excluded->contains_gtid(gtid->get_sidno(true),
gtid->get_gno());
}
filter_based_on_gtids= filtered;
filtered= filtered || opt_skip_gtids;
}
break;
/* Skip previous gtids if --skip-gtids is set. */
case binary_log::PREVIOUS_GTIDS_LOG_EVENT:
filtered= opt_skip_gtids;
break;
/*
Transaction boundaries reset the global filtering flag.
Since in the relay log a transaction can span multiple
log files, we do not reset filter_based_on_gtids flag when
processing control events (they can appear in the middle
of a transaction). But then, if:
FILE1: ... GTID BEGIN QUERY QUERY COMMIT ROTATE
FILE2: FD BEGIN QUERY QUERY COMMIT
Events on the second file would not be outputted, even
though they should.
*/
case binary_log::XID_EVENT:
filtered= filter_based_on_gtids;
filter_based_on_gtids= false;
break;
case binary_log::QUERY_EVENT:
filtered= filter_based_on_gtids;
if (((Query_log_event *)ev)->ends_group())
filter_based_on_gtids= false;
break;
/*
Never skip STOP, FD, ROTATE, IGNORABLE or INCIDENT events.
SLAVE_EVENT and START_EVENT_V3 are there for completion.
Although in the binlog transactions do not span multiple
log files, in the relay-log, that can happen. As such,
we need to explicitly state that we do not filter these
events, because there is a chance that they appear in the
middle of a filtered transaction, e.g.:
FILE1: ... GTID BEGIN QUERY QUERY ROTATE
FILE2: FD QUERY QUERY COMMIT GTID BEGIN ...
In this case, ROTATE and FD events should be processed and
outputted.
*/
case binary_log::START_EVENT_V3: /* for completion */
case binary_log::SLAVE_EVENT: /* for completion */
case binary_log::STOP_EVENT:
case binary_log::FORMAT_DESCRIPTION_EVENT:
case binary_log::ROTATE_EVENT:
case binary_log::IGNORABLE_LOG_EVENT:
case binary_log::INCIDENT_EVENT:
filtered= false;
break;
default:
filtered= filter_based_on_gtids;
break;
}
return filtered;
}
/**
Print the given event, and either delete it or delegate the deletion
to someone else.
The deletion may be delegated in two cases: (1) the event is a
Format_description_log_event, and is saved in
glob_description_event; (2) the event is a Create_file_log_event,
and is saved in load_processor.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@param[in] ev Log_event to process.
@param[in] pos Offset from beginning of binlog file.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
Exit_status process_event(PRINT_EVENT_INFO *print_event_info, Log_event *ev,
my_off_t pos, const char *logname)
{
char ll_buff[21];
Log_event_type ev_type= ev->get_type_code();
my_bool destroy_evt= TRUE;
DBUG_ENTER("process_event");
Exit_status retval= OK_CONTINUE;
IO_CACHE *const head= &print_event_info->head_cache;
/*
Format events are not concerned by --offset and such, we always need to
read them to be able to process the wanted events.
*/
if (((rec_count >= offset) &&
((my_time_t) (ev->common_header->when.tv_sec) >= start_datetime)) ||
(ev_type == binary_log::FORMAT_DESCRIPTION_EVENT))
{
if (ev_type != binary_log::FORMAT_DESCRIPTION_EVENT)
{
/*
We have found an event after start_datetime, from now on print
everything (in case the binlog has timestamps increasing and
decreasing, we do this to avoid cutting the middle).
*/
start_datetime= 0;
offset= 0; // print everything and protect against cycling rec_count
/*
Skip events according to the --server-id flag. However, don't
skip format_description or rotate events, because they they
are really "global" events that are relevant for the entire
binlog, even if they have a server_id. Also, we have to read
the format_description event so that we can parse subsequent
events.
*/
if (ev_type != binary_log::ROTATE_EVENT &&
filter_server_id && (filter_server_id != ev->server_id))
goto end;
}
if (((my_time_t) (ev->common_header->when.tv_sec) >= stop_datetime)
|| (pos >= stop_position_mot))
{
/* end the program */
retval= OK_STOP;
goto end;
}
if (!short_form)
my_b_printf(&print_event_info->head_cache,
"# at %s\n",llstr(pos,ll_buff));
if (!opt_hexdump)
print_event_info->hexdump_from= 0; /* Disabled */
else
print_event_info->hexdump_from= pos;
DBUG_PRINT("debug", ("event_type: %s", ev->get_type_str()));
if (shall_skip_gtids(ev))
goto end;
switch (ev_type) {
case binary_log::QUERY_EVENT:
{
Query_log_event *qle= (Query_log_event*) ev;
bool parent_query_skips=
!qle->is_trans_keyword() && shall_skip_blockchain(qle->db);
bool ends_group= ((Query_log_event*) ev)->ends_group();
bool starts_group= ((Query_log_event*) ev)->starts_group();
for (size_t i= 0; i < buff_ev->size(); i++)
{
buff_event_info pop_event_array= buff_ev->at(i);
Log_event *temp_event= pop_event_array.event;
my_off_t temp_log_pos= pop_event_array.event_pos;
print_event_info->hexdump_from= (opt_hexdump ? temp_log_pos : 0);
if (!parent_query_skips)
temp_event->print(result_file, print_event_info);
delete temp_event;
}
print_event_info->hexdump_from= (opt_hexdump ? pos : 0);
buff_ev->clear();
if (parent_query_skips)
{
/*
Even though there would be no need to set the flag here,
since parent_query_skips is never true when handling "COMMIT"
statements in the Query_log_event, we still need to handle DDL,
which causes a commit itself.
*/
if (seen_gtids && !in_transaction && !starts_group && !ends_group)
{
/*
For DDLs, print the COMMIT right away.
*/
fprintf(result_file, "COMMIT /* added by myblockchainbinlog */%s\n", print_event_info->delimiter);
print_event_info->skipped_event_in_transaction= false;
in_transaction= false;
}
else
print_event_info->skipped_event_in_transaction= true;
goto end;
}
if (ends_group)
{
in_transaction= false;
print_event_info->skipped_event_in_transaction= false;
if (print_event_info->is_gtid_next_set)
print_event_info->is_gtid_next_valid= false;
}
else if (starts_group)
in_transaction= true;
else
{
/*
We are not in a transaction and are not seeing a BEGIN or
COMMIT. So this is an implicitly committing DDL.
*/
if (print_event_info->is_gtid_next_set && !in_transaction)
print_event_info->is_gtid_next_valid= false;
}
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
destroy_evt= TRUE;
}
case binary_log::INTVAR_EVENT:
{
destroy_evt= FALSE;
buff_event.event= ev;
buff_event.event_pos= pos;
buff_ev->push_back(buff_event);
break;
}
case binary_log::RAND_EVENT:
{
destroy_evt= FALSE;
buff_event.event= ev;
buff_event.event_pos= pos;
buff_ev->push_back(buff_event);
break;
}
case binary_log::USER_VAR_EVENT:
{
destroy_evt= FALSE;
buff_event.event= ev;
buff_event.event_pos= pos;
buff_ev->push_back(buff_event);
break;
}
case binary_log::CREATE_FILE_EVENT:
{
Create_file_log_event* ce= (Create_file_log_event*)ev;
/*
We test if this event has to be ignored. If yes, we don't save
this event; this will have the good side-effect of ignoring all
related Append_block and Exec_load.
Note that Load event from 3.23 is not tested.
*/
if (shall_skip_blockchain(ce->db))
{
print_event_info->skipped_event_in_transaction= true;
goto end; // Next event
}
/*
We print the event, but with a leading '#': this is just to inform
the user of the original command; the command we want to execute
will be a derivation of this original command (we will change the
filename and use LOCAL), prepared in the 'case EXEC_LOAD_EVENT'
below.
*/
{
ce->print(result_file, print_event_info, TRUE);
if (head->error == -1)
goto err;
}
// If this binlog is not 3.23 ; why this test??
if (glob_description_event->binlog_version >= 3)
{
/*
transfer the responsibility for destroying the event to
load_processor
*/
ev= NULL;
if ((retval= load_processor.process(ce)) != OK_CONTINUE)
goto end;
}
break;
}
case binary_log::APPEND_BLOCK_EVENT:
/*
Append_block_log_events can safely print themselves even if
the subsequent call load_processor.process fails, because the
output of Append_block_log_event::print is only a comment.
*/
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
if ((retval= load_processor.process((Append_block_log_event*) ev)) !=
OK_CONTINUE)
goto end;
break;
case binary_log::EXEC_LOAD_EVENT:
{
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
Execute_load_log_event *exv= (Execute_load_log_event*)ev;
Create_file_log_event *ce= load_processor.grab_event(exv->file_id);
/*
if ce is 0, it probably means that we have not seen the Create_file
event (a bad binlog, or most probably --start-position is after the
Create_file event). Print a warning comment.
*/
if (ce)
{
/*
We must not convert earlier, since the file is used by
my_open() in Load_log_processor::append().
*/
convert_path_to_forward_slashes((char*) ce->fname);
ce->print(result_file, print_event_info, TRUE);
my_free((void*)ce->fname);
delete ce;
if (head->error == -1)
goto err;
}
else
warning("Ignoring Execute_load_log_event as there is no "
"Create_file event for file_id: %u", exv->file_id);
break;
}
case binary_log::FORMAT_DESCRIPTION_EVENT:
delete glob_description_event;
glob_description_event= (Format_description_log_event*) ev;
/*
The first FD event in log is always generated
from the local server. So if it is first FD event to be
processed (i.e., if server_id_from_fd_event is 0),
get server_id from the FD event and keep it in
server_id_from_fd_event to differentiate between FDs
(originated from local server vs another server).
*/
if (print_event_info->server_id_from_fd_event == 0)
print_event_info->server_id_from_fd_event= ev->server_id;
print_event_info->common_header_len=
glob_description_event->common_header_len;
ev->print(result_file, print_event_info);
/*
At this point, if we are in transaction that means
we are reading a relay log file (transaction cannot
spawn across two binary log files, they are writen
at once in binlog). When AUTO_POSITION is enabled
and if IO thread stopped in between the GTID transaction,
upon IO thread restart, Master will send the GTID events
again from the begin of the transaction. Hence, we should
rollback the old transaction.
If you are reading FD event that came from Master
(first FD event is from the server that owns the relaylog
and second one is from Master) and if it's log_pos is > 0
then it represents the begin of a master's binary log
(any unfinished transaction will not be finished) or that
auto_position is enabled (any partial transaction left will
not be finished but will be fully retrieved again). On both
cases, the next transaction in the relay log will start from the
beginning and we must rollback any unfinished transaction
*/
if (ev->server_id !=0 &&
ev->server_id != print_event_info->server_id_from_fd_event &&
ev->common_header->log_pos > 0)
{
if (in_transaction)
{
my_b_printf(&print_event_info->head_cache,
"ROLLBACK /* added by myblockchainbinlog */ %s\n",
print_event_info->delimiter);
}
else if (print_event_info->is_gtid_next_set &&
print_event_info->is_gtid_next_valid)
{
/*
If we are here, then we have seen only GTID_LOG_EVENT
of a transaction and did not see even a BEGIN event
(in_transaction flag is false). So generate BEGIN event
also along with ROLLBACK event.
*/
my_b_printf(&print_event_info->head_cache,
"BEGIN /*added by myblockchainbinlog */ %s\n"
"ROLLBACK /* added by myblockchainbinlog */ %s\n",
print_event_info->delimiter,
print_event_info->delimiter);
}
}
if (head->error == -1)
goto err;
if (opt_remote_proto == BINLOG_LOCAL)
{
ev->free_temp_buf(); // free memory allocated in dump_local_log_entries
}
else
{
/*
disassociate but not free dump_remote_log_entries time memory
*/
ev->temp_buf= 0;
}
/*
We don't want this event to be deleted now, so let's hide it (I
(Guilhem) should later see if this triggers a non-serious Valgrind
error). Not serious error, because we will free description_event
later.
*/
ev= 0;
if (!force_if_open_opt &&
(glob_description_event->common_header->flags &
LOG_EVENT_BINLOG_IN_USE_F))
{
error("Attempting to dump binlog '%s', which was not closed properly. "
"Most probably, myblockchaind is still writing it, or it crashed. "
"Rerun with --force-if-open to ignore this problem.", logname);
DBUG_RETURN(ERROR_STOP);
}
break;
case binary_log::BEGIN_LOAD_QUERY_EVENT:
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
if ((retval= load_processor.process((Begin_load_query_log_event*) ev)) !=
OK_CONTINUE)
goto end;
break;
case binary_log::EXECUTE_LOAD_QUERY_EVENT:
{
Execute_load_query_log_event *exlq= (Execute_load_query_log_event*)ev;
char *fname= load_processor.grab_fname(exlq->file_id);
if (shall_skip_blockchain(exlq->db))
print_event_info->skipped_event_in_transaction= true;
else
{
if (fname)
{
convert_path_to_forward_slashes(fname);
exlq->print(result_file, print_event_info, fname);
if (head->error == -1)
{
if (fname)
my_free(fname);
goto err;
}
}
else
warning("Ignoring Execute_load_query since there is no "
"Begin_load_query event for file_id: %u", exlq->file_id);
}
if (fname)
my_free(fname);
break;
}
case binary_log::TABLE_MAP_EVENT:
{
Table_map_log_event *map= ((Table_map_log_event *)ev);
if (shall_skip_blockchain(map->get_db_name()))
{
print_event_info->skipped_event_in_transaction= true;
print_event_info->m_table_map_ignored.set_table(map->get_table_id(), map);
destroy_evt= FALSE;
goto end;
}
}
case binary_log::ROWS_QUERY_LOG_EVENT:
case binary_log::WRITE_ROWS_EVENT:
case binary_log::DELETE_ROWS_EVENT:
case binary_log::UPDATE_ROWS_EVENT:
case binary_log::WRITE_ROWS_EVENT_V1:
case binary_log::UPDATE_ROWS_EVENT_V1:
case binary_log::DELETE_ROWS_EVENT_V1:
case binary_log::PRE_GA_WRITE_ROWS_EVENT:
case binary_log::PRE_GA_DELETE_ROWS_EVENT:
case binary_log::PRE_GA_UPDATE_ROWS_EVENT:
{
bool stmt_end= FALSE;
Table_map_log_event *ignored_map= NULL;
if (ev_type == binary_log::WRITE_ROWS_EVENT ||
ev_type == binary_log::DELETE_ROWS_EVENT ||
ev_type == binary_log::UPDATE_ROWS_EVENT ||
ev_type == binary_log::WRITE_ROWS_EVENT_V1 ||
ev_type == binary_log::DELETE_ROWS_EVENT_V1 ||
ev_type == binary_log::UPDATE_ROWS_EVENT_V1)
{
Rows_log_event *new_ev= (Rows_log_event*) ev;
if (new_ev->get_flags(Rows_log_event::STMT_END_F))
stmt_end= TRUE;
ignored_map= print_event_info->m_table_map_ignored.get_table(new_ev->get_table_id());
}
else if (ev_type == binary_log::PRE_GA_WRITE_ROWS_EVENT ||
ev_type == binary_log::PRE_GA_DELETE_ROWS_EVENT ||
ev_type == binary_log::PRE_GA_UPDATE_ROWS_EVENT)
{
Old_rows_log_event *old_ev= (Old_rows_log_event*) ev;
if (old_ev->get_flags(Rows_log_event::STMT_END_F))
stmt_end= TRUE;
ignored_map= print_event_info->m_table_map_ignored.get_table(old_ev->get_table_id());
}
bool skip_event= (ignored_map != NULL);
/*
end of statement check:
i) destroy/free ignored maps
ii) if skip event
a) set the unflushed_events flag to false
b) since we are skipping the last event,
append END-MARKER(') to body cache (if required)
c) flush cache now
*/
if (stmt_end)
{
/*
Now is safe to clear ignored map (clear_tables will also
delete original table map events stored in the map).
*/
if (print_event_info->m_table_map_ignored.count() > 0)
print_event_info->m_table_map_ignored.clear_tables();
/*
One needs to take into account an event that gets
filtered but was last event in the statement. If this is
the case, previous rows events that were written into
IO_CACHEs still need to be copied from cache to
result_file (as it would happen in ev->print(...) if
event was not skipped).
*/
if (skip_event)
{
// set the unflushed_events flag to false
print_event_info->have_unflushed_events= FALSE;
// append END-MARKER(') with delimiter
IO_CACHE *const body_cache= &print_event_info->body_cache;
if (my_b_tell(body_cache))
my_b_printf(body_cache, "'%s\n", print_event_info->delimiter);
// flush cache
if ((copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
result_file, stop_never /* flush result_file */) ||
copy_event_cache_to_file_and_reinit(&print_event_info->body_cache,
result_file, stop_never /* flush result_file */) ||
copy_event_cache_to_file_and_reinit(&print_event_info->footer_cache,
result_file, stop_never /* flush result_file */)))
goto err;
}
}
/* skip the event check */
if (skip_event)
{
print_event_info->skipped_event_in_transaction= true;
goto end;
}
/*
These events must be printed in base64 format, if printed.
base64 format requires a FD event to be safe, so if no FD
event has been printed, we give an error. Except if user
passed --short-form, because --short-form disables printing
row events.
*/
if (!print_event_info->printed_fd_event && !short_form &&
ev_type != binary_log::TABLE_MAP_EVENT &&
ev_type != binary_log::ROWS_QUERY_LOG_EVENT &&
opt_base64_output_mode != BASE64_OUTPUT_DECODE_ROWS)
{
const char* type_str= ev->get_type_str();
if (opt_base64_output_mode == BASE64_OUTPUT_NEVER)
error("--base64-output=never specified, but binlog contains a "
"%s event which must be printed in base64.",
type_str);
else
error("malformed binlog: it does not contain any "
"Format_description_log_event. I now found a %s event, which "
"is not safe to process without a "
"Format_description_log_event.",
type_str);
goto err;
}
ev->print(result_file, print_event_info);
print_event_info->have_unflushed_events= TRUE;
/* Flush head,body and footer cache to result_file */
if (stmt_end)
{
print_event_info->have_unflushed_events= FALSE;
if (copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
result_file, stop_never /* flush result file */) ||
copy_event_cache_to_file_and_reinit(&print_event_info->body_cache,
result_file, stop_never /* flush result file */) ||
copy_event_cache_to_file_and_reinit(&print_event_info->footer_cache,
result_file, stop_never /* flush result file */))
goto err;
goto end;
}
break;
}
case binary_log::ANONYMOUS_GTID_LOG_EVENT:
case binary_log::GTID_LOG_EVENT:
{
seen_gtids= true;
print_event_info->is_gtid_next_set= true;
print_event_info->is_gtid_next_valid= true;
if (print_event_info->skipped_event_in_transaction == true)
fprintf(result_file, "COMMIT /* added by myblockchainbinlog */%s\n", print_event_info->delimiter);
print_event_info->skipped_event_in_transaction= false;
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
}
case binary_log::XID_EVENT:
{
in_transaction= false;
print_event_info->skipped_event_in_transaction= false;
if (print_event_info->is_gtid_next_set)
print_event_info->is_gtid_next_valid= false;
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
}
case binary_log::ROTATE_EVENT:
{
Rotate_log_event *rev= (Rotate_log_event *) ev;
/* no transaction context, gtids seen and not a fake rotate */
if (seen_gtids)
{
/*
Fake rotate events have 'when' set to zero. @c fake_rotate_event(...).
*/
bool is_fake= (rev->common_header->when.tv_sec == 0);
/*
'in_transaction' flag is not set to true even after GTID_LOG_EVENT
of a transaction is seen. ('myblockchainbinlog' tool assumes that there
is only one event per DDL transaction other than BEGIN and COMMIT
events. Using 'in_transaction' flag and 'starts_group', 'ends_group'
flags, DDL transaction generation is handled. Hence 'in_transaction'
cannot be set to true after seeing GTID_LOG_EVENT). So in order to
see if we are out of a transaction or not, we should check that
'in_transaction' is false and we have not seen GTID_LOG_EVENT.
To see if a GTID_LOG_EVENT of a transaction is seen or not,
we should check is_gtid_next_valid flag is false.
*/
if (!is_fake && !in_transaction &&
print_event_info->is_gtid_next_set &&
!print_event_info->is_gtid_next_valid)
{
/*
If processing multiple files, we must reset this flag,
since there may be no gtids on the next one.
*/
seen_gtids= false;
fprintf(result_file, "%sAUTOMATIC' /* added by myblockchainbinlog */ %s\n",
Gtid_log_event::SET_STRING_PREFIX,
print_event_info->delimiter);
print_event_info->is_gtid_next_set= false;
print_event_info->is_gtid_next_valid= true;
}
}
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
break;
}
case binary_log::PREVIOUS_GTIDS_LOG_EVENT:
if (one_blockchain && !opt_skip_gtids)
warning("The option --blockchain has been used. It may filter "
"parts of transactions, but will include the GTIDs in "
"any case. If you want to exclude or include transactions, "
"you should use the options --exclude-gtids or "
"--include-gtids, respectively, instead.");
/* fall through */
default:
ev->print(result_file, print_event_info);
if (head->error == -1)
goto err;
}
/* Flush head cache to result_file for every event */
if (copy_event_cache_to_file_and_reinit(&print_event_info->head_cache,
result_file, stop_never /* flush result_file */))
goto err;
}
goto end;
err:
retval= ERROR_STOP;
end:
rec_count++;
/*
Destroy the log_event object. If reading from a remote host,
set the temp_buf to NULL so that memory isn't freed twice.
*/
if (ev)
{
if (opt_remote_proto != BINLOG_LOCAL)
ev->temp_buf= 0;
if (destroy_evt) /* destroy it later if not set (ignored table map) */
delete ev;
}
DBUG_RETURN(retval);
}
static struct my_option my_long_options[] =
{
{"help", '?', "Display this help and exit.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"base64-output", OPT_BASE64_OUTPUT_MODE,
/* 'unspec' is not mentioned because it is just a placeholder. */
"Determine when the output statements should be base64-encoded BINLOG "
"statements: 'never' disables it and works only for binlogs without "
"row-based events; 'decode-rows' decodes row events into commented pseudo-SQL "
"statements if the --verbose option is also given; 'auto' prints base64 "
"only when necessary (i.e., for row-based events and format description "
"events). If no --base64-output[=name] option is given at all, the "
"default is 'auto'.",
&opt_base64_output_mode_str, &opt_base64_output_mode_str,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"bind-address", 0, "IP address to bind to.",
(uchar**) &opt_bind_addr, (uchar**) &opt_bind_addr, 0, GET_STR,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
/*
myblockchainbinlog needs charsets knowledge, to be able to convert a charset
number found in binlog to a charset name (to be able to print things
like this:
SET @`a`:=_cp850 0x4DFC6C6C6572 COLLATE `cp850_general_ci`;
*/
{"character-sets-dir", OPT_CHARSETS_DIR,
"Directory for character set files.", &charsets_dir,
&charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"blockchain", 'd', "List entries for just this blockchain (local log only).",
&blockchain, &blockchain, 0, GET_STR_ALLOC, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"rewrite-db", OPT_REWRITE_DB, "Rewrite the row event to point so that "
"it can be applied to a new blockchain", &rewrite, &rewrite, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#ifdef DBUG_OFF
{"debug", '#', "This is a non-debug version. Catch this and exit.",
0, 0, 0, GET_DISABLED, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"debug-check", OPT_DEBUG_CHECK, "This is a non-debug version. Catch this and exit.",
0, 0, 0,
GET_DISABLED, NO_ARG, 0, 0, 0, 0, 0, 0},
{"debug-info", OPT_DEBUG_INFO, "This is a non-debug version. Catch this and exit.", 0,
0, 0, GET_DISABLED, NO_ARG, 0, 0, 0, 0, 0, 0},
#else
{"debug", '#', "Output debug log.", &default_dbug_option,
&default_dbug_option, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"debug-check", OPT_DEBUG_CHECK, "Check memory and open file usage at exit .",
&debug_check_flag, &debug_check_flag, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"debug-info", OPT_DEBUG_INFO, "Print some debug info at exit.",
&debug_info_flag, &debug_info_flag,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"default_auth", OPT_DEFAULT_AUTH,
"Default authentication client-side plugin to use.",
&opt_default_auth, &opt_default_auth, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"disable-log-bin", 'D', "Disable binary log. This is useful, if you "
"enabled --to-last-log and are sending the output to the same MyBlockchain server. "
"This way you could avoid an endless loop. You would also like to use it "
"when restoring after a crash to avoid duplication of the statements you "
"already have. NOTE: you will need a SUPER privilege to use this option.",
&disable_log_bin, &disable_log_bin, 0, GET_BOOL,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"force-if-open", 'F', "Force if binlog was not closed properly.",
&force_if_open_opt, &force_if_open_opt, 0, GET_BOOL, NO_ARG,
1, 0, 0, 0, 0, 0},
{"force-read", 'f', "Force reading unknown binlog events.",
&force_opt, &force_opt, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"hexdump", 'H', "Augment output with hexadecimal and ASCII event dump.",
&opt_hexdump, &opt_hexdump, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
{"host", 'h', "Get the binlog from server.", &host, &host,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"idempotent", 'i', "Notify the server to use idempotent mode before "
"applying Row Events", &idempotent_mode, &idempotent_mode, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"local-load", 'l', "Prepare local temporary files for LOAD DATA INFILE in the specified directory.",
&dirname_for_local_load, &dirname_for_local_load, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"offset", 'o', "Skip the first N entries.", &offset, &offset,
0, GET_ULL, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"password", 'p', "Password to connect to remote server.",
0, 0, 0, GET_PASSWORD, OPT_ARG, 0, 0, 0, 0, 0, 0},
{"plugin_dir", OPT_PLUGIN_DIR, "Directory for client-side plugins.",
&opt_plugin_dir, &opt_plugin_dir, 0,
GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"port", 'P', "Port number to use for connection or 0 for default to, in "
"order of preference, my.cnf, $MYBLOCKCHAIN_TCP_PORT, "
#if MYBLOCKCHAIN_PORT_DEFAULT == 0
"/etc/services, "
#endif
"built-in default (" STRINGIFY_ARG(MYBLOCKCHAIN_PORT) ").",
&port, &port, 0, GET_INT, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"protocol", OPT_MYBLOCKCHAIN_PROTOCOL,
"The protocol to use for connection (tcp, socket, pipe, memory).",
0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"read-from-remote-server", 'R', "Read binary logs from a MyBlockchain server. "
"This is an alias for read-from-remote-master=BINLOG-DUMP-NON-GTIDS.",
&opt_remote_alias, &opt_remote_alias, 0, GET_BOOL, NO_ARG,
0, 0, 0, 0, 0, 0},
{"read-from-remote-master", OPT_REMOTE_PROTO,
"Read binary logs from a MyBlockchain server through the COM_BINLOG_DUMP or "
"COM_BINLOG_DUMP_GTID commands by setting the option to either "
"BINLOG-DUMP-NON-GTIDS or BINLOG-DUMP-GTIDS, respectively. If "
"--read-from-remote-master=BINLOG-DUMP-GTIDS is combined with "
"--exclude-gtids, transactions can be filtered out on the master "
"avoiding unnecessary network traffic.",
&opt_remote_proto_str, &opt_remote_proto_str, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"raw", OPT_RAW_OUTPUT, "Requires -R. Output raw binlog data instead of SQL "
"statements, output is to log files.",
&raw_mode, &raw_mode, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"result-file", 'r', "Direct output to a given file. With --raw this is a "
"prefix for the file names.",
&output_file, &output_file, 0, GET_STR, REQUIRED_ARG,
0, 0, 0, 0, 0, 0},
{"secure-auth", OPT_SECURE_AUTH, "Refuse client connecting to server if it"
" uses old (pre-4.1.1) protocol. Deprecated. Always TRUE",
&opt_secure_auth, &opt_secure_auth, 0, GET_BOOL, NO_ARG, 1, 0, 0, 0, 0, 0},
{"server-id", OPT_SERVER_ID,
"Extract only binlog entries created by the server having the given id.",
&filter_server_id, &filter_server_id, 0, GET_ULONG,
REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"server-id-bits", 0,
"Set number of significant bits in server-id",
&opt_server_id_bits, &opt_server_id_bits,
/* Default + Max 32 bits, minimum 7 bits */
0, GET_UINT, REQUIRED_ARG, 32, 7, 32, 0, 0, 0},
{"set-charset", OPT_SET_CHARSET,
"Add 'SET NAMES character_set' to the output.", &charset,
&charset, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
{"shared-memory-base-name", OPT_SHARED_MEMORY_BASE_NAME,
"Base name of shared memory.", &shared_memory_base_name,
&shared_memory_base_name,
0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
#endif
{"short-form", 's', "Just show regular queries: no extra info and no "
"row-based events. This is for testing only, and should not be used in "
"production systems. If you want to suppress base64-output, consider "
"using --base64-output=never instead.",
&short_form, &short_form, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0,
0, 0},
{"socket", 'S', "The socket file to use for connection.",
&sock, &sock, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0,
0, 0},
#include <sslopt-longopts.h>
{"start-datetime", OPT_START_DATETIME,
"Start reading the binlog at first event having a datetime equal or "
"posterior to the argument; the argument must be a date and time "
"in the local time zone, in any format accepted by the MyBlockchain server "
"for DATETIME and TIMESTAMP types, for example: 2004-12-25 11:25:56 "
"(you should probably use quotes for your shell to set it properly).",
&start_datetime_str, &start_datetime_str,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"start-position", 'j',
"Start reading the binlog at position N. Applies to the first binlog "
"passed on the command line.",
&start_position, &start_position, 0, GET_ULL,
REQUIRED_ARG, BIN_LOG_HEADER_SIZE, BIN_LOG_HEADER_SIZE,
/* COM_BINLOG_DUMP accepts only 4 bytes for the position */
(ulonglong)(~(uint32)0), 0, 0, 0},
{"stop-datetime", OPT_STOP_DATETIME,
"Stop reading the binlog at first event having a datetime equal or "
"posterior to the argument; the argument must be a date and time "
"in the local time zone, in any format accepted by the MyBlockchain server "
"for DATETIME and TIMESTAMP types, for example: 2004-12-25 11:25:56 "
"(you should probably use quotes for your shell to set it properly).",
&stop_datetime_str, &stop_datetime_str,
0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"stop-never", OPT_STOP_NEVER, "Wait for more data from the server "
"instead of stopping at the end of the last log. Implicitly sets "
"--to-last-log but instead of stopping at the end of the last log "
"it continues to wait till the server disconnects.",
&stop_never, &stop_never, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"stop-never-slave-server-id", OPT_WAIT_SERVER_ID,
"The slave server_id used for --read-from-remote-server --stop-never."
" This option cannot be used together with connection-server-id.",
&stop_never_slave_server_id, &stop_never_slave_server_id, 0,
GET_LL, REQUIRED_ARG, -1, -1, 0xFFFFFFFFLL, 0, 0, 0},
{"connection-server-id", OPT_CONNECTION_SERVER_ID,
"The slave server_id used for --read-from-remote-server."
" This option cannot be used together with stop-never-slave-server-id.",
&connection_server_id, &connection_server_id, 0,
GET_LL, REQUIRED_ARG, -1, -1, 0xFFFFFFFFLL, 0, 0, 0},
{"stop-position", OPT_STOP_POSITION,
"Stop reading the binlog at position N. Applies to the last binlog "
"passed on the command line.",
&stop_position, &stop_position, 0, GET_ULL,
REQUIRED_ARG, (longlong)(~(my_off_t)0), BIN_LOG_HEADER_SIZE,
(ulonglong)(~(my_off_t)0), 0, 0, 0},
{"to-last-log", 't', "Requires -R. Will not stop at the end of the "
"requested binlog but rather continue printing until the end of the last "
"binlog of the MyBlockchain server. If you send the output to the same MyBlockchain "
"server, that may lead to an endless loop.",
&to_last_remote_log, &to_last_remote_log, 0, GET_BOOL,
NO_ARG, 0, 0, 0, 0, 0, 0},
{"user", 'u', "Connect to the remote server as username.",
&user, &user, 0, GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0,
0, 0},
{"verbose", 'v', "Reconstruct pseudo-SQL statements out of row events. "
"-v -v adds comments on column data types.",
0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
{"version", 'V', "Print version and exit.", 0, 0, 0, GET_NO_ARG, NO_ARG, 0,
0, 0, 0, 0, 0},
{"open_files_limit", OPT_OPEN_FILES_LIMIT,
"Used to reserve file descriptors for use by this program.",
&open_files_limit, &open_files_limit, 0, GET_ULONG,
REQUIRED_ARG, MY_NFILE, 8, OS_FILE_LIMIT, 0, 1, 0},
{"verify-binlog-checksum", 'c', "Verify checksum binlog events.",
(uchar**) &opt_verify_binlog_checksum, (uchar**) &opt_verify_binlog_checksum,
0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"binlog-row-event-max-size", OPT_BINLOG_ROWS_EVENT_MAX_SIZE,
"The maximum size of a row-based binary log event in bytes. Rows will be "
"grouped into events smaller than this size if possible. "
"This value must be a multiple of 256.",
&opt_binlog_rows_event_max_size,
&opt_binlog_rows_event_max_size, 0,
GET_ULONG, REQUIRED_ARG,
/* def_value 4GB */ UINT_MAX, /* min_value */ 256,
/* max_value */ ULONG_MAX, /* sub_size */ 0,
/* block_size */ 256, /* app_type */ 0},
{"skip-gtids", OPT_MYBLOCKCHAINBINLOG_SKIP_GTIDS,
"Do not preserve Global Transaction Identifiers; instead make the server "
"execute the transactions as if they were new.",
&opt_skip_gtids, &opt_skip_gtids, 0,
GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
{"include-gtids", OPT_MYBLOCKCHAINBINLOG_INCLUDE_GTIDS,
"Print events whose Global Transaction Identifiers "
"were provided.",
&opt_include_gtids_str, &opt_include_gtids_str, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{"exclude-gtids", OPT_MYBLOCKCHAINBINLOG_EXCLUDE_GTIDS,
"Print all events but those whose Global Transaction "
"Identifiers were provided.",
&opt_exclude_gtids_str, &opt_exclude_gtids_str, 0,
GET_STR_ALLOC, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
};
/**
Auxiliary function used by error() and warning().
Prints the given text (normally "WARNING: " or "ERROR: "), followed
by the given vprintf-style string, followed by a newline.
@param format Printf-style format string.
@param args List of arguments for the format string.
@param msg Text to print before the string.
*/
static void error_or_warning(const char *format, va_list args, const char *msg)
{
fprintf(stderr, "%s: ", msg);
vfprintf(stderr, format, args);
fprintf(stderr, "\n");
}
/**
Prints a message to stderr, prefixed with the text "ERROR: " and
suffixed with a newline.
@param format Printf-style format string, followed by printf
varargs.
*/
static void error(const char *format,...)
{
va_list args;
va_start(args, format);
error_or_warning(format, args, "ERROR");
va_end(args);
}
/**
This function is used in log_event.cc to report errors.
@param format Printf-style format string, followed by printf
varargs.
*/
static void sql_print_error(const char *format,...)
{
va_list args;
va_start(args, format);
error_or_warning(format, args, "ERROR");
va_end(args);
}
/**
Prints a message to stderr, prefixed with the text "WARNING: " and
suffixed with a newline.
@param format Printf-style format string, followed by printf
varargs.
*/
static void warning(const char *format,...)
{
va_list args;
va_start(args, format);
error_or_warning(format, args, "WARNING");
va_end(args);
}
/**
Frees memory for global variables in this file.
*/
static void cleanup()
{
my_free(pass);
my_free(blockchain);
my_free(rewrite);
my_free(host);
my_free(user);
my_free(dirname_for_local_load);
for (size_t i= 0; i < buff_ev->size(); i++)
{
buff_event_info pop_event_array= buff_ev->at(i);
delete (pop_event_array.event);
}
delete buff_ev;
delete glob_description_event;
if (myblockchain)
myblockchain_close(myblockchain);
}
static void print_version()
{
printf("%s Ver 3.4 for %s at %s\n", my_progname, SYSTEM_TYPE, MACHINE_TYPE);
}
static void usage()
{
print_version();
puts(ORACLE_WELCOME_COPYRIGHT_NOTICE("2000"));
printf("\
Dumps a MyBlockchain binary log in a format usable for viewing or for piping to\n\
the myblockchain command line client.\n\n");
printf("Usage: %s [options] log-files\n", my_progname);
/*
Turn default for zombies off so that the help on how to
turn them off text won't show up.
This is safe to do since it's followed by a call to exit().
*/
for (struct my_option *optp= my_long_options; optp->name; optp++)
{
if (optp->id == OPT_SECURE_AUTH)
{
optp->def_value= 0;
break;
}
}
my_print_help(my_long_options);
my_print_variables(my_long_options);
}
static my_time_t convert_str_to_timestamp(const char* str)
{
MYBLOCKCHAIN_TIME_STATUS status;
MYBLOCKCHAIN_TIME l_time;
long dummy_my_timezone;
my_bool dummy_in_dst_time_gap;
/* We require a total specification (date AND time) */
if (str_to_datetime(str, strlen(str), &l_time, 0, &status) ||
l_time.time_type != MYBLOCKCHAIN_TIMESTAMP_DATETIME || status.warnings)
{
error("Incorrect date and time argument: %s", str);
exit(1);
}
/*
Note that Feb 30th, Apr 31st cause no error messages and are mapped to
the next existing day, like in myblockchaind. Maybe this could be changed when
myblockchaind is changed too (with its "strict" mode?).
*/
return
my_system_gmt_sec(&l_time, &dummy_my_timezone, &dummy_in_dst_time_gap);
}
extern "C" my_bool
get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
char *argument)
{
bool tty_password=0;
switch (optid) {
#ifndef DBUG_OFF
case '#':
DBUG_PUSH(argument ? argument : default_dbug_option);
break;
#endif
#include <sslopt-case.h>
case 'd':
one_blockchain = 1;
break;
case OPT_REWRITE_DB:
{
char *from_db= argument, *p, *to_db;
if (!(p= strstr(argument, "->")))
{
sql_print_error("Bad syntax in myblockchainbinlog-rewrite-db - missing '->'!\n");
return 1;
}
to_db= p + 2;
while(p > argument && my_isspace(myblockchaind_charset, p[-1]))
p--;
*p= 0;
if (!*from_db)
{
sql_print_error("Bad syntax in myblockchainbinlog-rewrite-db - empty FROM db!\n");
return 1;
}
while (*to_db && my_isspace(myblockchaind_charset, *to_db))
to_db++;
if (!*to_db)
{
sql_print_error("Bad syntax in myblockchainbinlog-rewrite-db - empty TO db!\n");
return 1;
}
/* Add the blockchain to the mapping */
map_myblockchainbinlog_rewrite_db[from_db]= to_db;
break;
}
case 'p':
if (argument == disabled_my_option)
argument= (char*) ""; // Don't require password
if (argument)
{
my_free(pass);
char *start=argument;
pass= my_strdup(PSI_NOT_INSTRUMENTED,
argument,MYF(MY_FAE));
while (*argument) *argument++= 'x'; /* Destroy argument */
if (*start)
start[1]=0; /* Cut length of argument */
}
else
tty_password=1;
break;
case 'R':
opt_remote_alias= 1;
opt_remote_proto= BINLOG_DUMP_NON_GTID;
break;
case OPT_REMOTE_PROTO:
opt_remote_proto= (enum_remote_proto)
(find_type_or_exit(argument, &remote_proto_typelib, opt->name) - 1);
break;
case OPT_MYBLOCKCHAIN_PROTOCOL:
opt_protocol= find_type_or_exit(argument, &sql_protocol_typelib,
opt->name);
break;
case OPT_START_DATETIME:
start_datetime= convert_str_to_timestamp(start_datetime_str);
break;
case OPT_STOP_DATETIME:
stop_datetime= convert_str_to_timestamp(stop_datetime_str);
break;
case OPT_BASE64_OUTPUT_MODE:
opt_base64_output_mode= (enum_base64_output_mode)
(find_type_or_exit(argument, &base64_output_mode_typelib, opt->name)-1);
break;
case 'v':
if (argument == disabled_my_option)
verbose= 0;
else
verbose++;
break;
case 'V':
print_version();
exit(0);
case OPT_STOP_NEVER:
/* wait-for-data implicitly sets to-last-log */
to_last_remote_log= 1;
break;
case '?':
usage();
exit(0);
case OPT_SECURE_AUTH:
/* --secure-auth is a zombie option. */
if (!opt_secure_auth)
{
fprintf(stderr, "myblockchainbinlog: [ERROR] --skip-secure-auth is not supported.\n");
exit(1);
}
else
CLIENT_WARN_DEPRECATED_NO_REPLACEMENT("--secure-auth");
break;
}
if (tty_password)
pass= get_tty_password(NullS);
return 0;
}
static int parse_args(int *argc, char*** argv)
{
int ho_error;
result_file = stdout;
if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
exit(ho_error);
if (debug_info_flag)
my_end_arg= MY_CHECK_ERROR | MY_GIVE_INFO;
if (debug_check_flag)
my_end_arg= MY_CHECK_ERROR;
return 0;
}
/**
Create and initialize the global myblockchain object, and connect to the
server.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
static Exit_status safe_connect()
{
myblockchain= myblockchain_init(NULL);
if (!myblockchain)
{
error("Failed on myblockchain_init.");
return ERROR_STOP;
}
SSL_SET_OPTIONS(myblockchain);
if (opt_plugin_dir && *opt_plugin_dir)
myblockchain_options(myblockchain, MYBLOCKCHAIN_PLUGIN_DIR, opt_plugin_dir);
if (opt_default_auth && *opt_default_auth)
myblockchain_options(myblockchain, MYBLOCKCHAIN_DEFAULT_AUTH, opt_default_auth);
if (opt_protocol)
myblockchain_options(myblockchain, MYBLOCKCHAIN_OPT_PROTOCOL, (char*) &opt_protocol);
if (opt_bind_addr)
myblockchain_options(myblockchain, MYBLOCKCHAIN_OPT_BIND, opt_bind_addr);
#if defined (_WIN32) && !defined (EMBEDDED_LIBRARY)
if (shared_memory_base_name)
myblockchain_options(myblockchain, MYBLOCKCHAIN_SHARED_MEMORY_BASE_NAME,
shared_memory_base_name);
#endif
myblockchain_options(myblockchain, MYBLOCKCHAIN_OPT_CONNECT_ATTR_RESET, 0);
myblockchain_options4(myblockchain, MYBLOCKCHAIN_OPT_CONNECT_ATTR_ADD,
"program_name", "myblockchainbinlog");
myblockchain_options4(myblockchain, MYBLOCKCHAIN_OPT_CONNECT_ATTR_ADD,
"_client_role", "binary_log_listener");
if (!myblockchain_real_connect(myblockchain, host, user, pass, 0, port, sock, 0))
{
error("Failed on connect: %s", myblockchain_error(myblockchain));
return ERROR_STOP;
}
myblockchain->reconnect= 1;
return OK_CONTINUE;
}
/**
High-level function for dumping a named binlog.
This function calls dump_remote_log_entries() or
dump_local_log_entries() to do the job.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status dump_single_log(PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
DBUG_ENTER("dump_single_log");
Exit_status rc= OK_CONTINUE;
switch (opt_remote_proto)
{
case BINLOG_LOCAL:
rc= dump_local_log_entries(print_event_info, logname);
break;
case BINLOG_DUMP_NON_GTID:
case BINLOG_DUMP_GTID:
rc= dump_remote_log_entries(print_event_info, logname);
break;
default:
DBUG_ASSERT(0);
break;
}
DBUG_RETURN(rc);
}
static Exit_status dump_multiple_logs(int argc, char **argv)
{
DBUG_ENTER("dump_multiple_logs");
Exit_status rc= OK_CONTINUE;
PRINT_EVENT_INFO print_event_info;
if (!print_event_info.init_ok())
DBUG_RETURN(ERROR_STOP);
/*
Set safe delimiter, to dump things
like CREATE PROCEDURE safely
*/
if (!raw_mode)
{
fprintf(result_file, "DELIMITER /*!*/;\n");
}
my_stpcpy(print_event_info.delimiter, "/*!*/;");
print_event_info.verbose= short_form ? 0 : verbose;
print_event_info.short_form= short_form;
print_event_info.base64_output_mode= opt_base64_output_mode;
print_event_info.skip_gtids= opt_skip_gtids;
// Dump all logs.
my_off_t save_stop_position= stop_position;
stop_position= ~(my_off_t)0;
for (int i= 0; i < argc; i++)
{
if (i == argc - 1) // last log, --stop-position applies
stop_position= save_stop_position;
if ((rc= dump_single_log(&print_event_info, argv[i])) != OK_CONTINUE)
break;
// For next log, --start-position does not apply
start_position= BIN_LOG_HEADER_SIZE;
}
if (!buff_ev->empty())
warning("The range of printed events ends with an Intvar_event, "
"Rand_event or User_var_event with no matching Query_log_event. "
"This might be because the last statement was not fully written "
"to the log, or because you are using a --stop-position or "
"--stop-datetime that refers to an event in the middle of a "
"statement. The event(s) from the partial statement have not been "
"written to output. ");
else if (print_event_info.have_unflushed_events)
warning("The range of printed events ends with a row event or "
"a table map event that does not have the STMT_END_F "
"flag set. This might be because the last statement "
"was not fully written to the log, or because you are "
"using a --stop-position or --stop-datetime that refers "
"to an event in the middle of a statement. The event(s) "
"from the partial statement have not been written to output.");
/* Set delimiter back to semicolon */
if (!raw_mode)
{
if (print_event_info.skipped_event_in_transaction)
fprintf(result_file, "COMMIT /* added by myblockchainbinlog */%s\n", print_event_info.delimiter);
if (!print_event_info.is_gtid_next_valid)
{
fprintf(result_file, "%sAUTOMATIC' /* added by myblockchainbinlog */%s\n",
Gtid_log_event::SET_STRING_PREFIX,
print_event_info.delimiter);
print_event_info.is_gtid_next_set= false;
print_event_info.is_gtid_next_valid= true;
}
fprintf(result_file, "DELIMITER ;\n");
my_stpcpy(print_event_info.delimiter, ";");
}
DBUG_RETURN(rc);
}
/**
When reading a remote binlog, this function is used to grab the
Format_description_log_event in the beginning of the stream.
This is not as smart as check_header() (used for local log); it will
not work for a binlog which mixes format. TODO: fix this.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
*/
static Exit_status check_master_version()
{
DBUG_ENTER("check_master_version");
MYBLOCKCHAIN_RES* res = 0;
MYBLOCKCHAIN_ROW row;
const char* version;
if (myblockchain_query(myblockchain, "SELECT VERSION()") ||
!(res = myblockchain_store_result(myblockchain)))
{
error("Could not find server version: "
"Query failed when checking master version: %s", myblockchain_error(myblockchain));
DBUG_RETURN(ERROR_STOP);
}
if (!(row = myblockchain_fetch_row(res)))
{
error("Could not find server version: "
"Master returned no rows for SELECT VERSION().");
goto err;
}
if (!(version = row[0]))
{
error("Could not find server version: "
"Master reported NULL for the version.");
goto err;
}
/*
Make a notice to the server that this client
is checksum-aware. It does not need the first fake Rotate
necessary checksummed.
That preference is specified below.
*/
if (myblockchain_query(myblockchain, "SET @master_binlog_checksum='NONE'"))
{
error("Could not notify master about checksum awareness."
"Master returned '%s'", myblockchain_error(myblockchain));
goto err;
}
delete glob_description_event;
switch (*version) {
case '3':
glob_description_event= new Format_description_log_event(1);
break;
case '4':
glob_description_event= new Format_description_log_event(3);
break;
case '5':
/*
The server is soon going to send us its Format_description log
event, unless it is a 5.0 server with 3.23 or 4.0 binlogs.
So we first assume that this is 4.0 (which is enough to read the
Format_desc event if one comes).
*/
glob_description_event= new Format_description_log_event(3);
break;
default:
glob_description_event= NULL;
error("Could not find server version: "
"Master reported unrecognized MyBlockchain version '%s'.", version);
goto err;
}
if (!glob_description_event || !glob_description_event->is_valid())
{
error("Failed creating Format_description_log_event; out of memory?");
goto err;
}
myblockchain_free_result(res);
DBUG_RETURN(OK_CONTINUE);
err:
myblockchain_free_result(res);
DBUG_RETURN(ERROR_STOP);
}
static int get_dump_flags()
{
return stop_never ? 0 : BINLOG_DUMP_NON_BLOCK;
}
/**
Requests binlog dump from a remote server and prints the events it
receives.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status dump_remote_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
uchar *command_buffer= NULL;
size_t command_size= 0;
ulong len= 0;
size_t logname_len= 0;
uint server_id= 0;
NET* net= NULL;
my_off_t old_off= start_position_mot;
char fname[FN_REFLEN + 1];
char log_file_name[FN_REFLEN + 1];
Exit_status retval= OK_CONTINUE;
enum enum_server_command command= COM_END;
DBUG_ENTER("dump_remote_log_entries");
fname[0]= log_file_name[0]= 0;
/*
Even if we already read one binlog (case of >=2 binlogs on command line),
we cannot re-use the same connection as before, because it is now dead
(COM_BINLOG_DUMP kills the thread when it finishes).
*/
if ((retval= safe_connect()) != OK_CONTINUE)
DBUG_RETURN(retval);
net= &myblockchain->net;
if ((retval= check_master_version()) != OK_CONTINUE)
DBUG_RETURN(retval);
/*
Fake a server ID to log continously. This will show as a
slave on the myblockchain server.
*/
if (to_last_remote_log && stop_never)
{
if (stop_never_slave_server_id == -1)
server_id= 1;
else
server_id= static_cast<uint>(stop_never_slave_server_id);
}
else
server_id= 0;
if (connection_server_id != -1)
server_id= static_cast<uint>(connection_server_id);
size_t tlen = strlen(logname);
if (tlen > UINT_MAX)
{
error("Log name too long.");
DBUG_RETURN(ERROR_STOP);
}
const size_t BINLOG_NAME_INFO_SIZE= logname_len= tlen;
if (opt_remote_proto == BINLOG_DUMP_NON_GTID)
{
command= COM_BINLOG_DUMP;
size_t allocation_size= ::BINLOG_POS_OLD_INFO_SIZE +
BINLOG_NAME_INFO_SIZE + ::BINLOG_FLAGS_INFO_SIZE +
::BINLOG_SERVER_ID_INFO_SIZE + 1;
if (!(command_buffer= (uchar *) my_malloc(PSI_NOT_INSTRUMENTED,
allocation_size, MYF(MY_WME))))
{
error("Got fatal error allocating memory.");
DBUG_RETURN(ERROR_STOP);
}
uchar* ptr_buffer= command_buffer;
/*
COM_BINLOG_DUMP accepts only 4 bytes for the position, so
we are forced to cast to uint32.
*/
int4store(ptr_buffer, (uint32) start_position);
ptr_buffer+= ::BINLOG_POS_OLD_INFO_SIZE;
int2store(ptr_buffer, get_dump_flags());
ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE;
int4store(ptr_buffer, server_id);
ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE;
memcpy(ptr_buffer, logname, BINLOG_NAME_INFO_SIZE);
ptr_buffer+= BINLOG_NAME_INFO_SIZE;
command_size= ptr_buffer - command_buffer;
DBUG_ASSERT(command_size == (allocation_size - 1));
}
else
{
command= COM_BINLOG_DUMP_GTID;
global_sid_lock->rdlock();
// allocate buffer
size_t encoded_data_size= gtid_set_excluded->get_encoded_length();
size_t allocation_size=
::BINLOG_FLAGS_INFO_SIZE + ::BINLOG_SERVER_ID_INFO_SIZE +
::BINLOG_NAME_SIZE_INFO_SIZE + BINLOG_NAME_INFO_SIZE +
::BINLOG_POS_INFO_SIZE + ::BINLOG_DATA_SIZE_INFO_SIZE +
encoded_data_size + 1;
if (!(command_buffer= (uchar *) my_malloc(PSI_NOT_INSTRUMENTED,
allocation_size, MYF(MY_WME))))
{
error("Got fatal error allocating memory.");
global_sid_lock->unlock();
DBUG_RETURN(ERROR_STOP);
}
uchar* ptr_buffer= command_buffer;
int2store(ptr_buffer, get_dump_flags());
ptr_buffer+= ::BINLOG_FLAGS_INFO_SIZE;
int4store(ptr_buffer, server_id);
ptr_buffer+= ::BINLOG_SERVER_ID_INFO_SIZE;
int4store(ptr_buffer, static_cast<uint32>(BINLOG_NAME_INFO_SIZE));
ptr_buffer+= ::BINLOG_NAME_SIZE_INFO_SIZE;
memcpy(ptr_buffer, logname, BINLOG_NAME_INFO_SIZE);
ptr_buffer+= BINLOG_NAME_INFO_SIZE;
int8store(ptr_buffer, start_position);
ptr_buffer+= ::BINLOG_POS_INFO_SIZE;
int4store(ptr_buffer, static_cast<uint32>(encoded_data_size));
ptr_buffer+= ::BINLOG_DATA_SIZE_INFO_SIZE;
gtid_set_excluded->encode(ptr_buffer);
ptr_buffer+= encoded_data_size;
global_sid_lock->unlock();
command_size= ptr_buffer - command_buffer;
DBUG_ASSERT(command_size == (allocation_size - 1));
}
if (simple_command(myblockchain, command, command_buffer, command_size, 1))
{
error("Got fatal error sending the log dump command.");
my_free(command_buffer);
DBUG_RETURN(ERROR_STOP);
}
my_free(command_buffer);
for (;;)
{
const char *error_msg= NULL;
Log_event *ev= NULL;
Log_event_type type= binary_log::UNKNOWN_EVENT;
len= cli_safe_read(myblockchain, NULL);
if (len == packet_error)
{
error("Got error reading packet from server: %s", myblockchain_error(myblockchain));
DBUG_RETURN(ERROR_STOP);
}
if (len < 8 && net->read_pos[0] == 254)
break; // end of data
DBUG_PRINT("info",( "len: %lu net->read_pos[5]: %d\n",
len, net->read_pos[5]));
/*
In raw mode We only need the full event details if it is a
ROTATE_EVENT or FORMAT_DESCRIPTION_EVENT
*/
type= (Log_event_type) net->read_pos[1 + EVENT_TYPE_OFFSET];
/*
Ignore HEARBEAT events. They can show up if myblockchainbinlog is
running with:
--read-from-remote-server
--read-from-remote-master=BINLOG-DUMP-GTIDS'
--stop-never
--stop-never-slave-server-id
i.e., acting as a fake slave.
*/
if (type == binary_log::HEARTBEAT_LOG_EVENT)
continue;
if (!raw_mode || (type == binary_log::ROTATE_EVENT) ||
(type == binary_log::FORMAT_DESCRIPTION_EVENT))
{
if (!(ev= Log_event::read_log_event((const char*) net->read_pos + 1 ,
len - 1, &error_msg,
glob_description_event,
opt_verify_binlog_checksum)))
{
error("Could not construct log event object: %s", error_msg);
DBUG_RETURN(ERROR_STOP);
}
/*
If reading from a remote host, ensure the temp_buf for the
Log_event class is pointing to the incoming stream.
*/
ev->register_temp_buf((char *) net->read_pos + 1);
}
if (raw_mode || (type != binary_log::LOAD_EVENT))
{
/*
If this is a Rotate event, maybe it's the end of the requested binlog;
in this case we are done (stop transfer).
This is suitable for binlogs, not relay logs (but for now we don't read
relay logs remotely because the server is not able to do that). If one
day we read relay logs remotely, then we will have a problem with the
detection below: relay logs contain Rotate events which are about the
binlogs, so which would trigger the end-detection below.
*/
if (type == binary_log::ROTATE_EVENT)
{
Rotate_log_event *rev= (Rotate_log_event *)ev;
/*
If this is a fake Rotate event, and not about our log, we can stop
transfer. If this a real Rotate event (so it's not about our log,
it's in our log describing the next log), we print it (because it's
part of our log) and then we will stop when we receive the fake one
soon.
*/
if (raw_mode)
{
if (output_file != 0)
{
my_snprintf(log_file_name, sizeof(log_file_name), "%s%s",
output_file, rev->new_log_ident);
}
else
{
my_stpcpy(log_file_name, rev->new_log_ident);
}
}
if (rev->common_header->when.tv_sec == 0)
{
if (!to_last_remote_log)
{
if ((rev->ident_len != logname_len) ||
memcmp(rev->new_log_ident, logname, logname_len))
{
DBUG_RETURN(OK_CONTINUE);
}
/*
Otherwise, this is a fake Rotate for our log, at the very
beginning for sure. Skip it, because it was not in the original
log. If we are running with to_last_remote_log, we print it,
because it serves as a useful marker between binlogs then.
*/
continue;
}
/*
Reset the value of '# at pos' field shown against first event of
next binlog file (fake rotate) picked by myblockchainbinlog --to-last-log
*/
old_off= start_position_mot;
len= 1; // fake Rotate, so don't increment old_off
}
}
else if (type == binary_log::FORMAT_DESCRIPTION_EVENT)
{
/*
This could be an fake Format_description_log_event that server
(5.0+) automatically sends to a slave on connect, before sending
a first event at the requested position. If this is the case,
don't increment old_off. Real Format_description_log_event always
starts from BIN_LOG_HEADER_SIZE position.
*/
// fake event when not in raw mode, don't increment old_off
if ((old_off != BIN_LOG_HEADER_SIZE) && (!raw_mode))
len= 1;
if (raw_mode)
{
if (result_file && (result_file != stdout))
my_fclose(result_file, MYF(0));
if (!(result_file = my_fopen(log_file_name, O_WRONLY | O_BINARY,
MYF(MY_WME))))
{
error("Could not create log file '%s'", log_file_name);
DBUG_RETURN(ERROR_STOP);
}
DBUG_EXECUTE_IF("simulate_result_file_write_error_for_FD_event",
DBUG_SET("+d,simulate_fwrite_error"););
if (my_fwrite(result_file, (const uchar*) BINLOG_MAGIC,
BIN_LOG_HEADER_SIZE, MYF(MY_NABP)))
{
error("Could not write into log file '%s'", log_file_name);
DBUG_RETURN(ERROR_STOP);
}
/*
Need to handle these events correctly in raw mode too
or this could get messy
*/
delete glob_description_event;
glob_description_event= (Format_description_log_event*) ev;
print_event_info->common_header_len= glob_description_event->common_header_len;
ev->temp_buf= 0;
ev= 0;
}
}
if (type == binary_log::LOAD_EVENT)
{
DBUG_ASSERT(raw_mode);
warning("Attempting to load a remote pre-4.0 binary log that contains "
"LOAD DATA INFILE statements. The file will not be copied from "
"the remote server. ");
}
if (raw_mode)
{
DBUG_EXECUTE_IF("simulate_result_file_write_error",
DBUG_SET("+d,simulate_fwrite_error"););
if (my_fwrite(result_file, net->read_pos + 1 , len - 1, MYF(MY_NABP)))
{
error("Could not write into log file '%s'", log_file_name);
retval= ERROR_STOP;
}
if (ev)
{
ev->temp_buf=0;
delete ev;
}
}
else
{
retval= process_event(print_event_info, ev, old_off, logname);
}
if (retval != OK_CONTINUE)
DBUG_RETURN(retval);
}
else
{
Load_log_event *le= (Load_log_event*)ev;
const char *old_fname= le->fname;
size_t old_len= le->fname_len;
File file;
if ((file= load_processor.prepare_new_file_for_old_format(le,fname)) < 0)
DBUG_RETURN(ERROR_STOP);
retval= process_event(print_event_info, ev, old_off, logname);
if (retval != OK_CONTINUE)
{
my_close(file,MYF(MY_WME));
DBUG_RETURN(retval);
}
retval= load_processor.load_old_format_file(net,old_fname,old_len,file);
my_close(file,MYF(MY_WME));
if (retval != OK_CONTINUE)
DBUG_RETURN(retval);
}
/*
Let's adjust offset for remote log as for local log to produce
similar text and to have --stop-position to work identically.
*/
old_off+= len-1;
}
DBUG_RETURN(OK_CONTINUE);
}
/**
Reads the @c Format_description_log_event from the beginning of a
local input file.
The @c Format_description_log_event is only read if it is outside
the range specified with @c --start-position; otherwise, it will be
seen later. If this is an old binlog, a fake @c
Format_description_event is created. This also prints a @c
Format_description_log_event to the output, unless we reach the
--start-position range. In this case, it is assumed that a @c
Format_description_log_event will be found when reading events the
usual way.
@param file The file to which a @c Format_description_log_event will
be printed.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@param[in] logname Name of input binlog.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status check_header(IO_CACHE* file,
PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
DBUG_ENTER("check_header");
uchar header[BIN_LOG_HEADER_SIZE];
uchar buf[PROBE_HEADER_LEN];
my_off_t tmp_pos, pos;
MY_STAT my_file_stat;
delete glob_description_event;
if (!(glob_description_event= new Format_description_log_event(3)))
{
error("Failed creating Format_description_log_event; out of memory?");
DBUG_RETURN(ERROR_STOP);
}
pos= my_b_tell(file);
/* fstat the file to check if the file is a regular file. */
if (my_fstat(file->file, &my_file_stat, MYF(0)) == -1)
{
error("Unable to stat the file.");
DBUG_RETURN(ERROR_STOP);
}
if ((my_file_stat.st_mode & S_IFMT) == S_IFREG)
my_b_seek(file, (my_off_t)0);
if (my_b_read(file, header, sizeof(header)))
{
error("Failed reading header; probably an empty file.");
DBUG_RETURN(ERROR_STOP);
}
if (memcmp(header, BINLOG_MAGIC, sizeof(header)))
{
error("File is not a binary log file.");
DBUG_RETURN(ERROR_STOP);
}
/*
Imagine we are running with --start-position=1000. We still need
to know the binlog format's. So we still need to find, if there is
one, the Format_desc event, or to know if this is a 3.23
binlog. So we need to first read the first events of the log,
those around offset 4. Even if we are reading a 3.23 binlog from
the start (no --start-position): we need to know the header length
(which is 13 in 3.23, 19 in 4.x) to be able to successfully print
the first event (Start_log_event_v3). So even in this case, we
need to "probe" the first bytes of the log *before* we do a real
read_log_event(). Because read_log_event() needs to know the
header's length to work fine.
*/
for(;;)
{
tmp_pos= my_b_tell(file); /* should be 4 the first time */
if (my_b_read(file, buf, sizeof(buf)))
{
if (file->error)
{
error("Could not read entry at offset %llu: "
"Error in log format or read error.", (ulonglong)tmp_pos);
DBUG_RETURN(ERROR_STOP);
}
/*
Otherwise this is just EOF : this log currently contains 0-2
events. Maybe it's going to be filled in the next
milliseconds; then we are going to have a problem if this a
3.23 log (imagine we are locally reading a 3.23 binlog which
is being written presently): we won't know it in
read_log_event() and will fail(). Similar problems could
happen with hot relay logs if --start-position is used (but a
--start-position which is posterior to the current size of the log).
These are rare problems anyway (reading a hot log + when we
read the first events there are not all there yet + when we
read a bit later there are more events + using a strange
--start-position).
*/
break;
}
else
{
DBUG_PRINT("info",("buf[EVENT_TYPE_OFFSET=%d]=%d",
EVENT_TYPE_OFFSET, buf[EVENT_TYPE_OFFSET]));
/* always test for a Start_v3, even if no --start-position */
if (buf[EVENT_TYPE_OFFSET] == binary_log::START_EVENT_V3)
{
/* This is 3.23 or 4.x */
if (uint4korr(buf + EVENT_LEN_OFFSET) <
(LOG_EVENT_MINIMAL_HEADER_LEN + Binary_log_event::START_V3_HEADER_LEN))
{
/* This is 3.23 (format 1) */
delete glob_description_event;
if (!(glob_description_event= new Format_description_log_event(1)))
{
error("Failed creating Format_description_log_event; "
"out of memory?");
DBUG_RETURN(ERROR_STOP);
}
}
break;
}
else if (tmp_pos >= start_position)
break;
else if (buf[EVENT_TYPE_OFFSET] == binary_log::FORMAT_DESCRIPTION_EVENT)
{
/* This is 5.0 */
Format_description_log_event *new_description_event;
my_b_seek(file, tmp_pos); /* seek back to event's start */
if (!(new_description_event= (Format_description_log_event*)
Log_event::read_log_event(file, glob_description_event,
opt_verify_binlog_checksum,
rewrite_db_filter)))
/* EOF can't be hit here normally, so it's a real error */
{
error("Could not read a Format_description_log_event event at "
"offset %llu; this could be a log format error or read error.",
(ulonglong)tmp_pos);
DBUG_RETURN(ERROR_STOP);
}
if (opt_base64_output_mode == BASE64_OUTPUT_AUTO)
{
/*
process_event will delete *description_event and set it to
the new one, so we should not do it ourselves in this
case.
*/
Exit_status retval= process_event(print_event_info,
new_description_event, tmp_pos,
logname);
if (retval != OK_CONTINUE)
DBUG_RETURN(retval);
}
else
{
delete glob_description_event;
glob_description_event= new_description_event;
}
DBUG_PRINT("info",("Setting description_event"));
}
else if (buf[EVENT_TYPE_OFFSET] == binary_log::ROTATE_EVENT)
{
Log_event *ev;
my_b_seek(file, tmp_pos); /* seek back to event's start */
if (!(ev= Log_event::read_log_event(file, glob_description_event,
opt_verify_binlog_checksum,
rewrite_db_filter)))
{
/* EOF can't be hit here normally, so it's a real error */
error("Could not read a Rotate_log_event event at offset %llu;"
" this could be a log format error or read error.",
(ulonglong)tmp_pos);
DBUG_RETURN(ERROR_STOP);
}
delete ev;
}
else
break;
}
}
my_b_seek(file, pos);
DBUG_RETURN(OK_CONTINUE);
}
/**
Reads a local binlog and prints the events it sees.
@param[in] logname Name of input binlog.
@param[in,out] print_event_info Parameters and context state
determining how to print.
@retval ERROR_STOP An error occurred - the program should terminate.
@retval OK_CONTINUE No error, the program should continue.
@retval OK_STOP No error, but the end of the specified range of
events to process has been reached and the program should terminate.
*/
static Exit_status dump_local_log_entries(PRINT_EVENT_INFO *print_event_info,
const char* logname)
{
File fd = -1;
IO_CACHE cache,*file= &cache;
uchar tmp_buff[BIN_LOG_HEADER_SIZE];
Exit_status retval= OK_CONTINUE;
if (logname && strcmp(logname, "-") != 0)
{
/* read from normal file */
if ((fd = my_open(logname, O_RDONLY | O_BINARY, MYF(MY_WME))) < 0)
return ERROR_STOP;
if (init_io_cache(file, fd, 0, READ_CACHE, start_position_mot, 0,
MYF(MY_WME | MY_NABP)))
{
my_close(fd, MYF(MY_WME));
return ERROR_STOP;
}
if ((retval= check_header(file, print_event_info, logname)) != OK_CONTINUE)
goto end;
}
else
{
/* read from stdin */
/*
Windows opens stdin in text mode by default. Certain characters
such as CTRL-Z are interpeted as events and the read() method
will stop. CTRL-Z is the EOF marker in Windows. to get past this
you have to open stdin in binary mode. Setmode() is used to set
stdin in binary mode. Errors on setting this mode result in
halting the function and printing an error message to stderr.
*/
#if defined(_WIN32)
if (_setmode(fileno(stdin), O_BINARY) == -1)
{
error("Could not set binary mode on stdin.");
return ERROR_STOP;
}
#endif
if (init_io_cache(file, my_fileno(stdin), 0, READ_CACHE, (my_off_t) 0,
0, MYF(MY_WME | MY_NABP | MY_DONT_CHECK_FILESIZE)))
{
error("Failed to init IO cache.");
return ERROR_STOP;
}
if ((retval= check_header(file, print_event_info, logname)) != OK_CONTINUE)
goto end;
if (start_position)
{
/* skip 'start_position' characters from stdin */
uchar buff[IO_SIZE];
my_off_t length,tmp;
for (length= start_position_mot ; length > 0 ; length-=tmp)
{
tmp= min(static_cast<size_t>(length), sizeof(buff));
if (my_b_read(file, buff, (uint) tmp))
{
error("Failed reading from file.");
goto err;
}
}
}
}
if (!glob_description_event || !glob_description_event->is_valid())
{
error("Invalid Format_description log event; could be out of memory.");
goto err;
}
if (!start_position && my_b_read(file, tmp_buff, BIN_LOG_HEADER_SIZE))
{
error("Failed reading from file.");
goto err;
}
for (;;)
{
char llbuff[21];
my_off_t old_off = my_b_tell(file);
Log_event* ev = Log_event::read_log_event(file, glob_description_event,
opt_verify_binlog_checksum,
rewrite_db_filter);
if (!ev)
{
/*
if binlog wasn't closed properly ("in use" flag is set) don't complain
about a corruption, but treat it as EOF and move to the next binlog.
*/
if (glob_description_event->common_header->flags &
LOG_EVENT_BINLOG_IN_USE_F)
file->error= 0;
else if (file->error)
{
error("Could not read entry at offset %s: "
"Error in log format or read error.",
llstr(old_off,llbuff));
goto err;
}
// file->error == 0 means EOF, that's OK, we break in this case
goto end;
}
if ((retval= process_event(print_event_info, ev, old_off, logname)) !=
OK_CONTINUE)
goto end;
}
/* NOTREACHED */
err:
retval= ERROR_STOP;
end:
if (fd >= 0)
my_close(fd, MYF(MY_WME));
/*
Since the end_io_cache() writes to the
file errors may happen.
*/
if (end_io_cache(file))
retval= ERROR_STOP;
return retval;
}
/* Post processing of arguments to check for conflicts and other setups */
static int args_post_process(void)
{
DBUG_ENTER("args_post_process");
if (opt_remote_alias && opt_remote_proto != BINLOG_DUMP_NON_GTID)
{
error("The option read-from-remote-server cannot be used when "
"read-from-remote-master is defined and is not equal to "
"BINLOG-DUMP-NON-GTIDS");
DBUG_RETURN(ERROR_STOP);
}
if (raw_mode)
{
if (one_blockchain)
warning("The --blockchain option is ignored with --raw mode");
if (opt_remote_proto == BINLOG_LOCAL)
{
error("The --raw flag requires one of --read-from-remote-master or --read-from-remote-server");
DBUG_RETURN(ERROR_STOP);
}
if (opt_include_gtids_str != NULL)
{
error("You cannot use --include-gtids and --raw together.");
DBUG_RETURN(ERROR_STOP);
}
if (opt_remote_proto == BINLOG_DUMP_NON_GTID &&
opt_exclude_gtids_str != NULL)
{
error("You cannot use both of --exclude-gtids and --raw together "
"with one of --read-from-remote-server or "
"--read-from-remote-master=BINLOG-DUMP-NON-GTID.");
DBUG_RETURN(ERROR_STOP);
}
if (stop_position != (ulonglong)(~(my_off_t)0))
warning("The --stop-position option is ignored in raw mode");
if (stop_datetime != MY_TIME_T_MAX)
warning("The --stop-datetime option is ignored in raw mode");
}
else if (output_file)
{
if (!(result_file = my_fopen(output_file, O_WRONLY | O_BINARY, MYF(MY_WME))))
{
error("Could not create log file '%s'", output_file);
DBUG_RETURN(ERROR_STOP);
}
}
global_sid_lock->rdlock();
if (opt_include_gtids_str != NULL)
{
if (gtid_set_included->add_gtid_text(opt_include_gtids_str) !=
RETURN_STATUS_OK)
{
error("Could not configure --include-gtids '%s'", opt_include_gtids_str);
global_sid_lock->unlock();
DBUG_RETURN(ERROR_STOP);
}
}
if (opt_exclude_gtids_str != NULL)
{
if (gtid_set_excluded->add_gtid_text(opt_exclude_gtids_str) !=
RETURN_STATUS_OK)
{
error("Could not configure --exclude-gtids '%s'", opt_exclude_gtids_str);
global_sid_lock->unlock();
DBUG_RETURN(ERROR_STOP);
}
}
global_sid_lock->unlock();
if (connection_server_id == 0 && stop_never)
error("Cannot set --server-id=0 when --stop-never is specified.");
if (connection_server_id != -1 && stop_never_slave_server_id != -1)
error("Cannot set --connection-server-id= %lld and"
"--stop-never-slave-server-id= %lld. ", connection_server_id,
stop_never_slave_server_id);
DBUG_RETURN(OK_CONTINUE);
}
/**
GTID cleanup destroys objects and reset their pointer.
Function is reentrant.
*/
inline void gtid_client_cleanup()
{
delete global_sid_lock;
delete global_sid_map;
delete gtid_set_excluded;
delete gtid_set_included;
global_sid_lock= NULL;
global_sid_map= NULL;
gtid_set_excluded= NULL;
gtid_set_included= NULL;
}
/**
GTID initialization.
@return true if allocation does not succeed
false if OK
*/
inline bool gtid_client_init()
{
bool res=
(!(global_sid_lock= new Checkable_rwlock) ||
!(global_sid_map= new Sid_map(global_sid_lock)) ||
!(gtid_set_excluded= new Gtid_set(global_sid_map)) ||
!(gtid_set_included= new Gtid_set(global_sid_map)));
if (res)
{
gtid_client_cleanup();
}
return res;
}
int main(int argc, char** argv)
{
char **defaults_argv;
Exit_status retval= OK_CONTINUE;
MY_INIT(argv[0]);
DBUG_ENTER("main");
DBUG_PROCESS(argv[0]);
my_init_time(); // for time functions
tzset(); // set tzname
/*
A pointer of type Log_event can point to
INTVAR
USER_VAR
RANDOM
events.
*/
buff_ev= new Buff_ev(PSI_NOT_INSTRUMENTED);
my_getopt_use_args_separator= TRUE;
if (load_defaults("my", load_default_groups, &argc, &argv))
exit(1);
my_getopt_use_args_separator= FALSE;
defaults_argv= argv;
parse_args(&argc, &argv);
if (!argc)
{
usage();
free_defaults(defaults_argv);
my_end(my_end_arg);
exit(1);
}
if (gtid_client_init())
{
error("Could not initialize GTID structuress.");
exit(1);
}
umask(((~my_umask) & 0666));
/* Check for argument conflicts and do any post-processing */
if (args_post_process() == ERROR_STOP)
exit(1);
if (opt_base64_output_mode == BASE64_OUTPUT_UNSPEC)
opt_base64_output_mode= BASE64_OUTPUT_AUTO;
opt_server_id_mask = (opt_server_id_bits == 32)?
~ ulong(0) : (1 << opt_server_id_bits) -1;
my_set_max_open_files(open_files_limit);
MY_TMPDIR tmpdir;
tmpdir.list= 0;
if (!dirname_for_local_load)
{
if (init_tmpdir(&tmpdir, 0))
exit(1);
dirname_for_local_load= my_strdup(PSI_NOT_INSTRUMENTED,
my_tmpdir(&tmpdir), MY_WME);
}
if (dirname_for_local_load)
load_processor.init_by_dir_name(dirname_for_local_load);
else
load_processor.init_by_cur_dir();
if (!raw_mode)
{
fprintf(result_file, "/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=1*/;\n");
if (disable_log_bin)
fprintf(result_file,
"/*!32316 SET @OLD_SQL_LOG_BIN=@@SQL_LOG_BIN, SQL_LOG_BIN=0*/;\n");
/*
In myblockchainbinlog|myblockchain, don't want myblockchain to be disconnected after each
transaction (which would be the case with GLOBAL.COMPLETION_TYPE==2).
*/
fprintf(result_file,
"/*!50003 SET @OLD_COMPLETION_TYPE=@@COMPLETION_TYPE,"
"COMPLETION_TYPE=0*/;\n");
if (charset)
fprintf(result_file,
"\n/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;"
"\n/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;"
"\n/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;"
"\n/*!40101 SET NAMES %s */;\n", charset);
}
/*
In case '--idempotent' or '-i' options has been used, we will notify the
server to use idempotent mode for the following events.
*/
if (idempotent_mode)
fprintf(result_file,
"/*!50700 SET @@SESSION.RBR_EXEC_MODE=IDEMPOTENT*/;\n\n");
retval= dump_multiple_logs(argc, argv);
if (!raw_mode)
{
/*
Issue a ROLLBACK in case the last printed binlog was crashed and had half
of transaction.
*/
fprintf(result_file,
"# End of log file\nROLLBACK /* added by myblockchainbinlog */;\n"
"/*!50003 SET COMPLETION_TYPE=@OLD_COMPLETION_TYPE*/;\n");
if (disable_log_bin)
fprintf(result_file, "/*!32316 SET SQL_LOG_BIN=@OLD_SQL_LOG_BIN*/;\n");
if (charset)
fprintf(result_file,
"/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;\n"
"/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;\n"
"/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;\n");
fprintf(result_file, "/*!50530 SET @@SESSION.PSEUDO_SLAVE_MODE=0*/;\n");
}
/*
We should unset the RBR_EXEC_MODE since the user may concatenate output of
multiple runs of myblockchainbinlog, all of which may not run in idempotent mode.
*/
if (idempotent_mode)
fprintf(result_file,
"/*!50700 SET @@SESSION.RBR_EXEC_MODE=STRICT*/;\n");
if (tmpdir.list)
free_tmpdir(&tmpdir);
if (result_file && (result_file != stdout))
my_fclose(result_file, MYF(0));
cleanup();
if (defaults_argv)
free_defaults(defaults_argv);
my_free_open_file_info();
load_processor.destroy();
/* We cannot free DBUG, it is used in global destructors after exit(). */
my_end(my_end_arg | MY_DONT_FREE_DBUG);
gtid_client_cleanup();
exit(retval == ERROR_STOP ? 1 : 0);
/* Keep compilers happy. */
DBUG_RETURN(retval == ERROR_STOP ? 1 : 0);
}
/*
We must include this here as it's compiled with different options for
the server
*/
#include "decimal.c"
#include "my_decimal.cc"
#include "log_event.cc"
#include "log_event_old.cc"
#include "rpl_utility.cc"
#include "rpl_gtid_sid_map.cc"
#include "rpl_gtid_misc.cc"
#include "rpl_gtid_set.cc"
#include "rpl_gtid_specification.cc"
#include "rpl_tblmap.cc"
|
myblockchain/myblockchain
|
client/mysqlbinlog.cc
|
C++
|
gpl-2.0
| 115,233
|
/*
* (C) Copyright 2000
* Sangmoon Kim, Etin Systems. dogoil@etinsys.com.
*
* See file CREDITS for list of people who contributed to this
* project.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of
* the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston,
* MA 02111-1307 USA
*/
#include <common.h>
#include <mpc824x.h>
#include <pci.h>
#include <i2c.h>
#include <netdev.h>
DECLARE_GLOBAL_DATA_PTR;
int checkboard (void)
{
/*TODO: Check processor type */
puts ( "Board: Debris "
#ifdef CONFIG_MPC8240
"8240"
#endif
#ifdef CONFIG_MPC8245
"8245"
#endif
" ##Test not implemented yet##\n");
return 0;
}
#if 0 /* NOT USED */
int checkflash (void)
{
/* TODO: XXX XXX XXX */
printf ("## Test not implemented yet ##\n");
return (0);
}
#endif
phys_size_t initdram (int board_type)
{
int m, row, col, bank, i;
unsigned long start, end;
uint32_t mccr1;
uint32_t mear1 = 0, emear1 = 0, msar1 = 0, emsar1 = 0;
uint32_t mear2 = 0, emear2 = 0, msar2 = 0, emsar2 = 0;
uint8_t mber = 0;
i2c_init(CONFIG_SYS_I2C_SPEED, CONFIG_SYS_I2C_SLAVE);
if (i2c_reg_read (0x50, 2) != 0x04) return 0; /* Memory type */
m = i2c_reg_read (0x50, 5); /* # of physical banks */
row = i2c_reg_read (0x50, 3); /* # of rows */
col = i2c_reg_read (0x50, 4); /* # of columns */
bank = i2c_reg_read (0x50, 17); /* # of logical banks */
CONFIG_READ_WORD(MCCR1, mccr1);
mccr1 &= 0xffff0000;
start = CONFIG_SYS_SDRAM_BASE;
end = start + (1 << (col + row + 3) ) * bank - 1;
for (i = 0; i < m; i++) {
mccr1 |= ((row == 13)? 2 : (bank == 4)? 0 : 3) << i * 2;
if (i < 4) {
msar1 |= ((start >> 20) & 0xff) << i * 8;
emsar1 |= ((start >> 28) & 0xff) << i * 8;
mear1 |= ((end >> 20) & 0xff) << i * 8;
emear1 |= ((end >> 28) & 0xff) << i * 8;
} else {
msar2 |= ((start >> 20) & 0xff) << (i-4) * 8;
emsar2 |= ((start >> 28) & 0xff) << (i-4) * 8;
mear2 |= ((end >> 20) & 0xff) << (i-4) * 8;
emear2 |= ((end >> 28) & 0xff) << (i-4) * 8;
}
mber |= 1 << i;
start += (1 << (col + row + 3) ) * bank;
end += (1 << (col + row + 3) ) * bank;
}
for (; i < 8; i++) {
if (i < 4) {
msar1 |= 0xff << i * 8;
emsar1 |= 0x30 << i * 8;
mear1 |= 0xff << i * 8;
emear1 |= 0x30 << i * 8;
} else {
msar2 |= 0xff << (i-4) * 8;
emsar2 |= 0x30 << (i-4) * 8;
mear2 |= 0xff << (i-4) * 8;
emear2 |= 0x30 << (i-4) * 8;
}
}
CONFIG_WRITE_WORD(MCCR1, mccr1);
CONFIG_WRITE_WORD(MSAR1, msar1);
CONFIG_WRITE_WORD(EMSAR1, emsar1);
CONFIG_WRITE_WORD(MEAR1, mear1);
CONFIG_WRITE_WORD(EMEAR1, emear1);
CONFIG_WRITE_WORD(MSAR2, msar2);
CONFIG_WRITE_WORD(EMSAR2, emsar2);
CONFIG_WRITE_WORD(MEAR2, mear2);
CONFIG_WRITE_WORD(EMEAR2, emear2);
CONFIG_WRITE_BYTE(MBER, mber);
return (1 << (col + row + 3) ) * bank * m;
}
/*
* Initialize PCI Devices, report devices found.
*/
#ifndef CONFIG_PCI_PNP
static struct pci_config_table pci_debris_config_table[] = {
{ PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, 0x0f, PCI_ANY_ID,
pci_cfgfunc_config_device, { PCI_ENET0_IOADDR,
PCI_ENET0_MEMADDR,
PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER }},
{ PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, PCI_ANY_ID, 0x10, PCI_ANY_ID,
pci_cfgfunc_config_device, { PCI_ENET1_IOADDR,
PCI_ENET1_MEMADDR,
PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER }},
{ }
};
#endif
struct pci_controller hose = {
#ifndef CONFIG_PCI_PNP
config_table: pci_debris_config_table,
#endif
};
void pci_init_board(void)
{
pci_mpc824x_init(&hose);
}
void *nvram_read(void *dest, const long src, size_t count)
{
volatile uchar *d = (volatile uchar*) dest;
volatile uchar *s = (volatile uchar*) src;
while(count--) {
*d++ = *s++;
asm volatile("sync");
}
return dest;
}
void nvram_write(long dest, const void *src, size_t count)
{
volatile uchar *d = (volatile uchar*)dest;
volatile uchar *s = (volatile uchar*)src;
while(count--) {
*d++ = *s++;
asm volatile("sync");
}
}
int misc_init_r(void)
{
/* Write ethernet addr in NVRAM for VxWorks */
nvram_write(CONFIG_ENV_ADDR + CONFIG_SYS_NVRAM_VXWORKS_OFFS,
(char*)&gd->bd->bi_enetaddr[0], 6);
return 0;
}
int board_eth_init(bd_t *bis)
{
return pci_eth_init(bis);
}
|
diverger/uboot-lpc32xx
|
board/etin/debris/debris.c
|
C
|
gpl-2.0
| 4,763
|
/*
w83627hf.c - Part of lm_sensors, Linux kernel modules for hardware
monitoring
Copyright (c) 1998 - 2003 Frodo Looijaard <frodol@dds.nl>,
Philip Edelbrock <phil@netroedge.com>,
and Mark Studebaker <mdsxyz123@yahoo.com>
Ported to 2.6 by Bernhard C. Schrenk <clemy@clemy.org>
Copyright (c) 2007 Jean Delvare <khali@linux-fr.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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
Supports following chips:
Chip #vin #fanin #pwm #temp wchipid vendid i2c ISA
w83627hf 9 3 2 3 0x20 0x5ca3 no yes(LPC)
w83627thf 7 3 3 3 0x90 0x5ca3 no yes(LPC)
w83637hf 7 3 3 3 0x80 0x5ca3 no yes(LPC)
w83687thf 7 3 3 3 0x90 0x5ca3 no yes(LPC)
w83697hf 8 2 2 2 0x60 0x5ca3 no yes(LPC)
For other winbond chips, and for i2c support in the above chips,
use w83781d.c.
Note: automatic ("cruise") fan control for 697, 637 & 627thf not
supported yet.
*/
#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/hwmon.h>
#include <linux/hwmon-sysfs.h>
#include <linux/hwmon-vid.h>
#include <linux/err.h>
#include <linux/mutex.h>
#include <linux/ioport.h>
#include <asm/io.h>
#include "lm75.h"
static struct platform_device *pdev;
#define DRVNAME "w83627hf"
enum chips { w83627hf, w83627thf, w83697hf, w83637hf, w83687thf };
static u16 force_addr;
module_param(force_addr, ushort, 0);
MODULE_PARM_DESC(force_addr,
"Initialize the base address of the sensors");
static u8 force_i2c = 0x1f;
module_param(force_i2c, byte, 0);
MODULE_PARM_DESC(force_i2c,
"Initialize the i2c address of the sensors");
static int reset;
module_param(reset, bool, 0);
MODULE_PARM_DESC(reset, "Set to one to reset chip on load");
static int init = 1;
module_param(init, bool, 0);
MODULE_PARM_DESC(init, "Set to zero to bypass chip initialization");
static unsigned short force_id;
module_param(force_id, ushort, 0);
MODULE_PARM_DESC(force_id, "Override the detected device ID");
/* modified from kernel/include/traps.c */
static int REG; /* The register to read/write */
#define DEV 0x07 /* Register: Logical device select */
static int VAL; /* The value to read/write */
/* logical device numbers for superio_select (below) */
#define W83627HF_LD_FDC 0x00
#define W83627HF_LD_PRT 0x01
#define W83627HF_LD_UART1 0x02
#define W83627HF_LD_UART2 0x03
#define W83627HF_LD_KBC 0x05
#define W83627HF_LD_CIR 0x06 /* w83627hf only */
#define W83627HF_LD_GAME 0x07
#define W83627HF_LD_MIDI 0x07
#define W83627HF_LD_GPIO1 0x07
#define W83627HF_LD_GPIO5 0x07 /* w83627thf only */
#define W83627HF_LD_GPIO2 0x08
#define W83627HF_LD_GPIO3 0x09
#define W83627HF_LD_GPIO4 0x09 /* w83627thf only */
#define W83627HF_LD_ACPI 0x0a
#define W83627HF_LD_HWM 0x0b
#define DEVID 0x20 /* Register: Device ID */
#define W83627THF_GPIO5_EN 0x30 /* w83627thf only */
#define W83627THF_GPIO5_IOSR 0xf3 /* w83627thf only */
#define W83627THF_GPIO5_DR 0xf4 /* w83627thf only */
#define W83687THF_VID_EN 0x29 /* w83687thf only */
#define W83687THF_VID_CFG 0xF0 /* w83687thf only */
#define W83687THF_VID_DATA 0xF1 /* w83687thf only */
static inline void
superio_outb(int reg, int val)
{
outb(reg, REG);
outb(val, VAL);
}
static inline int
superio_inb(int reg)
{
outb(reg, REG);
return inb(VAL);
}
static inline void
superio_select(int ld)
{
outb(DEV, REG);
outb(ld, VAL);
}
static inline void
superio_enter(void)
{
outb(0x87, REG);
outb(0x87, REG);
}
static inline void
superio_exit(void)
{
outb(0xAA, REG);
}
#define W627_DEVID 0x52
#define W627THF_DEVID 0x82
#define W697_DEVID 0x60
#define W637_DEVID 0x70
#define W687THF_DEVID 0x85
#define WINB_ACT_REG 0x30
#define WINB_BASE_REG 0x60
/* Constants specified below */
/* Alignment of the base address */
#define WINB_ALIGNMENT ~7
/* Offset & size of I/O region we are interested in */
#define WINB_REGION_OFFSET 5
#define WINB_REGION_SIZE 2
/* Where are the sensors address/data registers relative to the region offset */
#define W83781D_ADDR_REG_OFFSET 0
#define W83781D_DATA_REG_OFFSET 1
/* The W83781D registers */
/* The W83782D registers for nr=7,8 are in bank 5 */
#define W83781D_REG_IN_MAX(nr) ((nr < 7) ? (0x2b + (nr) * 2) : \
(0x554 + (((nr) - 7) * 2)))
#define W83781D_REG_IN_MIN(nr) ((nr < 7) ? (0x2c + (nr) * 2) : \
(0x555 + (((nr) - 7) * 2)))
#define W83781D_REG_IN(nr) ((nr < 7) ? (0x20 + (nr)) : \
(0x550 + (nr) - 7))
/* nr:0-2 for fans:1-3 */
#define W83627HF_REG_FAN_MIN(nr) (0x3b + (nr))
#define W83627HF_REG_FAN(nr) (0x28 + (nr))
#define W83627HF_REG_TEMP2_CONFIG 0x152
#define W83627HF_REG_TEMP3_CONFIG 0x252
/* these are zero-based, unlike config constants above */
static const u16 w83627hf_reg_temp[] = { 0x27, 0x150, 0x250 };
static const u16 w83627hf_reg_temp_hyst[] = { 0x3A, 0x153, 0x253 };
static const u16 w83627hf_reg_temp_over[] = { 0x39, 0x155, 0x255 };
#define W83781D_REG_BANK 0x4E
#define W83781D_REG_CONFIG 0x40
#define W83781D_REG_ALARM1 0x459
#define W83781D_REG_ALARM2 0x45A
#define W83781D_REG_ALARM3 0x45B
#define W83781D_REG_BEEP_CONFIG 0x4D
#define W83781D_REG_BEEP_INTS1 0x56
#define W83781D_REG_BEEP_INTS2 0x57
#define W83781D_REG_BEEP_INTS3 0x453
#define W83781D_REG_VID_FANDIV 0x47
#define W83781D_REG_CHIPID 0x49
#define W83781D_REG_WCHIPID 0x58
#define W83781D_REG_CHIPMAN 0x4F
#define W83781D_REG_PIN 0x4B
#define W83781D_REG_VBAT 0x5D
#define W83627HF_REG_PWM1 0x5A
#define W83627HF_REG_PWM2 0x5B
#define W83627THF_REG_PWM1 0x01 /* 697HF/637HF/687THF too */
#define W83627THF_REG_PWM2 0x03 /* 697HF/637HF/687THF too */
#define W83627THF_REG_PWM3 0x11 /* 637HF/687THF too */
#define W83627THF_REG_VRM_OVT_CFG 0x18 /* 637HF/687THF too */
static const u8 regpwm_627hf[] = { W83627HF_REG_PWM1, W83627HF_REG_PWM2 };
static const u8 regpwm[] = { W83627THF_REG_PWM1, W83627THF_REG_PWM2,
W83627THF_REG_PWM3 };
#define W836X7HF_REG_PWM(type, nr) (((type) == w83627hf) ? \
regpwm_627hf[nr] : regpwm[nr])
#define W83627HF_REG_PWM_FREQ 0x5C /* Only for the 627HF */
#define W83637HF_REG_PWM_FREQ1 0x00 /* 697HF/687THF too */
#define W83637HF_REG_PWM_FREQ2 0x02 /* 697HF/687THF too */
#define W83637HF_REG_PWM_FREQ3 0x10 /* 687THF too */
static const u8 W83637HF_REG_PWM_FREQ[] = { W83637HF_REG_PWM_FREQ1,
W83637HF_REG_PWM_FREQ2,
W83637HF_REG_PWM_FREQ3 };
#define W83627HF_BASE_PWM_FREQ 46870
#define W83781D_REG_I2C_ADDR 0x48
#define W83781D_REG_I2C_SUBADDR 0x4A
/* Sensor selection */
#define W83781D_REG_SCFG1 0x5D
static const u8 BIT_SCFG1[] = { 0x02, 0x04, 0x08 };
#define W83781D_REG_SCFG2 0x59
static const u8 BIT_SCFG2[] = { 0x10, 0x20, 0x40 };
#define W83781D_DEFAULT_BETA 3435
/* Conversions. Limit checking is only done on the TO_REG
variants. Note that you should be a bit careful with which arguments
these macros are called: arguments may be evaluated more than once.
Fixing this is just not worth it. */
#define IN_TO_REG(val) (SENSORS_LIMIT((((val) + 8)/16),0,255))
#define IN_FROM_REG(val) ((val) * 16)
static inline u8 FAN_TO_REG(long rpm, int div)
{
if (rpm == 0)
return 255;
rpm = SENSORS_LIMIT(rpm, 1, 1000000);
return SENSORS_LIMIT((1350000 + rpm * div / 2) / (rpm * div), 1,
254);
}
#define TEMP_MIN (-128000)
#define TEMP_MAX ( 127000)
/* TEMP: 0.001C/bit (-128C to +127C)
REG: 1C/bit, two's complement */
static u8 TEMP_TO_REG(long temp)
{
int ntemp = SENSORS_LIMIT(temp, TEMP_MIN, TEMP_MAX);
ntemp += (ntemp<0 ? -500 : 500);
return (u8)(ntemp / 1000);
}
static int TEMP_FROM_REG(u8 reg)
{
return (s8)reg * 1000;
}
#define FAN_FROM_REG(val,div) ((val)==0?-1:(val)==255?0:1350000/((val)*(div)))
#define PWM_TO_REG(val) (SENSORS_LIMIT((val),0,255))
static inline unsigned long pwm_freq_from_reg_627hf(u8 reg)
{
unsigned long freq;
freq = W83627HF_BASE_PWM_FREQ >> reg;
return freq;
}
static inline u8 pwm_freq_to_reg_627hf(unsigned long val)
{
u8 i;
/* Only 5 dividers (1 2 4 8 16)
Search for the nearest available frequency */
for (i = 0; i < 4; i++) {
if (val > (((W83627HF_BASE_PWM_FREQ >> i) +
(W83627HF_BASE_PWM_FREQ >> (i+1))) / 2))
break;
}
return i;
}
static inline unsigned long pwm_freq_from_reg(u8 reg)
{
/* Clock bit 8 -> 180 kHz or 24 MHz */
unsigned long clock = (reg & 0x80) ? 180000UL : 24000000UL;
reg &= 0x7f;
/* This should not happen but anyway... */
if (reg == 0)
reg++;
return (clock / (reg << 8));
}
static inline u8 pwm_freq_to_reg(unsigned long val)
{
/* Minimum divider value is 0x01 and maximum is 0x7F */
if (val >= 93750) /* The highest we can do */
return 0x01;
if (val >= 720) /* Use 24 MHz clock */
return (24000000UL / (val << 8));
if (val < 6) /* The lowest we can do */
return 0xFF;
else /* Use 180 kHz clock */
return (0x80 | (180000UL / (val << 8)));
}
#define BEEP_MASK_FROM_REG(val) ((val) & 0xff7fff)
#define BEEP_MASK_TO_REG(val) ((val) & 0xff7fff)
#define DIV_FROM_REG(val) (1 << (val))
static inline u8 DIV_TO_REG(long val)
{
int i;
val = SENSORS_LIMIT(val, 1, 128) >> 1;
for (i = 0; i < 7; i++) {
if (val == 0)
break;
val >>= 1;
}
return ((u8) i);
}
/* For each registered chip, we need to keep some data in memory.
The structure is dynamically allocated. */
struct w83627hf_data {
unsigned short addr;
const char *name;
struct class_device *class_dev;
struct mutex lock;
enum chips type;
struct mutex update_lock;
char valid; /* !=0 if following fields are valid */
unsigned long last_updated; /* In jiffies */
u8 in[9]; /* Register value */
u8 in_max[9]; /* Register value */
u8 in_min[9]; /* Register value */
u8 fan[3]; /* Register value */
u8 fan_min[3]; /* Register value */
u16 temp[3]; /* Register value */
u16 temp_max[3]; /* Register value */
u16 temp_max_hyst[3]; /* Register value */
u8 fan_div[3]; /* Register encoding, shifted right */
u8 vid; /* Register encoding, combined */
u32 alarms; /* Register encoding, combined */
u32 beep_mask; /* Register encoding, combined */
u8 pwm[3]; /* Register value */
u8 pwm_freq[3]; /* Register value */
u16 sens[3]; /* 1 = pentium diode; 2 = 3904 diode;
4 = thermistor */
u8 vrm;
u8 vrm_ovt; /* Register value, 627THF/637HF/687THF only */
};
struct w83627hf_sio_data {
enum chips type;
};
static int w83627hf_probe(struct platform_device *pdev);
static int __devexit w83627hf_remove(struct platform_device *pdev);
static int w83627hf_read_value(struct w83627hf_data *data, u16 reg);
static int w83627hf_write_value(struct w83627hf_data *data, u16 reg, u16 value);
static void w83627hf_update_fan_div(struct w83627hf_data *data);
static struct w83627hf_data *w83627hf_update_device(struct device *dev);
static void w83627hf_init_device(struct platform_device *pdev);
static struct platform_driver w83627hf_driver = {
.driver = {
.owner = THIS_MODULE,
.name = DRVNAME,
},
.probe = w83627hf_probe,
.remove = __devexit_p(w83627hf_remove),
};
static ssize_t
show_in_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long)IN_FROM_REG(data->in[nr]));
}
static ssize_t
show_in_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long)IN_FROM_REG(data->in_min[nr]));
}
static ssize_t
show_in_max(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long)IN_FROM_REG(data->in_max[nr]));
}
static ssize_t
store_in_min(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->in_min[nr] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MIN(nr), data->in_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
store_in_max(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
long val = simple_strtol(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->in_max[nr] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MAX(nr), data->in_max[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_vin_decl(offset) \
static SENSOR_DEVICE_ATTR(in##offset##_input, S_IRUGO, \
show_in_input, NULL, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_min, S_IRUGO|S_IWUSR, \
show_in_min, store_in_min, offset); \
static SENSOR_DEVICE_ATTR(in##offset##_max, S_IRUGO|S_IWUSR, \
show_in_max, store_in_max, offset);
sysfs_vin_decl(1);
sysfs_vin_decl(2);
sysfs_vin_decl(3);
sysfs_vin_decl(4);
sysfs_vin_decl(5);
sysfs_vin_decl(6);
sysfs_vin_decl(7);
sysfs_vin_decl(8);
/* use a different set of functions for in0 */
static ssize_t show_in_0(struct w83627hf_data *data, char *buf, u8 reg)
{
long in0;
if ((data->vrm_ovt & 0x01) &&
(w83627thf == data->type || w83637hf == data->type
|| w83687thf == data->type))
/* use VRM9 calculation */
in0 = (long)((reg * 488 + 70000 + 50) / 100);
else
/* use VRM8 (standard) calculation */
in0 = (long)IN_FROM_REG(reg);
return sprintf(buf,"%ld\n", in0);
}
static ssize_t show_regs_in_0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return show_in_0(data, buf, data->in[0]);
}
static ssize_t show_regs_in_min0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return show_in_0(data, buf, data->in_min[0]);
}
static ssize_t show_regs_in_max0(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return show_in_0(data, buf, data->in_max[0]);
}
static ssize_t store_regs_in_min0(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
u32 val;
val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
if ((data->vrm_ovt & 0x01) &&
(w83627thf == data->type || w83637hf == data->type
|| w83687thf == data->type))
/* use VRM9 calculation */
data->in_min[0] =
SENSORS_LIMIT(((val * 100) - 70000 + 244) / 488, 0,
255);
else
/* use VRM8 (standard) calculation */
data->in_min[0] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MIN(0), data->in_min[0]);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t store_regs_in_max0(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
u32 val;
val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
if ((data->vrm_ovt & 0x01) &&
(w83627thf == data->type || w83637hf == data->type
|| w83687thf == data->type))
/* use VRM9 calculation */
data->in_max[0] =
SENSORS_LIMIT(((val * 100) - 70000 + 244) / 488, 0,
255);
else
/* use VRM8 (standard) calculation */
data->in_max[0] = IN_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_IN_MAX(0), data->in_max[0]);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(in0_input, S_IRUGO, show_regs_in_0, NULL);
static DEVICE_ATTR(in0_min, S_IRUGO | S_IWUSR,
show_regs_in_min0, store_regs_in_min0);
static DEVICE_ATTR(in0_max, S_IRUGO | S_IWUSR,
show_regs_in_max0, store_regs_in_max0);
static ssize_t
show_fan_input(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", FAN_FROM_REG(data->fan[nr],
(long)DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t
show_fan_min(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", FAN_FROM_REG(data->fan_min[nr],
(long)DIV_FROM_REG(data->fan_div[nr])));
}
static ssize_t
store_fan_min(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
u32 val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
data->fan_min[nr] = FAN_TO_REG(val, DIV_FROM_REG(data->fan_div[nr]));
w83627hf_write_value(data, W83627HF_REG_FAN_MIN(nr),
data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_fan_decl(offset) \
static SENSOR_DEVICE_ATTR(fan##offset##_input, S_IRUGO, \
show_fan_input, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(fan##offset##_min, S_IRUGO | S_IWUSR, \
show_fan_min, store_fan_min, offset - 1);
sysfs_fan_decl(1);
sysfs_fan_decl(2);
sysfs_fan_decl(3);
static ssize_t
show_temp(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
u16 tmp = data->temp[nr];
return sprintf(buf, "%ld\n", (nr) ? (long) LM75_TEMP_FROM_REG(tmp)
: (long) TEMP_FROM_REG(tmp));
}
static ssize_t
show_temp_max(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
u16 tmp = data->temp_max[nr];
return sprintf(buf, "%ld\n", (nr) ? (long) LM75_TEMP_FROM_REG(tmp)
: (long) TEMP_FROM_REG(tmp));
}
static ssize_t
show_temp_max_hyst(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
u16 tmp = data->temp_max_hyst[nr];
return sprintf(buf, "%ld\n", (nr) ? (long) LM75_TEMP_FROM_REG(tmp)
: (long) TEMP_FROM_REG(tmp));
}
static ssize_t
store_temp_max(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
long val = simple_strtol(buf, NULL, 10);
u16 tmp = (nr) ? LM75_TEMP_TO_REG(val) : TEMP_TO_REG(val);
mutex_lock(&data->update_lock);
data->temp_max[nr] = tmp;
w83627hf_write_value(data, w83627hf_reg_temp_over[nr], tmp);
mutex_unlock(&data->update_lock);
return count;
}
static ssize_t
store_temp_max_hyst(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
long val = simple_strtol(buf, NULL, 10);
u16 tmp = (nr) ? LM75_TEMP_TO_REG(val) : TEMP_TO_REG(val);
mutex_lock(&data->update_lock);
data->temp_max_hyst[nr] = tmp;
w83627hf_write_value(data, w83627hf_reg_temp_hyst[nr], tmp);
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_temp_decl(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_input, S_IRUGO, \
show_temp, NULL, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max, S_IRUGO|S_IWUSR, \
show_temp_max, store_temp_max, offset - 1); \
static SENSOR_DEVICE_ATTR(temp##offset##_max_hyst, S_IRUGO|S_IWUSR, \
show_temp_max_hyst, store_temp_max_hyst, offset - 1);
sysfs_temp_decl(1);
sysfs_temp_decl(2);
sysfs_temp_decl(3);
static ssize_t
show_vid_reg(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) vid_from_reg(data->vid, data->vrm));
}
static DEVICE_ATTR(cpu0_vid, S_IRUGO, show_vid_reg, NULL);
static ssize_t
show_vrm_reg(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%ld\n", (long) data->vrm);
}
static ssize_t
store_vrm_reg(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
u32 val;
val = simple_strtoul(buf, NULL, 10);
data->vrm = val;
return count;
}
static DEVICE_ATTR(vrm, S_IRUGO | S_IWUSR, show_vrm_reg, store_vrm_reg);
static ssize_t
show_alarms_reg(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->alarms);
}
static DEVICE_ATTR(alarms, S_IRUGO, show_alarms_reg, NULL);
static ssize_t
show_alarm(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%u\n", (data->alarms >> bitnr) & 1);
}
static SENSOR_DEVICE_ATTR(in0_alarm, S_IRUGO, show_alarm, NULL, 0);
static SENSOR_DEVICE_ATTR(in1_alarm, S_IRUGO, show_alarm, NULL, 1);
static SENSOR_DEVICE_ATTR(in2_alarm, S_IRUGO, show_alarm, NULL, 2);
static SENSOR_DEVICE_ATTR(in3_alarm, S_IRUGO, show_alarm, NULL, 3);
static SENSOR_DEVICE_ATTR(in4_alarm, S_IRUGO, show_alarm, NULL, 8);
static SENSOR_DEVICE_ATTR(in5_alarm, S_IRUGO, show_alarm, NULL, 9);
static SENSOR_DEVICE_ATTR(in6_alarm, S_IRUGO, show_alarm, NULL, 10);
static SENSOR_DEVICE_ATTR(in7_alarm, S_IRUGO, show_alarm, NULL, 16);
static SENSOR_DEVICE_ATTR(in8_alarm, S_IRUGO, show_alarm, NULL, 17);
static SENSOR_DEVICE_ATTR(fan1_alarm, S_IRUGO, show_alarm, NULL, 6);
static SENSOR_DEVICE_ATTR(fan2_alarm, S_IRUGO, show_alarm, NULL, 7);
static SENSOR_DEVICE_ATTR(fan3_alarm, S_IRUGO, show_alarm, NULL, 11);
static SENSOR_DEVICE_ATTR(temp1_alarm, S_IRUGO, show_alarm, NULL, 4);
static SENSOR_DEVICE_ATTR(temp2_alarm, S_IRUGO, show_alarm, NULL, 5);
static SENSOR_DEVICE_ATTR(temp3_alarm, S_IRUGO, show_alarm, NULL, 13);
static ssize_t
show_beep_mask(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n",
(long)BEEP_MASK_FROM_REG(data->beep_mask));
}
static ssize_t
store_beep_mask(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long val;
val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
/* preserve beep enable */
data->beep_mask = (data->beep_mask & 0x8000)
| BEEP_MASK_TO_REG(val);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS1,
data->beep_mask & 0xff);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS3,
((data->beep_mask) >> 16) & 0xff);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS2,
(data->beep_mask >> 8) & 0xff);
mutex_unlock(&data->update_lock);
return count;
}
static DEVICE_ATTR(beep_mask, S_IRUGO | S_IWUSR,
show_beep_mask, store_beep_mask);
static ssize_t
show_beep(struct device *dev, struct device_attribute *attr, char *buf)
{
struct w83627hf_data *data = w83627hf_update_device(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
return sprintf(buf, "%u\n", (data->beep_mask >> bitnr) & 1);
}
static ssize_t
store_beep(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
int bitnr = to_sensor_dev_attr(attr)->index;
unsigned long bit;
u8 reg;
bit = simple_strtoul(buf, NULL, 10);
if (bit & ~1)
return -EINVAL;
mutex_lock(&data->update_lock);
if (bit)
data->beep_mask |= (1 << bitnr);
else
data->beep_mask &= ~(1 << bitnr);
if (bitnr < 8) {
reg = w83627hf_read_value(data, W83781D_REG_BEEP_INTS1);
if (bit)
reg |= (1 << bitnr);
else
reg &= ~(1 << bitnr);
w83627hf_write_value(data, W83781D_REG_BEEP_INTS1, reg);
} else if (bitnr < 16) {
reg = w83627hf_read_value(data, W83781D_REG_BEEP_INTS2);
if (bit)
reg |= (1 << (bitnr - 8));
else
reg &= ~(1 << (bitnr - 8));
w83627hf_write_value(data, W83781D_REG_BEEP_INTS2, reg);
} else {
reg = w83627hf_read_value(data, W83781D_REG_BEEP_INTS3);
if (bit)
reg |= (1 << (bitnr - 16));
else
reg &= ~(1 << (bitnr - 16));
w83627hf_write_value(data, W83781D_REG_BEEP_INTS3, reg);
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(in0_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 0);
static SENSOR_DEVICE_ATTR(in1_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 1);
static SENSOR_DEVICE_ATTR(in2_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 2);
static SENSOR_DEVICE_ATTR(in3_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 3);
static SENSOR_DEVICE_ATTR(in4_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 8);
static SENSOR_DEVICE_ATTR(in5_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 9);
static SENSOR_DEVICE_ATTR(in6_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 10);
static SENSOR_DEVICE_ATTR(in7_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 16);
static SENSOR_DEVICE_ATTR(in8_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 17);
static SENSOR_DEVICE_ATTR(fan1_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 6);
static SENSOR_DEVICE_ATTR(fan2_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 7);
static SENSOR_DEVICE_ATTR(fan3_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 11);
static SENSOR_DEVICE_ATTR(temp1_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 4);
static SENSOR_DEVICE_ATTR(temp2_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 5);
static SENSOR_DEVICE_ATTR(temp3_beep, S_IRUGO | S_IWUSR,
show_beep, store_beep, 13);
static SENSOR_DEVICE_ATTR(beep_enable, S_IRUGO | S_IWUSR,
show_beep, store_beep, 15);
static ssize_t
show_fan_div(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n",
(long) DIV_FROM_REG(data->fan_div[nr]));
}
/* Note: we save and restore the fan minimum here, because its value is
determined in part by the fan divisor. This follows the principle of
least surprise; the user doesn't expect the fan minimum to change just
because the divisor changed. */
static ssize_t
store_fan_div(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
unsigned long min;
u8 reg;
unsigned long val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
/* Save fan_min */
min = FAN_FROM_REG(data->fan_min[nr],
DIV_FROM_REG(data->fan_div[nr]));
data->fan_div[nr] = DIV_TO_REG(val);
reg = (w83627hf_read_value(data, nr==2 ? W83781D_REG_PIN : W83781D_REG_VID_FANDIV)
& (nr==0 ? 0xcf : 0x3f))
| ((data->fan_div[nr] & 0x03) << (nr==0 ? 4 : 6));
w83627hf_write_value(data, nr==2 ? W83781D_REG_PIN : W83781D_REG_VID_FANDIV, reg);
reg = (w83627hf_read_value(data, W83781D_REG_VBAT)
& ~(1 << (5 + nr)))
| ((data->fan_div[nr] & 0x04) << (3 + nr));
w83627hf_write_value(data, W83781D_REG_VBAT, reg);
/* Restore fan_min */
data->fan_min[nr] = FAN_TO_REG(min, DIV_FROM_REG(data->fan_div[nr]));
w83627hf_write_value(data, W83627HF_REG_FAN_MIN(nr), data->fan_min[nr]);
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(fan1_div, S_IRUGO|S_IWUSR,
show_fan_div, store_fan_div, 0);
static SENSOR_DEVICE_ATTR(fan2_div, S_IRUGO|S_IWUSR,
show_fan_div, store_fan_div, 1);
static SENSOR_DEVICE_ATTR(fan3_div, S_IRUGO|S_IWUSR,
show_fan_div, store_fan_div, 2);
static ssize_t
show_pwm(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->pwm[nr]);
}
static ssize_t
store_pwm(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
u32 val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
if (data->type == w83627thf) {
/* bits 0-3 are reserved in 627THF */
data->pwm[nr] = PWM_TO_REG(val) & 0xf0;
w83627hf_write_value(data,
W836X7HF_REG_PWM(data->type, nr),
data->pwm[nr] |
(w83627hf_read_value(data,
W836X7HF_REG_PWM(data->type, nr)) & 0x0f));
} else {
data->pwm[nr] = PWM_TO_REG(val);
w83627hf_write_value(data,
W836X7HF_REG_PWM(data->type, nr),
data->pwm[nr]);
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 0);
static SENSOR_DEVICE_ATTR(pwm2, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 1);
static SENSOR_DEVICE_ATTR(pwm3, S_IRUGO|S_IWUSR, show_pwm, store_pwm, 2);
static ssize_t
show_pwm_freq(struct device *dev, struct device_attribute *devattr, char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
if (data->type == w83627hf)
return sprintf(buf, "%ld\n",
pwm_freq_from_reg_627hf(data->pwm_freq[nr]));
else
return sprintf(buf, "%ld\n",
pwm_freq_from_reg(data->pwm_freq[nr]));
}
static ssize_t
store_pwm_freq(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
static const u8 mask[]={0xF8, 0x8F};
u32 val;
val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
if (data->type == w83627hf) {
data->pwm_freq[nr] = pwm_freq_to_reg_627hf(val);
w83627hf_write_value(data, W83627HF_REG_PWM_FREQ,
(data->pwm_freq[nr] << (nr*4)) |
(w83627hf_read_value(data,
W83627HF_REG_PWM_FREQ) & mask[nr]));
} else {
data->pwm_freq[nr] = pwm_freq_to_reg(val);
w83627hf_write_value(data, W83637HF_REG_PWM_FREQ[nr],
data->pwm_freq[nr]);
}
mutex_unlock(&data->update_lock);
return count;
}
static SENSOR_DEVICE_ATTR(pwm1_freq, S_IRUGO|S_IWUSR,
show_pwm_freq, store_pwm_freq, 0);
static SENSOR_DEVICE_ATTR(pwm2_freq, S_IRUGO|S_IWUSR,
show_pwm_freq, store_pwm_freq, 1);
static SENSOR_DEVICE_ATTR(pwm3_freq, S_IRUGO|S_IWUSR,
show_pwm_freq, store_pwm_freq, 2);
static ssize_t
show_temp_type(struct device *dev, struct device_attribute *devattr,
char *buf)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = w83627hf_update_device(dev);
return sprintf(buf, "%ld\n", (long) data->sens[nr]);
}
static ssize_t
store_temp_type(struct device *dev, struct device_attribute *devattr,
const char *buf, size_t count)
{
int nr = to_sensor_dev_attr(devattr)->index;
struct w83627hf_data *data = dev_get_drvdata(dev);
u32 val, tmp;
val = simple_strtoul(buf, NULL, 10);
mutex_lock(&data->update_lock);
switch (val) {
case 1: /* PII/Celeron diode */
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
w83627hf_write_value(data, W83781D_REG_SCFG1,
tmp | BIT_SCFG1[nr]);
tmp = w83627hf_read_value(data, W83781D_REG_SCFG2);
w83627hf_write_value(data, W83781D_REG_SCFG2,
tmp | BIT_SCFG2[nr]);
data->sens[nr] = val;
break;
case 2: /* 3904 */
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
w83627hf_write_value(data, W83781D_REG_SCFG1,
tmp | BIT_SCFG1[nr]);
tmp = w83627hf_read_value(data, W83781D_REG_SCFG2);
w83627hf_write_value(data, W83781D_REG_SCFG2,
tmp & ~BIT_SCFG2[nr]);
data->sens[nr] = val;
break;
case W83781D_DEFAULT_BETA:
dev_warn(dev, "Sensor type %d is deprecated, please use 4 "
"instead\n", W83781D_DEFAULT_BETA);
/* fall through */
case 4: /* thermistor */
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
w83627hf_write_value(data, W83781D_REG_SCFG1,
tmp & ~BIT_SCFG1[nr]);
data->sens[nr] = val;
break;
default:
dev_err(dev,
"Invalid sensor type %ld; must be 1, 2, or 4\n",
(long) val);
break;
}
mutex_unlock(&data->update_lock);
return count;
}
#define sysfs_temp_type(offset) \
static SENSOR_DEVICE_ATTR(temp##offset##_type, S_IRUGO | S_IWUSR, \
show_temp_type, store_temp_type, offset - 1);
sysfs_temp_type(1);
sysfs_temp_type(2);
sysfs_temp_type(3);
static ssize_t
show_name(struct device *dev, struct device_attribute *devattr, char *buf)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", data->name);
}
static DEVICE_ATTR(name, S_IRUGO, show_name, NULL);
static int __init w83627hf_find(int sioaddr, unsigned short *addr,
struct w83627hf_sio_data *sio_data)
{
int err = -ENODEV;
u16 val;
static const __initdata char *names[] = {
"W83627HF",
"W83627THF",
"W83697HF",
"W83637HF",
"W83687THF",
};
REG = sioaddr;
VAL = sioaddr + 1;
superio_enter();
val = force_id ? force_id : superio_inb(DEVID);
switch (val) {
case W627_DEVID:
sio_data->type = w83627hf;
break;
case W627THF_DEVID:
sio_data->type = w83627thf;
break;
case W697_DEVID:
sio_data->type = w83697hf;
break;
case W637_DEVID:
sio_data->type = w83637hf;
break;
case W687THF_DEVID:
sio_data->type = w83687thf;
break;
case 0xff: /* No device at all */
goto exit;
default:
pr_debug(DRVNAME ": Unsupported chip (DEVID=0x%02x)\n", val);
goto exit;
}
superio_select(W83627HF_LD_HWM);
force_addr &= WINB_ALIGNMENT;
if (force_addr) {
printk(KERN_WARNING DRVNAME ": Forcing address 0x%x\n",
force_addr);
superio_outb(WINB_BASE_REG, force_addr >> 8);
superio_outb(WINB_BASE_REG + 1, force_addr & 0xff);
}
val = (superio_inb(WINB_BASE_REG) << 8) |
superio_inb(WINB_BASE_REG + 1);
*addr = val & WINB_ALIGNMENT;
if (*addr == 0) {
printk(KERN_WARNING DRVNAME ": Base address not set, "
"skipping\n");
goto exit;
}
val = superio_inb(WINB_ACT_REG);
if (!(val & 0x01)) {
printk(KERN_WARNING DRVNAME ": Enabling HWM logical device\n");
superio_outb(WINB_ACT_REG, val | 0x01);
}
err = 0;
pr_info(DRVNAME ": Found %s chip at %#x\n",
names[sio_data->type], *addr);
exit:
superio_exit();
return err;
}
#define VIN_UNIT_ATTRS(_X_) \
&sensor_dev_attr_in##_X_##_input.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_min.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_max.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_alarm.dev_attr.attr, \
&sensor_dev_attr_in##_X_##_beep.dev_attr.attr
#define FAN_UNIT_ATTRS(_X_) \
&sensor_dev_attr_fan##_X_##_input.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_min.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_div.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_alarm.dev_attr.attr, \
&sensor_dev_attr_fan##_X_##_beep.dev_attr.attr
#define TEMP_UNIT_ATTRS(_X_) \
&sensor_dev_attr_temp##_X_##_input.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_max.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_max_hyst.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_type.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_alarm.dev_attr.attr, \
&sensor_dev_attr_temp##_X_##_beep.dev_attr.attr
static struct attribute *w83627hf_attributes[] = {
&dev_attr_in0_input.attr,
&dev_attr_in0_min.attr,
&dev_attr_in0_max.attr,
&sensor_dev_attr_in0_alarm.dev_attr.attr,
&sensor_dev_attr_in0_beep.dev_attr.attr,
VIN_UNIT_ATTRS(2),
VIN_UNIT_ATTRS(3),
VIN_UNIT_ATTRS(4),
VIN_UNIT_ATTRS(7),
VIN_UNIT_ATTRS(8),
FAN_UNIT_ATTRS(1),
FAN_UNIT_ATTRS(2),
TEMP_UNIT_ATTRS(1),
TEMP_UNIT_ATTRS(2),
&dev_attr_alarms.attr,
&sensor_dev_attr_beep_enable.dev_attr.attr,
&dev_attr_beep_mask.attr,
&sensor_dev_attr_pwm1.dev_attr.attr,
&sensor_dev_attr_pwm2.dev_attr.attr,
&dev_attr_name.attr,
NULL
};
static const struct attribute_group w83627hf_group = {
.attrs = w83627hf_attributes,
};
static struct attribute *w83627hf_attributes_opt[] = {
VIN_UNIT_ATTRS(1),
VIN_UNIT_ATTRS(5),
VIN_UNIT_ATTRS(6),
FAN_UNIT_ATTRS(3),
TEMP_UNIT_ATTRS(3),
&sensor_dev_attr_pwm3.dev_attr.attr,
&sensor_dev_attr_pwm1_freq.dev_attr.attr,
&sensor_dev_attr_pwm2_freq.dev_attr.attr,
&sensor_dev_attr_pwm3_freq.dev_attr.attr,
NULL
};
static const struct attribute_group w83627hf_group_opt = {
.attrs = w83627hf_attributes_opt,
};
static int __devinit w83627hf_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct w83627hf_sio_data *sio_data = dev->platform_data;
struct w83627hf_data *data;
struct resource *res;
int err, i;
static const char *names[] = {
"w83627hf",
"w83627thf",
"w83697hf",
"w83637hf",
"w83687thf",
};
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
if (!request_region(res->start, WINB_REGION_SIZE, DRVNAME)) {
dev_err(dev, "Failed to request region 0x%lx-0x%lx\n",
(unsigned long)res->start,
(unsigned long)(res->start + WINB_REGION_SIZE - 1));
err = -EBUSY;
goto ERROR0;
}
if (!(data = kzalloc(sizeof(struct w83627hf_data), GFP_KERNEL))) {
err = -ENOMEM;
goto ERROR1;
}
data->addr = res->start;
data->type = sio_data->type;
data->name = names[sio_data->type];
mutex_init(&data->lock);
mutex_init(&data->update_lock);
platform_set_drvdata(pdev, data);
/* Initialize the chip */
w83627hf_init_device(pdev);
/* A few vars need to be filled upon startup */
for (i = 0; i <= 2; i++)
data->fan_min[i] = w83627hf_read_value(
data, W83627HF_REG_FAN_MIN(i));
w83627hf_update_fan_div(data);
/* Register common device attributes */
if ((err = sysfs_create_group(&dev->kobj, &w83627hf_group)))
goto ERROR3;
/* Register chip-specific device attributes */
if (data->type == w83627hf || data->type == w83697hf)
if ((err = device_create_file(dev,
&sensor_dev_attr_in5_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in5_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in6_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm1_freq.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm2_freq.dev_attr)))
goto ERROR4;
if (data->type != w83697hf)
if ((err = device_create_file(dev,
&sensor_dev_attr_in1_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_in1_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_min.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_div.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_fan3_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_input.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_max.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_max_hyst.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_alarm.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_beep.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_temp3_type.dev_attr)))
goto ERROR4;
if (data->type != w83697hf && data->vid != 0xff) {
/* Convert VID to voltage based on VRM */
data->vrm = vid_which_vrm();
if ((err = device_create_file(dev, &dev_attr_cpu0_vid))
|| (err = device_create_file(dev, &dev_attr_vrm)))
goto ERROR4;
}
if (data->type == w83627thf || data->type == w83637hf
|| data->type == w83687thf)
if ((err = device_create_file(dev,
&sensor_dev_attr_pwm3.dev_attr)))
goto ERROR4;
if (data->type == w83637hf || data->type == w83687thf)
if ((err = device_create_file(dev,
&sensor_dev_attr_pwm1_freq.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm2_freq.dev_attr))
|| (err = device_create_file(dev,
&sensor_dev_attr_pwm3_freq.dev_attr)))
goto ERROR4;
data->class_dev = hwmon_device_register(dev);
if (IS_ERR(data->class_dev)) {
err = PTR_ERR(data->class_dev);
goto ERROR4;
}
return 0;
ERROR4:
sysfs_remove_group(&dev->kobj, &w83627hf_group);
sysfs_remove_group(&dev->kobj, &w83627hf_group_opt);
ERROR3:
platform_set_drvdata(pdev, NULL);
kfree(data);
ERROR1:
release_region(res->start, WINB_REGION_SIZE);
ERROR0:
return err;
}
static int __devexit w83627hf_remove(struct platform_device *pdev)
{
struct w83627hf_data *data = platform_get_drvdata(pdev);
struct resource *res;
hwmon_device_unregister(data->class_dev);
sysfs_remove_group(&pdev->dev.kobj, &w83627hf_group);
sysfs_remove_group(&pdev->dev.kobj, &w83627hf_group_opt);
platform_set_drvdata(pdev, NULL);
kfree(data);
res = platform_get_resource(pdev, IORESOURCE_IO, 0);
release_region(res->start, WINB_REGION_SIZE);
return 0;
}
/* Registers 0x50-0x5f are banked */
static inline void w83627hf_set_bank(struct w83627hf_data *data, u16 reg)
{
if ((reg & 0x00f0) == 0x50) {
outb_p(W83781D_REG_BANK, data->addr + W83781D_ADDR_REG_OFFSET);
outb_p(reg >> 8, data->addr + W83781D_DATA_REG_OFFSET);
}
}
/* Not strictly necessary, but play it safe for now */
static inline void w83627hf_reset_bank(struct w83627hf_data *data, u16 reg)
{
if (reg & 0xff00) {
outb_p(W83781D_REG_BANK, data->addr + W83781D_ADDR_REG_OFFSET);
outb_p(0, data->addr + W83781D_DATA_REG_OFFSET);
}
}
static int w83627hf_read_value(struct w83627hf_data *data, u16 reg)
{
int res, word_sized;
mutex_lock(&data->lock);
word_sized = (((reg & 0xff00) == 0x100)
|| ((reg & 0xff00) == 0x200))
&& (((reg & 0x00ff) == 0x50)
|| ((reg & 0x00ff) == 0x53)
|| ((reg & 0x00ff) == 0x55));
w83627hf_set_bank(data, reg);
outb_p(reg & 0xff, data->addr + W83781D_ADDR_REG_OFFSET);
res = inb_p(data->addr + W83781D_DATA_REG_OFFSET);
if (word_sized) {
outb_p((reg & 0xff) + 1,
data->addr + W83781D_ADDR_REG_OFFSET);
res =
(res << 8) + inb_p(data->addr +
W83781D_DATA_REG_OFFSET);
}
w83627hf_reset_bank(data, reg);
mutex_unlock(&data->lock);
return res;
}
static int __devinit w83627thf_read_gpio5(struct platform_device *pdev)
{
int res = 0xff, sel;
superio_enter();
superio_select(W83627HF_LD_GPIO5);
/* Make sure these GPIO pins are enabled */
if (!(superio_inb(W83627THF_GPIO5_EN) & (1<<3))) {
dev_dbg(&pdev->dev, "GPIO5 disabled, no VID function\n");
goto exit;
}
/* Make sure the pins are configured for input
There must be at least five (VRM 9), and possibly 6 (VRM 10) */
sel = superio_inb(W83627THF_GPIO5_IOSR) & 0x3f;
if ((sel & 0x1f) != 0x1f) {
dev_dbg(&pdev->dev, "GPIO5 not configured for VID "
"function\n");
goto exit;
}
dev_info(&pdev->dev, "Reading VID from GPIO5\n");
res = superio_inb(W83627THF_GPIO5_DR) & sel;
exit:
superio_exit();
return res;
}
static int __devinit w83687thf_read_vid(struct platform_device *pdev)
{
int res = 0xff;
superio_enter();
superio_select(W83627HF_LD_HWM);
/* Make sure these GPIO pins are enabled */
if (!(superio_inb(W83687THF_VID_EN) & (1 << 2))) {
dev_dbg(&pdev->dev, "VID disabled, no VID function\n");
goto exit;
}
/* Make sure the pins are configured for input */
if (!(superio_inb(W83687THF_VID_CFG) & (1 << 4))) {
dev_dbg(&pdev->dev, "VID configured as output, "
"no VID function\n");
goto exit;
}
res = superio_inb(W83687THF_VID_DATA) & 0x3f;
exit:
superio_exit();
return res;
}
static int w83627hf_write_value(struct w83627hf_data *data, u16 reg, u16 value)
{
int word_sized;
mutex_lock(&data->lock);
word_sized = (((reg & 0xff00) == 0x100)
|| ((reg & 0xff00) == 0x200))
&& (((reg & 0x00ff) == 0x53)
|| ((reg & 0x00ff) == 0x55));
w83627hf_set_bank(data, reg);
outb_p(reg & 0xff, data->addr + W83781D_ADDR_REG_OFFSET);
if (word_sized) {
outb_p(value >> 8,
data->addr + W83781D_DATA_REG_OFFSET);
outb_p((reg & 0xff) + 1,
data->addr + W83781D_ADDR_REG_OFFSET);
}
outb_p(value & 0xff,
data->addr + W83781D_DATA_REG_OFFSET);
w83627hf_reset_bank(data, reg);
mutex_unlock(&data->lock);
return 0;
}
static void __devinit w83627hf_init_device(struct platform_device *pdev)
{
struct w83627hf_data *data = platform_get_drvdata(pdev);
int i;
enum chips type = data->type;
u8 tmp;
if (reset) {
/* Resetting the chip has been the default for a long time,
but repeatedly caused problems (fans going to full
speed...) so it is now optional. It might even go away if
nobody reports it as being useful, as I see very little
reason why this would be needed at all. */
dev_info(&pdev->dev, "If reset=1 solved a problem you were "
"having, please report!\n");
/* save this register */
i = w83627hf_read_value(data, W83781D_REG_BEEP_CONFIG);
/* Reset all except Watchdog values and last conversion values
This sets fan-divs to 2, among others */
w83627hf_write_value(data, W83781D_REG_CONFIG, 0x80);
/* Restore the register and disable power-on abnormal beep.
This saves FAN 1/2/3 input/output values set by BIOS. */
w83627hf_write_value(data, W83781D_REG_BEEP_CONFIG, i | 0x80);
/* Disable master beep-enable (reset turns it on).
Individual beeps should be reset to off but for some reason
disabling this bit helps some people not get beeped */
w83627hf_write_value(data, W83781D_REG_BEEP_INTS2, 0);
}
/* Minimize conflicts with other winbond i2c-only clients... */
/* disable i2c subclients... how to disable main i2c client?? */
/* force i2c address to relatively uncommon address */
w83627hf_write_value(data, W83781D_REG_I2C_SUBADDR, 0x89);
w83627hf_write_value(data, W83781D_REG_I2C_ADDR, force_i2c);
/* Read VID only once */
if (type == w83627hf || type == w83637hf) {
int lo = w83627hf_read_value(data, W83781D_REG_VID_FANDIV);
int hi = w83627hf_read_value(data, W83781D_REG_CHIPID);
data->vid = (lo & 0x0f) | ((hi & 0x01) << 4);
} else if (type == w83627thf) {
data->vid = w83627thf_read_gpio5(pdev);
} else if (type == w83687thf) {
data->vid = w83687thf_read_vid(pdev);
}
/* Read VRM & OVT Config only once */
if (type == w83627thf || type == w83637hf || type == w83687thf) {
data->vrm_ovt =
w83627hf_read_value(data, W83627THF_REG_VRM_OVT_CFG);
}
tmp = w83627hf_read_value(data, W83781D_REG_SCFG1);
for (i = 1; i <= 3; i++) {
if (!(tmp & BIT_SCFG1[i - 1])) {
data->sens[i - 1] = 4;
} else {
if (w83627hf_read_value
(data,
W83781D_REG_SCFG2) & BIT_SCFG2[i - 1])
data->sens[i - 1] = 1;
else
data->sens[i - 1] = 2;
}
if ((type == w83697hf) && (i == 2))
break;
}
if(init) {
/* Enable temp2 */
tmp = w83627hf_read_value(data, W83627HF_REG_TEMP2_CONFIG);
if (tmp & 0x01) {
dev_warn(&pdev->dev, "Enabling temp2, readings "
"might not make sense\n");
w83627hf_write_value(data, W83627HF_REG_TEMP2_CONFIG,
tmp & 0xfe);
}
/* Enable temp3 */
if (type != w83697hf) {
tmp = w83627hf_read_value(data,
W83627HF_REG_TEMP3_CONFIG);
if (tmp & 0x01) {
dev_warn(&pdev->dev, "Enabling temp3, "
"readings might not make sense\n");
w83627hf_write_value(data,
W83627HF_REG_TEMP3_CONFIG, tmp & 0xfe);
}
}
}
/* Start monitoring */
w83627hf_write_value(data, W83781D_REG_CONFIG,
(w83627hf_read_value(data,
W83781D_REG_CONFIG) & 0xf7)
| 0x01);
/* Enable VBAT monitoring if needed */
tmp = w83627hf_read_value(data, W83781D_REG_VBAT);
if (!(tmp & 0x01))
w83627hf_write_value(data, W83781D_REG_VBAT, tmp | 0x01);
}
static void w83627hf_update_fan_div(struct w83627hf_data *data)
{
int reg;
reg = w83627hf_read_value(data, W83781D_REG_VID_FANDIV);
data->fan_div[0] = (reg >> 4) & 0x03;
data->fan_div[1] = (reg >> 6) & 0x03;
if (data->type != w83697hf) {
data->fan_div[2] = (w83627hf_read_value(data,
W83781D_REG_PIN) >> 6) & 0x03;
}
reg = w83627hf_read_value(data, W83781D_REG_VBAT);
data->fan_div[0] |= (reg >> 3) & 0x04;
data->fan_div[1] |= (reg >> 4) & 0x04;
if (data->type != w83697hf)
data->fan_div[2] |= (reg >> 5) & 0x04;
}
static struct w83627hf_data *w83627hf_update_device(struct device *dev)
{
struct w83627hf_data *data = dev_get_drvdata(dev);
int i, num_temps = (data->type == w83697hf) ? 2 : 3;
mutex_lock(&data->update_lock);
if (time_after(jiffies, data->last_updated + HZ + HZ / 2)
|| !data->valid) {
for (i = 0; i <= 8; i++) {
/* skip missing sensors */
if (((data->type == w83697hf) && (i == 1)) ||
((data->type != w83627hf && data->type != w83697hf)
&& (i == 5 || i == 6)))
continue;
data->in[i] =
w83627hf_read_value(data, W83781D_REG_IN(i));
data->in_min[i] =
w83627hf_read_value(data,
W83781D_REG_IN_MIN(i));
data->in_max[i] =
w83627hf_read_value(data,
W83781D_REG_IN_MAX(i));
}
for (i = 0; i <= 2; i++) {
data->fan[i] =
w83627hf_read_value(data, W83627HF_REG_FAN(i));
data->fan_min[i] =
w83627hf_read_value(data,
W83627HF_REG_FAN_MIN(i));
}
for (i = 0; i <= 2; i++) {
u8 tmp = w83627hf_read_value(data,
W836X7HF_REG_PWM(data->type, i));
/* bits 0-3 are reserved in 627THF */
if (data->type == w83627thf)
tmp &= 0xf0;
data->pwm[i] = tmp;
if (i == 1 &&
(data->type == w83627hf || data->type == w83697hf))
break;
}
if (data->type == w83627hf) {
u8 tmp = w83627hf_read_value(data,
W83627HF_REG_PWM_FREQ);
data->pwm_freq[0] = tmp & 0x07;
data->pwm_freq[1] = (tmp >> 4) & 0x07;
} else if (data->type != w83627thf) {
for (i = 1; i <= 3; i++) {
data->pwm_freq[i - 1] =
w83627hf_read_value(data,
W83637HF_REG_PWM_FREQ[i - 1]);
if (i == 2 && (data->type == w83697hf))
break;
}
}
for (i = 0; i < num_temps; i++) {
data->temp[i] = w83627hf_read_value(
data, w83627hf_reg_temp[i]);
data->temp_max[i] = w83627hf_read_value(
data, w83627hf_reg_temp_over[i]);
data->temp_max_hyst[i] = w83627hf_read_value(
data, w83627hf_reg_temp_hyst[i]);
}
w83627hf_update_fan_div(data);
data->alarms =
w83627hf_read_value(data, W83781D_REG_ALARM1) |
(w83627hf_read_value(data, W83781D_REG_ALARM2) << 8) |
(w83627hf_read_value(data, W83781D_REG_ALARM3) << 16);
i = w83627hf_read_value(data, W83781D_REG_BEEP_INTS2);
data->beep_mask = (i << 8) |
w83627hf_read_value(data, W83781D_REG_BEEP_INTS1) |
w83627hf_read_value(data, W83781D_REG_BEEP_INTS3) << 16;
data->last_updated = jiffies;
data->valid = 1;
}
mutex_unlock(&data->update_lock);
return data;
}
static int __init w83627hf_device_add(unsigned short address,
const struct w83627hf_sio_data *sio_data)
{
struct resource res = {
.start = address + WINB_REGION_OFFSET,
.end = address + WINB_REGION_OFFSET + WINB_REGION_SIZE - 1,
.name = DRVNAME,
.flags = IORESOURCE_IO,
};
int err;
pdev = platform_device_alloc(DRVNAME, address);
if (!pdev) {
err = -ENOMEM;
printk(KERN_ERR DRVNAME ": Device allocation failed\n");
goto exit;
}
err = platform_device_add_resources(pdev, &res, 1);
if (err) {
printk(KERN_ERR DRVNAME ": Device resource addition failed "
"(%d)\n", err);
goto exit_device_put;
}
err = platform_device_add_data(pdev, sio_data,
sizeof(struct w83627hf_sio_data));
if (err) {
printk(KERN_ERR DRVNAME ": Platform data allocation failed\n");
goto exit_device_put;
}
err = platform_device_add(pdev);
if (err) {
printk(KERN_ERR DRVNAME ": Device addition failed (%d)\n",
err);
goto exit_device_put;
}
return 0;
exit_device_put:
platform_device_put(pdev);
exit:
return err;
}
static int __init sensors_w83627hf_init(void)
{
int err;
unsigned short address;
struct w83627hf_sio_data sio_data;
if (w83627hf_find(0x2e, &address, &sio_data)
&& w83627hf_find(0x4e, &address, &sio_data))
return -ENODEV;
err = platform_driver_register(&w83627hf_driver);
if (err)
goto exit;
/* Sets global pdev as a side effect */
err = w83627hf_device_add(address, &sio_data);
if (err)
goto exit_driver;
return 0;
exit_driver:
platform_driver_unregister(&w83627hf_driver);
exit:
return err;
}
static void __exit sensors_w83627hf_exit(void)
{
platform_device_unregister(pdev);
platform_driver_unregister(&w83627hf_driver);
}
MODULE_AUTHOR("Frodo Looijaard <frodol@dds.nl>, "
"Philip Edelbrock <phil@netroedge.com>, "
"and Mark Studebaker <mdsxyz123@yahoo.com>");
MODULE_DESCRIPTION("W83627HF driver");
MODULE_LICENSE("GPL");
module_init(sensors_w83627hf_init);
module_exit(sensors_w83627hf_exit);
|
dduval/kernel-rhel5
|
drivers/hwmon/w83627hf.c
|
C
|
gpl-2.0
| 54,201
|
/*
* Copyright (c) 2007 Cyrille Berger <cberger@cberger.net>
*
* This library is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef _KIS_ENTRY_EDITOR_H_
#define _KIS_ENTRY_EDITOR_H_
#include <QObject>
class QString;
namespace KisMetaData
{
class Store;
}
class KisEntryEditor : public QObject
{
Q_OBJECT
struct Private;
public:
KisEntryEditor(QObject* obj, KisMetaData::Store* store, QString key, QString propertyName, QString structField, int arrayIndex);
~KisEntryEditor();
public Q_SLOTS:
void valueEdited();
void valueChanged();
Q_SIGNALS:
void valueHasBeenEdited();
private:
Private* const d;
};
#endif
|
donniexyz/calligra
|
krita/plugins/extensions/metadataeditor/kis_entry_editor.h
|
C
|
gpl-2.0
| 1,344
|
package org.oztrack.controller;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.oztrack.app.OzTrackApplication;
import org.oztrack.app.OzTrackConfiguration;
import org.oztrack.data.access.CountryDao;
import org.oztrack.data.access.InstitutionDao;
import org.oztrack.data.access.OaiPmhRecordDao;
import org.oztrack.data.access.PersonDao;
import org.oztrack.data.access.UserDao;
import org.oztrack.data.model.Country;
import org.oztrack.data.model.Institution;
import org.oztrack.data.model.User;
import org.oztrack.validator.UserFormValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
@Controller
public class UserController {
@Autowired
private OzTrackConfiguration configuration;
@Autowired
private UserDao userDao;
@Autowired
private PersonDao personDao;
@Autowired
private InstitutionDao institutionDao;
@Autowired
private CountryDao countryDao;
@Autowired
private OaiPmhRecordDao oaiPmhRecordDao;
@Autowired
private OzTrackPermissionEvaluator permissionEvaluator;
@InitBinder("user")
public void initUserBinder(WebDataBinder binder) {
binder.setAllowedFields(
"username",
"title",
"firstName",
"lastName",
"description",
"institutions",
"country",
"email"
);
binder.registerCustomEditor(List.class, "institutions", new InstitutionsPropertyEditor(institutionDao));
binder.registerCustomEditor(Country.class, "country", new CountryPropertyEditor(countryDao));
}
@ModelAttribute("user")
public User getUser(@PathVariable(value="id") Long id) throws Exception {
return userDao.getById(id);
}
@RequestMapping(value="/users/{id}/edit", method=RequestMethod.GET)
public String getEditView(
Authentication authentication,
Model model,
@ModelAttribute(value="user") User user,
@RequestHeader(value="eppn", required=false) String aafIdHeader,
@RequestParam(value="aafId", required=false) String aafIdParam
) {
User currentUser = permissionEvaluator.getAuthenticatedUser(authentication);
if (currentUser == null || (!currentUser.equals(user) && (currentUser.getAdmin() != Boolean.TRUE))) {
return "redirect:/login";
}
if (configuration.isAafEnabled()) {
if (StringUtils.isNotBlank(aafIdParam) && StringUtils.equals(aafIdParam, aafIdHeader)) {
user.setAafId(aafIdHeader);
}
}
addFormAttributes(model);
return "user-form";
}
@RequestMapping(value="/users/{id}", method=RequestMethod.PUT)
public String processUpdate(
Authentication authentication,
Model model,
@ModelAttribute(value="user") User user,
@RequestHeader(value="eppn", required=false) String aafIdHeader,
@RequestParam(value="aafId", required=false) String aafIdParam,
@RequestParam(value="password", required=false) String newPassword,
@RequestParam(value="password2", required=false) String newPassword2,
@RequestParam(value="institutions", required=false) List<String> institutionIds,
BindingResult bindingResult
) throws Exception {
User currentUser = permissionEvaluator.getAuthenticatedUser(authentication);
if (currentUser == null || (!currentUser.equals(user) && (currentUser.getAdmin() != Boolean.TRUE))) {
return "redirect:/login";
}
if (OzTrackApplication.getApplicationContext().isAafEnabled()) {
if (StringUtils.isBlank(aafIdParam)) {
user.setAafId(null);
}
else if (!StringUtils.equals(user.getAafId(), aafIdParam)) {
if (StringUtils.equals(aafIdHeader, aafIdParam)) {
user.setAafId(aafIdHeader);
}
else {
throw new RuntimeException("Attempt to set AAF ID without being logged in");
}
}
}
// Catch empty institutions list here: although WebDataBinder will produce new list when
// at least one institution entered, it will not be triggered for an empty list, leaving old value.
if (institutionIds == null) {
user.setInstitutions(Collections.<Institution>emptyList());
}
new UserFormValidator(userDao).validate(user, bindingResult);
if (!StringUtils.equals(newPassword, newPassword2)) {
bindingResult.rejectValue("password", "error.password.mismatch", "Passwords do not match");
}
else if (StringUtils.isBlank(user.getPassword()) && StringUtils.isBlank(user.getAafId())) {
bindingResult.rejectValue("password", "error.empty.field", "Please enter password");
}
if (bindingResult.hasErrors()) {
addFormAttributes(model);
return "user-form";
}
if (StringUtils.isNotBlank(newPassword)) {
user.setPassword(BCrypt.hashpw(newPassword, BCrypt.gensalt()));
}
user.setUpdateDate(new Date());
user.setUpdateUser(currentUser);
userDao.update(user);
personDao.setInstitutionsIncludeInOaiPmh(user.getPerson());
oaiPmhRecordDao.updateOaiPmhSets();
return "redirect:/projects";
}
private void addFormAttributes(Model model) {
model.addAttribute("institutions", institutionDao.getAllOrderedByTitle());
model.addAttribute("countries", countryDao.getAllOrderedByTitle());
}
}
|
uq-eresearch/oztrack
|
src/main/java/org/oztrack/controller/UserController.java
|
Java
|
gpl-2.0
| 6,416
|
use strict; #-*-cperl-*-
use warnings;
use lib qw( ../../../../lib );
=head1 NAME
Algorithm::Evolutionary::Fitness::Base - Base class for fitness functions
=head1 SYNOPSIS
Shouldn't be used directly, it's an abstract class whose siblings are
used to implement fitness functions.
=head1 DESCRIPTION
This module includes functionality that should be common to all fitness. Or at least it
would be nice to have it in common. It counts the number of evaluations and includes a common API for caching evaluations.
=head1 METHODS
=cut
package Algorithm::Evolutionary::Fitness::Base;
use Carp;
our $VERSION = '3.1';
=head2 new()
Initializes common variables, like the number of evaluations. Cache is not initialized.
=cut
sub new {
my $class = shift;
my $self = {};
bless $self, $class;
$self->initialize();
return $self;
}
=head2 initialize()
Called from new, initializes the evaluations counter.
=cut
sub initialize {
my $self = shift;
$self->{'_counter'} = 0;
$self->{'_cache'} = {}; # This is optional; should be used from derived classes
}
=head2 apply( $individual )
Applies the instantiated problem to a chromosome. Actually it is a
wrapper around C<_apply>
=cut
sub apply {
my $self = shift;
my $individual = shift;
$self->{'_counter'}++;
return $self->_apply( $individual );
}
=head2 _apply( $individual )
This is the one that really does the stuff. Should be overloaded by
derived clases
=cut
sub _apply {
croak "You should have overloaded this\n";
}
=head2 evaluations()
Returns the number of evaluations made with this object. Useful for
collecting stats
=cut
sub evaluations {
my $self = shift;
return $self->{'_counter'};
}
=head2 reset_evaluations()
Sets to 0 the number of evaluations; useful for repeated use of the fitness object
=cut
sub reset_evaluations {
my $self = shift;
$self->{'_counter'} = 0;
}
=head2 cache()
Returns a reference to the internal evaluations cache. Not very encapsulated, but...
=cut
sub cache {
my $self = shift;
return $self->{'cache'};
}
=head1 Known subclasses
=over 4
=item *
L<Algorithm::Evolutionary::Fitness::MMDP>
=item *
L<Algorithm::Evolutionary::Fitness::P_Peaks>
=item *
L<Algorithm::Evolutionary::Fitness::wP_Peaks>
=item *
L<Algorithm::Evolutionary::Fitness::Knapsack>
=item *
L<Algorithm::Evolutionary::Fitness::ECC>
=item *
L<Algorithm::Evolutionary::Fitness::Royal_Road>
=item *
L<Algorithm::Evolutionary::Fitness::String>
=item *
L<Algorithm::Evolutionary::Fitness::Trap>
=item *
L<Algorithm::Evolutionary::Fitness::Noisy>
=back
=head1 Copyright
This file is released under the GPL. See the LICENSE file included in this distribution,
or go to http://www.fsf.org/licenses/gpl.txt
=cut
"What???";
|
gitpan/Algorithm-Evolutionary
|
lib/Algorithm/Evolutionary/Fitness/Base.pm
|
Perl
|
gpl-2.0
| 2,791
|
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "config.h"
#include "ThreadableBlobRegistry.h"
#include "BlobData.h"
#include "BlobRegistry.h"
#include "BlobURL.h"
#include "SecurityOrigin.h"
#include <mutex>
#include <wtf/HashMap.h>
#include <wtf/MainThread.h>
#include <wtf/RefPtr.h>
#include <wtf/ThreadSpecific.h>
#include <wtf/text/StringHash.h>
using WTF::ThreadSpecific;
namespace WebCore {
struct BlobRegistryContext {
WTF_MAKE_FAST_ALLOCATED;
public:
BlobRegistryContext(const URL& url, std::unique_ptr<BlobData> blobData)
: url(url.copy())
, blobData(std::move(blobData))
{
this->blobData->detachFromCurrentThread();
}
BlobRegistryContext(const URL& url, const URL& srcURL)
: url(url.copy())
, srcURL(srcURL.copy())
{
}
BlobRegistryContext(const URL& url)
: url(url.copy())
{
}
URL url;
URL srcURL;
std::unique_ptr<BlobData> blobData;
};
#if ENABLE(BLOB)
typedef HashMap<String, RefPtr<SecurityOrigin>> BlobUrlOriginMap;
static ThreadSpecific<BlobUrlOriginMap>& originMap()
{
static std::once_flag onceFlag;
static ThreadSpecific<BlobUrlOriginMap>* map;
std::call_once(onceFlag, []{
map = new ThreadSpecific<BlobUrlOriginMap>;
});
return *map;
}
static void registerBlobURLTask(void* context)
{
std::unique_ptr<BlobRegistryContext> blobRegistryContext(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerBlobURL(blobRegistryContext->url, std::move(blobRegistryContext->blobData));
}
void ThreadableBlobRegistry::registerBlobURL(const URL& url, std::unique_ptr<BlobData> blobData)
{
if (isMainThread())
blobRegistry().registerBlobURL(url, std::move(blobData));
else
callOnMainThread(®isterBlobURLTask, new BlobRegistryContext(url, std::move(blobData)));
}
static void registerBlobURLFromTask(void* context)
{
std::unique_ptr<BlobRegistryContext> blobRegistryContext(static_cast<BlobRegistryContext*>(context));
blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
}
void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin* origin, const URL& url, const URL& srcURL)
{
// If the blob URL contains null origin, as in the context with unique security origin or file URL, save the mapping between url and origin so that the origin can be retrived when doing security origin check.
if (origin && BlobURL::getOrigin(url) == "null")
originMap()->add(url.string(), origin);
if (isMainThread())
blobRegistry().registerBlobURL(url, srcURL);
else
callOnMainThread(®isterBlobURLFromTask, new BlobRegistryContext(url, srcURL));
}
static void unregisterBlobURLTask(void* context)
{
std::unique_ptr<BlobRegistryContext> blobRegistryContext(static_cast<BlobRegistryContext*>(context));
blobRegistry().unregisterBlobURL(blobRegistryContext->url);
}
void ThreadableBlobRegistry::unregisterBlobURL(const URL& url)
{
if (BlobURL::getOrigin(url) == "null")
originMap()->remove(url.string());
if (isMainThread())
blobRegistry().unregisterBlobURL(url);
else
callOnMainThread(&unregisterBlobURLTask, new BlobRegistryContext(url));
}
PassRefPtr<SecurityOrigin> ThreadableBlobRegistry::getCachedOrigin(const URL& url)
{
return originMap()->get(url.string());
}
#else
void ThreadableBlobRegistry::registerBlobURL(const URL&, std::unique_ptr<BlobData>)
{
}
void ThreadableBlobRegistry::registerBlobURL(SecurityOrigin*, const URL&, const URL&)
{
}
void ThreadableBlobRegistry::unregisterBlobURL(const URL&)
{
}
PassRefPtr<SecurityOrigin> ThreadableBlobRegistry::getCachedOrigin(const URL&)
{
return 0;
}
#endif // ENABL(BLOB)
} // namespace WebCore
|
loveyoupeng/rt
|
modules/web/src/main/native/Source/WebCore/fileapi/ThreadableBlobRegistry.cpp
|
C++
|
gpl-2.0
| 5,301
|
/* vi: set sw=4 ts=4: */
/*
* Simple telnet server
* Bjorn Wesen, Axis Communications AB (bjornw@axis.com)
*
* Licensed under GPLv2 or later, see file LICENSE in this source tree.
*
* ---------------------------------------------------------------------------
* (C) Copyright 2000, Axis Communications AB, LUND, SWEDEN
****************************************************************************
*
* The telnetd manpage says it all:
*
* Telnetd operates by allocating a pseudo-terminal device (see pty(4)) for
* a client, then creating a login process which has the slave side of the
* pseudo-terminal as stdin, stdout, and stderr. Telnetd manipulates the
* master side of the pseudo-terminal, implementing the telnet protocol and
* passing characters between the remote client and the login process.
*
* Vladimir Oleynik <dzo@simtreas.ru> 2001
* Set process group corrections, initial busybox port
*/
//usage:#define telnetd_trivial_usage
//usage: "[OPTIONS]"
//usage:#define telnetd_full_usage "\n\n"
//usage: "Handle incoming telnet connections"
//usage: IF_NOT_FEATURE_TELNETD_STANDALONE(" via inetd") "\n"
//usage: "\n -l LOGIN Exec LOGIN on connect"
//usage: "\n -f ISSUE_FILE Display ISSUE_FILE instead of /etc/issue"
//usage: "\n -K Close connection as soon as login exits"
//usage: "\n (normally wait until all programs close slave pty)"
//usage: IF_FEATURE_TELNETD_STANDALONE(
//usage: "\n -p PORT Port to listen on"
//usage: "\n -b ADDR[:PORT] Address to bind to"
//usage: "\n -F Run in foreground"
//usage: "\n -i Inetd mode"
//usage: IF_FEATURE_TELNETD_INETD_WAIT(
//usage: "\n -w SEC Inetd 'wait' mode, linger time SEC"
//usage: "\n -S Log to syslog (implied by -i or without -F and -w)"
//usage: )
//usage: )
#define DEBUG 0
#include "libbb.h"
#include <syslog.h>
#if DEBUG
# define TELCMDS
# define TELOPTS
#endif
#include <arpa/telnet.h>
struct tsession {
struct tsession *next;
pid_t shell_pid;
int sockfd_read;
int sockfd_write;
int ptyfd;
/* two circular buffers */
/*char *buf1, *buf2;*/
/*#define TS_BUF1(ts) ts->buf1*/
/*#define TS_BUF2(ts) TS_BUF2(ts)*/
#define TS_BUF1(ts) ((unsigned char*)(ts + 1))
#define TS_BUF2(ts) (((unsigned char*)(ts + 1)) + BUFSIZE)
int rdidx1, wridx1, size1;
int rdidx2, wridx2, size2;
};
/* Two buffers are directly after tsession in malloced memory.
* Make whole thing fit in 4k */
enum { BUFSIZE = (4 * 1024 - sizeof(struct tsession)) / 2 };
/* Globals */
struct globals {
struct tsession *sessions;
const char *loginpath;
const char *issuefile;
int maxfd;
} FIX_ALIASING;
#define G (*(struct globals*)&bb_common_bufsiz1)
#define INIT_G() do { \
G.loginpath = "/system/xbin/login"; \
G.issuefile = "/etc/issue.net"; \
} while (0)
/*
Remove all IAC's from buf1 (received IACs are ignored and must be removed
so as to not be interpreted by the terminal). Make an uninterrupted
string of characters fit for the terminal. Do this by packing
all characters meant for the terminal sequentially towards the end of buf.
Return a pointer to the beginning of the characters meant for the terminal
and make *num_totty the number of characters that should be sent to
the terminal.
Note - if an IAC (3 byte quantity) starts before (bf + len) but extends
past (bf + len) then that IAC will be left unprocessed and *processed
will be less than len.
CR-LF ->'s CR mapping is also done here, for convenience.
NB: may fail to remove iacs which wrap around buffer!
*/
static unsigned char *
remove_iacs(struct tsession *ts, int *pnum_totty)
{
unsigned char *ptr0 = TS_BUF1(ts) + ts->wridx1;
unsigned char *ptr = ptr0;
unsigned char *totty = ptr;
unsigned char *end = ptr + MIN(BUFSIZE - ts->wridx1, ts->size1);
int num_totty;
while (ptr < end) {
if (*ptr != IAC) {
char c = *ptr;
*totty++ = c;
ptr++;
/* We map \r\n ==> \r for pragmatic reasons.
* Many client implementations send \r\n when
* the user hits the CarriageReturn key.
* See RFC 1123 3.3.1 Telnet End-of-Line Convention.
*/
if (c == '\r' && ptr < end && (*ptr == '\n' || *ptr == '\0'))
ptr++;
continue;
}
if ((ptr+1) >= end)
break;
if (ptr[1] == NOP) { /* Ignore? (putty keepalive, etc.) */
ptr += 2;
continue;
}
if (ptr[1] == IAC) { /* Literal IAC? (emacs M-DEL) */
*totty++ = ptr[1];
ptr += 2;
continue;
}
/*
* TELOPT_NAWS support!
*/
if ((ptr+2) >= end) {
/* Only the beginning of the IAC is in the
buffer we were asked to process, we can't
process this char */
break;
}
/*
* IAC -> SB -> TELOPT_NAWS -> 4-byte -> IAC -> SE
*/
if (ptr[1] == SB && ptr[2] == TELOPT_NAWS) {
struct winsize ws;
if ((ptr+8) >= end)
break; /* incomplete, can't process */
ws.ws_col = (ptr[3] << 8) | ptr[4];
ws.ws_row = (ptr[5] << 8) | ptr[6];
ioctl(ts->ptyfd, TIOCSWINSZ, (char *)&ws);
ptr += 9;
continue;
}
/* skip 3-byte IAC non-SB cmd */
#if DEBUG
fprintf(stderr, "Ignoring IAC %s,%s\n",
TELCMD(ptr[1]), TELOPT(ptr[2]));
#endif
ptr += 3;
}
num_totty = totty - ptr0;
*pnum_totty = num_totty;
/* The difference between ptr and totty is number of iacs
we removed from the stream. Adjust buf1 accordingly */
if ((ptr - totty) == 0) /* 99.999% of cases */
return ptr0;
ts->wridx1 += ptr - totty;
ts->size1 -= ptr - totty;
/* Move chars meant for the terminal towards the end of the buffer */
return memmove(ptr - num_totty, ptr0, num_totty);
}
/*
* Converting single IAC into double on output
*/
static size_t iac_safe_write(int fd, const char *buf, size_t count)
{
const char *IACptr;
size_t wr, rc, total;
total = 0;
while (1) {
if (count == 0)
return total;
if (*buf == (char)IAC) {
static const char IACIAC[] ALIGN1 = { IAC, IAC };
rc = safe_write(fd, IACIAC, 2);
if (rc != 2)
break;
buf++;
total++;
count--;
continue;
}
/* count != 0, *buf != IAC */
IACptr = memchr(buf, IAC, count);
wr = count;
if (IACptr)
wr = IACptr - buf;
rc = safe_write(fd, buf, wr);
if (rc != wr)
break;
buf += rc;
total += rc;
count -= rc;
}
/* here: rc - result of last short write */
if ((ssize_t)rc < 0) { /* error? */
if (total == 0)
return rc;
rc = 0;
}
return total + rc;
}
/* Must match getopt32 string */
enum {
OPT_WATCHCHILD = (1 << 2), /* -K */
OPT_INETD = (1 << 3) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -i */
OPT_PORT = (1 << 4) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -p PORT */
OPT_FOREGROUND = (1 << 6) * ENABLE_FEATURE_TELNETD_STANDALONE, /* -F */
OPT_SYSLOG = (1 << 7) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -S */
OPT_WAIT = (1 << 8) * ENABLE_FEATURE_TELNETD_INETD_WAIT, /* -w SEC */
};
static struct tsession *
make_new_session(
IF_FEATURE_TELNETD_STANDALONE(int sock)
IF_NOT_FEATURE_TELNETD_STANDALONE(void)
) {
#if !ENABLE_FEATURE_TELNETD_STANDALONE
enum { sock = 0 };
#endif
const char *login_argv[2];
struct termios termbuf;
int fd, pid;
char tty_name[GETPTY_BUFSIZE];
struct tsession *ts = xzalloc(sizeof(struct tsession) + BUFSIZE * 2);
/*ts->buf1 = (char *)(ts + 1);*/
/*ts->buf2 = ts->buf1 + BUFSIZE;*/
/* Got a new connection, set up a tty */
fd = xgetpty(tty_name);
if (fd > G.maxfd)
G.maxfd = fd;
ts->ptyfd = fd;
ndelay_on(fd);
close_on_exec_on(fd);
/* SO_KEEPALIVE by popular demand */
setsockopt_keepalive(sock);
#if ENABLE_FEATURE_TELNETD_STANDALONE
ts->sockfd_read = sock;
ndelay_on(sock);
if (sock == 0) { /* We are called with fd 0 - we are in inetd mode */
sock++; /* so use fd 1 for output */
ndelay_on(sock);
}
ts->sockfd_write = sock;
if (sock > G.maxfd)
G.maxfd = sock;
#else
/* ts->sockfd_read = 0; - done by xzalloc */
ts->sockfd_write = 1;
ndelay_on(0);
ndelay_on(1);
#endif
/* Make the telnet client understand we will echo characters so it
* should not do it locally. We don't tell the client to run linemode,
* because we want to handle line editing and tab completion and other
* stuff that requires char-by-char support. */
{
static const char iacs_to_send[] ALIGN1 = {
IAC, DO, TELOPT_ECHO,
IAC, DO, TELOPT_NAWS,
/* This requires telnetd.ctrlSQ.patch (incomplete) */
/*IAC, DO, TELOPT_LFLOW,*/
IAC, WILL, TELOPT_ECHO,
IAC, WILL, TELOPT_SGA
};
/* This confuses iac_safe_write(), it will try to duplicate
* each IAC... */
//memcpy(TS_BUF2(ts), iacs_to_send, sizeof(iacs_to_send));
//ts->rdidx2 = sizeof(iacs_to_send);
//ts->size2 = sizeof(iacs_to_send);
/* So just stuff it into TCP stream! (no error check...) */
#if ENABLE_FEATURE_TELNETD_STANDALONE
safe_write(sock, iacs_to_send, sizeof(iacs_to_send));
#else
safe_write(1, iacs_to_send, sizeof(iacs_to_send));
#endif
/*ts->rdidx2 = 0; - xzalloc did it */
/*ts->size2 = 0;*/
}
fflush_all();
pid = vfork(); /* NOMMU-friendly */
if (pid < 0) {
free(ts);
close(fd);
/* sock will be closed by caller */
bb_perror_msg("vfork");
return NULL;
}
if (pid > 0) {
/* Parent */
ts->shell_pid = pid;
return ts;
}
/* Child */
/* Careful - we are after vfork! */
/* Restore default signal handling ASAP */
bb_signals((1 << SIGCHLD) + (1 << SIGPIPE), SIG_DFL);
pid = getpid();
if (ENABLE_FEATURE_UTMP) {
len_and_sockaddr *lsa = get_peer_lsa(sock);
char *hostname = NULL;
if (lsa) {
hostname = xmalloc_sockaddr2dotted(&lsa->u.sa);
free(lsa);
}
write_new_utmp(pid, LOGIN_PROCESS, tty_name, /*username:*/ "LOGIN", hostname);
free(hostname);
}
/* Make new session and process group */
setsid();
/* Open the child's side of the tty */
/* NB: setsid() disconnects from any previous ctty's. Therefore
* we must open child's side of the tty AFTER setsid! */
close(0);
xopen(tty_name, O_RDWR); /* becomes our ctty */
xdup2(0, 1);
xdup2(0, 2);
tcsetpgrp(0, pid); /* switch this tty's process group to us */
/* The pseudo-terminal allocated to the client is configured to operate
* in cooked mode, and with XTABS CRMOD enabled (see tty(4)) */
tcgetattr(0, &termbuf);
termbuf.c_lflag |= ECHO; /* if we use readline we dont want this */
termbuf.c_oflag |= ONLCR | XTABS;
termbuf.c_iflag |= ICRNL;
termbuf.c_iflag &= ~IXOFF;
/*termbuf.c_lflag &= ~ICANON;*/
tcsetattr_stdin_TCSANOW(&termbuf);
/* Uses FILE-based I/O to stdout, but does fflush_all(),
* so should be safe with vfork.
* I fear, though, that some users will have ridiculously big
* issue files, and they may block writing to fd 1,
* (parent is supposed to read it, but parent waits
* for vforked child to exec!) */
print_login_issue(G.issuefile, tty_name);
/* Exec shell / login / whatever */
login_argv[0] = G.loginpath;
login_argv[1] = NULL;
/* exec busybox applet (if PREFER_APPLETS=y), if that fails,
* exec external program.
* NB: sock is either 0 or has CLOEXEC set on it.
* fd has CLOEXEC set on it too. These two fds will be closed here.
*/
BB_EXECVP(G.loginpath, (char **)login_argv);
/* _exit is safer with vfork, and we shouldn't send message
* to remote clients anyway */
_exit(EXIT_FAILURE); /*bb_perror_msg_and_die("execv %s", G.loginpath);*/
}
#if ENABLE_FEATURE_TELNETD_STANDALONE
static void
free_session(struct tsession *ts)
{
struct tsession *t;
if (option_mask32 & OPT_INETD)
exit(EXIT_SUCCESS);
/* Unlink this telnet session from the session list */
t = G.sessions;
if (t == ts)
G.sessions = ts->next;
else {
while (t->next != ts)
t = t->next;
t->next = ts->next;
}
#if 0
/* It was said that "normal" telnetd just closes ptyfd,
* doesn't send SIGKILL. When we close ptyfd,
* kernel sends SIGHUP to processes having slave side opened. */
kill(ts->shell_pid, SIGKILL);
waitpid(ts->shell_pid, NULL, 0);
#endif
close(ts->ptyfd);
close(ts->sockfd_read);
/* We do not need to close(ts->sockfd_write), it's the same
* as sockfd_read unless we are in inetd mode. But in inetd mode
* we do not reach this */
free(ts);
/* Scan all sessions and find new maxfd */
G.maxfd = 0;
ts = G.sessions;
while (ts) {
if (G.maxfd < ts->ptyfd)
G.maxfd = ts->ptyfd;
if (G.maxfd < ts->sockfd_read)
G.maxfd = ts->sockfd_read;
#if 0
/* Again, sockfd_write == sockfd_read here */
if (G.maxfd < ts->sockfd_write)
G.maxfd = ts->sockfd_write;
#endif
ts = ts->next;
}
}
#else /* !FEATURE_TELNETD_STANDALONE */
/* Used in main() only, thus "return 0" actually is exit(EXIT_SUCCESS). */
#define free_session(ts) return 0
#endif
static void handle_sigchld(int sig UNUSED_PARAM)
{
pid_t pid;
struct tsession *ts;
int save_errno = errno;
/* Looping: more than one child may have exited */
while (1) {
pid = wait_any_nohang(NULL);
if (pid <= 0)
break;
ts = G.sessions;
while (ts) {
if (ts->shell_pid == pid) {
ts->shell_pid = -1;
update_utmp_DEAD_PROCESS(pid);
break;
}
ts = ts->next;
}
}
errno = save_errno;
}
int telnetd_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
int telnetd_main(int argc UNUSED_PARAM, char **argv)
{
fd_set rdfdset, wrfdset;
unsigned opt;
int count;
struct tsession *ts;
#if ENABLE_FEATURE_TELNETD_STANDALONE
#define IS_INETD (opt & OPT_INETD)
int master_fd = 0;
int sec_linger = 0;
char *opt_bindaddr = NULL;
char *opt_portnbr;
#else
enum {
IS_INETD = 1,
master_fd = -1,
};
#endif
INIT_G();
/* -w NUM, and implies -F. -w and -i don't mix */
IF_FEATURE_TELNETD_INETD_WAIT(opt_complementary = "wF:w+:i--w:w--i";)
/* Even if !STANDALONE, we accept (and ignore) -i, thus people
* don't need to guess whether it's ok to pass -i to us */
opt = getopt32(argv, "f:l:Ki"
IF_FEATURE_TELNETD_STANDALONE("p:b:F")
IF_FEATURE_TELNETD_INETD_WAIT("Sw:"),
&G.issuefile, &G.loginpath
IF_FEATURE_TELNETD_STANDALONE(, &opt_portnbr, &opt_bindaddr)
IF_FEATURE_TELNETD_INETD_WAIT(, &sec_linger)
);
if (!IS_INETD /*&& !re_execed*/) {
/* inform that we start in standalone mode?
* May be useful when people forget to give -i */
/*bb_error_msg("listening for connections");*/
if (!(opt & OPT_FOREGROUND)) {
/* DAEMON_CHDIR_ROOT was giving inconsistent
* behavior with/without -F, -i */
bb_daemonize_or_rexec(0 /*was DAEMON_CHDIR_ROOT*/, argv);
}
}
/* Redirect log to syslog early, if needed */
if (IS_INETD || (opt & OPT_SYSLOG) || !(opt & OPT_FOREGROUND)) {
openlog(applet_name, LOG_PID, LOG_DAEMON);
logmode = LOGMODE_SYSLOG;
}
#if ENABLE_FEATURE_TELNETD_STANDALONE
if (IS_INETD) {
G.sessions = make_new_session(0);
if (!G.sessions) /* pty opening or vfork problem, exit */
return 1; /* make_new_session printed error message */
} else {
master_fd = 0;
if (!(opt & OPT_WAIT)) {
unsigned portnbr = 23;
if (opt & OPT_PORT)
portnbr = xatou16(opt_portnbr);
master_fd = create_and_bind_stream_or_die(opt_bindaddr, portnbr);
xlisten(master_fd, 1);
}
close_on_exec_on(master_fd);
}
#else
G.sessions = make_new_session();
if (!G.sessions) /* pty opening or vfork problem, exit */
return 1; /* make_new_session printed error message */
#endif
/* We don't want to die if just one session is broken */
signal(SIGPIPE, SIG_IGN);
if (opt & OPT_WATCHCHILD)
signal(SIGCHLD, handle_sigchld);
else /* prevent dead children from becoming zombies */
signal(SIGCHLD, SIG_IGN);
/*
This is how the buffers are used. The arrows indicate data flow.
+-------+ wridx1++ +------+ rdidx1++ +----------+
| | <-------------- | buf1 | <-------------- | |
| | size1-- +------+ size1++ | |
| pty | | socket |
| | rdidx2++ +------+ wridx2++ | |
| | --------------> | buf2 | --------------> | |
+-------+ size2++ +------+ size2-- +----------+
size1: "how many bytes are buffered for pty between rdidx1 and wridx1?"
size2: "how many bytes are buffered for socket between rdidx2 and wridx2?"
Each session has got two buffers. Buffers are circular. If sizeN == 0,
buffer is empty. If sizeN == BUFSIZE, buffer is full. In both these cases
rdidxN == wridxN.
*/
again:
FD_ZERO(&rdfdset);
FD_ZERO(&wrfdset);
/* Select on the master socket, all telnet sockets and their
* ptys if there is room in their session buffers.
* NB: scalability problem: we recalculate entire bitmap
* before each select. Can be a problem with 500+ connections. */
ts = G.sessions;
while (ts) {
struct tsession *next = ts->next; /* in case we free ts */
if (ts->shell_pid == -1) {
/* Child died and we detected that */
free_session(ts);
} else {
if (ts->size1 > 0) /* can write to pty */
FD_SET(ts->ptyfd, &wrfdset);
if (ts->size1 < BUFSIZE) /* can read from socket */
FD_SET(ts->sockfd_read, &rdfdset);
if (ts->size2 > 0) /* can write to socket */
FD_SET(ts->sockfd_write, &wrfdset);
if (ts->size2 < BUFSIZE) /* can read from pty */
FD_SET(ts->ptyfd, &rdfdset);
}
ts = next;
}
if (!IS_INETD) {
FD_SET(master_fd, &rdfdset);
/* This is needed because free_session() does not
* take master_fd into account when it finds new
* maxfd among remaining fd's */
if (master_fd > G.maxfd)
G.maxfd = master_fd;
}
{
struct timeval *tv_ptr = NULL;
#if ENABLE_FEATURE_TELNETD_INETD_WAIT
struct timeval tv;
if ((opt & OPT_WAIT) && !G.sessions) {
tv.tv_sec = sec_linger;
tv.tv_usec = 0;
tv_ptr = &tv;
}
#endif
count = select(G.maxfd + 1, &rdfdset, &wrfdset, NULL, tv_ptr);
}
if (count == 0) /* "telnetd -w SEC" timed out */
return 0;
if (count < 0)
goto again; /* EINTR or ENOMEM */
#if ENABLE_FEATURE_TELNETD_STANDALONE
/* Check for and accept new sessions */
if (!IS_INETD && FD_ISSET(master_fd, &rdfdset)) {
int fd;
struct tsession *new_ts;
fd = accept(master_fd, NULL, NULL);
if (fd < 0)
goto again;
close_on_exec_on(fd);
/* Create a new session and link it into active list */
new_ts = make_new_session(fd);
if (new_ts) {
new_ts->next = G.sessions;
G.sessions = new_ts;
} else {
close(fd);
}
}
#endif
/* Then check for data tunneling */
ts = G.sessions;
while (ts) { /* For all sessions... */
struct tsession *next = ts->next; /* in case we free ts */
if (/*ts->size1 &&*/ FD_ISSET(ts->ptyfd, &wrfdset)) {
int num_totty;
unsigned char *ptr;
/* Write to pty from buffer 1 */
ptr = remove_iacs(ts, &num_totty);
count = safe_write(ts->ptyfd, ptr, num_totty);
if (count < 0) {
if (errno == EAGAIN)
goto skip1;
goto kill_session;
}
ts->size1 -= count;
ts->wridx1 += count;
if (ts->wridx1 >= BUFSIZE) /* actually == BUFSIZE */
ts->wridx1 = 0;
}
skip1:
if (/*ts->size2 &&*/ FD_ISSET(ts->sockfd_write, &wrfdset)) {
/* Write to socket from buffer 2 */
count = MIN(BUFSIZE - ts->wridx2, ts->size2);
count = iac_safe_write(ts->sockfd_write, (void*)(TS_BUF2(ts) + ts->wridx2), count);
if (count < 0) {
if (errno == EAGAIN)
goto skip2;
goto kill_session;
}
ts->size2 -= count;
ts->wridx2 += count;
if (ts->wridx2 >= BUFSIZE) /* actually == BUFSIZE */
ts->wridx2 = 0;
}
skip2:
/* Should not be needed, but... remove_iacs is actually buggy
* (it cannot process iacs which wrap around buffer's end)!
* Since properly fixing it requires writing bigger code,
* we rely instead on this code making it virtually impossible
* to have wrapped iac (people don't type at 2k/second).
* It also allows for bigger reads in common case. */
if (ts->size1 == 0) {
ts->rdidx1 = 0;
ts->wridx1 = 0;
}
if (ts->size2 == 0) {
ts->rdidx2 = 0;
ts->wridx2 = 0;
}
if (/*ts->size1 < BUFSIZE &&*/ FD_ISSET(ts->sockfd_read, &rdfdset)) {
/* Read from socket to buffer 1 */
count = MIN(BUFSIZE - ts->rdidx1, BUFSIZE - ts->size1);
count = safe_read(ts->sockfd_read, TS_BUF1(ts) + ts->rdidx1, count);
if (count <= 0) {
if (count < 0 && errno == EAGAIN)
goto skip3;
goto kill_session;
}
/* Ignore trailing NUL if it is there */
if (!TS_BUF1(ts)[ts->rdidx1 + count - 1]) {
--count;
}
ts->size1 += count;
ts->rdidx1 += count;
if (ts->rdidx1 >= BUFSIZE) /* actually == BUFSIZE */
ts->rdidx1 = 0;
}
skip3:
if (/*ts->size2 < BUFSIZE &&*/ FD_ISSET(ts->ptyfd, &rdfdset)) {
/* Read from pty to buffer 2 */
count = MIN(BUFSIZE - ts->rdidx2, BUFSIZE - ts->size2);
count = safe_read(ts->ptyfd, TS_BUF2(ts) + ts->rdidx2, count);
if (count <= 0) {
if (count < 0 && errno == EAGAIN)
goto skip4;
goto kill_session;
}
ts->size2 += count;
ts->rdidx2 += count;
if (ts->rdidx2 >= BUFSIZE) /* actually == BUFSIZE */
ts->rdidx2 = 0;
}
skip4:
ts = next;
continue;
kill_session:
if (ts->shell_pid > 0)
update_utmp_DEAD_PROCESS(ts->shell_pid);
free_session(ts);
ts = next;
}
goto again;
}
|
VRToxin-AOSP/android_external_busybox
|
networking/telnetd.c
|
C
|
gpl-2.0
| 20,915
|
/**************************************************************************************
* Copyright (C) 2008 EsperTech, Inc. All rights reserved. *
* http://esper.codehaus.org *
* http://www.espertech.com *
* ---------------------------------------------------------------------------------- *
* The software in this package is published under the terms of the GPL license *
* a copy of which has been included with this distribution in the license.txt file. *
**************************************************************************************/
package com.espertech.esper.epl.expression;
import com.espertech.esper.filter.FilterSpecLookupable;
public interface ExprFilterOptimizableNode
{
public boolean getFilterLookupEligible();
public FilterSpecLookupable getFilterLookupable();
}
|
mobile-event-processing/Asper
|
source/src/com/espertech/esper/epl/expression/ExprFilterOptimizableNode.java
|
Java
|
gpl-2.0
| 972
|
//////////////////////////////////////////////////////////////////////////
// Family Basic Keyboard //
//////////////////////////////////////////////////////////////////////////
class EXPAD_Keyboard : public EXPAD
{
public:
EXPAD_Keyboard( NES* parent ) : EXPAD( parent ) {}
void Reset();
BYTE Read4016();
BYTE Read4017();
void Write4016( BYTE data );
protected:
BOOL bGraph;
BOOL bOut;
BYTE ScanNo;
private:
};
|
yamanyandakure/VirtuaNES097
|
NES/PadEX/EXPAD_Keyboard.h
|
C
|
gpl-2.0
| 471
|
/*
* QEMU Cirrus CLGD 54xx VGA Emulator.
*
* Copyright (c) 2004 Fabrice Bellard
* Copyright (c) 2004 Makoto Suzuki (suzu)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/*
* Reference: Finn Thogersons' VGADOC4b
* available at http://home.worldonline.dk/~finth/
*/
#include "hw.h"
#include "pc.h"
#include "pci.h"
#include "console.h"
#include "vga_int.h"
#include "kvm.h"
#include "qemu-kvm.h"
#include "loader.h"
/*
* TODO:
* - destination write mask support not complete (bits 5..7)
* - optimize linear mappings
* - optimize bitblt functions
*/
//#define DEBUG_CIRRUS
//#define DEBUG_BITBLT
/***************************************
*
* definitions
*
***************************************/
// ID
#define CIRRUS_ID_CLGD5422 (0x23<<2)
#define CIRRUS_ID_CLGD5426 (0x24<<2)
#define CIRRUS_ID_CLGD5424 (0x25<<2)
#define CIRRUS_ID_CLGD5428 (0x26<<2)
#define CIRRUS_ID_CLGD5430 (0x28<<2)
#define CIRRUS_ID_CLGD5434 (0x2A<<2)
#define CIRRUS_ID_CLGD5436 (0x2B<<2)
#define CIRRUS_ID_CLGD5446 (0x2E<<2)
// sequencer 0x07
#define CIRRUS_SR7_BPP_VGA 0x00
#define CIRRUS_SR7_BPP_SVGA 0x01
#define CIRRUS_SR7_BPP_MASK 0x0e
#define CIRRUS_SR7_BPP_8 0x00
#define CIRRUS_SR7_BPP_16_DOUBLEVCLK 0x02
#define CIRRUS_SR7_BPP_24 0x04
#define CIRRUS_SR7_BPP_16 0x06
#define CIRRUS_SR7_BPP_32 0x08
#define CIRRUS_SR7_ISAADDR_MASK 0xe0
// sequencer 0x0f
#define CIRRUS_MEMSIZE_512k 0x08
#define CIRRUS_MEMSIZE_1M 0x10
#define CIRRUS_MEMSIZE_2M 0x18
#define CIRRUS_MEMFLAGS_BANKSWITCH 0x80 // bank switching is enabled.
// sequencer 0x12
#define CIRRUS_CURSOR_SHOW 0x01
#define CIRRUS_CURSOR_HIDDENPEL 0x02
#define CIRRUS_CURSOR_LARGE 0x04 // 64x64 if set, 32x32 if clear
// sequencer 0x17
#define CIRRUS_BUSTYPE_VLBFAST 0x10
#define CIRRUS_BUSTYPE_PCI 0x20
#define CIRRUS_BUSTYPE_VLBSLOW 0x30
#define CIRRUS_BUSTYPE_ISA 0x38
#define CIRRUS_MMIO_ENABLE 0x04
#define CIRRUS_MMIO_USE_PCIADDR 0x40 // 0xb8000 if cleared.
#define CIRRUS_MEMSIZEEXT_DOUBLE 0x80
// control 0x0b
#define CIRRUS_BANKING_DUAL 0x01
#define CIRRUS_BANKING_GRANULARITY_16K 0x20 // set:16k, clear:4k
// control 0x30
#define CIRRUS_BLTMODE_BACKWARDS 0x01
#define CIRRUS_BLTMODE_MEMSYSDEST 0x02
#define CIRRUS_BLTMODE_MEMSYSSRC 0x04
#define CIRRUS_BLTMODE_TRANSPARENTCOMP 0x08
#define CIRRUS_BLTMODE_PATTERNCOPY 0x40
#define CIRRUS_BLTMODE_COLOREXPAND 0x80
#define CIRRUS_BLTMODE_PIXELWIDTHMASK 0x30
#define CIRRUS_BLTMODE_PIXELWIDTH8 0x00
#define CIRRUS_BLTMODE_PIXELWIDTH16 0x10
#define CIRRUS_BLTMODE_PIXELWIDTH24 0x20
#define CIRRUS_BLTMODE_PIXELWIDTH32 0x30
// control 0x31
#define CIRRUS_BLT_BUSY 0x01
#define CIRRUS_BLT_START 0x02
#define CIRRUS_BLT_RESET 0x04
#define CIRRUS_BLT_FIFOUSED 0x10
#define CIRRUS_BLT_AUTOSTART 0x80
// control 0x32
#define CIRRUS_ROP_0 0x00
#define CIRRUS_ROP_SRC_AND_DST 0x05
#define CIRRUS_ROP_NOP 0x06
#define CIRRUS_ROP_SRC_AND_NOTDST 0x09
#define CIRRUS_ROP_NOTDST 0x0b
#define CIRRUS_ROP_SRC 0x0d
#define CIRRUS_ROP_1 0x0e
#define CIRRUS_ROP_NOTSRC_AND_DST 0x50
#define CIRRUS_ROP_SRC_XOR_DST 0x59
#define CIRRUS_ROP_SRC_OR_DST 0x6d
#define CIRRUS_ROP_NOTSRC_OR_NOTDST 0x90
#define CIRRUS_ROP_SRC_NOTXOR_DST 0x95
#define CIRRUS_ROP_SRC_OR_NOTDST 0xad
#define CIRRUS_ROP_NOTSRC 0xd0
#define CIRRUS_ROP_NOTSRC_OR_DST 0xd6
#define CIRRUS_ROP_NOTSRC_AND_NOTDST 0xda
#define CIRRUS_ROP_NOP_INDEX 2
#define CIRRUS_ROP_SRC_INDEX 5
// control 0x33
#define CIRRUS_BLTMODEEXT_SOLIDFILL 0x04
#define CIRRUS_BLTMODEEXT_COLOREXPINV 0x02
#define CIRRUS_BLTMODEEXT_DWORDGRANULARITY 0x01
// memory-mapped IO
#define CIRRUS_MMIO_BLTBGCOLOR 0x00 // dword
#define CIRRUS_MMIO_BLTFGCOLOR 0x04 // dword
#define CIRRUS_MMIO_BLTWIDTH 0x08 // word
#define CIRRUS_MMIO_BLTHEIGHT 0x0a // word
#define CIRRUS_MMIO_BLTDESTPITCH 0x0c // word
#define CIRRUS_MMIO_BLTSRCPITCH 0x0e // word
#define CIRRUS_MMIO_BLTDESTADDR 0x10 // dword
#define CIRRUS_MMIO_BLTSRCADDR 0x14 // dword
#define CIRRUS_MMIO_BLTWRITEMASK 0x17 // byte
#define CIRRUS_MMIO_BLTMODE 0x18 // byte
#define CIRRUS_MMIO_BLTROP 0x1a // byte
#define CIRRUS_MMIO_BLTMODEEXT 0x1b // byte
#define CIRRUS_MMIO_BLTTRANSPARENTCOLOR 0x1c // word?
#define CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK 0x20 // word?
#define CIRRUS_MMIO_LINEARDRAW_START_X 0x24 // word
#define CIRRUS_MMIO_LINEARDRAW_START_Y 0x26 // word
#define CIRRUS_MMIO_LINEARDRAW_END_X 0x28 // word
#define CIRRUS_MMIO_LINEARDRAW_END_Y 0x2a // word
#define CIRRUS_MMIO_LINEARDRAW_LINESTYLE_INC 0x2c // byte
#define CIRRUS_MMIO_LINEARDRAW_LINESTYLE_ROLLOVER 0x2d // byte
#define CIRRUS_MMIO_LINEARDRAW_LINESTYLE_MASK 0x2e // byte
#define CIRRUS_MMIO_LINEARDRAW_LINESTYLE_ACCUM 0x2f // byte
#define CIRRUS_MMIO_BRESENHAM_K1 0x30 // word
#define CIRRUS_MMIO_BRESENHAM_K3 0x32 // word
#define CIRRUS_MMIO_BRESENHAM_ERROR 0x34 // word
#define CIRRUS_MMIO_BRESENHAM_DELTA_MAJOR 0x36 // word
#define CIRRUS_MMIO_BRESENHAM_DIRECTION 0x38 // byte
#define CIRRUS_MMIO_LINEDRAW_MODE 0x39 // byte
#define CIRRUS_MMIO_BLTSTATUS 0x40 // byte
#define CIRRUS_PNPMMIO_SIZE 0x1000
#define BLTUNSAFE(s) \
( \
( /* check dst is within bounds */ \
(s)->cirrus_blt_height * ABS((s)->cirrus_blt_dstpitch) \
+ ((s)->cirrus_blt_dstaddr & (s)->cirrus_addr_mask) > \
(s)->vga.vram_size \
) || \
( /* check src is within bounds */ \
(s)->cirrus_blt_height * ABS((s)->cirrus_blt_srcpitch) \
+ ((s)->cirrus_blt_srcaddr & (s)->cirrus_addr_mask) > \
(s)->vga.vram_size \
) \
)
struct CirrusVGAState;
typedef void (*cirrus_bitblt_rop_t) (struct CirrusVGAState *s,
uint8_t * dst, const uint8_t * src,
int dstpitch, int srcpitch,
int bltwidth, int bltheight);
typedef void (*cirrus_fill_t)(struct CirrusVGAState *s,
uint8_t *dst, int dst_pitch, int width, int height);
typedef struct CirrusVGAState {
VGACommonState vga;
int cirrus_linear_io_addr;
int cirrus_linear_bitblt_io_addr;
int cirrus_mmio_io_addr;
uint32_t cirrus_addr_mask;
uint32_t linear_mmio_mask;
uint8_t cirrus_shadow_gr0;
uint8_t cirrus_shadow_gr1;
uint8_t cirrus_hidden_dac_lockindex;
uint8_t cirrus_hidden_dac_data;
uint32_t cirrus_bank_base[2];
uint32_t cirrus_bank_limit[2];
uint8_t cirrus_hidden_palette[48];
uint32_t hw_cursor_x;
uint32_t hw_cursor_y;
int cirrus_blt_pixelwidth;
int cirrus_blt_width;
int cirrus_blt_height;
int cirrus_blt_dstpitch;
int cirrus_blt_srcpitch;
uint32_t cirrus_blt_fgcol;
uint32_t cirrus_blt_bgcol;
uint32_t cirrus_blt_dstaddr;
uint32_t cirrus_blt_srcaddr;
uint8_t cirrus_blt_mode;
uint8_t cirrus_blt_modeext;
cirrus_bitblt_rop_t cirrus_rop;
#define CIRRUS_BLTBUFSIZE (2048 * 4) /* one line width */
uint8_t cirrus_bltbuf[CIRRUS_BLTBUFSIZE];
uint8_t *cirrus_srcptr;
uint8_t *cirrus_srcptr_end;
uint32_t cirrus_srccounter;
/* hwcursor display state */
int last_hw_cursor_size;
int last_hw_cursor_x;
int last_hw_cursor_y;
int last_hw_cursor_y_start;
int last_hw_cursor_y_end;
int real_vram_size; /* XXX: suppress that */
int device_id;
int bustype;
} CirrusVGAState;
typedef struct PCICirrusVGAState {
PCIDevice dev;
CirrusVGAState cirrus_vga;
} PCICirrusVGAState;
static uint8_t rop_to_index[256];
/***************************************
*
* prototypes.
*
***************************************/
static void cirrus_bitblt_reset(CirrusVGAState *s);
static void cirrus_update_memory_access(CirrusVGAState *s);
/***************************************
*
* raster operations
*
***************************************/
static void cirrus_bitblt_rop_nop(CirrusVGAState *s,
uint8_t *dst,const uint8_t *src,
int dstpitch,int srcpitch,
int bltwidth,int bltheight)
{
}
static void cirrus_bitblt_fill_nop(CirrusVGAState *s,
uint8_t *dst,
int dstpitch, int bltwidth,int bltheight)
{
}
#define ROP_NAME 0
#define ROP_OP(d, s) d = 0
#include "cirrus_vga_rop.h"
#define ROP_NAME src_and_dst
#define ROP_OP(d, s) d = (s) & (d)
#include "cirrus_vga_rop.h"
#define ROP_NAME src_and_notdst
#define ROP_OP(d, s) d = (s) & (~(d))
#include "cirrus_vga_rop.h"
#define ROP_NAME notdst
#define ROP_OP(d, s) d = ~(d)
#include "cirrus_vga_rop.h"
#define ROP_NAME src
#define ROP_OP(d, s) d = s
#include "cirrus_vga_rop.h"
#define ROP_NAME 1
#define ROP_OP(d, s) d = ~0
#include "cirrus_vga_rop.h"
#define ROP_NAME notsrc_and_dst
#define ROP_OP(d, s) d = (~(s)) & (d)
#include "cirrus_vga_rop.h"
#define ROP_NAME src_xor_dst
#define ROP_OP(d, s) d = (s) ^ (d)
#include "cirrus_vga_rop.h"
#define ROP_NAME src_or_dst
#define ROP_OP(d, s) d = (s) | (d)
#include "cirrus_vga_rop.h"
#define ROP_NAME notsrc_or_notdst
#define ROP_OP(d, s) d = (~(s)) | (~(d))
#include "cirrus_vga_rop.h"
#define ROP_NAME src_notxor_dst
#define ROP_OP(d, s) d = ~((s) ^ (d))
#include "cirrus_vga_rop.h"
#define ROP_NAME src_or_notdst
#define ROP_OP(d, s) d = (s) | (~(d))
#include "cirrus_vga_rop.h"
#define ROP_NAME notsrc
#define ROP_OP(d, s) d = (~(s))
#include "cirrus_vga_rop.h"
#define ROP_NAME notsrc_or_dst
#define ROP_OP(d, s) d = (~(s)) | (d)
#include "cirrus_vga_rop.h"
#define ROP_NAME notsrc_and_notdst
#define ROP_OP(d, s) d = (~(s)) & (~(d))
#include "cirrus_vga_rop.h"
static const cirrus_bitblt_rop_t cirrus_fwd_rop[16] = {
cirrus_bitblt_rop_fwd_0,
cirrus_bitblt_rop_fwd_src_and_dst,
cirrus_bitblt_rop_nop,
cirrus_bitblt_rop_fwd_src_and_notdst,
cirrus_bitblt_rop_fwd_notdst,
cirrus_bitblt_rop_fwd_src,
cirrus_bitblt_rop_fwd_1,
cirrus_bitblt_rop_fwd_notsrc_and_dst,
cirrus_bitblt_rop_fwd_src_xor_dst,
cirrus_bitblt_rop_fwd_src_or_dst,
cirrus_bitblt_rop_fwd_notsrc_or_notdst,
cirrus_bitblt_rop_fwd_src_notxor_dst,
cirrus_bitblt_rop_fwd_src_or_notdst,
cirrus_bitblt_rop_fwd_notsrc,
cirrus_bitblt_rop_fwd_notsrc_or_dst,
cirrus_bitblt_rop_fwd_notsrc_and_notdst,
};
static const cirrus_bitblt_rop_t cirrus_bkwd_rop[16] = {
cirrus_bitblt_rop_bkwd_0,
cirrus_bitblt_rop_bkwd_src_and_dst,
cirrus_bitblt_rop_nop,
cirrus_bitblt_rop_bkwd_src_and_notdst,
cirrus_bitblt_rop_bkwd_notdst,
cirrus_bitblt_rop_bkwd_src,
cirrus_bitblt_rop_bkwd_1,
cirrus_bitblt_rop_bkwd_notsrc_and_dst,
cirrus_bitblt_rop_bkwd_src_xor_dst,
cirrus_bitblt_rop_bkwd_src_or_dst,
cirrus_bitblt_rop_bkwd_notsrc_or_notdst,
cirrus_bitblt_rop_bkwd_src_notxor_dst,
cirrus_bitblt_rop_bkwd_src_or_notdst,
cirrus_bitblt_rop_bkwd_notsrc,
cirrus_bitblt_rop_bkwd_notsrc_or_dst,
cirrus_bitblt_rop_bkwd_notsrc_and_notdst,
};
#define TRANSP_ROP(name) {\
name ## _8,\
name ## _16,\
}
#define TRANSP_NOP(func) {\
func,\
func,\
}
static const cirrus_bitblt_rop_t cirrus_fwd_transp_rop[16][2] = {
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_0),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src_and_dst),
TRANSP_NOP(cirrus_bitblt_rop_nop),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src_and_notdst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_notdst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_1),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_notsrc_and_dst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src_xor_dst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src_or_dst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_notsrc_or_notdst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src_notxor_dst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_src_or_notdst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_notsrc),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_notsrc_or_dst),
TRANSP_ROP(cirrus_bitblt_rop_fwd_transp_notsrc_and_notdst),
};
static const cirrus_bitblt_rop_t cirrus_bkwd_transp_rop[16][2] = {
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_0),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src_and_dst),
TRANSP_NOP(cirrus_bitblt_rop_nop),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src_and_notdst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_notdst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_1),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_notsrc_and_dst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src_xor_dst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src_or_dst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_notsrc_or_notdst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src_notxor_dst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_src_or_notdst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_notsrc),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_notsrc_or_dst),
TRANSP_ROP(cirrus_bitblt_rop_bkwd_transp_notsrc_and_notdst),
};
#define ROP2(name) {\
name ## _8,\
name ## _16,\
name ## _24,\
name ## _32,\
}
#define ROP_NOP2(func) {\
func,\
func,\
func,\
func,\
}
static const cirrus_bitblt_rop_t cirrus_patternfill[16][4] = {
ROP2(cirrus_patternfill_0),
ROP2(cirrus_patternfill_src_and_dst),
ROP_NOP2(cirrus_bitblt_rop_nop),
ROP2(cirrus_patternfill_src_and_notdst),
ROP2(cirrus_patternfill_notdst),
ROP2(cirrus_patternfill_src),
ROP2(cirrus_patternfill_1),
ROP2(cirrus_patternfill_notsrc_and_dst),
ROP2(cirrus_patternfill_src_xor_dst),
ROP2(cirrus_patternfill_src_or_dst),
ROP2(cirrus_patternfill_notsrc_or_notdst),
ROP2(cirrus_patternfill_src_notxor_dst),
ROP2(cirrus_patternfill_src_or_notdst),
ROP2(cirrus_patternfill_notsrc),
ROP2(cirrus_patternfill_notsrc_or_dst),
ROP2(cirrus_patternfill_notsrc_and_notdst),
};
static const cirrus_bitblt_rop_t cirrus_colorexpand_transp[16][4] = {
ROP2(cirrus_colorexpand_transp_0),
ROP2(cirrus_colorexpand_transp_src_and_dst),
ROP_NOP2(cirrus_bitblt_rop_nop),
ROP2(cirrus_colorexpand_transp_src_and_notdst),
ROP2(cirrus_colorexpand_transp_notdst),
ROP2(cirrus_colorexpand_transp_src),
ROP2(cirrus_colorexpand_transp_1),
ROP2(cirrus_colorexpand_transp_notsrc_and_dst),
ROP2(cirrus_colorexpand_transp_src_xor_dst),
ROP2(cirrus_colorexpand_transp_src_or_dst),
ROP2(cirrus_colorexpand_transp_notsrc_or_notdst),
ROP2(cirrus_colorexpand_transp_src_notxor_dst),
ROP2(cirrus_colorexpand_transp_src_or_notdst),
ROP2(cirrus_colorexpand_transp_notsrc),
ROP2(cirrus_colorexpand_transp_notsrc_or_dst),
ROP2(cirrus_colorexpand_transp_notsrc_and_notdst),
};
static const cirrus_bitblt_rop_t cirrus_colorexpand[16][4] = {
ROP2(cirrus_colorexpand_0),
ROP2(cirrus_colorexpand_src_and_dst),
ROP_NOP2(cirrus_bitblt_rop_nop),
ROP2(cirrus_colorexpand_src_and_notdst),
ROP2(cirrus_colorexpand_notdst),
ROP2(cirrus_colorexpand_src),
ROP2(cirrus_colorexpand_1),
ROP2(cirrus_colorexpand_notsrc_and_dst),
ROP2(cirrus_colorexpand_src_xor_dst),
ROP2(cirrus_colorexpand_src_or_dst),
ROP2(cirrus_colorexpand_notsrc_or_notdst),
ROP2(cirrus_colorexpand_src_notxor_dst),
ROP2(cirrus_colorexpand_src_or_notdst),
ROP2(cirrus_colorexpand_notsrc),
ROP2(cirrus_colorexpand_notsrc_or_dst),
ROP2(cirrus_colorexpand_notsrc_and_notdst),
};
static const cirrus_bitblt_rop_t cirrus_colorexpand_pattern_transp[16][4] = {
ROP2(cirrus_colorexpand_pattern_transp_0),
ROP2(cirrus_colorexpand_pattern_transp_src_and_dst),
ROP_NOP2(cirrus_bitblt_rop_nop),
ROP2(cirrus_colorexpand_pattern_transp_src_and_notdst),
ROP2(cirrus_colorexpand_pattern_transp_notdst),
ROP2(cirrus_colorexpand_pattern_transp_src),
ROP2(cirrus_colorexpand_pattern_transp_1),
ROP2(cirrus_colorexpand_pattern_transp_notsrc_and_dst),
ROP2(cirrus_colorexpand_pattern_transp_src_xor_dst),
ROP2(cirrus_colorexpand_pattern_transp_src_or_dst),
ROP2(cirrus_colorexpand_pattern_transp_notsrc_or_notdst),
ROP2(cirrus_colorexpand_pattern_transp_src_notxor_dst),
ROP2(cirrus_colorexpand_pattern_transp_src_or_notdst),
ROP2(cirrus_colorexpand_pattern_transp_notsrc),
ROP2(cirrus_colorexpand_pattern_transp_notsrc_or_dst),
ROP2(cirrus_colorexpand_pattern_transp_notsrc_and_notdst),
};
static const cirrus_bitblt_rop_t cirrus_colorexpand_pattern[16][4] = {
ROP2(cirrus_colorexpand_pattern_0),
ROP2(cirrus_colorexpand_pattern_src_and_dst),
ROP_NOP2(cirrus_bitblt_rop_nop),
ROP2(cirrus_colorexpand_pattern_src_and_notdst),
ROP2(cirrus_colorexpand_pattern_notdst),
ROP2(cirrus_colorexpand_pattern_src),
ROP2(cirrus_colorexpand_pattern_1),
ROP2(cirrus_colorexpand_pattern_notsrc_and_dst),
ROP2(cirrus_colorexpand_pattern_src_xor_dst),
ROP2(cirrus_colorexpand_pattern_src_or_dst),
ROP2(cirrus_colorexpand_pattern_notsrc_or_notdst),
ROP2(cirrus_colorexpand_pattern_src_notxor_dst),
ROP2(cirrus_colorexpand_pattern_src_or_notdst),
ROP2(cirrus_colorexpand_pattern_notsrc),
ROP2(cirrus_colorexpand_pattern_notsrc_or_dst),
ROP2(cirrus_colorexpand_pattern_notsrc_and_notdst),
};
static const cirrus_fill_t cirrus_fill[16][4] = {
ROP2(cirrus_fill_0),
ROP2(cirrus_fill_src_and_dst),
ROP_NOP2(cirrus_bitblt_fill_nop),
ROP2(cirrus_fill_src_and_notdst),
ROP2(cirrus_fill_notdst),
ROP2(cirrus_fill_src),
ROP2(cirrus_fill_1),
ROP2(cirrus_fill_notsrc_and_dst),
ROP2(cirrus_fill_src_xor_dst),
ROP2(cirrus_fill_src_or_dst),
ROP2(cirrus_fill_notsrc_or_notdst),
ROP2(cirrus_fill_src_notxor_dst),
ROP2(cirrus_fill_src_or_notdst),
ROP2(cirrus_fill_notsrc),
ROP2(cirrus_fill_notsrc_or_dst),
ROP2(cirrus_fill_notsrc_and_notdst),
};
static inline void cirrus_bitblt_fgcol(CirrusVGAState *s)
{
unsigned int color;
switch (s->cirrus_blt_pixelwidth) {
case 1:
s->cirrus_blt_fgcol = s->cirrus_shadow_gr1;
break;
case 2:
color = s->cirrus_shadow_gr1 | (s->vga.gr[0x11] << 8);
s->cirrus_blt_fgcol = le16_to_cpu(color);
break;
case 3:
s->cirrus_blt_fgcol = s->cirrus_shadow_gr1 |
(s->vga.gr[0x11] << 8) | (s->vga.gr[0x13] << 16);
break;
default:
case 4:
color = s->cirrus_shadow_gr1 | (s->vga.gr[0x11] << 8) |
(s->vga.gr[0x13] << 16) | (s->vga.gr[0x15] << 24);
s->cirrus_blt_fgcol = le32_to_cpu(color);
break;
}
}
static inline void cirrus_bitblt_bgcol(CirrusVGAState *s)
{
unsigned int color;
switch (s->cirrus_blt_pixelwidth) {
case 1:
s->cirrus_blt_bgcol = s->cirrus_shadow_gr0;
break;
case 2:
color = s->cirrus_shadow_gr0 | (s->vga.gr[0x10] << 8);
s->cirrus_blt_bgcol = le16_to_cpu(color);
break;
case 3:
s->cirrus_blt_bgcol = s->cirrus_shadow_gr0 |
(s->vga.gr[0x10] << 8) | (s->vga.gr[0x12] << 16);
break;
default:
case 4:
color = s->cirrus_shadow_gr0 | (s->vga.gr[0x10] << 8) |
(s->vga.gr[0x12] << 16) | (s->vga.gr[0x14] << 24);
s->cirrus_blt_bgcol = le32_to_cpu(color);
break;
}
}
static void cirrus_invalidate_region(CirrusVGAState * s, int off_begin,
int off_pitch, int bytesperline,
int lines)
{
int y;
int off_cur;
int off_cur_end;
for (y = 0; y < lines; y++) {
off_cur = off_begin;
off_cur_end = (off_cur + bytesperline) & s->cirrus_addr_mask;
off_cur &= TARGET_PAGE_MASK;
while (off_cur < off_cur_end) {
cpu_physical_memory_set_dirty(s->vga.vram_offset + off_cur);
off_cur += TARGET_PAGE_SIZE;
}
off_begin += off_pitch;
}
}
static int cirrus_bitblt_common_patterncopy(CirrusVGAState * s,
const uint8_t * src)
{
uint8_t *dst;
dst = s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask);
if (BLTUNSAFE(s))
return 0;
(*s->cirrus_rop) (s, dst, src,
s->cirrus_blt_dstpitch, 0,
s->cirrus_blt_width, s->cirrus_blt_height);
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,
s->cirrus_blt_dstpitch, s->cirrus_blt_width,
s->cirrus_blt_height);
return 1;
}
/* fill */
static int cirrus_bitblt_solidfill(CirrusVGAState *s, int blt_rop)
{
cirrus_fill_t rop_func;
if (BLTUNSAFE(s))
return 0;
rop_func = cirrus_fill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
rop_func(s, s->vga.vram_ptr + (s->cirrus_blt_dstaddr & s->cirrus_addr_mask),
s->cirrus_blt_dstpitch,
s->cirrus_blt_width, s->cirrus_blt_height);
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,
s->cirrus_blt_dstpitch, s->cirrus_blt_width,
s->cirrus_blt_height);
cirrus_bitblt_reset(s);
return 1;
}
/***************************************
*
* bitblt (video-to-video)
*
***************************************/
static int cirrus_bitblt_videotovideo_patterncopy(CirrusVGAState * s)
{
return cirrus_bitblt_common_patterncopy(s,
s->vga.vram_ptr + ((s->cirrus_blt_srcaddr & ~7) &
s->cirrus_addr_mask));
}
static void cirrus_do_copy(CirrusVGAState *s, int dst, int src, int w, int h)
{
int sx, sy;
int dx, dy;
int width, height;
int depth;
int notify = 0;
depth = s->vga.get_bpp(&s->vga) / 8;
s->vga.get_resolution(&s->vga, &width, &height);
/* extra x, y */
sx = (src % ABS(s->cirrus_blt_srcpitch)) / depth;
sy = (src / ABS(s->cirrus_blt_srcpitch));
dx = (dst % ABS(s->cirrus_blt_dstpitch)) / depth;
dy = (dst / ABS(s->cirrus_blt_dstpitch));
/* normalize width */
w /= depth;
/* if we're doing a backward copy, we have to adjust
our x/y to be the upper left corner (instead of the lower
right corner) */
if (s->cirrus_blt_dstpitch < 0) {
sx -= (s->cirrus_blt_width / depth) - 1;
dx -= (s->cirrus_blt_width / depth) - 1;
sy -= s->cirrus_blt_height - 1;
dy -= s->cirrus_blt_height - 1;
}
/* are we in the visible portion of memory? */
if (sx >= 0 && sy >= 0 && dx >= 0 && dy >= 0 &&
(sx + w) <= width && (sy + h) <= height &&
(dx + w) <= width && (dy + h) <= height) {
notify = 1;
}
/* make to sure only copy if it's a plain copy ROP */
if (*s->cirrus_rop != cirrus_bitblt_rop_fwd_src &&
*s->cirrus_rop != cirrus_bitblt_rop_bkwd_src)
notify = 0;
/* we have to flush all pending changes so that the copy
is generated at the appropriate moment in time */
if (notify)
vga_hw_update();
(*s->cirrus_rop) (s, s->vga.vram_ptr +
(s->cirrus_blt_dstaddr & s->cirrus_addr_mask),
s->vga.vram_ptr +
(s->cirrus_blt_srcaddr & s->cirrus_addr_mask),
s->cirrus_blt_dstpitch, s->cirrus_blt_srcpitch,
s->cirrus_blt_width, s->cirrus_blt_height);
if (notify)
qemu_console_copy(s->vga.ds,
sx, sy, dx, dy,
s->cirrus_blt_width / depth,
s->cirrus_blt_height);
/* we don't have to notify the display that this portion has
changed since qemu_console_copy implies this */
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr,
s->cirrus_blt_dstpitch, s->cirrus_blt_width,
s->cirrus_blt_height);
}
static int cirrus_bitblt_videotovideo_copy(CirrusVGAState * s)
{
if (BLTUNSAFE(s))
return 0;
cirrus_do_copy(s, s->cirrus_blt_dstaddr - s->vga.start_addr,
s->cirrus_blt_srcaddr - s->vga.start_addr,
s->cirrus_blt_width, s->cirrus_blt_height);
return 1;
}
/***************************************
*
* bitblt (cpu-to-video)
*
***************************************/
static void cirrus_bitblt_cputovideo_next(CirrusVGAState * s)
{
int copy_count;
uint8_t *end_ptr;
if (s->cirrus_srccounter > 0) {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {
cirrus_bitblt_common_patterncopy(s, s->cirrus_bltbuf);
the_end:
s->cirrus_srccounter = 0;
cirrus_bitblt_reset(s);
} else {
/* at least one scan line */
do {
(*s->cirrus_rop)(s, s->vga.vram_ptr +
(s->cirrus_blt_dstaddr & s->cirrus_addr_mask),
s->cirrus_bltbuf, 0, 0, s->cirrus_blt_width, 1);
cirrus_invalidate_region(s, s->cirrus_blt_dstaddr, 0,
s->cirrus_blt_width, 1);
s->cirrus_blt_dstaddr += s->cirrus_blt_dstpitch;
s->cirrus_srccounter -= s->cirrus_blt_srcpitch;
if (s->cirrus_srccounter <= 0)
goto the_end;
/* more bytes than needed can be transfered because of
word alignment, so we keep them for the next line */
/* XXX: keep alignment to speed up transfer */
end_ptr = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;
copy_count = s->cirrus_srcptr_end - end_ptr;
memmove(s->cirrus_bltbuf, end_ptr, copy_count);
s->cirrus_srcptr = s->cirrus_bltbuf + copy_count;
s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;
} while (s->cirrus_srcptr >= s->cirrus_srcptr_end);
}
}
}
/***************************************
*
* bitblt wrapper
*
***************************************/
static void cirrus_bitblt_reset(CirrusVGAState * s)
{
int need_update;
s->vga.gr[0x31] &=
~(CIRRUS_BLT_START | CIRRUS_BLT_BUSY | CIRRUS_BLT_FIFOUSED);
need_update = s->cirrus_srcptr != &s->cirrus_bltbuf[0]
|| s->cirrus_srcptr_end != &s->cirrus_bltbuf[0];
s->cirrus_srcptr = &s->cirrus_bltbuf[0];
s->cirrus_srcptr_end = &s->cirrus_bltbuf[0];
s->cirrus_srccounter = 0;
if (!need_update)
return;
cirrus_update_memory_access(s);
}
static int cirrus_bitblt_cputovideo(CirrusVGAState * s)
{
int w;
s->cirrus_blt_mode &= ~CIRRUS_BLTMODE_MEMSYSSRC;
s->cirrus_srcptr = &s->cirrus_bltbuf[0];
s->cirrus_srcptr_end = &s->cirrus_bltbuf[0];
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_COLOREXPAND) {
s->cirrus_blt_srcpitch = 8;
} else {
/* XXX: check for 24 bpp */
s->cirrus_blt_srcpitch = 8 * 8 * s->cirrus_blt_pixelwidth;
}
s->cirrus_srccounter = s->cirrus_blt_srcpitch;
} else {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_COLOREXPAND) {
w = s->cirrus_blt_width / s->cirrus_blt_pixelwidth;
if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_DWORDGRANULARITY)
s->cirrus_blt_srcpitch = ((w + 31) >> 5);
else
s->cirrus_blt_srcpitch = ((w + 7) >> 3);
} else {
/* always align input size to 32 bits */
s->cirrus_blt_srcpitch = (s->cirrus_blt_width + 3) & ~3;
}
s->cirrus_srccounter = s->cirrus_blt_srcpitch * s->cirrus_blt_height;
}
s->cirrus_srcptr = s->cirrus_bltbuf;
s->cirrus_srcptr_end = s->cirrus_bltbuf + s->cirrus_blt_srcpitch;
cirrus_update_memory_access(s);
return 1;
}
static int cirrus_bitblt_videotocpu(CirrusVGAState * s)
{
/* XXX */
#ifdef DEBUG_BITBLT
printf("cirrus: bitblt (video to cpu) is not implemented yet\n");
#endif
return 0;
}
static int cirrus_bitblt_videotovideo(CirrusVGAState * s)
{
int ret;
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {
ret = cirrus_bitblt_videotovideo_patterncopy(s);
} else {
ret = cirrus_bitblt_videotovideo_copy(s);
}
if (ret)
cirrus_bitblt_reset(s);
return ret;
}
static void cirrus_bitblt_start(CirrusVGAState * s)
{
uint8_t blt_rop;
s->vga.gr[0x31] |= CIRRUS_BLT_BUSY;
s->cirrus_blt_width = (s->vga.gr[0x20] | (s->vga.gr[0x21] << 8)) + 1;
s->cirrus_blt_height = (s->vga.gr[0x22] | (s->vga.gr[0x23] << 8)) + 1;
s->cirrus_blt_dstpitch = (s->vga.gr[0x24] | (s->vga.gr[0x25] << 8));
s->cirrus_blt_srcpitch = (s->vga.gr[0x26] | (s->vga.gr[0x27] << 8));
s->cirrus_blt_dstaddr =
(s->vga.gr[0x28] | (s->vga.gr[0x29] << 8) | (s->vga.gr[0x2a] << 16));
s->cirrus_blt_srcaddr =
(s->vga.gr[0x2c] | (s->vga.gr[0x2d] << 8) | (s->vga.gr[0x2e] << 16));
s->cirrus_blt_mode = s->vga.gr[0x30];
s->cirrus_blt_modeext = s->vga.gr[0x33];
blt_rop = s->vga.gr[0x32];
#ifdef DEBUG_BITBLT
printf("rop=0x%02x mode=0x%02x modeext=0x%02x w=%d h=%d dpitch=%d spitch=%d daddr=0x%08x saddr=0x%08x writemask=0x%02x\n",
blt_rop,
s->cirrus_blt_mode,
s->cirrus_blt_modeext,
s->cirrus_blt_width,
s->cirrus_blt_height,
s->cirrus_blt_dstpitch,
s->cirrus_blt_srcpitch,
s->cirrus_blt_dstaddr,
s->cirrus_blt_srcaddr,
s->vga.gr[0x2f]);
#endif
switch (s->cirrus_blt_mode & CIRRUS_BLTMODE_PIXELWIDTHMASK) {
case CIRRUS_BLTMODE_PIXELWIDTH8:
s->cirrus_blt_pixelwidth = 1;
break;
case CIRRUS_BLTMODE_PIXELWIDTH16:
s->cirrus_blt_pixelwidth = 2;
break;
case CIRRUS_BLTMODE_PIXELWIDTH24:
s->cirrus_blt_pixelwidth = 3;
break;
case CIRRUS_BLTMODE_PIXELWIDTH32:
s->cirrus_blt_pixelwidth = 4;
break;
default:
#ifdef DEBUG_BITBLT
printf("cirrus: bitblt - pixel width is unknown\n");
#endif
goto bitblt_ignore;
}
s->cirrus_blt_mode &= ~CIRRUS_BLTMODE_PIXELWIDTHMASK;
if ((s->
cirrus_blt_mode & (CIRRUS_BLTMODE_MEMSYSSRC |
CIRRUS_BLTMODE_MEMSYSDEST))
== (CIRRUS_BLTMODE_MEMSYSSRC | CIRRUS_BLTMODE_MEMSYSDEST)) {
#ifdef DEBUG_BITBLT
printf("cirrus: bitblt - memory-to-memory copy is requested\n");
#endif
goto bitblt_ignore;
}
if ((s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_SOLIDFILL) &&
(s->cirrus_blt_mode & (CIRRUS_BLTMODE_MEMSYSDEST |
CIRRUS_BLTMODE_TRANSPARENTCOMP |
CIRRUS_BLTMODE_PATTERNCOPY |
CIRRUS_BLTMODE_COLOREXPAND)) ==
(CIRRUS_BLTMODE_PATTERNCOPY | CIRRUS_BLTMODE_COLOREXPAND)) {
cirrus_bitblt_fgcol(s);
cirrus_bitblt_solidfill(s, blt_rop);
} else {
if ((s->cirrus_blt_mode & (CIRRUS_BLTMODE_COLOREXPAND |
CIRRUS_BLTMODE_PATTERNCOPY)) ==
CIRRUS_BLTMODE_COLOREXPAND) {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_TRANSPARENTCOMP) {
if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV)
cirrus_bitblt_bgcol(s);
else
cirrus_bitblt_fgcol(s);
s->cirrus_rop = cirrus_colorexpand_transp[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
} else {
cirrus_bitblt_fgcol(s);
cirrus_bitblt_bgcol(s);
s->cirrus_rop = cirrus_colorexpand[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
}
} else if (s->cirrus_blt_mode & CIRRUS_BLTMODE_PATTERNCOPY) {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_COLOREXPAND) {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_TRANSPARENTCOMP) {
if (s->cirrus_blt_modeext & CIRRUS_BLTMODEEXT_COLOREXPINV)
cirrus_bitblt_bgcol(s);
else
cirrus_bitblt_fgcol(s);
s->cirrus_rop = cirrus_colorexpand_pattern_transp[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
} else {
cirrus_bitblt_fgcol(s);
cirrus_bitblt_bgcol(s);
s->cirrus_rop = cirrus_colorexpand_pattern[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
}
} else {
s->cirrus_rop = cirrus_patternfill[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
}
} else {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_TRANSPARENTCOMP) {
if (s->cirrus_blt_pixelwidth > 2) {
printf("src transparent without colorexpand must be 8bpp or 16bpp\n");
goto bitblt_ignore;
}
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_BACKWARDS) {
s->cirrus_blt_dstpitch = -s->cirrus_blt_dstpitch;
s->cirrus_blt_srcpitch = -s->cirrus_blt_srcpitch;
s->cirrus_rop = cirrus_bkwd_transp_rop[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
} else {
s->cirrus_rop = cirrus_fwd_transp_rop[rop_to_index[blt_rop]][s->cirrus_blt_pixelwidth - 1];
}
} else {
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_BACKWARDS) {
s->cirrus_blt_dstpitch = -s->cirrus_blt_dstpitch;
s->cirrus_blt_srcpitch = -s->cirrus_blt_srcpitch;
s->cirrus_rop = cirrus_bkwd_rop[rop_to_index[blt_rop]];
} else {
s->cirrus_rop = cirrus_fwd_rop[rop_to_index[blt_rop]];
}
}
}
// setup bitblt engine.
if (s->cirrus_blt_mode & CIRRUS_BLTMODE_MEMSYSSRC) {
if (!cirrus_bitblt_cputovideo(s))
goto bitblt_ignore;
} else if (s->cirrus_blt_mode & CIRRUS_BLTMODE_MEMSYSDEST) {
if (!cirrus_bitblt_videotocpu(s))
goto bitblt_ignore;
} else {
if (!cirrus_bitblt_videotovideo(s))
goto bitblt_ignore;
}
}
return;
bitblt_ignore:;
cirrus_bitblt_reset(s);
}
static void cirrus_write_bitblt(CirrusVGAState * s, unsigned reg_value)
{
unsigned old_value;
old_value = s->vga.gr[0x31];
s->vga.gr[0x31] = reg_value;
if (((old_value & CIRRUS_BLT_RESET) != 0) &&
((reg_value & CIRRUS_BLT_RESET) == 0)) {
cirrus_bitblt_reset(s);
} else if (((old_value & CIRRUS_BLT_START) == 0) &&
((reg_value & CIRRUS_BLT_START) != 0)) {
cirrus_bitblt_start(s);
}
}
/***************************************
*
* basic parameters
*
***************************************/
static void cirrus_get_offsets(VGACommonState *s1,
uint32_t *pline_offset,
uint32_t *pstart_addr,
uint32_t *pline_compare)
{
CirrusVGAState * s = container_of(s1, CirrusVGAState, vga);
uint32_t start_addr, line_offset, line_compare;
line_offset = s->vga.cr[0x13]
| ((s->vga.cr[0x1b] & 0x10) << 4);
line_offset <<= 3;
*pline_offset = line_offset;
start_addr = (s->vga.cr[0x0c] << 8)
| s->vga.cr[0x0d]
| ((s->vga.cr[0x1b] & 0x01) << 16)
| ((s->vga.cr[0x1b] & 0x0c) << 15)
| ((s->vga.cr[0x1d] & 0x80) << 12);
*pstart_addr = start_addr;
line_compare = s->vga.cr[0x18] |
((s->vga.cr[0x07] & 0x10) << 4) |
((s->vga.cr[0x09] & 0x40) << 3);
*pline_compare = line_compare;
}
static uint32_t cirrus_get_bpp16_depth(CirrusVGAState * s)
{
uint32_t ret = 16;
switch (s->cirrus_hidden_dac_data & 0xf) {
case 0:
ret = 15;
break; /* Sierra HiColor */
case 1:
ret = 16;
break; /* XGA HiColor */
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: invalid DAC value %x in 16bpp\n",
(s->cirrus_hidden_dac_data & 0xf));
#endif
ret = 15; /* XXX */
break;
}
return ret;
}
static int cirrus_get_bpp(VGACommonState *s1)
{
CirrusVGAState * s = container_of(s1, CirrusVGAState, vga);
uint32_t ret = 8;
if ((s->vga.sr[0x07] & 0x01) != 0) {
/* Cirrus SVGA */
switch (s->vga.sr[0x07] & CIRRUS_SR7_BPP_MASK) {
case CIRRUS_SR7_BPP_8:
ret = 8;
break;
case CIRRUS_SR7_BPP_16_DOUBLEVCLK:
ret = cirrus_get_bpp16_depth(s);
break;
case CIRRUS_SR7_BPP_24:
ret = 24;
break;
case CIRRUS_SR7_BPP_16:
ret = cirrus_get_bpp16_depth(s);
break;
case CIRRUS_SR7_BPP_32:
ret = 32;
break;
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: unknown bpp - sr7=%x\n", s->vga.sr[0x7]);
#endif
ret = 8;
break;
}
} else {
/* VGA */
ret = 0;
}
return ret;
}
static void cirrus_get_resolution(VGACommonState *s, int *pwidth, int *pheight)
{
int width, height;
width = (s->cr[0x01] + 1) * 8;
height = s->cr[0x12] |
((s->cr[0x07] & 0x02) << 7) |
((s->cr[0x07] & 0x40) << 3);
height = (height + 1);
/* interlace support */
if (s->cr[0x1a] & 0x01)
height = height * 2;
*pwidth = width;
*pheight = height;
}
/***************************************
*
* bank memory
*
***************************************/
static void cirrus_update_bank_ptr(CirrusVGAState * s, unsigned bank_index)
{
unsigned offset;
unsigned limit;
if ((s->vga.gr[0x0b] & 0x01) != 0) /* dual bank */
offset = s->vga.gr[0x09 + bank_index];
else /* single bank */
offset = s->vga.gr[0x09];
if ((s->vga.gr[0x0b] & 0x20) != 0)
offset <<= 14;
else
offset <<= 12;
if (s->real_vram_size <= offset)
limit = 0;
else
limit = s->real_vram_size - offset;
if (((s->vga.gr[0x0b] & 0x01) == 0) && (bank_index != 0)) {
if (limit > 0x8000) {
offset += 0x8000;
limit -= 0x8000;
} else {
limit = 0;
}
}
if (limit > 0) {
/* Thinking about changing bank base? First, drop the dirty bitmap information
* on the current location, otherwise we lose this pointer forever */
if (s->vga.lfb_vram_mapped) {
target_phys_addr_t base_addr = isa_mem_base + 0xa0000 + bank_index * 0x8000;
cpu_physical_sync_dirty_bitmap(base_addr, base_addr + 0x8000);
}
s->cirrus_bank_base[bank_index] = offset;
s->cirrus_bank_limit[bank_index] = limit;
} else {
s->cirrus_bank_base[bank_index] = 0;
s->cirrus_bank_limit[bank_index] = 0;
}
}
/***************************************
*
* I/O access between 0x3c4-0x3c5
*
***************************************/
static int cirrus_vga_read_sr(CirrusVGAState * s)
{
switch (s->vga.sr_index) {
case 0x00: // Standard VGA
case 0x01: // Standard VGA
case 0x02: // Standard VGA
case 0x03: // Standard VGA
case 0x04: // Standard VGA
return s->vga.sr[s->vga.sr_index];
case 0x06: // Unlock Cirrus extensions
return s->vga.sr[s->vga.sr_index];
case 0x10:
case 0x30:
case 0x50:
case 0x70: // Graphics Cursor X
case 0x90:
case 0xb0:
case 0xd0:
case 0xf0: // Graphics Cursor X
return s->vga.sr[0x10];
case 0x11:
case 0x31:
case 0x51:
case 0x71: // Graphics Cursor Y
case 0x91:
case 0xb1:
case 0xd1:
case 0xf1: // Graphics Cursor Y
return s->vga.sr[0x11];
case 0x05: // ???
case 0x07: // Extended Sequencer Mode
case 0x08: // EEPROM Control
case 0x09: // Scratch Register 0
case 0x0a: // Scratch Register 1
case 0x0b: // VCLK 0
case 0x0c: // VCLK 1
case 0x0d: // VCLK 2
case 0x0e: // VCLK 3
case 0x0f: // DRAM Control
case 0x12: // Graphics Cursor Attribute
case 0x13: // Graphics Cursor Pattern Address
case 0x14: // Scratch Register 2
case 0x15: // Scratch Register 3
case 0x16: // Performance Tuning Register
case 0x17: // Configuration Readback and Extended Control
case 0x18: // Signature Generator Control
case 0x19: // Signal Generator Result
case 0x1a: // Signal Generator Result
case 0x1b: // VCLK 0 Denominator & Post
case 0x1c: // VCLK 1 Denominator & Post
case 0x1d: // VCLK 2 Denominator & Post
case 0x1e: // VCLK 3 Denominator & Post
case 0x1f: // BIOS Write Enable and MCLK select
#ifdef DEBUG_CIRRUS
printf("cirrus: handled inport sr_index %02x\n", s->vga.sr_index);
#endif
return s->vga.sr[s->vga.sr_index];
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: inport sr_index %02x\n", s->vga.sr_index);
#endif
return 0xff;
break;
}
}
static void cirrus_vga_write_sr(CirrusVGAState * s, uint32_t val)
{
switch (s->vga.sr_index) {
case 0x00: // Standard VGA
case 0x01: // Standard VGA
case 0x02: // Standard VGA
case 0x03: // Standard VGA
case 0x04: // Standard VGA
s->vga.sr[s->vga.sr_index] = val & sr_mask[s->vga.sr_index];
if (s->vga.sr_index == 1)
s->vga.update_retrace_info(&s->vga);
break;
case 0x06: // Unlock Cirrus extensions
val &= 0x17;
if (val == 0x12) {
s->vga.sr[s->vga.sr_index] = 0x12;
} else {
s->vga.sr[s->vga.sr_index] = 0x0f;
}
break;
case 0x10:
case 0x30:
case 0x50:
case 0x70: // Graphics Cursor X
case 0x90:
case 0xb0:
case 0xd0:
case 0xf0: // Graphics Cursor X
s->vga.sr[0x10] = val;
s->hw_cursor_x = (val << 3) | (s->vga.sr_index >> 5);
break;
case 0x11:
case 0x31:
case 0x51:
case 0x71: // Graphics Cursor Y
case 0x91:
case 0xb1:
case 0xd1:
case 0xf1: // Graphics Cursor Y
s->vga.sr[0x11] = val;
s->hw_cursor_y = (val << 3) | (s->vga.sr_index >> 5);
break;
case 0x07: // Extended Sequencer Mode
cirrus_update_memory_access(s);
case 0x08: // EEPROM Control
case 0x09: // Scratch Register 0
case 0x0a: // Scratch Register 1
case 0x0b: // VCLK 0
case 0x0c: // VCLK 1
case 0x0d: // VCLK 2
case 0x0e: // VCLK 3
case 0x0f: // DRAM Control
case 0x12: // Graphics Cursor Attribute
case 0x13: // Graphics Cursor Pattern Address
case 0x14: // Scratch Register 2
case 0x15: // Scratch Register 3
case 0x16: // Performance Tuning Register
case 0x18: // Signature Generator Control
case 0x19: // Signature Generator Result
case 0x1a: // Signature Generator Result
case 0x1b: // VCLK 0 Denominator & Post
case 0x1c: // VCLK 1 Denominator & Post
case 0x1d: // VCLK 2 Denominator & Post
case 0x1e: // VCLK 3 Denominator & Post
case 0x1f: // BIOS Write Enable and MCLK select
s->vga.sr[s->vga.sr_index] = val;
#ifdef DEBUG_CIRRUS
printf("cirrus: handled outport sr_index %02x, sr_value %02x\n",
s->vga.sr_index, val);
#endif
break;
case 0x17: // Configuration Readback and Extended Control
s->vga.sr[s->vga.sr_index] = (s->vga.sr[s->vga.sr_index] & 0x38)
| (val & 0xc7);
cirrus_update_memory_access(s);
break;
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: outport sr_index %02x, sr_value %02x\n",
s->vga.sr_index, val);
#endif
break;
}
}
/***************************************
*
* I/O access at 0x3c6
*
***************************************/
static int cirrus_read_hidden_dac(CirrusVGAState * s)
{
if (++s->cirrus_hidden_dac_lockindex == 5) {
s->cirrus_hidden_dac_lockindex = 0;
return s->cirrus_hidden_dac_data;
}
return 0xff;
}
static void cirrus_write_hidden_dac(CirrusVGAState * s, int reg_value)
{
if (s->cirrus_hidden_dac_lockindex == 4) {
s->cirrus_hidden_dac_data = reg_value;
#if defined(DEBUG_CIRRUS)
printf("cirrus: outport hidden DAC, value %02x\n", reg_value);
#endif
}
s->cirrus_hidden_dac_lockindex = 0;
}
/***************************************
*
* I/O access at 0x3c9
*
***************************************/
static int cirrus_vga_read_palette(CirrusVGAState * s)
{
int val;
if ((s->vga.sr[0x12] & CIRRUS_CURSOR_HIDDENPEL)) {
val = s->cirrus_hidden_palette[(s->vga.dac_read_index & 0x0f) * 3 +
s->vga.dac_sub_index];
} else {
val = s->vga.palette[s->vga.dac_read_index * 3 + s->vga.dac_sub_index];
}
if (++s->vga.dac_sub_index == 3) {
s->vga.dac_sub_index = 0;
s->vga.dac_read_index++;
}
return val;
}
static void cirrus_vga_write_palette(CirrusVGAState * s, int reg_value)
{
s->vga.dac_cache[s->vga.dac_sub_index] = reg_value;
if (++s->vga.dac_sub_index == 3) {
if ((s->vga.sr[0x12] & CIRRUS_CURSOR_HIDDENPEL)) {
memcpy(&s->cirrus_hidden_palette[(s->vga.dac_write_index & 0x0f) * 3],
s->vga.dac_cache, 3);
} else {
memcpy(&s->vga.palette[s->vga.dac_write_index * 3], s->vga.dac_cache, 3);
}
/* XXX update cursor */
s->vga.dac_sub_index = 0;
s->vga.dac_write_index++;
}
}
/***************************************
*
* I/O access between 0x3ce-0x3cf
*
***************************************/
static int cirrus_vga_read_gr(CirrusVGAState * s, unsigned reg_index)
{
switch (reg_index) {
case 0x00: // Standard VGA, BGCOLOR 0x000000ff
return s->cirrus_shadow_gr0;
case 0x01: // Standard VGA, FGCOLOR 0x000000ff
return s->cirrus_shadow_gr1;
case 0x02: // Standard VGA
case 0x03: // Standard VGA
case 0x04: // Standard VGA
case 0x06: // Standard VGA
case 0x07: // Standard VGA
case 0x08: // Standard VGA
return s->vga.gr[s->vga.gr_index];
case 0x05: // Standard VGA, Cirrus extended mode
default:
break;
}
if (reg_index < 0x3a) {
return s->vga.gr[reg_index];
} else {
#ifdef DEBUG_CIRRUS
printf("cirrus: inport gr_index %02x\n", reg_index);
#endif
return 0xff;
}
}
static void
cirrus_vga_write_gr(CirrusVGAState * s, unsigned reg_index, int reg_value)
{
#if defined(DEBUG_BITBLT) && 0
printf("gr%02x: %02x\n", reg_index, reg_value);
#endif
switch (reg_index) {
case 0x00: // Standard VGA, BGCOLOR 0x000000ff
s->vga.gr[reg_index] = reg_value & gr_mask[reg_index];
s->cirrus_shadow_gr0 = reg_value;
break;
case 0x01: // Standard VGA, FGCOLOR 0x000000ff
s->vga.gr[reg_index] = reg_value & gr_mask[reg_index];
s->cirrus_shadow_gr1 = reg_value;
break;
case 0x02: // Standard VGA
case 0x03: // Standard VGA
case 0x04: // Standard VGA
case 0x06: // Standard VGA
case 0x07: // Standard VGA
case 0x08: // Standard VGA
s->vga.gr[reg_index] = reg_value & gr_mask[reg_index];
break;
case 0x05: // Standard VGA, Cirrus extended mode
s->vga.gr[reg_index] = reg_value & 0x7f;
cirrus_update_memory_access(s);
break;
case 0x09: // bank offset #0
case 0x0A: // bank offset #1
s->vga.gr[reg_index] = reg_value;
cirrus_update_bank_ptr(s, 0);
cirrus_update_bank_ptr(s, 1);
cirrus_update_memory_access(s);
break;
case 0x0B:
s->vga.gr[reg_index] = reg_value;
cirrus_update_bank_ptr(s, 0);
cirrus_update_bank_ptr(s, 1);
cirrus_update_memory_access(s);
break;
case 0x10: // BGCOLOR 0x0000ff00
case 0x11: // FGCOLOR 0x0000ff00
case 0x12: // BGCOLOR 0x00ff0000
case 0x13: // FGCOLOR 0x00ff0000
case 0x14: // BGCOLOR 0xff000000
case 0x15: // FGCOLOR 0xff000000
case 0x20: // BLT WIDTH 0x0000ff
case 0x22: // BLT HEIGHT 0x0000ff
case 0x24: // BLT DEST PITCH 0x0000ff
case 0x26: // BLT SRC PITCH 0x0000ff
case 0x28: // BLT DEST ADDR 0x0000ff
case 0x29: // BLT DEST ADDR 0x00ff00
case 0x2c: // BLT SRC ADDR 0x0000ff
case 0x2d: // BLT SRC ADDR 0x00ff00
case 0x2f: // BLT WRITEMASK
case 0x30: // BLT MODE
case 0x32: // RASTER OP
case 0x33: // BLT MODEEXT
case 0x34: // BLT TRANSPARENT COLOR 0x00ff
case 0x35: // BLT TRANSPARENT COLOR 0xff00
case 0x38: // BLT TRANSPARENT COLOR MASK 0x00ff
case 0x39: // BLT TRANSPARENT COLOR MASK 0xff00
s->vga.gr[reg_index] = reg_value;
break;
case 0x21: // BLT WIDTH 0x001f00
case 0x23: // BLT HEIGHT 0x001f00
case 0x25: // BLT DEST PITCH 0x001f00
case 0x27: // BLT SRC PITCH 0x001f00
s->vga.gr[reg_index] = reg_value & 0x1f;
break;
case 0x2a: // BLT DEST ADDR 0x3f0000
s->vga.gr[reg_index] = reg_value & 0x3f;
/* if auto start mode, starts bit blt now */
if (s->vga.gr[0x31] & CIRRUS_BLT_AUTOSTART) {
cirrus_bitblt_start(s);
}
break;
case 0x2e: // BLT SRC ADDR 0x3f0000
s->vga.gr[reg_index] = reg_value & 0x3f;
break;
case 0x31: // BLT STATUS/START
cirrus_write_bitblt(s, reg_value);
break;
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: outport gr_index %02x, gr_value %02x\n", reg_index,
reg_value);
#endif
break;
}
}
/***************************************
*
* I/O access between 0x3d4-0x3d5
*
***************************************/
static int cirrus_vga_read_cr(CirrusVGAState * s, unsigned reg_index)
{
switch (reg_index) {
case 0x00: // Standard VGA
case 0x01: // Standard VGA
case 0x02: // Standard VGA
case 0x03: // Standard VGA
case 0x04: // Standard VGA
case 0x05: // Standard VGA
case 0x06: // Standard VGA
case 0x07: // Standard VGA
case 0x08: // Standard VGA
case 0x09: // Standard VGA
case 0x0a: // Standard VGA
case 0x0b: // Standard VGA
case 0x0c: // Standard VGA
case 0x0d: // Standard VGA
case 0x0e: // Standard VGA
case 0x0f: // Standard VGA
case 0x10: // Standard VGA
case 0x11: // Standard VGA
case 0x12: // Standard VGA
case 0x13: // Standard VGA
case 0x14: // Standard VGA
case 0x15: // Standard VGA
case 0x16: // Standard VGA
case 0x17: // Standard VGA
case 0x18: // Standard VGA
return s->vga.cr[s->vga.cr_index];
case 0x24: // Attribute Controller Toggle Readback (R)
return (s->vga.ar_flip_flop << 7);
case 0x19: // Interlace End
case 0x1a: // Miscellaneous Control
case 0x1b: // Extended Display Control
case 0x1c: // Sync Adjust and Genlock
case 0x1d: // Overlay Extended Control
case 0x22: // Graphics Data Latches Readback (R)
case 0x25: // Part Status
case 0x27: // Part ID (R)
return s->vga.cr[s->vga.cr_index];
case 0x26: // Attribute Controller Index Readback (R)
return s->vga.ar_index & 0x3f;
break;
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: inport cr_index %02x\n", reg_index);
#endif
return 0xff;
}
}
static void cirrus_vga_write_cr(CirrusVGAState * s, int reg_value)
{
switch (s->vga.cr_index) {
case 0x00: // Standard VGA
case 0x01: // Standard VGA
case 0x02: // Standard VGA
case 0x03: // Standard VGA
case 0x04: // Standard VGA
case 0x05: // Standard VGA
case 0x06: // Standard VGA
case 0x07: // Standard VGA
case 0x08: // Standard VGA
case 0x09: // Standard VGA
case 0x0a: // Standard VGA
case 0x0b: // Standard VGA
case 0x0c: // Standard VGA
case 0x0d: // Standard VGA
case 0x0e: // Standard VGA
case 0x0f: // Standard VGA
case 0x10: // Standard VGA
case 0x11: // Standard VGA
case 0x12: // Standard VGA
case 0x13: // Standard VGA
case 0x14: // Standard VGA
case 0x15: // Standard VGA
case 0x16: // Standard VGA
case 0x17: // Standard VGA
case 0x18: // Standard VGA
/* handle CR0-7 protection */
if ((s->vga.cr[0x11] & 0x80) && s->vga.cr_index <= 7) {
/* can always write bit 4 of CR7 */
if (s->vga.cr_index == 7)
s->vga.cr[7] = (s->vga.cr[7] & ~0x10) | (reg_value & 0x10);
return;
}
s->vga.cr[s->vga.cr_index] = reg_value;
switch(s->vga.cr_index) {
case 0x00:
case 0x04:
case 0x05:
case 0x06:
case 0x07:
case 0x11:
case 0x17:
s->vga.update_retrace_info(&s->vga);
break;
}
break;
case 0x19: // Interlace End
case 0x1a: // Miscellaneous Control
case 0x1b: // Extended Display Control
case 0x1c: // Sync Adjust and Genlock
case 0x1d: // Overlay Extended Control
s->vga.cr[s->vga.cr_index] = reg_value;
#ifdef DEBUG_CIRRUS
printf("cirrus: handled outport cr_index %02x, cr_value %02x\n",
s->vga.cr_index, reg_value);
#endif
break;
case 0x22: // Graphics Data Latches Readback (R)
case 0x24: // Attribute Controller Toggle Readback (R)
case 0x26: // Attribute Controller Index Readback (R)
case 0x27: // Part ID (R)
break;
case 0x25: // Part Status
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: outport cr_index %02x, cr_value %02x\n",
s->vga.cr_index, reg_value);
#endif
break;
}
}
/***************************************
*
* memory-mapped I/O (bitblt)
*
***************************************/
static uint8_t cirrus_mmio_blt_read(CirrusVGAState * s, unsigned address)
{
int value = 0xff;
switch (address) {
case (CIRRUS_MMIO_BLTBGCOLOR + 0):
value = cirrus_vga_read_gr(s, 0x00);
break;
case (CIRRUS_MMIO_BLTBGCOLOR + 1):
value = cirrus_vga_read_gr(s, 0x10);
break;
case (CIRRUS_MMIO_BLTBGCOLOR + 2):
value = cirrus_vga_read_gr(s, 0x12);
break;
case (CIRRUS_MMIO_BLTBGCOLOR + 3):
value = cirrus_vga_read_gr(s, 0x14);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 0):
value = cirrus_vga_read_gr(s, 0x01);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 1):
value = cirrus_vga_read_gr(s, 0x11);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 2):
value = cirrus_vga_read_gr(s, 0x13);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 3):
value = cirrus_vga_read_gr(s, 0x15);
break;
case (CIRRUS_MMIO_BLTWIDTH + 0):
value = cirrus_vga_read_gr(s, 0x20);
break;
case (CIRRUS_MMIO_BLTWIDTH + 1):
value = cirrus_vga_read_gr(s, 0x21);
break;
case (CIRRUS_MMIO_BLTHEIGHT + 0):
value = cirrus_vga_read_gr(s, 0x22);
break;
case (CIRRUS_MMIO_BLTHEIGHT + 1):
value = cirrus_vga_read_gr(s, 0x23);
break;
case (CIRRUS_MMIO_BLTDESTPITCH + 0):
value = cirrus_vga_read_gr(s, 0x24);
break;
case (CIRRUS_MMIO_BLTDESTPITCH + 1):
value = cirrus_vga_read_gr(s, 0x25);
break;
case (CIRRUS_MMIO_BLTSRCPITCH + 0):
value = cirrus_vga_read_gr(s, 0x26);
break;
case (CIRRUS_MMIO_BLTSRCPITCH + 1):
value = cirrus_vga_read_gr(s, 0x27);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 0):
value = cirrus_vga_read_gr(s, 0x28);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 1):
value = cirrus_vga_read_gr(s, 0x29);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 2):
value = cirrus_vga_read_gr(s, 0x2a);
break;
case (CIRRUS_MMIO_BLTSRCADDR + 0):
value = cirrus_vga_read_gr(s, 0x2c);
break;
case (CIRRUS_MMIO_BLTSRCADDR + 1):
value = cirrus_vga_read_gr(s, 0x2d);
break;
case (CIRRUS_MMIO_BLTSRCADDR + 2):
value = cirrus_vga_read_gr(s, 0x2e);
break;
case CIRRUS_MMIO_BLTWRITEMASK:
value = cirrus_vga_read_gr(s, 0x2f);
break;
case CIRRUS_MMIO_BLTMODE:
value = cirrus_vga_read_gr(s, 0x30);
break;
case CIRRUS_MMIO_BLTROP:
value = cirrus_vga_read_gr(s, 0x32);
break;
case CIRRUS_MMIO_BLTMODEEXT:
value = cirrus_vga_read_gr(s, 0x33);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 0):
value = cirrus_vga_read_gr(s, 0x34);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 1):
value = cirrus_vga_read_gr(s, 0x35);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 0):
value = cirrus_vga_read_gr(s, 0x38);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 1):
value = cirrus_vga_read_gr(s, 0x39);
break;
case CIRRUS_MMIO_BLTSTATUS:
value = cirrus_vga_read_gr(s, 0x31);
break;
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: mmio read - address 0x%04x\n", address);
#endif
break;
}
return (uint8_t) value;
}
static void cirrus_mmio_blt_write(CirrusVGAState * s, unsigned address,
uint8_t value)
{
switch (address) {
case (CIRRUS_MMIO_BLTBGCOLOR + 0):
cirrus_vga_write_gr(s, 0x00, value);
break;
case (CIRRUS_MMIO_BLTBGCOLOR + 1):
cirrus_vga_write_gr(s, 0x10, value);
break;
case (CIRRUS_MMIO_BLTBGCOLOR + 2):
cirrus_vga_write_gr(s, 0x12, value);
break;
case (CIRRUS_MMIO_BLTBGCOLOR + 3):
cirrus_vga_write_gr(s, 0x14, value);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 0):
cirrus_vga_write_gr(s, 0x01, value);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 1):
cirrus_vga_write_gr(s, 0x11, value);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 2):
cirrus_vga_write_gr(s, 0x13, value);
break;
case (CIRRUS_MMIO_BLTFGCOLOR + 3):
cirrus_vga_write_gr(s, 0x15, value);
break;
case (CIRRUS_MMIO_BLTWIDTH + 0):
cirrus_vga_write_gr(s, 0x20, value);
break;
case (CIRRUS_MMIO_BLTWIDTH + 1):
cirrus_vga_write_gr(s, 0x21, value);
break;
case (CIRRUS_MMIO_BLTHEIGHT + 0):
cirrus_vga_write_gr(s, 0x22, value);
break;
case (CIRRUS_MMIO_BLTHEIGHT + 1):
cirrus_vga_write_gr(s, 0x23, value);
break;
case (CIRRUS_MMIO_BLTDESTPITCH + 0):
cirrus_vga_write_gr(s, 0x24, value);
break;
case (CIRRUS_MMIO_BLTDESTPITCH + 1):
cirrus_vga_write_gr(s, 0x25, value);
break;
case (CIRRUS_MMIO_BLTSRCPITCH + 0):
cirrus_vga_write_gr(s, 0x26, value);
break;
case (CIRRUS_MMIO_BLTSRCPITCH + 1):
cirrus_vga_write_gr(s, 0x27, value);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 0):
cirrus_vga_write_gr(s, 0x28, value);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 1):
cirrus_vga_write_gr(s, 0x29, value);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 2):
cirrus_vga_write_gr(s, 0x2a, value);
break;
case (CIRRUS_MMIO_BLTDESTADDR + 3):
/* ignored */
break;
case (CIRRUS_MMIO_BLTSRCADDR + 0):
cirrus_vga_write_gr(s, 0x2c, value);
break;
case (CIRRUS_MMIO_BLTSRCADDR + 1):
cirrus_vga_write_gr(s, 0x2d, value);
break;
case (CIRRUS_MMIO_BLTSRCADDR + 2):
cirrus_vga_write_gr(s, 0x2e, value);
break;
case CIRRUS_MMIO_BLTWRITEMASK:
cirrus_vga_write_gr(s, 0x2f, value);
break;
case CIRRUS_MMIO_BLTMODE:
cirrus_vga_write_gr(s, 0x30, value);
break;
case CIRRUS_MMIO_BLTROP:
cirrus_vga_write_gr(s, 0x32, value);
break;
case CIRRUS_MMIO_BLTMODEEXT:
cirrus_vga_write_gr(s, 0x33, value);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 0):
cirrus_vga_write_gr(s, 0x34, value);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLOR + 1):
cirrus_vga_write_gr(s, 0x35, value);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 0):
cirrus_vga_write_gr(s, 0x38, value);
break;
case (CIRRUS_MMIO_BLTTRANSPARENTCOLORMASK + 1):
cirrus_vga_write_gr(s, 0x39, value);
break;
case CIRRUS_MMIO_BLTSTATUS:
cirrus_vga_write_gr(s, 0x31, value);
break;
default:
#ifdef DEBUG_CIRRUS
printf("cirrus: mmio write - addr 0x%04x val 0x%02x (ignored)\n",
address, value);
#endif
break;
}
}
/***************************************
*
* write mode 4/5
*
* assume TARGET_PAGE_SIZE >= 16
*
***************************************/
static void cirrus_mem_writeb_mode4and5_8bpp(CirrusVGAState * s,
unsigned mode,
unsigned offset,
uint32_t mem_value)
{
int x;
unsigned val = mem_value;
uint8_t *dst;
dst = s->vga.vram_ptr + (offset &= s->cirrus_addr_mask);
for (x = 0; x < 8; x++) {
if (val & 0x80) {
*dst = s->cirrus_shadow_gr1;
} else if (mode == 5) {
*dst = s->cirrus_shadow_gr0;
}
val <<= 1;
dst++;
}
cpu_physical_memory_set_dirty(s->vga.vram_offset + offset);
cpu_physical_memory_set_dirty(s->vga.vram_offset + offset + 7);
}
static void cirrus_mem_writeb_mode4and5_16bpp(CirrusVGAState * s,
unsigned mode,
unsigned offset,
uint32_t mem_value)
{
int x;
unsigned val = mem_value;
uint8_t *dst;
dst = s->vga.vram_ptr + (offset &= s->cirrus_addr_mask);
for (x = 0; x < 8; x++) {
if (val & 0x80) {
*dst = s->cirrus_shadow_gr1;
*(dst + 1) = s->vga.gr[0x11];
} else if (mode == 5) {
*dst = s->cirrus_shadow_gr0;
*(dst + 1) = s->vga.gr[0x10];
}
val <<= 1;
dst += 2;
}
cpu_physical_memory_set_dirty(s->vga.vram_offset + offset);
cpu_physical_memory_set_dirty(s->vga.vram_offset + offset + 15);
}
/***************************************
*
* memory access between 0xa0000-0xbffff
*
***************************************/
static uint32_t cirrus_vga_mem_readb(void *opaque, target_phys_addr_t addr)
{
CirrusVGAState *s = opaque;
unsigned bank_index;
unsigned bank_offset;
uint32_t val;
if ((s->vga.sr[0x07] & 0x01) == 0) {
return vga_mem_readb(s, addr);
}
addr &= 0x1ffff;
if (addr < 0x10000) {
/* XXX handle bitblt */
/* video memory */
bank_index = addr >> 15;
bank_offset = addr & 0x7fff;
if (bank_offset < s->cirrus_bank_limit[bank_index]) {
bank_offset += s->cirrus_bank_base[bank_index];
if ((s->vga.gr[0x0B] & 0x14) == 0x14) {
bank_offset <<= 4;
} else if (s->vga.gr[0x0B] & 0x02) {
bank_offset <<= 3;
}
bank_offset &= s->cirrus_addr_mask;
val = *(s->vga.vram_ptr + bank_offset);
} else
val = 0xff;
} else if (addr >= 0x18000 && addr < 0x18100) {
/* memory-mapped I/O */
val = 0xff;
if ((s->vga.sr[0x17] & 0x44) == 0x04) {
val = cirrus_mmio_blt_read(s, addr & 0xff);
}
} else {
val = 0xff;
#ifdef DEBUG_CIRRUS
printf("cirrus: mem_readb " TARGET_FMT_plx "\n", addr);
#endif
}
return val;
}
static uint32_t cirrus_vga_mem_readw(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_vga_mem_readb(opaque, addr) << 8;
v |= cirrus_vga_mem_readb(opaque, addr + 1);
#else
v = cirrus_vga_mem_readb(opaque, addr);
v |= cirrus_vga_mem_readb(opaque, addr + 1) << 8;
#endif
return v;
}
static uint32_t cirrus_vga_mem_readl(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_vga_mem_readb(opaque, addr) << 24;
v |= cirrus_vga_mem_readb(opaque, addr + 1) << 16;
v |= cirrus_vga_mem_readb(opaque, addr + 2) << 8;
v |= cirrus_vga_mem_readb(opaque, addr + 3);
#else
v = cirrus_vga_mem_readb(opaque, addr);
v |= cirrus_vga_mem_readb(opaque, addr + 1) << 8;
v |= cirrus_vga_mem_readb(opaque, addr + 2) << 16;
v |= cirrus_vga_mem_readb(opaque, addr + 3) << 24;
#endif
return v;
}
static void cirrus_vga_mem_writeb(void *opaque, target_phys_addr_t addr,
uint32_t mem_value)
{
CirrusVGAState *s = opaque;
unsigned bank_index;
unsigned bank_offset;
unsigned mode;
if ((s->vga.sr[0x07] & 0x01) == 0) {
vga_mem_writeb(s, addr, mem_value);
return;
}
addr &= 0x1ffff;
if (addr < 0x10000) {
if (s->cirrus_srcptr != s->cirrus_srcptr_end) {
/* bitblt */
*s->cirrus_srcptr++ = (uint8_t) mem_value;
if (s->cirrus_srcptr >= s->cirrus_srcptr_end) {
cirrus_bitblt_cputovideo_next(s);
}
} else {
/* video memory */
bank_index = addr >> 15;
bank_offset = addr & 0x7fff;
if (bank_offset < s->cirrus_bank_limit[bank_index]) {
bank_offset += s->cirrus_bank_base[bank_index];
if ((s->vga.gr[0x0B] & 0x14) == 0x14) {
bank_offset <<= 4;
} else if (s->vga.gr[0x0B] & 0x02) {
bank_offset <<= 3;
}
bank_offset &= s->cirrus_addr_mask;
mode = s->vga.gr[0x05] & 0x7;
if (mode < 4 || mode > 5 || ((s->vga.gr[0x0B] & 0x4) == 0)) {
*(s->vga.vram_ptr + bank_offset) = mem_value;
cpu_physical_memory_set_dirty(s->vga.vram_offset +
bank_offset);
} else {
if ((s->vga.gr[0x0B] & 0x14) != 0x14) {
cirrus_mem_writeb_mode4and5_8bpp(s, mode,
bank_offset,
mem_value);
} else {
cirrus_mem_writeb_mode4and5_16bpp(s, mode,
bank_offset,
mem_value);
}
}
}
}
} else if (addr >= 0x18000 && addr < 0x18100) {
/* memory-mapped I/O */
if ((s->vga.sr[0x17] & 0x44) == 0x04) {
cirrus_mmio_blt_write(s, addr & 0xff, mem_value);
}
} else {
#ifdef DEBUG_CIRRUS
printf("cirrus: mem_writeb " TARGET_FMT_plx " value %02x\n", addr,
mem_value);
#endif
}
}
static void cirrus_vga_mem_writew(void *opaque, target_phys_addr_t addr, uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_vga_mem_writeb(opaque, addr, (val >> 8) & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 1, val & 0xff);
#else
cirrus_vga_mem_writeb(opaque, addr, val & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 1, (val >> 8) & 0xff);
#endif
}
static void cirrus_vga_mem_writel(void *opaque, target_phys_addr_t addr, uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_vga_mem_writeb(opaque, addr, (val >> 24) & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 1, (val >> 16) & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 2, (val >> 8) & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 3, val & 0xff);
#else
cirrus_vga_mem_writeb(opaque, addr, val & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 1, (val >> 8) & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 2, (val >> 16) & 0xff);
cirrus_vga_mem_writeb(opaque, addr + 3, (val >> 24) & 0xff);
#endif
}
static CPUReadMemoryFunc * const cirrus_vga_mem_read[3] = {
cirrus_vga_mem_readb,
cirrus_vga_mem_readw,
cirrus_vga_mem_readl,
};
static CPUWriteMemoryFunc * const cirrus_vga_mem_write[3] = {
cirrus_vga_mem_writeb,
cirrus_vga_mem_writew,
cirrus_vga_mem_writel,
};
/***************************************
*
* hardware cursor
*
***************************************/
static inline void invalidate_cursor1(CirrusVGAState *s)
{
if (s->last_hw_cursor_size) {
vga_invalidate_scanlines(&s->vga,
s->last_hw_cursor_y + s->last_hw_cursor_y_start,
s->last_hw_cursor_y + s->last_hw_cursor_y_end);
}
}
static inline void cirrus_cursor_compute_yrange(CirrusVGAState *s)
{
const uint8_t *src;
uint32_t content;
int y, y_min, y_max;
src = s->vga.vram_ptr + s->real_vram_size - 16 * 1024;
if (s->vga.sr[0x12] & CIRRUS_CURSOR_LARGE) {
src += (s->vga.sr[0x13] & 0x3c) * 256;
y_min = 64;
y_max = -1;
for(y = 0; y < 64; y++) {
content = ((uint32_t *)src)[0] |
((uint32_t *)src)[1] |
((uint32_t *)src)[2] |
((uint32_t *)src)[3];
if (content) {
if (y < y_min)
y_min = y;
if (y > y_max)
y_max = y;
}
src += 16;
}
} else {
src += (s->vga.sr[0x13] & 0x3f) * 256;
y_min = 32;
y_max = -1;
for(y = 0; y < 32; y++) {
content = ((uint32_t *)src)[0] |
((uint32_t *)(src + 128))[0];
if (content) {
if (y < y_min)
y_min = y;
if (y > y_max)
y_max = y;
}
src += 4;
}
}
if (y_min > y_max) {
s->last_hw_cursor_y_start = 0;
s->last_hw_cursor_y_end = 0;
} else {
s->last_hw_cursor_y_start = y_min;
s->last_hw_cursor_y_end = y_max + 1;
}
}
/* NOTE: we do not currently handle the cursor bitmap change, so we
update the cursor only if it moves. */
static void cirrus_cursor_invalidate(VGACommonState *s1)
{
CirrusVGAState *s = container_of(s1, CirrusVGAState, vga);
int size;
if (!(s->vga.sr[0x12] & CIRRUS_CURSOR_SHOW)) {
size = 0;
} else {
if (s->vga.sr[0x12] & CIRRUS_CURSOR_LARGE)
size = 64;
else
size = 32;
}
/* invalidate last cursor and new cursor if any change */
if (s->last_hw_cursor_size != size ||
s->last_hw_cursor_x != s->hw_cursor_x ||
s->last_hw_cursor_y != s->hw_cursor_y) {
invalidate_cursor1(s);
s->last_hw_cursor_size = size;
s->last_hw_cursor_x = s->hw_cursor_x;
s->last_hw_cursor_y = s->hw_cursor_y;
/* compute the real cursor min and max y */
cirrus_cursor_compute_yrange(s);
invalidate_cursor1(s);
}
}
static void cirrus_cursor_draw_line(VGACommonState *s1, uint8_t *d1, int scr_y)
{
CirrusVGAState *s = container_of(s1, CirrusVGAState, vga);
int w, h, bpp, x1, x2, poffset;
unsigned int color0, color1;
const uint8_t *palette, *src;
uint32_t content;
if (!(s->vga.sr[0x12] & CIRRUS_CURSOR_SHOW))
return;
/* fast test to see if the cursor intersects with the scan line */
if (s->vga.sr[0x12] & CIRRUS_CURSOR_LARGE) {
h = 64;
} else {
h = 32;
}
if (scr_y < s->hw_cursor_y ||
scr_y >= (s->hw_cursor_y + h))
return;
src = s->vga.vram_ptr + s->real_vram_size - 16 * 1024;
if (s->vga.sr[0x12] & CIRRUS_CURSOR_LARGE) {
src += (s->vga.sr[0x13] & 0x3c) * 256;
src += (scr_y - s->hw_cursor_y) * 16;
poffset = 8;
content = ((uint32_t *)src)[0] |
((uint32_t *)src)[1] |
((uint32_t *)src)[2] |
((uint32_t *)src)[3];
} else {
src += (s->vga.sr[0x13] & 0x3f) * 256;
src += (scr_y - s->hw_cursor_y) * 4;
poffset = 128;
content = ((uint32_t *)src)[0] |
((uint32_t *)(src + 128))[0];
}
/* if nothing to draw, no need to continue */
if (!content)
return;
w = h;
x1 = s->hw_cursor_x;
if (x1 >= s->vga.last_scr_width)
return;
x2 = s->hw_cursor_x + w;
if (x2 > s->vga.last_scr_width)
x2 = s->vga.last_scr_width;
w = x2 - x1;
palette = s->cirrus_hidden_palette;
color0 = s->vga.rgb_to_pixel(c6_to_8(palette[0x0 * 3]),
c6_to_8(palette[0x0 * 3 + 1]),
c6_to_8(palette[0x0 * 3 + 2]));
color1 = s->vga.rgb_to_pixel(c6_to_8(palette[0xf * 3]),
c6_to_8(palette[0xf * 3 + 1]),
c6_to_8(palette[0xf * 3 + 2]));
bpp = ((ds_get_bits_per_pixel(s->vga.ds) + 7) >> 3);
d1 += x1 * bpp;
switch(ds_get_bits_per_pixel(s->vga.ds)) {
default:
break;
case 8:
vga_draw_cursor_line_8(d1, src, poffset, w, color0, color1, 0xff);
break;
case 15:
vga_draw_cursor_line_16(d1, src, poffset, w, color0, color1, 0x7fff);
break;
case 16:
vga_draw_cursor_line_16(d1, src, poffset, w, color0, color1, 0xffff);
break;
case 32:
vga_draw_cursor_line_32(d1, src, poffset, w, color0, color1, 0xffffff);
break;
}
}
/***************************************
*
* LFB memory access
*
***************************************/
static uint32_t cirrus_linear_readb(void *opaque, target_phys_addr_t addr)
{
CirrusVGAState *s = opaque;
uint32_t ret;
addr &= s->cirrus_addr_mask;
if (((s->vga.sr[0x17] & 0x44) == 0x44) &&
((addr & s->linear_mmio_mask) == s->linear_mmio_mask)) {
/* memory-mapped I/O */
ret = cirrus_mmio_blt_read(s, addr & 0xff);
} else if (0) {
/* XXX handle bitblt */
ret = 0xff;
} else {
/* video memory */
if ((s->vga.gr[0x0B] & 0x14) == 0x14) {
addr <<= 4;
} else if (s->vga.gr[0x0B] & 0x02) {
addr <<= 3;
}
addr &= s->cirrus_addr_mask;
ret = *(s->vga.vram_ptr + addr);
}
return ret;
}
static uint32_t cirrus_linear_readw(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_linear_readb(opaque, addr) << 8;
v |= cirrus_linear_readb(opaque, addr + 1);
#else
v = cirrus_linear_readb(opaque, addr);
v |= cirrus_linear_readb(opaque, addr + 1) << 8;
#endif
return v;
}
static uint32_t cirrus_linear_readl(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_linear_readb(opaque, addr) << 24;
v |= cirrus_linear_readb(opaque, addr + 1) << 16;
v |= cirrus_linear_readb(opaque, addr + 2) << 8;
v |= cirrus_linear_readb(opaque, addr + 3);
#else
v = cirrus_linear_readb(opaque, addr);
v |= cirrus_linear_readb(opaque, addr + 1) << 8;
v |= cirrus_linear_readb(opaque, addr + 2) << 16;
v |= cirrus_linear_readb(opaque, addr + 3) << 24;
#endif
return v;
}
static void cirrus_linear_writeb(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
CirrusVGAState *s = opaque;
unsigned mode;
addr &= s->cirrus_addr_mask;
if (((s->vga.sr[0x17] & 0x44) == 0x44) &&
((addr & s->linear_mmio_mask) == s->linear_mmio_mask)) {
/* memory-mapped I/O */
cirrus_mmio_blt_write(s, addr & 0xff, val);
} else if (s->cirrus_srcptr != s->cirrus_srcptr_end) {
/* bitblt */
*s->cirrus_srcptr++ = (uint8_t) val;
if (s->cirrus_srcptr >= s->cirrus_srcptr_end) {
cirrus_bitblt_cputovideo_next(s);
}
} else {
/* video memory */
if ((s->vga.gr[0x0B] & 0x14) == 0x14) {
addr <<= 4;
} else if (s->vga.gr[0x0B] & 0x02) {
addr <<= 3;
}
addr &= s->cirrus_addr_mask;
mode = s->vga.gr[0x05] & 0x7;
if (mode < 4 || mode > 5 || ((s->vga.gr[0x0B] & 0x4) == 0)) {
*(s->vga.vram_ptr + addr) = (uint8_t) val;
cpu_physical_memory_set_dirty(s->vga.vram_offset + addr);
} else {
if ((s->vga.gr[0x0B] & 0x14) != 0x14) {
cirrus_mem_writeb_mode4and5_8bpp(s, mode, addr, val);
} else {
cirrus_mem_writeb_mode4and5_16bpp(s, mode, addr, val);
}
}
}
}
static void cirrus_linear_writew(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_linear_writeb(opaque, addr, (val >> 8) & 0xff);
cirrus_linear_writeb(opaque, addr + 1, val & 0xff);
#else
cirrus_linear_writeb(opaque, addr, val & 0xff);
cirrus_linear_writeb(opaque, addr + 1, (val >> 8) & 0xff);
#endif
}
static void cirrus_linear_writel(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_linear_writeb(opaque, addr, (val >> 24) & 0xff);
cirrus_linear_writeb(opaque, addr + 1, (val >> 16) & 0xff);
cirrus_linear_writeb(opaque, addr + 2, (val >> 8) & 0xff);
cirrus_linear_writeb(opaque, addr + 3, val & 0xff);
#else
cirrus_linear_writeb(opaque, addr, val & 0xff);
cirrus_linear_writeb(opaque, addr + 1, (val >> 8) & 0xff);
cirrus_linear_writeb(opaque, addr + 2, (val >> 16) & 0xff);
cirrus_linear_writeb(opaque, addr + 3, (val >> 24) & 0xff);
#endif
}
static CPUReadMemoryFunc * const cirrus_linear_read[3] = {
cirrus_linear_readb,
cirrus_linear_readw,
cirrus_linear_readl,
};
static CPUWriteMemoryFunc * const cirrus_linear_write[3] = {
cirrus_linear_writeb,
cirrus_linear_writew,
cirrus_linear_writel,
};
/***************************************
*
* system to screen memory access
*
***************************************/
static uint32_t cirrus_linear_bitblt_readb(void *opaque, target_phys_addr_t addr)
{
uint32_t ret;
/* XXX handle bitblt */
ret = 0xff;
return ret;
}
static uint32_t cirrus_linear_bitblt_readw(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_linear_bitblt_readb(opaque, addr) << 8;
v |= cirrus_linear_bitblt_readb(opaque, addr + 1);
#else
v = cirrus_linear_bitblt_readb(opaque, addr);
v |= cirrus_linear_bitblt_readb(opaque, addr + 1) << 8;
#endif
return v;
}
static uint32_t cirrus_linear_bitblt_readl(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_linear_bitblt_readb(opaque, addr) << 24;
v |= cirrus_linear_bitblt_readb(opaque, addr + 1) << 16;
v |= cirrus_linear_bitblt_readb(opaque, addr + 2) << 8;
v |= cirrus_linear_bitblt_readb(opaque, addr + 3);
#else
v = cirrus_linear_bitblt_readb(opaque, addr);
v |= cirrus_linear_bitblt_readb(opaque, addr + 1) << 8;
v |= cirrus_linear_bitblt_readb(opaque, addr + 2) << 16;
v |= cirrus_linear_bitblt_readb(opaque, addr + 3) << 24;
#endif
return v;
}
static void cirrus_linear_bitblt_writeb(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
CirrusVGAState *s = opaque;
if (s->cirrus_srcptr != s->cirrus_srcptr_end) {
/* bitblt */
*s->cirrus_srcptr++ = (uint8_t) val;
if (s->cirrus_srcptr >= s->cirrus_srcptr_end) {
cirrus_bitblt_cputovideo_next(s);
}
}
}
static void cirrus_linear_bitblt_writew(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_linear_bitblt_writeb(opaque, addr, (val >> 8) & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 1, val & 0xff);
#else
cirrus_linear_bitblt_writeb(opaque, addr, val & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 1, (val >> 8) & 0xff);
#endif
}
static void cirrus_linear_bitblt_writel(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_linear_bitblt_writeb(opaque, addr, (val >> 24) & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 1, (val >> 16) & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 2, (val >> 8) & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 3, val & 0xff);
#else
cirrus_linear_bitblt_writeb(opaque, addr, val & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 1, (val >> 8) & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 2, (val >> 16) & 0xff);
cirrus_linear_bitblt_writeb(opaque, addr + 3, (val >> 24) & 0xff);
#endif
}
static CPUReadMemoryFunc * const cirrus_linear_bitblt_read[3] = {
cirrus_linear_bitblt_readb,
cirrus_linear_bitblt_readw,
cirrus_linear_bitblt_readl,
};
static CPUWriteMemoryFunc * const cirrus_linear_bitblt_write[3] = {
cirrus_linear_bitblt_writeb,
cirrus_linear_bitblt_writew,
cirrus_linear_bitblt_writel,
};
static void map_linear_vram(CirrusVGAState *s)
{
vga_dirty_log_stop(&s->vga);
if (!s->vga.map_addr && s->vga.lfb_addr && s->vga.lfb_end) {
s->vga.map_addr = s->vga.lfb_addr;
s->vga.map_end = s->vga.lfb_end;
cpu_register_physical_memory(s->vga.map_addr, s->vga.map_end - s->vga.map_addr, s->vga.vram_offset);
}
if (!s->vga.map_addr)
return;
#ifndef TARGET_IA64
s->vga.lfb_vram_mapped = 0;
cpu_register_physical_memory(isa_mem_base + 0xa0000, 0x8000,
(s->vga.vram_offset + s->cirrus_bank_base[0]) | IO_MEM_UNASSIGNED);
cpu_register_physical_memory(isa_mem_base + 0xa8000, 0x8000,
(s->vga.vram_offset + s->cirrus_bank_base[1]) | IO_MEM_UNASSIGNED);
if (!(s->cirrus_srcptr != s->cirrus_srcptr_end)
&& !((s->vga.sr[0x07] & 0x01) == 0)
&& !((s->vga.gr[0x0B] & 0x14) == 0x14)
&& !(s->vga.gr[0x0B] & 0x02)) {
vga_dirty_log_stop(&s->vga);
cpu_register_physical_memory(isa_mem_base + 0xa0000, 0x8000,
(s->vga.vram_offset + s->cirrus_bank_base[0]) | IO_MEM_RAM);
cpu_register_physical_memory(isa_mem_base + 0xa8000, 0x8000,
(s->vga.vram_offset + s->cirrus_bank_base[1]) | IO_MEM_RAM);
s->vga.lfb_vram_mapped = 1;
}
else {
cpu_register_physical_memory(isa_mem_base + 0xa0000, 0x20000,
s->vga.vga_io_memory);
}
#endif
vga_dirty_log_start(&s->vga);
}
static void unmap_linear_vram(CirrusVGAState *s)
{
vga_dirty_log_stop(&s->vga);
if (s->vga.map_addr && s->vga.lfb_addr && s->vga.lfb_end) {
s->vga.map_addr = s->vga.map_end = 0;
cpu_register_physical_memory(s->vga.lfb_addr, s->vga.vram_size,
s->cirrus_linear_io_addr);
}
s->vga.lfb_vram_mapped = 0;
cpu_register_physical_memory(isa_mem_base + 0xa0000, 0x20000,
s->vga.vga_io_memory);
vga_dirty_log_start(&s->vga);
}
/* Compute the memory access functions */
static void cirrus_update_memory_access(CirrusVGAState *s)
{
unsigned mode;
if ((s->vga.sr[0x17] & 0x44) == 0x44) {
goto generic_io;
} else if (s->cirrus_srcptr != s->cirrus_srcptr_end) {
goto generic_io;
} else {
if ((s->vga.gr[0x0B] & 0x14) == 0x14) {
goto generic_io;
} else if (s->vga.gr[0x0B] & 0x02) {
goto generic_io;
}
mode = s->vga.gr[0x05] & 0x7;
if (mode < 4 || mode > 5 || ((s->vga.gr[0x0B] & 0x4) == 0)) {
map_linear_vram(s);
} else {
generic_io:
unmap_linear_vram(s);
}
}
}
/* I/O ports */
static uint32_t cirrus_vga_ioport_read(void *opaque, uint32_t addr)
{
CirrusVGAState *c = opaque;
VGACommonState *s = &c->vga;
int val, index;
if (vga_ioport_invalid(s, addr)) {
val = 0xff;
} else {
switch (addr) {
case 0x3c0:
if (s->ar_flip_flop == 0) {
val = s->ar_index;
} else {
val = 0;
}
break;
case 0x3c1:
index = s->ar_index & 0x1f;
if (index < 21)
val = s->ar[index];
else
val = 0;
break;
case 0x3c2:
val = s->st00;
break;
case 0x3c4:
val = s->sr_index;
break;
case 0x3c5:
val = cirrus_vga_read_sr(c);
break;
#ifdef DEBUG_VGA_REG
printf("vga: read SR%x = 0x%02x\n", s->sr_index, val);
#endif
break;
case 0x3c6:
val = cirrus_read_hidden_dac(c);
break;
case 0x3c7:
val = s->dac_state;
break;
case 0x3c8:
val = s->dac_write_index;
c->cirrus_hidden_dac_lockindex = 0;
break;
case 0x3c9:
val = cirrus_vga_read_palette(c);
break;
case 0x3ca:
val = s->fcr;
break;
case 0x3cc:
val = s->msr;
break;
case 0x3ce:
val = s->gr_index;
break;
case 0x3cf:
val = cirrus_vga_read_gr(c, s->gr_index);
#ifdef DEBUG_VGA_REG
printf("vga: read GR%x = 0x%02x\n", s->gr_index, val);
#endif
break;
case 0x3b4:
case 0x3d4:
val = s->cr_index;
break;
case 0x3b5:
case 0x3d5:
val = cirrus_vga_read_cr(c, s->cr_index);
#ifdef DEBUG_VGA_REG
printf("vga: read CR%x = 0x%02x\n", s->cr_index, val);
#endif
break;
case 0x3ba:
case 0x3da:
/* just toggle to fool polling */
val = s->st01 = s->retrace(s);
s->ar_flip_flop = 0;
break;
default:
val = 0x00;
break;
}
}
#if defined(DEBUG_VGA)
printf("VGA: read addr=0x%04x data=0x%02x\n", addr, val);
#endif
return val;
}
static void cirrus_vga_ioport_write(void *opaque, uint32_t addr, uint32_t val)
{
CirrusVGAState *c = opaque;
VGACommonState *s = &c->vga;
int index;
/* check port range access depending on color/monochrome mode */
if (vga_ioport_invalid(s, addr)) {
return;
}
#ifdef DEBUG_VGA
printf("VGA: write addr=0x%04x data=0x%02x\n", addr, val);
#endif
switch (addr) {
case 0x3c0:
if (s->ar_flip_flop == 0) {
val &= 0x3f;
s->ar_index = val;
} else {
index = s->ar_index & 0x1f;
switch (index) {
case 0x00 ... 0x0f:
s->ar[index] = val & 0x3f;
break;
case 0x10:
s->ar[index] = val & ~0x10;
break;
case 0x11:
s->ar[index] = val;
break;
case 0x12:
s->ar[index] = val & ~0xc0;
break;
case 0x13:
s->ar[index] = val & ~0xf0;
break;
case 0x14:
s->ar[index] = val & ~0xf0;
break;
default:
break;
}
}
s->ar_flip_flop ^= 1;
break;
case 0x3c2:
s->msr = val & ~0x10;
s->update_retrace_info(s);
break;
case 0x3c4:
s->sr_index = val;
break;
case 0x3c5:
#ifdef DEBUG_VGA_REG
printf("vga: write SR%x = 0x%02x\n", s->sr_index, val);
#endif
cirrus_vga_write_sr(c, val);
break;
break;
case 0x3c6:
cirrus_write_hidden_dac(c, val);
break;
case 0x3c7:
s->dac_read_index = val;
s->dac_sub_index = 0;
s->dac_state = 3;
break;
case 0x3c8:
s->dac_write_index = val;
s->dac_sub_index = 0;
s->dac_state = 0;
break;
case 0x3c9:
cirrus_vga_write_palette(c, val);
break;
case 0x3ce:
s->gr_index = val;
break;
case 0x3cf:
#ifdef DEBUG_VGA_REG
printf("vga: write GR%x = 0x%02x\n", s->gr_index, val);
#endif
cirrus_vga_write_gr(c, s->gr_index, val);
break;
case 0x3b4:
case 0x3d4:
s->cr_index = val;
break;
case 0x3b5:
case 0x3d5:
#ifdef DEBUG_VGA_REG
printf("vga: write CR%x = 0x%02x\n", s->cr_index, val);
#endif
cirrus_vga_write_cr(c, val);
break;
case 0x3ba:
case 0x3da:
s->fcr = val & 0x10;
break;
}
}
/***************************************
*
* memory-mapped I/O access
*
***************************************/
static uint32_t cirrus_mmio_readb(void *opaque, target_phys_addr_t addr)
{
CirrusVGAState *s = opaque;
addr &= CIRRUS_PNPMMIO_SIZE - 1;
if (addr >= 0x100) {
return cirrus_mmio_blt_read(s, addr - 0x100);
} else {
return cirrus_vga_ioport_read(s, addr + 0x3c0);
}
}
static uint32_t cirrus_mmio_readw(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_mmio_readb(opaque, addr) << 8;
v |= cirrus_mmio_readb(opaque, addr + 1);
#else
v = cirrus_mmio_readb(opaque, addr);
v |= cirrus_mmio_readb(opaque, addr + 1) << 8;
#endif
return v;
}
static uint32_t cirrus_mmio_readl(void *opaque, target_phys_addr_t addr)
{
uint32_t v;
#ifdef TARGET_WORDS_BIGENDIAN
v = cirrus_mmio_readb(opaque, addr) << 24;
v |= cirrus_mmio_readb(opaque, addr + 1) << 16;
v |= cirrus_mmio_readb(opaque, addr + 2) << 8;
v |= cirrus_mmio_readb(opaque, addr + 3);
#else
v = cirrus_mmio_readb(opaque, addr);
v |= cirrus_mmio_readb(opaque, addr + 1) << 8;
v |= cirrus_mmio_readb(opaque, addr + 2) << 16;
v |= cirrus_mmio_readb(opaque, addr + 3) << 24;
#endif
return v;
}
static void cirrus_mmio_writeb(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
CirrusVGAState *s = opaque;
addr &= CIRRUS_PNPMMIO_SIZE - 1;
if (addr >= 0x100) {
cirrus_mmio_blt_write(s, addr - 0x100, val);
} else {
cirrus_vga_ioport_write(s, addr + 0x3c0, val);
}
}
static void cirrus_mmio_writew(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_mmio_writeb(opaque, addr, (val >> 8) & 0xff);
cirrus_mmio_writeb(opaque, addr + 1, val & 0xff);
#else
cirrus_mmio_writeb(opaque, addr, val & 0xff);
cirrus_mmio_writeb(opaque, addr + 1, (val >> 8) & 0xff);
#endif
}
static void cirrus_mmio_writel(void *opaque, target_phys_addr_t addr,
uint32_t val)
{
#ifdef TARGET_WORDS_BIGENDIAN
cirrus_mmio_writeb(opaque, addr, (val >> 24) & 0xff);
cirrus_mmio_writeb(opaque, addr + 1, (val >> 16) & 0xff);
cirrus_mmio_writeb(opaque, addr + 2, (val >> 8) & 0xff);
cirrus_mmio_writeb(opaque, addr + 3, val & 0xff);
#else
cirrus_mmio_writeb(opaque, addr, val & 0xff);
cirrus_mmio_writeb(opaque, addr + 1, (val >> 8) & 0xff);
cirrus_mmio_writeb(opaque, addr + 2, (val >> 16) & 0xff);
cirrus_mmio_writeb(opaque, addr + 3, (val >> 24) & 0xff);
#endif
}
static CPUReadMemoryFunc * const cirrus_mmio_read[3] = {
cirrus_mmio_readb,
cirrus_mmio_readw,
cirrus_mmio_readl,
};
static CPUWriteMemoryFunc * const cirrus_mmio_write[3] = {
cirrus_mmio_writeb,
cirrus_mmio_writew,
cirrus_mmio_writel,
};
/* load/save state */
static int cirrus_post_load(void *opaque, int version_id)
{
CirrusVGAState *s = opaque;
s->vga.gr[0x00] = s->cirrus_shadow_gr0 & 0x0f;
s->vga.gr[0x01] = s->cirrus_shadow_gr1 & 0x0f;
cirrus_update_memory_access(s);
/* force refresh */
s->vga.graphic_mode = -1;
cirrus_update_bank_ptr(s, 0);
cirrus_update_bank_ptr(s, 1);
return 0;
}
static const VMStateDescription vmstate_cirrus_vga = {
.name = "cirrus_vga",
.version_id = 2,
.minimum_version_id = 1,
.minimum_version_id_old = 1,
.post_load = cirrus_post_load,
.fields = (VMStateField []) {
VMSTATE_UINT32(vga.latch, CirrusVGAState),
VMSTATE_UINT8(vga.sr_index, CirrusVGAState),
VMSTATE_BUFFER(vga.sr, CirrusVGAState),
VMSTATE_UINT8(vga.gr_index, CirrusVGAState),
VMSTATE_UINT8(cirrus_shadow_gr0, CirrusVGAState),
VMSTATE_UINT8(cirrus_shadow_gr1, CirrusVGAState),
VMSTATE_BUFFER_START_MIDDLE(vga.gr, CirrusVGAState, 2),
VMSTATE_UINT8(vga.ar_index, CirrusVGAState),
VMSTATE_BUFFER(vga.ar, CirrusVGAState),
VMSTATE_INT32(vga.ar_flip_flop, CirrusVGAState),
VMSTATE_UINT8(vga.cr_index, CirrusVGAState),
VMSTATE_BUFFER(vga.cr, CirrusVGAState),
VMSTATE_UINT8(vga.msr, CirrusVGAState),
VMSTATE_UINT8(vga.fcr, CirrusVGAState),
VMSTATE_UINT8(vga.st00, CirrusVGAState),
VMSTATE_UINT8(vga.st01, CirrusVGAState),
VMSTATE_UINT8(vga.dac_state, CirrusVGAState),
VMSTATE_UINT8(vga.dac_sub_index, CirrusVGAState),
VMSTATE_UINT8(vga.dac_read_index, CirrusVGAState),
VMSTATE_UINT8(vga.dac_write_index, CirrusVGAState),
VMSTATE_BUFFER(vga.dac_cache, CirrusVGAState),
VMSTATE_BUFFER(vga.palette, CirrusVGAState),
VMSTATE_INT32(vga.bank_offset, CirrusVGAState),
VMSTATE_UINT8(cirrus_hidden_dac_lockindex, CirrusVGAState),
VMSTATE_UINT8(cirrus_hidden_dac_data, CirrusVGAState),
VMSTATE_UINT32(hw_cursor_x, CirrusVGAState),
VMSTATE_UINT32(hw_cursor_y, CirrusVGAState),
/* XXX: we do not save the bitblt state - we assume we do not save
the state when the blitter is active */
VMSTATE_END_OF_LIST()
}
};
static const VMStateDescription vmstate_pci_cirrus_vga = {
.name = "cirrus_vga",
.version_id = 2,
.minimum_version_id = 2,
.minimum_version_id_old = 2,
.post_load = cirrus_post_load,
.fields = (VMStateField []) {
VMSTATE_PCI_DEVICE(dev, PCICirrusVGAState),
VMSTATE_STRUCT(cirrus_vga, PCICirrusVGAState, 0,
vmstate_cirrus_vga, CirrusVGAState),
VMSTATE_END_OF_LIST()
}
};
/***************************************
*
* initialize
*
***************************************/
static void cirrus_reset(void *opaque)
{
CirrusVGAState *s = opaque;
vga_common_reset(&s->vga);
unmap_linear_vram(s);
s->vga.sr[0x06] = 0x0f;
if (s->device_id == CIRRUS_ID_CLGD5446) {
/* 4MB 64 bit memory config, always PCI */
s->vga.sr[0x1F] = 0x2d; // MemClock
s->vga.gr[0x18] = 0x0f; // fastest memory configuration
s->vga.sr[0x0f] = 0x98;
s->vga.sr[0x17] = 0x20;
s->vga.sr[0x15] = 0x04; /* memory size, 3=2MB, 4=4MB */
} else {
s->vga.sr[0x1F] = 0x22; // MemClock
s->vga.sr[0x0F] = CIRRUS_MEMSIZE_2M;
s->vga.sr[0x17] = s->bustype;
s->vga.sr[0x15] = 0x03; /* memory size, 3=2MB, 4=4MB */
}
s->vga.cr[0x27] = s->device_id;
/* Win2K seems to assume that the pattern buffer is at 0xff
initially ! */
memset(s->vga.vram_ptr, 0xff, s->real_vram_size);
s->cirrus_hidden_dac_lockindex = 5;
s->cirrus_hidden_dac_data = 0;
}
static void cirrus_init_common(CirrusVGAState * s, int device_id, int is_pci)
{
int i;
static int inited;
if (!inited) {
inited = 1;
for(i = 0;i < 256; i++)
rop_to_index[i] = CIRRUS_ROP_NOP_INDEX; /* nop rop */
rop_to_index[CIRRUS_ROP_0] = 0;
rop_to_index[CIRRUS_ROP_SRC_AND_DST] = 1;
rop_to_index[CIRRUS_ROP_NOP] = 2;
rop_to_index[CIRRUS_ROP_SRC_AND_NOTDST] = 3;
rop_to_index[CIRRUS_ROP_NOTDST] = 4;
rop_to_index[CIRRUS_ROP_SRC] = 5;
rop_to_index[CIRRUS_ROP_1] = 6;
rop_to_index[CIRRUS_ROP_NOTSRC_AND_DST] = 7;
rop_to_index[CIRRUS_ROP_SRC_XOR_DST] = 8;
rop_to_index[CIRRUS_ROP_SRC_OR_DST] = 9;
rop_to_index[CIRRUS_ROP_NOTSRC_OR_NOTDST] = 10;
rop_to_index[CIRRUS_ROP_SRC_NOTXOR_DST] = 11;
rop_to_index[CIRRUS_ROP_SRC_OR_NOTDST] = 12;
rop_to_index[CIRRUS_ROP_NOTSRC] = 13;
rop_to_index[CIRRUS_ROP_NOTSRC_OR_DST] = 14;
rop_to_index[CIRRUS_ROP_NOTSRC_AND_NOTDST] = 15;
s->device_id = device_id;
if (is_pci)
s->bustype = CIRRUS_BUSTYPE_PCI;
else
s->bustype = CIRRUS_BUSTYPE_ISA;
}
register_ioport_write(0x3c0, 16, 1, cirrus_vga_ioport_write, s);
register_ioport_write(0x3b4, 2, 1, cirrus_vga_ioport_write, s);
register_ioport_write(0x3d4, 2, 1, cirrus_vga_ioport_write, s);
register_ioport_write(0x3ba, 1, 1, cirrus_vga_ioport_write, s);
register_ioport_write(0x3da, 1, 1, cirrus_vga_ioport_write, s);
register_ioport_read(0x3c0, 16, 1, cirrus_vga_ioport_read, s);
register_ioport_read(0x3b4, 2, 1, cirrus_vga_ioport_read, s);
register_ioport_read(0x3d4, 2, 1, cirrus_vga_ioport_read, s);
register_ioport_read(0x3ba, 1, 1, cirrus_vga_ioport_read, s);
register_ioport_read(0x3da, 1, 1, cirrus_vga_ioport_read, s);
s->vga.vga_io_memory = cpu_register_io_memory(cirrus_vga_mem_read,
cirrus_vga_mem_write, s);
cpu_register_physical_memory(isa_mem_base + 0x000a0000, 0x20000,
s->vga.vga_io_memory);
qemu_register_coalesced_mmio(isa_mem_base + 0x000a0000, 0x20000);
/* I/O handler for LFB */
s->cirrus_linear_io_addr =
cpu_register_io_memory(cirrus_linear_read, cirrus_linear_write, s);
/* I/O handler for LFB */
s->cirrus_linear_bitblt_io_addr =
cpu_register_io_memory(cirrus_linear_bitblt_read,
cirrus_linear_bitblt_write, s);
/* I/O handler for memory-mapped I/O */
s->cirrus_mmio_io_addr =
cpu_register_io_memory(cirrus_mmio_read, cirrus_mmio_write, s);
s->real_vram_size =
(s->device_id == CIRRUS_ID_CLGD5446) ? 4096 * 1024 : 2048 * 1024;
/* XXX: s->vga.vram_size must be a power of two */
s->cirrus_addr_mask = s->real_vram_size - 1;
s->linear_mmio_mask = s->real_vram_size - 256;
s->vga.get_bpp = cirrus_get_bpp;
s->vga.get_offsets = cirrus_get_offsets;
s->vga.get_resolution = cirrus_get_resolution;
s->vga.cursor_invalidate = cirrus_cursor_invalidate;
s->vga.cursor_draw_line = cirrus_cursor_draw_line;
qemu_register_reset(cirrus_reset, s);
cirrus_reset(s);
}
/***************************************
*
* ISA bus support
*
***************************************/
void isa_cirrus_vga_init(void)
{
CirrusVGAState *s;
s = qemu_mallocz(sizeof(CirrusVGAState));
vga_common_init(&s->vga, VGA_RAM_SIZE);
cirrus_init_common(s, CIRRUS_ID_CLGD5430, 0);
s->vga.ds = graphic_console_init(s->vga.update, s->vga.invalidate,
s->vga.screen_dump, s->vga.text_update,
&s->vga);
vmstate_register(NULL, 0, &vmstate_cirrus_vga, s);
rom_add_vga(VGABIOS_CIRRUS_FILENAME);
/* XXX ISA-LFB support */
}
/***************************************
*
* PCI bus support
*
***************************************/
static void cirrus_pci_lfb_map(PCIDevice *d, int region_num,
pcibus_t addr, pcibus_t size, int type)
{
CirrusVGAState *s = &DO_UPCAST(PCICirrusVGAState, dev, d)->cirrus_vga;
vga_dirty_log_stop(&s->vga);
/* XXX: add byte swapping apertures */
cpu_register_physical_memory(addr, s->vga.vram_size,
s->cirrus_linear_io_addr);
cpu_register_physical_memory(addr + 0x1000000, 0x400000,
s->cirrus_linear_bitblt_io_addr);
s->vga.map_addr = s->vga.map_end = 0;
s->vga.lfb_addr = addr & TARGET_PAGE_MASK;
s->vga.lfb_end = ((addr + VGA_RAM_SIZE) + TARGET_PAGE_SIZE - 1) & TARGET_PAGE_MASK;
/* account for overflow */
if (s->vga.lfb_end < addr + VGA_RAM_SIZE)
s->vga.lfb_end = addr + VGA_RAM_SIZE;
vga_dirty_log_start(&s->vga);
}
static void cirrus_pci_mmio_map(PCIDevice *d, int region_num,
pcibus_t addr, pcibus_t size, int type)
{
CirrusVGAState *s = &DO_UPCAST(PCICirrusVGAState, dev, d)->cirrus_vga;
cpu_register_physical_memory(addr, CIRRUS_PNPMMIO_SIZE,
s->cirrus_mmio_io_addr);
}
static void pci_cirrus_write_config(PCIDevice *d,
uint32_t address, uint32_t val, int len)
{
PCICirrusVGAState *pvs = DO_UPCAST(PCICirrusVGAState, dev, d);
CirrusVGAState *s = &pvs->cirrus_vga;
vga_dirty_log_stop(&s->vga);
pci_default_write_config(d, address, val, len);
if (s->vga.map_addr && d->io_regions[0].addr == PCI_BAR_UNMAPPED)
s->vga.map_addr = 0;
cirrus_update_memory_access(s);
vga_dirty_log_start(&s->vga);
}
static int pci_cirrus_vga_initfn(PCIDevice *dev)
{
PCICirrusVGAState *d = DO_UPCAST(PCICirrusVGAState, dev, dev);
CirrusVGAState *s = &d->cirrus_vga;
uint8_t *pci_conf = d->dev.config;
int device_id = CIRRUS_ID_CLGD5446;
/* setup VGA */
vga_common_init(&s->vga, VGA_RAM_SIZE);
cirrus_init_common(s, device_id, 1);
s->vga.ds = graphic_console_init(s->vga.update, s->vga.invalidate,
s->vga.screen_dump, s->vga.text_update,
&s->vga);
/* setup PCI */
pci_config_set_vendor_id(pci_conf, PCI_VENDOR_ID_CIRRUS);
pci_config_set_device_id(pci_conf, device_id);
pci_config_set_class(pci_conf, PCI_CLASS_DISPLAY_VGA);
/* setup memory space */
/* memory #0 LFB */
/* memory #1 memory-mapped I/O */
/* XXX: s->vga.vram_size must be a power of two */
pci_register_bar((PCIDevice *)d, 0, 0x2000000,
PCI_BASE_ADDRESS_MEM_PREFETCH, cirrus_pci_lfb_map);
if (device_id == CIRRUS_ID_CLGD5446) {
pci_register_bar((PCIDevice *)d, 1, CIRRUS_PNPMMIO_SIZE,
PCI_BASE_ADDRESS_SPACE_MEMORY, cirrus_pci_mmio_map);
}
return 0;
}
void pci_cirrus_vga_init(PCIBus *bus)
{
pci_create_simple(bus, -1, "cirrus-vga");
}
static PCIDeviceInfo cirrus_vga_info = {
.qdev.name = "cirrus-vga",
.qdev.desc = "Cirrus CLGD 54xx VGA",
.qdev.size = sizeof(PCICirrusVGAState),
.qdev.vmsd = &vmstate_pci_cirrus_vga,
.no_hotplug = 1,
.init = pci_cirrus_vga_initfn,
.romfile = VGABIOS_CIRRUS_FILENAME,
.config_write = pci_cirrus_write_config,
};
static void cirrus_vga_register(void)
{
pci_qdev_register(&cirrus_vga_info);
}
device_init(cirrus_vga_register);
|
mithleshvrts/qemu-kvm-rhel6
|
hw/cirrus_vga.c
|
C
|
gpl-2.0
| 99,214
|
<?php
/*
+--------------------------------------------------------------------+
| CiviCRM version 4.4 |
+--------------------------------------------------------------------+
| Copyright CiviCRM LLC (c) 2004-2013 |
+--------------------------------------------------------------------+
| This file is a part of CiviCRM. |
| |
| CiviCRM is free software; you can copy, modify, and distribute it |
| under the terms of the GNU Affero General Public License |
| Version 3, 19 November 2007 and the CiviCRM Licensing Exception. |
| |
| CiviCRM is distributed in the hope that it will be useful, but |
| WITHOUT ANY WARRANTY; without even the implied warranty of |
| MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| See the GNU Affero General Public License for more details. |
| |
| You should have received a copy of the GNU Affero General Public |
| License and the CiviCRM Licensing Exception along |
| with this program; if not, contact CiviCRM LLC |
| at info[AT]civicrm[DOT]org. If you have questions about the |
| GNU Affero General Public License or the licensing of CiviCRM, |
| see the CiviCRM license FAQ at http://civicrm.org/licensing |
+--------------------------------------------------------------------+
*/
/**
* File for the CiviCRM APIv3 Volunteer Need functions
*
* @package CiviVolunteer_APIv3
* @subpackage API_Volunteer_Need
* @copyright CiviCRM LLC (c) 2004-2013
*/
/**
* Create or update a need
*
* @param array $params Associative array of property
* name/value pairs to insert in new 'need'
* @example NeedCreate.php Std Create example
*
* @return array api result array
* {@getfields volunteer_need create}
* @access public
*/
function civicrm_api3_volunteer_need_create($params) {
return _civicrm_api3_basic_create('CRM_Volunteer_BAO_Need', $params);
}
/**
* Adjust Metadata for Create action
*
* The metadata is used for setting defaults, documentation & validation
* @param array $params array or parameters determined by getfields
*/
function _civicrm_api3_volunteer_need_create_spec(&$params) {
$params['project_id']['api.required'] = 1;
$params['is_flexible']['api.default'] = 0;
$params['is_active']['api.default'] = 1;
$params['visibility_id']['api.default'] = CRM_Core_OptionGroup::getValue('visibility', 'public', 'name');
}
/**
* Returns array of needs matching a set of one or more group properties
*
* @param array $params Array of one or more valid
* property_name=>value pairs. If $params is set
* as null, all needs will be returned
*
* @return array (referance) Array of matching needs
* {@getfields need_get}
* @access public
*/
function civicrm_api3_volunteer_need_get($params) {
$result = _civicrm_api3_basic_get(_civicrm_api3_get_BAO(__FUNCTION__), $params);
if (!empty($result['values'])) {
foreach ($result['values'] as &$need) {
if (!empty($need['start_time'])) {
$need['display_time'] = CRM_Volunteer_BAO_Need::getTimes($need['start_time'], CRM_Utils_Array::value('duration', $need));
}
else {
$need['display_time'] = ts('Flexible', array('domain' => 'org.civicrm.volunteer'));
}
if (isset($need['role_id'])) {
$need['role_label'] = CRM_Core_OptionGroup::getLabel(
CRM_Volunteer_BAO_Assignment::ROLE_OPTION_GROUP,
$need['role_id']
);
} elseif (CRM_Utils_Array::value('is_flexible', $need)) {
$need['role_label'] = CRM_Volunteer_BAO_Need::getFlexibleRoleLabel();
}
}
}
return $result;
}
function _civicrm_api3_volunteer_need_get_spec(&$params) {
}
/**
* delete an existing need
*
* This method is used to delete any existing need. id of the group
* to be deleted is required field in $params array
*
* @param array $params (reference) array containing id of the group
* to be deleted
*
* @return array (referance) returns flag true if successfull, error
* message otherwise
* {@getfields need_delete}
* @access public
*/
function civicrm_api3_volunteer_need_delete($params) {
return _civicrm_api3_basic_delete('CRM_Volunteer_BAO_Need', $params);
}
|
glocalcoop/activist-network
|
wp-content/civicrm/extensions/org.civicrm.volunteer/api/v3/VolunteerNeed.php
|
PHP
|
gpl-2.0
| 4,634
|
/* SPDX-License-Identifier: LGPL-2.1+ */
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#if HAVE_XZ
#include <lzma.h>
#endif
#if HAVE_LZ4
#include <lz4.h>
#include <lz4frame.h>
#endif
#include "alloc-util.h"
#include "compress.h"
#include "fd-util.h"
#include "io-util.h"
#include "journal-def.h"
#include "macro.h"
#include "sparse-endian.h"
#include "string-table.h"
#include "string-util.h"
#include "unaligned.h"
#include "util.h"
#if HAVE_LZ4
DEFINE_TRIVIAL_CLEANUP_FUNC(LZ4F_compressionContext_t, LZ4F_freeCompressionContext);
DEFINE_TRIVIAL_CLEANUP_FUNC(LZ4F_decompressionContext_t, LZ4F_freeDecompressionContext);
#endif
#define ALIGN_8(l) ALIGN_TO(l, sizeof(size_t))
static const char* const object_compressed_table[_OBJECT_COMPRESSED_MAX] = {
[OBJECT_COMPRESSED_XZ] = "XZ",
[OBJECT_COMPRESSED_LZ4] = "LZ4",
};
DEFINE_STRING_TABLE_LOOKUP(object_compressed, int);
int compress_blob_xz(const void *src, uint64_t src_size,
void *dst, size_t dst_alloc_size, size_t *dst_size) {
#if HAVE_XZ
static const lzma_options_lzma opt = {
1u << 20u, NULL, 0, LZMA_LC_DEFAULT, LZMA_LP_DEFAULT,
LZMA_PB_DEFAULT, LZMA_MODE_FAST, 128, LZMA_MF_HC3, 4
};
static const lzma_filter filters[] = {
{ LZMA_FILTER_LZMA2, (lzma_options_lzma*) &opt },
{ LZMA_VLI_UNKNOWN, NULL }
};
lzma_ret ret;
size_t out_pos = 0;
assert(src);
assert(src_size > 0);
assert(dst);
assert(dst_alloc_size > 0);
assert(dst_size);
/* Returns < 0 if we couldn't compress the data or the
* compressed result is longer than the original */
if (src_size < 80)
return -ENOBUFS;
ret = lzma_stream_buffer_encode((lzma_filter*) filters, LZMA_CHECK_NONE, NULL,
src, src_size, dst, &out_pos, dst_alloc_size);
if (ret != LZMA_OK)
return -ENOBUFS;
*dst_size = out_pos;
return 0;
#else
return -EPROTONOSUPPORT;
#endif
}
int compress_blob_lz4(const void *src, uint64_t src_size,
void *dst, size_t dst_alloc_size, size_t *dst_size) {
#if HAVE_LZ4
int r;
assert(src);
assert(src_size > 0);
assert(dst);
assert(dst_alloc_size > 0);
assert(dst_size);
/* Returns < 0 if we couldn't compress the data or the
* compressed result is longer than the original */
if (src_size < 9)
return -ENOBUFS;
r = LZ4_compress_default(src, (char*)dst + 8, src_size, (int) dst_alloc_size - 8);
if (r <= 0)
return -ENOBUFS;
unaligned_write_le64(dst, src_size);
*dst_size = r + 8;
return 0;
#else
return -EPROTONOSUPPORT;
#endif
}
int decompress_blob_xz(const void *src, uint64_t src_size,
void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) {
#if HAVE_XZ
_cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
lzma_ret ret;
size_t space;
assert(src);
assert(src_size > 0);
assert(dst);
assert(dst_alloc_size);
assert(dst_size);
assert(*dst_alloc_size == 0 || *dst);
ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
if (ret != LZMA_OK)
return -ENOMEM;
space = MIN(src_size * 2, dst_max ?: (size_t) -1);
if (!greedy_realloc(dst, dst_alloc_size, space, 1))
return -ENOMEM;
s.next_in = src;
s.avail_in = src_size;
s.next_out = *dst;
s.avail_out = space;
for (;;) {
size_t used;
ret = lzma_code(&s, LZMA_FINISH);
if (ret == LZMA_STREAM_END)
break;
else if (ret != LZMA_OK)
return -ENOMEM;
if (dst_max > 0 && (space - s.avail_out) >= dst_max)
break;
else if (dst_max > 0 && space == dst_max)
return -ENOBUFS;
used = space - s.avail_out;
space = MIN(2 * space, dst_max ?: (size_t) -1);
if (!greedy_realloc(dst, dst_alloc_size, space, 1))
return -ENOMEM;
s.avail_out = space - used;
s.next_out = *(uint8_t**)dst + used;
}
*dst_size = space - s.avail_out;
return 0;
#else
return -EPROTONOSUPPORT;
#endif
}
int decompress_blob_lz4(const void *src, uint64_t src_size,
void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) {
#if HAVE_LZ4
char* out;
int r, size; /* LZ4 uses int for size */
assert(src);
assert(src_size > 0);
assert(dst);
assert(dst_alloc_size);
assert(dst_size);
assert(*dst_alloc_size == 0 || *dst);
if (src_size <= 8)
return -EBADMSG;
size = unaligned_read_le64(src);
if (size < 0 || (unsigned) size != unaligned_read_le64(src))
return -EFBIG;
if ((size_t) size > *dst_alloc_size) {
out = realloc(*dst, size);
if (!out)
return -ENOMEM;
*dst = out;
*dst_alloc_size = size;
} else
out = *dst;
r = LZ4_decompress_safe((char*)src + 8, out, src_size - 8, size);
if (r < 0 || r != size)
return -EBADMSG;
*dst_size = size;
return 0;
#else
return -EPROTONOSUPPORT;
#endif
}
int decompress_blob(int compression,
const void *src, uint64_t src_size,
void **dst, size_t *dst_alloc_size, size_t* dst_size, size_t dst_max) {
if (compression == OBJECT_COMPRESSED_XZ)
return decompress_blob_xz(src, src_size,
dst, dst_alloc_size, dst_size, dst_max);
else if (compression == OBJECT_COMPRESSED_LZ4)
return decompress_blob_lz4(src, src_size,
dst, dst_alloc_size, dst_size, dst_max);
else
return -EBADMSG;
}
int decompress_startswith_xz(const void *src, uint64_t src_size,
void **buffer, size_t *buffer_size,
const void *prefix, size_t prefix_len,
uint8_t extra) {
#if HAVE_XZ
_cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
lzma_ret ret;
/* Checks whether the decompressed blob starts with the
* mentioned prefix. The byte extra needs to follow the
* prefix */
assert(src);
assert(src_size > 0);
assert(buffer);
assert(buffer_size);
assert(prefix);
assert(*buffer_size == 0 || *buffer);
ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
if (ret != LZMA_OK)
return -EBADMSG;
if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1)))
return -ENOMEM;
s.next_in = src;
s.avail_in = src_size;
s.next_out = *buffer;
s.avail_out = *buffer_size;
for (;;) {
ret = lzma_code(&s, LZMA_FINISH);
if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END))
return -EBADMSG;
if (*buffer_size - s.avail_out >= prefix_len + 1)
return memcmp(*buffer, prefix, prefix_len) == 0 &&
((const uint8_t*) *buffer)[prefix_len] == extra;
if (ret == LZMA_STREAM_END)
return 0;
s.avail_out += *buffer_size;
if (!(greedy_realloc(buffer, buffer_size, *buffer_size * 2, 1)))
return -ENOMEM;
s.next_out = *(uint8_t**)buffer + *buffer_size - s.avail_out;
}
#else
return -EPROTONOSUPPORT;
#endif
}
int decompress_startswith_lz4(const void *src, uint64_t src_size,
void **buffer, size_t *buffer_size,
const void *prefix, size_t prefix_len,
uint8_t extra) {
#if HAVE_LZ4
/* Checks whether the decompressed blob starts with the
* mentioned prefix. The byte extra needs to follow the
* prefix */
int r;
assert(src);
assert(src_size > 0);
assert(buffer);
assert(buffer_size);
assert(prefix);
assert(*buffer_size == 0 || *buffer);
if (src_size <= 8)
return -EBADMSG;
if (!(greedy_realloc(buffer, buffer_size, ALIGN_8(prefix_len + 1), 1)))
return -ENOMEM;
r = LZ4_decompress_safe_partial((char*)src + 8, *buffer, src_size - 8,
prefix_len + 1, *buffer_size);
/* One lz4 < 1.8.3, we might get "failure" (r < 0), or "success" where
* just a part of the buffer is decompressed. But if we get a smaller
* amount of bytes than requested, we don't know whether there isn't enough
* data to fill the requested size or whether we just got a partial answer.
*/
if (r < 0 || (size_t) r < prefix_len + 1) {
size_t size;
if (LZ4_versionNumber() >= 10803)
/* We trust that the newer lz4 decompresses the number of bytes we
* requested if available in the compressed string. */
return 0;
if (r > 0)
/* Compare what we have first, in case of mismatch we can
* shortcut the full comparison. */
if (memcmp(*buffer, prefix, r) != 0)
return 0;
/* Before version 1.8.3, lz4 always tries to decode full a "sequence",
* so in pathological cases might need to decompress the full field. */
r = decompress_blob_lz4(src, src_size, buffer, buffer_size, &size, 0);
if (r < 0)
return r;
if (size < prefix_len + 1)
return 0;
}
return memcmp(*buffer, prefix, prefix_len) == 0 &&
((const uint8_t*) *buffer)[prefix_len] == extra;
#else
return -EPROTONOSUPPORT;
#endif
}
int decompress_startswith(int compression,
const void *src, uint64_t src_size,
void **buffer, size_t *buffer_size,
const void *prefix, size_t prefix_len,
uint8_t extra) {
if (compression == OBJECT_COMPRESSED_XZ)
return decompress_startswith_xz(src, src_size,
buffer, buffer_size,
prefix, prefix_len,
extra);
else if (compression == OBJECT_COMPRESSED_LZ4)
return decompress_startswith_lz4(src, src_size,
buffer, buffer_size,
prefix, prefix_len,
extra);
else
return -EBADMSG;
}
int compress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
#if HAVE_XZ
_cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
lzma_ret ret;
uint8_t buf[BUFSIZ], out[BUFSIZ];
lzma_action action = LZMA_RUN;
assert(fdf >= 0);
assert(fdt >= 0);
ret = lzma_easy_encoder(&s, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64);
if (ret != LZMA_OK) {
log_error("Failed to initialize XZ encoder: code %u", ret);
return -EINVAL;
}
for (;;) {
if (s.avail_in == 0 && action == LZMA_RUN) {
size_t m = sizeof(buf);
ssize_t n;
if (max_bytes != (uint64_t) -1 && (uint64_t) m > max_bytes)
m = (size_t) max_bytes;
n = read(fdf, buf, m);
if (n < 0)
return -errno;
if (n == 0)
action = LZMA_FINISH;
else {
s.next_in = buf;
s.avail_in = n;
if (max_bytes != (uint64_t) -1) {
assert(max_bytes >= (uint64_t) n);
max_bytes -= n;
}
}
}
if (s.avail_out == 0) {
s.next_out = out;
s.avail_out = sizeof(out);
}
ret = lzma_code(&s, action);
if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END)) {
log_error("Compression failed: code %u", ret);
return -EBADMSG;
}
if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
ssize_t n, k;
n = sizeof(out) - s.avail_out;
k = loop_write(fdt, out, n, false);
if (k < 0)
return k;
if (ret == LZMA_STREAM_END) {
log_debug("XZ compression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
s.total_in, s.total_out,
(double) s.total_out / s.total_in * 100);
return 0;
}
}
}
#else
return -EPROTONOSUPPORT;
#endif
}
#define LZ4_BUFSIZE (512*1024u)
int compress_stream_lz4(int fdf, int fdt, uint64_t max_bytes) {
#if HAVE_LZ4
LZ4F_errorCode_t c;
_cleanup_(LZ4F_freeCompressionContextp) LZ4F_compressionContext_t ctx = NULL;
_cleanup_free_ char *buf = NULL;
char *src = NULL;
size_t size, n, total_in = 0, total_out, offset = 0, frame_size;
struct stat st;
int r;
static const LZ4F_compressOptions_t options = {
.stableSrc = 1,
};
static const LZ4F_preferences_t preferences = {
.frameInfo.blockSizeID = 5,
};
c = LZ4F_createCompressionContext(&ctx, LZ4F_VERSION);
if (LZ4F_isError(c))
return -ENOMEM;
if (fstat(fdf, &st) < 0)
return log_debug_errno(errno, "fstat() failed: %m");
frame_size = LZ4F_compressBound(LZ4_BUFSIZE, &preferences);
size = frame_size + 64*1024; /* add some space for header and trailer */
buf = malloc(size);
if (!buf)
return -ENOMEM;
n = offset = total_out = LZ4F_compressBegin(ctx, buf, size, &preferences);
if (LZ4F_isError(n))
return -EINVAL;
src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fdf, 0);
if (src == MAP_FAILED)
return -errno;
log_debug("Buffer size is %zu bytes, header size %zu bytes.", size, n);
while (total_in < (size_t) st.st_size) {
ssize_t k;
k = MIN(LZ4_BUFSIZE, st.st_size - total_in);
n = LZ4F_compressUpdate(ctx, buf + offset, size - offset,
src + total_in, k, &options);
if (LZ4F_isError(n)) {
r = -ENOTRECOVERABLE;
goto cleanup;
}
total_in += k;
offset += n;
total_out += n;
if (max_bytes != (uint64_t) -1 && total_out > (size_t) max_bytes) {
log_debug("Compressed stream longer than %"PRIu64" bytes", max_bytes);
return -EFBIG;
}
if (size - offset < frame_size + 4) {
k = loop_write(fdt, buf, offset, false);
if (k < 0) {
r = k;
goto cleanup;
}
offset = 0;
}
}
n = LZ4F_compressEnd(ctx, buf + offset, size - offset, &options);
if (LZ4F_isError(n)) {
r = -ENOTRECOVERABLE;
goto cleanup;
}
offset += n;
total_out += n;
r = loop_write(fdt, buf, offset, false);
if (r < 0)
goto cleanup;
log_debug("LZ4 compression finished (%zu -> %zu bytes, %.1f%%)",
total_in, total_out,
(double) total_out / total_in * 100);
cleanup:
munmap(src, st.st_size);
return r;
#else
return -EPROTONOSUPPORT;
#endif
}
int decompress_stream_xz(int fdf, int fdt, uint64_t max_bytes) {
#if HAVE_XZ
_cleanup_(lzma_end) lzma_stream s = LZMA_STREAM_INIT;
lzma_ret ret;
uint8_t buf[BUFSIZ], out[BUFSIZ];
lzma_action action = LZMA_RUN;
assert(fdf >= 0);
assert(fdt >= 0);
ret = lzma_stream_decoder(&s, UINT64_MAX, 0);
if (ret != LZMA_OK) {
log_debug("Failed to initialize XZ decoder: code %u", ret);
return -ENOMEM;
}
for (;;) {
if (s.avail_in == 0 && action == LZMA_RUN) {
ssize_t n;
n = read(fdf, buf, sizeof(buf));
if (n < 0)
return -errno;
if (n == 0)
action = LZMA_FINISH;
else {
s.next_in = buf;
s.avail_in = n;
}
}
if (s.avail_out == 0) {
s.next_out = out;
s.avail_out = sizeof(out);
}
ret = lzma_code(&s, action);
if (!IN_SET(ret, LZMA_OK, LZMA_STREAM_END)) {
log_debug("Decompression failed: code %u", ret);
return -EBADMSG;
}
if (s.avail_out == 0 || ret == LZMA_STREAM_END) {
ssize_t n, k;
n = sizeof(out) - s.avail_out;
if (max_bytes != (uint64_t) -1) {
if (max_bytes < (uint64_t) n)
return -EFBIG;
max_bytes -= n;
}
k = loop_write(fdt, out, n, false);
if (k < 0)
return k;
if (ret == LZMA_STREAM_END) {
log_debug("XZ decompression finished (%"PRIu64" -> %"PRIu64" bytes, %.1f%%)",
s.total_in, s.total_out,
(double) s.total_out / s.total_in * 100);
return 0;
}
}
}
#else
log_debug("Cannot decompress file. Compiled without XZ support.");
return -EPROTONOSUPPORT;
#endif
}
int decompress_stream_lz4(int in, int out, uint64_t max_bytes) {
#if HAVE_LZ4
size_t c;
_cleanup_(LZ4F_freeDecompressionContextp) LZ4F_decompressionContext_t ctx = NULL;
_cleanup_free_ char *buf = NULL;
char *src;
struct stat st;
int r = 0;
size_t total_in = 0, total_out = 0;
c = LZ4F_createDecompressionContext(&ctx, LZ4F_VERSION);
if (LZ4F_isError(c))
return -ENOMEM;
if (fstat(in, &st) < 0)
return log_debug_errno(errno, "fstat() failed: %m");
buf = malloc(LZ4_BUFSIZE);
if (!buf)
return -ENOMEM;
src = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, in, 0);
if (src == MAP_FAILED)
return -errno;
while (total_in < (size_t) st.st_size) {
size_t produced = LZ4_BUFSIZE;
size_t used = st.st_size - total_in;
c = LZ4F_decompress(ctx, buf, &produced, src + total_in, &used, NULL);
if (LZ4F_isError(c)) {
r = -EBADMSG;
goto cleanup;
}
total_in += used;
total_out += produced;
if (max_bytes != (uint64_t) -1 && total_out > (size_t) max_bytes) {
log_debug("Decompressed stream longer than %"PRIu64" bytes", max_bytes);
r = -EFBIG;
goto cleanup;
}
r = loop_write(out, buf, produced, false);
if (r < 0)
goto cleanup;
}
log_debug("LZ4 decompression finished (%zu -> %zu bytes, %.1f%%)",
total_in, total_out,
total_in > 0 ? (double) total_out / total_in * 100 : 0.0);
cleanup:
munmap(src, st.st_size);
return r;
#else
log_debug("Cannot decompress file. Compiled without LZ4 support.");
return -EPROTONOSUPPORT;
#endif
}
int decompress_stream(const char *filename, int fdf, int fdt, uint64_t max_bytes) {
if (endswith(filename, ".lz4"))
return decompress_stream_lz4(fdf, fdt, max_bytes);
else if (endswith(filename, ".xz"))
return decompress_stream_xz(fdf, fdt, max_bytes);
else
return -EPROTONOSUPPORT;
}
|
jsynacek/systemd
|
src/journal/compress.c
|
C
|
gpl-2.0
| 22,226
|
using Server.Network;
using System;
namespace Server.Items
{
[Flipable(0x2A5D, 0x2A61)]
public class DisturbingPortraitComponent : AddonComponent
{
public DisturbingPortraitComponent()
: base(0x2A5D)
{
TimerRegistry.Register("DisturbingPortrait", this, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3), false, p => p.Change());
}
public DisturbingPortraitComponent(Serial serial)
: base(serial)
{
}
public override int LabelNumber => 1074479;// Disturbing portrait
public override void OnDoubleClick(Mobile from)
{
if (Utility.InRange(Location, from.Location, 2))
Effects.PlaySound(Location, Map, Utility.RandomMinMax(0x567, 0x568));
else
from.LocalOverheadMessage(MessageType.Regular, 0x3B2, 1019045); // I can't reach that.
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
TimerRegistry.Register("DisturbingPortrait", this, TimeSpan.FromMinutes(3), TimeSpan.FromMinutes(3), false, p => p.Change());
}
private void Change()
{
if (ItemID < 0x2A61)
ItemID = Utility.RandomMinMax(0x2A5D, 0x2A60);
else
ItemID = Utility.RandomMinMax(0x2A61, 0x2A64);
}
}
public class DisturbingPortraitAddon : BaseAddon
{
[Constructable]
public DisturbingPortraitAddon()
: base()
{
AddComponent(new DisturbingPortraitComponent(), 0, 0, 0);
}
public DisturbingPortraitAddon(Serial serial)
: base(serial)
{
}
public override BaseAddonDeed Deed => new DisturbingPortraitDeed();
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
}
}
public class DisturbingPortraitDeed : BaseAddonDeed
{
[Constructable]
public DisturbingPortraitDeed()
: base()
{
LootType = LootType.Blessed;
}
public DisturbingPortraitDeed(Serial serial)
: base(serial)
{
}
public override BaseAddon Addon => new DisturbingPortraitAddon();
public override int LabelNumber => 1074479;// Disturbing portrait
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.WriteEncodedInt(0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadEncodedInt();
}
}
}
|
zerodowned/ServUO
|
Scripts/Items/Addons/DisturbingPortrait.cs
|
C#
|
gpl-2.0
| 3,202
|
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'ZfcRbac\\' => array($vendorDir . '/zf-commons/zfc-rbac/src'),
'Zend\\' => array($vendorDir . '/zendframework/zendframework/library'),
'ZendXml' => array($vendorDir . '/zendframework/zendxml/library'),
'ZendService\\Amazon\\' => array($vendorDir . '/zendframework/zendservice-amazon/library'),
'ZendRest' => array($vendorDir . '/zendframework/zendrest/library'),
'VuFindHttp\\' => array($vendorDir . '/vufind-org/vufindhttp/src'),
'VuFindCode\\' => array($vendorDir . '/vufind-org/vufindcode/src'),
'SerialsSolutions' => array($vendorDir . '/serialssolutions/summon'),
'Rbac\\' => array($vendorDir . '/zfr/rbac/src'),
'ProxyManager\\' => array($vendorDir . '/ocramius/proxy-manager/src'),
'PHPQRCode' => array($vendorDir . '/aferrandini/phpqrcode/lib'),
'LosReCaptcha\\' => array($vendorDir . '/los/losrecaptcha/src'),
'Less' => array($vendorDir . '/oyejorge/less.php/lib'),
'Behat\\Mink\\Driver' => array($vendorDir . '/behat/mink-zombie-driver/src'),
);
|
paulusova/VuFind-2.x
|
vendor/composer/autoload_namespaces.php
|
PHP
|
gpl-2.0
| 1,158
|
from tasks import func
func.delay(1, 2)
|
emanuelvianna/microcelery
|
tests/client.py
|
Python
|
gpl-2.0
| 41
|
#include <linux/mm.h>
#include <linux/gfp.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/tlb.h>
#include <asm/fixmap.h>
#define PGALLOC_GFP GFP_KERNEL | __GFP_NOTRACK | __GFP_REPEAT | __GFP_ZERO
#ifdef CONFIG_HIGHPTE
#define PGALLOC_USER_GFP __GFP_HIGHMEM
#else
#define PGALLOC_USER_GFP 0
#endif
gfp_t __userpte_alloc_gfp = PGALLOC_GFP | PGALLOC_USER_GFP;
pte_t *pte_alloc_one_kernel(struct mm_struct *mm, unsigned long address)
{
return (pte_t *)__get_free_page(PGALLOC_GFP);
}
pgtable_t pte_alloc_one(struct mm_struct *mm, unsigned long address)
{
struct page *pte;
pte = alloc_pages(__userpte_alloc_gfp, 0);
if (pte)
pgtable_page_ctor(pte);
return pte;
}
static int __init setup_userpte(char *arg)
{
if (!arg)
return -EINVAL;
/*
* "userpte=nohigh" disables allocation of user pagetables in
* high memory.
*/
if (strcmp(arg, "nohigh") == 0)
__userpte_alloc_gfp &= ~__GFP_HIGHMEM;
else
return -EINVAL;
return 0;
}
early_param("userpte", setup_userpte);
void ___pte_free_tlb(struct mmu_gather *tlb, struct page *pte)
{
pgtable_page_dtor(pte);
paravirt_release_pte(page_to_pfn(pte));
tlb_remove_page(tlb, pte);
}
#if PAGETABLE_LEVELS > 2
void ___pmd_free_tlb(struct mmu_gather *tlb, pmd_t *pmd)
{
paravirt_release_pmd(__pa(pmd) >> PAGE_SHIFT);
tlb_remove_page(tlb, virt_to_page(pmd));
}
#if PAGETABLE_LEVELS > 3
void ___pud_free_tlb(struct mmu_gather *tlb, pud_t *pud)
{
paravirt_release_pud(__pa(pud) >> PAGE_SHIFT);
tlb_remove_page(tlb, virt_to_page(pud));
}
#endif /* PAGETABLE_LEVELS > 3 */
#endif /* PAGETABLE_LEVELS > 2 */
static inline void pgd_list_add(pgd_t *pgd)
{
struct page *page = virt_to_page(pgd);
list_add(&page->lru, &pgd_list);
}
static inline void pgd_list_del(pgd_t *pgd)
{
struct page *page = virt_to_page(pgd);
list_del(&page->lru);
}
#define UNSHARED_PTRS_PER_PGD \
(SHARED_KERNEL_PMD ? KERNEL_PGD_BOUNDARY : PTRS_PER_PGD)
static void pgd_set_mm(pgd_t *pgd, struct mm_struct *mm)
{
BUILD_BUG_ON(sizeof(virt_to_page(pgd)->index) < sizeof(mm));
virt_to_page(pgd)->index = (pgoff_t)mm;
}
struct mm_struct *pgd_page_get_mm(struct page *page)
{
return (struct mm_struct *)page->index;
}
static void pgd_ctor(struct mm_struct *mm, pgd_t *pgd)
{
/* If the pgd points to a shared pagetable level (either the
ptes in non-PAE, or shared PMD in PAE), then just copy the
references from swapper_pg_dir. */
if (PAGETABLE_LEVELS == 2 ||
(PAGETABLE_LEVELS == 3 && SHARED_KERNEL_PMD) ||
PAGETABLE_LEVELS == 4) {
clone_pgd_range(pgd + KERNEL_PGD_BOUNDARY,
swapper_pg_dir + KERNEL_PGD_BOUNDARY,
KERNEL_PGD_PTRS);
}
/* list required to sync kernel mapping updates */
if (!SHARED_KERNEL_PMD) {
pgd_set_mm(pgd, mm);
pgd_list_add(pgd);
}
}
static void pgd_dtor(pgd_t *pgd)
{
unsigned long flags; /* can be called from interrupt context */
if (SHARED_KERNEL_PMD)
return;
spin_lock_irqsave(&pgd_lock, flags);
pgd_list_del(pgd);
spin_unlock_irqrestore(&pgd_lock, flags);
}
/*
* List of all pgd's needed for non-PAE so it can invalidate entries
* in both cached and uncached pgd's; not needed for PAE since the
* kernel pmd is shared. If PAE were not to share the pmd a similar
* tactic would be needed. This is essentially codepath-based locking
* against pageattr.c; it is the unique case in which a valid change
* of kernel pagetables can't be lazily synchronized by vmalloc faults.
* vmalloc faults work because attached pagetables are never freed.
* -- wli
*/
#ifdef CONFIG_X86_PAE
/*
* In PAE mode, we need to do a cr3 reload (=tlb flush) when
* updating the top-level pagetable entries to guarantee the
* processor notices the update. Since this is expensive, and
* all 4 top-level entries are used almost immediately in a
* new process's life, we just pre-populate them here.
*
* Also, if we're in a paravirt environment where the kernel pmd is
* not shared between pagetables (!SHARED_KERNEL_PMDS), we allocate
* and initialize the kernel pmds here.
*/
#define PREALLOCATED_PMDS UNSHARED_PTRS_PER_PGD
void pud_populate(struct mm_struct *mm, pud_t *pudp, pmd_t *pmd)
{
paravirt_alloc_pmd(mm, __pa(pmd) >> PAGE_SHIFT);
/* Note: almost everything apart from _PAGE_PRESENT is
reserved at the pmd (PDPT) level. */
set_pud(pudp, __pud(__pa(pmd) | _PAGE_PRESENT));
/*
* According to Intel App note "TLBs, Paging-Structure Caches,
* and Their Invalidation", April 2007, document 317080-001,
* section 8.1: in PAE mode we explicitly have to flush the
* TLB via cr3 if the top-level pgd is changed...
*/
flush_tlb_mm(mm);
}
#else /* !CONFIG_X86_PAE */
/* No need to prepopulate any pagetable entries in non-PAE modes. */
#define PREALLOCATED_PMDS 0
#endif /* CONFIG_X86_PAE */
static void free_pmds(pmd_t *pmds[])
{
int i;
for(i = 0; i < PREALLOCATED_PMDS; i++)
if (pmds[i])
free_page((unsigned long)pmds[i]);
}
static int preallocate_pmds(pmd_t *pmds[])
{
int i;
bool failed = false;
for(i = 0; i < PREALLOCATED_PMDS; i++) {
pmd_t *pmd = (pmd_t *)__get_free_page(PGALLOC_GFP);
if (pmd == NULL)
failed = true;
pmds[i] = pmd;
}
if (failed) {
free_pmds(pmds);
return -ENOMEM;
}
return 0;
}
/*
* Mop up any pmd pages which may still be attached to the pgd.
* Normally they will be freed by munmap/exit_mmap, but any pmd we
* preallocate which never got a corresponding vma will need to be
* freed manually.
*/
static void pgd_mop_up_pmds(struct mm_struct *mm, pgd_t *pgdp)
{
int i;
for(i = 0; i < PREALLOCATED_PMDS; i++) {
pgd_t pgd = pgdp[i];
if (pgd_val(pgd) != 0) {
pmd_t *pmd = (pmd_t *)pgd_page_vaddr(pgd);
pgdp[i] = native_make_pgd(0);
paravirt_release_pmd(pgd_val(pgd) >> PAGE_SHIFT);
pmd_free(mm, pmd);
}
}
}
static void pgd_prepopulate_pmd(struct mm_struct *mm, pgd_t *pgd, pmd_t *pmds[])
{
pud_t *pud;
unsigned long addr;
int i;
if (PREALLOCATED_PMDS == 0) /* Work around gcc-3.4.x bug */
return;
pud = pud_offset(pgd, 0);
for (addr = i = 0; i < PREALLOCATED_PMDS;
i++, pud++, addr += PUD_SIZE) {
pmd_t *pmd = pmds[i];
if (i >= KERNEL_PGD_BOUNDARY)
memcpy(pmd, (pmd_t *)pgd_page_vaddr(swapper_pg_dir[i]),
sizeof(pmd_t) * PTRS_PER_PMD);
pud_populate(mm, pud, pmd);
}
}
pgd_t *pgd_alloc(struct mm_struct *mm)
{
pgd_t *pgd;
pmd_t *pmds[PREALLOCATED_PMDS];
unsigned long flags;
pgd = (pgd_t *)__get_free_page(PGALLOC_GFP);
if (pgd == NULL)
goto out;
mm->pgd = pgd;
if (preallocate_pmds(pmds) != 0)
goto out_free_pgd;
if (paravirt_pgd_alloc(mm) != 0)
goto out_free_pmds;
/*
* Make sure that pre-populating the pmds is atomic with
* respect to anything walking the pgd_list, so that they
* never see a partially populated pgd.
*/
spin_lock_irqsave(&pgd_lock, flags);
pgd_ctor(mm, pgd);
pgd_prepopulate_pmd(mm, pgd, pmds);
spin_unlock_irqrestore(&pgd_lock, flags);
return pgd;
out_free_pmds:
free_pmds(pmds);
out_free_pgd:
free_page((unsigned long)pgd);
out:
return NULL;
}
void pgd_free(struct mm_struct *mm, pgd_t *pgd)
{
pgd_mop_up_pmds(mm, pgd);
pgd_dtor(pgd);
paravirt_pgd_free(mm, pgd);
free_page((unsigned long)pgd);
}
int ptep_set_access_flags(struct vm_area_struct *vma,
unsigned long address, pte_t *ptep,
pte_t entry, int dirty)
{
int changed = !pte_same(*ptep, entry);
if (changed && dirty) {
*ptep = entry;
pte_update_defer(vma->vm_mm, address, ptep);
flush_tlb_page(vma, address);
}
return changed;
}
int ptep_test_and_clear_young(struct vm_area_struct *vma,
unsigned long addr, pte_t *ptep)
{
int ret = 0;
if (pte_young(*ptep))
ret = test_and_clear_bit(_PAGE_BIT_ACCESSED,
(unsigned long *) &ptep->pte);
if (ret)
pte_update(vma->vm_mm, addr, ptep);
return ret;
}
int ptep_clear_flush_young(struct vm_area_struct *vma,
unsigned long address, pte_t *ptep)
{
int young;
young = ptep_test_and_clear_young(vma, address, ptep);
if (young)
flush_tlb_page(vma, address);
return young;
}
/**
* reserve_top_address - reserves a hole in the top of kernel address space
* @reserve - size of hole to reserve
*
* Can be used to relocate the fixmap area and poke a hole in the top
* of kernel address space to make room for a hypervisor.
*/
void __init reserve_top_address(unsigned long reserve)
{
#ifdef CONFIG_X86_32
BUG_ON(fixmaps_set > 0);
printk(KERN_INFO "Reserving virtual address space above 0x%08x\n",
(int)-reserve);
__FIXADDR_TOP = -reserve - PAGE_SIZE;
#endif
}
int fixmaps_set;
void __native_set_fixmap(enum fixed_addresses idx, pte_t pte)
{
unsigned long address = __fix_to_virt(idx);
if (idx >= __end_of_fixed_addresses) {
BUG();
return;
}
set_pte_vaddr(address, pte);
fixmaps_set++;
}
void native_set_fixmap(enum fixed_addresses idx, phys_addr_t phys,
pgprot_t flags)
{
__native_set_fixmap(idx, pfn_pte(phys >> PAGE_SHIFT, flags));
}
|
steppnasty/platform_kernel_msm7x30
|
arch/x86/mm/pgtable.c
|
C
|
gpl-2.0
| 8,882
|
<html>
<head>
<title> XPPAUT - WINDOWS INSTALL </title>
</head>
<body bgcolor="#FFFFFF" link="#330099" alink="#FF3300" vlink="#330099">
<center> <h1>XPP WINDOWS INSTALL</h1> </center>
<p>
<!--
<p><br>
<table BORDER=0 WIDTH="100%" >
<tr>
<td ALIGN=LEFT BGCOLOR="#52799E">
<b><font face="Helvetica, Arial"><font color="#FFFFFF"><font size=+1>Contents</font></font></font></b></td>
</tr>
</table>
-->
These instructions were obtained from <a href=https://docs.math.osu.edu/windows/how-tos/install-xpp-xppaut-windows/> the OSU math department web site </a>
<ul>
<li> Step 0: If you are just upgrading to the newest XPP version jump to Step 2.
<li> Step 1: You must install an X11 server, <a href=http://sourceforge.net/projects/xming/files/latest/download> Xming </a> or you can get an older one from my web page. It is also useful to download the additional X11 fonts from <a href=http://sourceforge.net/projects/xming/files/Xming-fonts/7.5.0.70/Xming-fonts-7-5-0-70-setup.exe/download> here </a>
<ul>
<li> After downloading the two X11 programs, runs them to install on your computer. You can use the default / full installation settings for both the Xming program and the Xming fonts - just make sure that the "Normal PuTTY Link SSH client" option is selected in the Xming program installation settings. I usually include a Desktop shortcut.
<li> Run the Xming program from <b> (Start) --> All Programs / All Apps --> Xming --> Xming </b>
<li> Verify the Xming program is running by looking for the "X" icon in the Windows Taskbar Notifications Area.
</ul>
<li> Step 2: Download <a href=http://www.math.pitt.edu/~bard/bardware/binary/latest/xppwin.zip> XPPAUT "xppwin.zip" </a>
<ul>
<li> Extract / unzip the downloaded "xppwin.zip" file, by right-clicking on the file and then clicking to "Extract All...", which will reveal an "xppall" folder.
<li> Right-click to "Copy" the extracted "xppall" folder, then open your computer's "C:" drive and right-click in a blank space to "Paste" the folder in the root of the "C:" drive. <b> IMPORTANT:</b> The "xppall" folder must be placed so that the full path to the folder is"C:\xppall"
<li> Extra Step on Windows 8/10(?):
<ul>
<li> Open the "xppall" folder, find and right-click on the "xppaut.exe" file / application, then click to open its "Properties"
<li> On the "General" tab under "Security:", click the "Unblock" button to allow the application to run.
<li> Click "OK" to close the properties window
</ul>
<li> Open the "xppall" folder, find the "xpp - Shortcut" file, right-click on the file to "Copy" the shortcut, and then right-click on a blank space of the Desktop to "Paste" the shortcut on the Desktop.
<li> To use XPP / XPPAUT, drag and drop ODE files onto the "xpp - Shortcut" on your Desktop.
</ul>
</ul>
<p>
<hline>
<b> The best way to use XPP is from the command line as this gives you many more options and much more flexibility. </b> <p>
Here is how to do it.
<ul>
<li> Click on "Start" and <i>Search Programs</i> for "command prompt" and click on it to bring up a terminal
</li>
<li> Click on the terminal to start typing. Navigate to the "xppall" folder by typing:
<p>
<code> cd C:/xppall </code> <p>
</li>
<li> Test it by typing:
<p>
<code> xpp ode/lecar.ode </code> <p>
to load up the good old lecar.ode file
</li>
<li> You can directly access the <code> xppaut.exe </code> file from the command line as well but you should be sure to set the proper X11 Display. The <code> xpp.bat </code> file does this for you as well as setting a HOME directory and some other stuff that is largely irrelevant unless you want to call the help stuff from within XPP. For example, you may want to edit this file to set the HOME directory to, say <code> C:\Users\bard </code> or whatever your HOME is.
</ul>
<p>
<hline>
<h2> <center> Customizing defaults </center> </h2
<p>
You may want to customize your defaults so that XPP looks the way you want it to when you run it. I generally get rid of some defaults (such as the Bell) and make the fonts bigger so I can see them. This is done by creating a plain text file in your HOME directory called <code> .xpprc </code>. You can use Notepad or any plain text editor to create the file but make sure it is plain text and make sure that the <code> .txt </code> extension is left off. If you are using the commandline, then there is a very simple text editor called <code> edit </code> that can be called from the commmand line is is perfect for this sort of thing. I provide the following example (<code> .xpprc </code>) in Windows:
<p>
<code>
@ bell=0,grads=0,dwcolor=ffffee,forecolor=222200 <p>
@ ps_lw=15,ps_color=1,ps_font=Helvetica,ps_fsize=18 <p>
@ tutorial=0 <p>
</code>
<p>
This automatically turns the bell off, the fancy menus (grads) off, and the tutorial off. I also change the drawing window color from white to a kind of ivory and the drawing foreground color to a brown.
Finally, I change some of the postscript defaults. You can find out more about these options in the <b> xpp_sum.pdf </b> document.
The only way to change the fonts and the colors of XPP is via the <code> .xpprc </code> file or through the command line since these are processed before the X11 server starts. Sorry.
<p>
<hline>
<p>
<center>
<h2> Creating your own ODE files </h2>
</center>
ODE files are just descriptions of what you want to solve. They are plain text files that have the extension <code> .ode </code> but can have any extension you want as XPP ignores it. There are a few rules that are really important to understand:
<ul>
<li> XPP is case-insensitive so that <code> aBc </code> and <code> ABC </code> are the same to XPP.
<li> There should be a space after the "@" symbol in all options statements
<li> It is generally bad to put spaces between parameter/initial conditions and their values (although this is now OK), so write <code> iapp=0.1 </code> instead of <code> iapp = 0.1 </code>
<li> Any line beginning with <code> # </code> is a comment
<li> Always end your ODE file with <code> done </code> If you do you can write lots of instructions after this that will be ignored by the program but may be useful for the user who reads the ODE file.
<li> There is a specific order to the way things are evaluated in ODEs.
<ul>
<li> Expressions of the form <code> name=expression </code> are evaluated first and in the order they are written, so if one expression makes a reference to another, then make sure they are ordered appropriately
<li> Expressions like <code> special name=expression </code> like convolutions etc.
<li> Differential algebraic expressions
<li> Calls to C code via the <code> export </code> command
<li> Right hand sides of the ODEs
<li> Auxilliary quantities
</ul>
</ul>
Look at the many examples to see how to construct your own ODE files.
<h5> There are many XPP tutorials out there to help you get started </h5>
</body>
</html>
|
Ermentrout/xppaut
|
installonwindows.html
|
HTML
|
gpl-2.0
| 7,041
|
// This may look like C code, but it's really -*- C++ -*-
/*
* Copyright (C) 2008 Emweb bvba, Kessel-Lo, Belgium.
*
* See the LICENSE file for terms of use.
*/
#ifndef WT_DBO_DBACTION_IMPL_H_
#define WT_DBO_DBACTION_IMPL_H_
#include <Wt/Dbo/Exception>
#include <iostream>
#include <boost/lexical_cast.hpp>
namespace Wt {
namespace Dbo {
namespace Impl {
extern std::string WTDBO_API createJoinName(RelationType type,
const char *c1,
const char *c2);
}
template <class C, class Enable>
template <class A>
void persist<C, Enable>::apply(C& obj, A& action)
{
obj.persist(action);
}
/*
* InitSchema
*/
template<class C>
void InitSchema::visit(C& obj)
{
mapping_.surrogateIdFieldName = dbo_traits<C>::surrogateIdField();
mapping_.versionFieldName = dbo_traits<C>::versionField();
persist<C>::apply(obj, *this);
}
template<typename V>
void InitSchema::actId(V& value, const std::string& name, int size)
{
mapping_.naturalIdFieldName = name;
mapping_.naturalIdFieldSize = size;
if (mapping_.surrogateIdFieldName)
throw Exception("Error: Wt::Dbo::id() called for class C "
"with surrogate key: "
"Wt::Dbo::dbo_traits<C>::surrogateIdField() != 0");
idField_ = true;
field(*this, value, name, size);
idField_ = false;
}
template<class C>
void InitSchema::actId(ptr<C>& value, const std::string& name, int size,
int fkConstraints)
{
mapping_.naturalIdFieldName = name;
mapping_.naturalIdFieldSize = size;
if (mapping_.surrogateIdFieldName)
throw Exception("Error: Wt::Dbo::id() called for class C "
"with surrogate key: "
"Wt::Dbo::dbo_traits<C>::surrogateIdField() != 0");
idField_ = true;
actPtr(PtrRef<C>(value, name, size, fkConstraints));
idField_ = false;
}
template<typename V>
void InitSchema::act(const FieldRef<V>& field)
{
int flags = FieldInfo::Mutable | FieldInfo::NeedsQuotes;
if (idField_)
flags |= FieldInfo::NaturalId; // Natural id
if (!foreignKeyName_.empty())
// Foreign key
mapping_.fields.push_back
(FieldInfo(field.name(), &typeid(V), field.sqlType(session_),
foreignKeyTable_, foreignKeyName_,
flags | FieldInfo::ForeignKey, fkConstraints_));
else
// Normal field
mapping_.fields.push_back
(FieldInfo(field.name(), &typeid(V), field.sqlType(session_), flags));
}
template<class C>
void InitSchema::actPtr(const PtrRef<C>& field)
{
Session::Mapping<C> *mapping = session_.getMapping<C>();
bool setName = foreignKeyName_.empty();
if (setName) {
foreignKeyName_ = field.name();
foreignKeyTable_ = mapping->tableName;
fkConstraints_ = field.fkConstraints();
}
field.visit(*this, &session_);
if (setName) {
foreignKeyName_.clear();
foreignKeyTable_.clear();
fkConstraints_ = 0;
}
}
template<class C>
void InitSchema::actWeakPtr(const WeakPtrRef<C>& field)
{
const char *joinTableName = session_.tableName<C>();
std::string joinName = field.joinName();
if (joinName.empty())
joinName = mapping_.tableName;
mapping_.sets.push_back
(Session::SetInfo(joinTableName, ManyToOne, joinName, std::string(), 0));
}
template<class C>
void InitSchema::actCollection(const CollectionRef<C>& field)
{
const char *joinTableName = session_.tableName<C>();
std::string joinName = field.joinName();
if (joinName.empty())
joinName = Impl::createJoinName(field.type(),
mapping_.tableName, joinTableName);
mapping_.sets.push_back
(Session::SetInfo(joinTableName, field.type(), joinName, field.joinId(),
field.fkConstraints()));
}
/*
* DropSchema
*/
template<class C>
void DropSchema::visit(C& obj)
{
persist<C>::apply(obj, *this);
drop(mapping_.tableName);
}
template<typename V>
void DropSchema::actId(V& value, const std::string& name, int size)
{ }
template<class C>
void DropSchema::actId(ptr<C>& value, const std::string& name, int size,
int fkConstraints)
{ }
template<typename V>
void DropSchema::act(const FieldRef<V>& field)
{ }
template<class C>
void DropSchema::actPtr(const PtrRef<C>& field)
{ }
template<class C>
void DropSchema::actWeakPtr(const WeakPtrRef<C>& field)
{
const char *tableName = session_.tableName<C>();
if (tablesDropped_.count(tableName) == 0) {
DropSchema action(session_,
*session_.getMapping(tableName),
tablesDropped_);
C dummy;
action.visit(dummy);
}
}
template<class C>
void DropSchema::actCollection(const CollectionRef<C>& field)
{
if (field.type() == ManyToMany) {
const char *joinTableName = session_.tableName<C>();
std::string joinName = field.joinName();
if (joinName.empty())
joinName = Impl::createJoinName(field.type(),
mapping_.tableName,
joinTableName);
if (tablesDropped_.count(joinName) == 0)
drop(joinName);
} else {
const char *tableName = session_.tableName<C>();
if (tablesDropped_.count(tableName) == 0) {
DropSchema action(session_,
*session_.getMapping(tableName),
tablesDropped_);
C dummy;
action.visit(dummy);
}
}
}
/*
* DboAction
*/
template<class C>
void DboAction::actWeakPtr(const WeakPtrRef<C>& field)
{
Session::SetInfo *setInfo = &mapping_->sets[setIdx_++];
if (dbo_->session()) {
int statementIdx = Session::FirstSqlSelectSet + setStatementIdx_;
const std::string& sql
= dbo_->session()->getStatementSql(mapping_->tableName, statementIdx);
field.value().setRelationData(dbo_, &sql, setInfo);
} else
field.value().setRelationData(dbo_, 0, setInfo);
setStatementIdx_ += 1;
}
template<class C>
void DboAction::actCollection(const CollectionRef<C>& field)
{
Session::SetInfo *setInfo = &mapping_->sets[setIdx_++];
if (dbo_->session()) {
int statementIdx = Session::FirstSqlSelectSet + setStatementIdx_;
const std::string& sql
= dbo_->session()->getStatementSql(mapping_->tableName, statementIdx);
field.value().setRelationData(dbo_, &sql, setInfo);
} else
field.value().setRelationData(dbo_, 0, setInfo);
if (field.type() == ManyToOne)
setStatementIdx_ += 1;
else
setStatementIdx_ += 3;
}
/*
* LoadDbAction
*/
template<typename V>
void LoadBaseAction::act(const FieldRef<V>& field)
{
field.setValue(*session(), statement_, column_++);
}
template<class C>
void LoadBaseAction::actPtr(const PtrRef<C>& field)
{
field.visit(*this, session());
}
template <class C>
LoadDbAction<C>::LoadDbAction(MetaDbo<C>& dbo, Session::Mapping<C>& mapping,
SqlStatement *statement, int& column)
: LoadBaseAction(dbo, mapping, statement, column),
dbo_(dbo)
{ }
template<class C>
void LoadDbAction<C>::visit(C& obj)
{
ScopedStatementUse use(statement_);
bool continueStatement = statement_ != 0;
Session *session = dbo_.session();
if (!continueStatement) {
use(statement_ = session->template getStatement<C>(Session::SqlSelectById));
statement_->reset();
int column = 0;
dbo_.bindId(statement_, column);
statement_->execute();
if (!statement_->nextRow()) {
throw ObjectNotFoundException
(boost::lexical_cast<std::string>(dbo_.id()));
}
}
start();
persist<C>::apply(obj, *this);
if (!continueStatement && statement_->nextRow())
throw Exception("Dbo load: multiple rows for id "
+ boost::lexical_cast<std::string>(dbo_.id()) + " ??");
if (continueStatement)
use(0);
}
template<class C>
template<typename V>
void LoadDbAction<C>::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
dbo_.setId(value);
}
template<class C>
template<class D>
void LoadDbAction<C>::actId(ptr<D>& value, const std::string& name, int size,
int fkConstraints)
{
actPtr(PtrRef<D>(value, name, size, fkConstraints));
dbo_.setId(value);
}
/*
* SaveDbAction
*/
template<class C>
void SaveBaseAction::actPtr(const PtrRef<C>& field)
{
switch (pass_) {
case Dependencies:
field.value().flush();
break;
case Self:
bindNull_ = !field.value();
field.visit(*this, session());
bindNull_ = false;
break;
case Sets:
break;
}
}
template<class C>
void SaveBaseAction::actWeakPtr(const WeakPtrRef<C>& field)
{
switch (pass_) {
case Dependencies:
break;
case Self:
if (isInsert_)
needSetsPass_ = true;
break;
case Sets:
DboAction::actWeakPtr(field);
}
}
template<class C>
void SaveBaseAction::actCollection(const CollectionRef<C>& field)
{
switch (pass_) {
case Dependencies:
break;
case Self:
if (isInsert_ || field.type() == ManyToMany)
needSetsPass_ = true;
break;
case Sets:
if (field.type() == ManyToMany) {
typename collection< ptr<C> >::Activity *activity
= field.value().activity();
if (activity) {
std::set< ptr<C> >& inserted = activity->inserted;
// Sql insert
int statementIdx
= Session::FirstSqlSelectSet + setStatementIdx() + 1;
SqlStatement *statement;
statement = session()->getStatement(mapping().tableName, statementIdx);
{
ScopedStatementUse use(statement);
for (typename std::set< ptr<C> >::iterator i = inserted.begin();
i != inserted.end(); ++i) {
// Make sure it is saved
i->flush();
statement->reset();
int column = 0;
dbo().bindId(statement, column);
i->obj()->bindId(statement, column);
statement->execute();
}
}
std::set< ptr<C> >& erased = activity->erased;
// Sql delete
++statementIdx;
statement = session()->getStatement(mapping().tableName, statementIdx);
{
ScopedStatementUse use(statement);
for (typename std::set< ptr<C> >::iterator i = erased.begin();
i != erased.end(); ++i) {
// Make sure it is saved (?)
i->flush();
statement->reset();
int column = 0;
dbo().bindId(statement, column);
i->obj()->bindId(statement, column);
statement->execute();
}
}
activity->transactionInserted.insert(activity->inserted.begin(),
activity->inserted.end());
activity->transactionErased.insert(activity->erased.begin(),
activity->erased.end());
activity->inserted.clear();
activity->erased.clear();
}
}
DboAction::actCollection(field);
}
}
template <class C>
SaveDbAction<C>::SaveDbAction(MetaDbo<C>& dbo, Session::Mapping<C>& mapping)
: SaveBaseAction(dbo, mapping),
dbo_(dbo)
{ }
template<class C>
void SaveDbAction<C>::visit(C& obj)
{
/*
* (1) Dependencies
*/
startDependencyPass();
persist<C>::apply(obj, *this);
/*
* (2) Self
*/
{
ScopedStatementUse use(statement_);
if (!statement_) {
isInsert_ = dbo_.deletedInTransaction()
|| (dbo_.isNew() && !dbo_.savedInTransaction());
use(statement_ = isInsert_
? dbo_.session()->template getStatement<C>(Session::SqlInsert)
: dbo_.session()->template getStatement<C>(Session::SqlUpdate));
} else
isInsert_ = false;
startSelfPass();
persist<C>::apply(obj, *this);
if (!isInsert_) {
dbo_.bindId(statement_, column_);
if (mapping().versionFieldName) {
// when saved in the transaction, we will be at version() + 1
statement_->bind(column_++, dbo_.version()
+ (dbo_.savedInTransaction() ? 1 : 0));
}
}
exec();
if (!isInsert_) {
int modifiedCount = statement_->affectedRowCount();
if (modifiedCount != 1 && mapping().versionFieldName) {
MetaDbo<C>& dbo = static_cast< MetaDbo<C>& >(dbo_);
std::string idString = boost::lexical_cast<std::string>(dbo.id());
throw StaleObjectException(idString, dbo_.version());
}
}
}
/*
* (3) collections:
* - references in select queries (for ManyToOne and ManyToMany)
* - inserts in ManyToMany collections
* - deletes from ManyToMany collections
*/
if (needSetsPass_) {
startSetsPass();
persist<C>::apply(obj, *this);
}
}
template<class C>
template<typename V>
void SaveDbAction<C>::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
/* Later, we may also want to support id changes ? */
if (pass_ == Self && isInsert_)
dbo_.setId(value);
}
template<class C>
template<class D>
void SaveDbAction<C>::actId(ptr<D>& value, const std::string& name, int size,
int fkConstraints)
{
actPtr(PtrRef<D>(value, name, size, fkConstraints));
/* Later, we may also want to support id changes ? */
if (pass_ == Self && isInsert_)
dbo_.setId(value);
}
/*
* TransactionDoneAction
*/
template<class C>
void TransactionDoneAction::visit(C& obj)
{
persist<C>::apply(obj, *this);
}
template<typename V>
void TransactionDoneAction::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
}
template<class C>
void TransactionDoneAction::actId(ptr<C>& value, const std::string& name,
int size, int fkConstraints)
{
actPtr(PtrRef<C>(value, name, size, fkConstraints));
}
template<typename V>
void TransactionDoneAction::act(const FieldRef<V>& field)
{ }
template<class C>
void TransactionDoneAction::actPtr(const PtrRef<C>& field)
{ }
template<class C>
void TransactionDoneAction::actWeakPtr(const WeakPtrRef<C>& field)
{
if (!success_)
DboAction::actWeakPtr(field);
}
template<class C>
void TransactionDoneAction::actCollection(const CollectionRef<C>& field)
{
if (!success_)
DboAction::actCollection(field);
if (field.type() == ManyToMany) {
if (success_)
field.value().resetActivity();
else {
typename collection< ptr<C> >::Activity *activity
= field.value().activity();
if (activity) {
activity->inserted = activity->transactionInserted;
activity->transactionInserted.clear();
activity->erased = activity->transactionErased;
activity->transactionErased.clear();
}
}
}
}
/*
* SessionAddAction
*/
template<class C>
void SessionAddAction::visit(C& obj)
{
persist<C>::apply(obj, *this);
}
template<typename V>
void SessionAddAction::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
}
template<class C>
void SessionAddAction::actId(ptr<C>& value, const std::string& name,
int size, int fkConstraints)
{
actPtr(PtrRef<C>(value, name, size, fkConstraints));
}
template<typename V>
void SessionAddAction::act(const FieldRef<V>& field)
{ }
template<class C>
void SessionAddAction::actPtr(const PtrRef<C>& field)
{ }
template<class C>
void SessionAddAction::actCollection(const CollectionRef<C>& field)
{
DboAction::actCollection(field);
// FIXME: cascade add ?
}
template<class C>
void SessionAddAction::actWeakPtr(const WeakPtrRef<C>& field)
{
DboAction::actWeakPtr(field);
}
/*
* SetReciproceAction
*/
template<class C>
void SetReciproceAction::visit(C& obj)
{
persist<C>::apply(obj, *this);
}
template<typename V>
void SetReciproceAction::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
}
template<class C>
void SetReciproceAction::actId(ptr<C>& value, const std::string& name,
int size, int fkConstraints)
{
actPtr(PtrRef<C>(value, name, size, fkConstraints));
}
template<typename V>
void SetReciproceAction::act(const FieldRef<V>& field)
{ }
template<class C>
void SetReciproceAction::actPtr(const PtrRef<C>& field)
{
if (field.name() == joinName_)
field.value().resetObj(value_);
}
template<class C>
void SetReciproceAction::actWeakPtr(const WeakPtrRef<C>& field)
{
}
template<class C>
void SetReciproceAction::actCollection(const CollectionRef<C>& field)
{
}
/*
* ToAnysAction
*/
template<class C>
void ToAnysAction::visit(const ptr<C>& obj)
{
if (!session_ && obj.session())
session_ = obj.session();
if (dbo_traits<C>::surrogateIdField())
result_.push_back(obj.id());
if (dbo_traits<C>::versionField())
result_.push_back(obj.version());
if (obj) {
allEmpty_ = false;
persist<C>::apply(const_cast<C&>(*obj), *this);
} else {
C dummy;
allEmpty_ = true;
persist<C>::apply(dummy, *this);
}
}
template <typename V, class Enable = void>
struct ToAny
{
static boost::any convert(const V& v) {
return v;
}
};
template <typename Enum>
struct ToAny<Enum, typename boost::enable_if<boost::is_enum<Enum> >::type>
{
static boost::any convert(const Enum& v) {
return static_cast<int>(v);
}
};
template <typename V>
boost::any convertToAny(const V& v) {
return ToAny<V>::convert(v);
}
template<typename V>
void ToAnysAction::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
}
template<class C>
void ToAnysAction::actId(ptr<C>& value, const std::string& name,
int size, int fkConstraints)
{
actPtr(PtrRef<C>(value, name, size, fkConstraints));
}
template<typename V>
void ToAnysAction::act(const FieldRef<V>& field)
{
if (allEmpty_)
result_.push_back(boost::any());
else
result_.push_back(convertToAny(field.value()));
}
template<class C>
void ToAnysAction::actPtr(const PtrRef<C>& field)
{
field.visit(*this, session());
}
template<class C>
void ToAnysAction::actWeakPtr(const WeakPtrRef<C>& field)
{ }
template<class C>
void ToAnysAction::actCollection(const CollectionRef<C>& field)
{ }
/*
* FromAnyAction
*/
template<class C>
void FromAnyAction::visit(const ptr<C>& obj)
{
if (!session_ && obj.session())
session_ = obj.session();
if (dbo_traits<C>::surrogateIdField()) {
if (index_ == 0)
throw Exception("dbo_result_traits::setValues(): cannot set surrogate "
"id.");
--index_;
}
if (dbo_traits<C>::versionField()) {
if (index_ == 0)
throw Exception("dbo_result_traits::setValues(): "
"cannot set version field.");
--index_;
}
persist<C>::apply(const_cast<C&>(*obj), *this);
if (index_ == -1)
obj.modify();
}
template <typename V, class Enable = void>
struct FromAny
{
static V convert(const boost::any& v) {
return boost::any_cast<V>(v);
}
};
template <typename Enum>
struct FromAny<Enum, typename boost::enable_if<boost::is_enum<Enum> >::type>
{
static Enum convert(const boost::any& v) {
return static_cast<Enum>(boost::any_cast<int>(v));
}
};
template<typename V>
void FromAnyAction::actId(V& value, const std::string& name, int size)
{
field(*this, value, name, size);
}
template<class C>
void FromAnyAction::actId(ptr<C>& value, const std::string& name, int size,
int fkConstraints)
{
actPtr(PtrRef<C>(value, name, size, fkConstraints));
}
template<typename V>
void FromAnyAction::act(const FieldRef<V>& field)
{
if (index_ == 0) {
field.setValue(FromAny<V>::convert(value_));
index_ = -1;
} else if (index_ > 0)
--index_;
}
template<class C>
void FromAnyAction::actPtr(const PtrRef<C>& field)
{
field.visit(*this, session());
}
template<class C>
void FromAnyAction::actWeakPtr(const WeakPtrRef<C>& field)
{ }
template<class C>
void FromAnyAction::actCollection(const CollectionRef<C>& field)
{ }
}
}
#endif // WT_DBO_DBACTION_H_
|
pattop/wt
|
src/Wt/Dbo/DbAction_impl.h
|
C
|
gpl-2.0
| 19,216
|
/*-
* BSD LICENSE
*
* Copyright(c) Broadcom Limited.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Broadcom Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <inttypes.h>
#include <stdbool.h>
#include <rte_dev.h>
#include <rte_ethdev.h>
#include <rte_malloc.h>
#include <rte_cycles.h>
#include "bnxt.h"
#include "bnxt_cpr.h"
#include "bnxt_filter.h"
#include "bnxt_hwrm.h"
#include "bnxt_ring.h"
#include "bnxt_rxq.h"
#include "bnxt_rxr.h"
#include "bnxt_stats.h"
#include "bnxt_txq.h"
#include "bnxt_txr.h"
#include "bnxt_vnic.h"
#include "hsi_struct_def_dpdk.h"
#define DRV_MODULE_NAME "bnxt"
static const char bnxt_version[] =
"Broadcom Cumulus driver " DRV_MODULE_NAME "\n";
#define PCI_VENDOR_ID_BROADCOM 0x14E4
#define BROADCOM_DEV_ID_57301 0x16c8
#define BROADCOM_DEV_ID_57302 0x16c9
#define BROADCOM_DEV_ID_57304_PF 0x16ca
#define BROADCOM_DEV_ID_57304_VF 0x16cb
#define BROADCOM_DEV_ID_57402 0x16d0
#define BROADCOM_DEV_ID_57404 0x16d1
#define BROADCOM_DEV_ID_57406_PF 0x16d2
#define BROADCOM_DEV_ID_57406_VF 0x16d3
#define BROADCOM_DEV_ID_57406_MF 0x16d4
#define BROADCOM_DEV_ID_57314 0x16df
static struct rte_pci_id bnxt_pci_id_map[] = {
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57301) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57302) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57304_PF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57304_VF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57402) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57404) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57406_PF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57406_VF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57406_MF) },
{ RTE_PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, BROADCOM_DEV_ID_57314) },
{ .vendor_id = 0, /* sentinel */ },
};
#define BNXT_ETH_RSS_SUPPORT ( \
ETH_RSS_IPV4 | \
ETH_RSS_NONFRAG_IPV4_TCP | \
ETH_RSS_NONFRAG_IPV4_UDP | \
ETH_RSS_IPV6 | \
ETH_RSS_NONFRAG_IPV6_TCP | \
ETH_RSS_NONFRAG_IPV6_UDP)
/***********************/
/*
* High level utility functions
*/
static void bnxt_free_mem(struct bnxt *bp)
{
bnxt_free_filter_mem(bp);
bnxt_free_vnic_attributes(bp);
bnxt_free_vnic_mem(bp);
bnxt_free_stats(bp);
bnxt_free_tx_rings(bp);
bnxt_free_rx_rings(bp);
bnxt_free_def_cp_ring(bp);
}
static int bnxt_alloc_mem(struct bnxt *bp)
{
int rc;
/* Default completion ring */
rc = bnxt_init_def_ring_struct(bp, SOCKET_ID_ANY);
if (rc)
goto alloc_mem_err;
rc = bnxt_alloc_rings(bp, 0, NULL, NULL,
bp->def_cp_ring, "def_cp");
if (rc)
goto alloc_mem_err;
rc = bnxt_alloc_vnic_mem(bp);
if (rc)
goto alloc_mem_err;
rc = bnxt_alloc_vnic_attributes(bp);
if (rc)
goto alloc_mem_err;
rc = bnxt_alloc_filter_mem(bp);
if (rc)
goto alloc_mem_err;
return 0;
alloc_mem_err:
bnxt_free_mem(bp);
return rc;
}
static int bnxt_init_chip(struct bnxt *bp)
{
unsigned int i, rss_idx, fw_idx;
int rc;
rc = bnxt_alloc_all_hwrm_stat_ctxs(bp);
if (rc) {
RTE_LOG(ERR, PMD, "HWRM stat ctx alloc failure rc: %x\n", rc);
goto err_out;
}
rc = bnxt_alloc_hwrm_rings(bp);
if (rc) {
RTE_LOG(ERR, PMD, "HWRM ring alloc failure rc: %x\n", rc);
goto err_out;
}
rc = bnxt_alloc_all_hwrm_ring_grps(bp);
if (rc) {
RTE_LOG(ERR, PMD, "HWRM ring grp alloc failure: %x\n", rc);
goto err_out;
}
rc = bnxt_mq_rx_configure(bp);
if (rc) {
RTE_LOG(ERR, PMD, "MQ mode configure failure rc: %x\n", rc);
goto err_out;
}
/* VNIC configuration */
for (i = 0; i < bp->nr_vnics; i++) {
struct bnxt_vnic_info *vnic = &bp->vnic_info[i];
rc = bnxt_hwrm_vnic_alloc(bp, vnic);
if (rc) {
RTE_LOG(ERR, PMD, "HWRM vnic alloc failure rc: %x\n",
rc);
goto err_out;
}
rc = bnxt_hwrm_vnic_ctx_alloc(bp, vnic);
if (rc) {
RTE_LOG(ERR, PMD,
"HWRM vnic ctx alloc failure rc: %x\n", rc);
goto err_out;
}
rc = bnxt_hwrm_vnic_cfg(bp, vnic);
if (rc) {
RTE_LOG(ERR, PMD, "HWRM vnic cfg failure rc: %x\n", rc);
goto err_out;
}
rc = bnxt_set_hwrm_vnic_filters(bp, vnic);
if (rc) {
RTE_LOG(ERR, PMD, "HWRM vnic filter failure rc: %x\n",
rc);
goto err_out;
}
if (vnic->rss_table && vnic->hash_type) {
/*
* Fill the RSS hash & redirection table with
* ring group ids for all VNICs
*/
for (rss_idx = 0, fw_idx = 0;
rss_idx < HW_HASH_INDEX_SIZE;
rss_idx++, fw_idx++) {
if (vnic->fw_grp_ids[fw_idx] ==
INVALID_HW_RING_ID)
fw_idx = 0;
vnic->rss_table[rss_idx] =
vnic->fw_grp_ids[fw_idx];
}
rc = bnxt_hwrm_vnic_rss_cfg(bp, vnic);
if (rc) {
RTE_LOG(ERR, PMD,
"HWRM vnic set RSS failure rc: %x\n",
rc);
goto err_out;
}
}
}
rc = bnxt_hwrm_cfa_l2_set_rx_mask(bp, &bp->vnic_info[0]);
if (rc) {
RTE_LOG(ERR, PMD,
"HWRM cfa l2 rx mask failure rc: %x\n", rc);
goto err_out;
}
return 0;
err_out:
bnxt_free_all_hwrm_resources(bp);
return rc;
}
static int bnxt_shutdown_nic(struct bnxt *bp)
{
bnxt_free_all_hwrm_resources(bp);
bnxt_free_all_filters(bp);
bnxt_free_all_vnics(bp);
return 0;
}
static int bnxt_init_nic(struct bnxt *bp)
{
int rc;
bnxt_init_ring_grps(bp);
bnxt_init_vnics(bp);
bnxt_init_filters(bp);
rc = bnxt_init_chip(bp);
if (rc)
return rc;
return 0;
}
/*
* Device configuration and status function
*/
static void bnxt_dev_info_get_op(struct rte_eth_dev *eth_dev,
struct rte_eth_dev_info *dev_info)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
uint16_t max_vnics, i, j, vpool, vrxq;
/* MAC Specifics */
dev_info->max_mac_addrs = MAX_NUM_MAC_ADDR;
dev_info->max_hash_mac_addrs = 0;
/* PF/VF specifics */
if (BNXT_PF(bp)) {
dev_info->max_rx_queues = bp->pf.max_rx_rings;
dev_info->max_tx_queues = bp->pf.max_tx_rings;
dev_info->max_vfs = bp->pf.active_vfs;
dev_info->reta_size = bp->pf.max_rsscos_ctx;
max_vnics = bp->pf.max_vnics;
} else {
dev_info->max_rx_queues = bp->vf.max_rx_rings;
dev_info->max_tx_queues = bp->vf.max_tx_rings;
dev_info->reta_size = bp->vf.max_rsscos_ctx;
max_vnics = bp->vf.max_vnics;
}
/* Fast path specifics */
dev_info->min_rx_bufsize = 1;
dev_info->max_rx_pktlen = BNXT_MAX_MTU + ETHER_HDR_LEN + ETHER_CRC_LEN
+ VLAN_TAG_SIZE;
dev_info->rx_offload_capa = 0;
dev_info->tx_offload_capa = DEV_TX_OFFLOAD_IPV4_CKSUM |
DEV_TX_OFFLOAD_TCP_CKSUM |
DEV_TX_OFFLOAD_UDP_CKSUM |
DEV_TX_OFFLOAD_TCP_TSO;
/* *INDENT-OFF* */
dev_info->default_rxconf = (struct rte_eth_rxconf) {
.rx_thresh = {
.pthresh = 8,
.hthresh = 8,
.wthresh = 0,
},
.rx_free_thresh = 32,
.rx_drop_en = 0,
};
dev_info->default_txconf = (struct rte_eth_txconf) {
.tx_thresh = {
.pthresh = 32,
.hthresh = 0,
.wthresh = 0,
},
.tx_free_thresh = 32,
.tx_rs_thresh = 32,
.txq_flags = ETH_TXQ_FLAGS_NOMULTSEGS |
ETH_TXQ_FLAGS_NOOFFLOADS,
};
/* *INDENT-ON* */
/*
* TODO: default_rxconf, default_txconf, rx_desc_lim, and tx_desc_lim
* need further investigation.
*/
/* VMDq resources */
vpool = 64; /* ETH_64_POOLS */
vrxq = 128; /* ETH_VMDQ_DCB_NUM_QUEUES */
for (i = 0; i < 4; vpool >>= 1, i++) {
if (max_vnics > vpool) {
for (j = 0; j < 5; vrxq >>= 1, j++) {
if (dev_info->max_rx_queues > vrxq) {
if (vpool > vrxq)
vpool = vrxq;
goto found;
}
}
/* Not enough resources to support VMDq */
break;
}
}
/* Not enough resources to support VMDq */
vpool = 0;
vrxq = 0;
found:
dev_info->max_vmdq_pools = vpool;
dev_info->vmdq_queue_num = vrxq;
dev_info->vmdq_pool_base = 0;
dev_info->vmdq_queue_base = 0;
}
/* Configure the device based on the configuration provided */
static int bnxt_dev_configure_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
int rc;
bp->rx_queues = (void *)eth_dev->data->rx_queues;
bp->tx_queues = (void *)eth_dev->data->tx_queues;
/* Inherit new configurations */
bp->rx_nr_rings = eth_dev->data->nb_rx_queues;
bp->tx_nr_rings = eth_dev->data->nb_tx_queues;
bp->rx_cp_nr_rings = bp->rx_nr_rings;
bp->tx_cp_nr_rings = bp->tx_nr_rings;
if (eth_dev->data->dev_conf.rxmode.jumbo_frame)
eth_dev->data->mtu =
eth_dev->data->dev_conf.rxmode.max_rx_pkt_len -
ETHER_HDR_LEN - ETHER_CRC_LEN - VLAN_TAG_SIZE;
rc = bnxt_set_hwrm_link_config(bp, true);
return rc;
}
static int bnxt_dev_start_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
int rc;
rc = bnxt_hwrm_func_reset(bp);
if (rc) {
RTE_LOG(ERR, PMD, "hwrm chip reset failure rc: %x\n", rc);
rc = -1;
goto error;
}
rc = bnxt_alloc_mem(bp);
if (rc)
goto error;
rc = bnxt_init_nic(bp);
if (rc)
goto error;
return 0;
error:
bnxt_shutdown_nic(bp);
bnxt_free_tx_mbufs(bp);
bnxt_free_rx_mbufs(bp);
bnxt_free_mem(bp);
return rc;
}
static int bnxt_dev_set_link_up_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
eth_dev->data->dev_link.link_status = 1;
bnxt_set_hwrm_link_config(bp, true);
return 0;
}
static int bnxt_dev_set_link_down_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
eth_dev->data->dev_link.link_status = 0;
bnxt_set_hwrm_link_config(bp, false);
return 0;
}
static void bnxt_dev_close_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
bnxt_free_tx_mbufs(bp);
bnxt_free_rx_mbufs(bp);
bnxt_free_mem(bp);
rte_free(eth_dev->data->mac_addrs);
}
/* Unload the driver, release resources */
static void bnxt_dev_stop_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
if (bp->eth_dev->data->dev_started) {
/* TBD: STOP HW queues DMA */
eth_dev->data->dev_link.link_status = 0;
}
bnxt_shutdown_nic(bp);
}
static void bnxt_mac_addr_remove_op(struct rte_eth_dev *eth_dev,
uint32_t index)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
uint64_t pool_mask = eth_dev->data->mac_pool_sel[index];
struct bnxt_vnic_info *vnic;
struct bnxt_filter_info *filter, *temp_filter;
int i;
/*
* Loop through all VNICs from the specified filter flow pools to
* remove the corresponding MAC addr filter
*/
for (i = 0; i < MAX_FF_POOLS; i++) {
if (!(pool_mask & (1 << i)))
continue;
STAILQ_FOREACH(vnic, &bp->ff_pool[i], next) {
filter = STAILQ_FIRST(&vnic->filter);
while (filter) {
temp_filter = STAILQ_NEXT(filter, next);
if (filter->mac_index == index) {
STAILQ_REMOVE(&vnic->filter, filter,
bnxt_filter_info, next);
bnxt_hwrm_clear_filter(bp, filter);
filter->mac_index = INVALID_MAC_INDEX;
memset(&filter->l2_addr, 0,
ETHER_ADDR_LEN);
STAILQ_INSERT_TAIL(
&bp->free_filter_list,
filter, next);
}
filter = temp_filter;
}
}
}
}
static void bnxt_mac_addr_add_op(struct rte_eth_dev *eth_dev,
struct ether_addr *mac_addr,
uint32_t index, uint32_t pool)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic = STAILQ_FIRST(&bp->ff_pool[pool]);
struct bnxt_filter_info *filter;
if (!vnic) {
RTE_LOG(ERR, PMD, "VNIC not found for pool %d!\n", pool);
return;
}
/* Attach requested MAC address to the new l2_filter */
STAILQ_FOREACH(filter, &vnic->filter, next) {
if (filter->mac_index == index) {
RTE_LOG(ERR, PMD,
"MAC addr already existed for pool %d\n", pool);
return;
}
}
filter = bnxt_alloc_filter(bp);
if (!filter) {
RTE_LOG(ERR, PMD, "L2 filter alloc failed\n");
return;
}
STAILQ_INSERT_TAIL(&vnic->filter, filter, next);
filter->mac_index = index;
memcpy(filter->l2_addr, mac_addr, ETHER_ADDR_LEN);
bnxt_hwrm_set_filter(bp, vnic, filter);
}
static int bnxt_link_update_op(struct rte_eth_dev *eth_dev,
int wait_to_complete)
{
int rc = 0;
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct rte_eth_link new;
unsigned int cnt = BNXT_LINK_WAIT_CNT;
memset(&new, 0, sizeof(new));
do {
/* Retrieve link info from hardware */
rc = bnxt_get_hwrm_link_config(bp, &new);
if (rc) {
new.link_speed = ETH_LINK_SPEED_100M;
new.link_duplex = ETH_LINK_FULL_DUPLEX;
RTE_LOG(ERR, PMD,
"Failed to retrieve link rc = 0x%x!", rc);
goto out;
}
if (!wait_to_complete)
break;
rte_delay_ms(BNXT_LINK_WAIT_INTERVAL);
} while (!new.link_status && cnt--);
/* Timed out or success */
if (new.link_status) {
/* Update only if success */
eth_dev->data->dev_link.link_duplex = new.link_duplex;
eth_dev->data->dev_link.link_speed = new.link_speed;
}
eth_dev->data->dev_link.link_status = new.link_status;
out:
return rc;
}
static void bnxt_promiscuous_enable_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic;
if (bp->vnic_info == NULL)
return;
vnic = &bp->vnic_info[0];
vnic->flags |= BNXT_VNIC_INFO_PROMISC;
bnxt_hwrm_cfa_l2_set_rx_mask(bp, vnic);
}
static void bnxt_promiscuous_disable_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic;
if (bp->vnic_info == NULL)
return;
vnic = &bp->vnic_info[0];
vnic->flags &= ~BNXT_VNIC_INFO_PROMISC;
bnxt_hwrm_cfa_l2_set_rx_mask(bp, vnic);
}
static void bnxt_allmulticast_enable_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic;
if (bp->vnic_info == NULL)
return;
vnic = &bp->vnic_info[0];
vnic->flags |= BNXT_VNIC_INFO_ALLMULTI;
bnxt_hwrm_cfa_l2_set_rx_mask(bp, vnic);
}
static void bnxt_allmulticast_disable_op(struct rte_eth_dev *eth_dev)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic;
if (bp->vnic_info == NULL)
return;
vnic = &bp->vnic_info[0];
vnic->flags &= ~BNXT_VNIC_INFO_ALLMULTI;
bnxt_hwrm_cfa_l2_set_rx_mask(bp, vnic);
}
static int bnxt_reta_update_op(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_reta_entry64 *reta_conf,
uint16_t reta_size)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct rte_eth_conf *dev_conf = &bp->eth_dev->data->dev_conf;
struct bnxt_vnic_info *vnic;
int i;
if (!(dev_conf->rxmode.mq_mode & ETH_MQ_RX_RSS_FLAG))
return -EINVAL;
if (reta_size != HW_HASH_INDEX_SIZE) {
RTE_LOG(ERR, PMD, "The configured hash table lookup size "
"(%d) must equal the size supported by the hardware "
"(%d)\n", reta_size, HW_HASH_INDEX_SIZE);
return -EINVAL;
}
/* Update the RSS VNIC(s) */
for (i = 0; i < MAX_FF_POOLS; i++) {
STAILQ_FOREACH(vnic, &bp->ff_pool[i], next) {
memcpy(vnic->rss_table, reta_conf, reta_size);
bnxt_hwrm_vnic_rss_cfg(bp, vnic);
}
}
return 0;
}
static int bnxt_reta_query_op(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_reta_entry64 *reta_conf,
uint16_t reta_size)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic = &bp->vnic_info[0];
/* Retrieve from the default VNIC */
if (!vnic)
return -EINVAL;
if (!vnic->rss_table)
return -EINVAL;
if (reta_size != HW_HASH_INDEX_SIZE) {
RTE_LOG(ERR, PMD, "The configured hash table lookup size "
"(%d) must equal the size supported by the hardware "
"(%d)\n", reta_size, HW_HASH_INDEX_SIZE);
return -EINVAL;
}
/* EW - need to revisit here copying from u64 to u16 */
memcpy(reta_conf, vnic->rss_table, reta_size);
return 0;
}
static int bnxt_rss_hash_update_op(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_conf *rss_conf)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct rte_eth_conf *dev_conf = &bp->eth_dev->data->dev_conf;
struct bnxt_vnic_info *vnic;
uint16_t hash_type = 0;
int i;
/*
* If RSS enablement were different than dev_configure,
* then return -EINVAL
*/
if (dev_conf->rxmode.mq_mode & ETH_MQ_RX_RSS_FLAG) {
if (!rss_conf->rss_hf)
return -EINVAL;
} else {
if (rss_conf->rss_hf & BNXT_ETH_RSS_SUPPORT)
return -EINVAL;
}
if (rss_conf->rss_hf & ETH_RSS_IPV4)
hash_type |= HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_IPV4;
if (rss_conf->rss_hf & ETH_RSS_NONFRAG_IPV4_TCP)
hash_type |= HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_TCP_IPV4;
if (rss_conf->rss_hf & ETH_RSS_NONFRAG_IPV4_UDP)
hash_type |= HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_UDP_IPV4;
if (rss_conf->rss_hf & ETH_RSS_IPV6)
hash_type |= HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_IPV6;
if (rss_conf->rss_hf & ETH_RSS_NONFRAG_IPV6_TCP)
hash_type |= HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_TCP_IPV6;
if (rss_conf->rss_hf & ETH_RSS_NONFRAG_IPV6_UDP)
hash_type |= HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_UDP_IPV6;
/* Update the RSS VNIC(s) */
for (i = 0; i < MAX_FF_POOLS; i++) {
STAILQ_FOREACH(vnic, &bp->ff_pool[i], next) {
vnic->hash_type = hash_type;
/*
* Use the supplied key if the key length is
* acceptable and the rss_key is not NULL
*/
if (rss_conf->rss_key &&
rss_conf->rss_key_len <= HW_HASH_KEY_SIZE)
memcpy(vnic->rss_hash_key, rss_conf->rss_key,
rss_conf->rss_key_len);
bnxt_hwrm_vnic_rss_cfg(bp, vnic);
}
}
return 0;
}
static int bnxt_rss_hash_conf_get_op(struct rte_eth_dev *eth_dev,
struct rte_eth_rss_conf *rss_conf)
{
struct bnxt *bp = (struct bnxt *)eth_dev->data->dev_private;
struct bnxt_vnic_info *vnic = &bp->vnic_info[0];
int len;
uint32_t hash_types;
/* RSS configuration is the same for all VNICs */
if (vnic && vnic->rss_hash_key) {
if (rss_conf->rss_key) {
len = rss_conf->rss_key_len <= HW_HASH_KEY_SIZE ?
rss_conf->rss_key_len : HW_HASH_KEY_SIZE;
memcpy(rss_conf->rss_key, vnic->rss_hash_key, len);
}
hash_types = vnic->hash_type;
rss_conf->rss_hf = 0;
if (hash_types & HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_IPV4) {
rss_conf->rss_hf |= ETH_RSS_IPV4;
hash_types &= ~HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_IPV4;
}
if (hash_types & HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_TCP_IPV4) {
rss_conf->rss_hf |= ETH_RSS_NONFRAG_IPV4_TCP;
hash_types &=
~HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_TCP_IPV4;
}
if (hash_types & HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_UDP_IPV4) {
rss_conf->rss_hf |= ETH_RSS_NONFRAG_IPV4_UDP;
hash_types &=
~HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_UDP_IPV4;
}
if (hash_types & HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_IPV6) {
rss_conf->rss_hf |= ETH_RSS_IPV6;
hash_types &= ~HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_IPV6;
}
if (hash_types & HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_TCP_IPV6) {
rss_conf->rss_hf |= ETH_RSS_NONFRAG_IPV6_TCP;
hash_types &=
~HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_TCP_IPV6;
}
if (hash_types & HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_UDP_IPV6) {
rss_conf->rss_hf |= ETH_RSS_NONFRAG_IPV6_UDP;
hash_types &=
~HWRM_VNIC_RSS_CFG_INPUT_HASH_TYPE_UDP_IPV6;
}
if (hash_types) {
RTE_LOG(ERR, PMD,
"Unknwon RSS config from firmware (%08x), RSS disabled",
vnic->hash_type);
return -ENOTSUP;
}
} else {
rss_conf->rss_hf = 0;
}
return 0;
}
static int bnxt_flow_ctrl_get_op(struct rte_eth_dev *dev,
struct rte_eth_fc_conf *fc_conf __rte_unused)
{
struct bnxt *bp = (struct bnxt *)dev->data->dev_private;
struct rte_eth_link link_info;
int rc;
rc = bnxt_get_hwrm_link_config(bp, &link_info);
if (rc)
return rc;
memset(fc_conf, 0, sizeof(*fc_conf));
if (bp->link_info.auto_pause)
fc_conf->autoneg = 1;
switch (bp->link_info.pause) {
case 0:
fc_conf->mode = RTE_FC_NONE;
break;
case HWRM_PORT_PHY_QCFG_OUTPUT_PAUSE_TX:
fc_conf->mode = RTE_FC_TX_PAUSE;
break;
case HWRM_PORT_PHY_QCFG_OUTPUT_PAUSE_RX:
fc_conf->mode = RTE_FC_RX_PAUSE;
break;
case (HWRM_PORT_PHY_QCFG_OUTPUT_PAUSE_TX |
HWRM_PORT_PHY_QCFG_OUTPUT_PAUSE_RX):
fc_conf->mode = RTE_FC_FULL;
break;
}
return 0;
}
static int bnxt_flow_ctrl_set_op(struct rte_eth_dev *dev,
struct rte_eth_fc_conf *fc_conf)
{
struct bnxt *bp = (struct bnxt *)dev->data->dev_private;
switch (fc_conf->mode) {
case RTE_FC_NONE:
bp->link_info.auto_pause = 0;
bp->link_info.force_pause = 0;
break;
case RTE_FC_RX_PAUSE:
if (fc_conf->autoneg) {
bp->link_info.auto_pause =
HWRM_PORT_PHY_CFG_INPUT_AUTO_PAUSE_RX;
bp->link_info.force_pause = 0;
} else {
bp->link_info.auto_pause = 0;
bp->link_info.force_pause =
HWRM_PORT_PHY_CFG_INPUT_FORCE_PAUSE_RX;
}
break;
case RTE_FC_TX_PAUSE:
if (fc_conf->autoneg) {
bp->link_info.auto_pause =
HWRM_PORT_PHY_CFG_INPUT_AUTO_PAUSE_TX;
bp->link_info.force_pause = 0;
} else {
bp->link_info.auto_pause = 0;
bp->link_info.force_pause =
HWRM_PORT_PHY_CFG_INPUT_FORCE_PAUSE_TX;
}
break;
case RTE_FC_FULL:
if (fc_conf->autoneg) {
bp->link_info.auto_pause =
HWRM_PORT_PHY_CFG_INPUT_AUTO_PAUSE_TX |
HWRM_PORT_PHY_CFG_INPUT_AUTO_PAUSE_RX;
bp->link_info.force_pause = 0;
} else {
bp->link_info.auto_pause = 0;
bp->link_info.force_pause =
HWRM_PORT_PHY_CFG_INPUT_FORCE_PAUSE_TX |
HWRM_PORT_PHY_CFG_INPUT_FORCE_PAUSE_RX;
}
break;
}
return bnxt_set_hwrm_link_config(bp, true);
}
/*
* Initialization
*/
static struct eth_dev_ops bnxt_dev_ops = {
.dev_infos_get = bnxt_dev_info_get_op,
.dev_close = bnxt_dev_close_op,
.dev_configure = bnxt_dev_configure_op,
.dev_start = bnxt_dev_start_op,
.dev_stop = bnxt_dev_stop_op,
.dev_set_link_up = bnxt_dev_set_link_up_op,
.dev_set_link_down = bnxt_dev_set_link_down_op,
.stats_get = bnxt_stats_get_op,
.stats_reset = bnxt_stats_reset_op,
.rx_queue_setup = bnxt_rx_queue_setup_op,
.rx_queue_release = bnxt_rx_queue_release_op,
.tx_queue_setup = bnxt_tx_queue_setup_op,
.tx_queue_release = bnxt_tx_queue_release_op,
.reta_update = bnxt_reta_update_op,
.reta_query = bnxt_reta_query_op,
.rss_hash_update = bnxt_rss_hash_update_op,
.rss_hash_conf_get = bnxt_rss_hash_conf_get_op,
.link_update = bnxt_link_update_op,
.promiscuous_enable = bnxt_promiscuous_enable_op,
.promiscuous_disable = bnxt_promiscuous_disable_op,
.allmulticast_enable = bnxt_allmulticast_enable_op,
.allmulticast_disable = bnxt_allmulticast_disable_op,
.mac_addr_add = bnxt_mac_addr_add_op,
.mac_addr_remove = bnxt_mac_addr_remove_op,
.flow_ctrl_get = bnxt_flow_ctrl_get_op,
.flow_ctrl_set = bnxt_flow_ctrl_set_op,
};
static bool bnxt_vf_pciid(uint16_t id)
{
if (id == BROADCOM_DEV_ID_57304_VF ||
id == BROADCOM_DEV_ID_57406_VF)
return true;
return false;
}
static int bnxt_init_board(struct rte_eth_dev *eth_dev)
{
int rc;
struct bnxt *bp = eth_dev->data->dev_private;
/* enable device (incl. PCI PM wakeup), and bus-mastering */
if (!eth_dev->pci_dev->mem_resource[0].addr) {
RTE_LOG(ERR, PMD,
"Cannot find PCI device base address, aborting\n");
rc = -ENODEV;
goto init_err_disable;
}
bp->eth_dev = eth_dev;
bp->pdev = eth_dev->pci_dev;
bp->bar0 = (void *)eth_dev->pci_dev->mem_resource[0].addr;
if (!bp->bar0) {
RTE_LOG(ERR, PMD, "Cannot map device registers, aborting\n");
rc = -ENOMEM;
goto init_err_release;
}
return 0;
init_err_release:
if (bp->bar0)
bp->bar0 = NULL;
init_err_disable:
return rc;
}
static int
bnxt_dev_init(struct rte_eth_dev *eth_dev)
{
static int version_printed;
struct bnxt *bp;
int rc;
if (version_printed++ == 0)
RTE_LOG(INFO, PMD, "%s", bnxt_version);
if (eth_dev->pci_dev->addr.function >= 2 &&
eth_dev->pci_dev->addr.function < 4) {
RTE_LOG(ERR, PMD, "Function not enabled %x:\n",
eth_dev->pci_dev->addr.function);
rc = -ENOMEM;
goto error;
}
rte_eth_copy_pci_info(eth_dev, eth_dev->pci_dev);
bp = eth_dev->data->dev_private;
if (bnxt_vf_pciid(eth_dev->pci_dev->id.device_id))
bp->flags |= BNXT_FLAG_VF;
rc = bnxt_init_board(eth_dev);
if (rc) {
RTE_LOG(ERR, PMD,
"Board initialization failed rc: %x\n", rc);
goto error;
}
eth_dev->dev_ops = &bnxt_dev_ops;
eth_dev->rx_pkt_burst = &bnxt_recv_pkts;
eth_dev->tx_pkt_burst = &bnxt_xmit_pkts;
rc = bnxt_alloc_hwrm_resources(bp);
if (rc) {
RTE_LOG(ERR, PMD,
"hwrm resource allocation failure rc: %x\n", rc);
goto error_free;
}
rc = bnxt_hwrm_ver_get(bp);
if (rc)
goto error_free;
bnxt_hwrm_queue_qportcfg(bp);
/* Get the MAX capabilities for this function */
rc = bnxt_hwrm_func_qcaps(bp);
if (rc) {
RTE_LOG(ERR, PMD, "hwrm query capability failure rc: %x\n", rc);
goto error_free;
}
eth_dev->data->mac_addrs = rte_zmalloc("bnxt_mac_addr_tbl",
ETHER_ADDR_LEN * MAX_NUM_MAC_ADDR, 0);
if (eth_dev->data->mac_addrs == NULL) {
RTE_LOG(ERR, PMD,
"Failed to alloc %u bytes needed to store MAC addr tbl",
ETHER_ADDR_LEN * MAX_NUM_MAC_ADDR);
rc = -ENOMEM;
goto error_free;
}
/* Copy the permanent MAC from the qcap response address now. */
if (BNXT_PF(bp))
memcpy(bp->mac_addr, bp->pf.mac_addr, sizeof(bp->mac_addr));
else
memcpy(bp->mac_addr, bp->vf.mac_addr, sizeof(bp->mac_addr));
memcpy(ð_dev->data->mac_addrs[0], bp->mac_addr, ETHER_ADDR_LEN);
bp->grp_info = rte_zmalloc("bnxt_grp_info",
sizeof(*bp->grp_info) * bp->max_ring_grps, 0);
if (!bp->grp_info) {
RTE_LOG(ERR, PMD,
"Failed to alloc %zu bytes needed to store group info table\n",
sizeof(*bp->grp_info) * bp->max_ring_grps);
rc = -ENOMEM;
goto error_free;
}
rc = bnxt_hwrm_func_driver_register(bp, 0,
bp->pf.vf_req_fwd);
if (rc) {
RTE_LOG(ERR, PMD,
"Failed to register driver");
rc = -EBUSY;
goto error_free;
}
RTE_LOG(INFO, PMD,
DRV_MODULE_NAME " found at mem %" PRIx64 ", node addr %pM\n",
eth_dev->pci_dev->mem_resource[0].phys_addr,
eth_dev->pci_dev->mem_resource[0].addr);
return 0;
error_free:
eth_dev->driver->eth_dev_uninit(eth_dev);
error:
return rc;
}
static int
bnxt_dev_uninit(struct rte_eth_dev *eth_dev) {
struct bnxt *bp = eth_dev->data->dev_private;
int rc;
if (eth_dev->data->mac_addrs)
rte_free(eth_dev->data->mac_addrs);
if (bp->grp_info)
rte_free(bp->grp_info);
rc = bnxt_hwrm_func_driver_unregister(bp, 0);
bnxt_free_hwrm_resources(bp);
return rc;
}
static struct eth_driver bnxt_rte_pmd = {
.pci_drv = {
.name = "rte_" DRV_MODULE_NAME "_pmd",
.id_table = bnxt_pci_id_map,
.drv_flags = RTE_PCI_DRV_NEED_MAPPING,
},
.eth_dev_init = bnxt_dev_init,
.eth_dev_uninit = bnxt_dev_uninit,
.dev_private_size = sizeof(struct bnxt),
};
static int bnxt_rte_pmd_init(const char *name, const char *params __rte_unused)
{
RTE_LOG(INFO, PMD, "bnxt_rte_pmd_init() called for %s\n", name);
rte_eth_driver_register(&bnxt_rte_pmd);
return 0;
}
static struct rte_driver bnxt_pmd_drv = {
.type = PMD_PDEV,
.init = bnxt_rte_pmd_init,
};
PMD_REGISTER_DRIVER(bnxt_pmd_drv, bnxt);
DRIVER_REGISTER_PCI_TABLE(bnxt, bnxt_pci_id_map);
|
phyorat/Pktgen-user-payload
|
drivers/net/bnxt/bnxt_ethdev.c
|
C
|
gpl-2.0
| 28,223
|
/*
* Customer code to add GPIO control during WLAN start/stop
* Copyright (C) 1999-2011, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: dhd_custom_gpio.c 275786 2011-08-04 22:42:42Z $
*/
#include <typedefs.h>
#include <linuxver.h>
#include <osl.h>
#include <bcmutils.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <wlioctl.h>
#include <wl_iw.h>
#define WL_ERROR(x) printf x
#define WL_TRACE(x)
#if defined (CONFIG_MMC_SUN6I) || defined (CONFIG_MMC_SUN7I)
#define CUSTOMER_AW
#define SDIO_ID 1
extern void sw_mci_rescan_card(unsigned id, unsigned insert);
#ifdef CONFIG_MMC_SDIOPM
extern int mmc_pm_get_mod_type(void);
extern int mmc_pm_gpio_ctrl(char* name, int level);
extern int mmc_pm_get_io_val(char* name);
#else
static int mmc_pm_get_mod_type(void){return 0;}
static int mmc_pm_gpio_ctrl(char* name, int level){return -1;}
static int mmc_pm_get_io_val(char* name){return -1;}
#endif
#endif
#ifdef CUSTOMER_HW
extern void bcm_wlan_power_off(int);
extern void bcm_wlan_power_on(int);
#endif /* CUSTOMER_HW */
#if defined(CUSTOMER_HW2)
#ifdef CONFIG_WIFI_CONTROL_FUNC
int wifi_set_power(int on, unsigned long msec);
int wifi_get_irq_number(unsigned long *irq_flags_ptr);
int wifi_get_mac_addr(unsigned char *buf);
void *wifi_get_country_code(char *ccode);
#else
int wifi_set_power(int on, unsigned long msec) { return -1; }
int wifi_get_irq_number(unsigned long *irq_flags_ptr) { return -1; }
int wifi_get_mac_addr(unsigned char *buf) { return -1; }
void *wifi_get_country_code(char *ccode) { return NULL; }
#endif /* CONFIG_WIFI_CONTROL_FUNC */
#endif /* CUSTOMER_HW2 */
#if defined(OOB_INTR_ONLY)
#if defined(BCMLXSDMMC)
extern int sdioh_mmc_irq(int irq);
#endif /* (BCMLXSDMMC) */
#ifdef CUSTOMER_HW3
#include <mach/gpio.h>
#endif
/* Customer specific Host GPIO defintion */
static int dhd_oob_gpio_num = -1;
module_param(dhd_oob_gpio_num, int, 0644);
MODULE_PARM_DESC(dhd_oob_gpio_num, "DHD oob gpio number");
/* This function will return:
* 1) return : Host gpio interrupt number per customer platform
* 2) irq_flags_ptr : Type of Host interrupt as Level or Edge
*
* NOTE :
* Customer should check his platform definitions
* and his Host Interrupt spec
* to figure out the proper setting for his platform.
* Broadcom provides just reference settings as example.
*
*/
int dhd_customer_oob_irq_map(unsigned long *irq_flags_ptr)
{
int host_oob_irq = 0;
#ifdef CUSTOMER_HW2
host_oob_irq = wifi_get_irq_number(irq_flags_ptr);
#else
#if defined(CUSTOM_OOB_GPIO_NUM)
if (dhd_oob_gpio_num < 0) {
dhd_oob_gpio_num = CUSTOM_OOB_GPIO_NUM;
}
#endif /* CUSTOMER_HW2 */
if (dhd_oob_gpio_num < 0) {
WL_ERROR(("%s: ERROR customer specific Host GPIO is NOT defined \n",
__FUNCTION__));
return (dhd_oob_gpio_num);
}
WL_ERROR(("%s: customer specific Host GPIO number is (%d)\n",
__FUNCTION__, dhd_oob_gpio_num));
#if defined CUSTOMER_HW
host_oob_irq = MSM_GPIO_TO_INT(dhd_oob_gpio_num);
#elif defined CUSTOMER_HW3
gpio_request(dhd_oob_gpio_num, "oob irq");
host_oob_irq = gpio_to_irq(dhd_oob_gpio_num);
gpio_direction_input(dhd_oob_gpio_num);
#endif /* CUSTOMER_HW */
#endif /* CUSTOMER_HW2 */
return (host_oob_irq);
}
#endif /* defined(OOB_INTR_ONLY) */
/* Customer function to control hw specific wlan gpios */
void
dhd_customer_gpio_wlan_ctrl(int onoff)
{
switch (onoff) {
case WLAN_RESET_OFF:
WL_TRACE(("%s: call customer specific GPIO to insert WLAN RESET\n",
__FUNCTION__));
#ifdef CUSTOMER_AW
mmc_pm_gpio_ctrl("bcm40183_wl_regon", 0);
#endif
#ifdef CUSTOMER_HW
bcm_wlan_power_off(2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
wifi_set_power(0, 0);
#endif
WL_ERROR(("=========== WLAN placed in RESET ========\n"));
break;
case WLAN_RESET_ON:
WL_TRACE(("%s: callc customer specific GPIO to remove WLAN RESET\n",
__FUNCTION__));
#ifdef CUSTOMER_AW
mmc_pm_gpio_ctrl("bcm40183_wl_regon", 1);
#endif
#ifdef CUSTOMER_HW
bcm_wlan_power_on(2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
wifi_set_power(1, 0);
#endif
WL_ERROR(("=========== WLAN going back to live ========\n"));
break;
case WLAN_POWER_OFF:
WL_TRACE(("%s: call customer specific GPIO to turn off WL_REG_ON\n",
__FUNCTION__));
#ifdef CUSTOMER_AW
mmc_pm_gpio_ctrl("bcm40183_wl_regon", 1);
sw_mci_rescan_card(SDIO_ID, 0);
#endif
#ifdef CUSTOMER_HW
bcm_wlan_power_off(1);
#endif /* CUSTOMER_HW */
break;
case WLAN_POWER_ON:
WL_TRACE(("%s: call customer specific GPIO to turn on WL_REG_ON\n",
__FUNCTION__));
#ifdef CUSTOMER_AW
mmc_pm_gpio_ctrl("bcm40183_wl_regon", 1);
#endif
#ifdef CUSTOMER_HW
bcm_wlan_power_on(1);
/* Lets customer power to get stable */
#endif /* CUSTOMER_HW */
OSL_DELAY(200);
#ifdef CUSTOMER_AW
sw_mci_rescan_card(SDIO_ID, 1);
#endif
break;
}
}
#ifdef GET_CUSTOM_MAC_ENABLE
/* Function to get custom MAC address */
int
dhd_custom_get_mac_address(unsigned char *buf)
{
int ret = 0;
WL_TRACE(("%s Enter\n", __FUNCTION__));
if (!buf)
return -EINVAL;
/* Customer access to MAC address stored outside of DHD driver */
#if defined(CUSTOMER_HW2) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 35))
ret = wifi_get_mac_addr(buf);
#endif
#ifdef EXAMPLE_GET_MAC
/* EXAMPLE code */
{
struct ether_addr ea_example = {{0x00, 0x11, 0x22, 0x33, 0x44, 0xFF}};
bcopy((char *)&ea_example, buf, sizeof(struct ether_addr));
}
#endif /* EXAMPLE_GET_MAC */
return ret;
}
#endif /* GET_CUSTOM_MAC_ENABLE */
/* Customized Locale table : OPTIONAL feature */
const struct cntry_locales_custom translate_custom_table[] = {
/* Table should be filled out based on custom platform regulatory requirement */
#ifdef EXAMPLE_TABLE
{"", "XY", 4}, /* Universal if Country code is unknown or empty */
{"US", "US", 69}, /* input ISO "US" to : US regrev 69 */
{"CA", "US", 69}, /* input ISO "CA" to : US regrev 69 */
{"EU", "EU", 5}, /* European union countries to : EU regrev 05 */
{"AT", "EU", 5},
{"BE", "EU", 5},
{"BG", "EU", 5},
{"CY", "EU", 5},
{"CZ", "EU", 5},
{"DK", "EU", 5},
{"EE", "EU", 5},
{"FI", "EU", 5},
{"FR", "EU", 5},
{"DE", "EU", 5},
{"GR", "EU", 5},
{"HU", "EU", 5},
{"IE", "EU", 5},
{"IT", "EU", 5},
{"LV", "EU", 5},
{"LI", "EU", 5},
{"LT", "EU", 5},
{"LU", "EU", 5},
{"MT", "EU", 5},
{"NL", "EU", 5},
{"PL", "EU", 5},
{"PT", "EU", 5},
{"RO", "EU", 5},
{"SK", "EU", 5},
{"SI", "EU", 5},
{"ES", "EU", 5},
{"SE", "EU", 5},
{"GB", "EU", 5},
{"KR", "XY", 3},
{"AU", "XY", 3},
{"CN", "XY", 3}, /* input ISO "CN" to : XY regrev 03 */
{"TW", "XY", 3},
{"AR", "XY", 3},
{"MX", "XY", 3},
{"IL", "IL", 0},
{"CH", "CH", 0},
{"TR", "TR", 0},
{"NO", "NO", 0},
#endif /* EXMAPLE_TABLE */
};
/* Customized Locale convertor
* input : ISO 3166-1 country abbreviation
* output: customized cspec
*/
void get_customized_country_code(char *country_iso_code, wl_country_t *cspec)
{
#if defined(CUSTOMER_HW2) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 39))
struct cntry_locales_custom *cloc_ptr;
if (!cspec)
return;
cloc_ptr = wifi_get_country_code(country_iso_code);
if (cloc_ptr) {
strlcpy(cspec->ccode, cloc_ptr->custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = cloc_ptr->custom_locale_rev;
}
return;
#else
int size, i;
size = ARRAYSIZE(translate_custom_table);
if (cspec == 0)
return;
if (size == 0)
return;
for (i = 0; i < size; i++) {
if (strcmp(country_iso_code, translate_custom_table[i].iso_abbrev) == 0) {
memcpy(cspec->ccode,
translate_custom_table[i].custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = translate_custom_table[i].custom_locale_rev;
return;
}
}
#ifdef EXAMPLE_TABLE
/* if no country code matched return first universal code from translate_custom_table */
memcpy(cspec->ccode, translate_custom_table[0].custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = translate_custom_table[0].custom_locale_rev;
#endif /* EXMAPLE_TABLE */
return;
#endif /* defined(CUSTOMER_HW2) && (LINUX_VERSION_CODE >= KERNEL_VERSION(2, 6, 36)) */
}
|
qubir/PhoenixA20_linux_sourcecode
|
modules/wifi/bcm40183/5.90.125.95.3/open-src/src/dhd/sys/dhd_custom_gpio.c
|
C
|
gpl-2.0
| 9,042
|
/*
* $Id: tcp_server.h,v 1.3 2003/07/01 20:23:51 andrei Exp $
*
* Copyright (C) 2001-2003 Fhg Fokus
*
* This file is part of ser, a free SIP server.
*
* ser 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
*
* For a license to use the ser software under conditions
* other than those described here, or to purchase support for this
* software, please contact iptel.org by e-mail at the following addresses:
* info@iptel.org
*
* ser 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 tcp_server_h
#define tcp_server_h
/* "public" functions*/
struct tcp_connection* tcpconn_get(int id, struct ip_addr* ip, int port,
int timeout);
void tcpconn_put(struct tcp_connection* c);
int tcp_send(int type, char* buf, unsigned len, union sockaddr_union* to,
int id);
#endif
|
atmark-techno/atmark-dist
|
user/ser/tcp_server.h
|
C
|
gpl-2.0
| 1,396
|
var Backbone = require('backbone');
var Modules = require('collections/modules');
var ModuleFactory = require('utils/module-factory');
var Builder = Backbone.Model.extend({
defaults: {
selectDefault: modularPageBuilderData.l10n.selectDefault,
addNewButton: modularPageBuilderData.l10n.addNewButton,
selection: [], // Instance of Modules. Can't use a default, otherwise they won't be unique.
allowedModules: [], // Module names allowed for this builder.
requiredModules: [], // Module names required for this builder. They will be required in this order, at these positions.
},
initialize: function() {
// Set default selection to ensure it isn't a reference.
if ( ! ( this.get( 'selection' ) instanceof Modules ) ) {
this.set( 'selection', new Modules() );
}
this.get( 'selection' ).on( 'change reset add remove', this.setRequiredModules, this );
this.setRequiredModules();
},
setData: function( data ) {
var _selection;
if ( '' === data ) {
return;
}
// Handle either JSON string or proper obhect.
data = ( 'string' === typeof data ) ? JSON.parse( data ) : data;
// Convert saved data to Module models.
if ( data && Array.isArray( data ) ) {
_selection = data.map( function( module ) {
return ModuleFactory.create( module.name, module.attr );
} );
}
// Reset selection using data from hidden input.
if ( _selection && _selection.length ) {
this.get('selection').reset( _selection );
} else {
this.get('selection').reset( [] );
}
},
saveData: function() {
var data = [];
this.get('selection').each( function( module ) {
// Skip empty/broken modules.
if ( ! module.get('name' ) ) {
return;
}
data.push( module.toMicroJSON() );
} );
this.trigger( 'save', data );
},
/**
* List all available modules for this builder.
* All modules, filtered by this.allowedModules.
*/
getAvailableModules: function() {
return _.filter( ModuleFactory.availableModules, function( module ) {
return this.isModuleAllowed( module.name );
}.bind( this ) );
},
isModuleAllowed: function( moduleName ) {
return this.get('allowedModules').indexOf( moduleName ) >= 0;
},
setRequiredModules: function() {
var selection = this.get( 'selection' );
var required = this.get( 'requiredModules' );
if ( ! selection || ! required || required.length < 1 ) {
return;
}
for ( var i = 0; i < required.length; i++ ) {
if (
( ! selection.at( i ) || selection.at( i ).get( 'name' ) !== required[ i ] ) &&
this.isModuleAllowed( required[ i ] )
) {
var module = ModuleFactory.create( required[ i ], [], { sortable: false } );
selection.add( module, { at: i, silent: true } );
} else if ( selection.at( i ) && selection.at( i ).get( 'name' ) === required[ i ] ) {
selection.at( i ).set( 'sortable', false );
}
}
}
});
module.exports = Builder;
|
mattheu/modular-page-builder
|
assets/js/src/models/builder.js
|
JavaScript
|
gpl-2.0
| 2,924
|
/* This file is part of the ScriptDev2 Project. See AUTHORS file for Copyright information
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/* ScriptData
SDName: Boss_Ayamiss
SD%Complete: 80
SDComment: Timers and summon coords need adjustments
SDCategory: Ruins of Ahn'Qiraj
EndScriptData
*/
#include "AI/ScriptDevAI/PreCompiledHeader.h"
#include "ruins_of_ahnqiraj.h"
enum
{
EMOTE_GENERIC_FRENZY = -1000002,
SPELL_STINGER_SPRAY = 25749,
SPELL_POISON_STINGER = 25748, // only used in phase1
// SPELL_SUMMON_SWARMER = 25844, // might be 25708 - spells were removed since 2.0.1
SPELL_PARALYZE = 25725,
SPELL_LASH = 25852,
SPELL_FRENZY = 8269,
SPELL_TRASH = 3391,
SPELL_FEED = 25721, // cast by the Larva when reaches the player on the altar
NPC_LARVA = 15555,
NPC_SWARMER = 15546,
NPC_HORNET = 15934,
PHASE_AIR = 0,
PHASE_GROUND = 1
};
struct SummonLocation
{
float m_fX, m_fY, m_fZ;
};
// Spawn locations
static const SummonLocation aAyamissSpawnLocs[] =
{
{ -9674.4707f, 1528.4133f, 22.457f}, // larva
{ -9701.6005f, 1566.9993f, 24.118f}, // larva
{ -9647.352f, 1578.062f, 55.32f}, // anchor point for swarmers
{ -9717.18f, 1517.72f, 27.4677f}, // teleport location - need to be hardcoded because the player is teleported after the larva is summoned
};
struct boss_ayamissAI : public ScriptedAI
{
boss_ayamissAI(Creature* pCreature) : ScriptedAI(pCreature) {Reset();}
uint32 m_uiStingerSprayTimer;
uint32 m_uiPoisonStingerTimer;
uint32 m_uiSummonSwarmerTimer;
uint32 m_uiSwarmerAttackTimer;
uint32 m_uiParalyzeTimer;
uint32 m_uiLashTimer;
uint32 m_uiTrashTimer;
uint8 m_uiPhase;
bool m_bHasFrenzy;
ObjectGuid m_paralyzeTarget;
GuidList m_lSwarmersGuidList;
void Reset() override
{
m_uiStingerSprayTimer = urand(20000, 30000);
m_uiPoisonStingerTimer = 5000;
m_uiSummonSwarmerTimer = 5000;
m_uiSwarmerAttackTimer = 60000;
m_uiParalyzeTimer = 15000;
m_uiLashTimer = urand(5000, 8000);
m_uiTrashTimer = urand(3000, 6000);
m_bHasFrenzy = false;
m_uiPhase = PHASE_AIR;
SetCombatMovement(false);
}
void Aggro(Unit* /*pWho*/) override
{
m_creature->SetLevitate(true);
m_creature->GetMotionMaster()->MovePoint(0, m_creature->GetPositionX(), m_creature->GetPositionY(), m_creature->GetPositionZ() + 15.0f);
}
void JustSummoned(Creature* pSummoned) override
{
// store the swarmers for a future attack
if (pSummoned->GetEntry() == NPC_SWARMER)
m_lSwarmersGuidList.push_back(pSummoned->GetObjectGuid());
// move the larva to paralyze target position
else if (pSummoned->GetEntry() == NPC_LARVA)
{
pSummoned->SetWalk(false);
pSummoned->GetMotionMaster()->MovePoint(1, aAyamissSpawnLocs[3].m_fX, aAyamissSpawnLocs[3].m_fY, aAyamissSpawnLocs[3].m_fZ);
}
else if (pSummoned->GetEntry() == NPC_HORNET)
{
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
pSummoned->AI()->AttackStart(pTarget);
}
}
void SummonedMovementInform(Creature* pSummoned, uint32 /*uiMotionType*/, uint32 uiPointId) override
{
if (uiPointId != 1 || pSummoned->GetEntry() != NPC_LARVA)
return;
// Cast feed on target
if (Unit* pTarget = m_creature->GetMap()->GetUnit(m_paralyzeTarget))
pSummoned->CastSpell(pTarget, SPELL_FEED, TRIGGERED_OLD_TRIGGERED, nullptr, nullptr, m_creature->GetObjectGuid());
}
void UpdateAI(const uint32 uiDiff) override
{
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
if (!m_bHasFrenzy && m_creature->GetHealthPercent() < 20.0f)
{
if (DoCastSpellIfCan(m_creature, SPELL_FRENZY) == CAST_OK)
{
DoScriptText(EMOTE_GENERIC_FRENZY, m_creature);
m_bHasFrenzy = true;
}
}
// Stinger Spray
if (m_uiStingerSprayTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature, SPELL_STINGER_SPRAY) == CAST_OK)
m_uiStingerSprayTimer = urand(15000, 20000);
}
else
m_uiStingerSprayTimer -= uiDiff;
// Paralyze
if (m_uiParalyzeTimer < uiDiff)
{
Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 1, SPELL_PARALYZE, SELECT_FLAG_PLAYER);
if (!pTarget)
pTarget = m_creature->getVictim();
if (DoCastSpellIfCan(pTarget, SPELL_PARALYZE) == CAST_OK)
{
m_paralyzeTarget = pTarget->GetObjectGuid();
m_uiParalyzeTimer = 15000;
// Summon a larva
uint8 uiLoc = urand(0, 1);
m_creature->SummonCreature(NPC_LARVA, aAyamissSpawnLocs[uiLoc].m_fX, aAyamissSpawnLocs[uiLoc].m_fY, aAyamissSpawnLocs[uiLoc].m_fZ, 0, TEMPSUMMON_TIMED_OOC_OR_CORPSE_DESPAWN, 30000);
}
}
else
m_uiParalyzeTimer -= uiDiff;
// Summon Swarmer
if (m_uiSummonSwarmerTimer < uiDiff)
{
// The spell which summons these guys was removed in 2.0.1 -> therefore we need to summon them manually at a random location around the area
// The summon locations is guesswork - the real location is supposed to be handled by world triggers
// There should be about 24 swarmers per min
float fX, fY, fZ;
for (uint8 i = 0; i < 2; ++i)
{
m_creature->GetRandomPoint(aAyamissSpawnLocs[2].m_fX, aAyamissSpawnLocs[2].m_fY, aAyamissSpawnLocs[2].m_fZ, 80.0f, fX, fY, fZ);
m_creature->SummonCreature(NPC_SWARMER, fX, fY, aAyamissSpawnLocs[2].m_fZ, 0.0f, TEMPSUMMON_CORPSE_DESPAWN, 0);
}
m_uiSummonSwarmerTimer = 5000;
}
else
m_uiSummonSwarmerTimer -= uiDiff;
// All the swarmers attack at a certain period of time
if (m_uiSwarmerAttackTimer < uiDiff)
{
for (GuidList::const_iterator itr = m_lSwarmersGuidList.begin(); itr != m_lSwarmersGuidList.end(); ++itr)
{
if (Creature* pTemp = m_creature->GetMap()->GetCreature(*itr))
{
if (Unit* pTarget = m_creature->SelectAttackingTarget(ATTACKING_TARGET_RANDOM, 0))
pTemp->AI()->AttackStart(pTarget);
}
}
m_lSwarmersGuidList.clear();
m_uiSwarmerAttackTimer = 60000;
}
else
m_uiSwarmerAttackTimer -= uiDiff;
if (m_uiPhase == PHASE_AIR)
{
// Start ground phase at 70% of HP
if (m_creature->GetHealthPercent() <= 70.0f)
{
m_uiPhase = PHASE_GROUND;
SetCombatMovement(true);
m_creature->SetLevitate(false);
DoResetThreat();
if (m_creature->getVictim())
m_creature->GetMotionMaster()->MoveChase(m_creature->getVictim());
}
// Poison Stinger
if (m_uiPoisonStingerTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_POISON_STINGER) == CAST_OK)
m_uiPoisonStingerTimer = urand(2000, 3000);
}
else
m_uiPoisonStingerTimer -= uiDiff;
}
else
{
if (m_uiLashTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_LASH) == CAST_OK)
m_uiLashTimer = urand(8000, 15000);
}
else
m_uiLashTimer -= uiDiff;
if (m_uiTrashTimer < uiDiff)
{
if (DoCastSpellIfCan(m_creature->getVictim(), SPELL_TRASH) == CAST_OK)
m_uiTrashTimer = urand(5000, 7000);
}
else
m_uiTrashTimer -= uiDiff;
DoMeleeAttackIfReady();
}
}
};
CreatureAI* GetAI_boss_ayamiss(Creature* pCreature)
{
return new boss_ayamissAI(pCreature);
}
struct npc_hive_zara_larvaAI : public ScriptedAI
{
npc_hive_zara_larvaAI(Creature* pCreature) : ScriptedAI(pCreature)
{
m_pInstance = (instance_ruins_of_ahnqiraj*)m_creature->GetInstanceData();
Reset();
}
instance_ruins_of_ahnqiraj* m_pInstance;
void Reset() override { }
void AttackStart(Unit* pWho) override
{
// don't attack anything during the Ayamiss encounter
if (m_pInstance)
{
if (m_pInstance->GetData(TYPE_AYAMISS) == IN_PROGRESS)
return;
}
ScriptedAI::AttackStart(pWho);
}
void MoveInLineOfSight(Unit* pWho) override
{
// don't attack anything during the Ayamiss encounter
if (m_pInstance)
{
if (m_pInstance->GetData(TYPE_AYAMISS) == IN_PROGRESS)
return;
}
ScriptedAI::MoveInLineOfSight(pWho);
}
void UpdateAI(const uint32 /*uiDiff*/) override
{
if (m_pInstance)
{
if (m_pInstance->GetData(TYPE_AYAMISS) == IN_PROGRESS)
return;
}
if (!m_creature->SelectHostileTarget() || !m_creature->getVictim())
return;
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI_npc_hive_zara_larva(Creature* pCreature)
{
return new npc_hive_zara_larvaAI(pCreature);
}
void AddSC_boss_ayamiss()
{
Script* pNewScript;
pNewScript = new Script;
pNewScript->Name = "boss_ayamiss";
pNewScript->GetAI = &GetAI_boss_ayamiss;
pNewScript->RegisterSelf();
pNewScript = new Script;
pNewScript->Name = "npc_hive_zara_larva";
pNewScript->GetAI = &GetAI_npc_hive_zara_larva;
pNewScript->RegisterSelf();
}
|
blueboy/portalclassic
|
src/game/AI/ScriptDevAI/scripts/kalimdor/ruins_of_ahnqiraj/boss_ayamiss.cpp
|
C++
|
gpl-2.0
| 10,975
|
/*
* $Id: raster2pgsql.c 12748 2014-07-07 08:57:57Z strk $
*
* PostGIS raster loader
* http://trac.osgeo.org/postgis/wiki/WKTRaster
*
* Copyright 2001-2003 Refractions Research Inc.
* Copyright 2009 Paul Ramsey <pramsey@cleverelephant.ca>
* Copyright 2009 Mark Cave-Ayland <mark.cave-ayland@siriusit.co.uk>
* Copyright (C) 2011 Regents of the University of California
* <bkpark@ucdavis.edu>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#include "raster2pgsql.h"
#include "gdal_vrt.h"
#include "ogr_srs_api.h"
#include <assert.h>
static void
loader_rt_error_handler(const char *fmt, va_list ap) {
static const char *label = "ERROR: ";
char newfmt[1024] = {0};
snprintf(newfmt, 1024, "%s%s\n", label, fmt);
newfmt[1023] = '\0';
vfprintf(stderr, newfmt, ap);
va_end(ap);
}
static void
loader_rt_warning_handler(const char *fmt, va_list ap) {
static const char *label = "WARNING: ";
char newfmt[1024] = {0};
snprintf(newfmt, 1024, "%s%s\n", label, fmt);
newfmt[1023] = '\0';
vfprintf(stderr, newfmt, ap);
va_end(ap);
}
static void
loader_rt_info_handler(const char *fmt, va_list ap) {
static const char *label = "INFO: ";
char newfmt[1024] = {0};
snprintf(newfmt, 1024, "%s%s\n", label, fmt);
newfmt[1023] = '\0';
vfprintf(stderr, newfmt, ap);
va_end(ap);
}
void rt_init_allocators(void) {
rt_set_handlers(
default_rt_allocator,
default_rt_reallocator,
default_rt_deallocator,
loader_rt_error_handler,
loader_rt_info_handler,
loader_rt_warning_handler
);
}
static void
raster_destroy(rt_raster raster) {
uint16_t i;
uint16_t nbands = rt_raster_get_num_bands(raster);
for (i = 0; i < nbands; i++) {
rt_band band = rt_raster_get_band(raster, i);
if (band == NULL) continue;
if (!rt_band_is_offline(band) && !rt_band_get_ownsdata_flag(band)) {
void* mem = rt_band_get_data(band);
if (mem) rtdealloc(mem);
}
rt_band_destroy(band);
}
rt_raster_destroy(raster);
}
static int
array_range(int min, int max, int step, int **range, int *len) {
int i = 0;
int j = 0;
step = abs(step);
*len = (abs(max - min) + 1 + (step / 2)) / step;
*range = rtalloc(sizeof(int) * *len);
if (min < max) {
for (i = min, j = 0; i <= max; i += step, j++)
(*range)[j] = i;
}
else if (max < min) {
if (step > 0) step *= -1;
for (i = min, j = 0; i >= max; i += step, j++)
(*range)[j] = i;
}
else if (min == max) {
(*range)[0] = min;
}
else {
*len = 0;
*range = NULL;
return 0;
}
return 1;
}
/* string replacement function taken from
* http://ubuntuforums.org/showthread.php?s=aa6f015109fd7e4c7e30d2fd8b717497&t=141670&page=3
*/
/* ---------------------------------------------------------------------------
Name : replace - Search & replace a substring by another one.
Creation : Thierry Husson, Sept 2010
Parameters :
str : Big string where we search
oldstr : Substring we are looking for
newstr : Substring we want to replace with
count : Optional pointer to int (input / output value). NULL to ignore.
Input: Maximum replacements to be done. NULL or < 1 to do all.
Output: Number of replacements done or -1 if not enough memory.
Returns : Pointer to the new string or NULL if error.
Notes :
- Case sensitive - Otherwise, replace functions "strstr" by "strcasestr"
- Always allocates memory for the result.
--------------------------------------------------------------------------- */
static char*
strreplace(
const char *str,
const char *oldstr, const char *newstr,
int *count
) {
const char *tmp = str;
char *result;
int found = 0;
int length, reslen;
int oldlen = strlen(oldstr);
int newlen = strlen(newstr);
int limit = (count != NULL && *count > 0) ? *count : -1;
tmp = str;
while ((tmp = strstr(tmp, oldstr)) != NULL && found != limit)
found++, tmp += oldlen;
length = strlen(str) + found * (newlen - oldlen);
if ((result = (char *) rtalloc(length + 1)) == NULL) {
rterror(_("strreplace: Not enough memory"));
found = -1;
}
else {
tmp = str;
limit = found; /* Countdown */
reslen = 0; /* length of current result */
/* Replace each old string found with new string */
while ((limit-- > 0) && (tmp = strstr(tmp, oldstr)) != NULL) {
length = (tmp - str); /* Number of chars to keep intouched */
strncpy(result + reslen, str, length); /* Original part keeped */
strcpy(result + (reslen += length), newstr); /* Insert new string */
reslen += newlen;
tmp += oldlen;
str = tmp;
}
strcpy(result + reslen, str); /* Copies last part and ending null char */
}
if (count != NULL) *count = found;
return result;
}
static char *
strtolower(char * str) {
int j;
for (j = strlen(str) - 1; j >= 0; j--)
str[j] = tolower(str[j]);
return str;
}
/* split a string based on a delimiter */
static char**
strsplit(const char *str, const char *delimiter, int *n) {
char *tmp = NULL;
char **rtn = NULL;
char *token = NULL;
*n = 0;
if (!str)
return NULL;
/* copy str to tmp as strtok will mangle the string */
tmp = rtalloc(sizeof(char) * (strlen(str) + 1));
if (NULL == tmp) {
rterror(_("strsplit: Not enough memory"));
return NULL;
}
strcpy(tmp, str);
if (!strlen(tmp) || !delimiter || !strlen(delimiter)) {
*n = 1;
rtn = (char **) rtalloc(*n * sizeof(char *));
if (NULL == rtn) {
rterror(_("strsplit: Not enough memory"));
return NULL;
}
rtn[0] = (char *) rtalloc(sizeof(char) * (strlen(tmp) + 1));
if (NULL == rtn[0]) {
rterror(_("strsplit: Not enough memory"));
return NULL;
}
strcpy(rtn[0], tmp);
rtdealloc(tmp);
return rtn;
}
token = strtok(tmp, delimiter);
while (token != NULL) {
if (*n < 1) {
rtn = (char **) rtalloc(sizeof(char *));
}
else {
rtn = (char **) rtrealloc(rtn, (*n + 1) * sizeof(char *));
}
if (NULL == rtn) {
rterror(_("strsplit: Not enough memory"));
return NULL;
}
rtn[*n] = NULL;
rtn[*n] = (char *) rtalloc(sizeof(char) * (strlen(token) + 1));
if (NULL == rtn[*n]) {
rterror(_("strsplit: Not enough memory"));
return NULL;
}
strcpy(rtn[*n], token);
*n = *n + 1;
token = strtok(NULL, delimiter);
}
rtdealloc(tmp);
return rtn;
}
static char*
trim(const char *input) {
char *rtn;
char *ptr;
uint32_t offset = 0;
if (!input)
return NULL;
else if (!*input)
return (char *) input;
/* trim left */
while (isspace(*input))
input++;
/* trim right */
ptr = ((char *) input) + strlen(input);
while (isspace(*--ptr))
offset++;
rtn = rtalloc(sizeof(char) * (strlen(input) - offset + 1));
if (NULL == rtn) {
rterror(_("trim: Not enough memory"));
return NULL;
}
strncpy(rtn, input, strlen(input) - offset);
rtn[strlen(input) - offset] = '\0';
return rtn;
}
static char*
chartrim(const char *input, char *remove) {
char *rtn = NULL;
char *ptr = NULL;
uint32_t offset = 0;
if (!input)
return NULL;
else if (!*input)
return (char *) input;
/* trim left */
while (strchr(remove, *input) != NULL)
input++;
/* trim right */
ptr = ((char *) input) + strlen(input);
while (strchr(remove, *--ptr) != NULL)
offset++;
rtn = rtalloc(sizeof(char) * (strlen(input) - offset + 1));
if (NULL == rtn) {
rterror(_("chartrim: Not enough memory"));
return NULL;
}
strncpy(rtn, input, strlen(input) - offset);
rtn[strlen(input) - offset] = '\0';
return rtn;
}
static void
usage() {
printf(_("RELEASE: %s GDAL_VERSION=%d (r%d)\n"), POSTGIS_LIB_VERSION, POSTGIS_GDAL_VERSION, POSTGIS_SVN_REVISION);
printf(_(
"USAGE: raster2pgsql [<options>] <raster>[ <raster>[ ...]] [[<schema>.]<table>]\n"
" Multiple rasters can also be specified using wildcards (*,?).\n"
"\n"
"OPTIONS:\n"
));
printf(_(
" -s <srid> Set the raster's SRID. Defaults to %d. If SRID not\n"
" provided or is %d, raster's metadata will be checked to\n"
" determine an appropriate SRID.\n"
), SRID_UNKNOWN, SRID_UNKNOWN);
printf(_(
" -b <band> Index (1-based) of band to extract from raster. For more\n"
" than one band index, separate with comma (,). Ranges can be\n"
" defined by separating with dash (-). If unspecified, all bands\n"
" of raster will be extracted.\n"
));
printf(_(
" -t <tile size> Cut raster into tiles to be inserted one per\n"
" table row. <tile size> is expressed as WIDTHxHEIGHT.\n"
" <tile size> can also be \"auto\" to allow the loader to compute\n"
" an appropriate tile size using the first raster and applied to\n"
" all rasters.\n"
));
printf(_(
" -P Pad right-most and bottom-most tiles to guarantee that all tiles\n"
" have the same width and height.\n"
));
printf(_(
" -R Register the raster as an out-of-db (filesystem) raster. Provided\n"
" raster should have absolute path to the file\n"
));
printf(_(
" (-d|a|c|p) These are mutually exclusive options:\n"
" -d Drops the table, then recreates it and populates\n"
" it with current raster data.\n"
" -a Appends raster into current table, must be\n"
" exactly the same table schema.\n"
" -c Creates a new table and populates it, this is the\n"
" default if you do not specify any options.\n"
" -p Prepare mode, only creates the table.\n"
));
printf(_(
" -f <column> Specify the name of the raster column\n"
));
printf(_(
" -F Add a column with the filename of the raster.\n"
));
printf(_(
" -n <column> Specify the name of the filename column. Implies -F.\n"
));
printf(_(
" -l <overview factor> Create overview of the raster. For more than\n"
" one factor, separate with comma(,). Overview table name follows\n"
" the pattern o_<overview factor>_<table>. Created overview is\n"
" stored in the database and is not affected by -R.\n"
));
printf(_(
" -q Wrap PostgreSQL identifiers in quotes.\n"
));
printf(_(
" -I Create a GIST spatial index on the raster column. The ANALYZE\n"
" command will automatically be issued for the created index.\n"
));
printf(_(
" -M Run VACUUM ANALYZE on the table of the raster column. Most\n"
" useful when appending raster to existing table with -a.\n"
));
printf(_(
" -C Set the standard set of constraints on the raster\n"
" column after the rasters are loaded. Some constraints may fail\n"
" if one or more rasters violate the constraint.\n"
" -x Disable setting the max extent constraint. Only applied if\n"
" -C flag is also used.\n"
" -r Set the constraints (spatially unique and coverage tile) for\n"
" regular blocking. Only applied if -C flag is also used.\n"
));
printf(_(
" -T <tablespace> Specify the tablespace for the new table.\n"
" Note that indices (including the primary key) will still use\n"
" the default tablespace unless the -X flag is also used.\n"
));
printf(_(
" -X <tablespace> Specify the tablespace for the table's new index.\n"
" This applies to the primary key and the spatial index if\n"
" the -I flag is used.\n"
));
printf(_(
" -N <nodata> NODATA value to use on bands without a NODATA value.\n"
));
printf(_(
" -k Skip NODATA value checks for each raster band.\n"
));
printf(_(
" -E <endian> Control endianness of generated binary output of\n"
" raster. Use 0 for XDR and 1 for NDR (default). Only NDR\n"
" is supported at this time.\n"
));
printf(_(
" -V <version> Specify version of output WKB format. Default\n"
" is 0. Only 0 is supported at this time.\n"
));
printf(_(
" -e Execute each statement individually, do not use a transaction.\n"
));
printf(_(
" -Y Use COPY statements instead of INSERT statements.\n"
));
printf(_(
" -G Print the supported GDAL raster formats.\n"
));
printf(_(
" -? Display this help screen.\n"
));
}
static void calc_tile_size(
int dimX, int dimY,
int *tileX, int *tileY
) {
int i = 0;
int j = 0;
int min = 30;
int max = 100;
int d = 0;
double r = 0;
/*int _d = 0;*/
double _r = -1;
int _i = 0;
/* j = 0, X */
for (j = 0; j < 2; j++) {
_i = 0;
/*_d = 0;*/
_r = -1;
if (j < 1 && dimX <= max) {
*tileX = dimX;
continue;
}
else if (dimY <= max) {
*tileY = dimY;
continue;
}
for (i = max; i >= min; i--) {
if (j < 1) {
d = dimX / i;
r = (double) dimX / (double) i;
}
else {
d = dimY / i;
r = (double) dimY / (double) i;
}
r = r - (double) d;
if (
FLT_EQ(_r, -1) ||
(r < _r) ||
FLT_EQ(r, _r)
) {
/*_d = d;*/
_r = r;
_i = i;
}
}
if (j < 1)
*tileX = _i;
else
*tileY = _i;
}
}
static void
init_rastinfo(RASTERINFO *info) {
info->srid = SRID_UNKNOWN;
info->srs = NULL;
memset(info->dim, 0, sizeof(double) * 2);
info->nband_count = 0;
info->nband = NULL;
info->gdalbandtype = NULL;
info->bandtype = NULL;
info->hasnodata = NULL;
info->nodataval = NULL;
memset(info->gt, 0, sizeof(double) * 6);
memset(info->tile_size, 0, sizeof(int) * 2);
}
static void
rtdealloc_rastinfo(RASTERINFO *info) {
if (info->srs != NULL)
rtdealloc(info->srs);
if (info->nband_count > 0 && info->nband != NULL)
rtdealloc(info->nband);
if (info->gdalbandtype != NULL)
rtdealloc(info->gdalbandtype);
if (info->bandtype != NULL)
rtdealloc(info->bandtype);
if (info->hasnodata != NULL)
rtdealloc(info->hasnodata);
if (info->nodataval != NULL)
rtdealloc(info->nodataval);
}
static int
copy_rastinfo(RASTERINFO *dst, RASTERINFO *src) {
if (src->srs != NULL) {
dst->srs = rtalloc(sizeof(char) * (strlen(src->srs) + 1));
if (dst->srs == NULL) {
rterror(_("copy_rastinfo: Not enough memory"));
return 0;
}
strcpy(dst->srs, src->srs);
}
memcpy(dst->dim, src->dim, sizeof(uint32_t) * 2);
dst->nband_count = src->nband_count;
if (src->nband_count && src->nband != NULL) {
dst->nband = rtalloc(sizeof(int) * src->nband_count);
if (dst->nband == NULL) {
rterror(_("copy_rastinfo: Not enough memory"));
return 0;
}
memcpy(dst->nband, src->nband, sizeof(int) * src->nband_count);
}
if (src->gdalbandtype != NULL) {
dst->gdalbandtype = rtalloc(sizeof(GDALDataType) * src->nband_count);
if (dst->gdalbandtype == NULL) {
rterror(_("copy_rastinfo: Not enough memory"));
return 0;
}
memcpy(dst->gdalbandtype, src->gdalbandtype, sizeof(GDALDataType) * src->nband_count);
}
if (src->bandtype != NULL) {
dst->bandtype = rtalloc(sizeof(rt_pixtype) * src->nband_count);
if (dst->bandtype == NULL) {
rterror(_("copy_rastinfo: Not enough memory"));
return 0;
}
memcpy(dst->bandtype, src->bandtype, sizeof(rt_pixtype) * src->nband_count);
}
if (src->hasnodata != NULL) {
dst->hasnodata = rtalloc(sizeof(int) * src->nband_count);
if (dst->hasnodata == NULL) {
rterror(_("copy_rastinfo: Not enough memory"));
return 0;
}
memcpy(dst->hasnodata, src->hasnodata, sizeof(int) * src->nband_count);
}
if (src->nodataval != NULL) {
dst->nodataval = rtalloc(sizeof(double) * src->nband_count);
if (dst->nodataval == NULL) {
rterror(_("copy_rastinfo: Not enough memory"));
return 0;
}
memcpy(dst->nodataval, src->nodataval, sizeof(double) * src->nband_count);
}
memcpy(dst->gt, src->gt, sizeof(double) * 6);
memcpy(dst->tile_size, src->tile_size, sizeof(int) * 2);
return 1;
}
static void
diff_rastinfo(RASTERINFO *x, RASTERINFO *ref) {
static uint8_t msg[6] = {0};
int i = 0;
/* # of bands */
if (
!msg[0] &&
x->nband_count != ref->nband_count
) {
rtwarn(_("Different number of bands found in the set of rasters being converted to PostGIS raster"));
msg[0]++;
}
/* pixel types */
if (!msg[1]) {
for (i = 0; i < ref->nband_count; i++) {
if (x->bandtype[i] != ref->bandtype[i]) {
rtwarn(_("Different pixel types found for band %d in the set of rasters being converted to PostGIS raster"), ref->nband[i]);
msg[1]++;
}
}
}
/* hasnodata */
if (!msg[2]) {
for (i = 0; i < ref->nband_count; i++) {
if (x->hasnodata[i] != ref->hasnodata[i]) {
rtwarn(_("Different hasnodata flags found for band %d in the set of rasters being converted to PostGIS raster"), ref->nband[i]);
msg[2]++;
}
}
}
/* nodataval */
if (!msg[3]) {
for (i = 0; i < ref->nband_count; i++) {
if (!x->hasnodata[i] && !ref->hasnodata[i]) continue;
if (FLT_NEQ(x->hasnodata[i], ref->hasnodata[i])) {
rtwarn(_("Different NODATA values found for band %d in the set of rasters being converted to PostGIS raster"), ref->nband[i]);
msg[3]++;
}
}
}
/* alignment */
if (!msg[4]) {
rt_raster rx = NULL;
rt_raster rref = NULL;
int err;
int aligned;
if (
(rx = rt_raster_new(1, 1)) == NULL ||
(rref = rt_raster_new(1, 1)) == NULL
) {
rterror(_("diff_rastinfo: Could not allocate memory for raster alignment test"));
if (rx != NULL) rt_raster_destroy(rx);
if (rref != NULL) rt_raster_destroy(rref);
return;
}
rt_raster_set_geotransform_matrix(rx, x->gt);
rt_raster_set_geotransform_matrix(rref, ref->gt);
err = rt_raster_same_alignment(rx, rref, &aligned, NULL);
rt_raster_destroy(rx);
rt_raster_destroy(rref);
if (err != ES_NONE) {
rterror(_("diff_rastinfo: Could not run raster alignment test"));
return;
}
if (!aligned) {
rtwarn(_("Raster with different alignment found in the set of rasters being converted to PostGIS raster"));
msg[4]++;
}
}
/* tile size */
if (!msg[5]) {
for (i = 0; i < 2; i++) {
if (FLT_NEQ(x->tile_size[i], ref->tile_size[i])) {
rtwarn(_("Different tile sizes found in the set of rasters being converted to PostGIS raster"));
msg[5]++;
break;
}
}
}
}
static void
init_config(RTLOADERCFG *config) {
config->rt_file_count = 0;
config->rt_file = NULL;
config->rt_filename = NULL;
config->schema = NULL;
config->table = NULL;
config->raster_column = NULL;
config->file_column = 0;
config->file_column_name = NULL;
config->overview_count = 0;
config->overview = NULL;
config->overview_table = NULL;
config->quoteident = 0;
config->srid = SRID_UNKNOWN;
config->nband = NULL;
config->nband_count = 0;
memset(config->tile_size, 0, sizeof(int) * 2);
config->pad_tile = 0;
config->outdb = 0;
config->opt = 'c';
config->idx = 0;
config->maintenance = 0;
config->constraints = 0;
config->max_extent = 1;
config->regular_blocking = 0;
config->tablespace = NULL;
config->idx_tablespace = NULL;
config->hasnodata = 0;
config->nodataval = 0;
config->skip_nodataval_check = 0;
config->endian = 1;
config->version = 0;
config->transaction = 1;
config->copy_statements = 0;
}
static void
rtdealloc_config(RTLOADERCFG *config) {
int i = 0;
if (config->rt_file_count) {
for (i = config->rt_file_count - 1; i >= 0; i--) {
rtdealloc(config->rt_file[i]);
if (config->rt_filename)
rtdealloc(config->rt_filename[i]);
}
rtdealloc(config->rt_file);
if (config->rt_filename)
rtdealloc(config->rt_filename);
}
if (config->schema != NULL)
rtdealloc(config->schema);
if (config->table != NULL)
rtdealloc(config->table);
if (config->raster_column != NULL)
rtdealloc(config->raster_column);
if (config->file_column_name != NULL)
rtdealloc(config->file_column_name);
if (config->overview_count > 0) {
if (config->overview != NULL)
rtdealloc(config->overview);
if (config->overview_table != NULL) {
for (i = config->overview_count - 1; i >= 0; i--)
rtdealloc(config->overview_table[i]);
rtdealloc(config->overview_table);
}
}
if (config->nband_count > 0 && config->nband != NULL)
rtdealloc(config->nband);
if (config->tablespace != NULL)
rtdealloc(config->tablespace);
if (config->idx_tablespace != NULL)
rtdealloc(config->idx_tablespace);
rtdealloc(config);
}
static void
init_stringbuffer(STRINGBUFFER *buffer) {
buffer->line = NULL;
buffer->length = 0;
}
static void
rtdealloc_stringbuffer(STRINGBUFFER *buffer, int freebuffer) {
if (buffer->length) {
uint32_t i = 0;
for (i = 0; i < buffer->length; i++) {
if (buffer->line[i] != NULL)
rtdealloc(buffer->line[i]);
}
rtdealloc(buffer->line);
}
buffer->line = NULL;
buffer->length = 0;
if (freebuffer)
rtdealloc(buffer);
}
static void
dump_stringbuffer(STRINGBUFFER *buffer) {
int i = 0;
for (i = 0; i < buffer->length; i++) {
printf("%s\n", buffer->line[i]);
}
}
static void
flush_stringbuffer(STRINGBUFFER *buffer) {
dump_stringbuffer(buffer);
rtdealloc_stringbuffer(buffer, 0);
}
static int
append_stringbuffer(STRINGBUFFER *buffer, const char *str) {
buffer->length++;
buffer->line = rtrealloc(buffer->line, sizeof(char *) * buffer->length);
if (buffer->line == NULL) {
rterror(_("append_stringbuffer: Could not allocate memory for appending string to buffer"));
return 0;
}
buffer->line[buffer->length - 1] = NULL;
buffer->line[buffer->length - 1] = rtalloc(sizeof(char) * (strlen(str) + 1));
if (buffer->line[buffer->length - 1] == NULL) {
rterror(_("append_stringbuffer: Could not allocate memory for appending string to buffer"));
return 0;
}
strcpy(buffer->line[buffer->length - 1], str);
return 1;
}
static int
append_sql_to_buffer(STRINGBUFFER *buffer, const char *str) {
if (buffer->length > 9)
flush_stringbuffer(buffer);
return append_stringbuffer(buffer, str);
}
static int
insert_records(
const char *schema, const char *table, const char *column,
const char *filename, const char *file_column_name,
int copy_statements,
STRINGBUFFER *tileset, STRINGBUFFER *buffer
) {
char *fn = NULL;
uint32_t len = 0;
char *sql = NULL;
uint32_t x = 0;
assert(table != NULL);
assert(column != NULL);
/* COPY statements */
if (copy_statements) {
/* escape tabs in filename */
if (filename != NULL)
fn = strreplace(filename, "\t", "\\t", NULL);
/* rows */
for (x = 0; x < tileset->length; x++) {
len = strlen(tileset->line[x]) + 1;
if (filename != NULL)
len += strlen(fn) + 1;
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("insert_records: Could not allocate memory for COPY statement"));
return 0;
}
sprintf(sql, "%s%s%s",
tileset->line[x],
(filename != NULL ? "\t" : ""),
(filename != NULL ? fn : "")
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
sql = NULL;
}
}
/* INSERT statements */
else {
len = strlen("INSERT INTO () VALUES (''::raster);") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(table);
len += strlen(column);
if (filename != NULL)
len += strlen(",") + strlen(file_column_name);
/* escape single-quotes in filename */
if (filename != NULL)
fn = strreplace(filename, "'", "''", NULL);
for (x = 0; x < tileset->length; x++) {
int sqllen = len;
sqllen += strlen(tileset->line[x]);
if (filename != NULL)
sqllen += strlen(",''") + strlen(fn);
sql = rtalloc(sizeof(char) * sqllen);
if (sql == NULL) {
rterror(_("insert_records: Could not allocate memory for INSERT statement"));
return 0;
}
sprintf(sql, "INSERT INTO %s%s (%s%s%s) VALUES ('%s'::raster%s%s%s);",
(schema != NULL ? schema : ""),
table,
column,
(filename != NULL ? "," : ""),
(filename != NULL ? file_column_name : ""),
tileset->line[x],
(filename != NULL ? ",'" : ""),
(filename != NULL ? fn : ""),
(filename != NULL ? "'" : "")
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
sql = NULL;
}
}
if (fn != NULL) rtdealloc(fn);
return 1;
}
static int
drop_table(const char *schema, const char *table, STRINGBUFFER *buffer) {
char *sql = NULL;
uint32_t len = 0;
len = strlen("DROP TABLE IF EXISTS ;") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(table);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("drop_table: Could not allocate memory for DROP TABLE statement"));
return 0;
}
sprintf(sql, "DROP TABLE IF EXISTS %s%s;",
(schema != NULL ? schema : ""),
table
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
create_table(
const char *schema, const char *table, const char *column,
const int file_column, const char *file_column_name,
const char *tablespace, const char *idx_tablespace,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
assert(table != NULL);
assert(column != NULL);
len = strlen("CREATE TABLE (\"rid\" serial PRIMARY KEY, raster);") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(table);
len += strlen(column);
if (file_column)
len += strlen(", text") + strlen(file_column_name);
if (tablespace != NULL)
len += strlen(" TABLESPACE ") + strlen(tablespace);
if (idx_tablespace != NULL)
len += strlen(" USING INDEX TABLESPACE ") + strlen(idx_tablespace);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("create_table: Could not allocate memory for CREATE TABLE statement"));
return 0;
}
sprintf(sql, "CREATE TABLE %s%s (\"rid\" serial PRIMARY KEY%s%s,%s raster%s%s%s)%s%s;",
(schema != NULL ? schema : ""),
table,
(idx_tablespace != NULL ? " USING INDEX TABLESPACE " : ""),
(idx_tablespace != NULL ? idx_tablespace : ""),
column,
(file_column ? "," : ""),
(file_column ? file_column_name : ""),
(file_column ? " text" : ""),
(tablespace != NULL ? " TABLESPACE " : ""),
(tablespace != NULL ? tablespace : "")
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
copy_from(
const char *schema, const char *table, const char *column,
const char *filename, const char *file_column_name,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
assert(table != NULL);
assert(column != NULL);
len = strlen("COPY () FROM stdin;") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(table);
len += strlen(column);
if (filename != NULL)
len += strlen(",") + strlen(file_column_name);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("copy_from: Could not allocate memory for COPY statement"));
return 0;
}
sprintf(sql, "COPY %s%s (%s%s%s) FROM stdin;",
(schema != NULL ? schema : ""),
table,
column,
(filename != NULL ? "," : ""),
(filename != NULL ? file_column_name : "")
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
sql = NULL;
return 1;
}
static int
copy_from_end(STRINGBUFFER *buffer) {
/* end of data */
append_sql_to_buffer(buffer, "\\.");
return 1;
}
static int
create_index(
const char *schema, const char *table, const char *column,
const char *tablespace,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
char *_table = NULL;
char *_column = NULL;
assert(table != NULL);
assert(column != NULL);
_table = chartrim(table, "\"");
_column = chartrim(column, "\"");
/* create index */
len = strlen("CREATE INDEX \"__gist\" ON USING gist (st_convexhull());") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(_table);
len += strlen(_column);
len += strlen(table);
len += strlen(column);
if (tablespace != NULL)
len += strlen(" TABLESPACE ") + strlen(tablespace);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("create_index: Could not allocate memory for CREATE INDEX statement"));
rtdealloc(_table);
rtdealloc(_column);
return 0;
}
sprintf(sql, "CREATE INDEX ON %s%s USING gist (st_convexhull(%s))%s%s;",
(schema != NULL ? schema : ""),
table,
column,
(tablespace != NULL ? " TABLESPACE " : ""),
(tablespace != NULL ? tablespace : "")
);
rtdealloc(_table);
rtdealloc(_column);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
analyze_table(
const char *schema, const char *table,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
assert(table != NULL);
len = strlen("ANALYZE ;") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(table);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("analyze_table: Could not allocate memory for ANALYZE TABLE statement"));
return 0;
}
sprintf(sql, "ANALYZE %s%s;",
(schema != NULL ? schema : ""),
table
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
vacuum_table(
const char *schema, const char *table,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
assert(table != NULL);
len = strlen("VACUUM ANALYZE ;") + 1;
if (schema != NULL)
len += strlen(schema);
len += strlen(table);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("vacuum_table: Could not allocate memory for VACUUM statement"));
return 0;
}
sprintf(sql, "VACUUM ANALYZE %s%s;",
(schema != NULL ? schema : ""),
table
);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
add_raster_constraints(
const char *schema, const char *table, const char *column,
int regular_blocking, int max_extent,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
char *_tmp = NULL;
char *_schema = NULL;
char *_table = NULL;
char *_column = NULL;
assert(table != NULL);
assert(column != NULL);
/* schema */
if (schema != NULL) {
_tmp = chartrim(schema, ".");
_schema = chartrim(_tmp, "\"");
rtdealloc(_tmp);
_tmp = strreplace(_schema, "'", "''", NULL);
rtdealloc(_schema);
_schema = _tmp;
}
/* table */
_tmp = chartrim(table, "\"");
_table = strreplace(_tmp, "'", "''", NULL);
rtdealloc(_tmp);
/* column */
_tmp = chartrim(column, "\"");
_column = strreplace(_tmp, "'", "''", NULL);
rtdealloc(_tmp);
len = strlen("SELECT AddRasterConstraints('','','',TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,FALSE,TRUE,TRUE,TRUE,TRUE,FALSE);") + 1;
if (_schema != NULL)
len += strlen(_schema);
len += strlen(_table);
len += strlen(_column);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("add_raster_constraints: Could not allocate memory for AddRasterConstraints statement"));
return 0;
}
sprintf(sql, "SELECT AddRasterConstraints('%s','%s','%s',TRUE,TRUE,TRUE,TRUE,TRUE,TRUE,%s,TRUE,TRUE,TRUE,TRUE,%s);",
(_schema != NULL ? _schema : ""),
_table,
_column,
(regular_blocking ? "TRUE" : "FALSE"),
(max_extent ? "TRUE" : "FALSE")
);
if (_schema != NULL)
rtdealloc(_schema);
rtdealloc(_table);
rtdealloc(_column);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
add_overview_constraints(
const char *ovschema, const char *ovtable, const char *ovcolumn,
const char *schema, const char *table, const char *column,
const int factor,
STRINGBUFFER *buffer
) {
char *sql = NULL;
uint32_t len = 0;
char *_tmp = NULL;
char *_ovschema = NULL;
char *_ovtable = NULL;
char *_ovcolumn = NULL;
char *_schema = NULL;
char *_table = NULL;
char *_column = NULL;
assert(ovtable != NULL);
assert(ovcolumn != NULL);
assert(table != NULL);
assert(column != NULL);
assert(factor >= MINOVFACTOR && factor <= MAXOVFACTOR);
/* overview schema */
if (ovschema != NULL) {
_tmp = chartrim(ovschema, ".");
_ovschema = chartrim(_tmp, "\"");
rtdealloc(_tmp);
_tmp = strreplace(_ovschema, "'", "''", NULL);
rtdealloc(_ovschema);
_ovschema = _tmp;
}
/* overview table */
_tmp = chartrim(ovtable, "\"");
_ovtable = strreplace(_tmp, "'", "''", NULL);
rtdealloc(_tmp);
/* overview column*/
_tmp = chartrim(ovcolumn, "\"");
_ovcolumn = strreplace(_tmp, "'", "''", NULL);
rtdealloc(_tmp);
/* schema */
if (schema != NULL) {
_tmp = chartrim(schema, ".");
_schema = chartrim(_tmp, "\"");
rtdealloc(_tmp);
_tmp = strreplace(_schema, "'", "''", NULL);
rtdealloc(_schema);
_schema = _tmp;
}
/* table */
_tmp = chartrim(table, "\"");
_table = strreplace(_tmp, "'", "''", NULL);
rtdealloc(_tmp);
/* column */
_tmp = chartrim(column, "\"");
_column = strreplace(_tmp, "'", "''", NULL);
rtdealloc(_tmp);
len = strlen("SELECT AddOverviewConstraints('','','','','','',);") + 5;
if (_ovschema != NULL)
len += strlen(_ovschema);
len += strlen(_ovtable);
len += strlen(_ovcolumn);
if (_schema != NULL)
len += strlen(_schema);
len += strlen(_table);
len += strlen(_column);
sql = rtalloc(sizeof(char) * len);
if (sql == NULL) {
rterror(_("add_overview_constraints: Could not allocate memory for AddOverviewConstraints statement"));
return 0;
}
sprintf(sql, "SELECT AddOverviewConstraints('%s','%s','%s','%s','%s','%s',%d);",
(_ovschema != NULL ? _ovschema : ""),
_ovtable,
_ovcolumn,
(_schema != NULL ? _schema : ""),
_table,
_column,
factor
);
if (_ovschema != NULL)
rtdealloc(_ovschema);
rtdealloc(_ovtable);
rtdealloc(_ovcolumn);
if (_schema != NULL)
rtdealloc(_schema);
rtdealloc(_table);
rtdealloc(_column);
append_sql_to_buffer(buffer, sql);
rtdealloc(sql);
return 1;
}
static int
build_overview(int idx, RTLOADERCFG *config, RASTERINFO *info, int ovx, STRINGBUFFER *tileset, STRINGBUFFER *buffer) {
GDALDatasetH hdsSrc;
VRTDatasetH hdsOv;
VRTSourcedRasterBandH hbandOv;
double gtOv[6] = {0.};
int dimOv[2] = {0};
int j = 0;
int factor;
const char *ovtable = NULL;
VRTDatasetH hdsDst;
VRTSourcedRasterBandH hbandDst;
int tile_size[2] = {0};
int _tile_size[2] = {0};
int ntiles[2] = {1, 1};
int xtile = 0;
int ytile = 0;
double gt[6] = {0.};
rt_raster rast = NULL;
char *hex;
uint32_t hexlen = 0;
hdsSrc = GDALOpenShared(config->rt_file[idx], GA_ReadOnly);
if (hdsSrc == NULL) {
rterror(_("build_overview: Could not open raster: %s"), config->rt_file[idx]);
return 0;
}
/* working copy of geotransform matrix */
memcpy(gtOv, info->gt, sizeof(double) * 6);
if (ovx >= config->overview_count) {
rterror(_("build_overview: Invalid overview index: %d"), ovx);
return 0;
}
factor = config->overview[ovx];
ovtable = (const char *) config->overview_table[ovx];
/* factor must be within valid range */
if (factor < MINOVFACTOR || factor > MAXOVFACTOR) {
rterror(_("build_overview: Overview factor %d is not between %d and %d"), factor, MINOVFACTOR, MAXOVFACTOR);
return 0;
}
dimOv[0] = (int) (info->dim[0] + (factor / 2)) / factor;
dimOv[1] = (int) (info->dim[1] + (factor / 2)) / factor;
/* create VRT dataset */
hdsOv = VRTCreate(dimOv[0], dimOv[1]);
/*
GDALSetDescription(hdsOv, "/tmp/ov.vrt");
*/
GDALSetProjection(hdsOv, info->srs);
/* adjust scale */
gtOv[1] *= factor;
gtOv[5] *= factor;
GDALSetGeoTransform(hdsOv, gtOv);
/* add bands as simple sources */
for (j = 0; j < info->nband_count; j++) {
GDALAddBand(hdsOv, info->gdalbandtype[j], NULL);
hbandOv = (VRTSourcedRasterBandH) GDALGetRasterBand(hdsOv, j + 1);
if (info->hasnodata[j])
GDALSetRasterNoDataValue(hbandOv, info->nodataval[j]);
VRTAddSimpleSource(
hbandOv, GDALGetRasterBand(hdsSrc, info->nband[j]),
0, 0,
info->dim[0], info->dim[1],
0, 0,
dimOv[0], dimOv[1],
"near", VRT_NODATA_UNSET
);
}
/* make sure VRT reflects all changes */
VRTFlushCache(hdsOv);
/* decide on tile size */
if (!config->tile_size[0])
tile_size[0] = dimOv[0];
else
tile_size[0] = config->tile_size[0];
if (!config->tile_size[1])
tile_size[1] = dimOv[1];
else
tile_size[1] = config->tile_size[1];
/* number of tiles */
if (
tile_size[0] != dimOv[0] &&
tile_size[1] != dimOv[1]
) {
ntiles[0] = (dimOv[0] + tile_size[0] - 1) / tile_size[0];
ntiles[1] = (dimOv[1] + tile_size[1] - 1) / tile_size[1];
}
/* working copy of geotransform matrix */
memcpy(gt, gtOv, sizeof(double) * 6);
/* tile overview */
/* each tile is a VRT with constraints set for just the data required for the tile */
for (ytile = 0; ytile < ntiles[1]; ytile++) {
/* edge y tile */
if (!config->pad_tile && ntiles[1] > 1 && (ytile + 1) == ntiles[1])
_tile_size[1] = dimOv[1] - (ytile * tile_size[1]);
else
_tile_size[1] = tile_size[1];
for (xtile = 0; xtile < ntiles[0]; xtile++) {
/*
char fn[100];
sprintf(fn, "/tmp/ovtile%d.vrt", (ytile * ntiles[0]) + xtile);
*/
/* edge x tile */
if (!config->pad_tile && ntiles[0] > 1 && (xtile + 1) == ntiles[0])
_tile_size[0] = dimOv[0] - (xtile * tile_size[0]);
else
_tile_size[0] = tile_size[0];
/* compute tile's upper-left corner */
GDALApplyGeoTransform(
gtOv,
xtile * tile_size[0], ytile * tile_size[1],
&(gt[0]), &(gt[3])
);
/* create VRT dataset */
hdsDst = VRTCreate(_tile_size[0], _tile_size[1]);
/*
GDALSetDescription(hdsDst, fn);
*/
GDALSetProjection(hdsDst, info->srs);
GDALSetGeoTransform(hdsDst, gt);
/* add bands as simple sources */
for (j = 0; j < info->nband_count; j++) {
GDALAddBand(hdsDst, info->gdalbandtype[j], NULL);
hbandDst = (VRTSourcedRasterBandH) GDALGetRasterBand(hdsDst, j + 1);
if (info->hasnodata[j])
GDALSetRasterNoDataValue(hbandDst, info->nodataval[j]);
VRTAddSimpleSource(
hbandDst, GDALGetRasterBand(hdsOv, j + 1),
xtile * tile_size[0], ytile * tile_size[1],
_tile_size[0], _tile_size[1],
0, 0,
_tile_size[0], _tile_size[1],
"near", VRT_NODATA_UNSET
);
}
/* make sure VRT reflects all changes */
VRTFlushCache(hdsDst);
/* convert VRT dataset to rt_raster */
rast = rt_raster_from_gdal_dataset(hdsDst);
if (rast == NULL) {
rterror(_("build_overview: Could not convert VRT dataset to PostGIS raster"));
GDALClose(hdsDst);
return 0;
}
/* set srid if provided */
rt_raster_set_srid(rast, info->srid);
/* convert rt_raster to hexwkb */
hex = rt_raster_to_hexwkb(rast, FALSE, &hexlen);
raster_destroy(rast);
if (hex == NULL) {
rterror(_("build_overview: Could not convert PostGIS raster to hex WKB"));
GDALClose(hdsDst);
return 0;
}
/* add hexwkb to tileset */
append_stringbuffer(tileset, hex);
rtdealloc(hex);
GDALClose(hdsDst);
/* flush if tileset gets too big */
if (tileset->length > 10) {
if (!insert_records(
config->schema, ovtable, config->raster_column,
(config->file_column ? config->rt_filename[idx] : NULL), config->file_column_name,
config->copy_statements,
tileset, buffer
)) {
rterror(_("build_overview: Could not convert raster tiles into INSERT or COPY statements"));
GDALClose(hdsSrc);
return 0;
}
rtdealloc_stringbuffer(tileset, 0);
}
}
}
GDALClose(hdsOv);
GDALClose(hdsSrc);
return 1;
}
static int
convert_raster(int idx, RTLOADERCFG *config, RASTERINFO *info, STRINGBUFFER *tileset, STRINGBUFFER *buffer) {
GDALDatasetH hdsSrc;
GDALRasterBandH hbandSrc;
int nband = 0;
int i = 0;
int ntiles[2] = {1, 1};
int _tile_size[2] = {0, 0};
int xtile = 0;
int ytile = 0;
double gt[6] = {0.};
const char* pszProjectionRef = NULL;
int tilesize = 0;
rt_raster rast = NULL;
int numbands = 0;
rt_band band = NULL;
char *hex;
uint32_t hexlen = 0;
info->srid = config->srid;
hdsSrc = GDALOpenShared(config->rt_file[idx], GA_ReadOnly);
if (hdsSrc == NULL) {
rterror(_("convert_raster: Could not open raster: %s"), config->rt_file[idx]);
return 0;
}
nband = GDALGetRasterCount(hdsSrc);
if (!nband) {
rterror(_("convert_raster: No bands found in raster: %s"), config->rt_file[idx]);
GDALClose(hdsSrc);
return 0;
}
/* check that bands specified are available */
for (i = 0; i < config->nband_count; i++) {
if (config->nband[i] > nband) {
rterror(_("convert_raster: Band %d not found in raster: %s"), config->nband[i], config->rt_file[idx]);
GDALClose(hdsSrc);
return 0;
}
}
/* record srs */
pszProjectionRef = GDALGetProjectionRef(hdsSrc);
if (pszProjectionRef != NULL && pszProjectionRef[0] != '\0') {
info->srs = rtalloc(sizeof(char) * (strlen(pszProjectionRef) + 1));
if (info->srs == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing SRS"));
GDALClose(hdsSrc);
return 0;
}
strcpy(info->srs, pszProjectionRef);
if (info->srid == SRID_UNKNOWN) {
OGRSpatialReferenceH hSRS = OSRNewSpatialReference(NULL);
if (OSRSetFromUserInput(hSRS, pszProjectionRef) == OGRERR_NONE) {
const char* pszAuthorityName = OSRGetAuthorityName(hSRS, NULL);
const char* pszAuthorityCode = OSRGetAuthorityCode(hSRS, NULL);
if (
pszAuthorityName != NULL &&
strcmp(pszAuthorityName, "EPSG") == 0 &&
pszAuthorityCode != NULL
) {
info->srid = atoi(pszAuthorityCode);
}
}
OSRDestroySpatialReference(hSRS);
}
}
/* record geotransform matrix */
if (GDALGetGeoTransform(hdsSrc, info->gt) != CE_None) {
rtinfo(_("Using default geotransform matrix (0, 1, 0, 0, 0, -1) for raster: %s"), config->rt_file[idx]);
info->gt[0] = 0;
info->gt[1] = 1;
info->gt[2] = 0;
info->gt[3] = 0;
info->gt[4] = 0;
info->gt[5] = -1;
}
memcpy(gt, info->gt, sizeof(double) * 6);
/* record # of bands */
/* user-specified bands */
if (config->nband_count > 0) {
info->nband_count = config->nband_count;
info->nband = rtalloc(sizeof(int) * info->nband_count);
if (info->nband == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing band indices"));
GDALClose(hdsSrc);
return 0;
}
memcpy(info->nband, config->nband, sizeof(int) * info->nband_count);
}
/* all bands */
else {
info->nband_count = nband;
info->nband = rtalloc(sizeof(int) * info->nband_count);
if (info->nband == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing band indices"));
GDALClose(hdsSrc);
return 0;
}
for (i = 0; i < info->nband_count; i++)
info->nband[i] = i + 1;
}
/* initialize parameters dependent on nband */
info->gdalbandtype = rtalloc(sizeof(GDALDataType) * info->nband_count);
if (info->gdalbandtype == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing GDAL data type"));
GDALClose(hdsSrc);
return 0;
}
info->bandtype = rtalloc(sizeof(rt_pixtype) * info->nband_count);
if (info->bandtype == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing pixel type"));
GDALClose(hdsSrc);
return 0;
}
info->hasnodata = rtalloc(sizeof(int) * info->nband_count);
if (info->hasnodata == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing hasnodata flag"));
GDALClose(hdsSrc);
return 0;
}
info->nodataval = rtalloc(sizeof(double) * info->nband_count);
if (info->nodataval == NULL) {
rterror(_("convert_raster: Could not allocate memory for storing nodata value"));
GDALClose(hdsSrc);
return 0;
}
memset(info->gdalbandtype, GDT_Unknown, sizeof(GDALDataType) * info->nband_count);
memset(info->bandtype, PT_END, sizeof(rt_pixtype) * info->nband_count);
memset(info->hasnodata, 0, sizeof(int) * info->nband_count);
memset(info->nodataval, 0, sizeof(double) * info->nband_count);
/* dimensions of raster */
info->dim[0] = GDALGetRasterXSize(hdsSrc);
info->dim[1] = GDALGetRasterYSize(hdsSrc);
/* tile size is "auto" */
if (
config->tile_size[0] == -1 &&
config->tile_size[1] == -1
) {
calc_tile_size(
info->dim[0], info->dim[1],
&(config->tile_size[0]), &(config->tile_size[1])
);
rtinfo(_("Using computed tile size: %dx%d"), config->tile_size[0], config->tile_size[1]);
}
/* decide on tile size */
if (!config->tile_size[0])
info->tile_size[0] = info->dim[0];
else
info->tile_size[0] = config->tile_size[0];
if (!config->tile_size[1])
info->tile_size[1] = info->dim[1];
else
info->tile_size[1] = config->tile_size[1];
/* number of tiles */
if (info->tile_size[0] != info->dim[0])
ntiles[0] = (info->dim[0] + info->tile_size[0] - 1) / info->tile_size[0];
if (info->tile_size[1] != info->dim[1])
ntiles[1] = (info->dim[1] + info->tile_size[1] - 1) / info->tile_size[1];
/* estimate size of 1 tile */
tilesize = info->tile_size[0] * info->tile_size[1];
/* go through bands for attributes */
for (i = 0; i < info->nband_count; i++) {
hbandSrc = GDALGetRasterBand(hdsSrc, info->nband[i]);
/* datatype */
info->gdalbandtype[i] = GDALGetRasterDataType(hbandSrc);
/* complex data type? */
if (GDALDataTypeIsComplex(info->gdalbandtype[i])) {
rterror(_("convert_raster: The pixel type of band %d is a complex data type. PostGIS raster does not support complex data types"), i + 1);
GDALClose(hdsSrc);
return 0;
}
/* convert data type to that of postgis raster */
info->bandtype[i] = rt_util_gdal_datatype_to_pixtype(info->gdalbandtype[i]);
/* hasnodata and nodataval */
info->nodataval[i] = GDALGetRasterNoDataValue(hbandSrc, &(info->hasnodata[i]));
if (!info->hasnodata[i]) {
/* does NOT have nodata value, but user-specified */
if (config->hasnodata) {
info->hasnodata[i] = 1;
info->nodataval[i] = config->nodataval;
}
else
info->nodataval[i] = 0;
}
/* update estimated size of 1 tile */
tilesize *= rt_pixtype_size(info->bandtype[i]);
}
/* roughly estimate size of one tile and all bands */
tilesize *= 1.1;
if (tilesize > MAXTILESIZE)
rtwarn(_("The size of each output tile may exceed 1 GB. Use -t to specify a reasonable tile size"));
/* out-db raster */
if (config->outdb) {
GDALClose(hdsSrc);
/* each tile is a raster */
for (ytile = 0; ytile < ntiles[1]; ytile++) {
/* edge y tile */
if (!config->pad_tile && ntiles[1] > 1 && (ytile + 1) == ntiles[1])
_tile_size[1] = info->dim[1] - (ytile * info->tile_size[1]);
else
_tile_size[1] = info->tile_size[1];
for (xtile = 0; xtile < ntiles[0]; xtile++) {
/* edge x tile */
if (!config->pad_tile && ntiles[0] > 1 && (xtile + 1) == ntiles[0])
_tile_size[0] = info->dim[0] - (xtile * info->tile_size[0]);
else
_tile_size[0] = info->tile_size[0];
/* compute tile's upper-left corner */
GDALApplyGeoTransform(
info->gt,
xtile * info->tile_size[0], ytile * info->tile_size[1],
&(gt[0]), &(gt[3])
);
/* create raster object */
rast = rt_raster_new(_tile_size[0], _tile_size[1]);
if (rast == NULL) {
rterror(_("convert_raster: Could not create raster"));
return 0;
}
/* set raster attributes */
rt_raster_set_srid(rast, info->srid);
rt_raster_set_geotransform_matrix(rast, gt);
/* add bands */
for (i = 0; i < info->nband_count; i++) {
band = rt_band_new_offline(
_tile_size[0], _tile_size[1],
info->bandtype[i],
info->hasnodata[i], info->nodataval[i],
info->nband[i] - 1,
config->rt_file[idx]
);
if (band == NULL) {
rterror(_("convert_raster: Could not create offline band"));
raster_destroy(rast);
return 0;
}
/* add band to raster */
if (rt_raster_add_band(rast, band, rt_raster_get_num_bands(rast)) == -1) {
rterror(_("convert_raster: Could not add offlineband to raster"));
rt_band_destroy(band);
raster_destroy(rast);
return 0;
}
/* inspect each band of raster where band is NODATA */
if (!config->skip_nodataval_check)
rt_band_check_is_nodata(band);
}
/* convert rt_raster to hexwkb */
hex = rt_raster_to_hexwkb(rast, FALSE, &hexlen);
raster_destroy(rast);
if (hex == NULL) {
rterror(_("convert_raster: Could not convert PostGIS raster to hex WKB"));
return 0;
}
/* add hexwkb to tileset */
append_stringbuffer(tileset, hex);
rtdealloc(hex);
/* flush if tileset gets too big */
if (tileset->length > 10) {
if (!insert_records(
config->schema, config->table, config->raster_column,
(config->file_column ? config->rt_filename[idx] : NULL), config->file_column_name,
config->copy_statements,
tileset, buffer
)) {
rterror(_("convert_raster: Could not convert raster tiles into INSERT or COPY statements"));
return 0;
}
rtdealloc_stringbuffer(tileset, 0);
}
}
}
}
/* in-db raster */
else {
VRTDatasetH hdsDst;
VRTSourcedRasterBandH hbandDst;
/* each tile is a VRT with constraints set for just the data required for the tile */
for (ytile = 0; ytile < ntiles[1]; ytile++) {
/* edge y tile */
if (!config->pad_tile && ntiles[1] > 1 && (ytile + 1) == ntiles[1])
_tile_size[1] = info->dim[1] - (ytile * info->tile_size[1]);
else
_tile_size[1] = info->tile_size[1];
for (xtile = 0; xtile < ntiles[0]; xtile++) {
/*
char fn[100];
sprintf(fn, "/tmp/tile%d.vrt", (ytile * ntiles[0]) + xtile);
*/
/* edge x tile */
if (!config->pad_tile && ntiles[0] > 1 && (xtile + 1) == ntiles[0])
_tile_size[0] = info->dim[0] - (xtile * info->tile_size[0]);
else
_tile_size[0] = info->tile_size[0];
/* compute tile's upper-left corner */
GDALApplyGeoTransform(
info->gt,
xtile * info->tile_size[0], ytile * info->tile_size[1],
&(gt[0]), &(gt[3])
);
/*
rtinfo(_("tile (%d, %d) gt = (%f, %f, %f, %f, %f, %f)"),
xtile, ytile,
gt[0], gt[1], gt[2], gt[3], gt[4], gt[5]
);
*/
/* create VRT dataset */
hdsDst = VRTCreate(_tile_size[0], _tile_size[1]);
/*
GDALSetDescription(hdsDst, fn);
*/
GDALSetProjection(hdsDst, info->srs);
GDALSetGeoTransform(hdsDst, gt);
/* add bands as simple sources */
for (i = 0; i < info->nband_count; i++) {
GDALAddBand(hdsDst, info->gdalbandtype[i], NULL);
hbandDst = (VRTSourcedRasterBandH) GDALGetRasterBand(hdsDst, i + 1);
if (info->hasnodata[i])
GDALSetRasterNoDataValue(hbandDst, info->nodataval[i]);
VRTAddSimpleSource(
hbandDst, GDALGetRasterBand(hdsSrc, info->nband[i]),
xtile * info->tile_size[0], ytile * info->tile_size[1],
_tile_size[0], _tile_size[1],
0, 0,
_tile_size[0], _tile_size[1],
"near", VRT_NODATA_UNSET
);
}
/* make sure VRT reflects all changes */
VRTFlushCache(hdsDst);
/* convert VRT dataset to rt_raster */
rast = rt_raster_from_gdal_dataset(hdsDst);
if (rast == NULL) {
rterror(_("convert_raster: Could not convert VRT dataset to PostGIS raster"));
GDALClose(hdsDst);
return 0;
}
/* set srid if provided */
rt_raster_set_srid(rast, info->srid);
/* inspect each band of raster where band is NODATA */
numbands = rt_raster_get_num_bands(rast);
for (i = 0; i < numbands; i++) {
band = rt_raster_get_band(rast, i);
if (band != NULL && !config->skip_nodataval_check)
rt_band_check_is_nodata(band);
}
/* convert rt_raster to hexwkb */
hex = rt_raster_to_hexwkb(rast, FALSE, &hexlen);
raster_destroy(rast);
if (hex == NULL) {
rterror(_("convert_raster: Could not convert PostGIS raster to hex WKB"));
GDALClose(hdsDst);
return 0;
}
/* add hexwkb to tileset */
append_stringbuffer(tileset, hex);
rtdealloc(hex);
GDALClose(hdsDst);
/* flush if tileset gets too big */
if (tileset->length > 10) {
if (!insert_records(
config->schema, config->table, config->raster_column,
(config->file_column ? config->rt_filename[idx] : NULL), config->file_column_name,
config->copy_statements,
tileset, buffer
)) {
rterror(_("convert_raster: Could not convert raster tiles into INSERT or COPY statements"));
GDALClose(hdsSrc);
return 0;
}
rtdealloc_stringbuffer(tileset, 0);
}
}
}
GDALClose(hdsSrc);
}
return 1;
}
static int
process_rasters(RTLOADERCFG *config, STRINGBUFFER *buffer) {
int i = 0;
assert(config != NULL);
assert(config->table != NULL);
assert(config->raster_column != NULL);
if (config->transaction) {
if (!append_sql_to_buffer(buffer, "BEGIN;")) {
rterror(_("process_rasters: Could not add BEGIN statement to string buffer"));
return 0;
}
}
/* drop table */
if (config->opt == 'd') {
if (!drop_table(config->schema, config->table, buffer)) {
rterror(_("process_rasters: Could not add DROP TABLE statement to string buffer"));
return 0;
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
if (!drop_table(config->schema, config->overview_table[i], buffer)) {
rterror(_("process_rasters: Could not add an overview's DROP TABLE statement to string buffer"));
return 0;
}
}
}
}
/* create table */
if (config->opt != 'a') {
if (!create_table(
config->schema, config->table, config->raster_column,
config->file_column, config->file_column_name,
config->tablespace, config->idx_tablespace,
buffer
)) {
rterror(_("process_rasters: Could not add CREATE TABLE statement to string buffer"));
return 0;
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
if (!create_table(
config->schema, config->overview_table[i], config->raster_column,
config->file_column, config->file_column_name,
config->tablespace, config->idx_tablespace,
buffer
)) {
rterror(_("process_rasters: Could not add an overview's CREATE TABLE statement to string buffer"));
return 0;
}
}
}
}
/* no need to run if opt is 'p' */
if (config->opt != 'p') {
RASTERINFO refinfo;
init_rastinfo(&refinfo);
/* process each raster */
for (i = 0; i < config->rt_file_count; i++) {
RASTERINFO rastinfo;
STRINGBUFFER tileset;
fprintf(stderr, _("Processing %d/%d: %s\n"), i + 1, config->rt_file_count, config->rt_file[i]);
init_rastinfo(&rastinfo);
init_stringbuffer(&tileset);
if (config->copy_statements && !copy_from(
config->schema, config->table, config->raster_column,
(config->file_column ? config->rt_filename[i] : NULL), config->file_column_name,
buffer
)) {
rterror(_("process_rasters: Could not add COPY statement to string buffer"));
rtdealloc_rastinfo(&rastinfo);
rtdealloc_stringbuffer(&tileset, 0);
return 0;
}
/* convert raster */
if (!convert_raster(i, config, &rastinfo, &tileset, buffer)) {
rterror(_("process_rasters: Could not process raster: %s"), config->rt_file[i]);
rtdealloc_rastinfo(&rastinfo);
rtdealloc_stringbuffer(&tileset, 0);
return 0;
}
/* process raster tiles into COPY or INSERT statements */
if (tileset.length && !insert_records(
config->schema, config->table, config->raster_column,
(config->file_column ? config->rt_filename[i] : NULL), config->file_column_name,
config->copy_statements,
&tileset, buffer
)) {
rterror(_("process_rasters: Could not convert raster tiles into INSERT or COPY statements"));
rtdealloc_rastinfo(&rastinfo);
rtdealloc_stringbuffer(&tileset, 0);
return 0;
}
rtdealloc_stringbuffer(&tileset, 0);
if (config->copy_statements && !copy_from_end(buffer)) {
rterror(_("process_rasters: Could not add COPY end statement to string buffer"));
rtdealloc_rastinfo(&rastinfo);
return 0;
}
/* flush buffer after every raster */
flush_stringbuffer(buffer);
/* overviews */
if (config->overview_count) {
int j = 0;
for (j = 0; j < config->overview_count; j++) {
if (config->copy_statements && !copy_from(
config->schema, config->overview_table[j], config->raster_column,
(config->file_column ? config->rt_filename[i] : NULL), config->file_column_name,
buffer
)) {
rterror(_("process_rasters: Could not add COPY statement to string buffer"));
rtdealloc_rastinfo(&rastinfo);
rtdealloc_stringbuffer(&tileset, 0);
return 0;
}
if (!build_overview(i, config, &rastinfo, j, &tileset, buffer)) {
rterror(_("process_rasters: Could not create overview of factor %d for raster %s"), config->overview[j], config->rt_file[i]);
rtdealloc_rastinfo(&rastinfo);
rtdealloc_stringbuffer(&tileset, 0);
return 0;
}
if (tileset.length && !insert_records(
config->schema, config->overview_table[j], config->raster_column,
(config->file_column ? config->rt_filename[i] : NULL), config->file_column_name,
config->copy_statements,
&tileset, buffer
)) {
rterror(_("process_rasters: Could not convert overview tiles into INSERT or COPY statements"));
rtdealloc_rastinfo(&rastinfo);
rtdealloc_stringbuffer(&tileset, 0);
return 0;
}
rtdealloc_stringbuffer(&tileset, 0);
/* flush buffer after every raster */
flush_stringbuffer(buffer);
if (config->copy_statements) {
if (!copy_from_end(buffer)) {
rterror(_("process_rasters: Could not add COPY end statement to string buffer"));
rtdealloc_rastinfo(&rastinfo);
return 0;
}
}
}
}
if (config->rt_file_count > 1) {
if (i < 1)
copy_rastinfo(&refinfo, &rastinfo);
else {
diff_rastinfo(&rastinfo, &refinfo);
}
}
rtdealloc_rastinfo(&rastinfo);
}
rtdealloc_rastinfo(&refinfo);
}
/* index */
if (config->idx) {
/* create index */
if (!create_index(
config->schema, config->table, config->raster_column,
config->idx_tablespace,
buffer
)) {
rterror(_("process_rasters: Could not add CREATE INDEX statement to string buffer"));
return 0;
}
/* analyze */
if (config->opt != 'p') {
if (!analyze_table(
config->schema, config->table,
buffer
)) {
rterror(_("process_rasters: Could not add ANALYZE statement to string buffer"));
return 0;
}
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
/* create index */
if (!create_index(
config->schema, config->overview_table[i], config->raster_column,
config->idx_tablespace,
buffer
)) {
rterror(_("process_rasters: Could not add an overview's CREATE INDEX statement to string buffer"));
return 0;
}
/* analyze */
if (config->opt != 'p') {
if (!analyze_table(
config->schema, config->overview_table[i],
buffer
)) {
rterror(_("process_rasters: Could not add an overview's ANALYZE statement to string buffer"));
return 0;
}
}
}
}
}
/* add constraints */
if (config->constraints) {
if (!add_raster_constraints(
config->schema, config->table, config->raster_column,
config->regular_blocking, config->max_extent,
buffer
)) {
rterror(_("process:rasters: Could not add AddRasterConstraints statement to string buffer"));
return 0;
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
if (!add_raster_constraints(
config->schema, config->overview_table[i], config->raster_column,
config->regular_blocking, config->max_extent,
buffer
)) {
rterror(_("process_rasters: Could not add an overview's AddRasterConstraints statement to string buffer"));
return 0;
}
}
}
}
/* overview constraint is automatically added */
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
if (!add_overview_constraints(
config->schema, config->overview_table[i], config->raster_column,
config->schema, config->table, config->raster_column,
config->overview[i],
buffer
)) {
rterror(_("process_rasters: Could not add an overview's AddOverviewConstraints statement to string buffer"));
return 0;
}
}
}
if (config->transaction) {
if (!append_sql_to_buffer(buffer, "END;")) {
rterror(_("process_rasters: Could not add END statement to string buffer"));
return 0;
}
}
/* maintenance */
if (config->opt != 'p' && config->maintenance) {
if (!vacuum_table(
config->schema, config->table,
buffer
)) {
rterror(_("process_rasters: Could not add VACUUM statement to string buffer"));
return 0;
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
if (!vacuum_table(
config->schema, config->overview_table[i],
buffer
)) {
rterror(_("process_rasters: Could not add an overview's VACUUM statement to string buffer"));
return 0;
}
}
}
}
return 1;
}
int
main(int argc, char **argv) {
RTLOADERCFG *config = NULL;
STRINGBUFFER *buffer = NULL;
int i = 0;
int j = 0;
char **elements = NULL;
int n = 0;
GDALDriverH drv = NULL;
char *tmp = NULL;
#ifdef USE_NLS
setlocale (LC_ALL, "");
bindtextdomain (PACKAGE, LOCALEDIR);
textdomain (PACKAGE);
#endif
/* no args, show usage */
if (argc == 1) {
usage();
exit(0);
}
/* initialize config */
config = rtalloc(sizeof(RTLOADERCFG));
if (config == NULL) {
rterror(_("Could not allocate memory for loader configuration"));
exit(1);
}
init_config(config);
/****************************************************************************
* parse arguments
****************************************************************************/
for (i = 1; i < argc; i++) {
/* srid */
if (CSEQUAL(argv[i], "-s") && i < argc - 1) {
config->srid = atoi(argv[++i]);
}
/* band index */
else if (CSEQUAL(argv[i], "-b") && i < argc - 1) {
elements = strsplit(argv[++i], ",", &n);
if (n < 1) {
rterror(_("Could not process -b"));
rtdealloc_config(config);
exit(1);
}
config->nband_count = 0;
for (j = 0; j < n; j++) {
char *t = trim(elements[j]);
char **minmax = NULL;
int *range = NULL;
int p = 0;
int l = 0;
int m = 0;
int o = 0;
/* is t a range? */
minmax = strsplit(t, "-", &o);
if (o == 2) {
if (!array_range(atoi(minmax[0]), atoi(minmax[1]), 1, &range, &p)) {
rterror(_("Could not allocate memory for storing band indices"));
for (l = 0; l < o; l++)
rtdealloc(minmax[l]);
rtdealloc(minmax);
for (j = 0; j < n; j++)
rtdealloc(elements[j]);
rtdealloc(elements);
rtdealloc(t);
rtdealloc_config(config);
exit(1);
}
}
else {
p = 1;
range = rtalloc(sizeof(int));
if (range == NULL) {
rterror(_("Could not allocate memory for storing band indices"));
for (l = 0; l < o; l++)
rtdealloc(minmax[l]);
rtdealloc(minmax);
for (j = 0; j < n; j++)
rtdealloc(elements[j]);
rtdealloc(elements);
rtdealloc(t);
rtdealloc_config(config);
exit(1);
}
*range = atoi(t);
}
m = config->nband_count;
config->nband_count += p;
config->nband = rtrealloc(config->nband, sizeof(int) * config->nband_count);
if (config->nband == NULL) {
rterror(_("Could not allocate memory for storing band indices"));
rtdealloc(range);
for (l = 0; l < o; l++)
rtdealloc(minmax[l]);
rtdealloc(minmax);
for (j = 0; j < n; j++)
rtdealloc(elements[j]);
rtdealloc(elements);
rtdealloc(t);
rtdealloc_config(config);
exit(1);
}
for (l = 0; l < p; l++, m++)
config->nband[m] = range[l];
rtdealloc(range);
for (l = 0; l < o; l++)
rtdealloc(minmax[l]);
rtdealloc(minmax);
rtdealloc(t);
rtdealloc(elements[j]);
}
rtdealloc(elements);
elements = NULL;
n = 0;
for (j = 0; j < config->nband_count; j++) {
if (config->nband[j] < 1) {
rterror(_("Band index %d must be greater than 0"), config->nband[j]);
rtdealloc_config(config);
exit(1);
}
}
}
/* tile size */
else if (CSEQUAL(argv[i], "-t") && i < argc - 1) {
if (CSEQUAL(argv[++i], "auto")) {
config->tile_size[0] = -1;
config->tile_size[1] = -1;
}
else {
elements = strsplit(argv[i], "x", &n);
if (n != 2) {
rterror(_("Could not process -t"));
rtdealloc_config(config);
exit(1);
}
for (j = 0; j < n; j++) {
char *t = trim(elements[j]);
config->tile_size[j] = atoi(t);
rtdealloc(t);
rtdealloc(elements[j]);
}
rtdealloc(elements);
elements = NULL;
n = 0;
for (j = 0; j < 2; j++) {
if (config->tile_size[j] < 1) {
rterror(_("Tile size must be greater than 0x0"));
rtdealloc_config(config);
exit(1);
}
}
}
}
/* pad tiles */
else if (CSEQUAL(argv[i], "-P")) {
config->pad_tile = 1;
}
/* out-of-db raster */
else if (CSEQUAL(argv[i], "-R")) {
config->outdb = 1;
}
/* drop table and recreate */
else if (CSEQUAL(argv[i], "-d")) {
config->opt = 'd';
}
/* append to table */
else if (CSEQUAL(argv[i], "-a")) {
config->opt = 'a';
}
/* create new table */
else if (CSEQUAL(argv[i], "-c")) {
config->opt = 'c';
}
/* prepare only */
else if (CSEQUAL(argv[i], "-p")) {
config->opt = 'p';
}
/* raster column name */
else if (CSEQUAL(argv[i], "-f") && i < argc - 1) {
config->raster_column = rtalloc(sizeof(char) * (strlen(argv[++i]) + 1));
if (config->raster_column == NULL) {
rterror(_("Could not allocate memory for storing raster column name"));
rtdealloc_config(config);
exit(1);
}
strncpy(config->raster_column, argv[i], strlen(argv[i]) + 1);
}
/* filename column */
else if (CSEQUAL(argv[i], "-F")) {
config->file_column = 1;
}
/* filename column name */
else if (CSEQUAL(argv[i], "-n") && i < argc - 1) {
config->file_column_name = rtalloc(sizeof(char) * (strlen(argv[++i]) + 1));
if (config->file_column_name == NULL) {
rterror(_("Could not allocate memory for storing filename column name"));
rtdealloc_config(config);
exit(1);
}
strncpy(config->file_column_name, argv[i], strlen(argv[i]) + 1);
config->file_column = 1;
}
/* overview factors */
else if (CSEQUAL(argv[i], "-l") && i < argc - 1) {
elements = strsplit(argv[++i], ",", &n);
if (n < 1) {
rterror(_("Could not process -l"));
rtdealloc_config(config);
exit(1);
}
config->overview_count = n;
config->overview = rtalloc(sizeof(int) * n);
if (config->overview == NULL) {
rterror(_("Could not allocate memory for storing overview factors"));
rtdealloc_config(config);
exit(1);
}
for (j = 0; j < n; j++) {
char *t = trim(elements[j]);
config->overview[j] = atoi(t);
rtdealloc(t);
rtdealloc(elements[j]);
}
rtdealloc(elements);
elements = NULL;
n = 0;
for (j = 0; j < config->overview_count; j++) {
if (config->overview[j] < MINOVFACTOR || config->overview[j] > MAXOVFACTOR) {
rterror(_("Overview factor %d is not between %d and %d"), config->overview[j], MINOVFACTOR, MAXOVFACTOR);
rtdealloc_config(config);
exit(1);
}
}
}
/* quote identifiers */
else if (CSEQUAL(argv[i], "-q")) {
config->quoteident = 1;
}
/* create index */
else if (CSEQUAL(argv[i], "-I")) {
config->idx = 1;
}
/* maintenance */
else if (CSEQUAL(argv[i], "-M")) {
config->maintenance = 1;
}
/* set constraints */
else if (CSEQUAL(argv[i], "-C")) {
config->constraints = 1;
}
/* disable extent constraint */
else if (CSEQUAL(argv[i], "-x")) {
config->max_extent = 0;
}
/* enable regular_blocking */
else if (CSEQUAL(argv[i], "-r")) {
config->regular_blocking = 1;
}
/* tablespace of new table */
else if (CSEQUAL(argv[i], "-T") && i < argc - 1) {
config->tablespace = rtalloc(sizeof(char) * (strlen(argv[++i]) + 1));
if (config->tablespace == NULL) {
rterror(_("Could not allocate memory for storing tablespace of new table"));
rtdealloc_config(config);
exit(1);
}
strncpy(config->tablespace, argv[i], strlen(argv[i]) + 1);
}
/* tablespace of new index */
else if (CSEQUAL(argv[i], "-X") && i < argc - 1) {
config->idx_tablespace = rtalloc(sizeof(char) * (strlen(argv[++i]) + 1));
if (config->idx_tablespace == NULL) {
rterror(_("Could not allocate memory for storing tablespace of new indices"));
rtdealloc_config(config);
exit(1);
}
strncpy(config->idx_tablespace, argv[i], strlen(argv[i]) + 1);
}
/* nodata value */
else if (CSEQUAL(argv[i], "-N") && i < argc - 1) {
config->hasnodata = 1;
config->nodataval = atof(argv[++i]);
}
/* skip NODATA value check for bands */
else if (CSEQUAL(argv[i], "-k")) {
config->skip_nodataval_check = 1;
}
/* endianness */
else if (CSEQUAL(argv[i], "-E") && i < argc - 1) {
config->endian = atoi(argv[++i]);
config->endian = 1;
}
/* version */
else if (CSEQUAL(argv[i], "-V") && i < argc - 1) {
config->version = atoi(argv[++i]);
config->version = 0;
}
/* transaction */
else if (CSEQUAL(argv[i], "-e")) {
config->transaction = 0;
}
/* COPY statements */
else if (CSEQUAL(argv[i], "-Y")) {
config->copy_statements = 1;
}
/* GDAL formats */
else if (CSEQUAL(argv[i], "-G")) {
uint32_t drv_count = 0;
rt_gdaldriver drv_set = rt_raster_gdal_drivers(&drv_count, 0);
if (drv_set == NULL || !drv_count) {
rterror(_("Could not get list of available GDAL raster formats"));
}
else {
printf(_("Supported GDAL raster formats:\n"));
for (j = 0; j < drv_count; j++) {
printf(_(" %s\n"), drv_set[j].long_name);
rtdealloc(drv_set[j].short_name);
rtdealloc(drv_set[j].long_name);
rtdealloc(drv_set[j].create_options);
}
rtdealloc(drv_set);
}
rtdealloc_config(config);
exit(0);
}
/* help */
else if (CSEQUAL(argv[i], "-?")) {
usage();
rtdealloc_config(config);
exit(0);
}
else {
config->rt_file_count++;
config->rt_file = (char **) rtrealloc(config->rt_file, sizeof(char *) * config->rt_file_count);
if (config->rt_file == NULL) {
rterror(_("Could not allocate memory for storing raster files"));
rtdealloc_config(config);
exit(1);
}
config->rt_file[config->rt_file_count - 1] = rtalloc(sizeof(char) * (strlen(argv[i]) + 1));
if (config->rt_file[config->rt_file_count - 1] == NULL) {
rterror(_("Could not allocate memory for storing raster filename"));
rtdealloc_config(config);
exit(1);
}
strncpy(config->rt_file[config->rt_file_count - 1], argv[i], strlen(argv[i]) + 1);
}
}
/* register GDAL drivers */
GDALAllRegister();
/* no files provided */
if (!config->rt_file_count) {
rterror(_("No raster provided"));
rtdealloc_config(config);
exit(1);
}
/*
at least two files, see if last is table
last isn't recognized by GDAL
*/
else if (config->rt_file_count > 1) {
drv = GDALIdentifyDriver(config->rt_file[config->rt_file_count - 1], NULL);
if (drv == NULL) {
char *ptr;
ptr = strchr(config->rt_file[config->rt_file_count - 1], '.');
/* schema.table */
if (ptr) {
config->schema = rtalloc(sizeof(char) * (ptr - config->rt_file[config->rt_file_count - 1] + 1));
if (config->schema == NULL) {
rterror(_("Could not allocate memory for storing schema name"));
rtdealloc_config(config);
exit(1);
}
snprintf(config->schema, ptr - config->rt_file[config->rt_file_count - 1] + 1, "%s", config->rt_file[config->rt_file_count - 1]);
config->schema[ptr - config->rt_file[config->rt_file_count - 1]] = '\0';
config->table = rtalloc(sizeof(char) * (strlen(config->rt_file[config->rt_file_count - 1]) - strlen(config->schema) + 1));
if (config->table == NULL) {
rterror(_("Could not allocate memory for storing table name"));
rtdealloc_config(config);
exit(1);
}
snprintf(config->table, strlen(config->rt_file[config->rt_file_count - 1]) - strlen(config->schema), "%s", ptr + 1);
config->table[strlen(config->rt_file[config->rt_file_count - 1]) - strlen(config->schema)] = '\0';
}
/* table */
else {
config->table = rtalloc(sizeof(char) * strlen(config->rt_file[config->rt_file_count - 1]) + 1);
if (config->table == NULL) {
rterror(_("Could not allocate memory for storing table name"));
rtdealloc_config(config);
exit(1);
}
strncpy(config->table, config->rt_file[config->rt_file_count - 1], strlen(config->rt_file[config->rt_file_count - 1]) + 1);
}
rtdealloc(config->rt_file[--(config->rt_file_count)]);
config->rt_file = (char **) rtrealloc(config->rt_file, sizeof(char *) * config->rt_file_count);
if (config->rt_file == NULL) {
rterror(_("Could not reallocate the memory holding raster names"));
rtdealloc_config(config);
exit(1);
}
}
}
/****************************************************************************
* validate raster files
****************************************************************************/
/* check that GDAL recognizes all files */
for (i = 0; i < config->rt_file_count; i++) {
drv = GDALIdentifyDriver(config->rt_file[i], NULL);
if (drv == NULL) {
rterror(_("Unable to read raster file: %s"), config->rt_file[i]);
rtdealloc_config(config);
exit(1);
}
}
/* process each file for just the filename */
config->rt_filename = (char **) rtalloc(sizeof(char *) * config->rt_file_count);
if (config->rt_filename == NULL) {
rterror(_("Could not allocate memory for cleaned raster filenames"));
rtdealloc_config(config);
exit(1);
}
for (i = 0; i < config->rt_file_count; i++) {
char *file;
char *ptr;
file = rtalloc(sizeof(char) * (strlen(config->rt_file[i]) + 1));
if (file == NULL) {
rterror(_("Could not allocate memory for cleaned raster filename"));
rtdealloc_config(config);
exit(1);
}
strcpy(file, config->rt_file[i]);
for (ptr = file + strlen(file); ptr > file; ptr--) {
if (*ptr == '/' || *ptr == '\\') {
ptr++;
break;
}
}
config->rt_filename[i] = rtalloc(sizeof(char) * (strlen(ptr) + 1));
if (config->rt_filename[i] == NULL) {
rterror(_("Could not allocate memory for cleaned raster filename"));
rtdealloc_config(config);
exit(1);
}
strcpy(config->rt_filename[i], ptr);
rtdealloc(file);
}
/****************************************************************************
* defaults for table and column names
****************************************************************************/
/* first file as proxy table name */
if (config->table == NULL) {
char *file;
char *ptr;
file = rtalloc(sizeof(char) * (strlen(config->rt_filename[0]) + 1));
if (file == NULL) {
rterror(_("Could not allocate memory for proxy table name"));
rtdealloc_config(config);
exit(1);
}
strcpy(file, config->rt_filename[0]);
for (ptr = file + strlen(file); ptr > file; ptr--) {
if (*ptr == '.') {
*ptr = '\0';
break;
}
}
config->table = rtalloc(sizeof(char) * (strlen(file) + 1));
if (config->table == NULL) {
rterror(_("Could not allocate memory for proxy table name"));
rtdealloc_config(config);
exit(1);
}
strcpy(config->table, file);
rtdealloc(file);
}
/* raster_column not specified, default to "rast" */
if (config->raster_column == NULL) {
config->raster_column = rtalloc(sizeof(char) * (strlen("rast") + 1));
if (config->raster_column == NULL) {
rterror(_("Could not allocate memory for default raster column name"));
rtdealloc_config(config);
exit(1);
}
strcpy(config->raster_column, "rast");
}
/* file_column_name not specified, default to "filename" */
if (config->file_column_name == NULL) {
config->file_column_name = rtalloc(sizeof(char) * (strlen("filename") + 1));
if (config->file_column_name == NULL) {
rterror(_("Could not allocate memory for default filename column name"));
rtdealloc_config(config);
exit(1);
}
strcpy(config->file_column_name, "filename");
}
/****************************************************************************
* literal PostgreSQL identifiers disabled
****************************************************************************/
/* no quotes, lower case everything */
if (!config->quoteident) {
if (config->schema != NULL)
config->schema = strtolower(config->schema);
if (config->table != NULL)
config->table = strtolower(config->table);
if (config->raster_column != NULL)
config->raster_column = strtolower(config->raster_column);
if (config->file_column_name != NULL)
config->file_column_name = strtolower(config->file_column_name);
if (config->tablespace != NULL)
config->tablespace = strtolower(config->tablespace);
if (config->idx_tablespace != NULL)
config->idx_tablespace = strtolower(config->idx_tablespace);
}
/****************************************************************************
* overview table names
****************************************************************************/
if (config->overview_count) {
char factor[4];
config->overview_table = rtalloc(sizeof(char *) * config->overview_count);
if (config->overview_table == NULL) {
rterror(_("Could not allocate memory for overview table names"));
rtdealloc_config(config);
exit(1);
}
for (i = 0; i < config->overview_count; i++) {
sprintf(factor, "%d", config->overview[i]);
config->overview_table[i] = rtalloc(sizeof(char) * (strlen("o__") + strlen(factor) + strlen(config->table) + 1));
if (config->overview_table[i] == NULL) {
rterror(_("Could not allocate memory for overview table name"));
rtdealloc_config(config);
exit(1);
}
sprintf(config->overview_table[i], "o_%d_%s", config->overview[i], config->table);
}
}
/****************************************************************************
* check that identifiers won't get truncated
****************************************************************************/
if (config->schema != NULL && strlen(config->schema) > MAXNAMELEN) {
rtwarn(_("The schema name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->schema,
MAXNAMELEN
);
}
if (config->table != NULL && strlen(config->table) > MAXNAMELEN) {
rtwarn(_("The table name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->table,
MAXNAMELEN
);
}
if (config->raster_column != NULL && strlen(config->raster_column) > MAXNAMELEN) {
rtwarn(_("The column name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->raster_column,
MAXNAMELEN
);
}
if (config->file_column_name != NULL && strlen(config->file_column_name) > MAXNAMELEN) {
rtwarn(_("The column name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->file_column_name,
MAXNAMELEN
);
}
if (config->tablespace != NULL && strlen(config->tablespace) > MAXNAMELEN) {
rtwarn(_("The tablespace name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->tablespace,
MAXNAMELEN
);
}
if (config->idx_tablespace != NULL && strlen(config->idx_tablespace) > MAXNAMELEN) {
rtwarn(_("The index tablespace name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->idx_tablespace,
MAXNAMELEN
);
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
if (strlen(config->overview_table[i]) > MAXNAMELEN) {
rtwarn(_("The overview table name \"%s\" may exceed the maximum string length permitted for PostgreSQL identifiers (%d)"),
config->overview_table[i],
MAXNAMELEN
);
}
}
}
/****************************************************************************
* double quote identifiers
****************************************************************************/
if (config->schema != NULL) {
tmp = rtalloc(sizeof(char) * (strlen(config->schema) + 4));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting schema name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\".", config->schema);
rtdealloc(config->schema);
config->schema = tmp;
}
if (config->table != NULL) {
tmp = rtalloc(sizeof(char) * (strlen(config->table) + 3));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting table name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\"", config->table);
rtdealloc(config->table);
config->table = tmp;
}
if (config->raster_column != NULL) {
tmp = rtalloc(sizeof(char) * (strlen(config->raster_column) + 3));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting raster column name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\"", config->raster_column);
rtdealloc(config->raster_column);
config->raster_column = tmp;
}
if (config->file_column_name != NULL) {
tmp = rtalloc(sizeof(char) * (strlen(config->file_column_name) + 3));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting raster column name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\"", config->file_column_name);
rtdealloc(config->file_column_name);
config->file_column_name = tmp;
}
if (config->tablespace != NULL) {
tmp = rtalloc(sizeof(char) * (strlen(config->tablespace) + 3));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting tablespace name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\"", config->tablespace);
rtdealloc(config->tablespace);
config->tablespace = tmp;
}
if (config->idx_tablespace != NULL) {
tmp = rtalloc(sizeof(char) * (strlen(config->idx_tablespace) + 3));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting index tablespace name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\"", config->idx_tablespace);
rtdealloc(config->idx_tablespace);
config->idx_tablespace = tmp;
}
if (config->overview_count) {
for (i = 0; i < config->overview_count; i++) {
tmp = rtalloc(sizeof(char) * (strlen(config->overview_table[i]) + 3));
if (tmp == NULL) {
rterror(_("Could not allocate memory for quoting overview table name"));
rtdealloc_config(config);
exit(1);
}
sprintf(tmp, "\"%s\"", config->overview_table[i]);
rtdealloc(config->overview_table[i]);
config->overview_table[i] = tmp;
}
}
/****************************************************************************
* processing of rasters
****************************************************************************/
/* initialize string buffer */
buffer = rtalloc(sizeof(STRINGBUFFER));
if (buffer == NULL) {
rterror(_("Could not allocate memory for output string buffer"));
rtdealloc_config(config);
exit(1);
}
init_stringbuffer(buffer);
/* pass off to processing function */
if (!process_rasters(config, buffer)) {
rterror(_("Unable to process rasters"));
rtdealloc_stringbuffer(buffer, 1);
rtdealloc_config(config);
exit(1);
}
flush_stringbuffer(buffer);
rtdealloc_stringbuffer(buffer, 1);
rtdealloc_config(config);
return 0;
}
|
luisbosque/package-postgis
|
raster/loader/raster2pgsql.c
|
C
|
gpl-2.0
| 82,806
|
<?php
/**
* Part of the Joomla Framework Http Package
*
* @copyright Copyright (C) 2005 - 2013 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
namespace Joomla\Http\Transport;
use Joomla\Http\TransportInterface;
use Joomla\Http\Response;
use Joomla\Uri\UriInterface;
/**
* HTTP transport class for using PHP streams.
*
* @since 1.0
*/
class Stream implements TransportInterface
{
/**
* @var array The client options.
* @since 1.0
*/
protected $options;
/**
* Constructor.
*
* @param array $options Client options object.
*
* @since 1.0
* @throws \RuntimeException
*/
public function __construct($options = array())
{
// Verify that fopen() is available.
if (!self::isSupported())
{
throw new \RuntimeException('Cannot use a stream transport when fopen() is not available.');
}
// Verify that URLs can be used with fopen();
if (!ini_get('allow_url_fopen'))
{
throw new \RuntimeException('Cannot use a stream transport when "allow_url_fopen" is disabled.');
}
$this->options = $options;
}
/**
* Send a request to the server and return a JHttpResponse object with the response.
*
* @param string $method The HTTP method for sending the request.
* @param UriInterface $uri The URI to the resource to request.
* @param mixed $data Either an associative array or a string to be sent with the request.
* @param array $headers An array of request headers to send with the request.
* @param integer $timeout Read timeout in seconds.
* @param string $userAgent The optional user agent string to send with the request.
*
* @return Response
*
* @since 1.0
* @throws \RuntimeException
*/
public function request($method, UriInterface $uri, $data = null, array $headers = null, $timeout = null, $userAgent = null)
{
// Create the stream context options array with the required method offset.
$options = array('method' => strtoupper($method));
// If data exists let's encode it and make sure our Content-Type header is set.
if (isset($data))
{
// If the data is a scalar value simply add it to the stream context options.
if (is_scalar($data))
{
$options['content'] = $data;
}
else
// Otherwise we need to encode the value first.
{
$options['content'] = http_build_query($data);
}
if (!isset($headers['Content-Type']))
{
$headers['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
}
// Add the relevant headers.
$headers['Content-Length'] = strlen($options['content']);
}
// Build the headers string for the request.
$headerString = null;
if (isset($headers))
{
foreach ($headers as $key => $value)
{
$headerString .= $key . ': ' . $value . "\r\n";
}
// Add the headers string into the stream context options array.
$options['header'] = trim($headerString, "\r\n");
}
// If an explicit timeout is given user it.
if (isset($timeout))
{
$options['timeout'] = (int) $timeout;
}
// If an explicit user agent is given use it.
if (isset($userAgent))
{
$options['user_agent'] = $userAgent;
}
// Ignore HTTP errors so that we can capture them.
$options['ignore_errors'] = 1;
// Follow redirects.
$options['follow_location'] = isset($this->options['follow_location']) ? (int) $this->options['follow_location'] : 1;
// Create the stream context for the request.
$context = stream_context_create(array('http' => $options));
// Capture PHP errors
$php_errormsg = '';
$track_errors = ini_get('track_errors');
ini_set('track_errors', true);
// Open the stream for reading.
$stream = @fopen((string) $uri, 'r', false, $context);
if (!$stream)
{
if (!$php_errormsg)
{
// Error but nothing from php? Create our own
// @todo $err and $errno are undefined variables.
$php_errormsg = sprintf('Could not connect to resource: %s', $uri, $err, $errno);
}
// Restore error tracking to give control to the exception handler
ini_set('track_errors', $track_errors);
throw new \RuntimeException($php_errormsg);
}
// Restore error tracking to what it was before.
ini_set('track_errors', $track_errors);
// Get the metadata for the stream, including response headers.
$metadata = stream_get_meta_data($stream);
// Get the contents from the stream.
$content = stream_get_contents($stream);
// Close the stream.
fclose($stream);
if (isset($metadata['wrapper_data']['headers']))
{
$headers = $metadata['wrapper_data']['headers'];
}
elseif (isset($metadata['wrapper_data']))
{
$headers = $metadata['wrapper_data'];
}
else
{
$headers = array();
}
return $this->getResponse($headers, $content);
}
/**
* Method to get a response object from a server response.
*
* @param array $headers The response headers as an array.
* @param string $body The response body as a string.
*
* @return Response
*
* @since 1.0
* @throws \UnexpectedValueException
*/
protected function getResponse(array $headers, $body)
{
// Create the response object.
$return = new Response;
// Set the body for the response.
$return->body = $body;
// Get the response code from the first offset of the response headers.
preg_match('/[0-9]{3}/', array_shift($headers), $matches);
$code = $matches[0];
if (is_numeric($code))
{
$return->code = (int) $code;
}
// No valid response code was detected.
else
{
throw new \UnexpectedValueException('No HTTP response code found.');
}
// Add the response headers to the response object.
foreach ($headers as $header)
{
$pos = strpos($header, ':');
$return->headers[trim(substr($header, 0, $pos))] = trim(substr($header, ($pos + 1)));
}
return $return;
}
/**
* Method to check if http transport stream available for use
*
* @return boolean True if available else false
*
* @since 1.0
*/
public static function isSupported()
{
return function_exists('fopen') && is_callable('fopen') && ini_get('allow_url_fopen');
}
}
|
elkuku/jfw-http
|
src/Transport/Stream.php
|
PHP
|
gpl-2.0
| 6,215
|
/*
* Copyright (C) 2010 Google Inc. All rights reserved.
* Copyright (C) 2010, 2012, 2014 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <functional>
#include <wtf/Forward.h>
#include <wtf/Function.h>
namespace WebCore {
class FileStreamClient;
class FileStream;
class URL;
class WEBCORE_EXPORT AsyncFileStream {
public:
explicit AsyncFileStream(FileStreamClient&);
~AsyncFileStream();
void getSize(const String& path, double expectedModificationTime);
void openForRead(const String& path, long long offset, long long length);
void close();
void read(char* buffer, int length);
private:
void start();
void perform(Function<std::function<void(FileStreamClient&)>(FileStream&)>&&);
struct Internals;
std::unique_ptr<Internals> m_internals;
};
} // namespace WebCore
|
Debian/openjfx
|
modules/web/src/main/native/Source/WebCore/fileapi/AsyncFileStream.h
|
C
|
gpl-2.0
| 2,327
|
<?php
/**
* Module: Soapbox
* Author: hsalazar
* Licence: GNU
*/
use Xmf\Request;
use XoopsModules\Soapbox;
require __DIR__ . '/header.php';
/** @var Soapbox\Helper $helper */
$helper = Soapbox\Helper::getInstance();
global $moduleDirName;
$moduleDirName = $myts->htmlSpecialChars(basename(__DIR__));
if ('soapbox' !== $moduleDirName && '' !== $moduleDirName && !preg_match('/^(\D+)(\d*)$/', $moduleDirName)) {
echo('invalid dirname: ' . htmlspecialchars($moduleDirName, ENT_QUOTES));
}
//require_once XOOPS_ROOT_PATH . '/modules/' . $moduleDirName . '/include/cleantags.php';
//$articleID = Request::getInt('$articleID', Request::getInt('$articleID', 0, 'POST'), 'GET');
if (\Xmf\Request::hasVar('articleID', 'GET')) {
$articleID = \Xmf\Request::getInt('articleID', 0, 'GET');
}
if (\Xmf\Request::hasVar('articleID', 'POST')) {
$articleID = \Xmf\Request::getInt('articleID', 0, 'POST');
}
if (0 === $articleID) {
redirect_header('index.php');
}
/**
* @param $articleID
*/
function PrintPage($articleID)
{
global $moduleDirName;
global $xoopsConfig, $xoopsModule;
/** @var Soapbox\Helper $helper */
$helper = Soapbox\Helper::getInstance();
$cleantags = new Soapbox\Cleantags();
$myts = \MyTextSanitizer:: getInstance();
$articleID = (int)$articleID;
//get entry object
/** @var \XoopsModules\Soapbox\EntrygetHandler $entrydataHandler */
$entrydataHandler = new \XoopsModules\Soapbox\EntrygetHandler();
$_entryob = $entrydataHandler->getArticleOnePermcheck($articleID, true, true);
if (!is_object($_entryob)) {
redirect_header(XOOPS_URL . '/modules/' . $moduleDirName . '/index.php', 1, 'Not Found');
}
//-------------------------------------
$articles = $_entryob->toArray();
//get category object
$_categoryob = $_entryob->_sbcolumns;
//get vars
$category = $_categoryob->toArray();
//-------------------------------------
//get author
$authorname = Soapbox\Utility::getAuthorName($category['author']);
//-------------------------------------
$datetime = $myts->htmlSpecialChars(formatTimestamp($articles['datesub'], $helper->getConfig('dateformat')));
// $lead = $myts->htmlSpecialChars($lead);
// $bodytext = str_replace("[pagebreak]","<br style=\"page-break-after:always;\">",$bodytext);
// $bodytext = $myts->displayTarea($bodytext, $html, $smiley, $xcodes, '', $breaks);
$bodytext = str_replace('[pagebreak]', '<br style="page-break-after:always;">', $_entryob->getVar('bodytext', 'none'));
$bodytext = $cleantags->cleanTags($myts->displayTarea($bodytext, $articles['html'], $articles['smiley'], $articles['xcodes'], '', $articles['breaks']));
$sitename = $myts->htmlSpecialChars($xoopsConfig['sitename']);
$slogan = $myts->htmlSpecialChars($xoopsConfig['slogan']);
echo "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>\n";
echo "<html>\n<head>\n";
echo '<title>' . $sitename . "</title>\n";
echo "<meta http-equiv='Content-Type' content='text/html; charset=" . _CHARSET . "'>\n";
echo "<meta name='AUTHOR' content='" . $sitename . "'>\n";
echo "<meta name='COPYRIGHT' content='Copyright (с) " . $sitename . "'>\n";
echo "<meta name='DESCRIPTION' content='" . $slogan . "'>\n";
echo "<meta name='GENERATOR' content='" . XOOPS_VERSION . "'>\n\n\n";
//hack start 2003-3-18 by toshimitsu
//Column: --> _MD_SOAPBOX_COLUMNPRN , Author: --> _MD_SOAPBOX_AUTHORPRN
echo "<body bgcolor='#ffffff' text='#000000'>
<div style='width: 600px; border: 1px solid #000; padding: 20px;'>
<div style='text-align: center; display: block; padding-bottom: 12px; margin: 0 0 6px 0; border-bottom: 2px solid #ccc;'><h2 style='margin: 0;'>" . $sitename . '<br>' . $articles['headline'] . '</h2></div>
<div></div>
<div>' . _MD_SOAPBOX_COLUMNPRN . '<b>' . $category['name'] . "</b></div>
<div style='padding-bottom: 6px; border-bottom: 1px solid #ccc;'>" . _MD_SOAPBOX_AUTHORPRN . ' <b>' . $authorname . '</b></div>
<p>' . $articles['lead'] . '</p>
<p>' . $articles['bodytext'] . "</p>
<div style='padding-top: 12px; border-top: 2px solid #ccc;'><small><b>Published:</b> " . $datetime . '<br></div>
</div>
<br>
</body>
</html>';
}
PrintPage($articleID);
|
XoopsModules25x/soapbox
|
print.php
|
PHP
|
gpl-2.0
| 4,459
|
<?php
/**
* 迷你同学录 (http://mini_class.piscdong.com/)
* (c)PiscDong studio (http://www.piscdong.com/)
*
* 程序完全免费,请保留这段代码。
* 请勿出售本程序或其修改版,请勿利用本程序或其修改版进行任何商业活动。
*/
session_start();
require_once('config.php');
require_once('function.php');
$c_log=chklog();
if($c_log){
$id=(isset($_GET['i']) && intval($_GET['i']))?intval($_GET['i']):$_SESSION[$config['u_hash']];
switch($_GET['t']){
case 'sina':
if($config['is_sina']>0 && $config['sina_key']!='' && $config['sina_se']!=''){
$s_dby=sprintf('select s_id, s_t from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('sina', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/sina.php');
$so=new sinaPHP($config['sina_key'], $config['sina_se'], $r_dby['s_t']);
$ma=$so->user_timeline($r_dby['s_id'], 5);
if(!isset($ma['error_code']) && is_array($ma['statuses']) && count($ma['statuses'])>0){
foreach($ma['statuses'] as $v){
if(trim($v['text'])!='')echo '<div class="sync_list" style="background-image: url(images/i-sina.gif);">'.trim($v['text']).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 'tqq':
if($config['is_tqq']>0 && ($config['is_utqq']>0 || ($config['tqq_key']!='' && $config['tqq_se']!=''))){
$s_dby=sprintf('select s_id, s_t from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('tqq', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/tqq.php');
$o=new tqqPHP($config['tqq_key'], $config['tqq_se'], $r_dby['s_t'], $r_dby['s_id']);
$ma=$o->getMyTweet(5);
if(isset($ma['ret']) && $ma['ret']==0 && isset($ma['data']['info']) && is_array($ma['data']['info']) && count($ma['data']['info'])>0){
foreach($ma['data']['info'] as $v){
if(trim($v['text'])!='')echo '<div class="sync_list" style="background-image: url(images/i-tqq.gif);">'.trim($v['text']).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 'tsohu':
if($config['is_tsohu']>0 && ($config['is_utsohu']>0 || ($config['tsohu_key']!='' && $config['tsohu_se']!=''))){
$s_dby=sprintf('select s_id, s_t, s_s from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('tsohu', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/SohuOAuth.php');
$oauth=new SohuOAuth($config['tsohu_key'], $config['tsohu_se'], $r_dby['s_t'], $r_dby['s_s']);
$url='http://api.t.sohu.com/statuses/user_timeline/'.$r_dby['s_id'].'.json';
$ma=$oauth->get($url, array('count'=>5));
if(is_array($ma) && count($ma)>0){
foreach($ma as $v){
if(trim($v['text'])!='')echo '<div class="sync_list" style="background-image: url(images/i-tsohu.gif);">'.trim($v['text']).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 't163':
if($config['is_t163']>0 && $config['t163_key']!='' && $config['t163_se']!=''){
$s_dby=sprintf('select s_id, s_t from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('t163', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/t163.php');
$tblog=new t163PHP($config['t163_key'], $config['t163_se'], $r_dby['s_t']);
$ms=$tblog->user_timeline($r_dby['s_id'], 5);
if(is_array($ms) && count($ms)>0){
foreach($ms as $v){
if(trim($v['text'])!='')echo '<div class="sync_list" style="background-image: url(images/i-t163.gif);">'.trim($v['text']).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 'babab':
if($config['is_babab']>0 && ($config['is_ubabab']>0 || $config['babab_key']!='')){
$s_dby=sprintf('select s_t, is_show from %s where aid=%s and name=%s limit 1', $dbprefix.'m_sync', $id, SQLString('babab', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
$page=(isset($_GET['page']) && intval($_GET['page'])>0)?intval($_GET['page']):'1';
$isp=((isset($_GET['m']) && $_GET['m']=='1') || $id!=$_SESSION[$config['u_hash']])?1:0;
$p_page='5';
if($isp>0)$page='1';
if($r_dby['is_show']==0 || $isp==0){
require_once('lib/IXR.php');
$IXR_c=new IXR_Client('http://www.bababian.com/xmlrpc');
$IXR_c->query('bababian.photo.getPhotoList', $config['babab_key'], $r_dby['s_t'], $page, $p_page, '75');
$IXR_r=$IXR_c->getResponse();
if(is_array($IXR_r) && !isset($IXR_r['faultCode']) && count($IXR_r)>0 && isset($IXR_r[0]['photo_total']) && $IXR_r[0]['photo_total']>0){
if($isp>0){
echo '<div class="sync_list" style="background-image: url(images/i-babab.gif);"><div class="extr">最新巴巴变照片</div>';
}elseif($page==1){
echo '<span class="plist_babab" id="plist_babab_1"><input type="hidden" id="babab_isload" value="1"/>';
}
$babab_info=$IXR_r[0];
unset($IXR_r[0]);
foreach($IXR_r as $v){
if($isp==0){
$bimg=$v['src'];
$IXR_c->query('bababian.photo.getPhotoInfo', $config['babab_key'], $v['did'], '1', '1');
$bimg_a=$IXR_c->getResponse();
if(isset($bimg_a[0]['src']) && $bimg_a[0]['src']!='')$bimg=$bimg_a[0]['src'];
}
echo '<div class="al_list">'.($isp>0?'<a href="http://www.bababian.com/phoinfo/'.$v['did'].'" target="_blank">':'').'<img src="'.$v['src'].'" width="70" height="70" class="al_t'.($isp>0?'':' f_link" onclick="$(\'#formurl0\').val(\''.$bimg.'\');$(\'#formtitle1\').val($(this).attr(\'src\'));$(\'#formtitle0\').val($(this).attr(\'title\'));').'" alt="" title="'.$v['title'].'"/>'.($isp>0?'</a>':'').'</div>';
}
echo '<div class="extr"></div>';
if($isp>0){
echo '</div>';
}else{
$tp=$babab_info['page_total'];
if($tp>1){
for($i=1;$i<=$tp;$i++){
if($i==$page){
echo '['.$i.']';
}else{
echo '<span href="#" onclick="ld(\'babab\', '.$i.', \'j_sync.php?t=babab&page='.$i.'\');" class="mlink f_link">'.$i.'</span>';
}
echo ' ';
}
echo '| ';
}
if($page==1)echo '</span><span onclick="$(\'#album_sync_div\').slideUp(500);" class="mlink f_link">隐藏</span><input type="hidden" id="is_ax" value="babab"/><span id="p_babab" style="display: none;"> <img src="images/v.gif" alt="" title="载入中……" class="loading_va"/></span>';
}
}
}
}
mysql_free_result($q_dby);
}
break;
case 'twitter':
if($config['is_tw']>0 && $config['tw_key']!='' && $config['tw_se']!=''){
$s_dby=sprintf('select s_id, s_t, s_s from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('twitter', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/twitterOAuth.php');
$to=new TwitterOAuth($config['tw_key'], $config['tw_se'], $r_dby['s_t'], $r_dby['s_s']);
$ma=$to->OAuthRequest('https://twitter.com/statuses/user_timeline.json', array('count'=>5, 'user_id'=>$r_dby['s_id']), 'GET');
if(is_array($ma) && count($ma)>0){
foreach($ma as $v){
if(trim($v['text'])!='')echo '<div class="sync_list" style="background-image: url(images/i-twitter.gif);">'.trim($v['text']).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 'facebook':
if($config['is_fb']>0 && $config['fb_se']!='' && $config['fb_app_id']!=''){
$s_dby=sprintf('select s_t from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('sina', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/facebook.php');
$fb=new facebookPHP($config['fb_app_id'], $config['fb_se'], $r_dby['s_t']);
$sa=$fb->my_feed(5);
if(isset($sa['data']) && is_array($sa['data']) && count($sa['data'])>0){
foreach($sa['data'] as $v){
switch($v['type']){
case 'status':
echo '<div class="sync_list" style="background-image: url(images/i-facebook.gif);">'.$v['message'].'</div>';
break;
case 'link':
echo '<div class="sync_list" style="background-image: url(images/i-facebook.gif);"><a href="'.$v['link'].'" target="_blank">'.($v['name']!=''?$v['name']:$v['message']).'</a> '.$v['description'].'</div>';
break;
}
}
}
}
mysql_free_result($q_dby);
}
break;
case 'kx001':
if($config['is_kx001']>0 && $config['kx001_key']!='' && $config['kx001_se']!=''){
$s_dby=sprintf('select s_t from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('kx001', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/kaixin.php');
$kx_co=new kaixinPHP($config['kx001_key'], $config['kx001_se'], $r_dby['s_t']);
$kx_re=$kx_co->records_me(5);
if(isset($kx_re['data']) && count($kx_re['data'])>0){
foreach($kx_re['data'] as $v){
if(trim($v['main']['content'])!='')echo '<div class="sync_list" style="background-image: url(images/i-kx001.gif);">'.trim($v['main']['content']).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 'renren':
if($config['is_renren']>0 && $config['renren_key']!='' && $config['renren_se']!=''){
$s_dby=sprintf('select s_id, s_t from %s where aid=%s and name=%s and is_show=0 limit 1', $dbprefix.'m_sync', $id, SQLString('renren', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
require_once('lib/renren.php');
$rr_c=new renrenPHP($config['renren_key'], $config['renren_se'], $r_dby['s_t']);
$st=$rr_c->getStatus($r_dby['s_id'], 5);
if(is_array($st) && count($st)>0){
foreach($st as $v){
if(htmlspecialchars(trim($v['message']),ENT_QUOTES)!='')echo '<div class="sync_list" style="background-image: url(images/i-renren.gif);">'.htmlspecialchars(trim($v['message']),ENT_QUOTES).'</div>';
}
}
}
mysql_free_result($q_dby);
}
break;
case 'instagram':
if($config['is_instagram']>0 && $config['instagram_key']!='' && $config['instagram_se']!=''){
$s_dby=sprintf('select s_id, s_t, is_show from %s where aid=%s and name=%s limit 1', $dbprefix.'m_sync', $id, SQLString('instagram', 'text'));
$q_dby=mysql_query($s_dby) or die('');
$r_dby=mysql_fetch_assoc($q_dby);
if(mysql_num_rows($q_dby)>0){
$max_id=(isset($_GET['max_id']) && trim($_GET['max_id'])!='')?trim($_GET['max_id']):'';
$page=(isset($_GET['page']) && intval($_GET['page'])>0)?intval($_GET['page']):1;
$isp=((isset($_GET['m']) && $_GET['m']=='1') || $id!=$_SESSION[$config['u_hash']])?1:0;
$p_page=$isp>0?'5':'10';
if($isp>0){
$max_id='';
$page=1;
}
if($r_dby['is_show']==0 || $isp==0){
require_once('lib/instagram.php');
$io=new instagramPHP($config['instagram_key'], $config['instagram_se'], $r_dby['s_t']);
$ia=$io->user_media($r_dby['s_id'], $p_page, $max_id);
if(!isset($ia['meta']['error_type']) && isset($ia['data']) && is_array($ia['data']) && count($ia['data'])>0){
if($isp>0){
echo '<div class="sync_list" style="background-image: url(images/i-instagram.gif);"><div class="extr">最新Instagram照片</div>';
}elseif($page==1){
echo '<span class="plist_instagram" id="plist_instagram_1"><input type="hidden" id="instagram_isload" value="1"/>';
}
foreach($ia['data'] as $v){
if($v['type']=='image')echo '<div class="al_list">'.($isp>0?'<a href="'.$v['link'].'" target="_blank">':'').'<img src="'.$v['images']['thumbnail']['url'].'" width="70" height="70" class="al_t'.($isp>0?'':' f_link" onclick="$(\'#formurl0\').val(\''.$v['images']['standard_resolution']['url'].'\');$(\'#formtitle1\').val($(this).attr(\'src\'));$(\'#formtitle0\').val($(this).attr(\'title\'));').'" alt="" title="'.$v['caption']['text'].'"/>'.($isp>0?'</a>':'').'</div>';
}
echo '<div class="extr"></div>';
if($isp>0){
echo '</div>';
}else{
if($page>1)$pa[]='<span href="#" onclick="ld(\'instagram\', '.($page-1).', \'j_sync.php?t=instagram&page='.($page-1).'\');" class="mlink f_link">前页</span>';
if(isset($ia['pagination']['next_max_id']) && trim($ia['pagination']['next_max_id'])!='')$pa[]='<span href="#" onclick="ld(\'instagram\', '.($page+1).', \'j_sync.php?t=instagram&max_id='.$ia['pagination']['next_max_id'].'&page='.($page+1).'\');" class="mlink f_link">后页</span>';
if(isset($pa))echo join(' ', $pa).' | ';
if($page==1)echo '</span><span onclick="$(\'#album_sync_div\').slideUp(500);" class="mlink f_link">隐藏</span><input type="hidden" id="is_ax" value="instagram"/><span id="p_instagram" style="display: none;"> <img src="images/v.gif" alt="" title="载入中……" class="loading_va"/></span>';
}
}
}
}
mysql_free_result($q_dby);
}
break;
}
}
|
binsd/mini_class
|
j_sync.php
|
PHP
|
gpl-2.0
| 13,620
|
;throttle_momentum_lowpass.asm
.NOLIST
; ***************************************************************************************
; * PWM MODEL RAILROAD THROTTLE *
; * *
; * WRITTEN BY: PHILIP DEVRIES *
; * *
; * Copyright (C) 2003 Philip DeVries *
; * *
; * 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 *
; * *
; ***************************************************************************************
.LIST
.ifdef MOMENTUM_LOWPASS_ENABLED
;*****************************************************************
;* A transversal low pass filter *
;* *
;* This is copied from throttle_backemf.asm. *
;* See the documentation there. *
;*****************************************************************
HILOCAL1 _momentum_lo ; assign local variables
HILOCAL2 _momentum_hi
mov _momentum_lo,momentum_set
clr _momentum_hi
;****
;* 1. Add in cumulative previous throttle
;****
add _momentum_lo,momentum_lo_prev ; Add in scaled previous samples
adc _momentum_hi,momentum_hi_prev ;
;****
;* 2.
;****
mov momentum_lo_prev,_momentum_lo ; Store new value
mov momentum_hi_prev,_momentum_hi ; Store new value
;****
;* 3.
;****
B_TEMPLOCAL _lowpass_lo_byte
ldi _lowpass_lo_byte, momentum_lowpass_gain
rcall DIVIDE_16_SIMPLE
;****
;* 4.
;****
sub momentum_lo_prev,_momentum_lo
sbc momentum_hi_prev,_momentum_hi
mov momentum_set,_momentum_lo
.endif ;MOMENTUM_LOWPASS_ENABLED
|
pearsonalan/avra
|
examples/throttle_momentum_lowpass.asm
|
Assembly
|
gpl-2.0
| 3,339
|
/*
queryj
Copyright (C) 2002-today Jose San Leandro Armendariz
chous@acm-sl.org
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public
License as published by the Free Software Foundation; either
version 2 of the License, or 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
General Public License for more details.
You should have received a copy of the GNU General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Thanks to ACM S.L. for distributing this library under the GPL license.
Contact info: jose.sanleandro@acm-sl.com
******************************************************************************
*
* Filename: TemplateDefOutputVisitor.java
*
* Author: Jose San Leandro Armendariz
*
* Description: ANTLR4 visitor to retrieve the output definition.
*
* Date: 2013/08/13
* Time: 17:33
*
*/
package org.acmsl.queryj.templates.packaging.antlr;
/*
* Importing ANTLR-generated classes.
*/
import org.acmsl.queryj.templates.packaging.antlr.TemplateDefParser.OutputRuleContext;
/*
* Importing JetBrains annotations.
*/
import org.jetbrains.annotations.NotNull;
/*
* Importing checkthread.org annotations.
*/
import org.checkthread.annotations.NotThreadSafe;
/**
* ANTLR4 visitor to retrieve the output definition.
* @author <a href="mailto:queryj@acm-sl.org">Jose San Leandro</a>
* @since 3.0
* Created: 2013/08/13 17:33
*/
@NotThreadSafe
public class TemplateDefOutputVisitor
extends TemplateDefBaseVisitor<String>
{
/**
* The output value.
*/
private String m__strOutput;
/**
* Specifies the output.
* @param output the output value.
*/
protected final void immutableSetOutput(@NotNull final String output)
{
this.m__strOutput = output;
}
/**
* Specifies the output.
* @param output the output value.
*/
protected void setOutput(@NotNull final String output)
{
immutableSetOutput(output);
}
/**
* Retrieves the output.
* @return such information.
*/
@NotNull
public String getOutput()
{
return this.m__strOutput;
}
/**
* {@inheritDoc}
* The default implementation returns the result of calling
* {@link #visitChildren} on {@code ctx}.
*/
@Override
public String visitOutputRule(@NotNull final OutputRuleContext ctx)
{
setOutput(ctx.getChild(2).getText());
return super.visitOutputRule(ctx);
}
/**
* {@inheritDoc}
*/
@NotNull
@Override
public String toString()
{
return "{ 'class': 'TemplateDefOutputVisitor', " +
" 'output': '" + m__strOutput + "' }";
}
}
|
rydnr/queryj-rt
|
queryj-template-packaging/src/main/java/org/acmsl/queryj/templates/packaging/antlr/TemplateDefOutputVisitor.java
|
Java
|
gpl-2.0
| 3,088
|
{% if forumrow.S_THANKS_FORUM_REPUT_VIEW and forumrow.FORUM_REPUT and not S_IS_BOT %}
<div style="display: block; margin-left: 45px; padding-bottom: 5px;">
{% if forumrow.S_THANKS_REPUT_GRAPHIC %}
<span style="display: block; float: left; width: {{ forumrow.THANKS_REPUT_GRAPHIC_WIDTH }}px; height: {{ forumrow.THANKS_REPUT_HEIGHT }}px; background: url({{ forumrow.THANKS_REPUT_IMAGE_BACK }}); background-repeat: repeat-x;"><span style="display: block; height: {{ forumrow.THANKS_REPUT_HEIGHT }}px; width: {{ forumrow.FORUM_REPUT }}; background: url({{ forumrow.THANKS_REPUT_IMAGE }}); background-repeat: repeat-x;"></span></span>
{% endif %}
{{ lang('REPUT') }}{{ lang('COLON') }} {{ forumrow.FORUM_REPUT }}
</div>
{% endif %}
|
rxu/thanks_for_posts
|
styles/prosilver/template/event/forumlist_body_forum_row_append.html
|
HTML
|
gpl-2.0
| 744
|
#
# Makefile for the drm device driver. This driver provides support for the
# Direct Rendering Infrastructure (DRI) in XFree86 4.1.0 and higher.
ccflags-y := -Iinclude/drm -Idrivers/gpu/drm/exynos
exynosdrm-y := exynos_drm_drv.o exynos_drm_encoder.o exynos_drm_connector.o \
exynos_drm_crtc.o exynos_drm_fbdev.o exynos_drm_fb.o \
exynos_drm_buf.o exynos_drm_gem.o exynos_drm_core.o \
exynos_drm_plane.o exynos_trace_points.o
exynosdrm-$(CONFIG_DRM_EXYNOS_DMABUF) += exynos_drm_dmabuf.o
exynosdrm-$(CONFIG_DRM_EXYNOS_FIMD) += exynos_drm_fimd.o
exynosdrm-$(CONFIG_DRM_EXYNOS_HDMI) += exynos_hdmi.o exynos_mixer.o
exynosdrm-$(CONFIG_DRM_EXYNOS_DP) += exynos_dp_core.o exynos_dp_reg.o
exynosdrm-$(CONFIG_DRM_EXYNOS_VIDI) += exynos_drm_vidi.o
exynosdrm-$(CONFIG_DRM_EXYNOS_DEBUG) += exynos_drm_debugfs.o
obj-$(CONFIG_DRM_EXYNOS) += exynosdrm.o
CFLAGS_exynos_trace_points.o := -I$(src)
|
ArthySundaram/chromeos-kvm
|
drivers/gpu/drm/exynos/Makefile
|
Makefile
|
gpl-2.0
| 893
|
#include "swl/Config.h"
#include "swl/glutil/GLCamera.h"
#include "swl/math/MathConstant.h"
#include <GL/glut.h>
#include <cmath>
#include <cstring>
#if defined(_DEBUG) && defined(__SWL_CONFIG__USE_DEBUG_NEW)
#include "swl/ResourceLeakageCheck.h"
#define new DEBUG_NEW
#endif
namespace swl {
//--------------------------------------------------------------------------
// class GLCamera
GLCamera::GLCamera()
: base_type()
{}
GLCamera::GLCamera(const GLCamera &rhs)
: base_type(rhs)
{}
GLCamera::~GLCamera() {}
GLCamera & GLCamera::operator=(const GLCamera &rhs)
{
if (this == &rhs) return *this;
static_cast<base_type&>(*this) = rhs;
return *this;
}
/*
void GLCamera::write(std::ostream &stream)
{
beginWrite(stream);
// write version
stream << ' ' << GLCamera::getVersion();
// write base class
GLCamera::base_type::write(stream);
// write self
endWriteEndl(stream);
}
void GLCamera::read(std::istream &stream)
{
beginAssert(stream);
// read version
unsigned int iVersion;
stream >> iVersion;
// read base class
GLCamera::base_type::read(stream);
// read self
unsigned int iOldVersion = setReadVersion(iVersion);
switch (iVersion)
{
case 20021008:
read20021008(stream);
break;
default:
UtBsErrorHandler::throwFileReadError(ClassName(), iVersion);
}
setReadVersion(iOldVersion);
endAssert(stream);
}
void GLCamera::read20021008(std::istream& stream)
{
}
*/
bool GLCamera::doUpdateFrustum()
{
GLint oldMatrixMode;
glGetIntegerv(GL_MATRIX_MODE, &oldMatrixMode);
if (oldMatrixMode != GL_PROJECTION) glMatrixMode(GL_PROJECTION);
glLoadIdentity();
const Region2<double> &rctViewRegion = getCurrentViewRegion();
if (isPerspective_)
{
// object: ¼³Á¤µÈ view regionÀÌ near clipping plane»óÀÇ ¿µ¿ªÀÌ ¾Æ´Ñ
// reference object positionÀ» Áö³ª´Â Æò¸é»óÀÇ ¿µ¿ªÀ» ÀǹÌÇϵµ·Ï Çϱâ À§ÇØ
// merit: perspective & orthographic projectionÀÇ Àüȯ½Ã ȸ鿡 ±×·ÁÁö´Â imageÀÇ size º¯È°¡ Àû´Ù
// view boundÀÇ ¼³Á¤ÀÌ ½±´Ù
// demerit: eyeDistance_¿¡ ÀÇÇØ near clipping planeÀÇ size°¡ º¯°æµÇ¹Ç·Î
// object coordinates <==> window coordinates À¸·ÎÀÇ ÁÂÇ¥º¯°æ½Ã À̵éÀÇ ¿µÇâÀ» °í·ÁÇÏ¿©¾ß ÇÑ´Ù
if (nearPlane_ > 0.0 && farPlane_ > 0.0 && nearPlane_ < farPlane_)
{
const double dRatio = calcResizingRatio();
glFrustum(
rctViewRegion.left * dRatio, rctViewRegion.right * dRatio,
rctViewRegion.bottom * dRatio, rctViewRegion.top * dRatio,
nearPlane_, farPlane_
);
}
else isValid_ = false;
}
else
{
if (nearPlane_ < farPlane_)
glOrtho(
rctViewRegion.left, rctViewRegion.right,
rctViewRegion.bottom, rctViewRegion.top,
nearPlane_, farPlane_
);
else isValid_ = false;
}
//lookAt();
if (oldMatrixMode != GL_PROJECTION) glMatrixMode(oldMatrixMode);
return true;
}
inline bool GLCamera::doUpdateViewport()
{
glViewport(viewport_.left, viewport_.bottom, viewport_.getWidth(), viewport_.getHeight());
return doUpdateFrustum();
}
bool GLCamera::rotateViewAboutAxis(const EAxis eAxis, const int iX1, const int iY1, const int iX2, const int iY2)
{
#if 1
const double dDeltaX = double(iX2 - iX1) / zoomFactor_;
const double dDeltaY = double(iY1 - iY2) / zoomFactor_; // upward y-axis
//const double dDeltaY = double(iY2 - iY1) / zoomFactor_; // downward y-axis
const bool isPositiveDir = std::fabs(dDeltaX) > std::fabs(dDeltaY) ? dDeltaX >= 0.0 : dDeltaY >= 0.0;
double rotAxis[3] = { 0.0, 0.0, 0.0 }; // rotational axis
switch (eAxis)
{
case XAXIS:
rotAxis[0] = isPositiveDir ? 1.0 : -1.0;
break;
case YAXIS:
rotAxis[1] = isPositiveDir ? 1.0 : -1.0;
break;
case ZAXIS:
rotAxis[2] = isPositiveDir ? 1.0 : -1.0;
break;
default:
return false;
}
const double rotAngle = -MathConstant::_2_PI * std::sqrt(dDeltaX*dDeltaX + dDeltaY*dDeltaY) / base_type::getViewRegion().getDiagonal();
double mRot[9] = { 0.0, };
if (!calcRotationMatrix(rotAngle, rotAxis, mRot)) return false;
// the direction from the reference point to the eye point
double vV[3] = { 0.0, };
memcpy(vV, eyeDir_, 3 * sizeof(double));
productMatrixAndVector(mRot, vV, eyeDir_);
eyePosX_ = refObjX_ - eyeDistance_ * eyeDirX_; eyePosY_ = refObjY_ - eyeDistance_ * eyeDirY_; eyePosZ_ = refObjZ_ - eyeDistance_ * eyeDirZ_;
memcpy(vV, upDir_, 3 * sizeof(double));
productMatrixAndVector(mRot, vV, upDir_);
return true;
#else
const double eps = 1.0e-20;
GLint oldMatrixMode = 0;
glGetIntegerv(GL_MATRIX_MODE, &oldMatrixMode);
if (oldMatrixMode != GL_MODELVIEW) glMatrixMode(GL_MODELVIEW);
glPushMatrix();
glLoadIdentity();
// 1. need to load current modelview matrix
// e.g.) glLoadMatrixd(modelviewMatrix);
// 2. need to be thought of viewing transformation
// e.g.) camera->lookAt();
lookAt();
double modelview[16] = { 0.0, }, projection[16] = { 0.0, };
int viewport[4] = { 0, };
double depthRange[2] = { 0.0, 1.0 };
glGetDoublev(GL_MODELVIEW_MATRIX, modelview);
glGetDoublev(GL_PROJECTION_MATRIX, projection);
glGetIntegerv(GL_VIEWPORT, viewport);
glGetDoublev(GL_DEPTH_RANGE, depthRange);
double pt1[3] = { 0.0, }, pt2[3] = { 0.0, };
const bool ret = gluUnProject(double(iX1), double(viewport[3] - iY1), depthRange[0], modelview, projection, viewport, &pt1[0], &pt1[1], &pt1[2]) == GL_TRUE &&
gluUnProject(double(iX2), double(viewport[3] - iY2), depthRange[0], modelview, projection, viewport, &pt2[0], &pt2[1], &pt2[2]) == GL_TRUE;
glPopMatrix();
if (oldMatrixMode != GL_MODELVIEW) glMatrixMode(oldMatrixMode);
if (!ret) return false;
double vec1[3] = { pt1[0] - refObj_[0], pt1[1] - refObj_[1], pt1[2] - refObj_[2] };
double vec2[3] = { pt2[0] - refObj_[0], pt2[1] - refObj_[1], pt2[2] - refObj_[2] };
normalizeVector(vec1);
normalizeVector(vec2);
double rotAxis[3] = { 0.0, 0.0, 0.0 }; // rotational axis
double rotAngle = 0.0;
switch (eAxis)
{
case XAXIS:
{
rotAxis[0] = 1.0;
const double norm1 = std::sqrt(vec1[1]*vec1[1] + vec1[2]*vec1[2]);
const double norm2 = std::sqrt(vec2[1]*vec2[1] + vec2[2]*vec2[2]);
if (norm1 <= eps || norm2 <= eps) return false;
rotAngle = std::acos((vec1[1] * vec2[1] + vec1[2] * vec2[2]) / (norm1 * norm2));
}
break;
case YAXIS:
{
rotAxis[1] = 1.0;
const double norm1 = std::sqrt(vec1[0]*vec1[0] + vec1[2]*vec1[2]);
const double norm2 = std::sqrt(vec2[0]*vec2[0] + vec2[2]*vec2[2]);
if (norm1 <= eps || norm2 <= eps) return false;
rotAngle = std::acos((vec1[0] * vec2[0] + vec1[2] * vec2[2]) / (norm1 * norm2));
}
break;
case ZAXIS:
{
rotAxis[2] = 1.0;
const double norm1 = std::sqrt(vec1[0]*vec1[0] + vec1[1]*vec1[1]);
const double norm2 = std::sqrt(vec2[0]*vec2[0] + vec2[1]*vec2[1]);
if (norm1 <= eps || norm2 <= eps) return false;
rotAngle = std::acos((vec1[0] * vec2[0] + vec1[1] * vec2[1]) / (norm1 * norm2));
}
break;
default:
return false;
}
double vec3[3] = { 0.0, };
crossVector(vec1, vec2, vec3);
if (!normalizeVector(vec3)) return false;
const double betweenAngle = std::acos(vec3[0] * rotAxis[0] + vec3[1] * rotAxis[1] + vec3[2] * rotAxis[2]);
const bool isPositiveDir = betweenAngle < PI * 0.5;
double mRot[9] = { 0.0, };
if (!calcRotationMatrix(isPositiveDir ? -rotAngle : rotAngle, rotAxis, mRot)) return false;
// the direction from the reference point to the eye point
double vV[3] = { 0.0, };
memcpy(vV, eyeDir_, 3 * sizeof(double));
productMatrixAndVector(mRot, vV, eyeDir_);
eyePosX_ = refObjX_ - eyeDistance_ * eyeDirX_; eyePosY_ = refObjY_ - eyeDistance_ * eyeDirY_; eyePosZ_ = refObjZ_ - eyeDistance_ * eyeDirZ_;
memcpy(vV, upDir_, 3 * sizeof(double));
productMatrixAndVector(mRot, vV, upDir_);
return true;
#endif
}
inline void GLCamera::lookAt()
{
//doUpdateFrustum();
gluLookAt(eyePosX_, eyePosY_, eyePosZ_, eyePosX_+eyeDirX_, eyePosY_+eyeDirY_, eyePosZ_+eyeDirZ_, upDirX_, upDirY_, upDirZ_);
}
// projection transformation: an eye coordinates(before projection) ==> a clip coordinates(after projection)
// ==> OpenGL Red Book p. 96
bool GLCamera::doMapEyeToClip(const double ptEye[3], double ptClip[3]) const
{
// rojection transformation: an eye coordinates ==> a clip coordinates
Region2<double> rctViewRegion = getCurrentViewRegion();
//--S [] 2001/08/08: Sang-Wook Lee
// doUpdateFrustum()¿¡¼ glFrustum()À» È£ÃâÇϱâ À§ÇØ clipping regionÀ» ¼öÁ¤Çϰí Àֱ⠶§¹®¿¡
if (isPerspective())
rctViewRegion *= calcResizingRatio();
//--E [] 2001/08/08
if (!rctViewRegion.isValid() || nearPlane_ >= farPlane_)
return false;
// from OpenGL Red Book
if (isPerspective_)
{
const double dW = -ptEye[2];
if (dW <= 0.0 || nearPlane_ <= 0.0) return false;
ptClip[0] = (2.0*nearPlane_*ptEye[0] + (rctViewRegion.right+rctViewRegion.left)*ptEye[2]) / (rctViewRegion.right - rctViewRegion.left);
ptClip[1] = (2.0*nearPlane_*ptEye[1] + (rctViewRegion.top+rctViewRegion.bottom)*ptEye[2]) / (rctViewRegion.top - rctViewRegion.bottom);
ptClip[2] = (-2.0*farPlane_*nearPlane_ - (farPlane_+nearPlane_)*ptEye[2]) / (farPlane_ - nearPlane_);
// clip coordinates
// because of perspective, -1.0 <= x, y <= 1.0 at near plane
ptClip[0] /= dW;
ptClip[1] /= dW;
// -1.0 <= z <= 1.0
ptClip[2] /= dW;
}
else
{
// clip coordinates
// because of orthographic, -1.0 <= x, y & z <= 1.0
ptClip[0] = (2.0*ptEye[0] - (rctViewRegion.right+rctViewRegion.left)) / (rctViewRegion.right - rctViewRegion.left);
ptClip[1] = (2.0*ptEye[1] - (rctViewRegion.top+rctViewRegion.bottom)) / (rctViewRegion.top - rctViewRegion.bottom);
ptClip[2] = (-2.0*ptEye[2] - (farPlane_+nearPlane_)) / (farPlane_ - nearPlane_);
}
return true;
}
// viewport transformation: a clip coordinates ==> a window coordinates
bool GLCamera::doMapClipToWindow(const double ptClip[3], double ptWin[3]) const
{
// viewport transformation: a clip coordinates ==> a window coordinates
const Region2<double> rctViewRegion = getCurrentViewRegion();
/*
//--S [] 2001/08/08: Sang-Wook Lee
// doUpdateFrustum()¿¡¼ ::glFrustum()À» È£ÃâÇϱâ À§ÇØ clipping regionÀ» ¼öÁ¤Çϰí Àֱ⠶§¹®¿¡
if (isPerspective())
rctViewRegion *= calcResizingRatio();
//--E [] 2001/08/08
*/
const double dNCx = ptClip[0] * rctViewRegion.getWidth() * 0.5 + rctViewRegion.getCenterX();
const double dNCy = ptClip[1] * rctViewRegion.getHeight() * 0.5 + rctViewRegion.getCenterY();
int iX, iY;
if (base_type::mapCanvasToWindow(dNCx, dNCy, iX, iY))
{
ptWin[0] = double(iX);
ptWin[1] = double(iY);
ptWin[2] = ptClip[2]; // -1.0 <= z <= 1.0
return true;
}
else return false;
}
// inverse viewport transformation: a window coordinates ==> a clip coordinates
bool GLCamera::doMapWindowToClip(const double ptWin[3], double ptClip[3]) const
{
// inverse viewport transformation: a window coordinates ==> a clip coordinates
const Region2<double> rctViewRegion = getCurrentViewRegion();
/*
//--S [] 2001/08/08: Sang-Wook Lee
// doUpdateFrustum()¿¡¼ glFrustum()À» È£ÃâÇϱâ À§ÇØ clipping regionÀ» ¼öÁ¤Çϰí Àֱ⠶§¹®¿¡
if (isPerspective())
rctViewRegion *= calcResizingRatio();
//--E [] 2001/08/08
*/
double dNCx, dNCy;
if (rctViewRegion.isValid() && base_type::mapWindowToCanvas(int(ptWin[0]), int(ptWin[1]), dNCx, dNCy))
{
// if perspective, -1.0 <= x, y <= 1.0 at near plane
// if orthographic, -1.0 <= x, y <= 1.0
ptClip[0] = (dNCx - rctViewRegion.getCenterX()) / (rctViewRegion.getWidth() * 0.5);
ptClip[1] = (dNCy - rctViewRegion.getCenterY()) / (rctViewRegion.getHeight() * 0.5);
// -1.0 <= z <= 1.0
ptClip[2] = ptWin[2];
return true;
}
else return false;
}
// inverse projection transformation: a clip coordinates(after projection) ==> an eye coordinates(before projection)
// ==> OpenGL Red Book p. 96
bool GLCamera::doMapClipToEye(const double ptClip[3], double ptEye[3]) const
{
// inverse projection transformation: a clip coordinates ==> an eye coordinates
Region2<double> rctViewRegion = getCurrentViewRegion();
//--S [] 2001/08/08: Sang-Wook Lee
// doUpdateFrustum()¿¡¼ glFrustum()À» È£ÃâÇϱâ À§ÇØ clipping regionÀ» ¼öÁ¤Çϰí Àֱ⠶§¹®¿¡
if (isPerspective())
rctViewRegion *= calcResizingRatio();
//--E [] 2001/08/08
if (!rctViewRegion.isValid() || nearPlane_ >= farPlane_)
return false;
// from OpenGL Red Book
if (isPerspective_)
{
if (nearPlane_ <= 0.0) return false;
ptEye[0] = ((rctViewRegion.right-rctViewRegion.left)*ptClip[0] + (rctViewRegion.right+rctViewRegion.left)) / (2.0 * nearPlane_);
ptEye[1] = ((rctViewRegion.top-rctViewRegion.bottom)*ptClip[1] + (rctViewRegion.top+rctViewRegion.bottom)) / (2.0 * nearPlane_);
ptEye[2] = -1.0;
const double dW = (-(farPlane_-nearPlane_)*ptClip[2] + (farPlane_+nearPlane_)) / (2.0 * farPlane_ * nearPlane_);
const double dEPS = 1.0e-10;
if (-dEPS <= dW && dW <= dEPS) return false;
ptEye[0] /= dW;
ptEye[1] /= dW;
ptEye[2] /= dW;
}
else
{
ptEye[0] = ((rctViewRegion.right-rctViewRegion.left)*ptClip[0] + (rctViewRegion.right+rctViewRegion.left)) * 0.5;
ptEye[1] = ((rctViewRegion.top-rctViewRegion.bottom)*ptClip[1] + (rctViewRegion.top+rctViewRegion.bottom)) * 0.5;
//ptEye[2] = (-(farPlane_-nearPlane_)*ptClip[2] + (farPlane_+nearPlane_)) * 0.5;
ptEye[2] = (-(farPlane_-nearPlane_)*ptClip[2] - (farPlane_+nearPlane_)) * 0.5;
}
return true;
}
double GLCamera::calcResizingRatio() const
{
const double dEPS = 1.0e-10;
double dRatio = (-dEPS <= eyeDistance_ && eyeDistance_ <= dEPS) ? nearPlane_ : nearPlane_ / eyeDistance_;
checkLimit(dRatio);
return dRatio;
}
} // namespace swl
|
sangwook236/sangwook-library
|
cpp/src/glutil/GLCamera.cpp
|
C++
|
gpl-2.0
| 13,884
|
/* -*- Mode: C; indent-tabs-mode: t; c-basic-offset: 8; tab-width: 8 -*- */
/* nemo-column-chooser.h - A column chooser widget
Copyright (C) 2004 Novell, Inc.
The Gnome 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.
The Gnome 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 the Gnome Library; see the column COPYING.LIB. If not,
write to the Free Software Foundation, Inc., 51 Franklin Street - Suite 500,
Boston, MA 02110-1335, USA.
Authors: Dave Camp <dave@ximian.com>
*/
#include <config.h>
#include "nemo-column-chooser.h"
#include <string.h>
#include <gtk/gtk.h>
#include <glib/gi18n.h>
#include "nemo-column-utilities.h"
struct _NemoColumnChooserDetails
{
GtkTreeView *view;
GtkListStore *store;
GtkWidget *move_up_button;
GtkWidget *move_down_button;
GtkWidget *use_default_button;
NemoFile *file;
};
enum {
COLUMN_VISIBLE,
COLUMN_LABEL,
COLUMN_NAME,
NUM_COLUMNS
};
enum {
PROP_FILE = 1,
NUM_PROPERTIES
};
enum {
CHANGED,
USE_DEFAULT,
LAST_SIGNAL
};
static guint signals[LAST_SIGNAL];
G_DEFINE_TYPE(NemoColumnChooser, nemo_column_chooser, GTK_TYPE_BOX);
static void nemo_column_chooser_constructed (GObject *object);
static void
nemo_column_chooser_set_property (GObject *object,
guint param_id,
const GValue *value,
GParamSpec *pspec)
{
NemoColumnChooser *chooser;
chooser = NEMO_COLUMN_CHOOSER (object);
switch (param_id) {
case PROP_FILE:
chooser->details->file = g_value_get_object (value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID (object, param_id, pspec);
break;
}
}
static void
nemo_column_chooser_class_init (NemoColumnChooserClass *chooser_class)
{
GObjectClass *oclass;
oclass = G_OBJECT_CLASS (chooser_class);
oclass->set_property = nemo_column_chooser_set_property;
oclass->constructed = nemo_column_chooser_constructed;
signals[CHANGED] = g_signal_new
("changed",
G_TYPE_FROM_CLASS (chooser_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NemoColumnChooserClass,
changed),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
signals[USE_DEFAULT] = g_signal_new
("use_default",
G_TYPE_FROM_CLASS (chooser_class),
G_SIGNAL_RUN_LAST,
G_STRUCT_OFFSET (NemoColumnChooserClass,
use_default),
NULL, NULL,
g_cclosure_marshal_VOID__VOID,
G_TYPE_NONE, 0);
g_object_class_install_property (oclass,
PROP_FILE,
g_param_spec_object ("file",
"File",
"The file this column chooser is for",
NEMO_TYPE_FILE,
G_PARAM_CONSTRUCT_ONLY |
G_PARAM_WRITABLE));
g_type_class_add_private (chooser_class, sizeof (NemoColumnChooserDetails));
}
static void
update_buttons (NemoColumnChooser *chooser)
{
GtkTreeSelection *selection;
GtkTreeIter iter;
selection = gtk_tree_view_get_selection (chooser->details->view);
if (gtk_tree_selection_get_selected (selection, NULL, &iter)) {
gboolean visible;
gboolean top;
gboolean bottom;
GtkTreePath *first;
GtkTreePath *path;
gtk_tree_model_get (GTK_TREE_MODEL (chooser->details->store),
&iter,
COLUMN_VISIBLE, &visible,
-1);
path = gtk_tree_model_get_path (GTK_TREE_MODEL (chooser->details->store),
&iter);
first = gtk_tree_path_new_first ();
top = (gtk_tree_path_compare (path, first) == 0);
gtk_tree_path_free (path);
gtk_tree_path_free (first);
bottom = !gtk_tree_model_iter_next (GTK_TREE_MODEL (chooser->details->store),
&iter);
gtk_widget_set_sensitive (chooser->details->move_up_button,
!top);
gtk_widget_set_sensitive (chooser->details->move_down_button,
!bottom);
} else {
gtk_widget_set_sensitive (chooser->details->move_up_button,
FALSE);
gtk_widget_set_sensitive (chooser->details->move_down_button,
FALSE);
}
}
static void
list_changed (NemoColumnChooser *chooser)
{
update_buttons (chooser);
g_signal_emit (chooser, signals[CHANGED], 0);
}
static void
visible_toggled_callback (GtkCellRendererToggle *cell,
char *path_string,
gpointer user_data)
{
NemoColumnChooser *chooser;
GtkTreePath *path;
GtkTreeIter iter;
gboolean visible;
chooser = NEMO_COLUMN_CHOOSER (user_data);
path = gtk_tree_path_new_from_string (path_string);
gtk_tree_model_get_iter (GTK_TREE_MODEL (chooser->details->store),
&iter, path);
gtk_tree_model_get (GTK_TREE_MODEL (chooser->details->store),
&iter, COLUMN_VISIBLE, &visible, -1);
gtk_list_store_set (chooser->details->store,
&iter, COLUMN_VISIBLE, !visible, -1);
gtk_tree_path_free (path);
list_changed (chooser);
}
static void
selection_changed_callback (GtkTreeSelection *selection, gpointer user_data)
{
update_buttons (NEMO_COLUMN_CHOOSER (user_data));
}
static void
row_deleted_callback (GtkTreeModel *model,
GtkTreePath *path,
gpointer user_data)
{
list_changed (NEMO_COLUMN_CHOOSER (user_data));
}
static void
add_tree_view (NemoColumnChooser *chooser)
{
GtkWidget *scrolled;
GtkWidget *view;
GtkListStore *store;
GtkCellRenderer *cell;
GtkTreeSelection *selection;
view = gtk_tree_view_new ();
gtk_tree_view_set_headers_visible (GTK_TREE_VIEW (view), FALSE);
store = gtk_list_store_new (NUM_COLUMNS,
G_TYPE_BOOLEAN,
G_TYPE_STRING,
G_TYPE_STRING);
gtk_tree_view_set_model (GTK_TREE_VIEW (view),
GTK_TREE_MODEL (store));
g_object_unref (store);
gtk_tree_view_set_reorderable (GTK_TREE_VIEW (view), TRUE);
selection = gtk_tree_view_get_selection (GTK_TREE_VIEW (view));
g_signal_connect (selection, "changed",
G_CALLBACK (selection_changed_callback), chooser);
cell = gtk_cell_renderer_toggle_new ();
g_signal_connect (G_OBJECT (cell), "toggled",
G_CALLBACK (visible_toggled_callback), chooser);
gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (view),
-1, NULL,
cell,
"active", COLUMN_VISIBLE,
NULL);
cell = gtk_cell_renderer_text_new ();
gtk_tree_view_insert_column_with_attributes (GTK_TREE_VIEW (view),
-1, NULL,
cell,
"text", COLUMN_LABEL,
NULL);
chooser->details->view = GTK_TREE_VIEW (view);
chooser->details->store = store;
gtk_widget_show (view);
scrolled = gtk_scrolled_window_new (NULL, NULL);
gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled),
GTK_SHADOW_IN);
gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled),
GTK_POLICY_AUTOMATIC,
GTK_POLICY_AUTOMATIC);
gtk_widget_show (GTK_WIDGET (scrolled));
gtk_container_add (GTK_CONTAINER (scrolled), view);
gtk_box_pack_start (GTK_BOX (chooser), scrolled, TRUE, TRUE, 0);
}
static void
move_up_clicked_callback (GtkWidget *button, gpointer user_data)
{
NemoColumnChooser *chooser;
GtkTreeIter iter;
GtkTreeSelection *selection;
chooser = NEMO_COLUMN_CHOOSER (user_data);
selection = gtk_tree_view_get_selection (chooser->details->view);
if (gtk_tree_selection_get_selected (selection, NULL, &iter)) {
GtkTreePath *path;
GtkTreeIter prev;
path = gtk_tree_model_get_path (GTK_TREE_MODEL (chooser->details->store), &iter);
gtk_tree_path_prev (path);
if (gtk_tree_model_get_iter (GTK_TREE_MODEL (chooser->details->store), &prev, path)) {
gtk_list_store_move_before (chooser->details->store,
&iter,
&prev);
}
gtk_tree_path_free (path);
}
list_changed (chooser);
}
static void
move_down_clicked_callback (GtkWidget *button, gpointer user_data)
{
NemoColumnChooser *chooser;
GtkTreeIter iter;
GtkTreeSelection *selection;
chooser = NEMO_COLUMN_CHOOSER (user_data);
selection = gtk_tree_view_get_selection (chooser->details->view);
if (gtk_tree_selection_get_selected (selection, NULL, &iter)) {
GtkTreeIter next;
next = iter;
if (gtk_tree_model_iter_next (GTK_TREE_MODEL (chooser->details->store), &next)) {
gtk_list_store_move_after (chooser->details->store,
&iter,
&next);
}
}
list_changed (chooser);
}
static void
use_default_clicked_callback (GtkWidget *button, gpointer user_data)
{
g_signal_emit (NEMO_COLUMN_CHOOSER (user_data),
signals[USE_DEFAULT], 0);
}
static GtkWidget *
button_new_with_mnemonic (const gchar *stockid, const gchar *str)
{
GtkWidget *image;
GtkWidget *button;
button = gtk_button_new_with_mnemonic (str);
image = gtk_image_new_from_stock (stockid, GTK_ICON_SIZE_BUTTON);
gtk_button_set_image (GTK_BUTTON (button), image);
return button;
}
static void
add_buttons (NemoColumnChooser *chooser)
{
GtkWidget *box;
GtkWidget *separator;
box = gtk_box_new (GTK_ORIENTATION_VERTICAL, 8);
gtk_widget_show (box);
chooser->details->move_up_button = button_new_with_mnemonic (GTK_STOCK_GO_UP,
_("Move _Up"));
g_signal_connect (chooser->details->move_up_button,
"clicked", G_CALLBACK (move_up_clicked_callback),
chooser);
gtk_widget_show_all (chooser->details->move_up_button);
gtk_widget_set_sensitive (chooser->details->move_up_button, FALSE);
gtk_box_pack_start (GTK_BOX (box), chooser->details->move_up_button,
FALSE, FALSE, 0);
chooser->details->move_down_button = button_new_with_mnemonic (GTK_STOCK_GO_DOWN,
_("Move Dow_n"));
g_signal_connect (chooser->details->move_down_button,
"clicked", G_CALLBACK (move_down_clicked_callback),
chooser);
gtk_widget_show_all (chooser->details->move_down_button);
gtk_widget_set_sensitive (chooser->details->move_down_button, FALSE);
gtk_box_pack_start (GTK_BOX (box), chooser->details->move_down_button,
FALSE, FALSE, 0);
separator = gtk_separator_new (GTK_ORIENTATION_HORIZONTAL);
gtk_widget_show (separator);
gtk_box_pack_start (GTK_BOX (box), separator, FALSE, FALSE, 0);
chooser->details->use_default_button = gtk_button_new_with_mnemonic (_("Use De_fault"));
g_signal_connect (chooser->details->use_default_button,
"clicked", G_CALLBACK (use_default_clicked_callback),
chooser);
gtk_widget_show (chooser->details->use_default_button);
gtk_box_pack_start (GTK_BOX (box), chooser->details->use_default_button,
FALSE, FALSE, 0);
gtk_box_pack_start (GTK_BOX (chooser), box,
FALSE, FALSE, 0);
}
static void
populate_tree (NemoColumnChooser *chooser)
{
GList *columns;
GList *l;
columns = nemo_get_columns_for_file (chooser->details->file);
for (l = columns; l != NULL; l = l->next) {
GtkTreeIter iter;
NemoColumn *column;
char *name;
char *label;
column = NEMO_COLUMN (l->data);
g_object_get (G_OBJECT (column),
"name", &name, "label", &label,
NULL);
gtk_list_store_append (chooser->details->store, &iter);
gtk_list_store_set (chooser->details->store, &iter,
COLUMN_VISIBLE, FALSE,
COLUMN_LABEL, label,
COLUMN_NAME, name,
-1);
g_free (name);
g_free (label);
}
nemo_column_list_free (columns);
}
static void
nemo_column_chooser_constructed (GObject *object)
{
NemoColumnChooser *chooser;
chooser = NEMO_COLUMN_CHOOSER (object);
populate_tree (chooser);
g_signal_connect (chooser->details->store, "row_deleted",
G_CALLBACK (row_deleted_callback), chooser);
}
static void
nemo_column_chooser_init (NemoColumnChooser *chooser)
{
chooser->details = G_TYPE_INSTANCE_GET_PRIVATE ((chooser), NEMO_TYPE_COLUMN_CHOOSER, NemoColumnChooserDetails);
g_object_set (G_OBJECT (chooser),
"homogeneous", FALSE,
"spacing", 8,
"orientation", GTK_ORIENTATION_HORIZONTAL,
NULL);
add_tree_view (chooser);
add_buttons (chooser);
}
static void
set_visible_columns (NemoColumnChooser *chooser,
char **visible_columns)
{
GHashTable *visible_columns_hash;
GtkTreeIter iter;
int i;
visible_columns_hash = g_hash_table_new (g_str_hash, g_str_equal);
for (i = 0; visible_columns[i] != NULL; ++i) {
g_hash_table_insert (visible_columns_hash,
visible_columns[i],
visible_columns[i]);
}
if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (chooser->details->store),
&iter)) {
do {
char *name;
gboolean visible;
gtk_tree_model_get (GTK_TREE_MODEL (chooser->details->store),
&iter,
COLUMN_NAME, &name,
-1);
visible = (g_hash_table_lookup (visible_columns_hash, name) != NULL);
gtk_list_store_set (chooser->details->store,
&iter,
COLUMN_VISIBLE, visible,
-1);
g_free (name);
} while (gtk_tree_model_iter_next (GTK_TREE_MODEL (chooser->details->store), &iter));
}
g_hash_table_destroy (visible_columns_hash);
}
static char **
get_column_names (NemoColumnChooser *chooser, gboolean only_visible)
{
GPtrArray *ret;
GtkTreeIter iter;
ret = g_ptr_array_new ();
if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (chooser->details->store),
&iter)) {
do {
char *name;
gboolean visible;
gtk_tree_model_get (GTK_TREE_MODEL (chooser->details->store),
&iter,
COLUMN_VISIBLE, &visible,
COLUMN_NAME, &name,
-1);
if (!only_visible || visible) {
/* give ownership to the array */
g_ptr_array_add (ret, name);
}
} while (gtk_tree_model_iter_next (GTK_TREE_MODEL (chooser->details->store), &iter));
}
g_ptr_array_add (ret, NULL);
return (char **) g_ptr_array_free (ret, FALSE);
}
static gboolean
get_column_iter (NemoColumnChooser *chooser,
NemoColumn *column,
GtkTreeIter *iter)
{
char *column_name;
g_object_get (NEMO_COLUMN (column), "name", &column_name, NULL);
if (gtk_tree_model_get_iter_first (GTK_TREE_MODEL (chooser->details->store),
iter)) {
do {
char *name;
gtk_tree_model_get (GTK_TREE_MODEL (chooser->details->store),
iter,
COLUMN_NAME, &name,
-1);
if (!strcmp (name, column_name)) {
g_free (column_name);
g_free (name);
return TRUE;
}
g_free (name);
} while (gtk_tree_model_iter_next (GTK_TREE_MODEL (chooser->details->store), iter));
}
g_free (column_name);
return FALSE;
}
static void
set_column_order (NemoColumnChooser *chooser,
char **column_order)
{
GList *columns;
GList *l;
GtkTreePath *path;
columns = nemo_get_columns_for_file (chooser->details->file);
columns = nemo_sort_columns (columns, column_order);
g_signal_handlers_block_by_func (chooser->details->store,
G_CALLBACK (row_deleted_callback),
chooser);
path = gtk_tree_path_new_first ();
for (l = columns; l != NULL; l = l->next) {
GtkTreeIter iter;
if (get_column_iter (chooser, NEMO_COLUMN (l->data), &iter)) {
GtkTreeIter before;
if (path) {
gtk_tree_model_get_iter (GTK_TREE_MODEL (chooser->details->store),
&before, path);
gtk_list_store_move_after (chooser->details->store,
&iter, &before);
gtk_tree_path_next (path);
} else {
gtk_list_store_move_after (chooser->details->store,
&iter, NULL);
}
}
}
gtk_tree_path_free (path);
g_signal_handlers_unblock_by_func (chooser->details->store,
G_CALLBACK (row_deleted_callback),
chooser);
nemo_column_list_free (columns);
}
void
nemo_column_chooser_set_settings (NemoColumnChooser *chooser,
char **visible_columns,
char **column_order)
{
g_return_if_fail (NEMO_IS_COLUMN_CHOOSER (chooser));
g_return_if_fail (visible_columns != NULL);
g_return_if_fail (column_order != NULL);
set_visible_columns (chooser, visible_columns);
set_column_order (chooser, column_order);
list_changed (chooser);
}
void
nemo_column_chooser_get_settings (NemoColumnChooser *chooser,
char ***visible_columns,
char ***column_order)
{
g_return_if_fail (NEMO_IS_COLUMN_CHOOSER (chooser));
g_return_if_fail (visible_columns != NULL);
g_return_if_fail (column_order != NULL);
*visible_columns = get_column_names (chooser, TRUE);
*column_order = get_column_names (chooser, FALSE);
}
GtkWidget *
nemo_column_chooser_new (NemoFile *file)
{
return g_object_new (NEMO_TYPE_COLUMN_CHOOSER, "file", file, NULL);
}
|
nbourdau/pkg-nemo
|
libnemo-private/nemo-column-chooser.c
|
C
|
gpl-2.0
| 16,781
|
/*---------------------------------------------------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration |
\\ / A nd | Copyright held by original author
\\/ M anipulation |
-------------------------------------------------------------------------------
License
This file is part of OpenFOAM.
OpenFOAM 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.
OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation,
Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
\*---------------------------------------------------------------------------*/
// * * * * * * * * * * * * * * * Member Functions * * * * * * * * * * * * * //
template<class Type>
void Foam::fvMatrix<Type>::setComponentReference
(
const label patchi,
const label facei,
const direction cmpt,
const scalar value
)
{
if (psi_.needReference())
{
if (Pstream::master())
{
internalCoeffs_[patchi][facei].component(cmpt) +=
diag()[psi_.mesh().boundary()[patchi].faceCells()[facei]];
boundaryCoeffs_[patchi][facei].component(cmpt) +=
diag()[psi_.mesh().boundary()[patchi].faceCells()[facei]]
*value;
}
}
}
template<class Type>
Foam::lduMatrix::solverPerformance Foam::fvMatrix<Type>::solve
(
const dictionary& solverControls
)
{
if (debug)
{
Info<< "fvMatrix<Type>::solve(const dictionary&) : "
"solving fvMatrix<Type>"
<< endl;
}
lduSolverPerformance solverPerfVec
(
"fvMatrix<Type>::solve",
psi_.name()
);
scalarField saveDiag = diag();
Field<Type> source = source_;
// At this point include the boundary source from the coupled boundaries.
// This is corrected for the implicit part by updateMatrixInterfaces within
// the component loop.
addBoundarySource(source);
typename Type::labelType validComponents
(
pow
(
psi_.mesh().solutionD(),
pTraits<typename powProduct<Vector<label>, Type::rank>::type>::zero
)
);
// Make a copy of interfaces: no longer a reference
// HJ, 20/Nov/2007
lduInterfaceFieldPtrsList interfaces = psi_.boundaryField().interfaces();
for (direction cmpt = 0; cmpt < Type::nComponents; cmpt++)
{
if (validComponents[cmpt] == -1) continue;
// Copy field and source
scalarField psiCmpt = psi_.internalField().component(cmpt);
addBoundaryDiag(diag(), cmpt);
scalarField sourceCmpt = source.component(cmpt);
FieldField<Field, scalar> bouCoeffsCmpt
(
boundaryCoeffs_.component(cmpt)
);
FieldField<Field, scalar> intCoeffsCmpt
(
internalCoeffs_.component(cmpt)
);
// Use the initMatrixInterfaces and updateMatrixInterfaces to correct
// bouCoeffsCmpt for the explicit part of the coupled boundary
// conditions
initMatrixInterfaces
(
bouCoeffsCmpt,
interfaces,
psiCmpt,
sourceCmpt,
cmpt
);
updateMatrixInterfaces
(
bouCoeffsCmpt,
interfaces,
psiCmpt,
sourceCmpt,
cmpt
);
lduMatrix::solverPerformance solverPerf;
// Solver call
solverPerf = lduMatrix::solver::New
(
psi_.name() + pTraits<Type>::componentNames[cmpt],
*this,
bouCoeffsCmpt,
intCoeffsCmpt,
interfaces,
solverControls
)->solve(psiCmpt, sourceCmpt, cmpt);
solverPerf.print();
if
(
solverPerf.initialResidual() > solverPerfVec.initialResidual()
&& !solverPerf.singular()
)
{
solverPerfVec = solverPerf;
}
psi_.internalField().replace(cmpt, psiCmpt);
diag() = saveDiag;
}
psi_.correctBoundaryConditions();
return solverPerfVec;
}
template<class Type>
Foam::autoPtr<typename Foam::fvMatrix<Type>::fvSolver>
Foam::fvMatrix<Type>::solver()
{
return solver(psi_.mesh().solverDict(psi_.name()));
}
template<class Type>
Foam::lduMatrix::solverPerformance Foam::fvMatrix<Type>::fvSolver::solve()
{
return solve(psi_.mesh().solverDict(psi_.name()));
}
template<class Type>
Foam::lduMatrix::solverPerformance Foam::fvMatrix<Type>::solve()
{
return solve(psi_.mesh().solverDict(psi_.name()));
}
template<class Type>
Foam::tmp<Foam::Field<Type> > Foam::fvMatrix<Type>::residual() const
{
// Bug fix: Creating a tmp out of a const reference will change the field
// HJ, 15/Apr/2011
tmp<Field<Type> > tres(new Field<Type>(source_));
Field<Type>& res = tres();
addBoundarySource(res);
// Make a copy of interfaces: no longer a reference
// HJ, 20/Nov/2007
lduInterfaceFieldPtrsList interfaces = psi_.boundaryField().interfaces();
// Loop over field components
for (direction cmpt = 0; cmpt < Type::nComponents; cmpt++)
{
scalarField psiCmpt = psi_.internalField().component(cmpt);
scalarField boundaryDiagCmpt(psi_.size(), 0);
addBoundaryDiag(boundaryDiagCmpt, cmpt);
FieldField<Field, scalar> bouCoeffsCmpt
(
boundaryCoeffs_.component(cmpt)
);
res.replace
(
cmpt,
lduMatrix::residual
(
psiCmpt,
res.component(cmpt) - boundaryDiagCmpt*psiCmpt,
bouCoeffsCmpt,
interfaces,
cmpt
)
);
}
return tres;
}
// ************************************************************************* //
|
CFDEMproject/OpenFOAM-1.6-ext
|
src/finiteVolume/fvMatrices/fvMatrix/fvMatrixSolve.C
|
C++
|
gpl-2.0
| 6,420
|
/**
* upcasting & downcasting:
* substituting a subclass instance for its superclass is called 'upcasting',
* since a subclass is drawn below its superclass in UML. upcasting is always safe
* since a subclass instance contains all properties of its superclass.
* the compiler checks for valid upcasting, issuing errors when incompatible.
*
* we can revert a substituted instance back to a subclass reference,
* this is called 'downcasting'. this requires -explicit type casting operator-
* in the form of prefix operator (new-type). downcasting is not always safe,
* and throws a runtime 'ClassCastException' if the instance to be downcasted
* doesn't belong to the right subclass. a subclass object can be substituted
* for its superclass, but not conversely.
* Below: superclass A with subclass B, with subclass C
*/
public class A {
/**
* constructor
*/
public A() {
System.out.println("constructed A");
}
public String toString() {
return "this is object A";
}
}
|
mdnu/misc-java
|
Exercises/12 - Polymorphism/Examples/Upcasting and Downcasting/A.java
|
Java
|
gpl-2.0
| 986
|
<?php
/**
* This file is part of the eZ RepositoryForms package.
*
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
namespace EzSystems\RepositoryForms\FieldType\Mapper;
use EzSystems\RepositoryForms\Data\Content\FieldData;
use EzSystems\RepositoryForms\Data\FieldDefinitionData;
use EzSystems\RepositoryForms\FieldType\FieldDefinitionFormMapperInterface;
use EzSystems\RepositoryForms\FieldType\FieldValueFormMapperInterface;
use EzSystems\RepositoryForms\Form\Type\FieldType\CountryFieldType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\FormInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
class CountryFormMapper implements FieldDefinitionFormMapperInterface, FieldValueFormMapperInterface
{
public function mapFieldDefinitionForm(FormInterface $fieldDefinitionForm, FieldDefinitionData $data)
{
$isTranslation = $data->contentTypeData->languageCode !== $data->contentTypeData->mainLanguageCode;
$fieldDefinitionForm
->add(
'isMultiple',
CheckboxType::class, [
'required' => false,
'property_path' => 'fieldSettings[isMultiple]',
'label' => 'field_definition.ezcountry.is_multiple',
'disabled' => $isTranslation,
]
)
->add(
// Creating from FormBuilder as we need to add a DataTransformer.
$fieldDefinitionForm->getConfig()->getFormFactory()->createBuilder()
->create(
'defaultValue',
CountryFieldType::class, [
'choices_as_values' => true,
'multiple' => true,
'expanded' => false,
'required' => false,
'label' => 'field_definition.ezcountry.default_value',
'disabled' => $isTranslation,
]
)
// Deactivate auto-initialize as we're not on the root form.
->setAutoInitialize(false)->getForm()
);
}
public function mapFieldValueForm(FormInterface $fieldForm, FieldData $data)
{
$fieldDefinition = $data->fieldDefinition;
$fieldSettings = $fieldDefinition->getFieldSettings();
$formConfig = $fieldForm->getConfig();
$fieldForm
->add(
$formConfig->getFormFactory()->createBuilder()
->create('value', CountryFieldType::class, [
'multiple' => $fieldSettings['isMultiple'],
'required' => $fieldDefinition->isRequired,
'label' => $fieldDefinition->getName(),
])
->setAutoInitialize(false)
->getForm()
);
}
/**
* Fake method to set the translation domain for the extractor.
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver
->setDefaults([
'translation_domain' => 'ezrepoforms_content_type',
]);
}
}
|
ezpublishlegacy/repository-forms
|
lib/FieldType/Mapper/CountryFormMapper.php
|
PHP
|
gpl-2.0
| 3,380
|
/*
* Copyright (C) 2013 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
WebInspector.TimelineRecording = class TimelineRecording extends WebInspector.Object
{
constructor(identifier, displayName, instruments)
{
super();
this._identifier = identifier;
this._timelines = new Map;
this._displayName = displayName;
this._capturing = false;
this._readonly = false;
this._instruments = instruments || [];
let timelines = [
WebInspector.TimelineRecord.Type.Network,
WebInspector.TimelineRecord.Type.Layout,
WebInspector.TimelineRecord.Type.Script,
WebInspector.TimelineRecord.Type.RenderingFrame,
WebInspector.TimelineRecord.Type.Memory,
];
for (let type of timelines) {
let timeline = WebInspector.Timeline.create(type);
this._timelines.set(type, timeline);
timeline.addEventListener(WebInspector.Timeline.Event.TimesUpdated, this._timelineTimesUpdated, this);
}
// For legacy backends, we compute the elapsed time of records relative to this timestamp.
this._legacyFirstRecordedTimestamp = NaN;
this.reset(true);
}
// Static
static sourceCodeTimelinesSupported()
{
return WebInspector.debuggableType === WebInspector.DebuggableType.Web;
}
// Public
get displayName()
{
return this._displayName;
}
get identifier()
{
return this._identifier;
}
get timelines()
{
return this._timelines;
}
get instruments()
{
return this._instruments;
}
get readonly()
{
return this._readonly;
}
get startTime()
{
return this._startTime;
}
get endTime()
{
return this._endTime;
}
start()
{
console.assert(!this._capturing, "Attempted to start an already started session.");
console.assert(!this._readonly, "Attempted to start a readonly session.");
this._capturing = true;
for (let instrument of this._instruments)
instrument.startInstrumentation();
}
stop()
{
console.assert(this._capturing, "Attempted to stop an already stopped session.");
console.assert(!this._readonly, "Attempted to stop a readonly session.");
this._capturing = false;
for (let instrument of this._instruments)
instrument.stopInstrumentation();
}
saveIdentityToCookie()
{
// Do nothing. Timeline recordings are not persisted when the inspector is
// re-opened, so do not attempt to restore by identifier or display name.
}
isEmpty()
{
for (var timeline of this._timelines.values()) {
if (timeline.records.length)
return false;
}
return true;
}
unloaded()
{
console.assert(!this.isEmpty(), "Shouldn't unload an empty recording; it should be reused instead.");
this._readonly = true;
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.Unloaded);
}
reset(suppressEvents)
{
console.assert(!this._readonly, "Can't reset a read-only recording.");
this._sourceCodeTimelinesMap = new Map;
this._eventMarkers = [];
this._startTime = NaN;
this._endTime = NaN;
for (var timeline of this._timelines.values())
timeline.reset(suppressEvents);
WebInspector.RenderingFrameTimelineRecord.resetFrameIndex();
if (!suppressEvents) {
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.Reset);
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.TimesUpdated);
}
}
sourceCodeTimelinesForSourceCode(sourceCode)
{
var timelines = this._sourceCodeTimelinesMap.get(sourceCode);
if (!timelines)
return [];
return [...timelines.values()];
}
timelineForInstrument(instrument)
{
return this._timelines.get(instrument.timelineRecordType);
}
timelineForRecordType(recordType)
{
return this._timelines.get(recordType);
}
addInstrument(instrument)
{
console.assert(instrument instanceof WebInspector.Instrument, instrument);
console.assert(!this._instruments.contains(instrument), this._instruments, instrument);
this._instruments.push(instrument);
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.InstrumentAdded, {instrument});
}
removeInstrument(instrument)
{
console.assert(instrument instanceof WebInspector.Instrument, instrument);
console.assert(this._instruments.contains(instrument), this._instruments, instrument);
this._instruments.remove(instrument);
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.InstrumentRemoved, {instrument});
}
addEventMarker(marker)
{
if (!this._capturing)
return;
this._eventMarkers.push(marker);
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.MarkerAdded, {marker});
}
addRecord(record)
{
var timeline = this._timelines.get(record.type);
console.assert(timeline, record, this._timelines);
if (!timeline)
return;
// Add the record to the global timeline by type.
timeline.addRecord(record);
// Some records don't have source code timelines.
if (record.type === WebInspector.TimelineRecord.Type.Network
|| record.type === WebInspector.TimelineRecord.Type.RenderingFrame
|| record.type === WebInspector.TimelineRecord.Type.Memory)
return;
if (!WebInspector.TimelineRecording.sourceCodeTimelinesSupported())
return;
// Add the record to the source code timelines.
var activeMainResource = WebInspector.frameResourceManager.mainFrame.provisionalMainResource || WebInspector.frameResourceManager.mainFrame.mainResource;
var sourceCode = record.sourceCodeLocation ? record.sourceCodeLocation.sourceCode : activeMainResource;
var sourceCodeTimelines = this._sourceCodeTimelinesMap.get(sourceCode);
if (!sourceCodeTimelines) {
sourceCodeTimelines = new Map;
this._sourceCodeTimelinesMap.set(sourceCode, sourceCodeTimelines);
}
var newTimeline = false;
var key = this._keyForRecord(record);
var sourceCodeTimeline = sourceCodeTimelines.get(key);
if (!sourceCodeTimeline) {
sourceCodeTimeline = new WebInspector.SourceCodeTimeline(sourceCode, record.sourceCodeLocation, record.type, record.eventType);
sourceCodeTimelines.set(key, sourceCodeTimeline);
newTimeline = true;
}
sourceCodeTimeline.addRecord(record);
if (newTimeline)
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.SourceCodeTimelineAdded, {sourceCodeTimeline});
}
computeElapsedTime(timestamp)
{
if (!timestamp || isNaN(timestamp))
return NaN;
// COMPATIBILITY (iOS 8): old backends send timestamps (seconds or milliseconds since the epoch),
// rather than seconds elapsed since timeline capturing started. We approximate the latter by
// subtracting the start timestamp, as old versions did not use monotonic times.
if (WebInspector.TimelineRecording.isLegacy === undefined)
WebInspector.TimelineRecording.isLegacy = timestamp > WebInspector.TimelineRecording.TimestampThresholdForLegacyRecordConversion;
if (!WebInspector.TimelineRecording.isLegacy)
return timestamp;
// If the record's start time is large, but not really large, then it is seconds since epoch
// not millseconds since epoch, so convert it to milliseconds.
if (timestamp < WebInspector.TimelineRecording.TimestampThresholdForLegacyAssumedMilliseconds)
timestamp *= 1000;
if (isNaN(this._legacyFirstRecordedTimestamp))
this._legacyFirstRecordedTimestamp = timestamp;
// Return seconds since the first recorded value.
return (timestamp - this._legacyFirstRecordedTimestamp) / 1000.0;
}
setLegacyBaseTimestamp(timestamp)
{
console.assert(isNaN(this._legacyFirstRecordedTimestamp));
if (timestamp < WebInspector.TimelineRecording.TimestampThresholdForLegacyAssumedMilliseconds)
timestamp *= 1000;
this._legacyFirstRecordedTimestamp = timestamp;
}
initializeTimeBoundsIfNecessary(timestamp)
{
if (isNaN(this._startTime)) {
console.assert(isNaN(this._endTime));
this._startTime = timestamp;
this._endTime = timestamp;
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.TimesUpdated);
}
}
// Private
_keyForRecord(record)
{
var key = record.type;
if (record instanceof WebInspector.ScriptTimelineRecord || record instanceof WebInspector.LayoutTimelineRecord)
key += ":" + record.eventType;
if (record instanceof WebInspector.ScriptTimelineRecord && record.eventType === WebInspector.ScriptTimelineRecord.EventType.EventDispatched)
key += ":" + record.details;
if (record.sourceCodeLocation)
key += ":" + record.sourceCodeLocation.lineNumber + ":" + record.sourceCodeLocation.columnNumber;
return key;
}
_timelineTimesUpdated(event)
{
var timeline = event.target;
var changed = false;
if (isNaN(this._startTime) || timeline.startTime < this._startTime) {
this._startTime = timeline.startTime;
changed = true;
}
if (isNaN(this._endTime) || this._endTime < timeline.endTime) {
this._endTime = timeline.endTime;
changed = true;
}
if (changed)
this.dispatchEventToListeners(WebInspector.TimelineRecording.Event.TimesUpdated);
}
};
WebInspector.TimelineRecording.Event = {
Reset: "timeline-recording-reset",
Unloaded: "timeline-recording-unloaded",
SourceCodeTimelineAdded: "timeline-recording-source-code-timeline-added",
InstrumentAdded: "timeline-recording-instrument-added",
InstrumentRemoved: "timeline-recording-instrument-removed",
TimesUpdated: "timeline-recording-times-updated",
MarkerAdded: "timeline-recording-marker-added",
};
WebInspector.TimelineRecording.isLegacy = undefined;
WebInspector.TimelineRecording.TimestampThresholdForLegacyRecordConversion = 10000000; // Some value not near zero.
WebInspector.TimelineRecording.TimestampThresholdForLegacyAssumedMilliseconds = 1420099200000; // Date.parse("Jan 1, 2015"). Milliseconds since epoch.
|
qtproject/qtwebkit
|
Source/WebInspectorUI/UserInterface/Models/TimelineRecording.js
|
JavaScript
|
gpl-2.0
| 12,242
|
/* -*- c++ -*- ----------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifdef PAIR_CLASS
PairStyle(tersoff/mod/kk,PairTersoffMODKokkos<LMPDeviceType>)
PairStyle(tersoff/mod/kk/device,PairTersoffMODKokkos<LMPDeviceType>)
PairStyle(tersoff/mod/kk/host,PairTersoffMODKokkos<LMPHostType>)
#else
#ifndef LMP_PAIR_TERSOFF_MOD_KOKKOS_H
#define LMP_PAIR_TERSOFF_MOD_KOKKOS_H
#include <cstdio>
#include "pair_kokkos.h"
#include "pair_tersoff_mod.h"
#include "neigh_list_kokkos.h"
namespace LAMMPS_NS {
template<int NEIGHFLAG, int EVFLAG>
struct TagPairTersoffMODComputeHalf{};
template<int NEIGHFLAG, int EVFLAG>
struct TagPairTersoffMODComputeFullA{};
template<int NEIGHFLAG, int EVFLAG>
struct TagPairTersoffMODComputeFullB{};
struct TagPairTersoffMODComputeShortNeigh{};
template<class DeviceType>
class PairTersoffMODKokkos : public PairTersoffMOD {
public:
enum {EnabledNeighFlags=FULL};
enum {COUL_FLAG=0};
typedef DeviceType device_type;
typedef ArrayTypes<DeviceType> AT;
typedef EV_FLOAT value_type;
PairTersoffMODKokkos(class LAMMPS *);
virtual ~PairTersoffMODKokkos();
virtual void compute(int, int);
void init_style();
template<int NEIGHFLAG, int EVFLAG>
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeHalf<NEIGHFLAG,EVFLAG>, const int&, EV_FLOAT&) const;
template<int NEIGHFLAG, int EVFLAG>
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeHalf<NEIGHFLAG,EVFLAG>, const int&) const;
template<int NEIGHFLAG, int EVFLAG>
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeFullA<NEIGHFLAG,EVFLAG>, const int&, EV_FLOAT&) const;
template<int NEIGHFLAG, int EVFLAG>
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeFullA<NEIGHFLAG,EVFLAG>, const int&) const;
template<int NEIGHFLAG, int EVFLAG>
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeFullB<NEIGHFLAG,EVFLAG>, const int&, EV_FLOAT&) const;
template<int NEIGHFLAG, int EVFLAG>
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeFullB<NEIGHFLAG,EVFLAG>, const int&) const;
KOKKOS_INLINE_FUNCTION
void operator()(TagPairTersoffMODComputeShortNeigh, const int&) const;
KOKKOS_INLINE_FUNCTION
double ters_fc_k(const int &i, const int &j, const int &k, const F_FLOAT &r) const;
KOKKOS_INLINE_FUNCTION
double ters_dfc(const int &i, const int &j, const int &k, const F_FLOAT &r) const;
KOKKOS_INLINE_FUNCTION
double ters_fa_k(const int &i, const int &j, const int &k, const F_FLOAT &r) const;
KOKKOS_INLINE_FUNCTION
double ters_dfa(const int &i, const int &j, const int &k, const F_FLOAT &r) const;
KOKKOS_INLINE_FUNCTION
double ters_bij_k(const int &i, const int &j, const int &k, const F_FLOAT &bo) const;
KOKKOS_INLINE_FUNCTION
double ters_dbij(const int &i, const int &j, const int &k, const F_FLOAT &bo) const;
KOKKOS_INLINE_FUNCTION
double bondorder(const int &i, const int &j, const int &k,
const F_FLOAT &rij, const F_FLOAT &dx1, const F_FLOAT &dy1, const F_FLOAT &dz1,
const F_FLOAT &rik, const F_FLOAT &dx2, const F_FLOAT &dy2, const F_FLOAT &dz2) const;
KOKKOS_INLINE_FUNCTION
double ters_gijk(const int &i, const int &j, const int &k, const F_FLOAT &cos) const;
KOKKOS_INLINE_FUNCTION
double ters_dgijk(const int &i, const int &j, const int &k, const F_FLOAT &cos) const;
KOKKOS_INLINE_FUNCTION
void ters_dthb(const int &i, const int &j, const int &k, const F_FLOAT &prefactor,
const F_FLOAT &rij, const F_FLOAT &dx1, const F_FLOAT &dy1, const F_FLOAT &dz1,
const F_FLOAT &rik, const F_FLOAT &dx2, const F_FLOAT &dy2, const F_FLOAT &dz2,
F_FLOAT *fi, F_FLOAT *fj, F_FLOAT *fk) const;
KOKKOS_INLINE_FUNCTION
void ters_dthbj(const int &i, const int &j, const int &k, const F_FLOAT &prefactor,
const F_FLOAT &rij, const F_FLOAT &dx1, const F_FLOAT &dy1, const F_FLOAT &dz1,
const F_FLOAT &rik, const F_FLOAT &dx2, const F_FLOAT &dy2, const F_FLOAT &dz2,
F_FLOAT *fj, F_FLOAT *fk) const;
KOKKOS_INLINE_FUNCTION
void ters_dthbk(const int &i, const int &j, const int &k, const F_FLOAT &prefactor,
const F_FLOAT &rij, const F_FLOAT &dx1, const F_FLOAT &dy1, const F_FLOAT &dz1,
const F_FLOAT &rik, const F_FLOAT &dx2, const F_FLOAT &dy2, const F_FLOAT &dz2,
F_FLOAT *fk) const;
KOKKOS_INLINE_FUNCTION
double vec3_dot(const F_FLOAT x[3], const double y[3]) const {
return x[0]*y[0] + x[1]*y[1] + x[2]*y[2];
}
KOKKOS_INLINE_FUNCTION
void vec3_add(const F_FLOAT x[3], const double y[3], double * const z) const {
z[0] = x[0]+y[0]; z[1] = x[1]+y[1]; z[2] = x[2]+y[2];
}
KOKKOS_INLINE_FUNCTION
void vec3_scale(const F_FLOAT k, const double x[3], double y[3]) const {
y[0] = k*x[0]; y[1] = k*x[1]; y[2] = k*x[2];
}
KOKKOS_INLINE_FUNCTION
void vec3_scaleadd(const F_FLOAT k, const double x[3], const double y[3], double * const z) const {
z[0] = k*x[0]+y[0]; z[1] = k*x[1]+y[1]; z[2] = k*x[2]+y[2];
}
KOKKOS_INLINE_FUNCTION
int sbmask(const int& j) const;
struct params_ters{
KOKKOS_INLINE_FUNCTION
params_ters(){powerm=0;lam3=0;h=0;powern=0;beta=0;lam2=0;bigb=0;bigr=0;bigd=0;
lam1=0;biga=0;powern_del=0;cutsq=0;c1=0;c2=0;c3=0;c4=0;c5=0;ca1=0;ca4=0;};
KOKKOS_INLINE_FUNCTION
params_ters(int i){powerm=0;lam3=0;h=0;powern=0;beta=0;lam2=0;bigb=0;bigr=0;bigd=0;
lam1=0;biga=0;powern_del=0;cutsq=0;c1=0;c2=0;c3=0;c4=0;c5=0;ca1=0;ca4=0;};
F_FLOAT powerm, lam3, h, powern, beta, lam2, bigb, bigr, bigd,
lam1, biga, powern_del, cutsq, c1, c2, c3, c4, c5, ca1, ca4;
};
template<int NEIGHFLAG>
KOKKOS_INLINE_FUNCTION
void ev_tally(EV_FLOAT &ev, const int &i, const int &j,
const F_FLOAT &epair, const F_FLOAT &fpair, const F_FLOAT &delx,
const F_FLOAT &dely, const F_FLOAT &delz) const;
template<int NEIGHFLAG>
KOKKOS_INLINE_FUNCTION
void v_tally3(EV_FLOAT &ev, const int &i, const int &j, const int &k,
F_FLOAT *fj, F_FLOAT *fk, F_FLOAT *drij, F_FLOAT *drik) const;
KOKKOS_INLINE_FUNCTION
void v_tally3_atom(EV_FLOAT &ev, const int &i, const int &j, const int &k,
F_FLOAT *fj, F_FLOAT *fk, F_FLOAT *drji, F_FLOAT *drjk) const;
void allocate();
void setup_params();
protected:
void cleanup_copy();
typedef Kokkos::DualView<int***,DeviceType> tdual_int_3d;
Kokkos::DualView<params_ters***,Kokkos::LayoutRight,DeviceType> k_params;
typename Kokkos::DualView<params_ters***,
Kokkos::LayoutRight,DeviceType>::t_dev_const_um paramskk;
// hardwired to space for 12 atom types
//params_ters m_params[MAX_TYPES_STACKPARAMS+1][MAX_TYPES_STACKPARAMS+1][MAX_TYPES_STACKPARAMS+1];
int inum;
typename AT::t_x_array_randomread x;
typename AT::t_f_array f;
typename AT::t_int_1d_randomread type;
typename AT::t_tagint_1d tag;
DAT::tdual_efloat_1d k_eatom;
DAT::tdual_virial_array k_vatom;
typename ArrayTypes<DeviceType>::t_efloat_1d d_eatom;
typename ArrayTypes<DeviceType>::t_virial_array d_vatom;
int need_dup;
Kokkos::Experimental::ScatterView<F_FLOAT*[3], typename DAT::t_f_array::array_layout,DeviceType,Kokkos::Experimental::ScatterSum,Kokkos::Experimental::ScatterDuplicated> dup_f;
Kokkos::Experimental::ScatterView<E_FLOAT*, typename DAT::t_efloat_1d::array_layout,DeviceType,Kokkos::Experimental::ScatterSum,Kokkos::Experimental::ScatterDuplicated> dup_eatom;
Kokkos::Experimental::ScatterView<F_FLOAT*[6], typename DAT::t_virial_array::array_layout,DeviceType,Kokkos::Experimental::ScatterSum,Kokkos::Experimental::ScatterDuplicated> dup_vatom;
Kokkos::Experimental::ScatterView<F_FLOAT*[3], typename DAT::t_f_array::array_layout,DeviceType,Kokkos::Experimental::ScatterSum,Kokkos::Experimental::ScatterNonDuplicated> ndup_f;
Kokkos::Experimental::ScatterView<E_FLOAT*, typename DAT::t_efloat_1d::array_layout,DeviceType,Kokkos::Experimental::ScatterSum,Kokkos::Experimental::ScatterNonDuplicated> ndup_eatom;
Kokkos::Experimental::ScatterView<F_FLOAT*[6], typename DAT::t_virial_array::array_layout,DeviceType,Kokkos::Experimental::ScatterSum,Kokkos::Experimental::ScatterNonDuplicated> ndup_vatom;
typedef Kokkos::DualView<F_FLOAT**[7],Kokkos::LayoutRight,DeviceType> tdual_ffloat_2d_n7;
typedef typename tdual_ffloat_2d_n7::t_dev_const_randomread t_ffloat_2d_n7_randomread;
typedef typename tdual_ffloat_2d_n7::t_host t_host_ffloat_2d_n7;
typename AT::t_neighbors_2d d_neighbors;
typename AT::t_int_1d_randomread d_ilist;
typename AT::t_int_1d_randomread d_numneigh;
//NeighListKokkos<DeviceType> k_list;
int neighflag,newton_pair;
int nlocal,nall,eflag,vflag;
Kokkos::View<int**,DeviceType> d_neighbors_short;
Kokkos::View<int*,DeviceType> d_numneigh_short;
friend void pair_virial_fdotr_compute<PairTersoffMODKokkos>(PairTersoffMODKokkos*);
};
}
#endif
#endif
/* ERROR/WARNING messages:
E: Cannot (yet) use full neighbor list style with tersoff/mod/kk
Self-explanatory.
E: Cannot use chosen neighbor list style with tersoff/mod/kk
Self-explanatory.
*/
|
timattox/lammps_USER-DPD
|
src/KOKKOS/pair_tersoff_mod_kokkos.h
|
C
|
gpl-2.0
| 9,598
|
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="{{ site.url }}/assets/js/vendor/jquery-1.9.1.min.js"><\/script>')</script>
<script src="{{ site.url }}/assets/js/scripts.min.js"></script>
{% if site.google_analytics %}
<!-- Asynchronous Google Analytics snippet -->
<!-- Old
<script>
var _gaq = _gaq || [];
var pluginUrl =
'//www.google-analytics.com/plugins/ga/inpage_linkid.js';
_gaq.push(['_require', 'inpage_linkid', pluginUrl]);
_gaq.push(['_setAccount', '{{ site.google_analytics }}']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
-->
<!-- New -->
<!-- Global Site Tag (gtag.js) - Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', '{{ site.google_analytics }}', 'auto');
ga('send', 'pageview');
</script>
{% endif %}
{% if page.comments %}
{% include _disqus_comments.html %}
{% endif %}
|
mikeguru/mikeguru.github.io
|
_includes/_scripts.html
|
HTML
|
gpl-2.0
| 1,546
|
#!/bin/sh
# -*- mode: shell-script; indent-tabs-mode: nil; sh-basic-offset: 4; -*-
# ex: ts=8 sw=4 sts=4 et filetype=sh
# Licensed under the GPLv2
#
# Copyright (C) 2011 Politecnico di Torino, Italy
# TORSEC group -- http://security.polito.it
# Roberto Sassu <roberto.sassu@polito.it>
IMASECDIR="${SECURITYFSDIR}/ima"
IMACONFIG="${NEWROOT}/etc/sysconfig/ima"
IMAPOLICY="/etc/sysconfig/ima-policy"
load_ima_policy()
{
# check kernel support for IMA
if [ ! -e "${IMASECDIR}" ]; then
if [ "${RD_DEBUG}" = "yes" ]; then
info "integrity: IMA kernel support is disabled"
fi
return 0
fi
# override the default configuration
[ -f "${IMACONFIG}" ] && \
. ${IMACONFIG}
# set the IMA policy path name
IMAPOLICYPATH="${NEWROOT}${IMAPOLICY}"
# check the existence of the IMA policy file
[ -f "${IMAPOLICYPATH}" ] && {
info "Loading the provided IMA custom policy";
cat ${IMAPOLICYPATH} > ${IMASECDIR}/policy;
}
return 0
}
load_ima_policy
|
zfsonlinux/dracut
|
modules.d/98integrity/ima-policy-load.sh
|
Shell
|
gpl-2.0
| 1,056
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.