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) 2011, Code Aurora Forum. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include "board-msm7x30-regulator.h"
#define PCOM_VREG_CONSUMERS(name) \
static struct regulator_consumer_supply __pcom_vreg_supply_##name[]
#define PCOM_VREG_CONSTRAINT_LVSW(_name, _always_on, _boot_on, _supply_uV) \
{ \
.name = #_name, \
.min_uV = 0, \
.max_uV = 0, \
.input_uV = _supply_uV, \
.valid_modes_mask = REGULATOR_MODE_NORMAL, \
.valid_ops_mask = REGULATOR_CHANGE_STATUS, \
.apply_uV = 0, \
.boot_on = _boot_on, \
.always_on = _always_on \
}
#define PCOM_VREG_CONSTRAINT_DYN(_name, _min_uV, _max_uV, _always_on, \
_boot_on, _apply_uV, _supply_uV) \
{ \
.name = #_name, \
.min_uV = _min_uV, \
.max_uV = _max_uV, \
.valid_modes_mask = REGULATOR_MODE_NORMAL, \
.valid_ops_mask = REGULATOR_CHANGE_VOLTAGE | REGULATOR_CHANGE_STATUS, \
.input_uV = _supply_uV, \
.apply_uV = _apply_uV, \
.boot_on = _boot_on, \
.always_on = _always_on \
}
#define PCOM_VREG_INIT(_name, _supply, _constraints)\
{ \
.supply_regulator = _supply, \
.consumer_supplies = __pcom_vreg_supply_##_name, \
.num_consumer_supplies = ARRAY_SIZE(__pcom_vreg_supply_##_name), \
.constraints = _constraints \
}
#define PCOM_VREG_SMP(_name, _id, _supply, _min_uV, _max_uV, _rise_time, \
_pulldown, _always_on, _boot_on, _apply_uV, _supply_uV) \
{ \
.init_data = PCOM_VREG_INIT(_name, _supply, \
PCOM_VREG_CONSTRAINT_DYN(_name, _min_uV, _max_uV, _always_on, \
_boot_on, _apply_uV, _supply_uV)), \
.id = _id, \
.rise_time = _rise_time, \
.pulldown = _pulldown, \
.negative = 0, \
}
#define PCOM_VREG_LDO PCOM_VREG_SMP
#define PCOM_VREG_LVS(_name, _id, _supply, _rise_time, _pulldown, _always_on, \
_boot_on) \
{ \
.init_data = PCOM_VREG_INIT(_name, _supply, \
PCOM_VREG_CONSTRAINT_LVSW(_name, _always_on, _boot_on, 0)), \
.id = _id, \
.rise_time = _rise_time, \
.pulldown = _pulldown, \
.negative = 0, \
}
#define PCOM_VREG_NCP(_name, _id, _supply, _min_uV, _max_uV, _rise_time, \
_always_on, _boot_on, _apply_uV, _supply_uV) \
{ \
.init_data = PCOM_VREG_INIT(_name, _supply, \
PCOM_VREG_CONSTRAINT_DYN(_name, -(_min_uV), -(_max_uV), \
_always_on, _boot_on, _apply_uV, _supply_uV)), \
.id = _id, \
.rise_time = _rise_time, \
.pulldown = -1, \
.negative = 1, \
}
PCOM_VREG_CONSUMERS(smps0) = {
REGULATOR_SUPPLY("smps0", NULL),
REGULATOR_SUPPLY("msmc1", NULL),
};
PCOM_VREG_CONSUMERS(smps1) = {
REGULATOR_SUPPLY("smps1", NULL),
REGULATOR_SUPPLY("msmc2", NULL),
};
PCOM_VREG_CONSUMERS(smps2) = {
REGULATOR_SUPPLY("smps2", NULL),
REGULATOR_SUPPLY("s2", NULL),
};
PCOM_VREG_CONSUMERS(smps3) = {
REGULATOR_SUPPLY("smps3", NULL),
REGULATOR_SUPPLY("s3", NULL),
};
PCOM_VREG_CONSUMERS(smps4) = {
REGULATOR_SUPPLY("smps4", NULL),
REGULATOR_SUPPLY("s4", NULL),
};
PCOM_VREG_CONSUMERS(ldo00) = {
REGULATOR_SUPPLY("ldo00", NULL),
REGULATOR_SUPPLY("ldo0", NULL),
REGULATOR_SUPPLY("gp3", NULL),
};
PCOM_VREG_CONSUMERS(ldo02) = {
REGULATOR_SUPPLY("ldo02", NULL),
REGULATOR_SUPPLY("ldo2", NULL),
REGULATOR_SUPPLY("xo_out", NULL),
};
PCOM_VREG_CONSUMERS(ldo03) = {
REGULATOR_SUPPLY("ldo03", NULL),
REGULATOR_SUPPLY("ldo3", NULL),
REGULATOR_SUPPLY("ruim", NULL),
};
PCOM_VREG_CONSUMERS(ldo04) = {
REGULATOR_SUPPLY("ldo04", NULL),
REGULATOR_SUPPLY("ldo4", NULL),
REGULATOR_SUPPLY("tcxo", NULL),
};
PCOM_VREG_CONSUMERS(ldo05) = {
REGULATOR_SUPPLY("ldo05", NULL),
REGULATOR_SUPPLY("ldo5", NULL),
REGULATOR_SUPPLY("mmc", NULL),
};
PCOM_VREG_CONSUMERS(ldo06) = {
REGULATOR_SUPPLY("ldo06", NULL),
REGULATOR_SUPPLY("ldo6", NULL),
REGULATOR_SUPPLY("usb", NULL),
};
PCOM_VREG_CONSUMERS(ldo07) = {
REGULATOR_SUPPLY("ldo07", NULL),
REGULATOR_SUPPLY("ldo7", NULL),
REGULATOR_SUPPLY("usb2", NULL),
};
PCOM_VREG_CONSUMERS(ldo08) = {
REGULATOR_SUPPLY("ldo08", NULL),
REGULATOR_SUPPLY("ldo8", NULL),
REGULATOR_SUPPLY("gp7", NULL),
};
PCOM_VREG_CONSUMERS(ldo09) = {
REGULATOR_SUPPLY("ldo09", NULL),
REGULATOR_SUPPLY("ldo9", NULL),
REGULATOR_SUPPLY("gp1", NULL),
};
PCOM_VREG_CONSUMERS(ldo10) = {
REGULATOR_SUPPLY("ldo10", NULL),
REGULATOR_SUPPLY("gp4", NULL),
};
PCOM_VREG_CONSUMERS(ldo11) = {
REGULATOR_SUPPLY("ldo11", NULL),
REGULATOR_SUPPLY("gp2", NULL),
};
PCOM_VREG_CONSUMERS(ldo12) = {
REGULATOR_SUPPLY("ldo12", NULL),
REGULATOR_SUPPLY("gp9", NULL),
};
PCOM_VREG_CONSUMERS(ldo13) = {
REGULATOR_SUPPLY("ldo13", NULL),
REGULATOR_SUPPLY("wlan", NULL),
};
PCOM_VREG_CONSUMERS(ldo14) = {
REGULATOR_SUPPLY("ldo14", NULL),
REGULATOR_SUPPLY("rf", NULL),
};
PCOM_VREG_CONSUMERS(ldo15) = {
REGULATOR_SUPPLY("ldo15", NULL),
REGULATOR_SUPPLY("gp6", NULL),
};
PCOM_VREG_CONSUMERS(ldo16) = {
REGULATOR_SUPPLY("ldo16", NULL),
REGULATOR_SUPPLY("gp10", NULL),
};
PCOM_VREG_CONSUMERS(ldo17) = {
REGULATOR_SUPPLY("ldo17", NULL),
REGULATOR_SUPPLY("gp11", NULL),
};
PCOM_VREG_CONSUMERS(ldo18) = {
REGULATOR_SUPPLY("ldo18", NULL),
REGULATOR_SUPPLY("gp12", NULL),
};
PCOM_VREG_CONSUMERS(ldo19) = {
REGULATOR_SUPPLY("ldo19", NULL),
REGULATOR_SUPPLY("wlan2", NULL),
};
PCOM_VREG_CONSUMERS(ldo20) = {
REGULATOR_SUPPLY("ldo20", NULL),
REGULATOR_SUPPLY("gp13", NULL),
};
PCOM_VREG_CONSUMERS(ldo21) = {
REGULATOR_SUPPLY("ldo21", NULL),
REGULATOR_SUPPLY("gp14", NULL),
};
PCOM_VREG_CONSUMERS(ldo22) = {
REGULATOR_SUPPLY("ldo22", NULL),
REGULATOR_SUPPLY("gp15", NULL),
};
PCOM_VREG_CONSUMERS(ldo23) = {
REGULATOR_SUPPLY("ldo23", NULL),
REGULATOR_SUPPLY("gp5", NULL),
};
PCOM_VREG_CONSUMERS(ldo24) = {
REGULATOR_SUPPLY("ldo24", NULL),
REGULATOR_SUPPLY("gp16", NULL),
};
PCOM_VREG_CONSUMERS(ldo25) = {
REGULATOR_SUPPLY("ldo25", NULL),
REGULATOR_SUPPLY("gp17", NULL),
};
PCOM_VREG_CONSUMERS(lvsw0) = {
REGULATOR_SUPPLY("lvsw0", NULL),
REGULATOR_SUPPLY("lvs0", NULL),
};
PCOM_VREG_CONSUMERS(lvsw1) = {
REGULATOR_SUPPLY("lvsw1", NULL),
REGULATOR_SUPPLY("lvs1", NULL),
};
PCOM_VREG_CONSUMERS(ncp) = {
REGULATOR_SUPPLY("ncp", NULL),
};
/* This list needs to be verified against actual 7x30 hardware requirements. */
static struct proccomm_regulator_info msm7x30_pcom_vreg_info[] = {
/* Standard regulators (SMPS and LDO)
* R = rise time (us)
* P = pulldown (1 = pull down, 0 = float, -1 = don't care)
* A = always on
* B = boot on
* V = automatic voltage set (meaningful for single-voltage regs only)
* S = supply voltage (uV)
* name id supp min uV max uV R P A B V S */
PCOM_VREG_SMP(smps0, 3, NULL, 500000, 1500000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_SMP(smps1, 4, NULL, 500000, 1500000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_SMP(smps2, 28, NULL, 1300000, 1300000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_SMP(smps3, 29, NULL, 1800000, 1800000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_SMP(smps4, 43, NULL, 2200000, 2200000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo00, 5, NULL, 1200000, 1200000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo02, 46, NULL, 2600000, 2600000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo03, 19, NULL, 1800000, 3000000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo04, 9, NULL, 2850000, 2850000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo05, 18, NULL, 2850000, 2850000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo06, 16, NULL, 3075000, 3400000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo07, 44, NULL, 1800000, 1800000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo08, 32, NULL, 1800000, 2850000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo09, 8, NULL, 2050000, 2050000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo10, 7, NULL, 2600000, 2700000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo11, 21, NULL, 1800000, 2600000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo12, 34, NULL, 1800000, 1800000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo13, 15, NULL, 2900000, 3050000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo14, 24, NULL, 2850000, 2850000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo15, 23, NULL, 3050000, 3100000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo16, 35, NULL, 2600000, 2600000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo17, 36, NULL, 2600000, 2600000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo18, 37, NULL, 2200000, 2200000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo19, 45, NULL, 2400000, 2500000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo20, 38, NULL, 1500000, 1800000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo21, 39, NULL, 1100000, 1100000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo22, 40, NULL, 1200000, 1300000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo23, 22, NULL, 1350000, 1350000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo24, 41, NULL, 1200000, 1200000, 0, -1, 0, 0, 0, 0),
PCOM_VREG_LDO(ldo25, 42, NULL, 1200000, 1200000, 0, -1, 0, 0, 0, 0),
/* Low-voltage switches */
PCOM_VREG_LVS(lvsw0, 47, NULL, 0, -1, 0, 0),
PCOM_VREG_LVS(lvsw1, 48, NULL, 0, -1, 0, 0),
PCOM_VREG_NCP(ncp, 31, NULL, -1800000, -1800000, 0, 0, 0, 0, 0),
};
struct proccomm_regulator_platform_data msm7x30_proccomm_regulator_data = {
.regs = msm7x30_pcom_vreg_info,
.nregs = ARRAY_SIZE(msm7x30_pcom_vreg_info)
};
|
PaulMilbank/g300_kernel
|
arch/arm/mach-msm/board-msm7x30-regulator.c
|
C
|
gpl-2.0
| 9,390
|
<HTML>
<HEAD>
<!-- This HTML file has been created by texi2html 1.52b
from gettext.texi on 25 October 2006 -->
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=UTF-8">
<TITLE>GNU gettext utilities - 7 Updating Existing PO Files</TITLE>
</HEAD>
<BODY>
Go to the <A HREF="gettext_1.html">first</A>, <A HREF="gettext_6.html">previous</A>, <A HREF="gettext_8.html">next</A>, <A HREF="gettext_25.html">last</A> section, <A HREF="gettext_toc.html">table of contents</A>.
<P><HR><P>
<H1><A NAME="SEC39" HREF="gettext_toc.html#TOC39">7 Updating Existing PO Files</A></H1>
<H2><A NAME="SEC40" HREF="gettext_toc.html#TOC40">7.1 Invoking the <CODE>msgmerge</CODE> Program</A></H2>
<P>
<A NAME="IDX252"></A>
<A NAME="IDX253"></A>
<PRE>
msgmerge [<VAR>option</VAR>] <VAR>def</VAR>.po <VAR>ref</VAR>.pot
</PRE>
<P>
The <CODE>msgmerge</CODE> program merges two Uniforum style .po files together.
The <VAR>def</VAR>.po file is an existing PO file with translations which will
be taken over to the newly created file as long as they still match;
comments will be preserved, but extracted comments and file positions will
be discarded. The <VAR>ref</VAR>.pot file is the last created PO file with
up-to-date source references but old translations, or a PO Template file
(generally created by <CODE>xgettext</CODE>); any translations or comments
in the file will be discarded, however dot comments and file positions
will be preserved. Where an exact match cannot be found, fuzzy matching
is used to produce better results.
</P>
<H3><A NAME="SEC41" HREF="gettext_toc.html#TOC41">7.1.1 Input file location</A></H3>
<DL COMPACT>
<DT><SAMP>‘<VAR>def</VAR>.po’</SAMP>
<DD>
Translations referring to old sources.
<DT><SAMP>‘<VAR>ref</VAR>.pot’</SAMP>
<DD>
References to the new sources.
<DT><SAMP>‘-D <VAR>directory</VAR>’</SAMP>
<DD>
<DT><SAMP>‘--directory=<VAR>directory</VAR>’</SAMP>
<DD>
<A NAME="IDX254"></A>
<A NAME="IDX255"></A>
Add <VAR>directory</VAR> to the list of directories. Source files are
searched relative to this list of directories. The resulting <TT>‘.po’</TT>
file will be written relative to the current directory, though.
<DT><SAMP>‘-C <VAR>file</VAR>’</SAMP>
<DD>
<DT><SAMP>‘--compendium=<VAR>file</VAR>’</SAMP>
<DD>
<A NAME="IDX256"></A>
<A NAME="IDX257"></A>
Specify an additional library of message translations. See section <A HREF="gettext_8.html#SEC66">8.3.14 Using Translation Compendia</A>.
This option may be specified more than once.
</DL>
<H3><A NAME="SEC42" HREF="gettext_toc.html#TOC42">7.1.2 Operation mode</A></H3>
<DL COMPACT>
<DT><SAMP>‘-U’</SAMP>
<DD>
<DT><SAMP>‘--update’</SAMP>
<DD>
<A NAME="IDX258"></A>
<A NAME="IDX259"></A>
Update <VAR>def</VAR>.po. Do nothing if <VAR>def</VAR>.po is already up to date.
</DL>
<H3><A NAME="SEC43" HREF="gettext_toc.html#TOC43">7.1.3 Output file location</A></H3>
<DL COMPACT>
<DT><SAMP>‘-o <VAR>file</VAR>’</SAMP>
<DD>
<DT><SAMP>‘--output-file=<VAR>file</VAR>’</SAMP>
<DD>
<A NAME="IDX260"></A>
<A NAME="IDX261"></A>
Write output to specified file.
</DL>
<P>
<A NAME="IDX262"></A>
The results are written to standard output if no output file is specified
or if it is <SAMP>‘-’</SAMP>.
</P>
<H3><A NAME="SEC44" HREF="gettext_toc.html#TOC44">7.1.4 Output file location in update mode</A></H3>
<P>
The result is written back to <VAR>def</VAR>.po.
</P>
<DL COMPACT>
<DT><SAMP>‘--backup=<VAR>control</VAR>’</SAMP>
<DD>
<A NAME="IDX263"></A>
<A NAME="IDX264"></A>
Make a backup of <VAR>def</VAR>.po
<DT><SAMP>‘--suffix=<VAR>suffix</VAR>’</SAMP>
<DD>
<A NAME="IDX265"></A>
Override the usual backup suffix.
</DL>
<P>
<A NAME="IDX266"></A>
The version control method may be selected via the <CODE>--backup</CODE> option
or through the <CODE>VERSION_CONTROL</CODE> environment variable. Here are the
values:
</P>
<DL COMPACT>
<DT><SAMP>‘none’</SAMP>
<DD>
<DT><SAMP>‘off’</SAMP>
<DD>
Never make backups (even if <CODE>--backup</CODE> is given).
<DT><SAMP>‘numbered’</SAMP>
<DD>
<DT><SAMP>‘t’</SAMP>
<DD>
Make numbered backups.
<DT><SAMP>‘existing’</SAMP>
<DD>
<DT><SAMP>‘nil’</SAMP>
<DD>
Make numbered backups if numbered backups for this file already exist,
otherwise make simple backups.
<DT><SAMP>‘simple’</SAMP>
<DD>
<DT><SAMP>‘never’</SAMP>
<DD>
Always make simple backups.
</DL>
<P>
The backup suffix is <SAMP>‘~’</SAMP>, unless set with <CODE>--suffix</CODE> or the
<CODE>SIMPLE_BACKUP_SUFFIX</CODE> environment variable.
</P>
<H3><A NAME="SEC45" HREF="gettext_toc.html#TOC45">7.1.5 Operation modifiers</A></H3>
<DL COMPACT>
<DT><SAMP>‘-m’</SAMP>
<DD>
<DT><SAMP>‘--multi-domain’</SAMP>
<DD>
<A NAME="IDX267"></A>
<A NAME="IDX268"></A>
Apply <VAR>ref</VAR>.pot to each of the domains in <VAR>def</VAR>.po.
<DT><SAMP>‘-N’</SAMP>
<DD>
<DT><SAMP>‘--no-fuzzy-matching’</SAMP>
<DD>
<A NAME="IDX269"></A>
<A NAME="IDX270"></A>
Do not use fuzzy matching when an exact match is not found. This may speed
up the operation considerably.
<DT><SAMP>‘--previous’</SAMP>
<DD>
<A NAME="IDX271"></A>
Keep the previous msgids of translated messages, marked with <SAMP>‘#|’</SAMP>, when
adding the fuzzy marker to such messages.
</DL>
<H3><A NAME="SEC46" HREF="gettext_toc.html#TOC46">7.1.6 Input file syntax</A></H3>
<DL COMPACT>
<DT><SAMP>‘-P’</SAMP>
<DD>
<DT><SAMP>‘--properties-input’</SAMP>
<DD>
<A NAME="IDX272"></A>
<A NAME="IDX273"></A>
Assume the input files are Java ResourceBundles in Java <CODE>.properties</CODE>
syntax, not in PO file syntax.
<DT><SAMP>‘--stringtable-input’</SAMP>
<DD>
<A NAME="IDX274"></A>
Assume the input files are NeXTstep/GNUstep localized resource files in
<CODE>.strings</CODE> syntax, not in PO file syntax.
</DL>
<H3><A NAME="SEC47" HREF="gettext_toc.html#TOC47">7.1.7 Output details</A></H3>
<DL COMPACT>
<DT><SAMP>‘--force-po’</SAMP>
<DD>
<A NAME="IDX275"></A>
Always write an output file even if it contains no message.
<DT><SAMP>‘-i’</SAMP>
<DD>
<DT><SAMP>‘--indent’</SAMP>
<DD>
<A NAME="IDX276"></A>
<A NAME="IDX277"></A>
Write the .po file using indented style.
<DT><SAMP>‘--no-location’</SAMP>
<DD>
<A NAME="IDX278"></A>
Do not write <SAMP>‘#: <VAR>filename</VAR>:<VAR>line</VAR>’</SAMP> lines.
<DT><SAMP>‘--add-location’</SAMP>
<DD>
<A NAME="IDX279"></A>
Generate <SAMP>‘#: <VAR>filename</VAR>:<VAR>line</VAR>’</SAMP> lines (default).
<DT><SAMP>‘--strict’</SAMP>
<DD>
<A NAME="IDX280"></A>
Write out a strict Uniforum conforming PO file. Note that this
Uniforum format should be avoided because it doesn't support the
GNU extensions.
<DT><SAMP>‘-p’</SAMP>
<DD>
<DT><SAMP>‘--properties-output’</SAMP>
<DD>
<A NAME="IDX281"></A>
<A NAME="IDX282"></A>
Write out a Java ResourceBundle in Java <CODE>.properties</CODE> syntax. Note
that this file format doesn't support plural forms and silently drops
obsolete messages.
<DT><SAMP>‘--stringtable-output’</SAMP>
<DD>
<A NAME="IDX283"></A>
Write out a NeXTstep/GNUstep localized resource file in <CODE>.strings</CODE> syntax.
Note that this file format doesn't support plural forms.
<DT><SAMP>‘-w <VAR>number</VAR>’</SAMP>
<DD>
<DT><SAMP>‘--width=<VAR>number</VAR>’</SAMP>
<DD>
<A NAME="IDX284"></A>
<A NAME="IDX285"></A>
Set the output page width. Long strings in the output files will be
split across multiple lines in order to ensure that each line's width
(= number of screen columns) is less or equal to the given <VAR>number</VAR>.
<DT><SAMP>‘--no-wrap’</SAMP>
<DD>
<A NAME="IDX286"></A>
Do not break long message lines. Message lines whose width exceeds the
output page width will not be split into several lines. Only file reference
lines which are wider than the output page width will be split.
<DT><SAMP>‘-s’</SAMP>
<DD>
<DT><SAMP>‘--sort-output’</SAMP>
<DD>
<A NAME="IDX287"></A>
<A NAME="IDX288"></A>
<A NAME="IDX289"></A>
Generate sorted output. Note that using this option makes it much harder
for the translator to understand each message's context.
<DT><SAMP>‘-F’</SAMP>
<DD>
<DT><SAMP>‘--sort-by-file’</SAMP>
<DD>
<A NAME="IDX290"></A>
<A NAME="IDX291"></A>
Sort output by file location.
</DL>
<H3><A NAME="SEC48" HREF="gettext_toc.html#TOC48">7.1.8 Informative output</A></H3>
<DL COMPACT>
<DT><SAMP>‘-h’</SAMP>
<DD>
<DT><SAMP>‘--help’</SAMP>
<DD>
<A NAME="IDX292"></A>
<A NAME="IDX293"></A>
Display this help and exit.
<DT><SAMP>‘-V’</SAMP>
<DD>
<DT><SAMP>‘--version’</SAMP>
<DD>
<A NAME="IDX294"></A>
<A NAME="IDX295"></A>
Output version information and exit.
<DT><SAMP>‘-v’</SAMP>
<DD>
<DT><SAMP>‘--verbose’</SAMP>
<DD>
<A NAME="IDX296"></A>
<A NAME="IDX297"></A>
Increase verbosity level.
<DT><SAMP>‘-q’</SAMP>
<DD>
<DT><SAMP>‘--quiet’</SAMP>
<DD>
<DT><SAMP>‘--silent’</SAMP>
<DD>
<A NAME="IDX298"></A>
<A NAME="IDX299"></A>
<A NAME="IDX300"></A>
Suppress progress indicators.
</DL>
<P><HR><P>
Go to the <A HREF="gettext_1.html">first</A>, <A HREF="gettext_6.html">previous</A>, <A HREF="gettext_8.html">next</A>, <A HREF="gettext_25.html">last</A> section, <A HREF="gettext_toc.html">table of contents</A>.
</BODY>
</HTML>
|
ipwndev/DSLinux-Mirror
|
lib/gettext/src/gettext-tools/doc/gettext_7.html
|
HTML
|
gpl-2.0
| 9,712
|
# $Id: 150_srtp_1_1.py 369517 2012-07-01 17:28:57Z file $
#
from inc_cfg import *
test_param = TestParam(
"Callee=optional SRTP, caller=optional SRTP",
[
InstanceParam("callee", "--null-audio --use-srtp=1 --srtp-secure=0 --max-calls=1"),
InstanceParam("caller", "--null-audio --use-srtp=1 --srtp-secure=0 --max-calls=1")
]
)
|
fluentstream/asterisk-p2p
|
res/pjproject/tests/pjsua/scripts-call/150_srtp_1_1.py
|
Python
|
gpl-2.0
| 340
|
/*
* Bittorrent Client using Qt and libtorrent.
* Copyright (C) 2016 Vladimir Golovnev <glassez@yandex.ru>
*
* 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.
*
* In addition, as a special exception, the copyright holders give permission to
* link this program with the OpenSSL project's "OpenSSL" library (or with
* modified versions of it that use the same license as the "OpenSSL" library),
* and distribute the linked executables. You must obey the GNU General Public
* License in all respects for all of the code used other than "OpenSSL". If you
* modify file(s), you may extend this exception to your version of the file(s),
* but you are not obligated to do so. If you do not wish to do so, delete this
* exception statement from your version.
*/
#ifndef CATEGORYFILTERMODEL_H
#define CATEGORYFILTERMODEL_H
#include <QAbstractItemModel>
#include <QHash>
#include <QModelIndex>
namespace BitTorrent
{
class TorrentHandle;
}
class CategoryModelItem;
class CategoryFilterModel: public QAbstractItemModel
{
Q_OBJECT
public:
explicit CategoryFilterModel(QObject *parent = nullptr);
~CategoryFilterModel();
int columnCount(const QModelIndex &parent = QModelIndex()) const override;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const override;
Qt::ItemFlags flags(const QModelIndex &index) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const override;
QModelIndex index(int row, int column, const QModelIndex &parent = QModelIndex()) const override;
QModelIndex parent(const QModelIndex &index) const override;
int rowCount(const QModelIndex &parent = QModelIndex()) const override;
QModelIndex index(const QString &categoryName) const;
QString categoryName(const QModelIndex &index) const;
private slots:
void categoryAdded(const QString &categoryName);
void categoryRemoved(const QString &categoryName);
void torrentAdded(BitTorrent::TorrentHandle *const torrent);
void torrentAboutToBeRemoved(BitTorrent::TorrentHandle *const torrent);
void torrentCategoryChanged(BitTorrent::TorrentHandle *const torrent, const QString &oldCategory);
void subcategoriesSupportChanged();
private:
void populate();
QModelIndex index(CategoryModelItem *item) const;
CategoryModelItem *findItem(const QString &fullName) const;
bool m_isSubcategoriesEnabled;
CategoryModelItem *m_rootItem;
};
#endif // CATEGORYFILTERMODEL_H
|
buinsky/qBittorrent
|
src/gui/categoryfiltermodel.h
|
C
|
gpl-2.0
| 3,165
|
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2015 Timothy Pearson <tpearson@raptorengineeringinc.com>, Raptor Engineering
* Copyright (C) 2007-2008 Advanced Micro Devices, Inc.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; 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
*/
/*
* Description: Include file for all generic DDR 2 MCT files.
*/
#ifndef MCT_D_H
#define MCT_D_H
/*===========================================================================
CPU - K8/FAM10
===========================================================================*/
#define PT_L1 0 /* CPU Package Type */
#define PT_M2 1
#define PT_S1 2
#define PT_GR 3
#define J_MIN 0 /* j loop constraint. 1=CL 2.0 T*/
#define J_MAX 5 /* j loop constraint. 5=CL 7.0 T*/
#define K_MIN 1 /* k loop constraint. 1=200 MHz*/
#define K_MAX 5 /* k loop constraint. 5=533 MHz*/
#define CL_DEF 2 /* Default value for failsafe operation. 2=CL 4.0 T*/
#define T_DEF 1 /* Default value for failsafe operation. 1=5ns (cycle time)*/
#define BSCRate 1 /* reg bit field=rate of dram scrubber for ecc*/
/* memory initialization (ecc and check-bits).*/
/* 1=40 ns/64 bytes.*/
#define FirstPass 1 /* First pass through RcvEn training*/
#define SecondPass 2 /* Second pass through Rcven training*/
#define RCVREN_MARGIN 6 /* number of DLL taps to delay beyond first passing position*/
#define MAXASYNCLATCTL_2 2 /* Max Async Latency Control value*/
#define MAXASYNCLATCTL_3 3 /* Max Async Latency Control value*/
#define DQS_FAIL 1
#define DQS_PASS 0
#define DQS_WRITEDIR 1
#define DQS_READDIR 0
#define MIN_DQS_WNDW 3
#define secPassOffset 6
#define Pass1MemClkDly 0x20 /* Add 1/2 Memlock delay */
#define MAX_RD_LAT 0x3FF
#define MIN_FENCE 14
#define MAX_FENCE 20
#define MIN_DQS_WR_FENCE 14
#define MAX_DQS_WR_FENCE 20
#define FenceTrnFinDlySeed 19
#define EarlyArbEn 19
#define PA_HOST(Node) ((((0x18+Node) << 3)+0) << 12) /* Node 0 Host Bus function PCI Address bits [15:0]*/
#define PA_MAP(Node) ((((0x18+Node) << 3)+1) << 12) /* Node 0 MAP function PCI Address bits [15:0]*/
#define PA_DCT(Node) ((((0x18+Node) << 3)+2) << 12) /* Node 0 DCT function PCI Address bits [15:0]*/
//#define PA_EXT_DCT (((00 << 3)+4) << 8) /*Node 0 DCT extended configuration registers*/
//#define PA_DCTADDL (((00 << 3)+2) << 8) /*Node x DCT function, Additional Registers PCI Address bits [15:0]*/
//#define PA_EXT_DCTADDL (((00 << 3)+5) << 8) /*Node x DCT function, Additional Registers PCI Address bits [15:0]*/
#define PA_NBMISC(Node) ((((0x18+Node) << 3)+3) << 12) /*Node 0 Misc PCI Address bits [15:0]*/
//#define PA_NBDEVOP (((00 << 3)+3) << 8) /*Node 0 Misc PCI Address bits [15:0]*/
#define DCC_EN 1 /* X:2:0x94[19]*/
#define ILD_Lmt 3 /* X:2:0x94[18:16]*/
#define EncodedTSPD 0x00191709 /* encodes which SPD byte to get T from*/
/* versus CL X, CL X-.5, and CL X-1*/
#define Bias_TrpT 3 /* bias to convert bus clocks to bit field value*/
#define Bias_TrrdT 2
#define Bias_TrcdT 3
#define Bias_TrasT 3
#define Bias_TrcT 11
#define Bias_TrtpT 2
#define Bias_TwrT 3
#define Bias_TwtrT 0
#define Bias_TfawT 7
#define Min_TrpT 3 /* min programmable value in busclocks*/
#define Max_TrpT 6 /* max programmable value in busclocks*/
#define Min_TrrdT 2
#define Max_TrrdT 5
#define Min_TrcdT 3
#define Max_TrcdT 6
#define Min_TrasT 5
#define Max_TrasT 18
#define Min_TrcT 11
#define Max_TrcT 26
#define Min_TrtpT 2
#define Max_TrtpT 3
#define Min_TwrT 3
#define Max_TwrT 6
#define Min_TwtrT 1
#define Max_TwtrT 3
/*DDR2-1066 support*/
#define Bias_TrcdT_1066 5
#define Bias_TrasT_1066 15
#define Bias_TrrdT_1066 4
#define Bias_TwrT_1066 4
#define Bias_TrpT_1066 5
#define Bias_TwtrT_1066 4
#define Bias_TfawT_1066 15
#define Min_TrcdT_1066 5
#define Max_TrcdT_1066 12
#define Min_TrasT_1066 15
#define Max_TrasT_1066 30
#define Min_TrcT_1066 11
#define Max_TrcT_1066 42
#define Min_TrrdT_1066 4
#define Max_TrrdT_1066 7
#define Min_TwrT_1066 5
#define Max_TwrT_1066 8
#define Min_TrpT_1066 5
#define Max_TrpT_1066 12
#define Min_TwtrT_1066 4
#define Max_TwtrT_1066 7
/*common register bit names*/
#define DramHoleValid 0 /* func 1, offset F0h, bit 0*/
#define DramMemHoistValid 1 /* func 1, offset F0h, bit 1*/
#define CSEnable 0 /* func 2, offset 40h-5C, bit 0*/
#define Spare 1 /* func 2, offset 40h-5C, bit 1*/
#define TestFail 2 /* func 2, offset 40h-5C, bit 2*/
#define DqsRcvEnTrain 18 /* func 2, offset 78h, bit 18*/
#define EnDramInit 31 /* func 2, offset 7Ch, bit 31*/
#define DisAutoRefresh 18 /* func 2, offset 8Ch, bit 18*/
#define InitDram 0 /* func 2, offset 90h, bit 0*/
#define BurstLength32 10 /* func 2, offset 90h, bit 10*/
#define Width128 11 /* func 2, offset 90h, bit 11*/
#define X4Dimm 12 /* func 2, offset 90h, bit 12*/
#define UnBuffDimm 16 /* func 2, offset 90h, bit 16*/
#define DimmEcEn 19 /* func 2, offset 90h, bit 19*/
#define MemClkFreqVal 3 /* func 2, offset 94h, bit 3*/
#define RDqsEn 12 /* func 2, offset 94h, bit 12*/
#define DisDramInterface 14 /* func 2, offset 94h, bit 14*/
#define DctAccessWrite 30 /* func 2, offset 98h, bit 30*/
#define DctAccessDone 31 /* func 2, offset 98h, bit 31*/
#define MemClrStatus 0 /* func 2, offset A0h, bit 0*/
#define PwrSavingsEn 10 /* func 2, offset A0h, bit 10*/
#define Mod64BitMux 4 /* func 2, offset A0h, bit 4*/
#define DisableJitter 1 /* func 2, offset A0h, bit 1*/
#define MemClrDis 1 /* func 3, offset F8h, FNC 4, bit 1*/
#define SyncOnUcEccEn 2 /* func 3, offset 44h, bit 2*/
#define Dr_MemClrStatus 10 /* func 3, offset 110h, bit 10*/
#define MemClrBusy 9 /* func 3, offset 110h, bit 9*/
#define DctGangEn 4 /* func 3, offset 110h, bit 4*/
#define MemClrInit 3 /* func 3, offset 110h, bit 3*/
#define AssertCke 28 /* func 2, offset 7Ch, bit 28*/
#define DeassertMemRstX 27 /* func 2, offset 7Ch, bit 27*/
#define SendMrsCmd 26 /* func 2, offset 7Ch, bit 26*/
#define SendAutoRefresh 25 /* func 2, offset 7Ch, bit 25*/
#define SendPchgAll 24 /* func 2, offset 7Ch, bit 24*/
#define DisDqsBar 6 /* func 2, offset 90h, bit 6*/
#define DramEnabled 8 /* func 2, offset 110h, bit 8*/
#define LegacyBiosMode 9 /* func 2, offset 94h, bit 9*/
#define PrefDramTrainMode 28 /* func 2, offset 11Ch, bit 28*/
#define FlushWr 30 /* func 2, offset 11Ch, bit 30*/
#define DisAutoComp 30 /* func 2, offset 9Ch, Index 8, bit 30*/
#define DqsRcvTrEn 13 /* func 2, offset 9Ch, Index 8, bit 13*/
#define ForceAutoPchg 23 /* func 2, offset 90h, bit 23*/
#define ClLinesToNbDis 15 /* Bu_CFG2, bit 15*/
#define WbEnhWsbDis_D (48-32)
#define PhyFenceTrEn 3 /* func 2, offset 9Ch, Index 8, bit 3 */
#define ParEn 8 /* func 2, offset 90h, bit 8 */
#define DcqArbBypassEn 19 /* func 2, offset 94h, bit 19 */
#define ActiveCmdAtRst 1 /* func 2, offset A8H, bit 1 */
#define FlushWrOnStpGnt 29 /* func 2, offset 11Ch, bit 29 */
#define BankSwizzleMode 22 /* func 2, offset 94h, bit 22 */
#define ChSetupSync 15 /* func 2, offset 78h, bit 15 */
/*=============================================================================
SW Initialization
============================================================================*/
#define DLL_Enable 1
#define OCD_Default 2
#define OCD_Exit 3
/*=============================================================================
Jedec DDR II
=============================================================================*/
#define SPD_TYPE 2 /*SPD byte read location*/
#define JED_DDRSDRAM 0x07 /*Jedec defined bit field*/
#define JED_DDR2SDRAM 0x08 /*Jedec defined bit field*/
#define SPD_DIMMTYPE 20
#define SPD_ATTRIB 21
#define JED_DIFCKMSK 0x20 /*Differential Clock Input*/
#define JED_REGADCMSK 0x11 /*Registered Address/Control*/
#define JED_PROBEMSK 0x40 /*Analysis Probe installed*/
#define SPD_DEVATTRIB 22
#define SPD_EDCTYPE 11
#define JED_ECC 0x02
#define JED_ADRCPAR 0x04
#define SPD_ROWSZ 3
#define SPD_COLSZ 4
#define SPD_LBANKS 17 /*number of [logical] banks on each device*/
#define SPD_DMBANKS 5 /*number of physical banks on dimm*/
#define SPDPLBit 4 /* Dram package bit*/
#define SPD_BANKSZ 31 /*capacity of physical bank*/
#define SPD_DEVWIDTH 13
#define SPD_CASLAT 18
#define SPD_TRP 27
#define SPD_TRRD 28
#define SPD_TRCD 29
#define SPD_TRAS 30
#define SPD_TWR 36
#define SPD_TWTR 37
#define SPD_TRTP 38
#define SPD_TRCRFC 40
#define SPD_TRC 41
#define SPD_TRFC 42
#define SPD_MANID_START 64
#define SPD_PARTN_START 73
#define SPD_PARTN_LENGTH 18
#define SPD_REVNO_START 91
#define SPD_MANDATEYR 93 /*Module Manufacturing Year (BCD)*/
#define SPD_MANDATEWK 94 /*Module Manufacturing Week (BCD)*/
#define SPD_SERIAL_START 95
/*-----------------------------
Jedec DDR II related equates
-----------------------------*/
#define MYEAR06 6 /* Manufacturing Year BCD encoding of 2006 - 06d*/
#define MWEEK24 0x24 /* Manufacturing Week BCD encoding of June - 24d*/
/*=============================================================================
Macros
=============================================================================*/
#define _2GB_RJ8 (2<<(30-8))
#define _4GB_RJ8 (4<<(30-8))
#define _4GB_RJ4 (4<<(30-4))
#define BigPagex8_RJ8 (1<<(17+3-8)) /*128KB * 8 >> 8 */
/*=============================================================================
Global MCT Status Structure
=============================================================================*/
struct MCTStatStruc {
u32 GStatus; /* Global Status bitfield*/
u32 HoleBase; /* If not zero, BASE[39:8] (system address)
of sub 4GB dram hole for HW remapping.*/
u32 Sub4GCacheTop; /* If not zero, the 32-bit top of cacheable memory.*/
u32 SysLimit; /* LIMIT[39:8] (system address)*/
} __attribute__((packed));
/*=============================================================================
Global MCT Configuration Status Word (GStatus)
=============================================================================*/
/*These should begin at bit 0 of GStatus[31:0]*/
#define GSB_MTRRshort 0 /* Ran out of MTRRs while mapping memory*/
#define GSB_ECCDIMMs 1 /* All banks of all Nodes are ECC capable*/
#define GSB_DramECCDis 2 /* Dram ECC requested but not enabled.*/
#define GSB_SoftHole 3 /* A Node Base gap was created*/
#define GSB_HWHole 4 /* A HW dram remap was created*/
#define GSB_NodeIntlv 5 /* Node Memory interleaving was enabled*/
#define GSB_SpIntRemapHole 16 /* Special condition for Node Interleave and HW remapping*/
#define GSB_EnDIMMSpareNW 17 /* Indicates that DIMM Spare can be used without a warm reset */
/* NOTE: This is a local bit used by memory code */
/*===============================================================================
Local DCT Status structure (a structure for each DCT)
===============================================================================*/
struct DCTStatStruc { /* A per Node structure*/
/* DCTStatStruct_F - start */
u8 Node_ID; /* Node ID of current controller*/
u8 ErrCode; /* Current error condition of Node
0= no error
1= Variance Error, DCT is running but not in an optimal configuration.
2= Stop Error, DCT is NOT running
3= Fatal Error, DCT/MCT initialization has been halted.*/
u32 ErrStatus; /* Error Status bit Field */
u32 Status; /* Status bit Field*/
u8 DIMMAddr[8]; /* SPD address of DIMM controlled by MA0_CS_L[0,1]*/
/* SPD address of..MB0_CS_L[0,1]*/
/* SPD address of..MA1_CS_L[0,1]*/
/* SPD address of..MB1_CS_L[0,1]*/
/* SPD address of..MA2_CS_L[0,1]*/
/* SPD address of..MB2_CS_L[0,1]*/
/* SPD address of..MA3_CS_L[0,1]*/
/* SPD address of..MB3_CS_L[0,1]*/
u16 DIMMPresent; /*For each bit n 0..7, 1=DIMM n is present.
DIMM# Select Signal
0 MA0_CS_L[0,1]
1 MB0_CS_L[0,1]
2 MA1_CS_L[0,1]
3 MB1_CS_L[0,1]
4 MA2_CS_L[0,1]
5 MB2_CS_L[0,1]
6 MA3_CS_L[0,1]
7 MB3_CS_L[0,1]*/
u16 DIMMValid; /* For each bit n 0..7, 1=DIMM n is valid and is/will be configured*/
u16 DIMMMismatch; /* For each bit n 0..7, 1=DIMM n is mismatched, channel B is always considered the mismatch */
u16 DIMMSPDCSE; /* For each bit n 0..7, 1=DIMM n SPD checksum error*/
u16 DimmECCPresent; /* For each bit n 0..7, 1=DIMM n is ECC capable.*/
u16 DimmPARPresent; /* For each bit n 0..7, 1=DIMM n is ADR/CMD Parity capable.*/
u16 Dimmx4Present; /* For each bit n 0..7, 1=DIMM n contains x4 data devices.*/
u16 Dimmx8Present; /* For each bit n 0..7, 1=DIMM n contains x8 data devices.*/
u16 Dimmx16Present; /* For each bit n 0..7, 1=DIMM n contains x16 data devices.*/
u16 DIMM2Kpage; /* For each bit n 0..7, 1=DIMM n contains 1K page devices.*/
u8 MAload[2]; /* Number of devices loading MAA bus*/
/* Number of devices loading MAB bus*/
u8 MAdimms[2]; /*Number of DIMMs loading CH A*/
/* Number of DIMMs loading CH B*/
u8 DATAload[2]; /*Number of ranks loading CH A DATA*/
/* Number of ranks loading CH B DATA*/
u8 DIMMAutoSpeed; /*Max valid Mfg. Speed of DIMMs
1=200MHz
2=266MHz
3=333MHz
4=400MHz
5=533MHz*/
u8 DIMMCASL; /* Min valid Mfg. CL bitfield
0=2.0
1=3.0
2=4.0
3=5.0
4=6.0 */
u16 DIMMTrcd; /* Minimax Trcd*40 (ns) of DIMMs*/
u16 DIMMTrp; /* Minimax Trp*40 (ns) of DIMMs*/
u16 DIMMTrtp; /* Minimax Trtp*40 (ns) of DIMMs*/
u16 DIMMTras; /* Minimax Tras*40 (ns) of DIMMs*/
u16 DIMMTrc; /* Minimax Trc*40 (ns) of DIMMs*/
u16 DIMMTwr; /* Minimax Twr*40 (ns) of DIMMs*/
u16 DIMMTrrd; /* Minimax Trrd*40 (ns) of DIMMs*/
u16 DIMMTwtr; /* Minimax Twtr*40 (ns) of DIMMs*/
u8 Speed; /* Bus Speed (to set Controller)
1=200MHz
2=266MHz
3=333MHz
4=400MHz */
u8 CASL; /* CAS latency DCT setting
0=2.0
1=3.0
2=4.0
3=5.0
4=6.0 */
u8 Trcd; /* DCT Trcd (busclocks) */
u8 Trp; /* DCT Trp (busclocks) */
u8 Trtp; /* DCT Trtp (busclocks) */
u8 Tras; /* DCT Tras (busclocks) */
u8 Trc; /* DCT Trc (busclocks) */
u8 Twr; /* DCT Twr (busclocks) */
u8 Trrd; /* DCT Trrd (busclocks) */
u8 Twtr; /* DCT Twtr (busclocks) */
u8 Trfc[4]; /* DCT Logical DIMM0 Trfc
0=75ns (for 256Mb devs)
1=105ns (for 512Mb devs)
2=127.5ns (for 1Gb devs)
3=195ns (for 2Gb devs)
4=327.5ns (for 4Gb devs) */
/* DCT Logical DIMM1 Trfc (see Trfc0 for format) */
/* DCT Logical DIMM2 Trfc (see Trfc0 for format) */
/* DCT Logical DIMM3 Trfc (see Trfc0 for format) */
u16 CSPresent; /* For each bit n 0..7, 1=Chip-select n is present */
u16 CSTestFail; /* For each bit n 0..7, 1=Chip-select n is present but disabled */
u32 DCTSysBase; /* BASE[39:8] (system address) of this Node's DCTs. */
u32 DCTHoleBase; /* If not zero, BASE[39:8] (system address) of dram hole for HW remapping. Dram hole exists on this Node's DCTs. */
u32 DCTSysLimit; /* LIMIT[39:8] (system address) of this Node's DCTs */
u16 PresetmaxFreq; /* Maximum OEM defined DDR frequency
200=200MHz (DDR400)
266=266MHz (DDR533)
333=333MHz (DDR667)
400=400MHz (DDR800) */
u8 _2Tmode; /* 1T or 2T CMD mode (slow access mode)
1=1T
2=2T */
u8 TrwtTO; /* DCT TrwtTO (busclocks)*/
u8 Twrrd; /* DCT Twrrd (busclocks)*/
u8 Twrwr; /* DCT Twrwr (busclocks)*/
u8 Trdrd; /* DCT Trdrd (busclocks)*/
u32 CH_ODC_CTL[2]; /* Output Driver Strength (see BKDG FN2:Offset 9Ch, index 00h*/
u32 CH_ADDR_TMG[2]; /* Address Bus Timing (see BKDG FN2:Offset 9Ch, index 04h*/
/* Output Driver Strength (see BKDG FN2:Offset 9Ch, index 20h*/
/* Address Bus Timing (see BKDG FN2:Offset 9Ch, index 24h*/
u16 CH_EccDQSLike[2]; /* CHA DQS ECC byte like...*/
u8 CH_EccDQSScale[2]; /* CHA DQS ECC byte scale*/
/* CHA DQS ECC byte like...*/
/* CHA DQS ECC byte scale*/
u8 MaxAsyncLat; /* Max Asynchronous Latency (ns)*/
// NOTE: Not used in Barcelona - u8 CH_D_RCVRDLY[2][4];
/* CHA DIMM 0 - 4 Receiver Enable Delay*/
/* CHB DIMM 0 - 4 Receiver Enable Delay */
// NOTE: Not used in Barcelona - u8 CH_D_B_DQS[2][2][8];
/* CHA Byte 0-7 Write DQS Delay */
/* CHA Byte 0-7 Read DQS Delay */
/* CHB Byte 0-7 Write DQS Delay */
/* CHB Byte 0-7 Read DQS Delay */
u32 PtrPatternBufA; /* Ptr on stack to aligned DQS testing pattern*/
u32 PtrPatternBufB; /* Ptr on stack to aligned DQS testing pattern*/
u8 Channel; /* Current Channel (0= CH A, 1=CH B)*/
u8 ByteLane; /* Current Byte Lane (0..7)*/
u8 Direction; /* Current DQS-DQ training write direction (0=read, 1=write)*/
u8 Pattern; /* Current pattern*/
u8 DQSDelay; /* Current DQS delay value*/
u32 TrainErrors; /* Current Training Errors*/
u32 AMC_TSC_DeltaLo; /* Time Stamp Counter measurement of AMC, Low dword*/
u32 AMC_TSC_DeltaHi; /* Time Stamp Counter measurement of AMC, High dword*/
// NOTE: Not used in Barcelona - u8 CH_D_DIR_MaxMin_B_Dly[2][4][2][2][8];
/* CH A byte lane 0 - 7 minimum filtered window passing DQS delay value*/
/* CH A byte lane 0 - 7 maximum filtered window passing DQS delay value*/
/* CH B byte lane 0 - 7 minimum filtered window passing DQS delay value*/
/* CH B byte lane 0 - 7 maximum filtered window passing DQS delay value*/
/* CH A byte lane 0 - 7 minimum filtered window passing DQS delay value*/
/* CH A byte lane 0 - 7 maximum filtered window passing DQS delay value*/
/* CH B byte lane 0 - 7 minimum filtered window passing DQS delay value*/
/* CH B byte lane 0 - 7 maximum filtered window passing DQS delay value*/
u32 LogicalCPUID; /* The logical CPUID of the node*/
u16 HostBiosSrvc1; /* Word sized general purpose field for use by host BIOS. Scratch space.*/
u32 HostBiosSrvc2; /* Dword sized general purpose field for use by host BIOS. Scratch space.*/
u16 DimmQRPresent; /* QuadRank DIMM present?*/
u16 DimmTrainFail; /* Bitmap showing which dimms failed training*/
u16 CSTrainFail; /* Bitmap showing which chipselects failed training*/
u16 DimmYr06; /* Bitmap indicating which Dimms have a manufactur's year code <= 2006*/
u16 DimmWk2406; /* Bitmap indicating which Dimms have a manufactur's week code <= 24 of 2006 (June)*/
u16 DimmDRPresent; /* Bitmap indicating that Dual Rank Dimms are present*/
u16 DimmPlPresent; /* Bitmap indicating that Planar (1) or Stacked (0) Dimms are present.*/
u16 ChannelTrainFai; /* Bitmap showing the channel information about failed Chip Selects
0 in any bit field indicates Channel 0
1 in any bit field indicates Channel 1 */
u16 CSUsrTestFail; /* Chip selects excluded by user */
/* DCTStatStruct_F - end */
u16 CH_MaxRdLat[2]; /* Max Read Latency (ns) for DCT 0*/
/* Max Read Latency (ns) for DCT 1*/
u8 CH_D_DIR_B_DQS[2][4][2][9]; /* [A/B] [DIMM1-4] [R/W] [DQS] */
/* CHA DIMM0 Byte 0 - 7 and Check Write DQS Delay*/
/* CHA DIMM0 Byte 0 - 7 and Check Read DQS Delay*/
/* CHA DIMM1 Byte 0 - 7 and Check Write DQS Delay*/
/* CHA DIMM1 Byte 0 - 7 and Check Read DQS Delay*/
/* CHB DIMM0 Byte 0 - 7 and Check Write DQS Delay*/
/* CHB DIMM0 Byte 0 - 7 and Check Read DQS Delay*/
/* CHB DIMM1 Byte 0 - 7 and Check Write DQS Delay*/
/* CHB DIMM1 Byte 0 - 7 and Check Read DQS Delay*/
u8 CH_D_B_RCVRDLY[2][4][8]; /* [A/B] [DIMM0-3] [DQS] */
/* CHA DIMM 0 Receiver Enable Delay*/
/* CHA DIMM 1 Receiver Enable Delay*/
/* CHA DIMM 2 Receiver Enable Delay*/
/* CHA DIMM 3 Receiver Enable Delay*/
/* CHB DIMM 0 Receiver Enable Delay*/
/* CHB DIMM 1 Receiver Enable Delay*/
/* CHB DIMM 2 Receiver Enable Delay*/
/* CHB DIMM 3 Receiver Enable Delay*/
u8 CH_D_BC_RCVRDLY[2][4];
/* CHA DIMM 0 - 4 Check Byte Receiver Enable Delay*/
/* CHB DIMM 0 - 4 Check Byte Receiver Enable Delay*/
u8 DIMMValidDCT[2]; /* DIMM# in DCT0*/
/* DIMM# in DCT1*/
u8 MaxDCTs; /* Max number of DCTs in system*/
// NOTE: removed u8 DCT. Use ->dev_ for pci R/W; /*DCT pointer*/
u8 GangedMode; /* Ganged mode enabled, 0 = disabled, 1 = enabled*/
u8 DRPresent; /* Family 10 present flag, 0 = not Fam10, 1 = Fam10*/
u32 NodeSysLimit; /* BASE[39:8],for DCT0+DCT1 system address*/
u8 WrDatGrossH;
u8 DqsRcvEnGrossL;
// NOTE: Not used - u8 NodeSpeed /* Bus Speed (to set Controller)
/* 1=200MHz */
/* 2=266MHz */
/* 3=333MHz */
// NOTE: Not used - u8 NodeCASL /* CAS latency DCT setting
/* 0=2.0 */
/* 1=3.0 */
/* 2=4.0 */
/* 3=5.0 */
/* 4=6.0 */
u8 TrwtWB;
u8 CurrRcvrCHADelay; /* for keep current RcvrEnDly of chA*/
u16 T1000; /* get the T1000 figure (cycle time (ns)*1K)*/
u8 DqsRcvEn_Pass; /* for TrainRcvrEn byte lane pass flag*/
u8 DqsRcvEn_Saved; /* for TrainRcvrEn byte lane saved flag*/
u8 SeedPass1Remainder; /* for Phy assisted DQS receiver enable training*/
/* for second pass - Second pass should never run for Fam10*/
// NOTE: Not used for Barcelona - u8 CH_D_B_RCVRDLY_1[2][4][8]; /* CHA DIMM 0 Receiver Enable Delay*/
/* CHA DIMM 1 Receiver Enable Delay*/
/* CHA DIMM 2 Receiver Enable Delay*/
/* CHA DIMM 3 Receiver Enable Delay*/
/* CHB DIMM 0 Receiver Enable Delay*/
/* CHB DIMM 1 Receiver Enable Delay*/
/* CHB DIMM 2 Receiver Enable Delay*/
/* CHB DIMM 3 Receiver Enable Delay*/
u8 ClToNB_flag; /* is used to restore ClLinesToNbDis bit after memory */
u32 NodeSysBase; /* for channel interleave usage */
/* New for LB Support */
u8 NodePresent;
u32 dev_host;
u32 dev_map;
u32 dev_dct;
u32 dev_nbmisc;
uint8_t DimmRows[MAX_DIMMS_SUPPORTED];
uint8_t DimmCols[MAX_DIMMS_SUPPORTED];
uint8_t DimmRanks[MAX_DIMMS_SUPPORTED];
uint8_t DimmBanks[MAX_DIMMS_SUPPORTED];
uint8_t DimmWidth[MAX_DIMMS_SUPPORTED];
uint8_t DimmRegistered[MAX_DIMMS_SUPPORTED];
uint64_t DimmManufacturerID[MAX_DIMMS_SUPPORTED];
char DimmPartNumber[MAX_DIMMS_SUPPORTED][SPD_PARTN_LENGTH];
uint16_t DimmRevisionNumber[MAX_DIMMS_SUPPORTED];
uint32_t DimmSerialNumber[MAX_DIMMS_SUPPORTED];
} __attribute__((packed));
/*===============================================================================
Local Error Status Codes (DCTStatStruc.ErrCode)
===============================================================================*/
#define SC_RunningOK 0
#define SC_VarianceErr 1 /* Running non-optimally*/
#define SC_StopError 2 /* Not Running*/
#define SC_FatalErr 3 /* Fatal Error, MCTB has exited immediately*/
/*===============================================================================
Local Error Status (DCTStatStruc.ErrStatus[31:0])
===============================================================================*/
#define SB_NoDimms 0
#define SB_DIMMChkSum 1
#define SB_DimmMismatchM 2 /* dimm module type(buffer) mismatch*/
#define SB_DimmMismatchT 3 /* dimm CL/T mismatch*/
#define SB_DimmMismatchO 4 /* dimm organization mismatch (128-bit)*/
#define SB_NoTrcTrfc 5 /* SPD missing Trc or Trfc info*/
#define SB_NoCycTime 6 /* SPD missing byte 23 or 25*/
#define SB_BkIntDis 7 /* Bank interleave requested but not enabled*/
#define SB_DramECCDis 8 /* Dram ECC requested but not enabled*/
#define SB_SpareDis 9 /* Online spare requested but not enabled*/
#define SB_MinimumMode 10 /* Running in Minimum Mode*/
#define SB_NORCVREN 11 /* No DQS Receiver Enable pass window found*/
#define SB_CHA2BRCVREN 12 /* DQS Rcvr En pass window CHA to CH B too large*/
#define SB_SmallRCVR 13 /* DQS Rcvr En pass window too small (far right of dynamic range)*/
#define SB_NODQSPOS 14 /* No DQS-DQ passing positions*/
#define SB_SMALLDQS 15 /* DQS-DQ passing window too small*/
#define SB_DCBKScrubDis 16 /* DCache scrub requested but not enabled */
/*===============================================================================
Local Configuration Status (DCTStatStruc.Status[31:0])
===============================================================================*/
#define SB_Registered 0 /* All DIMMs are Registered*/
#define SB_ECCDIMMs 1 /* All banks ECC capable*/
#define SB_PARDIMMs 2 /* All banks Addr/CMD Parity capable*/
#define SB_DiagClks 3 /* Jedec ALL slots clock enable diag mode*/
#define SB_128bitmode 4 /* DCT in 128-bit mode operation*/
#define SB_64MuxedMode 5 /* DCT in 64-bit mux'ed mode.*/
#define SB_2TMode 6 /* 2T CMD timing mode is enabled.*/
#define SB_SWNodeHole 7 /* Remapping of Node Base on this Node to create a gap.*/
#define SB_HWHole 8 /* Memory Hole created on this Node using HW remapping.*/
#define SB_Over400MHz 9 /* DCT freq >= 400MHz flag*/
#define SB_DQSPos_Pass2 10 /* Using for TrainDQSPos DIMM0/1, when freq>=400MHz*/
#define SB_DQSRcvLimit 11 /* Using for DQSRcvEnTrain to know we have reached to upper bound.*/
#define SB_ExtConfig 12 /* Indicator the default setting for extend PCI configuration support*/
/*===============================================================================
NVRAM/run-time-configurable Items
===============================================================================*/
/*Platform Configuration*/
#define NV_PACK_TYPE 0 /* CPU Package Type (2-bits)
0=NPT L1
1=NPT M2
2=NPT S1*/
#define NV_MAX_NODES 1 /* Number of Nodes/Sockets (4-bits)*/
#define NV_MAX_DIMMS 2 /* Number of DIMM slots for the specified Node ID (4-bits)*/
#define NV_MAX_MEMCLK 3 /* Maximum platform demonstrated Memclock (10-bits)
200=200MHz (DDR400)
266=266MHz (DDR533)
333=333MHz (DDR667)
400=400MHz (DDR800)*/
#define NV_ECC_CAP 4 /* Bus ECC capable (1-bits)
0=Platform not capable
1=Platform is capable*/
#define NV_4RANKType 5 /* Quad Rank DIMM slot type (2-bits)
0=Normal
1=R4 (4-Rank Registered DIMMs in AMD server configuration)
2=S4 (Unbuffered SO-DIMMs)*/
#define NV_BYPMAX 6 /* Value to set DcqBypassMax field (See Function 2, Offset 94h, [27:24] of BKDG for field definition).
4=4 times bypass (normal for non-UMA systems)
7=7 times bypass (normal for UMA systems)*/
#define NV_RDWRQBYP 7 /* Value to set RdWrQByp field (See Function 2, Offset A0h, [3:2] of BKDG for field definition).
2=8 times (normal for non-UMA systems)
3=16 times (normal for UMA systems)*/
/*Dram Timing*/
#define NV_MCTUSRTMGMODE 10 /* User Memclock Mode (2-bits)
0=Auto, no user limit
1=Auto, user limit provided in NV_MemCkVal
2=Manual, user value provided in NV_MemCkVal*/
#define NV_MemCkVal 11 /* Memory Clock Value (2-bits)
0=200MHz
1=266MHz
2=333MHz
3=400MHz*/
/*Dram Configuration*/
#define NV_BankIntlv 20 /* Dram Bank (chip-select) Interleaving (1-bits)
0=disable
1=enable*/
#define NV_AllMemClks 21 /* Turn on All DIMM clocks (1-bits)
0=normal
1=enable all memclocks*/
#define NV_SPDCHK_RESTRT 22 /* SPD Check control bitmap (1-bits)
0=Exit current node init if any DIMM has SPD checksum error
1=Ignore faulty SPD checksums (Note: DIMM cannot be enabled)*/
#define NV_DQSTrainCTL 23 /* DQS Signal Timing Training Control
0=skip DQS training
1=perform DQS training*/
#define NV_NodeIntlv 24 /* Node Memory Interleaving (1-bits)
0=disable
1=enable*/
#define NV_BurstLen32 25 /* BurstLength32 for 64-bit mode (1-bits)
0=disable (normal)
1=enable (4 beat burst when width is 64-bits)*/
/*Dram Power*/
#define NV_CKE_PDEN 30 /* CKE based power down mode (1-bits)
0=disable
1=enable*/
#define NV_CKE_CTL 31 /* CKE based power down control (1-bits)
0=per Channel control
1=per Chip select control*/
#define NV_CLKHZAltVidC3 32 /* Memclock tri-stating during C3 and Alt VID (1-bits)
0=disable
1=enable*/
/*Memory Map/Mgt.*/
#define NV_BottomIO 40 /* Bottom of 32-bit IO space (8-bits)
NV_BottomIO[7:0]=Addr[31:24]*/
#define NV_BottomUMA 41 /* Bottom of shared graphics dram (8-bits)
NV_BottomUMA[7:0]=Addr[31:24]*/
#define NV_MemHole 42 /* Memory Hole Remapping (1-bits)
0=disable
1=enable */
/*ECC*/
#define NV_ECC 50 /* Dram ECC enable*/
#define NV_NBECC 52 /* ECC MCE enable*/
#define NV_ChipKill 53 /* Chip-Kill ECC Mode enable*/
#define NV_ECCRedir 54 /* Dram ECC Redirection enable*/
#define NV_DramBKScrub 55 /* Dram ECC Background Scrubber CTL*/
#define NV_L2BKScrub 56 /* L2 ECC Background Scrubber CTL*/
#define NV_DCBKScrub 57 /* DCache ECC Background Scrubber CTL*/
#define NV_CS_SpareCTL 58 /* Chip Select Spare Control bit 0:
0=disable Spare
1=enable Spare */
/* Chip Select Spare Control bit 1-4:
Reserved, must be zero*/
#define NV_SyncOnUnEccEn 61 /* SyncOnUnEccEn control
0=disable
1=enable*/
#define NV_Unganged 62
#define NV_ChannelIntlv 63 /* Channel Interleaving (3-bits)
xx0b = disable
yy1b = enable with DctSelIntLvAddr set to yyb */
/*===============================================================================
CBMEM storage
===============================================================================*/
struct amdmct_memory_info {
struct MCTStatStruc mct_stat;
struct DCTStatStruc dct_stat[MAX_NODES_SUPPORTED];
uint16_t ecc_enabled;
uint16_t ecc_scrub_rate;
} __attribute__((packed));
u32 Get_NB32(u32 dev, u32 reg);
void Set_NB32(u32 dev, u32 reg, u32 val);
u32 Get_NB32_index(u32 dev, u32 index_reg, u32 index);
void Set_NB32_index(u32 dev, u32 index_reg, u32 index, u32 data);
u32 Get_NB32_index_wait(u32 dev, u32 index_reg, u32 index);
void Set_NB32_index_wait(u32 dev, u32 index_reg, u32 index, u32 data);
u32 OtherTiming_A_D(struct DCTStatStruc *pDCTstat, u32 val);
void mct_ForceAutoPrecharge_D(struct DCTStatStruc *pDCTstat, u32 dct);
u32 Modify_D3CMP(struct DCTStatStruc *pDCTstat, u32 dct, u32 value);
u8 mct_checkNumberOfDqsRcvEn_1Pass(u8 pass);
u32 SetupDqsPattern_1PassA(u8 Pass);
u32 SetupDqsPattern_1PassB(u8 Pass);
u8 mct_Get_Start_RcvrEnDly_1Pass(u8 Pass);
u8 mct_Average_RcvrEnDly_Pass(struct DCTStatStruc *pDCTstat, u8 RcvrEnDly, u8 RcvrEnDlyLimit, u8 Channel, u8 Receiver, u8 Pass);
void CPUMemTyping_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void UMAMemTyping_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
u32 mctGetLogicalCPUID(u32 Node);
u8 ECCInit_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void TrainReceiverEn_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA, u8 Pass);
void mct_TrainDQSPos_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void mctSetEccDQSRcvrEn_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void TrainMaxReadLatency_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void mct_EndDQSTraining_D(struct MCTStatStruc *pMCTstat,struct DCTStatStruc *pDCTstatA);
void mct_SetRcvrEnDly_D(struct DCTStatStruc *pDCTstat, u8 RcvrEnDly, u8 FinalValue, u8 Channel, u8 Receiver, u32 dev, u32 index_reg, u8 Addl_Index, u8 Pass);
void SetEccDQSRcvrEn_D(struct DCTStatStruc *pDCTstat, u8 Channel);
void mctGet_PS_Cfg_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u32 dct);
void InterleaveBanks_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 dct);
void mct_SetDramConfigHi_D(struct DCTStatStruc *pDCTstat, u32 dct, u32 DramConfigHi);
void mct_DramInit_Hw_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 dct);
void SyncSetting(struct DCTStatStruc *pDCTstat);
void mct_SetClToNB_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat);
void mct_SetWbEnhWsbDis_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat);
void mct_TrainRcvrEn_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 Pass);
void mct_EnableDimmEccEn_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 _DisableDramECC);
u32 procOdtWorkaround(struct DCTStatStruc *pDCTstat, u32 dct, u32 val);
void mct_BeforeDramInit_D(struct DCTStatStruc *pDCTstat, u32 dct);
void mctGet_DIMMAddr(struct DCTStatStruc *pDCTstat, u32 node);
void mctSMBhub_Init(u32 node);
int mctRead_SPD(u32 smaddr, u32 reg);
void InterleaveNodes_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void InterleaveChannels_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
void mct_BeforeDQSTrain_Samp_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat);
void StoreDQSDatStrucVal_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 ChipSel);
void phyAssistedMemFnceTraining(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstatA);
u8 mct_SaveRcvEnDly_D_1Pass(struct DCTStatStruc *pDCTstat, u8 pass);
u32 CheckNBCOFAutoPrechg(struct DCTStatStruc *pDCTstat, u32 dct);
u8 mct_AdjustDQSPosDelay_D(struct DCTStatStruc *pDCTstat, u8 dly);
void mct_AdjustScrub_D(struct DCTStatStruc *pDCTstat, u16 *scrub_request);
u8 mct_InitReceiver_D(struct DCTStatStruc *pDCTstat, u8 dct);
void mct_Wait(u32 cycles);
u8 mct_RcvrRankEnabled_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 Channel, u8 ChipSel);
u32 mct_GetRcvrSysAddr_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u8 channel, u8 receiver, u8 *valid);
void mct_Read1LTestPattern_D(struct MCTStatStruc *pMCTstat, struct DCTStatStruc *pDCTstat, u32 addr);
void EarlySampleSupport_D(void);
#endif
|
tidatida/coreboot
|
src/northbridge/amd/amdmct/mct/mct_d.h
|
C
|
gpl-2.0
| 33,492
|
#ifndef _BATTERY_SSB_H
#define _BATTERY_SSB_H
#include <mach/mt_typedefs.h>
#include <mach/battery_meter.h>
// ============================================================
// define
// ============================================================
#define FEATURE_LABEL_CODE 0x4300
#define VOLTAGE_LABEL_CODE 0x4400
#define CURRENT_LABEL_CODE 0x4500
#define TEMPER_LABEL_CODE 0x4600
#define TIMER_LABEL_CODE 0x4700
#define PERCENTAGE_LABEL_CODE 0x4800
#define RESISTOR_LABEL_CODE 0x4900
#define FG_TUNING_LABEL_CODE 0x4a00
#define TR_TABLE_LABEL_CODE 0x4b00
#define PV_TABLE_LABEL_CODE 0x4c00
#define RV_TABLE_LABEL_CODE 0x4d00
#define BATTERY_NODE_CNT 11
// ============================================================
// ENUM
// ============================================================
enum {
T0_NEG_10C,
T1_0C,
T2_25C,
T3_50C,
T_NUM
};
enum {
TALKING_STOP_CHARGE_ENABLE,
LOW_TEMPERATURE_ENABLE,
TEMPERAURE_RECHARGE_ENABLE,
LOW_CHARGE_VOLT_ENABLE,
JEITA_ENABLE,
HIGH_BATTERY_ENABLE,
NOTIFY_CHR_VOLT_HIGH,
NOTIFY_TEMP_HIGH,
NOTIFY_CURRENT_HIGH,
NOTIFY_BAT_VOLT_HIGH,
NOTIFY_CHR_TIME_LONG,
EXT_CHR_SUPPORT_ID,
FEATURE_NUM
};
enum {
WAKEUP_VOLTAGE,
PULL_UP_VOLTAGE,
CHR_STAGE_VOLTAGE,
CHR_THR_VOLTAGE,
TALKING_MODE_RECHARGE_VOLTAGE,
ZERO_PERCENT_VOLTAGE,
JEITA_MODE_CV_VOLTAGE,
JEITA_LINEAR_VOLTAGE,
VOLTAGE_NUM
};
enum {
USB_CONF_CURRENT,
USB_TYPE_CURRENT,
JEITA_CURRENT,
CURRENT_NUM
};
enum {
TEMPER_FIX_TABLE,
TEMPER_PROTECTION,
TEMPER_NUM
};
enum {
ADC_RESISTOR,
FG_METER_RESISTOR,
PULL_RESISTOR,
RESISTOR_NUM
};
enum {
TRACKING_PERCNET,
FG_COMP_PERCENT,
PERCENT_NUM
};
enum {
WAKEUP_TIMER,
TALKING_TIMER,
PERCENT_TRACKING_TIMER,
TIMER_NUM
};
enum {
FUEL_GAUGE_TUNING,
HW_FG_TUNING,
CAPACITY_TUNING,
GAUGE_SELECT,
FG_NUM
};
// ============================================================
// typedef
// ============================================================
typedef struct {
unsigned int label;
unsigned int offset;
} battery_list;
typedef struct {
unsigned int label;
unsigned int para_len;
unsigned int battery_para[10];
} battery_store_type;
typedef struct {
int para_first;
int para_second;
} table_type;
typedef struct {
unsigned int label;
unsigned int len;
table_type mapping_data[80];
} mapping_table_type;
typedef struct {
unsigned int label;
unsigned int para_len;
unsigned int feature_para[FEATURE_NUM];
} feature_enable_type;
typedef struct {
battery_store_type voltage_para[VOLTAGE_NUM];
battery_store_type current_para[CURRENT_NUM];
battery_store_type temperature_para[TEMPER_NUM];
battery_store_type resistor_para[RESISTOR_NUM];
battery_store_type percent_para[PERCENT_NUM];
battery_store_type timer_para[TIMER_NUM];
battery_store_type fg_tuning_para[FG_NUM];
mapping_table_type temperature_resist_table[1];
mapping_table_type percent_volt_table[T_NUM];
mapping_table_type resist_volt_table[T_NUM];
feature_enable_type feature_enable_para[1];
} battery_data_type;
typedef struct {
unsigned int version;
battery_list battery_node[BATTERY_NODE_CNT];
} battery_header;
/* ============================================================ */
/* External Variables */
/* ============================================================ */
extern battery_header battery_hdr;
extern battery_data_type battery_cust_data;
extern unsigned int battery_cust_buf[MAX_BATTERY_PARA_SIZE];
/*wake up voltage {VBAT_NORMAL_WAKEUP, VBAT_LOW_POWER_WAKEUP}*/
extern kal_int32 v_normal_wakeup;
extern kal_int32 v_low_power_wakeup;
/*pull up voltage for NTC temperature calculation*/
extern kal_int32 v_pull_up;
/* Linear Charging Threshold*/
extern kal_int32 v_pre2cc;
extern kal_int32 v_cc2cv;
extern kal_int32 v_recharge;
/* charger error check*/
extern kal_int32 v_chr_max;
extern kal_int32 v_chr_min;
/* stop charging while in talking mode*/
extern kal_int32 v_recharge_at_talking;
/* start 0 percent tracking when reach this value */
extern kal_int32 v_0percent_sync;
/* JEITA parameter */
extern kal_int32 cv_above_pos_60;
extern kal_int32 cv_pos_45_60;
extern kal_int32 cv_pos_10_45;
extern kal_int32 cv_pos_0_10;
extern kal_int32 cv_neg_10_0;
extern kal_int32 cv_below_neg_10;
/* For JEITA Linear Charging only */
extern kal_int32 v_recharge_pos_45_60;
extern kal_int32 v_recharge_pos_10_45;
extern kal_int32 v_recharge_cv_pos_0_10;
extern kal_int32 v_recharge_neg_10_0;
extern kal_int32 cc2cv_pos_45_60;
extern kal_int32 cc2cv_pos_10_45;
extern kal_int32 cc2cv_pos_0_10;
extern kal_int32 cc2cv_neg_10_0;
/* Charging Current Setting */
extern kal_int32 cur_usb_suspend;
extern kal_int32 cur_usb_unconfigured;
extern kal_int32 cur_usb_configured;
/* Charging Current Setting */
extern kal_int32 cur_usb_charger;
extern kal_int32 cur_charging_host;
extern kal_int32 cur_no_std_charger;
extern kal_int32 cur_ac_charger;
extern kal_int32 cur_apple_2_1A;
extern kal_int32 cur_apple_1A;
extern kal_int32 cur_apple_0_5A;
/* For JEITA Linear Charging only */
extern kal_int32 cur_jeita_neg_10_to_0;
extern kal_int32 cur_jeita_pos_0_to_10;
extern kal_int32 cur_jeita_pos_45_to_60;
extern kal_int32 cur_terminate_neg_10;
/* mapping table measured with temperature fixed */
extern kal_int32 t0_zone;
extern kal_int32 t1_zone;
extern kal_int32 t2_zone;
extern kal_int32 t3_zone;
/* Battery Temperature Protection */
extern kal_int32 t_high_discharge_zone;
extern kal_int32 t_high_recharge_zone;
extern kal_int32 t_high_zone;
extern kal_int32 t_high2middle_zone;
extern kal_int32 t_middle2low_zone;
extern kal_int32 t_low_zone;
extern kal_int32 t_low_discharge_zone;
extern kal_int32 t_low_recharge_zone;
extern kal_int32 t_freeze_zone;
extern kal_int32 t_freeze2low_zone;
/* auxadc setting */
extern int g_R_BAT_SENSE;
extern int g_R_I_SENSE;
extern int g_R_CHARGER_1;
extern int g_R_CHARGER_2;
extern int g_R_CUST_SENSE;
/* fuel gauge resistor value */
extern int g_R_FG_VALUE;
extern int g_R_FG_METER;
/* NTC resistor value for pull up & down */
extern int g_R_PULL_UP;
extern int g_R_PULL_DOWN;
/* N percent tracking algorithm */
extern kal_int32 g_tracking_point;
/* Power on capacitydecision making setting */
extern kal_int32 poweron_hw_percent_diff;
extern kal_int32 poweron_lowest_percent;
extern kal_int32 poweron_max_percent;
extern kal_int32 poweron_sw_percent_diff;
/* Dynamic change wake up period of battery thread when suspend (sec) */
extern kal_int32 normal_wakeup_period;
extern kal_int32 low_power_wakeup_period;
extern kal_int32 close_poweroff_wakeup_period;
/* stop charging while in talking mode */
extern kal_int32 talking_sync_time;
/* Tracking TIME (sec) */
extern kal_int32 t_100percent_sync;
extern kal_int32 t_npercent_sync;
extern kal_int32 t_real_percent_sync;
extern kal_int32 t_jeita_sync;
/* Fuel gague relative setting */
extern kal_int32 aging_tuning_value;
extern kal_int32 oam_d5;
extern kal_int32 car_tune_value;
/* HW Fuel Gauge specific setting */
extern kal_int32 current_detect_r_fg;
extern kal_int32 min_error_offset;
extern kal_int32 fg_vbat_avg_size;
extern kal_int32 cust_r_fg_offset;
extern kal_int32 ocv_board_compesate;
/* Qmax for battery */
extern kal_int32 qmax_pos_50;
extern kal_int32 qmax_pos_25;
extern kal_int32 qmax_0;
extern kal_int32 qmax_neg_10;
extern kal_int32 qmax_pos_50_hcur;
extern kal_int32 qmax_pos_25_hcur;
extern kal_int32 qmax_0_hcur;
extern kal_int32 qmax_neg_10_hcur;
/* fuel gauge algorithm select by hw design {0: SOC_BY_AUXADC, 1: SOC_BY_HW_FG, 2:SOC_BY_SW_FG} */
extern kal_int32 fg_soc_method;
extern BATT_TEMPERATURE *batt_temperature_table;
extern BATTERY_PROFILE_STRUC **pv_profile_temperature;
extern R_PROFILE_STRUC **rv_profile_temperature;
extern BATTERY_PROFILE_STRUC *pv_empty_profile;
extern R_PROFILE_STRUC *rv_empty_profile;
/* feature option enable */
extern kal_uint32 talking_stop_charging_enable;
extern kal_uint32 low_temperature_protect_enable;
extern kal_uint32 temperature_recharge_enable;
extern kal_uint32 low_charge_volt_protect_enable;
extern kal_uint32 jeita_enable;
extern kal_uint32 high_battery_volt_enable;
extern kal_uint32 notify_chr_volt_high_enable;
extern kal_uint32 notify_temperature_high_enable;
extern kal_uint32 notify_current_high_enable;
extern kal_uint32 notify_bat_volt_enable;
extern kal_uint32 notify_chr_time_enable;
extern kal_uint32 ext_chr_ic_id;
/* others */
extern kal_uint32 temperature_table_len;
extern kal_uint32 pv_len;
extern kal_uint32 rv_len;
extern kal_uint32 ext_chr_id_done;
/* ============================================================ */
/* External function */
/* ============================================================ */
extern kal_int32 batmet_para_init(void);
extern void parse_sub_para_buf(feature_enable_type *feature_data, battery_store_type *store_data,
mapping_table_type *table_data, unsigned int *buf, unsigned int type, unsigned int label_code, unsigned int num);
extern int parsing_battery_init_para(U32 label_code);
#endif /* #ifndef _BATTERY_METER_H */
|
profglavcho/tesr1
|
include/mach/battery_ssb.h
|
C
|
gpl-2.0
| 8,983
|
//========================================================================
//
// pdfinfo.cc
//
// Copyright 1998-2003 Glyph & Cog, LLC
//
//========================================================================
//========================================================================
//
// Modified under the Poppler project - http://poppler.freedesktop.org
//
// All changes made under the Poppler project to this file are licensed
// under GPL version 2 or later
//
// Copyright (C) 2006 Dom Lachowicz <cinamod@hotmail.com>
// Copyright (C) 2007-2008 Albert Astals Cid <aacid@kde.org>
//
// To see a description of the changes please see the Changelog file that
// came with your tarball or type make ChangeLog if you are building from git
//
//========================================================================
#include "config.h"
#include <poppler-config.h>
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <time.h>
#include <math.h>
#include "parseargs.h"
#include "printencodings.h"
#include "goo/GooString.h"
#include "goo/gmem.h"
#include "GlobalParams.h"
#include "Object.h"
#include "Stream.h"
#include "Array.h"
#include "Dict.h"
#include "XRef.h"
#include "Catalog.h"
#include "Page.h"
#include "PDFDoc.h"
#include "CharTypes.h"
#include "UnicodeMap.h"
#include "PDFDocEncoding.h"
#include "Error.h"
#include "DateInfo.h"
static void printInfoString(Dict *infoDict, char *key, char *text,
UnicodeMap *uMap);
static void printInfoDate(Dict *infoDict, char *key, char *text);
static void printBox(char *text, PDFRectangle *box);
static int firstPage = 1;
static int lastPage = 0;
static GBool printBoxes = gFalse;
static GBool printMetadata = gFalse;
static char textEncName[128] = "";
static char ownerPassword[33] = "\001";
static char userPassword[33] = "\001";
static GBool printVersion = gFalse;
static GBool printHelp = gFalse;
static GBool printEnc = gFalse;
static const ArgDesc argDesc[] = {
{"-f", argInt, &firstPage, 0,
"first page to convert"},
{"-l", argInt, &lastPage, 0,
"last page to convert"},
{"-box", argFlag, &printBoxes, 0,
"print the page bounding boxes"},
{"-meta", argFlag, &printMetadata, 0,
"print the document metadata (XML)"},
{"-enc", argString, textEncName, sizeof(textEncName),
"output text encoding name"},
{"-listenc",argFlag, &printEnc, 0,
"list available encodings"},
{"-opw", argString, ownerPassword, sizeof(ownerPassword),
"owner password (for encrypted files)"},
{"-upw", argString, userPassword, sizeof(userPassword),
"user password (for encrypted files)"},
{"-v", argFlag, &printVersion, 0,
"print copyright and version info"},
{"-h", argFlag, &printHelp, 0,
"print usage information"},
{"-help", argFlag, &printHelp, 0,
"print usage information"},
{"--help", argFlag, &printHelp, 0,
"print usage information"},
{"-?", argFlag, &printHelp, 0,
"print usage information"},
{NULL}
};
int main(int argc, char *argv[]) {
PDFDoc *doc;
GooString *fileName;
GooString *ownerPW, *userPW;
UnicodeMap *uMap;
Page *page;
Object info;
char buf[256];
double w, h, wISO, hISO;
FILE *f;
GooString *metadata;
GBool ok;
int exitCode;
int pg, i;
GBool multiPage;
exitCode = 99;
// parse args
ok = parseArgs(argDesc, &argc, argv);
if (!ok || (argc != 2 && !printEnc) || printVersion || printHelp) {
fprintf(stderr, "pdfinfo version %s\n", PACKAGE_VERSION);
fprintf(stderr, "%s\n", popplerCopyright);
fprintf(stderr, "%s\n", xpdfCopyright);
if (!printVersion) {
printUsage("pdfinfo", "<PDF-file>", argDesc);
}
goto err0;
}
// read config file
globalParams = new GlobalParams();
if (printEnc) {
printEncodings();
delete globalParams;
goto err0;
}
fileName = new GooString(argv[1]);
if (textEncName[0]) {
globalParams->setTextEncoding(textEncName);
}
// get mapping to output encoding
if (!(uMap = globalParams->getTextEncoding())) {
error(-1, "Couldn't get text encoding");
delete fileName;
goto err1;
}
// open PDF file
if (ownerPassword[0] != '\001') {
ownerPW = new GooString(ownerPassword);
} else {
ownerPW = NULL;
}
if (userPassword[0] != '\001') {
userPW = new GooString(userPassword);
} else {
userPW = NULL;
}
if(fileName->cmp("-") != 0) {
doc = new PDFDoc(fileName, ownerPW, userPW);
} else {
Object obj;
obj.initNull();
doc = new PDFDoc(new FileStream(stdin, 0, gFalse, 0, &obj), ownerPW, userPW);
}
if (userPW) {
delete userPW;
}
if (ownerPW) {
delete ownerPW;
}
if (!doc->isOk()) {
exitCode = 1;
goto err2;
}
// get page range
if (firstPage < 1) {
firstPage = 1;
}
if (lastPage == 0) {
multiPage = gFalse;
lastPage = 1;
} else {
multiPage = gTrue;
}
if (lastPage < 1 || lastPage > doc->getNumPages()) {
lastPage = doc->getNumPages();
}
// print doc info
doc->getDocInfo(&info);
if (info.isDict()) {
printInfoString(info.getDict(), "Title", "Title: ", uMap);
printInfoString(info.getDict(), "Subject", "Subject: ", uMap);
printInfoString(info.getDict(), "Keywords", "Keywords: ", uMap);
printInfoString(info.getDict(), "Author", "Author: ", uMap);
printInfoString(info.getDict(), "Creator", "Creator: ", uMap);
printInfoString(info.getDict(), "Producer", "Producer: ", uMap);
printInfoDate(info.getDict(), "CreationDate", "CreationDate: ");
printInfoDate(info.getDict(), "ModDate", "ModDate: ");
}
info.free();
// print tagging info
printf("Tagged: %s\n",
doc->getStructTreeRoot()->isDict() ? "yes" : "no");
// print page count
printf("Pages: %d\n", doc->getNumPages());
// print encryption info
printf("Encrypted: ");
if (doc->isEncrypted()) {
printf("yes (print:%s copy:%s change:%s addNotes:%s)\n",
doc->okToPrint(gTrue) ? "yes" : "no",
doc->okToCopy(gTrue) ? "yes" : "no",
doc->okToChange(gTrue) ? "yes" : "no",
doc->okToAddNotes(gTrue) ? "yes" : "no");
} else {
printf("no\n");
}
// print page size
for (pg = firstPage; pg <= lastPage; ++pg) {
w = doc->getPageCropWidth(pg);
h = doc->getPageCropHeight(pg);
if (multiPage) {
printf("Page %4d size: %g x %g pts", pg, w, h);
} else {
printf("Page size: %g x %g pts", w, h);
}
if ((fabs(w - 612) < 0.1 && fabs(h - 792) < 0.1) ||
(fabs(w - 792) < 0.1 && fabs(h - 612) < 0.1)) {
printf(" (letter)");
} else {
hISO = sqrt(sqrt(2.0)) * 7200 / 2.54;
wISO = hISO / sqrt(2.0);
for (i = 0; i <= 6; ++i) {
if ((fabs(w - wISO) < 1 && fabs(h - hISO) < 1) ||
(fabs(w - hISO) < 1 && fabs(h - wISO) < 1)) {
printf(" (A%d)", i);
break;
}
hISO = wISO;
wISO /= sqrt(2.0);
}
}
printf("\n");
}
// print the boxes
if (printBoxes) {
if (multiPage) {
for (pg = firstPage; pg <= lastPage; ++pg) {
page = doc->getCatalog()->getPage(pg);
sprintf(buf, "Page %4d MediaBox: ", pg);
printBox(buf, page->getMediaBox());
sprintf(buf, "Page %4d CropBox: ", pg);
printBox(buf, page->getCropBox());
sprintf(buf, "Page %4d BleedBox: ", pg);
printBox(buf, page->getBleedBox());
sprintf(buf, "Page %4d TrimBox: ", pg);
printBox(buf, page->getTrimBox());
sprintf(buf, "Page %4d ArtBox: ", pg);
printBox(buf, page->getArtBox());
}
} else {
page = doc->getCatalog()->getPage(firstPage);
printBox("MediaBox: ", page->getMediaBox());
printBox("CropBox: ", page->getCropBox());
printBox("BleedBox: ", page->getBleedBox());
printBox("TrimBox: ", page->getTrimBox());
printBox("ArtBox: ", page->getArtBox());
}
}
// print file size
#ifdef VMS
f = fopen(fileName->getCString(), "rb", "ctx=stm");
#else
f = fopen(fileName->getCString(), "rb");
#endif
if (f) {
#if HAVE_FSEEKO
fseeko(f, 0, SEEK_END);
printf("File size: %u bytes\n", (Guint)ftello(f));
#elif HAVE_FSEEK64
fseek64(f, 0, SEEK_END);
printf("File size: %u bytes\n", (Guint)ftell64(f));
#else
fseek(f, 0, SEEK_END);
printf("File size: %d bytes\n", (int)ftell(f));
#endif
fclose(f);
}
// print linearization info
printf("Optimized: %s\n", doc->isLinearized() ? "yes" : "no");
// print PDF version
printf("PDF version: %.1f\n", doc->getPDFVersion());
// print the metadata
if (printMetadata && (metadata = doc->readMetadata())) {
fputs("Metadata:\n", stdout);
fputs(metadata->getCString(), stdout);
fputc('\n', stdout);
delete metadata;
}
exitCode = 0;
// clean up
err2:
uMap->decRefCnt();
delete doc;
err1:
delete globalParams;
err0:
// check for memory leaks
Object::memCheck(stderr);
gMemReport(stderr);
return exitCode;
}
static void printInfoString(Dict *infoDict, char *key, char *text,
UnicodeMap *uMap) {
Object obj;
GooString *s1;
GBool isUnicode;
Unicode u;
char buf[8];
int i, n;
if (infoDict->lookup(key, &obj)->isString()) {
fputs(text, stdout);
s1 = obj.getString();
if ((s1->getChar(0) & 0xff) == 0xfe &&
(s1->getChar(1) & 0xff) == 0xff) {
isUnicode = gTrue;
i = 2;
} else {
isUnicode = gFalse;
i = 0;
}
while (i < obj.getString()->getLength()) {
if (isUnicode) {
u = ((s1->getChar(i) & 0xff) << 8) |
(s1->getChar(i+1) & 0xff);
i += 2;
} else {
u = pdfDocEncoding[s1->getChar(i) & 0xff];
++i;
}
n = uMap->mapUnicode(u, buf, sizeof(buf));
fwrite(buf, 1, n, stdout);
}
fputc('\n', stdout);
}
obj.free();
}
static void printInfoDate(Dict *infoDict, char *key, char *text) {
Object obj;
char *s;
int year, mon, day, hour, min, sec, tz_hour, tz_minute;
char tz;
struct tm tmStruct;
char buf[256];
if (infoDict->lookup(key, &obj)->isString()) {
fputs(text, stdout);
s = obj.getString()->getCString();
// TODO do something with the timezone info
if ( parseDateString( s, &year, &mon, &day, &hour, &min, &sec, &tz, &tz_hour, &tz_minute ) ) {
tmStruct.tm_year = year - 1900;
tmStruct.tm_mon = mon - 1;
tmStruct.tm_mday = day;
tmStruct.tm_hour = hour;
tmStruct.tm_min = min;
tmStruct.tm_sec = sec;
tmStruct.tm_wday = -1;
tmStruct.tm_yday = -1;
tmStruct.tm_isdst = -1;
// compute the tm_wday and tm_yday fields
if (mktime(&tmStruct) != (time_t)-1 &&
strftime(buf, sizeof(buf), "%c", &tmStruct)) {
fputs(buf, stdout);
} else {
fputs(s, stdout);
}
} else {
fputs(s, stdout);
}
fputc('\n', stdout);
}
obj.free();
}
static void printBox(char *text, PDFRectangle *box) {
printf("%s%8.2f %8.2f %8.2f %8.2f\n",
text, box->x1, box->y1, box->x2, box->y2);
}
|
internetarchive/poppler-ia
|
utils/pdfinfo.cc
|
C++
|
gpl-2.0
| 11,091
|
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.tablet;
import android.app.ActivityManager;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.RemoteException;
import android.util.AttributeSet;
import android.util.Slog;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import com.android.systemui.R;
public class CompatModePanel extends FrameLayout implements StatusBarPanel,
View.OnClickListener {
private static final boolean DEBUG = TabletStatusBar.DEBUG;
private static final String TAG = "CompatModePanel";
private ActivityManager mAM;
private boolean mAttached = false;
private Context mContext;
private RadioButton mOnButton, mOffButton;
private View mTrigger;
// private InputMethodButton mInputMethodSwitchButton;
public CompatModePanel(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
mAM = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
}
@Override
public void onFinishInflate() {
mOnButton = (RadioButton) findViewById(R.id.compat_mode_on_radio);
mOffButton = (RadioButton) findViewById(R.id.compat_mode_off_radio);
mOnButton.setOnClickListener(this);
mOffButton.setOnClickListener(this);
refresh();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
if (mAttached) {
mAttached = false;
}
}
@Override
protected void onAttachedToWindow() {
super.onAttachedToWindow();
if (!mAttached) {
mAttached = true;
}
}
@Override
public void onClick(View v) {
if (v == mOnButton) {
mAM.setFrontActivityScreenCompatMode(ActivityManager.COMPAT_MODE_ENABLED);
} else if (v == mOffButton) {
mAM.setFrontActivityScreenCompatMode(ActivityManager.COMPAT_MODE_DISABLED);
}
}
@Override
public boolean isInContentArea(int x, int y) {
return false;
}
@Override
public boolean dispatchHoverEvent(MotionEvent event) {
// Ignore hover events outside of this panel bounds since such events
// generate spurious accessibility events with the panel content when
// tapping outside of it, thus confusing the user.
final int x = (int) event.getX();
final int y = (int) event.getY();
if (x >= 0 && x < getWidth() && y >= 0 && y < getHeight()) {
return super.dispatchHoverEvent(event);
}
return true;
}
public void setTrigger(View v) {
mTrigger = v;
}
public void openPanel() {
setVisibility(View.VISIBLE);
if (mTrigger != null) mTrigger.setSelected(true);
refresh();
}
public void closePanel() {
setVisibility(View.GONE);
if (mTrigger != null) mTrigger.setSelected(false);
}
private void refresh() {
int mode = mAM.getFrontActivityScreenCompatMode();
if (mode == ActivityManager.COMPAT_MODE_ALWAYS
|| mode == ActivityManager.COMPAT_MODE_NEVER) {
// No longer have something to switch.
closePanel();
return;
}
final boolean on = (mode == ActivityManager.COMPAT_MODE_ENABLED);
mOnButton.setChecked(on);
mOffButton.setChecked(!on);
}
}
|
rex-xxx/mt6572_x201
|
frameworks/base/packages/SystemUI/src/com/android/systemui/statusbar/tablet/CompatModePanel.java
|
Java
|
gpl-2.0
| 4,182
|
<?php
/* vim: set expandtab sw=4 ts=4 sts=4: */
/**
* Test for several string operations
*
* @package PhpMyAdmin-test
* @group common.lib-tests
*/
/*
* Include to test.
*/
require_once 'libraries/Util.class.php';
class PMA_stringOperations_test extends PHPUnit_Framework_TestCase
{
/**
* temporary variable for globals array
*/
protected $tmpGlobals;
/**
* temporary variable for session array
*/
protected $tmpSession;
/**
* storing globals and session
*/
public function setUp()
{
global $GLOBALS, $_SESSION;
$this->tmpGlobals = $GLOBALS;
$this->tmpSession = $_SESSION;
}
/**
* data provider for PMA_Util::flipstring test
*
* @return array
*/
public function flipStringDataProvider()
{
return array(
array('test', "t<br />\ne<br />\ns<br />\nt"),
array('te ;st', "t<br />\ne<br />\n <br />\n;<br />\ns<br />\nt")
);
}
/**
* test of changing string from horizontal to vertical orientation
* @dataProvider flipStringDataProvider
*/
public function testFlipString($a, $e)
{
$this->assertEquals($e, PMA_Util::flipstring($a));
}
/**
* data provider for PMA_Util::userDir test
*
* @return array
*/
public function userDirDataProvider()
{
return array(
array('/var/pma_tmp/%u/', "/var/pma_tmp/root/"),
array('/home/%u/pma', "/home/root/pma/")
);
}
/**
* test of generating user dir, globals are defined
* @dataProvider userDirDataProvider
*/
public function testUserDirString($a, $e)
{
$GLOBALS['cfg']['Server']['user'] = 'root';
$this->assertEquals($e, PMA_Util::userDir($a));
}
/**
* data provider for replace binary content test
*
* @return array
*/
public function replaceBinaryContentsDataProvider()
{
return array(
array("\x000", '\00'),
array("\x08\x0a\x0d\x1atest", '\b\n\r\Ztest'),
array("\ntest", '\ntest')
);
}
/**
* replace binary contents test
* @dataProvider replaceBinaryContentsDataProvider
*/
public function testReplaceBinaryContents($a, $e)
{
$this->assertEquals(
$e, PMA_Util::replaceBinaryContents($a)
);
}
/**
* data provider for duplicate first newline test
*
* @return array
*/
public function duplicateFirstNewlineDataProvider()
{
return array(
array('test', 'test'),
array("\r\ntest", "\n\r\ntest"),
array("\ntest", "\ntest"),
array("\n\r\ntest", "\n\r\ntest")
);
}
/**
* duplicate first newline test
* @dataProvider duplicateFirstNewlineDataProvider
*/
public function testDuplicateFirstNewline($a, $e)
{
$this->assertEquals(
$e, PMA_Util::duplicateFirstNewline($a)
);
}
}
?>
|
allen501pc/phpmyadmin
|
test/libraries/common/PMA_stringOperations_test.php
|
PHP
|
gpl-2.0
| 3,067
|
/*
* Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.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, see <http://www.gnu.org/licenses/>.
*/
/*
* Comment: The event with the Living Mojos is not implemented, just is done that when one of the mojos around the boss take damage will make the boss enter in combat!
*/
#include "ScriptMgr.h"
#include "gundrak.h"
#include "InstanceScript.h"
#include "MotionMaster.h"
#include "ScriptedCreature.h"
#include "SpellInfo.h"
enum Texts
{
// Drakkari Elemental
EMOTE_MOJO = 0,
EMOTE_ACTIVATE_ALTAR = 1
};
enum Spells
{
SPELL_EMERGE = 54850,
SPELL_ELEMENTAL_SPAWN_EFFECT = 54888,
SPELL_MOJO_VOLLEY = 54849,
SPELL_SURGE_VISUAL = 54827,
SPELL_MERGE = 54878,
SPELL_MIGHTY_BLOW = 54719,
SPELL_SURGE = 54801,
SPELL_FREEZE_ANIM = 16245,
SPELL_MOJO_PUDDLE = 55627,
SPELL_MOJO_WAVE = 55626,
};
enum ColossusEvents
{
EVENT_MIGHTY_BLOW = 1,
};
enum ColossusActions
{
ACTION_SUMMON_ELEMENTAL = 1,
ACTION_FREEZE_COLOSSUS = 2,
ACTION_UNFREEZE_COLOSSUS = 3,
};
enum ColossusPhases
{
COLOSSUS_PHASE_NORMAL = 1,
COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON = 2,
COLOSSUS_PHASE_SECOND_ELEMENTAL_SUMMON = 3
};
enum ColossusData
{
DATA_COLOSSUS_PHASE = 1,
DATA_INTRO_DONE = 2
};
enum ElementalActions
{
ACTION_RETURN_TO_COLOSSUS = 1
};
enum ElementalEvents
{
EVENT_SURGE = 1
};
class boss_drakkari_colossus : public CreatureScript
{
public:
boss_drakkari_colossus() : CreatureScript("boss_drakkari_colossus") { }
struct boss_drakkari_colossusAI : public BossAI
{
boss_drakkari_colossusAI(Creature* creature) : BossAI(creature, DATA_DRAKKARI_COLOSSUS)
{
Initialize();
me->SetReactState(REACT_PASSIVE);
introDone = false;
}
void Initialize()
{
phase = COLOSSUS_PHASE_NORMAL;
}
void Reset() override
{
_Reset();
if (GetData(DATA_INTRO_DONE))
{
me->SetReactState(REACT_AGGRESSIVE);
me->SetImmuneToPC(false);
me->RemoveAura(SPELL_FREEZE_ANIM);
}
events.ScheduleEvent(EVENT_MIGHTY_BLOW, urand(10000, 30000));
Initialize();
}
void JustEngagedWith(Unit* /*who*/) override
{
_JustEngagedWith();
me->RemoveAura(SPELL_FREEZE_ANIM);
}
void JustDied(Unit* /*killer*/) override
{
_JustDied();
}
void DoAction(int32 action) override
{
switch (action)
{
case ACTION_SUMMON_ELEMENTAL:
DoCast(SPELL_EMERGE);
break;
case ACTION_FREEZE_COLOSSUS:
me->GetMotionMaster()->Clear();
me->GetMotionMaster()->MoveIdle();
me->SetReactState(REACT_PASSIVE);
me->SetImmuneToPC(true);
DoCast(me, SPELL_FREEZE_ANIM);
break;
case ACTION_UNFREEZE_COLOSSUS:
if (me->GetReactState() == REACT_AGGRESSIVE)
return;
me->SetImmuneToPC(false);
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveAura(SPELL_FREEZE_ANIM);
DoZoneInCombat();
break;
}
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) override
{
if (me->IsImmuneToPC())
damage = 0;
if (phase == COLOSSUS_PHASE_NORMAL ||
phase == COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON)
{
if (HealthBelowPct(phase == COLOSSUS_PHASE_NORMAL ? 50 : 5))
{
damage = 0;
phase = (phase == COLOSSUS_PHASE_NORMAL ? COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON : COLOSSUS_PHASE_SECOND_ELEMENTAL_SUMMON);
DoAction(ACTION_FREEZE_COLOSSUS);
DoAction(ACTION_SUMMON_ELEMENTAL);
}
}
}
uint32 GetData(uint32 data) const override
{
if (data == DATA_COLOSSUS_PHASE)
return phase;
else if (data == DATA_INTRO_DONE)
return introDone;
return 0;
}
void SetData(uint32 type, uint32 data) override
{
if (type == DATA_INTRO_DONE)
introDone = data != 0;
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_MIGHTY_BLOW:
DoCastVictim(SPELL_MIGHTY_BLOW);
events.ScheduleEvent(EVENT_MIGHTY_BLOW, urand(5000, 15000));
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
if (me->GetReactState() == REACT_AGGRESSIVE)
DoMeleeAttackIfReady();
}
void JustSummoned(Creature* summon) override
{
DoZoneInCombat(summon);
if (phase == COLOSSUS_PHASE_SECOND_ELEMENTAL_SUMMON)
summon->SetHealth(summon->GetMaxHealth() / 2);
}
private:
uint8 phase;
bool introDone;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetGundrakAI<boss_drakkari_colossusAI>(creature);
}
};
class boss_drakkari_elemental : public CreatureScript
{
public:
boss_drakkari_elemental() : CreatureScript("boss_drakkari_elemental") { }
struct boss_drakkari_elementalAI : public ScriptedAI
{
boss_drakkari_elementalAI(Creature* creature) : ScriptedAI(creature)
{
DoCast(me, SPELL_ELEMENTAL_SPAWN_EFFECT);
instance = creature->GetInstanceScript();
}
void Reset() override
{
events.Reset();
events.ScheduleEvent(EVENT_SURGE, urand(5000, 15000));
me->AddAura(SPELL_MOJO_VOLLEY, me);
}
void JustDied(Unit* killer) override
{
Talk(EMOTE_ACTIVATE_ALTAR);
if (Creature* colossus = instance->GetCreature(DATA_DRAKKARI_COLOSSUS))
Unit::Kill(killer, colossus);
}
void UpdateAI(uint32 diff) override
{
if (!UpdateVictim())
return;
events.Update(diff);
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_SURGE:
DoCast(SPELL_SURGE_VISUAL);
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 1, 0.0f, true))
DoCast(target, SPELL_SURGE);
events.ScheduleEvent(EVENT_SURGE, urand(5000, 15000));
break;
}
if (me->HasUnitState(UNIT_STATE_CASTING))
return;
}
DoMeleeAttackIfReady();
}
void DoAction(int32 action) override
{
switch (action)
{
case ACTION_RETURN_TO_COLOSSUS:
Talk(EMOTE_MOJO);
DoCast(SPELL_SURGE_VISUAL);
if (Creature* colossus = instance->GetCreature(DATA_DRAKKARI_COLOSSUS))
// what if the elemental is more than 80 yards from drakkari colossus ?
DoCast(colossus, SPELL_MERGE, true);
break;
}
}
void DamageTaken(Unit* /*attacker*/, uint32& damage) override
{
if (HealthBelowPct(50))
{
if (Creature* colossus = instance->GetCreature(DATA_DRAKKARI_COLOSSUS))
{
if (colossus->AI()->GetData(DATA_COLOSSUS_PHASE) == COLOSSUS_PHASE_FIRST_ELEMENTAL_SUMMON)
{
damage = 0;
// to prevent spell spaming
if (me->HasUnitState(UNIT_STATE_CHARGING))
return;
// not sure about this, the idea of this code is to prevent bug the elemental
// if it is not in a acceptable distance to cast the charge spell.
/*if (me->GetDistance(colossus) > 80.0f)
{
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
return;
me->GetMotionMaster()->MovePoint(0, colossus->GetPositionX(), colossus->GetPositionY(), colossus->GetPositionZ());
return;
}*/
DoAction(ACTION_RETURN_TO_COLOSSUS);
}
}
}
}
void EnterEvadeMode(EvadeReason /*why*/) override
{
me->DespawnOrUnsummon();
}
void SpellHitTarget(Unit* target, SpellInfo const* spell) override
{
if (spell->Id == SPELL_MERGE)
{
if (Creature* colossus = target->ToCreature())
{
colossus->AI()->DoAction(ACTION_UNFREEZE_COLOSSUS);
me->DespawnOrUnsummon();
}
}
}
private:
EventMap events;
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetGundrakAI<boss_drakkari_elementalAI>(creature);
}
};
class npc_living_mojo : public CreatureScript
{
public:
npc_living_mojo() : CreatureScript("npc_living_mojo") { }
CreatureAI* GetAI(Creature* creature) const override
{
return GetGundrakAI<npc_living_mojoAI>(creature);
}
struct npc_living_mojoAI : public ScriptedAI
{
npc_living_mojoAI(Creature* creature) : ScriptedAI(creature)
{
Initialize();
instance = creature->GetInstanceScript();
}
void Initialize()
{
mojoWaveTimer = 2 * IN_MILLISECONDS;
mojoPuddleTimer = 7 * IN_MILLISECONDS;
}
void Reset() override
{
Initialize();
}
void MoveMojos(Creature* boss)
{
std::list<Creature*> mojosList;
boss->GetCreatureListWithEntryInGrid(mojosList, me->GetEntry(), 12.0f);
if (!mojosList.empty())
{
for (std::list<Creature*>::const_iterator itr = mojosList.begin(); itr != mojosList.end(); ++itr)
{
if (Creature* mojo = *itr)
mojo->GetMotionMaster()->MovePoint(1, boss->GetHomePosition().GetPositionX(), boss->GetHomePosition().GetPositionY(), boss->GetHomePosition().GetPositionZ());
}
}
}
void MovementInform(uint32 type, uint32 id) override
{
if (type != POINT_MOTION_TYPE)
return;
if (id == 1)
{
if (Creature* colossus = instance->GetCreature(DATA_DRAKKARI_COLOSSUS))
{
colossus->AI()->DoAction(ACTION_UNFREEZE_COLOSSUS);
if (!colossus->AI()->GetData(DATA_INTRO_DONE))
colossus->AI()->SetData(DATA_INTRO_DONE, true);
DoZoneInCombat(colossus);
me->DespawnOrUnsummon();
}
}
}
void AttackStart(Unit* attacker) override
{
if (me->GetMotionMaster()->GetCurrentMovementGeneratorType() == POINT_MOTION_TYPE)
return;
// we do this checks to see if the creature is one of the creatures that sorround the boss
if (Creature* colossus = instance->GetCreature(DATA_DRAKKARI_COLOSSUS))
{
Position homePosition = me->GetHomePosition();
float distance = homePosition.GetExactDist(&colossus->GetHomePosition());
if (distance < 12.0f)
{
MoveMojos(colossus);
me->SetReactState(REACT_PASSIVE);
}
else
ScriptedAI::AttackStart(attacker);
}
}
void UpdateAI(uint32 diff) override
{
//Return since we have no target
if (!UpdateVictim())
return;
if (mojoWaveTimer <= diff)
{
DoCastVictim(SPELL_MOJO_WAVE);
mojoWaveTimer = 15*IN_MILLISECONDS;
} else mojoWaveTimer -= diff;
if (mojoPuddleTimer <= diff)
{
DoCastVictim(SPELL_MOJO_PUDDLE);
mojoPuddleTimer = 18*IN_MILLISECONDS;
} else mojoPuddleTimer -= diff;
DoMeleeAttackIfReady();
}
private:
InstanceScript* instance;
uint32 mojoWaveTimer;
uint32 mojoPuddleTimer;
};
};
void AddSC_boss_drakkari_colossus()
{
new boss_drakkari_colossus();
new boss_drakkari_elemental();
new npc_living_mojo();
}
|
tkrokli/TrinityCore
|
src/server/scripts/Northrend/Gundrak/boss_drakkari_colossus.cpp
|
C++
|
gpl-2.0
| 15,618
|
.size 8000
.code@48
jp l1000
.code@100
jp l150
.data@143
c0
.code@150
l150:
ld a, 00
ldff(ff), a
ld a, 30
ldff(00), a
ld a, 01
ldff(4d), a
stop, 00
xor a, a
dec a
ldff(45), a
ld c, 44
ld b, 91
l166:
ldff a, (c)
cmp a, b
jpnz l166
ld hl, fe00
ld d, 10
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 08
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 28
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 28
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 28
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 48
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 48
ld(hl++), a
inc l
inc l
ld a, d
ld(hl++), a
ld a, 48
ld(hl++), a
nop
nop
nop
nop
nop
nop
nop
ld a, 40
ldff(41), a
ld a, 02
ldff(ff), a
xor a, a
ldff(0f), a
ei
ld a, 01
ldff(45), a
ld c, 41
ld b, 03
ld a, 93
ldff(40), a
ld a, 03
ldff(43), a
.code@1000
l1000:
nop
.code@1093
ldff a, (c)
and a, b
ld(ff80), a
jp l7000
.code@2000
l2000:
nop
.code@6ffd
jp l2000
l7000:
ld c, 44
ld b, 91
l7004:
ldff a, (c)
cmp a, b
jpnz l7004
xor a, a
ldff(40), a
ld bc, 7a00
ld hl, 8000
ld d, a0
l7014:
ld a, (bc)
inc bc
ld(hl++), a
dec d
jpnz l7014
ld a, c0
ldff(47), a
ld a, 80
ldff(68), a
ld a, ff
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ldff(69), a
ld a, 00
ldff(69), a
ldff(69), a
ld a, (ff80)
ld(9800), a
xor a, a
ldff(43), a
ld a, 91
ldff(40), a
jp l2000
.data@7a02
7f 7f 41 41 41 41 41 41
41 41 41 41 7f 7f 00 00
08 08 08 08 08 08 08 08
08 08 08 08 08 08 00 00
7f 7f 01 01 01 01 7f 7f
40 40 40 40 7f 7f 00 00
7f 7f 01 01 01 01 3f 3f
01 01 01 01 7f 7f 00 00
41 41 41 41 41 41 7f 7f
01 01 01 01 01 01 00 00
7f 7f 40 40 40 40 7e 7e
01 01 01 01 7e 7e 00 00
7f 7f 40 40 40 40 7f 7f
41 41 41 41 7f 7f 00 00
7f 7f 01 01 02 02 04 04
08 08 10 10 10 10 00 00
3e 3e 41 41 41 41 3e 3e
41 41 41 41 3e 3e 00 00
7f 7f 41 41 41 41 7f 7f
01 01 01 01 7f 7f
|
aliaspider/gambatte-libretro
|
testrunner/hwtests/sprites/space/3overlap8_scx3_m3stat_ds_1_out3.asm
|
Assembly
|
gpl-2.0
| 2,085
|
/*
* *************************************************************************************
* Copyright (C) 2006-2015 EsperTech, Inc. All rights reserved. *
* http://www.espertech.com/esper *
* 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.core.eval;
import com.espertech.esper.client.EventType;
import com.espertech.esper.epl.core.SelectExprProcessor;
import com.espertech.esper.epl.spec.SelectClauseStreamCompiledSpec;
import java.util.List;
public abstract class EvalSelectStreamBase implements SelectExprProcessor {
protected final SelectExprContext selectExprContext;
protected final EventType resultEventType;
protected final List<SelectClauseStreamCompiledSpec> namedStreams;
protected final boolean isUsingWildcard;
public EvalSelectStreamBase(SelectExprContext selectExprContext, EventType resultEventType, List<SelectClauseStreamCompiledSpec> namedStreams, boolean usingWildcard) {
this.selectExprContext = selectExprContext;
this.resultEventType = resultEventType;
this.namedStreams = namedStreams;
this.isUsingWildcard = usingWildcard;
}
public EventType getResultEventType()
{
return resultEventType;
}
public SelectExprContext getSelectExprContext() {
return selectExprContext;
}
}
|
georgenicoll/esper
|
esper/src/main/java/com/espertech/esper/epl/core/eval/EvalSelectStreamBase.java
|
Java
|
gpl-2.0
| 1,813
|
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
namespace Uniframework
{
/// <summary>
/// ¶¯Ì¬ÅÅÐò¹¤¾ßÀà
/// </summary>
[Serializable]
public class DynamicComparer<T> : IComparer<T>
{
/// <summary>
/// ±È½ÏÁ½¸ö¶ÔÏó
/// </summary>
/// <param name="x">The first object to compare.</param>
/// <param name="y">The second object to compare.</param>
/// <returns>
/// Value Condition Less than zero<paramref name="x"/> is less than <paramref name="y"/>.Zero<paramref name="x"/> equals <paramref name="y"/>.Greater than zero<paramref name="x"/> is greater than <paramref name="y"/>.
/// </returns>
public int Compare(T x, T y)
{
Type type = typeof(T);
for (int i = 0; i < sortProperties.Length; i++)
{
PropertyInfo pi = type.GetProperty(sortProperties[i].Name);
object pvalx = pi.GetValue(x, null);
object pvaly = pi.GetValue(y, null);
if (pvalx == null && pvaly == null) return 0;
if (pvalx == null && pvaly != null) return -1;
if (pvalx != null && pvaly == null) return 1;
IComparable xc = (IComparable)pvalx;
int iResult = xc.CompareTo(pvaly);
if (iResult != 0)
{
if (sortProperties[i].Descending)
{
return -iResult;
}
else
{
return iResult;
}
}
}
return 0;
}
/// <summary>
/// Parses the order by.
/// </summary>
/// <param name="orderBy">The order by.</param>
/// <returns></returns>
protected SortProperty[] ParseOrderBy(string orderBy)
{
if (orderBy == null || orderBy.Length == 0)
throw new ArgumentNullException("ÅÅÐò×Ö·û´®²»ÄÜΪ¿Õ");
string[] props = orderBy.Split(',');
SortProperty[] sortProps = new SortProperty[props.Length];
string prop;
bool descending;
for (int i = 0; i < props.Length; i++)
{
descending = false;
prop = props[i].Trim();
if (prop.ToUpper().EndsWith(" DESC"))
{
descending = true;
prop = prop.Substring(0, prop.ToUpper().LastIndexOf(" DESC"));
}
else if (prop.ToUpper().EndsWith(" ASC"))
{
prop = prop.Substring(0, prop.ToUpper().LastIndexOf(" ASC"));
}
prop = prop.Trim();
sortProps[i] = new SortProperty(prop, descending);
}
return sortProps;
}
/// <summary>
/// Checks the sort properties.
/// </summary>
/// <param name="sortProperties">The sort properties.</param>
private void CheckSortProperties(SortProperty[] sortProperties)
{
Type instanceType = typeof(T);
if (!instanceType.IsPublic)
throw new ArgumentException(string.Format("Type \"{0}\" is not public.", typeof(T).FullName));
foreach (SortProperty sProp in sortProperties)
{
PropertyInfo pInfo = instanceType.GetProperty(sProp.Name);
if (pInfo == null)
throw new ArgumentException(string.Format("No public property named \"{0}\" was found.", sProp.Name));
if (!pInfo.CanRead)
throw new ArgumentException(string.Format("The property \"{0}\" is write-only.", sProp.Name));
}
}
/// <summary>
/// Initializes the specified sort properties.
/// </summary>
/// <param name="sortProperties">The sort properties.</param>
private void Initialize(SortProperty[] sortProperties)
{
CheckSortProperties(sortProperties);
this.sortProperties = sortProperties;
}
/// <summary>
/// Initializes a new instance of the <see cref="DynamicComparer<T>"/> class.
/// </summary>
/// <param name="orderBy">The order by.</param>
public DynamicComparer(string orderBy)
{
Initialize(ParseOrderBy(orderBy));
}
private SortProperty[] sortProperties;
}
/// <summary>
///
/// </summary>
public struct SortProperty
{
#region Properties
private string name;
public string Name
{
get
{
return name;
}
set
{
if (String.IsNullOrEmpty(value))
throw new ArgumentException("A property cannot have an empty name.", "value");
name = value.Trim();
}
}
private bool descending;
public bool Descending
{
get
{
return descending;
}
set
{
descending = value;
}
}
public static bool IsComparable(Type valueType)
{
bool isNullable;
return IsComparable(valueType, out isNullable);
}
public static bool IsComparable(Type valueType, out bool isNullable)
{
isNullable = valueType.IsGenericType
&& !valueType.IsGenericTypeDefinition
&& valueType.IsAssignableFrom(typeof(Nullable<>).MakeGenericType(valueType.GetGenericArguments()[0]));
return (typeof(IComparable).IsAssignableFrom(valueType)
|| typeof(IComparable<>).MakeGenericType(valueType).IsAssignableFrom(valueType)
|| isNullable);
}
#region Internals
private Type valueType;
internal Type ValueType
{
get
{
return valueType;
}
private set
{
valueType = value;
if (!IsComparable(value, out isNullable))
{
throw new NotSupportedException("The type \""
+ value.FullName
+ "\" of the property \""
+ this.Name
+ "\" does not implement IComparable, IComparible<T> or is Nullable<T>.");
}
}
}
private MethodInfo get;
internal MethodInfo Get
{
get
{
return get;
}
private set
{
get = value;
}
}
private FieldInfo field;
internal FieldInfo Field
{
get
{
return field;
}
private set
{
field = value;
}
}
private bool isNullable;
internal bool IsNullable
{
get
{
return isNullable;
}
}
#endregion
#endregion
#region Static methods
public static SortProperty[] ParseOrderBy(string orderBy)
{
if (orderBy == null)
throw new ArgumentException("The orderBy clause may not be null.", "orderBy");
string[] properties = orderBy.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
SortProperty[] sortProperties = new SortProperty[properties.Length];
for (int i = 0; i < properties.Length; i++)
{
bool descending = false;
string property = properties[i].Trim();
string[] propertyElements = property.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
if (propertyElements.Length > 1)
{
if (propertyElements[1].Equals("DESC", StringComparison.OrdinalIgnoreCase))
{
descending = true;
}
else if (propertyElements[1].Equals("ASC", StringComparison.OrdinalIgnoreCase))
{
// already set to descending = false;
}
else
{
throw new ArgumentException("Unexpected sort order type \"" + propertyElements[1] + "\" for \"" + propertyElements[0] + "\"", "orderBy");
}
}
sortProperties[i] = new SortProperty(propertyElements[0], descending);
}
return sortProperties;
}
#endregion
#region Constructors
public SortProperty(string propertyName, bool sortDescending)
{
if (String.IsNullOrEmpty(propertyName))
throw new ArgumentException("A property cannot have an empty name.", "propertyName");
name = propertyName;
descending = sortDescending;
// we set these when accessor validated
valueType = null;
get = null;
field = null;
isNullable = false;
}
#endregion
#region Internals
internal static void BindSortProperties(SortProperty[] sortProperties, Type instanceType)
{
BindingFlags flags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic;
if (sortProperties == null)
sortProperties = new SortProperty[0];
if (sortProperties.Length > 0)
{
for (int index = 0; index < sortProperties.Length; index++)
{
string propertyName = sortProperties[index].Name;
PropertyInfo propertyInfo = instanceType.GetProperty(propertyName, BindingFlags.GetProperty | flags);
if (propertyInfo != null)
{
sortProperties[index].ValueType = propertyInfo.PropertyType;
sortProperties[index].Get = propertyInfo.GetGetMethod(true);
}
else
{
FieldInfo fieldInfo = instanceType.GetField(propertyName, BindingFlags.GetField | flags);
if (fieldInfo != null)
{
sortProperties[index].ValueType = fieldInfo.FieldType;
sortProperties[index].Field = fieldInfo;
}
else
{
throw new ArgumentException("No public property or field named \""
+ propertyName
+ "\" was found in type \""
+ instanceType.FullName
+ "\".");
}
}
}
}
else
{
if (!IsComparable(instanceType))
throw new NotSupportedException("The type \""
+ instanceType.FullName
+ "\" does not implement IComparable, IComparable<T> nor is a Nullable<T>.");
}
}
#endregion
}
}
|
tws67/uniframework
|
sources/Uniframework/Common/DynamicComparer.cs
|
C#
|
gpl-2.0
| 11,975
|
require 'test/unit'
require 'securerandom'
require 'tempfile'
# This testcase does NOT aim to test cryptographically strongness and randomness.
class TestSecureRandom < Test::Unit::TestCase
def setup
@it = SecureRandom
end
def test_s_random_bytes
assert_equal(16, @it.random_bytes.size)
assert_equal(Encoding::ASCII_8BIT, @it.random_bytes.encoding)
65.times do |idx|
assert_equal(idx, @it.random_bytes(idx).size)
end
end
# This test took 2 minutes on my machine.
# And 65536 times loop could not be enough for forcing PID recycle.
if false
def test_s_random_bytes_is_fork_safe
begin
require 'openssl'
rescue LoadError
return
end
SecureRandom.random_bytes(8)
pid, v1 = forking_random_bytes
assert(check_forking_random_bytes(pid, v1), 'Process ID not recycled?')
end
def forking_random_bytes
r, w = IO.pipe
pid = fork {
r.close
w.write SecureRandom.random_bytes(8)
w.close
}
w.close
v = r.read(8)
r.close
Process.waitpid2(pid)
[pid, v]
end
def check_forking_random_bytes(target_pid, target)
65536.times do
pid = fork {
if $$ == target_pid
v2 = SecureRandom.random_bytes(8)
if v2 == target
exit(1)
else
exit(2)
end
end
exit(3)
}
pid, status = Process.waitpid2(pid)
case status.exitstatus
when 1
raise 'returned same sequence for same PID'
when 2
return true
end
end
false # not recycled?
end
end
def test_s_random_bytes_without_openssl
begin
require 'openssl'
rescue LoadError
return
end
begin
load_path = $LOAD_PATH.dup
loaded_features = $LOADED_FEATURES.dup
openssl = Object.instance_eval { remove_const(:OpenSSL) }
remove_feature('securerandom.rb')
remove_feature('openssl.rb')
Dir.mktmpdir do |dir|
open(File.join(dir, 'openssl.rb'), 'w') { |f|
f << 'raise LoadError'
}
$LOAD_PATH.unshift(dir)
v = $VERBOSE
begin
$VERBOSE = false
require 'securerandom'
ensure
$VERBOSE = v
end
test_s_random_bytes
end
ensure
$LOADED_FEATURES.replace(loaded_features)
$LOAD_PATH.replace(load_path)
Object.const_set(:OpenSSL, openssl)
end
end
def test_s_hex
assert_equal(16 * 2, @it.hex.size)
33.times do |idx|
assert_equal(idx * 2, @it.hex(idx).size)
assert_equal(idx, @it.hex(idx).gsub(/(..)/) { [$1].pack('H*') }.size)
end
end
def test_hex_encoding
assert_equal(Encoding::US_ASCII, @it.hex.encoding)
end
def test_s_base64
assert_equal(16, @it.base64.unpack('m*')[0].size)
17.times do |idx|
assert_equal(idx, @it.base64(idx).unpack('m*')[0].size)
end
end
def test_s_urlsafe_base64
safe = /[\n+\/]/
65.times do |idx|
assert_not_match(safe, @it.urlsafe_base64(idx))
end
# base64 can include unsafe byte
10001.times do |idx|
return if safe =~ @it.base64(idx)
end
flunk
end
def test_s_random_number_float
101.times do
v = @it.random_number
assert(0.0 <= v && v < 1.0)
end
end
def test_s_random_number_float_by_zero
101.times do
v = @it.random_number(0)
assert(0.0 <= v && v < 1.0)
end
end
def test_s_random_number_int
101.times do |idx|
next if idx.zero?
v = @it.random_number(idx)
assert(0 <= v && v < idx)
end
end
def test_uuid
uuid = @it.uuid
assert_equal(36, uuid.size)
uuid.unpack('a8xa4xa4xa4xa12').each do |e|
assert_match(/^[0-9a-f]+$/, e)
end
end
def protect
begin
yield
rescue NotImplementedError
# ignore
end
end
def remove_feature(basename)
$LOADED_FEATURES.delete_if { |path|
if File.basename(path) == basename
$LOAD_PATH.any? { |dir|
File.exists?(File.join(dir, basename))
}
end
}
end
end
|
atmark-techno/atmark-dist
|
user/ruby/ruby-2.1.2/test/test_securerandom.rb
|
Ruby
|
gpl-2.0
| 4,079
|
/* Misfit Model 3D
*
* Copyright (c) 2004-2007 Kevin Worcester
*
* 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.
*
* See the COPYING file for full license text.
*/
#include "backgroundwin.h"
#include "backgroundselect.h"
#include "model.h"
#include "log.h"
#include "decalmgr.h"
#include "textureframe.h"
#include "helpwin.h"
#include <QtGui/QPushButton>
#include <QtGui/QLayout>
#include <QtGui/QTabWidget>
#include <QtGui/QHBoxLayout>
#include <QtGui/QShortcut>
#include <stdlib.h>
using std::list;
using std::map;
BackgroundWin::BackgroundWin( Model * model, QWidget * parent )
: QDialog( parent ),
m_model( model )
{
setAttribute( Qt::WA_DeleteOnClose );
setupUi( this );
setModal( true );
for ( unsigned t = 0; t < 6; t++ )
{
QWidget * p = m_tabs->widget( t );
QHBoxLayout * l = new QHBoxLayout( p );
m_bgSelect[t] = new BackgroundSelect( m_model, t, p );
l->addWidget( m_bgSelect[t] );
}
QShortcut * help = new QShortcut( QKeySequence( tr("F1", "Help Shortcut")), this );
connect( help, SIGNAL(activated()), this, SLOT(helpNowEvent()) );
}
BackgroundWin::~BackgroundWin()
{
}
void BackgroundWin::helpNowEvent()
{
HelpWin * win = new HelpWin( "olh_backgroundwin.html", true );
win->show();
}
void BackgroundWin::selectedPageEvent( const QString & str )
{
QWidget * widget = m_tabs->currentWidget();
widget->repaint();
}
void BackgroundWin::accept()
{
m_model->operationComplete( tr( "Background Image", "operation complete" ).toUtf8() );
QDialog::accept();
}
void BackgroundWin::reject()
{
m_model->undoCurrent();
DecalManager::getInstance()->modelUpdated( m_model );
QDialog::reject();
}
|
icebreaker/mm3d
|
src/implui/backgroundwin.cc
|
C++
|
gpl-2.0
| 2,385
|
/******************************************************************************
* Product: Adempiere ERP & CRM Smart Business Solution *
* Copyright (C) 1999-2007 ComPiere, Inc. All Rights Reserved. *
* This program is free software, you can redistribute it and/or modify it *
* under the terms version 2 of the GNU General Public License as published *
* by the Free Software Foundation. This program is distributed in the hope *
* that it will be useful, but WITHOUT ANY WARRANTY, without even the implied *
* warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *
* See the GNU General Public License for more details. *
* You should have received a copy of the GNU General Public License along *
* with this program, if not, write to the Free Software Foundation, Inc., *
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. *
* For the text or an alternative of this public license, you may reach us *
* ComPiere, Inc., 2620 Augustine Dr. #245, Santa Clara, CA 95054, USA *
* or via info@compiere.org or http://www.compiere.org/license.html *
*****************************************************************************/
package org.compiere.model;
import java.math.BigDecimal;
import java.sql.Timestamp;
import org.compiere.util.KeyNamePair;
/** Generated Interface for A_Depreciation_Entry
* @author Adempiere (generated)
* @version Release 3.8.0
*/
public interface I_A_Depreciation_Entry
{
/** TableName=A_Depreciation_Entry */
public static final String Table_Name = "A_Depreciation_Entry";
/** AD_Table_ID=53121 */
public static final int Table_ID = MTable.getTable_ID(Table_Name);
KeyNamePair Model = new KeyNamePair(Table_ID, Table_Name);
/** AccessLevel = 3 - Client - Org
*/
BigDecimal accessLevel = BigDecimal.valueOf(3);
/** Load Meta Data */
/** Column name AD_Client_ID */
public static final String COLUMNNAME_AD_Client_ID = "AD_Client_ID";
/** Get Client.
* Client/Tenant for this installation.
*/
public int getAD_Client_ID();
/** Column name AD_Org_ID */
public static final String COLUMNNAME_AD_Org_ID = "AD_Org_ID";
/** Set Organization.
* Organizational entity within client
*/
public void setAD_Org_ID (int AD_Org_ID);
/** Get Organization.
* Organizational entity within client
*/
public int getAD_Org_ID();
/** Column name A_Depreciation_Entry_ID */
public static final String COLUMNNAME_A_Depreciation_Entry_ID = "A_Depreciation_Entry_ID";
/** Set Depreciation Entry */
public void setA_Depreciation_Entry_ID (int A_Depreciation_Entry_ID);
/** Get Depreciation Entry */
public int getA_Depreciation_Entry_ID();
/** Column name A_Entry_Type */
public static final String COLUMNNAME_A_Entry_Type = "A_Entry_Type";
/** Set Entry Type */
public void setA_Entry_Type (String A_Entry_Type);
/** Get Entry Type */
public String getA_Entry_Type();
/** Column name C_AcctSchema_ID */
public static final String COLUMNNAME_C_AcctSchema_ID = "C_AcctSchema_ID";
/** Set Accounting Schema.
* Rules for accounting
*/
public void setC_AcctSchema_ID (int C_AcctSchema_ID);
/** Get Accounting Schema.
* Rules for accounting
*/
public int getC_AcctSchema_ID();
public org.compiere.model.I_C_AcctSchema getC_AcctSchema() throws RuntimeException;
/** Column name C_Currency_ID */
public static final String COLUMNNAME_C_Currency_ID = "C_Currency_ID";
/** Set Currency.
* The Currency for this record
*/
public void setC_Currency_ID (int C_Currency_ID);
/** Get Currency.
* The Currency for this record
*/
public int getC_Currency_ID();
public org.compiere.model.I_C_Currency getC_Currency() throws RuntimeException;
/** Column name C_DocType_ID */
public static final String COLUMNNAME_C_DocType_ID = "C_DocType_ID";
/** Set Document Type.
* Document type or rules
*/
public void setC_DocType_ID (int C_DocType_ID);
/** Get Document Type.
* Document type or rules
*/
public int getC_DocType_ID();
public org.compiere.model.I_C_DocType getC_DocType() throws RuntimeException;
/** Column name C_Period_ID */
public static final String COLUMNNAME_C_Period_ID = "C_Period_ID";
/** Set Period.
* Period of the Calendar
*/
public void setC_Period_ID (int C_Period_ID);
/** Get Period.
* Period of the Calendar
*/
public int getC_Period_ID();
public org.compiere.model.I_C_Period getC_Period() throws RuntimeException;
/** Column name Created */
public static final String COLUMNNAME_Created = "Created";
/** Get Created.
* Date this record was created
*/
public Timestamp getCreated();
/** Column name CreatedBy */
public static final String COLUMNNAME_CreatedBy = "CreatedBy";
/** Get Created By.
* User who created this records
*/
public int getCreatedBy();
/** Column name DateAcct */
public static final String COLUMNNAME_DateAcct = "DateAcct";
/** Set Account Date.
* Accounting Date
*/
public void setDateAcct (Timestamp DateAcct);
/** Get Account Date.
* Accounting Date
*/
public Timestamp getDateAcct();
/** Column name DateDoc */
public static final String COLUMNNAME_DateDoc = "DateDoc";
/** Set Document Date.
* Date of the Document
*/
public void setDateDoc (Timestamp DateDoc);
/** Get Document Date.
* Date of the Document
*/
public Timestamp getDateDoc();
/** Column name Description */
public static final String COLUMNNAME_Description = "Description";
/** Set Description.
* Optional short description of the record
*/
public void setDescription (String Description);
/** Get Description.
* Optional short description of the record
*/
public String getDescription();
/** Column name DocAction */
public static final String COLUMNNAME_DocAction = "DocAction";
/** Set Document Action.
* The targeted status of the document
*/
public void setDocAction (String DocAction);
/** Get Document Action.
* The targeted status of the document
*/
public String getDocAction();
/** Column name DocStatus */
public static final String COLUMNNAME_DocStatus = "DocStatus";
/** Set Document Status.
* The current status of the document
*/
public void setDocStatus (String DocStatus);
/** Get Document Status.
* The current status of the document
*/
public String getDocStatus();
/** Column name DocumentNo */
public static final String COLUMNNAME_DocumentNo = "DocumentNo";
/** Set Document No.
* Document sequence number of the document
*/
public void setDocumentNo (String DocumentNo);
/** Get Document No.
* Document sequence number of the document
*/
public String getDocumentNo();
/** Column name IsActive */
public static final String COLUMNNAME_IsActive = "IsActive";
/** Set Active.
* The record is active in the system
*/
public void setIsActive (boolean IsActive);
/** Get Active.
* The record is active in the system
*/
public boolean isActive();
/** Column name IsApproved */
public static final String COLUMNNAME_IsApproved = "IsApproved";
/** Set Approved.
* Indicates if this document requires approval
*/
public void setIsApproved (boolean IsApproved);
/** Get Approved.
* Indicates if this document requires approval
*/
public boolean isApproved();
/** Column name Posted */
public static final String COLUMNNAME_Posted = "Posted";
/** Set Posted.
* Posting status
*/
public void setPosted (boolean Posted);
/** Get Posted.
* Posting status
*/
public boolean isPosted();
/** Column name PostingType */
public static final String COLUMNNAME_PostingType = "PostingType";
/** Set PostingType.
* The type of posted amount for the transaction
*/
public void setPostingType (String PostingType);
/** Get PostingType.
* The type of posted amount for the transaction
*/
public String getPostingType();
/** Column name Processed */
public static final String COLUMNNAME_Processed = "Processed";
/** Set Processed.
* The document has been processed
*/
public void setProcessed (boolean Processed);
/** Get Processed.
* The document has been processed
*/
public boolean isProcessed();
/** Column name ProcessedOn */
public static final String COLUMNNAME_ProcessedOn = "ProcessedOn";
/** Set Processed On.
* The date+time (expressed in decimal format) when the document has been processed
*/
public void setProcessedOn (BigDecimal ProcessedOn);
/** Get Processed On.
* The date+time (expressed in decimal format) when the document has been processed
*/
public BigDecimal getProcessedOn();
/** Column name Processing */
public static final String COLUMNNAME_Processing = "Processing";
/** Set Process Now */
public void setProcessing (boolean Processing);
/** Get Process Now */
public boolean isProcessing();
/** Column name Updated */
public static final String COLUMNNAME_Updated = "Updated";
/** Get Updated.
* Date this record was updated
*/
public Timestamp getUpdated();
/** Column name UpdatedBy */
public static final String COLUMNNAME_UpdatedBy = "UpdatedBy";
/** Get Updated By.
* User who updated this records
*/
public int getUpdatedBy();
}
|
erpcya/adempierePOS
|
base/src/org/compiere/model/I_A_Depreciation_Entry.java
|
Java
|
gpl-2.0
| 9,484
|
--闇霊神オブルミラージュ
function c59281822.initial_effect(c)
c:EnableReviveLimit()
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_SPSUMMON_PROC)
e2:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e2:SetRange(LOCATION_HAND)
e2:SetCondition(c59281822.spcon)
c:RegisterEffect(e2)
--to hand
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(59281822,0))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetCountLimit(1,59281822)
e3:SetTarget(c59281822.thtg)
e3:SetOperation(c59281822.thop)
c:RegisterEffect(e3)
--leave
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e4:SetCode(EVENT_LEAVE_FIELD_P)
e4:SetOperation(c59281822.leaveop)
c:RegisterEffect(e4)
end
function c59281822.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 and
Duel.GetMatchingGroupCount(Card.IsAttribute,c:GetControler(),LOCATION_GRAVE,0,nil,ATTRIBUTE_DARK)==5
end
function c59281822.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c59281822.thfilter(c)
return c:IsAttackBelow(1500) and c:IsType(TYPE_MONSTER) and c:IsAbleToHand()
end
function c59281822.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c59281822.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
function c59281822.leaveop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsFacedown() then return end
local effp=e:GetHandler():GetControler()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SKIP_BP)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
if Duel.GetTurnPlayer()==effp then
e1:SetLabel(Duel.GetTurnCount())
e1:SetCondition(c59281822.skipcon)
e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN,2)
else
e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN,1)
end
Duel.RegisterEffect(e1,effp)
end
function c59281822.skipcon(e)
return Duel.GetTurnCount()~=e:GetLabel()
end
|
mercury233/ygopro-scripts
|
c59281822.lua
|
Lua
|
gpl-2.0
| 2,563
|
# This file is autogenerated. Instead of editing this file, please use the
# migrations feature of ActiveRecord to incrementally modify your database, and
# then regenerate this schema definition.
ActiveRecord::Schema.define(:version => 9) do
create_table "double_sti_parent_relationships", :force => true do |t|
t.column "the_bone_type", :string, :default => "", :null => false
t.column "the_bone_id", :integer, :null => false
t.column "parent_type", :string, :default => "", :null => false
t.column "parent_id", :integer, :null => false
end
create_table "double_sti_parents", :force => true do |t|
t.column "name", :string
end
create_table "library_models", :force => true do |t|
t.column "name", :string
end
create_table "organic_substances", :force => true do |t|
t.column "type", :string
end
create_table "single_sti_parent_relationships", :force => true do |t|
t.column "the_bone_type", :string, :default => "", :null => false
t.column "the_bone_id", :integer, :null => false
t.column "single_sti_parent_id", :integer, :null => false
end
create_table "single_sti_parents", :force => true do |t|
t.column "name", :string
end
create_table "sticks", :force => true do |t|
t.column "name", :string
end
create_table "stones", :force => true do |t|
t.column "name", :string
end
end
|
theRocket/saturnaled
|
vendor/gems/has_many_polymorphs-2.12/test/integration/app/db/schema.rb
|
Ruby
|
gpl-2.0
| 1,467
|
/*
* Copyright 2009 Marcin Kościelnicki
*
* 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 COPYRIGHT HOLDER(S) OR AUTHOR(S) 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.
*/
#include <core/gpuobj.h>
#define CP_FLAG_CLEAR 0
#define CP_FLAG_SET 1
#define CP_FLAG_SWAP_DIRECTION ((0 * 32) + 0)
#define CP_FLAG_SWAP_DIRECTION_LOAD 0
#define CP_FLAG_SWAP_DIRECTION_SAVE 1
#define CP_FLAG_UNK01 ((0 * 32) + 1)
#define CP_FLAG_UNK01_CLEAR 0
#define CP_FLAG_UNK01_SET 1
#define CP_FLAG_UNK03 ((0 * 32) + 3)
#define CP_FLAG_UNK03_CLEAR 0
#define CP_FLAG_UNK03_SET 1
#define CP_FLAG_USER_SAVE ((0 * 32) + 5)
#define CP_FLAG_USER_SAVE_NOT_PENDING 0
#define CP_FLAG_USER_SAVE_PENDING 1
#define CP_FLAG_USER_LOAD ((0 * 32) + 6)
#define CP_FLAG_USER_LOAD_NOT_PENDING 0
#define CP_FLAG_USER_LOAD_PENDING 1
#define CP_FLAG_UNK0B ((0 * 32) + 0xb)
#define CP_FLAG_UNK0B_CLEAR 0
#define CP_FLAG_UNK0B_SET 1
#define CP_FLAG_XFER_SWITCH ((0 * 32) + 0xe)
#define CP_FLAG_XFER_SWITCH_DISABLE 0
#define CP_FLAG_XFER_SWITCH_ENABLE 1
#define CP_FLAG_STATE ((0 * 32) + 0x1c)
#define CP_FLAG_STATE_STOPPED 0
#define CP_FLAG_STATE_RUNNING 1
#define CP_FLAG_UNK1D ((0 * 32) + 0x1d)
#define CP_FLAG_UNK1D_CLEAR 0
#define CP_FLAG_UNK1D_SET 1
#define CP_FLAG_UNK20 ((1 * 32) + 0)
#define CP_FLAG_UNK20_CLEAR 0
#define CP_FLAG_UNK20_SET 1
#define CP_FLAG_STATUS ((2 * 32) + 0)
#define CP_FLAG_STATUS_BUSY 0
#define CP_FLAG_STATUS_IDLE 1
#define CP_FLAG_AUTO_SAVE ((2 * 32) + 4)
#define CP_FLAG_AUTO_SAVE_NOT_PENDING 0
#define CP_FLAG_AUTO_SAVE_PENDING 1
#define CP_FLAG_AUTO_LOAD ((2 * 32) + 5)
#define CP_FLAG_AUTO_LOAD_NOT_PENDING 0
#define CP_FLAG_AUTO_LOAD_PENDING 1
#define CP_FLAG_NEWCTX ((2 * 32) + 10)
#define CP_FLAG_NEWCTX_BUSY 0
#define CP_FLAG_NEWCTX_DONE 1
#define CP_FLAG_XFER ((2 * 32) + 11)
#define CP_FLAG_XFER_IDLE 0
#define CP_FLAG_XFER_BUSY 1
#define CP_FLAG_ALWAYS ((2 * 32) + 13)
#define CP_FLAG_ALWAYS_FALSE 0
#define CP_FLAG_ALWAYS_TRUE 1
#define CP_FLAG_INTR ((2 * 32) + 15)
#define CP_FLAG_INTR_NOT_PENDING 0
#define CP_FLAG_INTR_PENDING 1
#define CP_CTX 0x00100000
#define CP_CTX_COUNT 0x000f0000
#define CP_CTX_COUNT_SHIFT 16
#define CP_CTX_REG 0x00003fff
#define CP_LOAD_SR 0x00200000
#define CP_LOAD_SR_VALUE 0x000fffff
#define CP_BRA 0x00400000
#define CP_BRA_IP 0x0001ff00
#define CP_BRA_IP_SHIFT 8
#define CP_BRA_IF_CLEAR 0x00000080
#define CP_BRA_FLAG 0x0000007f
#define CP_WAIT 0x00500000
#define CP_WAIT_SET 0x00000080
#define CP_WAIT_FLAG 0x0000007f
#define CP_SET 0x00700000
#define CP_SET_1 0x00000080
#define CP_SET_FLAG 0x0000007f
#define CP_NEWCTX 0x00600004
#define CP_NEXT_TO_SWAP 0x00600005
#define CP_SET_CONTEXT_POINTER 0x00600006
#define CP_SET_XFER_POINTER 0x00600007
#define CP_ENABLE 0x00600009
#define CP_END 0x0060000c
#define CP_NEXT_TO_CURRENT 0x0060000d
#define CP_DISABLE1 0x0090ffff
#define CP_DISABLE2 0x0091ffff
#define CP_XFER_1 0x008000ff
#define CP_XFER_2 0x008800ff
#define CP_SEEK_1 0x00c000ff
#define CP_SEEK_2 0x00c800ff
#include "nv50.h"
#include "ctx.h"
#define IS_NVA3F(x) (((x) > 0xa0 && (x) < 0xaa) || (x) == 0xaf)
#define IS_NVAAF(x) ((x) >= 0xaa && (x) <= 0xac)
/*
* This code deals with PGRAPH contexts on NV50 family cards. Like NV40, it's
* the GPU itself that does context-switching, but it needs a special
* microcode to do it. And it's the driver's task to supply this microcode,
* further known as ctxprog, as well as the initial context values, known
* as ctxvals.
*
* Without ctxprog, you cannot switch contexts. Not even in software, since
* the majority of context [xfer strands] isn't accessible directly. You're
* stuck with a single channel, and you also suffer all the problems resulting
* from missing ctxvals, since you cannot load them.
*
* Without ctxvals, you're stuck with PGRAPH's default context. It's enough to
* run 2d operations, but trying to utilise 3d or CUDA will just lock you up,
* since you don't have... some sort of needed setup.
*
* Nouveau will just disable acceleration if not given ctxprog + ctxvals, since
* it's too much hassle to handle no-ctxprog as a special case.
*/
/*
* How ctxprogs work.
*
* The ctxprog is written in its own kind of microcode, with very small and
* crappy set of available commands. You upload it to a small [512 insns]
* area of memory on PGRAPH, and it'll be run when PFIFO wants PGRAPH to
* switch channel. or when the driver explicitely requests it. Stuff visible
* to ctxprog consists of: PGRAPH MMIO registers, PGRAPH context strands,
* the per-channel context save area in VRAM [known as ctxvals or grctx],
* 4 flags registers, a scratch register, two grctx pointers, plus many
* random poorly-understood details.
*
* When ctxprog runs, it's supposed to check what operations are asked of it,
* save old context if requested, optionally reset PGRAPH and switch to the
* new channel, and load the new context. Context consists of three major
* parts: subset of MMIO registers and two "xfer areas".
*/
/* TODO:
* - document unimplemented bits compared to nvidia
* - NVAx: make a TP subroutine, use it.
* - use 0x4008fc instead of 0x1540?
*/
enum cp_label {
cp_check_load = 1,
cp_setup_auto_load,
cp_setup_load,
cp_setup_save,
cp_swap_state,
cp_prepare_exit,
cp_exit,
};
static void nv50_graph_construct_mmio(struct nouveau_grctx *ctx);
static void nv50_graph_construct_xfer1(struct nouveau_grctx *ctx);
static void nv50_graph_construct_xfer2(struct nouveau_grctx *ctx);
/* Main function: construct the ctxprog skeleton, call the other functions. */
static int
nv50_grctx_generate(struct nouveau_grctx *ctx)
{
cp_set (ctx, STATE, RUNNING);
cp_set (ctx, XFER_SWITCH, ENABLE);
/* decide whether we're loading/unloading the context */
cp_bra (ctx, AUTO_SAVE, PENDING, cp_setup_save);
cp_bra (ctx, USER_SAVE, PENDING, cp_setup_save);
cp_name(ctx, cp_check_load);
cp_bra (ctx, AUTO_LOAD, PENDING, cp_setup_auto_load);
cp_bra (ctx, USER_LOAD, PENDING, cp_setup_load);
cp_bra (ctx, ALWAYS, TRUE, cp_prepare_exit);
/* setup for context load */
cp_name(ctx, cp_setup_auto_load);
cp_out (ctx, CP_DISABLE1);
cp_out (ctx, CP_DISABLE2);
cp_out (ctx, CP_ENABLE);
cp_out (ctx, CP_NEXT_TO_SWAP);
cp_set (ctx, UNK01, SET);
cp_name(ctx, cp_setup_load);
cp_out (ctx, CP_NEWCTX);
cp_wait(ctx, NEWCTX, BUSY);
cp_set (ctx, UNK1D, CLEAR);
cp_set (ctx, SWAP_DIRECTION, LOAD);
cp_bra (ctx, UNK0B, SET, cp_prepare_exit);
cp_bra (ctx, ALWAYS, TRUE, cp_swap_state);
/* setup for context save */
cp_name(ctx, cp_setup_save);
cp_set (ctx, UNK1D, SET);
cp_wait(ctx, STATUS, BUSY);
cp_wait(ctx, INTR, PENDING);
cp_bra (ctx, STATUS, BUSY, cp_setup_save);
cp_set (ctx, UNK01, SET);
cp_set (ctx, SWAP_DIRECTION, SAVE);
/* general PGRAPH state */
cp_name(ctx, cp_swap_state);
cp_set (ctx, UNK03, SET);
cp_pos (ctx, 0x00004/4);
cp_ctx (ctx, 0x400828, 1); /* needed. otherwise, flickering happens. */
cp_pos (ctx, 0x00100/4);
nv50_graph_construct_mmio(ctx);
nv50_graph_construct_xfer1(ctx);
nv50_graph_construct_xfer2(ctx);
cp_bra (ctx, SWAP_DIRECTION, SAVE, cp_check_load);
cp_set (ctx, UNK20, SET);
cp_set (ctx, SWAP_DIRECTION, SAVE); /* no idea why this is needed, but fixes at least one lockup. */
cp_lsr (ctx, ctx->ctxvals_base);
cp_out (ctx, CP_SET_XFER_POINTER);
cp_lsr (ctx, 4);
cp_out (ctx, CP_SEEK_1);
cp_out (ctx, CP_XFER_1);
cp_wait(ctx, XFER, BUSY);
/* pre-exit state updates */
cp_name(ctx, cp_prepare_exit);
cp_set (ctx, UNK01, CLEAR);
cp_set (ctx, UNK03, CLEAR);
cp_set (ctx, UNK1D, CLEAR);
cp_bra (ctx, USER_SAVE, PENDING, cp_exit);
cp_out (ctx, CP_NEXT_TO_CURRENT);
cp_name(ctx, cp_exit);
cp_set (ctx, USER_SAVE, NOT_PENDING);
cp_set (ctx, USER_LOAD, NOT_PENDING);
cp_set (ctx, XFER_SWITCH, DISABLE);
cp_set (ctx, STATE, STOPPED);
cp_out (ctx, CP_END);
ctx->ctxvals_pos += 0x400; /* padding... no idea why you need it */
return 0;
}
void
nv50_grctx_fill(struct nouveau_device *device, struct nouveau_gpuobj *mem)
{
nv50_grctx_generate(&(struct nouveau_grctx) {
.device = device,
.mode = NOUVEAU_GRCTX_VALS,
.data = mem,
});
}
int
nv50_grctx_init(struct nouveau_device *device, u32 *size)
{
u32 *ctxprog = kmalloc(512 * 4, GFP_KERNEL), i;
struct nouveau_grctx ctx = {
.device = device,
.mode = NOUVEAU_GRCTX_PROG,
.data = ctxprog,
.ctxprog_max = 512,
};
if (!ctxprog)
return -ENOMEM;
nv50_grctx_generate(&ctx);
nv_wr32(device, 0x400324, 0);
for (i = 0; i < ctx.ctxprog_len; i++)
nv_wr32(device, 0x400328, ctxprog[i]);
*size = ctx.ctxvals_pos * 4;
kfree(ctxprog);
return 0;
}
/*
* Constructs MMIO part of ctxprog and ctxvals. Just a matter of knowing which
* registers to save/restore and the default values for them.
*/
static void
nv50_graph_construct_mmio_ddata(struct nouveau_grctx *ctx);
static void
nv50_graph_construct_mmio(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int i, j;
int offset, base;
u32 units = nv_rd32 (ctx->device, 0x1540);
/* 0800: DISPATCH */
cp_ctx(ctx, 0x400808, 7);
gr_def(ctx, 0x400814, 0x00000030);
cp_ctx(ctx, 0x400834, 0x32);
if (device->chipset == 0x50) {
gr_def(ctx, 0x400834, 0xff400040);
gr_def(ctx, 0x400838, 0xfff00080);
gr_def(ctx, 0x40083c, 0xfff70090);
gr_def(ctx, 0x400840, 0xffe806a8);
}
gr_def(ctx, 0x400844, 0x00000002);
if (IS_NVA3F(device->chipset))
gr_def(ctx, 0x400894, 0x00001000);
gr_def(ctx, 0x4008e8, 0x00000003);
gr_def(ctx, 0x4008ec, 0x00001000);
if (device->chipset == 0x50)
cp_ctx(ctx, 0x400908, 0xb);
else if (device->chipset < 0xa0)
cp_ctx(ctx, 0x400908, 0xc);
else
cp_ctx(ctx, 0x400908, 0xe);
if (device->chipset >= 0xa0)
cp_ctx(ctx, 0x400b00, 0x1);
if (IS_NVA3F(device->chipset)) {
cp_ctx(ctx, 0x400b10, 0x1);
gr_def(ctx, 0x400b10, 0x0001629d);
cp_ctx(ctx, 0x400b20, 0x1);
gr_def(ctx, 0x400b20, 0x0001629d);
}
nv50_graph_construct_mmio_ddata(ctx);
/* 0C00: VFETCH */
cp_ctx(ctx, 0x400c08, 0x2);
gr_def(ctx, 0x400c08, 0x0000fe0c);
/* 1000 */
if (device->chipset < 0xa0) {
cp_ctx(ctx, 0x401008, 0x4);
gr_def(ctx, 0x401014, 0x00001000);
} else if (!IS_NVA3F(device->chipset)) {
cp_ctx(ctx, 0x401008, 0x5);
gr_def(ctx, 0x401018, 0x00001000);
} else {
cp_ctx(ctx, 0x401008, 0x5);
gr_def(ctx, 0x401018, 0x00004000);
}
/* 1400 */
cp_ctx(ctx, 0x401400, 0x8);
cp_ctx(ctx, 0x401424, 0x3);
if (device->chipset == 0x50)
gr_def(ctx, 0x40142c, 0x0001fd87);
else
gr_def(ctx, 0x40142c, 0x00000187);
cp_ctx(ctx, 0x401540, 0x5);
gr_def(ctx, 0x401550, 0x00001018);
/* 1800: STREAMOUT */
cp_ctx(ctx, 0x401814, 0x1);
gr_def(ctx, 0x401814, 0x000000ff);
if (device->chipset == 0x50) {
cp_ctx(ctx, 0x40181c, 0xe);
gr_def(ctx, 0x401850, 0x00000004);
} else if (device->chipset < 0xa0) {
cp_ctx(ctx, 0x40181c, 0xf);
gr_def(ctx, 0x401854, 0x00000004);
} else {
cp_ctx(ctx, 0x40181c, 0x13);
gr_def(ctx, 0x401864, 0x00000004);
}
/* 1C00 */
cp_ctx(ctx, 0x401c00, 0x1);
switch (device->chipset) {
case 0x50:
gr_def(ctx, 0x401c00, 0x0001005f);
break;
case 0x84:
case 0x86:
case 0x94:
gr_def(ctx, 0x401c00, 0x044d00df);
break;
case 0x92:
case 0x96:
case 0x98:
case 0xa0:
case 0xaa:
case 0xac:
gr_def(ctx, 0x401c00, 0x042500df);
break;
case 0xa3:
case 0xa5:
case 0xa8:
case 0xaf:
gr_def(ctx, 0x401c00, 0x142500df);
break;
}
/* 2000 */
/* 2400 */
cp_ctx(ctx, 0x402400, 0x1);
if (device->chipset == 0x50)
cp_ctx(ctx, 0x402408, 0x1);
else
cp_ctx(ctx, 0x402408, 0x2);
gr_def(ctx, 0x402408, 0x00000600);
/* 2800: CSCHED */
cp_ctx(ctx, 0x402800, 0x1);
if (device->chipset == 0x50)
gr_def(ctx, 0x402800, 0x00000006);
/* 2C00: ZCULL */
cp_ctx(ctx, 0x402c08, 0x6);
if (device->chipset != 0x50)
gr_def(ctx, 0x402c14, 0x01000000);
gr_def(ctx, 0x402c18, 0x000000ff);
if (device->chipset == 0x50)
cp_ctx(ctx, 0x402ca0, 0x1);
else
cp_ctx(ctx, 0x402ca0, 0x2);
if (device->chipset < 0xa0)
gr_def(ctx, 0x402ca0, 0x00000400);
else if (!IS_NVA3F(device->chipset))
gr_def(ctx, 0x402ca0, 0x00000800);
else
gr_def(ctx, 0x402ca0, 0x00000400);
cp_ctx(ctx, 0x402cac, 0x4);
/* 3000: ENG2D */
cp_ctx(ctx, 0x403004, 0x1);
gr_def(ctx, 0x403004, 0x00000001);
/* 3400 */
if (device->chipset >= 0xa0) {
cp_ctx(ctx, 0x403404, 0x1);
gr_def(ctx, 0x403404, 0x00000001);
}
/* 5000: CCACHE */
cp_ctx(ctx, 0x405000, 0x1);
switch (device->chipset) {
case 0x50:
gr_def(ctx, 0x405000, 0x00300080);
break;
case 0x84:
case 0xa0:
case 0xa3:
case 0xa5:
case 0xa8:
case 0xaa:
case 0xac:
case 0xaf:
gr_def(ctx, 0x405000, 0x000e0080);
break;
case 0x86:
case 0x92:
case 0x94:
case 0x96:
case 0x98:
gr_def(ctx, 0x405000, 0x00000080);
break;
}
cp_ctx(ctx, 0x405014, 0x1);
gr_def(ctx, 0x405014, 0x00000004);
cp_ctx(ctx, 0x40501c, 0x1);
cp_ctx(ctx, 0x405024, 0x1);
cp_ctx(ctx, 0x40502c, 0x1);
/* 6000? */
if (device->chipset == 0x50)
cp_ctx(ctx, 0x4063e0, 0x1);
/* 6800: M2MF */
if (device->chipset < 0x90) {
cp_ctx(ctx, 0x406814, 0x2b);
gr_def(ctx, 0x406818, 0x00000f80);
gr_def(ctx, 0x406860, 0x007f0080);
gr_def(ctx, 0x40689c, 0x007f0080);
} else {
cp_ctx(ctx, 0x406814, 0x4);
if (device->chipset == 0x98)
gr_def(ctx, 0x406818, 0x00000f80);
else
gr_def(ctx, 0x406818, 0x00001f80);
if (IS_NVA3F(device->chipset))
gr_def(ctx, 0x40681c, 0x00000030);
cp_ctx(ctx, 0x406830, 0x3);
}
/* 7000: per-ROP group state */
for (i = 0; i < 8; i++) {
if (units & (1<<(i+16))) {
cp_ctx(ctx, 0x407000 + (i<<8), 3);
if (device->chipset == 0x50)
gr_def(ctx, 0x407000 + (i<<8), 0x1b74f820);
else if (device->chipset != 0xa5)
gr_def(ctx, 0x407000 + (i<<8), 0x3b74f821);
else
gr_def(ctx, 0x407000 + (i<<8), 0x7b74f821);
gr_def(ctx, 0x407004 + (i<<8), 0x89058001);
if (device->chipset == 0x50) {
cp_ctx(ctx, 0x407010 + (i<<8), 1);
} else if (device->chipset < 0xa0) {
cp_ctx(ctx, 0x407010 + (i<<8), 2);
gr_def(ctx, 0x407010 + (i<<8), 0x00001000);
gr_def(ctx, 0x407014 + (i<<8), 0x0000001f);
} else {
cp_ctx(ctx, 0x407010 + (i<<8), 3);
gr_def(ctx, 0x407010 + (i<<8), 0x00001000);
if (device->chipset != 0xa5)
gr_def(ctx, 0x407014 + (i<<8), 0x000000ff);
else
gr_def(ctx, 0x407014 + (i<<8), 0x000001ff);
}
cp_ctx(ctx, 0x407080 + (i<<8), 4);
if (device->chipset != 0xa5)
gr_def(ctx, 0x407080 + (i<<8), 0x027c10fa);
else
gr_def(ctx, 0x407080 + (i<<8), 0x827c10fa);
if (device->chipset == 0x50)
gr_def(ctx, 0x407084 + (i<<8), 0x000000c0);
else
gr_def(ctx, 0x407084 + (i<<8), 0x400000c0);
gr_def(ctx, 0x407088 + (i<<8), 0xb7892080);
if (device->chipset < 0xa0)
cp_ctx(ctx, 0x407094 + (i<<8), 1);
else if (!IS_NVA3F(device->chipset))
cp_ctx(ctx, 0x407094 + (i<<8), 3);
else {
cp_ctx(ctx, 0x407094 + (i<<8), 4);
gr_def(ctx, 0x4070a0 + (i<<8), 1);
}
}
}
cp_ctx(ctx, 0x407c00, 0x3);
if (device->chipset < 0x90)
gr_def(ctx, 0x407c00, 0x00010040);
else if (device->chipset < 0xa0)
gr_def(ctx, 0x407c00, 0x00390040);
else
gr_def(ctx, 0x407c00, 0x003d0040);
gr_def(ctx, 0x407c08, 0x00000022);
if (device->chipset >= 0xa0) {
cp_ctx(ctx, 0x407c10, 0x3);
cp_ctx(ctx, 0x407c20, 0x1);
cp_ctx(ctx, 0x407c2c, 0x1);
}
if (device->chipset < 0xa0) {
cp_ctx(ctx, 0x407d00, 0x9);
} else {
cp_ctx(ctx, 0x407d00, 0x15);
}
if (device->chipset == 0x98)
gr_def(ctx, 0x407d08, 0x00380040);
else {
if (device->chipset < 0x90)
gr_def(ctx, 0x407d08, 0x00010040);
else if (device->chipset < 0xa0)
gr_def(ctx, 0x407d08, 0x00390040);
else
gr_def(ctx, 0x407d08, 0x003d0040);
gr_def(ctx, 0x407d0c, 0x00000022);
}
/* 8000+: per-TP state */
for (i = 0; i < 10; i++) {
if (units & (1<<i)) {
if (device->chipset < 0xa0)
base = 0x408000 + (i<<12);
else
base = 0x408000 + (i<<11);
if (device->chipset < 0xa0)
offset = base + 0xc00;
else
offset = base + 0x80;
cp_ctx(ctx, offset + 0x00, 1);
gr_def(ctx, offset + 0x00, 0x0000ff0a);
cp_ctx(ctx, offset + 0x08, 1);
/* per-MP state */
for (j = 0; j < (device->chipset < 0xa0 ? 2 : 4); j++) {
if (!(units & (1 << (j+24)))) continue;
if (device->chipset < 0xa0)
offset = base + 0x200 + (j<<7);
else
offset = base + 0x100 + (j<<7);
cp_ctx(ctx, offset, 0x20);
gr_def(ctx, offset + 0x00, 0x01800000);
gr_def(ctx, offset + 0x04, 0x00160000);
gr_def(ctx, offset + 0x08, 0x01800000);
gr_def(ctx, offset + 0x18, 0x0003ffff);
switch (device->chipset) {
case 0x50:
gr_def(ctx, offset + 0x1c, 0x00080000);
break;
case 0x84:
gr_def(ctx, offset + 0x1c, 0x00880000);
break;
case 0x86:
gr_def(ctx, offset + 0x1c, 0x018c0000);
break;
case 0x92:
case 0x96:
case 0x98:
gr_def(ctx, offset + 0x1c, 0x118c0000);
break;
case 0x94:
gr_def(ctx, offset + 0x1c, 0x10880000);
break;
case 0xa0:
case 0xa5:
gr_def(ctx, offset + 0x1c, 0x310c0000);
break;
case 0xa3:
case 0xa8:
case 0xaa:
case 0xac:
case 0xaf:
gr_def(ctx, offset + 0x1c, 0x300c0000);
break;
}
gr_def(ctx, offset + 0x40, 0x00010401);
if (device->chipset == 0x50)
gr_def(ctx, offset + 0x48, 0x00000040);
else
gr_def(ctx, offset + 0x48, 0x00000078);
gr_def(ctx, offset + 0x50, 0x000000bf);
gr_def(ctx, offset + 0x58, 0x00001210);
if (device->chipset == 0x50)
gr_def(ctx, offset + 0x5c, 0x00000080);
else
gr_def(ctx, offset + 0x5c, 0x08000080);
if (device->chipset >= 0xa0)
gr_def(ctx, offset + 0x68, 0x0000003e);
}
if (device->chipset < 0xa0)
cp_ctx(ctx, base + 0x300, 0x4);
else
cp_ctx(ctx, base + 0x300, 0x5);
if (device->chipset == 0x50)
gr_def(ctx, base + 0x304, 0x00007070);
else if (device->chipset < 0xa0)
gr_def(ctx, base + 0x304, 0x00027070);
else if (!IS_NVA3F(device->chipset))
gr_def(ctx, base + 0x304, 0x01127070);
else
gr_def(ctx, base + 0x304, 0x05127070);
if (device->chipset < 0xa0)
cp_ctx(ctx, base + 0x318, 1);
else
cp_ctx(ctx, base + 0x320, 1);
if (device->chipset == 0x50)
gr_def(ctx, base + 0x318, 0x0003ffff);
else if (device->chipset < 0xa0)
gr_def(ctx, base + 0x318, 0x03ffffff);
else
gr_def(ctx, base + 0x320, 0x07ffffff);
if (device->chipset < 0xa0)
cp_ctx(ctx, base + 0x324, 5);
else
cp_ctx(ctx, base + 0x328, 4);
if (device->chipset < 0xa0) {
cp_ctx(ctx, base + 0x340, 9);
offset = base + 0x340;
} else if (!IS_NVA3F(device->chipset)) {
cp_ctx(ctx, base + 0x33c, 0xb);
offset = base + 0x344;
} else {
cp_ctx(ctx, base + 0x33c, 0xd);
offset = base + 0x344;
}
gr_def(ctx, offset + 0x0, 0x00120407);
gr_def(ctx, offset + 0x4, 0x05091507);
if (device->chipset == 0x84)
gr_def(ctx, offset + 0x8, 0x05100202);
else
gr_def(ctx, offset + 0x8, 0x05010202);
gr_def(ctx, offset + 0xc, 0x00030201);
if (device->chipset == 0xa3)
cp_ctx(ctx, base + 0x36c, 1);
cp_ctx(ctx, base + 0x400, 2);
gr_def(ctx, base + 0x404, 0x00000040);
cp_ctx(ctx, base + 0x40c, 2);
gr_def(ctx, base + 0x40c, 0x0d0c0b0a);
gr_def(ctx, base + 0x410, 0x00141210);
if (device->chipset < 0xa0)
offset = base + 0x800;
else
offset = base + 0x500;
cp_ctx(ctx, offset, 6);
gr_def(ctx, offset + 0x0, 0x000001f0);
gr_def(ctx, offset + 0x4, 0x00000001);
gr_def(ctx, offset + 0x8, 0x00000003);
if (device->chipset == 0x50 || IS_NVAAF(device->chipset))
gr_def(ctx, offset + 0xc, 0x00008000);
gr_def(ctx, offset + 0x14, 0x00039e00);
cp_ctx(ctx, offset + 0x1c, 2);
if (device->chipset == 0x50)
gr_def(ctx, offset + 0x1c, 0x00000040);
else
gr_def(ctx, offset + 0x1c, 0x00000100);
gr_def(ctx, offset + 0x20, 0x00003800);
if (device->chipset >= 0xa0) {
cp_ctx(ctx, base + 0x54c, 2);
if (!IS_NVA3F(device->chipset))
gr_def(ctx, base + 0x54c, 0x003fe006);
else
gr_def(ctx, base + 0x54c, 0x003fe007);
gr_def(ctx, base + 0x550, 0x003fe000);
}
if (device->chipset < 0xa0)
offset = base + 0xa00;
else
offset = base + 0x680;
cp_ctx(ctx, offset, 1);
gr_def(ctx, offset, 0x00404040);
if (device->chipset < 0xa0)
offset = base + 0xe00;
else
offset = base + 0x700;
cp_ctx(ctx, offset, 2);
if (device->chipset < 0xa0)
gr_def(ctx, offset, 0x0077f005);
else if (device->chipset == 0xa5)
gr_def(ctx, offset, 0x6cf7f007);
else if (device->chipset == 0xa8)
gr_def(ctx, offset, 0x6cfff007);
else if (device->chipset == 0xac)
gr_def(ctx, offset, 0x0cfff007);
else
gr_def(ctx, offset, 0x0cf7f007);
if (device->chipset == 0x50)
gr_def(ctx, offset + 0x4, 0x00007fff);
else if (device->chipset < 0xa0)
gr_def(ctx, offset + 0x4, 0x003f7fff);
else
gr_def(ctx, offset + 0x4, 0x02bf7fff);
cp_ctx(ctx, offset + 0x2c, 1);
if (device->chipset == 0x50) {
cp_ctx(ctx, offset + 0x50, 9);
gr_def(ctx, offset + 0x54, 0x000003ff);
gr_def(ctx, offset + 0x58, 0x00000003);
gr_def(ctx, offset + 0x5c, 0x00000003);
gr_def(ctx, offset + 0x60, 0x000001ff);
gr_def(ctx, offset + 0x64, 0x0000001f);
gr_def(ctx, offset + 0x68, 0x0000000f);
gr_def(ctx, offset + 0x6c, 0x0000000f);
} else if (device->chipset < 0xa0) {
cp_ctx(ctx, offset + 0x50, 1);
cp_ctx(ctx, offset + 0x70, 1);
} else {
cp_ctx(ctx, offset + 0x50, 1);
cp_ctx(ctx, offset + 0x60, 5);
}
}
}
}
static void
dd_emit(struct nouveau_grctx *ctx, int num, u32 val) {
int i;
if (val && ctx->mode == NOUVEAU_GRCTX_VALS)
for (i = 0; i < num; i++)
nv_wo32(ctx->data, 4 * (ctx->ctxvals_pos + i), val);
ctx->ctxvals_pos += num;
}
static void
nv50_graph_construct_mmio_ddata(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int base, num;
base = ctx->ctxvals_pos;
/* tesla state */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
/* SRC_TIC state */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 2);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0); /* 000000ff SRC_ADDRESS_HIGH */
dd_emit(ctx, 1, 0);
if (device->chipset >= 0x94)
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1); /* 00000fff SRC_DEPTH */
dd_emit(ctx, 1, 0x100); /* 0000ffff SRC_HEIGHT */
/* turing state */
dd_emit(ctx, 1, 0); /* 0000000f TEXTURES_LOG2 */
dd_emit(ctx, 1, 0); /* 0000000f SAMPLERS_LOG2 */
dd_emit(ctx, 1, 0); /* 000000ff CB_DEF_ADDRESS_HIGH */
dd_emit(ctx, 1, 0); /* ffffffff CB_DEF_ADDRESS_LOW */
dd_emit(ctx, 1, 0); /* ffffffff SHARED_SIZE */
dd_emit(ctx, 1, 2); /* ffffffff REG_MODE */
dd_emit(ctx, 1, 1); /* 0000ffff BLOCK_ALLOC_THREADS */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0); /* 000000ff UNK370 */
dd_emit(ctx, 1, 0); /* 000000ff USER_PARAM_UNK */
dd_emit(ctx, 1, 0); /* 000000ff USER_PARAM_COUNT */
dd_emit(ctx, 1, 1); /* 000000ff UNK384 bits 8-15 */
dd_emit(ctx, 1, 0x3fffff); /* 003fffff TIC_LIMIT */
dd_emit(ctx, 1, 0x1fff); /* 000fffff TSC_LIMIT */
dd_emit(ctx, 1, 0); /* 0000ffff CB_ADDR_INDEX */
dd_emit(ctx, 1, 1); /* 000007ff BLOCKDIM_X */
dd_emit(ctx, 1, 1); /* 000007ff BLOCKDIM_XMY */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1); /* 0003ffff BLOCKDIM_XMYMZ */
dd_emit(ctx, 1, 1); /* 000007ff BLOCKDIM_Y */
dd_emit(ctx, 1, 1); /* 0000007f BLOCKDIM_Z */
dd_emit(ctx, 1, 4); /* 000000ff CP_REG_ALLOC_TEMP */
dd_emit(ctx, 1, 1);
if (IS_NVA3F(device->chipset))
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1); /* 0000007f BLOCK_ALLOC_HALFWARPS */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 7);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 7);
dd_emit(ctx, 1, 1); /* 00001fff BLOCK_ALLOC_REGSLOTS_PACKED */
dd_emit(ctx, 1, 1); /* 00001fff BLOCK_ALLOC_REGSLOTS_STRIDED */
dd_emit(ctx, 1, 1); /* 000007ff BLOCK_ALLOC_THREADS */
/* compat 2d state */
if (device->chipset == 0x50) {
dd_emit(ctx, 4, 0); /* 0000ffff clip X, Y, W, H */
dd_emit(ctx, 1, 1); /* ffffffff chroma COLOR_FORMAT */
dd_emit(ctx, 1, 1); /* ffffffff pattern COLOR_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff pattern SHAPE */
dd_emit(ctx, 1, 1); /* ffffffff pattern PATTERN_SELECT */
dd_emit(ctx, 1, 0xa); /* ffffffff surf2d SRC_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff surf2d DMA_SRC */
dd_emit(ctx, 1, 0); /* 000000ff surf2d SRC_ADDRESS_HIGH */
dd_emit(ctx, 1, 0); /* ffffffff surf2d SRC_ADDRESS_LOW */
dd_emit(ctx, 1, 0x40); /* 0000ffff surf2d SRC_PITCH */
dd_emit(ctx, 1, 0); /* 0000000f surf2d SRC_TILE_MODE_Z */
dd_emit(ctx, 1, 2); /* 0000000f surf2d SRC_TILE_MODE_Y */
dd_emit(ctx, 1, 0x100); /* ffffffff surf2d SRC_HEIGHT */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0x100); /* ffffffff surf2d SRC_WIDTH */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect CLIP_B_X */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect CLIP_B_Y */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect CLIP_C_X */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect CLIP_C_Y */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect CLIP_D_X */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect CLIP_D_Y */
dd_emit(ctx, 1, 1); /* ffffffff gdirect COLOR_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff gdirect OPERATION */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect POINT_X */
dd_emit(ctx, 1, 0); /* 0000ffff gdirect POINT_Y */
dd_emit(ctx, 1, 0); /* 0000ffff blit SRC_Y */
dd_emit(ctx, 1, 0); /* ffffffff blit OPERATION */
dd_emit(ctx, 1, 0); /* ffffffff ifc OPERATION */
dd_emit(ctx, 1, 0); /* ffffffff iifc INDEX_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff iifc LUT_OFFSET */
dd_emit(ctx, 1, 4); /* ffffffff iifc COLOR_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff iifc OPERATION */
}
/* m2mf state */
dd_emit(ctx, 1, 0); /* ffffffff m2mf LINE_COUNT */
dd_emit(ctx, 1, 0); /* ffffffff m2mf LINE_LENGTH_IN */
dd_emit(ctx, 2, 0); /* ffffffff m2mf OFFSET_IN, OFFSET_OUT */
dd_emit(ctx, 1, 1); /* ffffffff m2mf TILING_DEPTH_OUT */
dd_emit(ctx, 1, 0x100); /* ffffffff m2mf TILING_HEIGHT_OUT */
dd_emit(ctx, 1, 0); /* ffffffff m2mf TILING_POSITION_OUT_Z */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 2, 0); /* 0000ffff m2mf TILING_POSITION_OUT_X, Y */
dd_emit(ctx, 1, 0x100); /* ffffffff m2mf TILING_PITCH_OUT */
dd_emit(ctx, 1, 1); /* ffffffff m2mf TILING_DEPTH_IN */
dd_emit(ctx, 1, 0x100); /* ffffffff m2mf TILING_HEIGHT_IN */
dd_emit(ctx, 1, 0); /* ffffffff m2mf TILING_POSITION_IN_Z */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 2, 0); /* 0000ffff m2mf TILING_POSITION_IN_X, Y */
dd_emit(ctx, 1, 0x100); /* ffffffff m2mf TILING_PITCH_IN */
/* more compat 2d state */
if (device->chipset == 0x50) {
dd_emit(ctx, 1, 1); /* ffffffff line COLOR_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff line OPERATION */
dd_emit(ctx, 1, 1); /* ffffffff triangle COLOR_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff triangle OPERATION */
dd_emit(ctx, 1, 0); /* 0000000f sifm TILE_MODE_Z */
dd_emit(ctx, 1, 2); /* 0000000f sifm TILE_MODE_Y */
dd_emit(ctx, 1, 0); /* 000000ff sifm FORMAT_FILTER */
dd_emit(ctx, 1, 1); /* 000000ff sifm FORMAT_ORIGIN */
dd_emit(ctx, 1, 0); /* 0000ffff sifm SRC_PITCH */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0); /* 000000ff sifm SRC_OFFSET_HIGH */
dd_emit(ctx, 1, 0); /* ffffffff sifm SRC_OFFSET */
dd_emit(ctx, 1, 0); /* 0000ffff sifm SRC_HEIGHT */
dd_emit(ctx, 1, 0); /* 0000ffff sifm SRC_WIDTH */
dd_emit(ctx, 1, 3); /* ffffffff sifm COLOR_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff sifm OPERATION */
dd_emit(ctx, 1, 0); /* ffffffff sifc OPERATION */
}
/* tesla state */
dd_emit(ctx, 1, 0); /* 0000000f GP_TEXTURES_LOG2 */
dd_emit(ctx, 1, 0); /* 0000000f GP_SAMPLERS_LOG2 */
dd_emit(ctx, 1, 0); /* 000000ff */
dd_emit(ctx, 1, 0); /* ffffffff */
dd_emit(ctx, 1, 4); /* 000000ff UNK12B0_0 */
dd_emit(ctx, 1, 0x70); /* 000000ff UNK12B0_1 */
dd_emit(ctx, 1, 0x80); /* 000000ff UNK12B0_3 */
dd_emit(ctx, 1, 0); /* 000000ff UNK12B0_2 */
dd_emit(ctx, 1, 0); /* 0000000f FP_TEXTURES_LOG2 */
dd_emit(ctx, 1, 0); /* 0000000f FP_SAMPLERS_LOG2 */
if (IS_NVA3F(device->chipset)) {
dd_emit(ctx, 1, 0); /* ffffffff */
dd_emit(ctx, 1, 0); /* 0000007f MULTISAMPLE_SAMPLES_LOG2 */
} else {
dd_emit(ctx, 1, 0); /* 0000000f MULTISAMPLE_SAMPLES_LOG2 */
}
dd_emit(ctx, 1, 0xc); /* 000000ff SEMANTIC_COLOR.BFC0_ID */
if (device->chipset != 0x50)
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 8); /* 000000ff SEMANTIC_COLOR.COLR_NR */
dd_emit(ctx, 1, 0x14); /* 000000ff SEMANTIC_COLOR.FFC0_ID */
if (device->chipset == 0x50) {
dd_emit(ctx, 1, 0); /* 000000ff SEMANTIC_LAYER */
dd_emit(ctx, 1, 0);
} else {
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0x29); /* 000000ff SEMANTIC_PTSZ.PTSZ_ID */
dd_emit(ctx, 1, 0x27); /* 000000ff SEMANTIC_PRIM */
dd_emit(ctx, 1, 0x26); /* 000000ff SEMANTIC_LAYER */
dd_emit(ctx, 1, 8); /* 0000000f SMENATIC_CLIP.CLIP_HIGH */
dd_emit(ctx, 1, 4); /* 000000ff SEMANTIC_CLIP.CLIP_LO */
dd_emit(ctx, 1, 0x27); /* 000000ff UNK0FD4 */
dd_emit(ctx, 1, 0);
}
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 2);
dd_emit(ctx, 1, 3);
dd_emit(ctx, 1, 4);
dd_emit(ctx, 1, 5);
dd_emit(ctx, 1, 6);
dd_emit(ctx, 1, 7);
dd_emit(ctx, 1, 1); /* 0000000f RT_CONTROL_COUNT */
dd_emit(ctx, 8, 0);
dd_emit(ctx, 8, 0); /* ffffffff RT_ADDRESS_LOW */
dd_emit(ctx, 1, 0xcf); /* 000000ff RT_FORMAT */
dd_emit(ctx, 7, 0); /* 000000ff RT_FORMAT */
if (device->chipset != 0x50)
dd_emit(ctx, 3, 0); /* 1, 1, 1 */
else
dd_emit(ctx, 2, 0); /* 1, 1 */
dd_emit(ctx, 1, 0); /* ffffffff GP_ENABLE */
dd_emit(ctx, 1, 0x80); /* 0000ffff GP_VERTEX_OUTPUT_COUNT*/
dd_emit(ctx, 1, 4); /* 000000ff GP_REG_ALLOC_RESULT */
dd_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
if (IS_NVA3F(device->chipset)) {
dd_emit(ctx, 1, 3);
dd_emit(ctx, 1, 0);
}
if (device->chipset != 0x50)
dd_emit(ctx, 1, 3);
dd_emit(ctx, 1, 1); /* ffffffff RASTERIZE_ENABLE */
dd_emit(ctx, 1, 0);
if (device->chipset != 0x50)
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0x12); /* 000000ff FP_INTERPOLANT_CTRL.COUNT */
dd_emit(ctx, 1, 0x10); /* 000000ff FP_INTERPOLANT_CTRL.COUNT_NONFLAT */
dd_emit(ctx, 1, 0xc); /* 000000ff FP_INTERPOLANT_CTRL.OFFSET */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 4); /* 000000ff FP_RESULT_COUNT */
dd_emit(ctx, 1, 2); /* ffffffff REG_MODE */
dd_emit(ctx, 1, 4); /* 000000ff FP_REG_ALLOC_TEMP */
if (device->chipset >= 0xa0)
dd_emit(ctx, 1, 0); /* ffffffff */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0); /* ffffffff STRMOUT_ENABLE */
dd_emit(ctx, 1, 0x3fffff); /* 003fffff TIC_LIMIT */
dd_emit(ctx, 1, 0x1fff); /* 000fffff TSC_LIMIT */
dd_emit(ctx, 1, 0);
if (device->chipset != 0x50)
dd_emit(ctx, 8, 0);
if (device->chipset >= 0xa0) {
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 2);
dd_emit(ctx, 1, 0); /* 000000ff VTX_ATTR_DEFINE.ATTR */
}
dd_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
dd_emit(ctx, 1, 0x14); /* 0000001f ZETA_FORMAT */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0); /* 0000000f VP_TEXTURES_LOG2 */
dd_emit(ctx, 1, 0); /* 0000000f VP_SAMPLERS_LOG2 */
if (IS_NVA3F(device->chipset))
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 2);
if (device->chipset >= 0xa0)
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0); /* 0000ffff CB_ADDR_INDEX */
if (device->chipset >= 0xa0)
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 2);
dd_emit(ctx, 1, 0x1000); /* 00007fff UNK141C */
if (device->chipset != 0x50) {
dd_emit(ctx, 1, 0xe00); /* 7fff */
dd_emit(ctx, 1, 0x1000); /* 7fff */
dd_emit(ctx, 1, 0x1e00); /* 7fff */
}
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 1); /* 000000ff GP_REG_ALLOC_TEMP / 4 rounded up */
dd_emit(ctx, 1, 1); /* 000000ff FP_REG_ALLOC_TEMP... without /4? */
dd_emit(ctx, 1, 1); /* 000000ff VP_REG_ALLOC_TEMP / 4 rounded up */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0x200); /* 0003ffff GP_VERTEX_OUTPUT_COUNT*GP_REG_ALLOC_RESULT */
if (IS_NVA3F(device->chipset))
dd_emit(ctx, 1, 0x200);
dd_emit(ctx, 1, 0);
if (device->chipset < 0xa0) {
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0x70); /* 000000ff */
dd_emit(ctx, 1, 0x80); /* 000000ff */
dd_emit(ctx, 1, 0); /* 000000ff */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0x70); /* 000000ff */
dd_emit(ctx, 1, 0x80); /* 000000ff */
dd_emit(ctx, 1, 0); /* 000000ff */
} else {
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0xf0); /* 000000ff */
dd_emit(ctx, 1, 0xff); /* 000000ff */
dd_emit(ctx, 1, 0); /* 000000ff */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0xf0); /* 000000ff */
dd_emit(ctx, 1, 0xff); /* 000000ff */
dd_emit(ctx, 1, 0); /* 000000ff */
dd_emit(ctx, 1, 9); /* 0000003f UNK114C.COMP,SIZE */
}
/* eng2d state */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 1); /* ffffffff eng2d DST_DEPTH */
dd_emit(ctx, 1, 0xcf); /* 000000ff eng2d DST_FORMAT */
dd_emit(ctx, 1, 0); /* ffffffff eng2d DST_LAYER */
dd_emit(ctx, 1, 1);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0xcf); /* 000000ff eng2d SIFC_FORMAT */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 2);
dd_emit(ctx, 1, 0); /* ffffffff eng2d BLIT_DU_DX_FRACT */
dd_emit(ctx, 1, 1); /* ffffffff eng2d BLIT_DU_DX_INT */
dd_emit(ctx, 1, 0); /* ffffffff eng2d BLIT_DV_DY_FRACT */
dd_emit(ctx, 1, 1); /* ffffffff eng2d BLIT_DV_DY_INT */
dd_emit(ctx, 1, 0);
dd_emit(ctx, 1, 0xcf); /* 000000ff eng2d DRAW_COLOR_FORMAT */
dd_emit(ctx, 1, 0xcf); /* 000000ff eng2d SRC_FORMAT */
dd_emit(ctx, 1, 1);
num = ctx->ctxvals_pos - base;
ctx->ctxvals_pos = base;
if (IS_NVA3F(device->chipset))
cp_ctx(ctx, 0x404800, num);
else
cp_ctx(ctx, 0x405400, num);
}
/*
* xfer areas. These are a pain.
*
* There are 2 xfer areas: the first one is big and contains all sorts of
* stuff, the second is small and contains some per-TP context.
*
* Each area is split into 8 "strands". The areas, when saved to grctx,
* are made of 8-word blocks. Each block contains a single word from
* each strand. The strands are independent of each other, their
* addresses are unrelated to each other, and data in them is closely
* packed together. The strand layout varies a bit between cards: here
* and there, a single word is thrown out in the middle and the whole
* strand is offset by a bit from corresponding one on another chipset.
* For this reason, addresses of stuff in strands are almost useless.
* Knowing sequence of stuff and size of gaps between them is much more
* useful, and that's how we build the strands in our generator.
*
* NVA0 takes this mess to a whole new level by cutting the old strands
* into a few dozen pieces [known as genes], rearranging them randomly,
* and putting them back together to make new strands. Hopefully these
* genes correspond more or less directly to the same PGRAPH subunits
* as in 400040 register.
*
* The most common value in default context is 0, and when the genes
* are separated by 0's, gene bounduaries are quite speculative...
* some of them can be clearly deduced, others can be guessed, and yet
* others won't be resolved without figuring out the real meaning of
* given ctxval. For the same reason, ending point of each strand
* is unknown. Except for strand 0, which is the longest strand and
* its end corresponds to end of the whole xfer.
*
* An unsolved mystery is the seek instruction: it takes an argument
* in bits 8-18, and that argument is clearly the place in strands to
* seek to... but the offsets don't seem to correspond to offsets as
* seen in grctx. Perhaps there's another, real, not randomly-changing
* addressing in strands, and the xfer insn just happens to skip over
* the unused bits? NV10-NV30 PIPE comes to mind...
*
* As far as I know, there's no way to access the xfer areas directly
* without the help of ctxprog.
*/
static void
xf_emit(struct nouveau_grctx *ctx, int num, u32 val) {
int i;
if (val && ctx->mode == NOUVEAU_GRCTX_VALS)
for (i = 0; i < num; i++)
nv_wo32(ctx->data, 4 * (ctx->ctxvals_pos + (i << 3)), val);
ctx->ctxvals_pos += num << 3;
}
/* Gene declarations... */
static void nv50_graph_construct_gene_dispatch(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_m2mf(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_ccache(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_unk10xx(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_unk14xx(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_zcull(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_clipid(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_unk24xx(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_vfetch(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_eng2d(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_csched(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_unk1cxx(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_strmout(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_unk34xx(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_ropm1(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_ropm2(struct nouveau_grctx *ctx);
static void nv50_graph_construct_gene_ropc(struct nouveau_grctx *ctx);
static void nv50_graph_construct_xfer_tp(struct nouveau_grctx *ctx);
static void
nv50_graph_construct_xfer1(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int i;
int offset;
int size = 0;
u32 units = nv_rd32 (ctx->device, 0x1540);
offset = (ctx->ctxvals_pos+0x3f)&~0x3f;
ctx->ctxvals_base = offset;
if (device->chipset < 0xa0) {
/* Strand 0 */
ctx->ctxvals_pos = offset;
nv50_graph_construct_gene_dispatch(ctx);
nv50_graph_construct_gene_m2mf(ctx);
nv50_graph_construct_gene_unk24xx(ctx);
nv50_graph_construct_gene_clipid(ctx);
nv50_graph_construct_gene_zcull(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 1 */
ctx->ctxvals_pos = offset + 0x1;
nv50_graph_construct_gene_vfetch(ctx);
nv50_graph_construct_gene_eng2d(ctx);
nv50_graph_construct_gene_csched(ctx);
nv50_graph_construct_gene_ropm1(ctx);
nv50_graph_construct_gene_ropm2(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 2 */
ctx->ctxvals_pos = offset + 0x2;
nv50_graph_construct_gene_ccache(ctx);
nv50_graph_construct_gene_unk1cxx(ctx);
nv50_graph_construct_gene_strmout(ctx);
nv50_graph_construct_gene_unk14xx(ctx);
nv50_graph_construct_gene_unk10xx(ctx);
nv50_graph_construct_gene_unk34xx(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 3: per-ROP group state */
ctx->ctxvals_pos = offset + 3;
for (i = 0; i < 6; i++)
if (units & (1 << (i + 16)))
nv50_graph_construct_gene_ropc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strands 4-7: per-TP state */
for (i = 0; i < 4; i++) {
ctx->ctxvals_pos = offset + 4 + i;
if (units & (1 << (2 * i)))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << (2 * i + 1)))
nv50_graph_construct_xfer_tp(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
}
} else {
/* Strand 0 */
ctx->ctxvals_pos = offset;
nv50_graph_construct_gene_dispatch(ctx);
nv50_graph_construct_gene_m2mf(ctx);
nv50_graph_construct_gene_unk34xx(ctx);
nv50_graph_construct_gene_csched(ctx);
nv50_graph_construct_gene_unk1cxx(ctx);
nv50_graph_construct_gene_strmout(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 1 */
ctx->ctxvals_pos = offset + 1;
nv50_graph_construct_gene_unk10xx(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 2 */
ctx->ctxvals_pos = offset + 2;
if (device->chipset == 0xa0)
nv50_graph_construct_gene_unk14xx(ctx);
nv50_graph_construct_gene_unk24xx(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 3 */
ctx->ctxvals_pos = offset + 3;
nv50_graph_construct_gene_vfetch(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 4 */
ctx->ctxvals_pos = offset + 4;
nv50_graph_construct_gene_ccache(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 5 */
ctx->ctxvals_pos = offset + 5;
nv50_graph_construct_gene_ropm2(ctx);
nv50_graph_construct_gene_ropm1(ctx);
/* per-ROP context */
for (i = 0; i < 8; i++)
if (units & (1<<(i+16)))
nv50_graph_construct_gene_ropc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 6 */
ctx->ctxvals_pos = offset + 6;
nv50_graph_construct_gene_zcull(ctx);
nv50_graph_construct_gene_clipid(ctx);
nv50_graph_construct_gene_eng2d(ctx);
if (units & (1 << 0))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 1))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 2))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 3))
nv50_graph_construct_xfer_tp(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 7 */
ctx->ctxvals_pos = offset + 7;
if (device->chipset == 0xa0) {
if (units & (1 << 4))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 5))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 6))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 7))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 8))
nv50_graph_construct_xfer_tp(ctx);
if (units & (1 << 9))
nv50_graph_construct_xfer_tp(ctx);
} else {
nv50_graph_construct_gene_unk14xx(ctx);
}
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
}
ctx->ctxvals_pos = offset + size * 8;
ctx->ctxvals_pos = (ctx->ctxvals_pos+0x3f)&~0x3f;
cp_lsr (ctx, offset);
cp_out (ctx, CP_SET_XFER_POINTER);
cp_lsr (ctx, size);
cp_out (ctx, CP_SEEK_1);
cp_out (ctx, CP_XFER_1);
cp_wait(ctx, XFER, BUSY);
}
/*
* non-trivial demagiced parts of ctx init go here
*/
static void
nv50_graph_construct_gene_dispatch(struct nouveau_grctx *ctx)
{
/* start of strand 0 */
struct nouveau_device *device = ctx->device;
/* SEEK */
if (device->chipset == 0x50)
xf_emit(ctx, 5, 0);
else if (!IS_NVA3F(device->chipset))
xf_emit(ctx, 6, 0);
else
xf_emit(ctx, 4, 0);
/* SEEK */
/* the PGRAPH's internal FIFO */
if (device->chipset == 0x50)
xf_emit(ctx, 8*3, 0);
else
xf_emit(ctx, 0x100*3, 0);
/* and another bonus slot?!? */
xf_emit(ctx, 3, 0);
/* and YET ANOTHER bonus slot? */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 3, 0);
/* SEEK */
/* CTX_SWITCH: caches of gr objects bound to subchannels. 8 values, last used index */
xf_emit(ctx, 9, 0);
/* SEEK */
xf_emit(ctx, 9, 0);
/* SEEK */
xf_emit(ctx, 9, 0);
/* SEEK */
xf_emit(ctx, 9, 0);
/* SEEK */
if (device->chipset < 0x90)
xf_emit(ctx, 4, 0);
/* SEEK */
xf_emit(ctx, 2, 0);
/* SEEK */
xf_emit(ctx, 6*2, 0);
xf_emit(ctx, 2, 0);
/* SEEK */
xf_emit(ctx, 2, 0);
/* SEEK */
xf_emit(ctx, 6*2, 0);
xf_emit(ctx, 2, 0);
/* SEEK */
if (device->chipset == 0x50)
xf_emit(ctx, 0x1c, 0);
else if (device->chipset < 0xa0)
xf_emit(ctx, 0x1e, 0);
else
xf_emit(ctx, 0x22, 0);
/* SEEK */
xf_emit(ctx, 0x15, 0);
}
static void
nv50_graph_construct_gene_m2mf(struct nouveau_grctx *ctx)
{
/* Strand 0, right after dispatch */
struct nouveau_device *device = ctx->device;
int smallm2mf = 0;
if (device->chipset < 0x92 || device->chipset == 0x98)
smallm2mf = 1;
/* SEEK */
xf_emit (ctx, 1, 0); /* DMA_NOTIFY instance >> 4 */
xf_emit (ctx, 1, 0); /* DMA_BUFFER_IN instance >> 4 */
xf_emit (ctx, 1, 0); /* DMA_BUFFER_OUT instance >> 4 */
xf_emit (ctx, 1, 0); /* OFFSET_IN */
xf_emit (ctx, 1, 0); /* OFFSET_OUT */
xf_emit (ctx, 1, 0); /* PITCH_IN */
xf_emit (ctx, 1, 0); /* PITCH_OUT */
xf_emit (ctx, 1, 0); /* LINE_LENGTH */
xf_emit (ctx, 1, 0); /* LINE_COUNT */
xf_emit (ctx, 1, 0x21); /* FORMAT: bits 0-4 INPUT_INC, bits 5-9 OUTPUT_INC */
xf_emit (ctx, 1, 1); /* LINEAR_IN */
xf_emit (ctx, 1, 0x2); /* TILING_MODE_IN: bits 0-2 y tiling, bits 3-5 z tiling */
xf_emit (ctx, 1, 0x100); /* TILING_PITCH_IN */
xf_emit (ctx, 1, 0x100); /* TILING_HEIGHT_IN */
xf_emit (ctx, 1, 1); /* TILING_DEPTH_IN */
xf_emit (ctx, 1, 0); /* TILING_POSITION_IN_Z */
xf_emit (ctx, 1, 0); /* TILING_POSITION_IN */
xf_emit (ctx, 1, 1); /* LINEAR_OUT */
xf_emit (ctx, 1, 0x2); /* TILING_MODE_OUT: bits 0-2 y tiling, bits 3-5 z tiling */
xf_emit (ctx, 1, 0x100); /* TILING_PITCH_OUT */
xf_emit (ctx, 1, 0x100); /* TILING_HEIGHT_OUT */
xf_emit (ctx, 1, 1); /* TILING_DEPTH_OUT */
xf_emit (ctx, 1, 0); /* TILING_POSITION_OUT_Z */
xf_emit (ctx, 1, 0); /* TILING_POSITION_OUT */
xf_emit (ctx, 1, 0); /* OFFSET_IN_HIGH */
xf_emit (ctx, 1, 0); /* OFFSET_OUT_HIGH */
/* SEEK */
if (smallm2mf)
xf_emit(ctx, 0x40, 0); /* 20 * ffffffff, 3ffff */
else
xf_emit(ctx, 0x100, 0); /* 80 * ffffffff, 3ffff */
xf_emit(ctx, 4, 0); /* 1f/7f, 0, 1f/7f, 0 [1f for smallm2mf, 7f otherwise] */
/* SEEK */
if (smallm2mf)
xf_emit(ctx, 0x400, 0); /* ffffffff */
else
xf_emit(ctx, 0x800, 0); /* ffffffff */
xf_emit(ctx, 4, 0); /* ff/1ff, 0, 0, 0 [ff for smallm2mf, 1ff otherwise] */
/* SEEK */
xf_emit(ctx, 0x40, 0); /* 20 * bits ffffffff, 3ffff */
xf_emit(ctx, 0x6, 0); /* 1f, 0, 1f, 0, 1f, 0 */
}
static void
nv50_graph_construct_gene_ccache(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
xf_emit(ctx, 2, 0); /* RO */
xf_emit(ctx, 0x800, 0); /* ffffffff */
switch (device->chipset) {
case 0x50:
case 0x92:
case 0xa0:
xf_emit(ctx, 0x2b, 0);
break;
case 0x84:
xf_emit(ctx, 0x29, 0);
break;
case 0x94:
case 0x96:
case 0xa3:
xf_emit(ctx, 0x27, 0);
break;
case 0x86:
case 0x98:
case 0xa5:
case 0xa8:
case 0xaa:
case 0xac:
case 0xaf:
xf_emit(ctx, 0x25, 0);
break;
}
/* CB bindings, 0x80 of them. first word is address >> 8, second is
* size >> 4 | valid << 24 */
xf_emit(ctx, 0x100, 0); /* ffffffff CB_DEF */
xf_emit(ctx, 1, 0); /* 0000007f CB_ADDR_BUFFER */
xf_emit(ctx, 1, 0); /* 0 */
xf_emit(ctx, 0x30, 0); /* ff SET_PROGRAM_CB */
xf_emit(ctx, 1, 0); /* 3f last SET_PROGRAM_CB */
xf_emit(ctx, 4, 0); /* RO */
xf_emit(ctx, 0x100, 0); /* ffffffff */
xf_emit(ctx, 8, 0); /* 1f, 0, 0, ... */
xf_emit(ctx, 8, 0); /* ffffffff */
xf_emit(ctx, 4, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 3 */
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_CODE_CB */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_TIC */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_TSC */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff TIC_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff TIC_ADDRESS_LOW */
xf_emit(ctx, 1, 0x3fffff); /* 003fffff TIC_LIMIT */
xf_emit(ctx, 1, 0); /* 000000ff TSC_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff TSC_ADDRESS_LOW */
xf_emit(ctx, 1, 0x1fff); /* 000fffff TSC_LIMIT */
xf_emit(ctx, 1, 0); /* 000000ff VP_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff VP_ADDRESS_LOW */
xf_emit(ctx, 1, 0); /* 00ffffff VP_START_ID */
xf_emit(ctx, 1, 0); /* 000000ff CB_DEF_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff CB_DEF_ADDRESS_LOW */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff GP_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff GP_ADDRESS_LOW */
xf_emit(ctx, 1, 0); /* 00ffffff GP_START_ID */
xf_emit(ctx, 1, 0); /* 000000ff FP_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff FP_ADDRESS_LOW */
xf_emit(ctx, 1, 0); /* 00ffffff FP_START_ID */
}
static void
nv50_graph_construct_gene_unk10xx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int i;
/* end of area 2 on pre-NVA0, area 1 on NVAx */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x80); /* 0000ffff GP_VERTEX_OUTPUT_COUNT */
xf_emit(ctx, 1, 4); /* 000000ff GP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 0x80c14); /* 01ffffff SEMANTIC_COLOR */
xf_emit(ctx, 1, 0);
if (device->chipset == 0x50)
xf_emit(ctx, 1, 0x3ff);
else
xf_emit(ctx, 1, 0x7ff); /* 000007ff */
xf_emit(ctx, 1, 0); /* 111/113 */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
for (i = 0; i < 8; i++) {
switch (device->chipset) {
case 0x50:
case 0x86:
case 0x98:
case 0xaa:
case 0xac:
xf_emit(ctx, 0xa0, 0); /* ffffffff */
break;
case 0x84:
case 0x92:
case 0x94:
case 0x96:
xf_emit(ctx, 0x120, 0);
break;
case 0xa5:
case 0xa8:
xf_emit(ctx, 0x100, 0); /* ffffffff */
break;
case 0xa0:
case 0xa3:
case 0xaf:
xf_emit(ctx, 0x400, 0); /* ffffffff */
break;
}
xf_emit(ctx, 4, 0); /* 3f, 0, 0, 0 */
xf_emit(ctx, 4, 0); /* ffffffff */
}
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x80); /* 0000ffff GP_VERTEX_OUTPUT_COUNT */
xf_emit(ctx, 1, 4); /* 000000ff GP_REG_ALLOC_TEMP */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x27); /* 000000ff UNK0FD4 */
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 0x26); /* 000000ff SEMANTIC_LAYER */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
}
static void
nv50_graph_construct_gene_unk34xx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
/* end of area 2 on pre-NVA0, area 1 on NVAx */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x10, 0x04000000); /* 07ffffff VIEWPORT_CLIP_HORIZ*8, VIEWPORT_CLIP_VERT*8 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x20, 0); /* ffffffff POLYGON_STIPPLE */
xf_emit(ctx, 2, 0); /* 00007fff WINDOW_OFFSET_XY */
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 0x04e3bfdf); /* ffffffff UNK0D64 */
xf_emit(ctx, 1, 0x04e3bfdf); /* ffffffff UNK0DF4 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x1fe21); /* 0001ffff tesla UNK0FAC */
if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 0x0fac6881);
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 1);
xf_emit(ctx, 3, 0);
}
}
static void
nv50_graph_construct_gene_unk14xx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
/* middle of area 2 on pre-NVA0, beginning of area 2 on NVA0, area 7 on >NVA0 */
if (device->chipset != 0x50) {
xf_emit(ctx, 5, 0); /* ffffffff */
xf_emit(ctx, 1, 0x80c14); /* 01ffffff SEMANTIC_COLOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
xf_emit(ctx, 1, 0x804); /* 00000fff SEMANTIC_CLIP */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 4); /* 7f, ff */
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
}
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x10); /* 7f/ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0); /* 000000ff VP_CLIP_DISTANCE_ENABLE */
if (device->chipset != 0x50)
xf_emit(ctx, 1, 0); /* 3ff */
xf_emit(ctx, 1, 0); /* 000000ff tesla UNK1940 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x804); /* 00000fff SEMANTIC_CLIP */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
if (device->chipset != 0x50)
xf_emit(ctx, 1, 0x7f); /* 000000ff tesla UNK0FFC */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x80c14); /* 01ffffff SEMANTIC_COLOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x10); /* 7f/ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 4, 0); /* ffffffff NOPERSPECTIVE_BITMAP */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f */
if (device->chipset == 0x50)
xf_emit(ctx, 1, 0x3ff); /* 000003ff tesla UNK0D68 */
else
xf_emit(ctx, 1, 0x7ff); /* 000007ff tesla UNK0D68 */
xf_emit(ctx, 1, 0x80c14); /* 01ffffff SEMANTIC_COLOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x30, 0); /* ffffffff VIEWPORT_SCALE: X0, Y0, Z0, X1, Y1, ... */
xf_emit(ctx, 3, 0); /* f, 0, 0 */
xf_emit(ctx, 3, 0); /* ffffffff last VIEWPORT_SCALE? */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x10); /* 000000ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x30, 0); /* ffffffff VIEWPORT_TRANSLATE */
xf_emit(ctx, 3, 0); /* f, 0, 0 */
xf_emit(ctx, 3, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 2, 0x88); /* 000001ff tesla UNK19D8 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 4); /* 0000000f CULL_MODE */
xf_emit(ctx, 2, 0); /* 07ffffff SCREEN_SCISSOR */
xf_emit(ctx, 2, 0); /* 00007fff WINDOW_OFFSET_XY */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x10, 0);
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 0x26); /* 000000ff SEMANTIC_LAYER */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f */
xf_emit(ctx, 1, 0x3f800000); /* ffffffff LINE_WIDTH */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
xf_emit(ctx, 1, 0x10); /* 000000ff VIEW_VOLUME_CLIP_CTRL */
if (device->chipset != 0x50) {
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
}
xf_emit(ctx, 0x20, 0); /* 10xbits ffffffff, 3fffff. SCISSOR_* */
xf_emit(ctx, 1, 0); /* f */
xf_emit(ctx, 1, 0); /* 0? */
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 003fffff */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0x52); /* 000001ff SEMANTIC_PTSZ */
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 0x26); /* 000000ff SEMANTIC_LAYER */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x00ffff00); /* 00ffffff LINE_STIPPLE_PATTERN */
xf_emit(ctx, 1, 0); /* 0000000f */
}
static void
nv50_graph_construct_gene_zcull(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
/* end of strand 0 on pre-NVA0, beginning of strand 6 on NVAx */
/* SEEK */
xf_emit(ctx, 1, 0x3f); /* 0000003f UNK1590 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_REF */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 2);
xf_emit(ctx, 2, 0x04000000); /* 07ffffff tesla UNK0D6C */
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffffffff DEPTH_BOUNDS */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 0000000f CULL_MODE */
xf_emit(ctx, 1, 0); /* 0000ffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 0); /* 000000ff CLEAR_STENCIL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_REF */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff CLEAR_DEPTH */
xf_emit(ctx, 1, 0);
if (device->chipset != 0x50)
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x1001); /* 00001fff ZETA_ARRAY_MODE */
/* SEEK */
xf_emit(ctx, 4, 0xffff); /* 0000ffff MSAA_MASK */
xf_emit(ctx, 0x10, 0);
xf_emit(ctx, 0x10, 0); /* ffffffff DEPTH_RANGE_NEAR */
xf_emit(ctx, 0x10, 0x3f800000); /* ffffffff DEPTH_RANGE_FAR */
xf_emit(ctx, 1, 0x10); /* 7f/ff/3ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0);
if (device->chipset != 0x50)
xf_emit(ctx, 1, 0); /* 0fffffff tesla UNK1104 */
xf_emit(ctx, 1, 0);
}
static void
nv50_graph_construct_gene_clipid(struct nouveau_grctx *ctx)
{
/* middle of strand 0 on pre-NVA0 [after 24xx], middle of area 6 on NVAx */
/* SEEK */
xf_emit(ctx, 1, 0);
/* SEEK */
xf_emit(ctx, 4, 0); /* 07ffffff CLIPID_REGION_HORIZ */
xf_emit(ctx, 4, 0); /* 07ffffff CLIPID_REGION_VERT */
xf_emit(ctx, 2, 0); /* 07ffffff SCREEN_SCISSOR */
xf_emit(ctx, 2, 0x04000000); /* 07ffffff UNK1508 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x80); /* 00003fff CLIPID_WIDTH */
xf_emit(ctx, 1, 0); /* 000000ff CLIPID_ID */
xf_emit(ctx, 1, 0); /* 000000ff CLIPID_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff CLIPID_ADDRESS_LOW */
xf_emit(ctx, 1, 0x80); /* 00003fff CLIPID_HEIGHT */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_CLIPID */
}
static void
nv50_graph_construct_gene_unk24xx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int i;
/* middle of strand 0 on pre-NVA0 [after m2mf], end of strand 2 on NVAx */
/* SEEK */
xf_emit(ctx, 0x33, 0);
/* SEEK */
xf_emit(ctx, 2, 0);
/* SEEK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
/* SEEK */
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 4, 0); /* RO */
xf_emit(ctx, 0xe10, 0); /* 190 * 9: 8*ffffffff, 7ff */
xf_emit(ctx, 1, 0); /* 1ff */
xf_emit(ctx, 8, 0); /* 0? */
xf_emit(ctx, 9, 0); /* ffffffff, 7ff */
xf_emit(ctx, 4, 0); /* RO */
xf_emit(ctx, 0xe10, 0); /* 190 * 9: 8*ffffffff, 7ff */
xf_emit(ctx, 1, 0); /* 1ff */
xf_emit(ctx, 8, 0); /* 0? */
xf_emit(ctx, 9, 0); /* ffffffff, 7ff */
} else {
xf_emit(ctx, 0xc, 0); /* RO */
/* SEEK */
xf_emit(ctx, 0xe10, 0); /* 190 * 9: 8*ffffffff, 7ff */
xf_emit(ctx, 1, 0); /* 1ff */
xf_emit(ctx, 8, 0); /* 0? */
/* SEEK */
xf_emit(ctx, 0xc, 0); /* RO */
/* SEEK */
xf_emit(ctx, 0xe10, 0); /* 190 * 9: 8*ffffffff, 7ff */
xf_emit(ctx, 1, 0); /* 1ff */
xf_emit(ctx, 8, 0); /* 0? */
}
/* SEEK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
if (device->chipset != 0x50)
xf_emit(ctx, 1, 3);
/* SEEK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 0); /* 0000000f VP_GP_BUILTIN_ATTR_EN */
xf_emit(ctx, 1, 0x80c14); /* 01ffffff SEMANTIC_COLOR */
xf_emit(ctx, 1, 1);
/* SEEK */
if (device->chipset >= 0xa0)
xf_emit(ctx, 2, 4); /* 000000ff */
xf_emit(ctx, 1, 0x80c14); /* 01ffffff SEMANTIC_COLOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 0x27); /* 000000ff SEMANTIC_PRIM_ID */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f */
xf_emit(ctx, 1, 1);
for (i = 0; i < 10; i++) {
/* SEEK */
xf_emit(ctx, 0x40, 0); /* ffffffff */
xf_emit(ctx, 0x10, 0); /* 3, 0, 0.... */
xf_emit(ctx, 0x10, 0); /* ffffffff */
}
/* SEEK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 4, 0); /* ffffffff NOPERSPECTIVE_BITMAP */
xf_emit(ctx, 0x10, 0); /* 00ffffff POINT_COORD_REPLACE_MAP */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
if (device->chipset != 0x50)
xf_emit(ctx, 1, 0); /* 000003ff */
}
static void
nv50_graph_construct_gene_vfetch(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int acnt = 0x10, rep, i;
/* beginning of strand 1 on pre-NVA0, strand 3 on NVAx */
if (IS_NVA3F(device->chipset))
acnt = 0x20;
/* SEEK */
if (device->chipset >= 0xa0) {
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK13A4 */
xf_emit(ctx, 1, 1); /* 00000fff tesla UNK1318 */
}
xf_emit(ctx, 1, 0); /* ffffffff VERTEX_BUFFER_FIRST */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff PRIMITIVE_RESTART_INDEX */
xf_emit(ctx, 1, 0xf); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, (acnt/8)-1, 0); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, acnt/8, 0); /* ffffffff VTX_ATR_MASK_UNK0DD0 */
xf_emit(ctx, 1, 0); /* 0000000f VP_GP_BUILTIN_ATTR_EN */
xf_emit(ctx, 1, 0x20); /* 0000ffff tesla UNK129C */
xf_emit(ctx, 1, 0); /* 000000ff turing UNK370??? */
xf_emit(ctx, 1, 0); /* 0000ffff turing USER_PARAM_COUNT */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
/* SEEK */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0xb, 0); /* RO */
else if (device->chipset >= 0xa0)
xf_emit(ctx, 0x9, 0); /* RO */
else
xf_emit(ctx, 0x8, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
/* SEEK */
xf_emit(ctx, 0xc, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0); /* 7f/ff */
xf_emit(ctx, 1, 4); /* 7f/ff VP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 4); /* 7f/ff VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0); /* 0000000f VP_GP_BUILTIN_ATTR_EN */
xf_emit(ctx, 1, 4); /* 000001ff UNK1A28 */
xf_emit(ctx, 1, 8); /* 000001ff UNK0DF0 */
xf_emit(ctx, 1, 0);
if (device->chipset == 0x50)
xf_emit(ctx, 1, 0x3ff); /* 3ff tesla UNK0D68 */
else
xf_emit(ctx, 1, 0x7ff); /* 7ff tesla UNK0D68 */
if (device->chipset == 0xa8)
xf_emit(ctx, 1, 0x1e00); /* 7fff */
/* SEEK */
xf_emit(ctx, 0xc, 0); /* RO or close */
/* SEEK */
xf_emit(ctx, 1, 0xf); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, (acnt/8)-1, 0); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, 1, 0); /* 0000000f VP_GP_BUILTIN_ATTR_EN */
if (device->chipset > 0x50 && device->chipset < 0xa0)
xf_emit(ctx, 2, 0); /* ffffffff */
else
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0);
/* SEEK */
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 0x10, 0); /* 0? */
xf_emit(ctx, 2, 0); /* weird... */
xf_emit(ctx, 2, 0); /* RO */
} else {
xf_emit(ctx, 8, 0); /* 0? */
xf_emit(ctx, 1, 0); /* weird... */
xf_emit(ctx, 2, 0); /* RO */
}
/* SEEK */
xf_emit(ctx, 1, 0); /* ffffffff VB_ELEMENT_BASE */
xf_emit(ctx, 1, 0); /* ffffffff UNK1438 */
xf_emit(ctx, acnt, 0); /* 1 tesla UNK1000 */
if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1118? */
/* SEEK */
xf_emit(ctx, acnt, 0); /* ffffffff VERTEX_ARRAY_UNK90C */
xf_emit(ctx, 1, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* ffffffff VERTEX_ARRAY_UNK90C */
xf_emit(ctx, 1, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* RO */
xf_emit(ctx, 2, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK111C? */
xf_emit(ctx, 1, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0); /* 000000ff UNK15F4_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff UNK15F4_ADDRESS_LOW */
xf_emit(ctx, 1, 0); /* 000000ff UNK0F84_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff UNK0F84_ADDRESS_LOW */
/* SEEK */
xf_emit(ctx, acnt, 0); /* 00003fff VERTEX_ARRAY_ATTRIB_OFFSET */
xf_emit(ctx, 3, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* 00000fff VERTEX_ARRAY_STRIDE */
xf_emit(ctx, 3, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* ffffffff VERTEX_ARRAY_LOW */
xf_emit(ctx, 3, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* 000000ff VERTEX_ARRAY_HIGH */
xf_emit(ctx, 3, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* ffffffff VERTEX_LIMIT_LOW */
xf_emit(ctx, 3, 0); /* f/1f */
/* SEEK */
xf_emit(ctx, acnt, 0); /* 000000ff VERTEX_LIMIT_HIGH */
xf_emit(ctx, 3, 0); /* f/1f */
/* SEEK */
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, acnt, 0); /* f */
xf_emit(ctx, 3, 0); /* f/1f */
}
/* SEEK */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 2, 0); /* RO */
else
xf_emit(ctx, 5, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0); /* ffff DMA_VTXBUF */
/* SEEK */
if (device->chipset < 0xa0) {
xf_emit(ctx, 0x41, 0); /* RO */
/* SEEK */
xf_emit(ctx, 0x11, 0); /* RO */
} else if (!IS_NVA3F(device->chipset))
xf_emit(ctx, 0x50, 0); /* RO */
else
xf_emit(ctx, 0x58, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0xf); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, (acnt/8)-1, 0); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, 1, 1); /* 1 UNK0DEC */
/* SEEK */
xf_emit(ctx, acnt*4, 0); /* ffffffff VTX_ATTR */
xf_emit(ctx, 4, 0); /* f/1f, 0, 0, 0 */
/* SEEK */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0x1d, 0); /* RO */
else
xf_emit(ctx, 0x16, 0); /* RO */
/* SEEK */
xf_emit(ctx, 1, 0xf); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, (acnt/8)-1, 0); /* ffffffff VP_ATTR_EN */
/* SEEK */
if (device->chipset < 0xa0)
xf_emit(ctx, 8, 0); /* RO */
else if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0xc, 0); /* RO */
else
xf_emit(ctx, 7, 0); /* RO */
/* SEEK */
xf_emit(ctx, 0xa, 0); /* RO */
if (device->chipset == 0xa0)
rep = 0xc;
else
rep = 4;
for (i = 0; i < rep; i++) {
/* SEEK */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0x20, 0); /* ffffffff */
xf_emit(ctx, 0x200, 0); /* ffffffff */
xf_emit(ctx, 4, 0); /* 7f/ff, 0, 0, 0 */
xf_emit(ctx, 4, 0); /* ffffffff */
}
/* SEEK */
xf_emit(ctx, 1, 0); /* 113/111 */
xf_emit(ctx, 1, 0xf); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, (acnt/8)-1, 0); /* ffffffff VP_ATTR_EN */
xf_emit(ctx, acnt/8, 0); /* ffffffff VTX_ATTR_MASK_UNK0DD0 */
xf_emit(ctx, 1, 0); /* 0000000f VP_GP_BUILTIN_ATTR_EN */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
/* SEEK */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 7, 0); /* weird... */
else
xf_emit(ctx, 5, 0); /* weird... */
}
static void
nv50_graph_construct_gene_eng2d(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
/* middle of strand 1 on pre-NVA0 [after vfetch], middle of strand 6 on NVAx */
/* SEEK */
xf_emit(ctx, 2, 0); /* 0001ffff CLIP_X, CLIP_Y */
xf_emit(ctx, 2, 0); /* 0000ffff CLIP_W, CLIP_H */
xf_emit(ctx, 1, 0);
if (device->chipset < 0xa0) {
/* this is useless on everything but the original NV50,
* guess they forgot to nuke it. Or just didn't bother. */
xf_emit(ctx, 2, 0); /* 0000ffff IFC_CLIP_X, Y */
xf_emit(ctx, 2, 1); /* 0000ffff IFC_CLIP_W, H */
xf_emit(ctx, 1, 0);
}
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x100); /* 0001ffff DST_WIDTH */
xf_emit(ctx, 1, 0x100); /* 0001ffff DST_HEIGHT */
xf_emit(ctx, 1, 0x11); /* 3f[NV50]/7f[NV84+] DST_FORMAT */
xf_emit(ctx, 1, 0); /* 0001ffff DRAW_POINT_X */
xf_emit(ctx, 1, 8); /* 0000000f DRAW_UNK58C */
xf_emit(ctx, 1, 0); /* 000fffff SIFC_DST_X_FRACT */
xf_emit(ctx, 1, 0); /* 0001ffff SIFC_DST_X_INT */
xf_emit(ctx, 1, 0); /* 000fffff SIFC_DST_Y_FRACT */
xf_emit(ctx, 1, 0); /* 0001ffff SIFC_DST_Y_INT */
xf_emit(ctx, 1, 0); /* 000fffff SIFC_DX_DU_FRACT */
xf_emit(ctx, 1, 1); /* 0001ffff SIFC_DX_DU_INT */
xf_emit(ctx, 1, 0); /* 000fffff SIFC_DY_DV_FRACT */
xf_emit(ctx, 1, 1); /* 0001ffff SIFC_DY_DV_INT */
xf_emit(ctx, 1, 1); /* 0000ffff SIFC_WIDTH */
xf_emit(ctx, 1, 1); /* 0000ffff SIFC_HEIGHT */
xf_emit(ctx, 1, 0xcf); /* 000000ff SIFC_FORMAT */
xf_emit(ctx, 1, 2);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000ffff BLIT_DST_X */
xf_emit(ctx, 1, 0); /* 0000ffff BLIT_DST_Y */
xf_emit(ctx, 1, 0); /* 000fffff BLIT_DU_DX_FRACT */
xf_emit(ctx, 1, 1); /* 0001ffff BLIT_DU_DX_INT */
xf_emit(ctx, 1, 0); /* 000fffff BLIT_DV_DY_FRACT */
xf_emit(ctx, 1, 1); /* 0001ffff BLIT_DV_DY_INT */
xf_emit(ctx, 1, 1); /* 0000ffff BLIT_DST_W */
xf_emit(ctx, 1, 1); /* 0000ffff BLIT_DST_H */
xf_emit(ctx, 1, 0); /* 000fffff BLIT_SRC_X_FRACT */
xf_emit(ctx, 1, 0); /* 0001ffff BLIT_SRC_X_INT */
xf_emit(ctx, 1, 0); /* 000fffff BLIT_SRC_Y_FRACT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 0000003f UNK884 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK0FB8 */
xf_emit(ctx, 1, 0x15); /* 000000ff tesla UNK128C */
xf_emit(ctx, 2, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x4444480); /* 1fffffff UNK870 */
/* SEEK */
xf_emit(ctx, 0x10, 0);
/* SEEK */
xf_emit(ctx, 0x27, 0);
}
static void
nv50_graph_construct_gene_csched(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
/* middle of strand 1 on pre-NVA0 [after eng2d], middle of strand 0 on NVAx */
/* SEEK */
xf_emit(ctx, 2, 0); /* 00007fff WINDOW_OFFSET_XY... what is it doing here??? */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 0); /* 000003ff */
/* SEEK */
xf_emit(ctx, 1, 0); /* ffffffff turing UNK364 */
xf_emit(ctx, 1, 0); /* 0000000f turing UNK36C */
xf_emit(ctx, 1, 0); /* 0000ffff USER_PARAM_COUNT */
xf_emit(ctx, 1, 0x100); /* 00ffffff turing UNK384 */
xf_emit(ctx, 1, 0); /* 0000000f turing UNK2A0 */
xf_emit(ctx, 1, 0); /* 0000ffff GRIDID */
xf_emit(ctx, 1, 0x10001); /* ffffffff GRIDDIM_XY */
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0x10001); /* ffffffff BLOCKDIM_XY */
xf_emit(ctx, 1, 1); /* 0000ffff BLOCKDIM_Z */
xf_emit(ctx, 1, 0x10001); /* 00ffffff BLOCK_ALLOC */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 4); /* 000000ff FP_REG_ALLOC_TEMP */
xf_emit(ctx, 1, 2);
/* SEEK */
xf_emit(ctx, 0x40, 0); /* ffffffff USER_PARAM */
switch (device->chipset) {
case 0x50:
case 0x92:
xf_emit(ctx, 8, 0); /* 7, 0, 0, 0, ... */
xf_emit(ctx, 0x80, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 0x10*2, 0); /* ffffffff, 1f */
break;
case 0x84:
xf_emit(ctx, 8, 0); /* 7, 0, 0, 0, ... */
xf_emit(ctx, 0x60, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 0xc*2, 0); /* ffffffff, 1f */
break;
case 0x94:
case 0x96:
xf_emit(ctx, 8, 0); /* 7, 0, 0, 0, ... */
xf_emit(ctx, 0x40, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 8*2, 0); /* ffffffff, 1f */
break;
case 0x86:
case 0x98:
xf_emit(ctx, 4, 0); /* f, 0, 0, 0 */
xf_emit(ctx, 0x10, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 2*2, 0); /* ffffffff, 1f */
break;
case 0xa0:
xf_emit(ctx, 8, 0); /* 7, 0, 0, 0, ... */
xf_emit(ctx, 0xf0, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 0x1e*2, 0); /* ffffffff, 1f */
break;
case 0xa3:
xf_emit(ctx, 8, 0); /* 7, 0, 0, 0, ... */
xf_emit(ctx, 0x60, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 0xc*2, 0); /* ffffffff, 1f */
break;
case 0xa5:
case 0xaf:
xf_emit(ctx, 8, 0); /* 7, 0, 0, 0, ... */
xf_emit(ctx, 0x30, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 6*2, 0); /* ffffffff, 1f */
break;
case 0xaa:
xf_emit(ctx, 0x12, 0);
break;
case 0xa8:
case 0xac:
xf_emit(ctx, 4, 0); /* f, 0, 0, 0 */
xf_emit(ctx, 0x10, 0); /* fff */
xf_emit(ctx, 2, 0); /* ff, fff */
xf_emit(ctx, 2*2, 0); /* ffffffff, 1f */
break;
}
xf_emit(ctx, 1, 0); /* 0000000f */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 0000001f */
xf_emit(ctx, 4, 0); /* ffffffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 4, 0); /* ffffffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 000000ff */
}
static void
nv50_graph_construct_gene_unk1cxx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
xf_emit(ctx, 2, 0); /* 00007fff WINDOW_OFFSET_XY */
xf_emit(ctx, 1, 0x3f800000); /* ffffffff LINE_WIDTH */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 4); /* 0000000f CULL_MODE */
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 0x10, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x00ffff00); /* 00ffffff LINE_STIPPLE_PATTERN */
xf_emit(ctx, 1, 0); /* ffffffff POLYGON_OFFSET_UNITS */
xf_emit(ctx, 1, 0); /* ffffffff POLYGON_OFFSET_FACTOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* 07ffffff SCREEN_SCISSOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0xf); /* 0000000f COLOR_MASK */
xf_emit(ctx, 7, 0); /* 0000000f COLOR_MASK */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0x11); /* 0000007f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 0000007f RT_FORMAT */
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 3);
else if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 2);
xf_emit(ctx, 2, 0x04000000); /* 07ffffff tesla UNK0D6C */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_MASK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 5); /* 0000000f UNK1408 */
xf_emit(ctx, 1, 0x52); /* 000001ff SEMANTIC_PTSZ */
xf_emit(ctx, 1, 0); /* ffffffff POINT_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (device->chipset != 0x50) {
xf_emit(ctx, 1, 0); /* 3ff */
xf_emit(ctx, 1, 1);
}
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x10, 0); /* ffffffff DEPTH_RANGE_NEAR */
xf_emit(ctx, 0x10, 0x3f800000); /* ffffffff DEPTH_RANGE_FAR */
xf_emit(ctx, 1, 0x10); /* 000000ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 0x20, 0); /* 07ffffff VIEWPORT_HORIZ, then VIEWPORT_VERT. (W&0x3fff)<<13 | (X&0x1fff). */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK187C */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_MASK */
xf_emit(ctx, 1, 0x8100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 5); /* 0000000f tesla UNK1220 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff tesla UNK1A20 */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 4, 0xffff); /* 0000ffff MSAA_MASK */
if (device->chipset != 0x50)
xf_emit(ctx, 1, 3);
if (device->chipset < 0xa0)
xf_emit(ctx, 0x1c, 0); /* RO */
else if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0x9, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x00ffff00); /* 00ffffff LINE_STIPPLE_PATTERN */
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
xf_emit(ctx, 1, 0);
if (device->chipset != 0x50) {
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0); /* 3ff */
}
/* XXX: the following block could belong either to unk1cxx, or
* to STRMOUT. Rather hard to tell. */
if (device->chipset < 0xa0)
xf_emit(ctx, 0x25, 0);
else
xf_emit(ctx, 0x3b, 0);
}
static void
nv50_graph_construct_gene_strmout(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
xf_emit(ctx, 1, 0x102); /* 0000ffff STRMOUT_BUFFER_CTRL */
xf_emit(ctx, 1, 0); /* ffffffff STRMOUT_PRIMITIVE_COUNT */
xf_emit(ctx, 4, 4); /* 000000ff STRMOUT_NUM_ATTRIBS */
if (device->chipset >= 0xa0) {
xf_emit(ctx, 4, 0); /* ffffffff UNK1A8C */
xf_emit(ctx, 4, 0); /* ffffffff UNK1780 */
}
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 4); /* 0000007f VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
if (device->chipset == 0x50)
xf_emit(ctx, 1, 0x3ff); /* 000003ff tesla UNK0D68 */
else
xf_emit(ctx, 1, 0x7ff); /* 000007ff tesla UNK0D68 */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
/* SEEK */
xf_emit(ctx, 1, 0x102); /* 0000ffff STRMOUT_BUFFER_CTRL */
xf_emit(ctx, 1, 0); /* ffffffff STRMOUT_PRIMITIVE_COUNT */
xf_emit(ctx, 4, 0); /* 000000ff STRMOUT_ADDRESS_HIGH */
xf_emit(ctx, 4, 0); /* ffffffff STRMOUT_ADDRESS_LOW */
xf_emit(ctx, 4, 4); /* 000000ff STRMOUT_NUM_ATTRIBS */
if (device->chipset >= 0xa0) {
xf_emit(ctx, 4, 0); /* ffffffff UNK1A8C */
xf_emit(ctx, 4, 0); /* ffffffff UNK1780 */
}
xf_emit(ctx, 1, 0); /* 0000ffff DMA_STRMOUT */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_QUERY */
xf_emit(ctx, 1, 0); /* 000000ff QUERY_ADDRESS_HIGH */
xf_emit(ctx, 2, 0); /* ffffffff QUERY_ADDRESS_LOW QUERY_COUNTER */
xf_emit(ctx, 2, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
/* SEEK */
xf_emit(ctx, 0x20, 0); /* ffffffff STRMOUT_MAP */
xf_emit(ctx, 1, 0); /* 0000000f */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffffffff */
}
static void
nv50_graph_construct_gene_ropm1(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
xf_emit(ctx, 1, 0x4e3bfdf); /* ffffffff UNK0D64 */
xf_emit(ctx, 1, 0x4e3bfdf); /* ffffffff UNK0DF4 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 0x11); /* 000000ff tesla UNK1968 */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
}
static void
nv50_graph_construct_gene_ropm2(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
/* SEEK */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_QUERY */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 2, 0); /* ffffffff */
xf_emit(ctx, 1, 0); /* 000000ff QUERY_ADDRESS_HIGH */
xf_emit(ctx, 2, 0); /* ffffffff QUERY_ADDRESS_LOW, COUNTER */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 7 */
/* SEEK */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_QUERY */
xf_emit(ctx, 1, 0); /* 000000ff QUERY_ADDRESS_HIGH */
xf_emit(ctx, 2, 0); /* ffffffff QUERY_ADDRESS_LOW, COUNTER */
xf_emit(ctx, 1, 0x4e3bfdf); /* ffffffff UNK0D64 */
xf_emit(ctx, 1, 0x4e3bfdf); /* ffffffff UNK0DF4 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 0x11); /* 000000ff tesla UNK1968 */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
}
static void
nv50_graph_construct_gene_ropc(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int magic2;
if (device->chipset == 0x50) {
magic2 = 0x00003e60;
} else if (!IS_NVA3F(device->chipset)) {
magic2 = 0x001ffe67;
} else {
magic2 = 0x00087e67;
}
xf_emit(ctx, 1, 0); /* f/7 MUTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 2);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, magic2); /* 001fffff tesla UNK0F78 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 0);
if (device->chipset >= 0xa0 && !IS_NVAAF(device->chipset))
xf_emit(ctx, 1, 0x15); /* 000000ff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x10); /* 3ff/ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0); /* ffffffff CLEAR_DEPTH */
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
if (device->chipset == 0x86 || device->chipset == 0x92 || device->chipset == 0x98 || device->chipset >= 0xa0) {
xf_emit(ctx, 3, 0); /* ff, ffffffff, ffffffff */
xf_emit(ctx, 1, 4); /* 7 */
xf_emit(ctx, 1, 0x400); /* fffffff */
xf_emit(ctx, 1, 0x300); /* ffff */
xf_emit(ctx, 1, 0x1001); /* 1fff */
if (device->chipset != 0xa0) {
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 0); /* 0000000f UNK15C8 */
else
xf_emit(ctx, 1, 0x15); /* ff */
}
}
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_MASK */
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 2);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_MASK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x10); /* 7f/ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_REF */
xf_emit(ctx, 2, 0); /* ffffffff DEPTH_BOUNDS */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_REF */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x10); /* 7f/ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 0x10, 0); /* ffffffff DEPTH_RANGE_NEAR */
xf_emit(ctx, 0x10, 0x3f800000); /* ffffffff DEPTH_RANGE_FAR */
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_FUNC_REF */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 2, 0); /* ffffffff DEPTH_BOUNDS */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff CLEAR_STENCIL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_FUNC_REF */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x10); /* 7f/ff VIEW_VOLUME_CLIP_CTRL */
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 0x3f); /* 0000003f UNK1590 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffff0ff3, ffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff CLEAR_DEPTH */
xf_emit(ctx, 1, 1);
if (device->chipset >= 0xa0) {
xf_emit(ctx, 2, 0);
xf_emit(ctx, 1, 0x1001);
xf_emit(ctx, 0xb, 0);
} else {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
}
xf_emit(ctx, 1, 0x11); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 1, 0xf); /* 0000000f COLOR_MASK */
xf_emit(ctx, 7, 0); /* 0000000f COLOR_MASK */
xf_emit(ctx, 1, 0x11); /* 3f/7f */
xf_emit(ctx, 1, 0);
if (device->chipset != 0x50) {
xf_emit(ctx, 1, 0); /* 0000000f LOGIC_OP */
xf_emit(ctx, 1, 0); /* 000000ff */
}
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 1);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_RGB */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_RGB */
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, magic2); /* 001fffff tesla UNK0F78 */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_FUNC_SRC_RGB */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_FUNC_DST_RGB */
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0);
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0); /* 0000000f */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 2, 0);
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
} else if (device->chipset >= 0xa0) {
xf_emit(ctx, 2, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 2, 0);
} else {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
}
xf_emit(ctx, 4, 0); /* ffffffff CLEAR_COLOR */
xf_emit(ctx, 4, 0); /* ffffffff BLEND_COLOR A R G B */
xf_emit(ctx, 1, 0); /* 00000fff eng2d UNK2B0 */
if (device->chipset >= 0xa0)
xf_emit(ctx, 2, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_RGB */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_RGB */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f LOGIC_OP */
if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_FUNC_SRC_RGB */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_FUNC_DST_RGB */
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
}
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffffffff PATTERN_MONO_COLOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffffffff PATTERN_MONO_BITMAP */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff ROP */
xf_emit(ctx, 1, 0); /* ffffffff BETA1 */
xf_emit(ctx, 1, 0); /* ffffffff BETA4 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 0x50, 0); /* 10x ffffff, ffffff, ffffff, ffffff, 3 PATTERN */
}
static void
nv50_graph_construct_xfer_unk84xx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int magic3;
switch (device->chipset) {
case 0x50:
magic3 = 0x1000;
break;
case 0x86:
case 0x98:
case 0xa8:
case 0xaa:
case 0xac:
case 0xaf:
magic3 = 0x1e00;
break;
default:
magic3 = 0;
}
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 7f/ff[NVA0+] VP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0); /* 111/113[NVA0+] */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0x1f, 0); /* ffffffff */
else if (device->chipset >= 0xa0)
xf_emit(ctx, 0x0f, 0); /* ffffffff */
else
xf_emit(ctx, 0x10, 0); /* fffffff VP_RESULT_MAP_1 up */
xf_emit(ctx, 2, 0); /* f/1f[NVA3], fffffff/ffffffff[NVA0+] */
xf_emit(ctx, 1, 4); /* 7f/ff VP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 4); /* 7f/ff VP_RESULT_MAP_SIZE */
if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 0x03020100); /* ffffffff */
else
xf_emit(ctx, 1, 0x00608080); /* fffffff VP_RESULT_MAP_0 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 2, 0); /* 111/113, 7f/ff */
xf_emit(ctx, 1, 4); /* 7f/ff VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff GP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0x80); /* 0000ffff GP_VERTEX_OUTPUT_COUNT */
if (magic3)
xf_emit(ctx, 1, magic3); /* 00007fff tesla UNK141C */
xf_emit(ctx, 1, 4); /* 7f/ff VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0); /* 111/113 */
xf_emit(ctx, 0x1f, 0); /* ffffffff GP_RESULT_MAP_1 up */
xf_emit(ctx, 1, 0); /* 0000001f */
xf_emit(ctx, 1, 0); /* ffffffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff GP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 0x80); /* 0000ffff GP_VERTEX_OUTPUT_COUNT */
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0x03020100); /* ffffffff GP_RESULT_MAP_0 */
xf_emit(ctx, 1, 3);
if (magic3)
xf_emit(ctx, 1, magic3); /* 7fff tesla UNK141C */
xf_emit(ctx, 1, 4); /* 7f/ff VP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0); /* 111/113 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 7f/ff VP_REG_ALLOC_RESULT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
xf_emit(ctx, 1, 0); /* 111/113 */
if (device->chipset == 0x94 || device->chipset == 0x96)
xf_emit(ctx, 0x1020, 0); /* 4 x (0x400 x 0xffffffff, ff, 0, 0, 0, 4 x ffffffff) */
else if (device->chipset < 0xa0)
xf_emit(ctx, 0xa20, 0); /* 4 x (0x280 x 0xffffffff, ff, 0, 0, 0, 4 x ffffffff) */
else if (!IS_NVA3F(device->chipset))
xf_emit(ctx, 0x210, 0); /* ffffffff */
else
xf_emit(ctx, 0x410, 0); /* ffffffff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff GP_RESULT_MAP_SIZE */
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
}
static void
nv50_graph_construct_xfer_tprop(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int magic1, magic2;
if (device->chipset == 0x50) {
magic1 = 0x3ff;
magic2 = 0x00003e60;
} else if (!IS_NVA3F(device->chipset)) {
magic1 = 0x7ff;
magic2 = 0x001ffe67;
} else {
magic1 = 0x7ff;
magic2 = 0x00087e67;
}
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff ALPHA_TEST_REF */
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000000f UNK16A0 */
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_BACK_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 4, 0); /* ffffffff BLEND_COLOR */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0xf); /* 0000000f COLOR_MASK */
xf_emit(ctx, 7, 0); /* 0000000f COLOR_MASK */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ff[NV50]/3ff[NV84+] */
xf_emit(ctx, 1, 4);
xf_emit(ctx, 4, 0xffff); /* 0000ffff MSAA_MASK */
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_MASK */
xf_emit(ctx, 3, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* 00007fff WINDOW_OFFSET_XY */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* 7 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff COLOR_KEY */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffffffff SIFC_BITMAP_COLOR */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
} else if (device->chipset >= 0xa0) {
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
} else {
xf_emit(ctx, 1, 0);
}
xf_emit(ctx, 1, 0);
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_RGB */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_RGB */
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_SRC_RGB */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_DST_RGB */
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_SRC_ALPHA */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_DST_ALPHA */
xf_emit(ctx, 1, 0);
}
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 0x11); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 7 */
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0xcf); /* 000000ff SIFC_FORMAT */
xf_emit(ctx, 1, 0xcf); /* 000000ff DRAW_COLOR_FORMAT */
xf_emit(ctx, 1, 0xcf); /* 000000ff SRC_FORMAT */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
xf_emit(ctx, 1, 0); /* 7/f[NVA3] MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_RGB */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_RGB */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 8, 1);
xf_emit(ctx, 1, 0x11); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0xf); /* 0000000f COLOR_MASK */
xf_emit(ctx, 7, 0); /* 0000000f COLOR_MASK */
xf_emit(ctx, 1, magic2); /* 001fffff tesla UNK0F78 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 1);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
if (device->chipset == 0x50)
xf_emit(ctx, 1, 0); /* ff */
else
xf_emit(ctx, 3, 0); /* 1, 7, 3ff */
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 0x11); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* 000fffff BLIT_DU_DX_FRACT */
xf_emit(ctx, 1, 1); /* 0001ffff BLIT_DU_DX_INT */
xf_emit(ctx, 1, 0); /* 000fffff BLIT_DV_DY_FRACT */
xf_emit(ctx, 1, 1); /* 0001ffff BLIT_DV_DY_INT */
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, magic1); /* 3ff/7ff tesla UNK0D68 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 8, 0); /* 0000ffff DMA_COLOR */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_GLOBAL */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_LOCAL */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_STACK */
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_DST */
xf_emit(ctx, 1, 0); /* 7 */
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 8, 0); /* 000000ff RT_ADDRESS_HIGH */
xf_emit(ctx, 8, 0); /* ffffffff RT_LAYER_STRIDE */
xf_emit(ctx, 8, 0); /* ffffffff RT_ADDRESS_LOW */
xf_emit(ctx, 8, 8); /* 0000007f RT_TILE_MODE */
xf_emit(ctx, 1, 0x11); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 8, 0x400); /* 0fffffff RT_HORIZ */
xf_emit(ctx, 8, 0x300); /* 0000ffff RT_VERT */
xf_emit(ctx, 1, 1); /* 00001fff RT_ARRAY_MODE */
xf_emit(ctx, 1, 0xf); /* 0000000f COLOR_MASK */
xf_emit(ctx, 7, 0); /* 0000000f COLOR_MASK */
xf_emit(ctx, 1, 0x20); /* 00000fff DST_TILE_MODE */
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 0x100); /* 0001ffff DST_HEIGHT */
xf_emit(ctx, 1, 0); /* 000007ff DST_LAYER */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0); /* ffffffff DST_ADDRESS_LOW */
xf_emit(ctx, 1, 0); /* 000000ff DST_ADDRESS_HIGH */
xf_emit(ctx, 1, 0x40); /* 0007ffff DST_PITCH */
xf_emit(ctx, 1, 0x100); /* 0001ffff DST_WIDTH */
xf_emit(ctx, 1, 0); /* 0000ffff */
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, magic2); /* 001fffff tesla UNK0F78 */
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 2);
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_ZETA */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 2, 0); /* ffff, ff/3ff */
xf_emit(ctx, 1, 0); /* 0001ffff GP_BUILTIN_RESULT_EN */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000000ff STENCIL_FRONT_MASK */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff ZETA_LAYER_STRIDE */
xf_emit(ctx, 1, 0); /* 000000ff ZETA_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff ZETA_ADDRESS_LOW */
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x400); /* 0fffffff ZETA_HORIZ */
xf_emit(ctx, 1, 0x300); /* 0000ffff ZETA_VERT */
xf_emit(ctx, 1, 0x1001); /* 00001fff ZETA_ARRAY_MODE */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 0x11); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 3f/7f RT_FORMAT */
xf_emit(ctx, 1, 0x0fac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0xf); /* 0000000f COLOR_MASK */
xf_emit(ctx, 7, 0); /* 0000000f COLOR_MASK */
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 7 */
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
}
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 0x0fac6881); /* fffffff */
xf_emit(ctx, 1, magic2); /* 001fffff tesla UNK0F78 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 0000000f ZETA_FORMAT */
xf_emit(ctx, 1, 1);
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0); /* 0000000f tesla UNK15C8 */
}
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A3C */
if (device->chipset >= 0xa0) {
xf_emit(ctx, 3, 0); /* 7/f, 1, ffff0ff3 */
xf_emit(ctx, 1, 0xfac6881); /* fffffff */
xf_emit(ctx, 4, 0); /* 1, 1, 1, 3ff */
xf_emit(ctx, 1, 4); /* 7 */
xf_emit(ctx, 1, 0); /* 1 */
xf_emit(ctx, 2, 1); /* 1 */
xf_emit(ctx, 2, 0); /* 7, f */
xf_emit(ctx, 1, 1); /* 1 */
xf_emit(ctx, 1, 0); /* 7/f */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 0x9, 0); /* 1 */
else
xf_emit(ctx, 0x8, 0); /* 1 */
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 8, 1); /* 1 */
xf_emit(ctx, 1, 0x11); /* 7f */
xf_emit(ctx, 7, 0); /* 7f */
xf_emit(ctx, 1, 0xfac6881); /* fffffff */
xf_emit(ctx, 1, 0xf); /* f */
xf_emit(ctx, 7, 0); /* f */
xf_emit(ctx, 1, 0x11); /* 7f */
xf_emit(ctx, 1, 1); /* 1 */
xf_emit(ctx, 5, 0); /* 1, 7, 3ff, 3, 7 */
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
}
}
}
static void
nv50_graph_construct_xfer_tex(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
xf_emit(ctx, 2, 0); /* 1 LINKED_TSC. yes, 2. */
if (device->chipset != 0x50)
xf_emit(ctx, 1, 0); /* 3 */
xf_emit(ctx, 1, 1); /* 1ffff BLIT_DU_DX_INT */
xf_emit(ctx, 1, 0); /* fffff BLIT_DU_DX_FRACT */
xf_emit(ctx, 1, 1); /* 1ffff BLIT_DV_DY_INT */
xf_emit(ctx, 1, 0); /* fffff BLIT_DV_DY_FRACT */
if (device->chipset == 0x50)
xf_emit(ctx, 1, 0); /* 3 BLIT_CONTROL */
else
xf_emit(ctx, 2, 0); /* 3ff, 1 */
xf_emit(ctx, 1, 0x2a712488); /* ffffffff SRC_TIC_0 */
xf_emit(ctx, 1, 0); /* ffffffff SRC_TIC_1 */
xf_emit(ctx, 1, 0x4085c000); /* ffffffff SRC_TIC_2 */
xf_emit(ctx, 1, 0x40); /* ffffffff SRC_TIC_3 */
xf_emit(ctx, 1, 0x100); /* ffffffff SRC_TIC_4 */
xf_emit(ctx, 1, 0x10100); /* ffffffff SRC_TIC_5 */
xf_emit(ctx, 1, 0x02800000); /* ffffffff SRC_TIC_6 */
xf_emit(ctx, 1, 0); /* ffffffff SRC_TIC_7 */
if (device->chipset == 0x50) {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A34? */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
} else if (!IS_NVAAF(device->chipset)) {
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A34? */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 000003ff */
} else {
xf_emit(ctx, 0x6, 0);
}
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A34 */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_TEXTURE */
xf_emit(ctx, 1, 0); /* 0000ffff DMA_SRC */
}
static void
nv50_graph_construct_xfer_unk8cxx(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 2, 0); /* 7, ffff0ff3 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x04e3bfdf); /* ffffffff UNK0D64 */
xf_emit(ctx, 1, 0x04e3bfdf); /* ffffffff UNK0DF4 */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x00ffff00); /* 00ffffff LINE_STIPPLE_PATTERN */
xf_emit(ctx, 1, 1);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x00ffff00); /* 00ffffff LINE_STIPPLE_PATTERN */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* ffff0ff3 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x30201000); /* ffffffff tesla UNK1670 */
xf_emit(ctx, 1, 0x70605040); /* ffffffff tesla UNK1670 */
xf_emit(ctx, 1, 0xb8a89888); /* ffffffff tesla UNK1670 */
xf_emit(ctx, 1, 0xf8e8d8c8); /* ffffffff tesla UNK1670 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0x1a); /* 0000001f POLYGON_MODE */
}
static void
nv50_graph_construct_xfer_tp(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
if (device->chipset < 0xa0) {
nv50_graph_construct_xfer_unk84xx(ctx);
nv50_graph_construct_xfer_tprop(ctx);
nv50_graph_construct_xfer_tex(ctx);
nv50_graph_construct_xfer_unk8cxx(ctx);
} else {
nv50_graph_construct_xfer_tex(ctx);
nv50_graph_construct_xfer_tprop(ctx);
nv50_graph_construct_xfer_unk8cxx(ctx);
nv50_graph_construct_xfer_unk84xx(ctx);
}
}
static void
nv50_graph_construct_xfer_mpc(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int i, mpcnt = 2;
switch (device->chipset) {
case 0x98:
case 0xaa:
mpcnt = 1;
break;
case 0x50:
case 0x84:
case 0x86:
case 0x92:
case 0x94:
case 0x96:
case 0xa8:
case 0xac:
mpcnt = 2;
break;
case 0xa0:
case 0xa3:
case 0xa5:
case 0xaf:
mpcnt = 3;
break;
}
for (i = 0; i < mpcnt; i++) {
xf_emit(ctx, 1, 0); /* ff */
xf_emit(ctx, 1, 0x80); /* ffffffff tesla UNK1404 */
xf_emit(ctx, 1, 0x80007004); /* ffffffff tesla UNK12B0 */
xf_emit(ctx, 1, 0x04000400); /* ffffffff */
if (device->chipset >= 0xa0)
xf_emit(ctx, 1, 0xc0); /* 00007fff tesla UNK152C */
xf_emit(ctx, 1, 0x1000); /* 0000ffff tesla UNK0D60 */
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A30 */
if (device->chipset == 0x86 || device->chipset == 0x98 || device->chipset == 0xa8 || IS_NVAAF(device->chipset)) {
xf_emit(ctx, 1, 0xe00); /* 7fff */
xf_emit(ctx, 1, 0x1e00); /* 7fff */
}
xf_emit(ctx, 1, 1); /* 000000ff VP_REG_ALLOC_TEMP */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
if (device->chipset == 0x50)
xf_emit(ctx, 2, 0x1000); /* 7fff tesla UNK141C */
xf_emit(ctx, 1, 1); /* 000000ff GP_REG_ALLOC_TEMP */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff FP_REG_ALLOC_TEMP */
xf_emit(ctx, 1, 2);
if (IS_NVAAF(device->chipset))
xf_emit(ctx, 0xb, 0); /* RO */
else if (device->chipset >= 0xa0)
xf_emit(ctx, 0xc, 0); /* RO */
else
xf_emit(ctx, 0xa, 0); /* RO */
}
xf_emit(ctx, 1, 0x08100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 0); /* ff/3ff */
if (device->chipset >= 0xa0) {
xf_emit(ctx, 1, 0x1fe21); /* 0003ffff tesla UNK0FAC */
}
xf_emit(ctx, 3, 0); /* 7fff, 0, 0 */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0); /* 7/f MULTISAMPLE_SAMPLES_LOG2 */
xf_emit(ctx, 4, 0xffff); /* 0000ffff MSAA_MASK */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 0x10001); /* 00ffffff BLOCK_ALLOC */
xf_emit(ctx, 1, 0x10001); /* ffffffff BLOCKDIM_XY */
xf_emit(ctx, 1, 1); /* 0000ffff BLOCKDIM_Z */
xf_emit(ctx, 1, 0); /* ffffffff SHARED_SIZE */
xf_emit(ctx, 1, 0x1fe21); /* 1ffff/3ffff[NVA0+] tesla UNk0FAC */
xf_emit(ctx, 1, 0); /* ffffffff tesla UNK1A34 */
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 1); /* 0000001f tesla UNK169C */
xf_emit(ctx, 1, 0); /* ff/3ff */
xf_emit(ctx, 1, 0); /* 1 LINKED_TSC */
xf_emit(ctx, 1, 0); /* ff FP_ADDRESS_HIGH */
xf_emit(ctx, 1, 0); /* ffffffff FP_ADDRESS_LOW */
xf_emit(ctx, 1, 0x08100c12); /* 1fffffff FP_INTERPOLANT_CTRL */
xf_emit(ctx, 1, 4);
xf_emit(ctx, 1, 0); /* 000000ff FRAG_COLOR_CLAMP_EN */
xf_emit(ctx, 1, 2);
xf_emit(ctx, 1, 0x11); /* 0000007f RT_FORMAT */
xf_emit(ctx, 7, 0); /* 0000007f RT_FORMAT */
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0xfac6881); /* 0fffffff RT_CONTROL */
xf_emit(ctx, 1, 0);
if (IS_NVA3F(device->chipset))
xf_emit(ctx, 1, 3);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* ffffffff tesla UNK1400 */
xf_emit(ctx, 8, 0);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_RGB */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_RGB */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 2); /* 0000001f BLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 1, 1); /* 0000001f BLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 1, 1);
xf_emit(ctx, 1, 1);
if (IS_NVA3F(device->chipset)) {
xf_emit(ctx, 1, 0);
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_FUNC_SRC_RGB */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_FUNC_DST_RGB */
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 2); /* 0000001f IBLEND_FUNC_SRC_ALPHA */
xf_emit(ctx, 8, 1); /* 0000001f IBLEND_FUNC_DST_ALPHA */
xf_emit(ctx, 8, 1);
xf_emit(ctx, 8, 1);
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 0);
}
xf_emit(ctx, 1, 0);
xf_emit(ctx, 1, 4); /* 000000ff FP_RESULT_COUNT */
/* XXX: demagic this part some day */
if (device->chipset == 0x50)
xf_emit(ctx, 0x3a0, 0);
else if (device->chipset < 0x94)
xf_emit(ctx, 0x3a2, 0);
else if (device->chipset == 0x98 || device->chipset == 0xaa)
xf_emit(ctx, 0x39f, 0);
else
xf_emit(ctx, 0x3a3, 0);
xf_emit(ctx, 1, 0x11); /* 3f/7f DST_FORMAT */
xf_emit(ctx, 1, 0); /* 7 OPERATION */
xf_emit(ctx, 1, 1); /* 1 DST_LINEAR */
xf_emit(ctx, 0x2d, 0);
}
static void
nv50_graph_construct_xfer2(struct nouveau_grctx *ctx)
{
struct nouveau_device *device = ctx->device;
int i;
u32 offset;
u32 units = nv_rd32 (ctx->device, 0x1540);
int size = 0;
offset = (ctx->ctxvals_pos+0x3f)&~0x3f;
if (device->chipset < 0xa0) {
for (i = 0; i < 8; i++) {
ctx->ctxvals_pos = offset + i;
/* that little bugger belongs to csched. No idea
* what it's doing here. */
if (i == 0)
xf_emit(ctx, 1, 0x08100c12); /* FP_INTERPOLANT_CTRL */
if (units & (1 << i))
nv50_graph_construct_xfer_mpc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
}
} else {
/* Strand 0: TPs 0, 1 */
ctx->ctxvals_pos = offset;
/* that little bugger belongs to csched. No idea
* what it's doing here. */
xf_emit(ctx, 1, 0x08100c12); /* FP_INTERPOLANT_CTRL */
if (units & (1 << 0))
nv50_graph_construct_xfer_mpc(ctx);
if (units & (1 << 1))
nv50_graph_construct_xfer_mpc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 1: TPs 2, 3 */
ctx->ctxvals_pos = offset + 1;
if (units & (1 << 2))
nv50_graph_construct_xfer_mpc(ctx);
if (units & (1 << 3))
nv50_graph_construct_xfer_mpc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 2: TPs 4, 5, 6 */
ctx->ctxvals_pos = offset + 2;
if (units & (1 << 4))
nv50_graph_construct_xfer_mpc(ctx);
if (units & (1 << 5))
nv50_graph_construct_xfer_mpc(ctx);
if (units & (1 << 6))
nv50_graph_construct_xfer_mpc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
/* Strand 3: TPs 7, 8, 9 */
ctx->ctxvals_pos = offset + 3;
if (units & (1 << 7))
nv50_graph_construct_xfer_mpc(ctx);
if (units & (1 << 8))
nv50_graph_construct_xfer_mpc(ctx);
if (units & (1 << 9))
nv50_graph_construct_xfer_mpc(ctx);
if ((ctx->ctxvals_pos-offset)/8 > size)
size = (ctx->ctxvals_pos-offset)/8;
}
ctx->ctxvals_pos = offset + size * 8;
ctx->ctxvals_pos = (ctx->ctxvals_pos+0x3f)&~0x3f;
cp_lsr (ctx, offset);
cp_out (ctx, CP_SET_XFER_POINTER);
cp_lsr (ctx, size);
cp_out (ctx, CP_SEEK_2);
cp_out (ctx, CP_XFER_2);
cp_wait(ctx, XFER, BUSY);
}
|
asyan4ik/android_kernel_huawei_h60
|
drivers/gpu/drm/nouveau/core/engine/graph/ctxnv50.c
|
C
|
gpl-2.0
| 111,699
|
<?php
/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
class Google_Service_ServiceNetworking_GoogleCloudServicenetworkingV1ConsumerConfigReservedRange extends Google_Model
{
public $address;
public $ipPrefixLength;
public $name;
public function setAddress($address)
{
$this->address = $address;
}
public function getAddress()
{
return $this->address;
}
public function setIpPrefixLength($ipPrefixLength)
{
$this->ipPrefixLength = $ipPrefixLength;
}
public function getIpPrefixLength()
{
return $this->ipPrefixLength;
}
public function setName($name)
{
$this->name = $name;
}
public function getName()
{
return $this->name;
}
}
|
palasthotel/grid-wordpress-box-social
|
vendor/google/apiclient-services/src/Google/Service/ServiceNetworking/GoogleCloudServicenetworkingV1ConsumerConfigReservedRange.php
|
PHP
|
gpl-2.0
| 1,238
|
/* Copyright (C) 1995,96,97,98,99,2000,2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
Written by Ulrich Drepper <drepper@cygnus.com>, 1995.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#include <assert.h>
#include <langinfo.h>
#include <locale.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef STRING_TYPE
# define STRING_TYPE char
# define USTRING_TYPE unsigned char
# ifdef USE_IN_EXTENDED_LOCALE_MODEL
# define STRCOLL __strcoll_l
# else
# define STRCOLL strcoll
# endif
# define STRCMP strcmp
# define STRLEN strlen
# define WEIGHT_H "../locale/weight.h"
# define SUFFIX MB
# define L(arg) arg
#endif
#define CONCAT(a,b) CONCAT1(a,b)
#define CONCAT1(a,b) a##b
#include "../locale/localeinfo.h"
#ifndef USE_IN_EXTENDED_LOCALE_MODEL
int
STRCOLL (s1, s2)
const STRING_TYPE *s1;
const STRING_TYPE *s2;
#else
int
STRCOLL (s1, s2, l)
const STRING_TYPE *s1;
const STRING_TYPE *s2;
__locale_t l;
#endif
{
#ifdef USE_IN_EXTENDED_LOCALE_MODEL
struct locale_data *current = l->__locales[LC_COLLATE];
uint_fast32_t nrules = current->values[_NL_ITEM_INDEX (_NL_COLLATE_NRULES)].word;
#else
uint_fast32_t nrules = _NL_CURRENT_WORD (LC_COLLATE, _NL_COLLATE_NRULES);
#endif
/* We don't assign the following values right away since it might be
unnecessary in case there are no rules. */
const unsigned char *rulesets;
const int32_t *table;
const USTRING_TYPE *weights;
const USTRING_TYPE *extra;
const int32_t *indirect;
uint_fast32_t pass;
int result = 0;
const USTRING_TYPE *us1;
const USTRING_TYPE *us2;
size_t s1len;
size_t s2len;
int32_t *idx1arr;
int32_t *idx2arr;
unsigned char *rule1arr;
unsigned char *rule2arr;
size_t idx1max;
size_t idx2max;
size_t idx1cnt;
size_t idx2cnt;
size_t idx1now;
size_t idx2now;
size_t backw1_stop;
size_t backw2_stop;
size_t backw1;
size_t backw2;
int val1;
int val2;
int position;
int seq1len;
int seq2len;
int use_malloc;
#include WEIGHT_H
if (nrules == 0)
return STRCMP (s1, s2);
#ifdef USE_IN_EXTENDED_LOCALE_MODEL
rulesets = (const unsigned char *)
current->values[_NL_ITEM_INDEX (_NL_COLLATE_RULESETS)].string;
table = (const int32_t *)
current->values[_NL_ITEM_INDEX (CONCAT(_NL_COLLATE_TABLE,SUFFIX))].string;
weights = (const USTRING_TYPE *)
current->values[_NL_ITEM_INDEX (CONCAT(_NL_COLLATE_WEIGHT,SUFFIX))].string;
extra = (const USTRING_TYPE *)
current->values[_NL_ITEM_INDEX (CONCAT(_NL_COLLATE_EXTRA,SUFFIX))].string;
indirect = (const int32_t *)
current->values[_NL_ITEM_INDEX (CONCAT(_NL_COLLATE_INDIRECT,SUFFIX))].string;
#else
rulesets = (const unsigned char *)
_NL_CURRENT (LC_COLLATE, _NL_COLLATE_RULESETS);
table = (const int32_t *)
_NL_CURRENT (LC_COLLATE, CONCAT(_NL_COLLATE_TABLE,SUFFIX));
weights = (const USTRING_TYPE *)
_NL_CURRENT (LC_COLLATE, CONCAT(_NL_COLLATE_WEIGHT,SUFFIX));
extra = (const USTRING_TYPE *)
_NL_CURRENT (LC_COLLATE, CONCAT(_NL_COLLATE_EXTRA,SUFFIX));
indirect = (const int32_t *)
_NL_CURRENT (LC_COLLATE, CONCAT(_NL_COLLATE_INDIRECT,SUFFIX));
#endif
use_malloc = 0;
assert (((uintptr_t) table) % __alignof__ (table[0]) == 0);
assert (((uintptr_t) weights) % __alignof__ (weights[0]) == 0);
assert (((uintptr_t) extra) % __alignof__ (extra[0]) == 0);
assert (((uintptr_t) indirect) % __alignof__ (indirect[0]) == 0);
/* We need this a few times. */
s1len = STRLEN (s1);
s2len = STRLEN (s2);
/* We need the elements of the strings as unsigned values since they
are used as indeces. */
us1 = (const USTRING_TYPE *) s1;
us2 = (const USTRING_TYPE *) s2;
/* Perform the first pass over the string and while doing this find
and store the weights for each character. Since we want this to
be as fast as possible we are using `alloca' to store the temporary
values. But since there is no limit on the length of the string
we have to use `malloc' if the string is too long. We should be
very conservative here.
Please note that the localedef programs makes sure that `position'
is not used at the first level. */
if (s1len + s2len >= 16384)
{
idx1arr = (int32_t *) malloc ((s1len + s2len) * (sizeof (int32_t) + 1));
idx2arr = &idx1arr[s1len];
rule1arr = (unsigned char *) &idx2arr[s2len];
rule2arr = &rule1arr[s1len];
if (idx1arr == NULL)
/* No memory. Well, go with the stack then.
XXX Once this implementation is stable we will handle this
differently. Instead of precomputing the indeces we will
do this in time. This means, though, that this happens for
every pass again. */
goto try_stack;
use_malloc = 1;
}
else
{
try_stack:
idx1arr = (int32_t *) alloca (s1len * sizeof (int32_t));
idx2arr = (int32_t *) alloca (s2len * sizeof (int32_t));
rule1arr = (unsigned char *) alloca (s1len);
rule2arr = (unsigned char *) alloca (s2len);
}
idx1cnt = 0;
idx2cnt = 0;
idx1max = 0;
idx2max = 0;
idx1now = 0;
idx2now = 0;
backw1_stop = ~0ul;
backw2_stop = ~0ul;
backw1 = ~0ul;
backw2 = ~0ul;
seq1len = 0;
seq2len = 0;
position = rulesets[0] & sort_position;
while (1)
{
val1 = 0;
val2 = 0;
/* Get the next non-IGNOREd element for string `s1'. */
if (seq1len == 0)
do
{
++val1;
if (backw1_stop != ~0ul)
{
/* The is something pushed. */
if (backw1 == backw1_stop)
{
/* The last pushed character was handled. Continue
with forward characters. */
if (idx1cnt < idx1max)
idx1now = idx1cnt;
else
/* Nothing anymore. The backward sequence ended with
the last sequence in the string. Note that seq1len
is still zero. */
break;
}
else
idx1now = --backw1;
}
else
{
backw1_stop = idx1max;
while (*us1 != L('\0'))
{
int32_t tmp = findidx (&us1);
rule1arr[idx1max] = tmp >> 24;
idx1arr[idx1max] = tmp & 0xffffff;
idx1cnt = idx1max++;
if ((rulesets[rule1arr[idx1cnt] * nrules]
& sort_backward) == 0)
/* No more backward characters to push. */
break;
++idx1cnt;
}
if (backw1_stop >= idx1cnt)
{
/* No sequence at all or just one. */
if (idx1cnt == idx1max || backw1_stop > idx1cnt)
/* Note that seq1len is still zero. */
break;
backw1_stop = ~0ul;
idx1now = idx1cnt;
}
else
/* We pushed backward sequences. */
idx1now = backw1 = idx1cnt - 1;
}
}
while ((seq1len = weights[idx1arr[idx1now]++]) == 0);
/* And the same for string `s2'. */
if (seq2len == 0)
do
{
++val2;
if (backw2_stop != ~0ul)
{
/* The is something pushed. */
if (backw2 == backw2_stop)
{
/* The last pushed character was handled. Continue
with forward characters. */
if (idx2cnt < idx2max)
idx2now = idx2cnt;
else
/* Nothing anymore. The backward sequence ended with
the last sequence in the string. Note that seq2len
is still zero. */
break;
}
else
idx2now = --backw2;
}
else
{
backw2_stop = idx2max;
while (*us2 != L('\0'))
{
int32_t tmp = findidx (&us2);
rule2arr[idx2max] = tmp >> 24;
idx2arr[idx2max] = tmp & 0xffffff;
idx2cnt = idx2max++;
if ((rulesets[rule2arr[idx2cnt] * nrules]
& sort_backward) == 0)
/* No more backward characters to push. */
break;
++idx2cnt;
}
if (backw2_stop >= idx2cnt)
{
/* No sequence at all or just one. */
if (idx2cnt == idx2max || backw2_stop > idx2cnt)
/* Note that seq1len is still zero. */
break;
backw2_stop = ~0ul;
idx2now = idx2cnt;
}
else
/* We pushed backward sequences. */
idx2now = backw2 = idx2cnt - 1;
}
}
while ((seq2len = weights[idx2arr[idx2now]++]) == 0);
/* See whether any or both strings are empty. */
if (seq1len == 0 || seq2len == 0)
{
if (seq1len == seq2len)
/* Both ended. So far so good, both strings are equal at the
first level. */
break;
/* This means one string is shorter than the other. Find out
which one and return an appropriate value. */
result = seq1len == 0 ? -1 : 1;
goto free_and_return;
}
/* Test for position if necessary. */
if (position && val1 != val2)
{
result = val1 - val2;
goto free_and_return;
}
/* Compare the two sequences. */
do
{
if (weights[idx1arr[idx1now]] != weights[idx2arr[idx2now]])
{
/* The sequences differ. */
result = weights[idx1arr[idx1now]] - weights[idx2arr[idx2now]];
goto free_and_return;
}
/* Increment the offsets. */
++idx1arr[idx1now];
++idx2arr[idx2now];
--seq1len;
--seq2len;
}
while (seq1len > 0 && seq2len > 0);
if (position && seq1len != seq2len)
{
result = seq1len - seq2len;
goto free_and_return;
}
}
/* Now the remaining passes over the weights. We now use the
indeces we found before. */
for (pass = 1; pass < nrules; ++pass)
{
/* We assume that if a rule has defined `position' in one section
this is true for all of them. */
idx1cnt = 0;
idx2cnt = 0;
backw1_stop = ~0ul;
backw2_stop = ~0ul;
backw1 = ~0ul;
backw2 = ~0ul;
position = rulesets[rule1arr[0] * nrules + pass] & sort_position;
while (1)
{
val1 = 0;
val2 = 0;
/* Get the next non-IGNOREd element for string `s1'. */
if (seq1len == 0)
do
{
++val1;
if (backw1_stop != ~0ul)
{
/* The is something pushed. */
if (backw1 == backw1_stop)
{
/* The last pushed character was handled. Continue
with forward characters. */
if (idx1cnt < idx1max)
idx1now = idx1cnt;
else
{
/* Nothing anymore. The backward sequence
ended with the last sequence in the string. */
idx1now = ~0ul;
break;
}
}
else
idx1now = --backw1;
}
else
{
backw1_stop = idx1cnt;
while (idx1cnt < idx1max)
{
if ((rulesets[rule1arr[idx1cnt] * nrules + pass]
& sort_backward) == 0)
/* No more backward characters to push. */
break;
++idx1cnt;
}
if (backw1_stop == idx1cnt)
{
/* No sequence at all or just one. */
if (idx1cnt == idx1max)
/* Note that seq1len is still zero. */
break;
backw1_stop = ~0ul;
idx1now = idx1cnt++;
}
else
/* We pushed backward sequences. */
idx1now = backw1 = idx1cnt - 1;
}
}
while ((seq1len = weights[idx1arr[idx1now]++]) == 0);
/* And the same for string `s2'. */
if (seq2len == 0)
do
{
++val2;
if (backw2_stop != ~0ul)
{
/* The is something pushed. */
if (backw2 == backw2_stop)
{
/* The last pushed character was handled. Continue
with forward characters. */
if (idx2cnt < idx2max)
idx2now = idx2cnt;
else
{
/* Nothing anymore. The backward sequence
ended with the last sequence in the string. */
idx2now = ~0ul;
break;
}
}
else
idx2now = --backw2;
}
else
{
backw2_stop = idx2cnt;
while (idx2cnt < idx2max)
{
if ((rulesets[rule2arr[idx2cnt] * nrules + pass]
& sort_backward) == 0)
/* No more backward characters to push. */
break;
++idx2cnt;
}
if (backw2_stop == idx2cnt)
{
/* No sequence at all or just one. */
if (idx2cnt == idx2max)
/* Note that seq2len is still zero. */
break;
backw2_stop = ~0ul;
idx2now = idx2cnt++;
}
else
/* We pushed backward sequences. */
idx2now = backw2 = idx2cnt - 1;
}
}
while ((seq2len = weights[idx2arr[idx2now]++]) == 0);
/* See whether any or both strings are empty. */
if (seq1len == 0 || seq2len == 0)
{
if (seq1len == seq2len)
/* Both ended. So far so good, both strings are equal
at this level. */
break;
/* This means one string is shorter than the other. Find out
which one and return an appropriate value. */
result = seq1len == 0 ? -1 : 1;
goto free_and_return;
}
/* Test for position if necessary. */
if (position && val1 != val2)
{
result = val1 - val2;
goto free_and_return;
}
/* Compare the two sequences. */
do
{
if (weights[idx1arr[idx1now]] != weights[idx2arr[idx2now]])
{
/* The sequences differ. */
result = (weights[idx1arr[idx1now]]
- weights[idx2arr[idx2now]]);
goto free_and_return;
}
/* Increment the offsets. */
++idx1arr[idx1now];
++idx2arr[idx2now];
--seq1len;
--seq2len;
}
while (seq1len > 0 && seq2len > 0);
if (position && seq1len != seq2len)
{
result = seq1len - seq2len;
goto free_and_return;
}
}
}
/* Free the memory if needed. */
free_and_return:
if (use_malloc)
free (idx1arr);
return result;
}
|
nslu2/glibc
|
string/strcoll.c
|
C
|
gpl-2.0
| 14,056
|
DELETE FROM 'playlists' WHERE id == :id;
|
galaxy001/Play
|
SQL/delete_playlist.sql
|
SQL
|
gpl-2.0
| 41
|
<?php
$HOME = realpath(dirname(__FILE__)) . "/../../../..";
require_once($HOME . "/tests/class/Common_TestCase.php");
/*
* This file is part of EC-CUBE
*
* Copyright(c) 2000-2014 LOCKON CO.,LTD. All Rights Reserved.
*
* http://www.lockon.co.jp/
*
* 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.
*/
/**
* SC_Utils::sfSwapArray()のテストクラス.
*
*
* @author Hiroko Tamagawa
* @version $Id: SC_Utils_sfSwapArrayTest.php 23546 2014-06-12 14:47:59Z shutta $
*/
class SC_Utils_sfSwapArrayTest extends Common_TestCase
{
protected function setUp()
{
parent::setUp();
}
protected function tearDown()
{
parent::tearDown();
}
/////////////////////////////////////////
public function testSfSwapArray_カラム名ありの指定の場合_キーに名称が入る()
{
$input_array = array(
array('id' => '1001', 'name' => 'name1001'),
array('id' => '1002', 'name' => 'name1002')
);
$this->expected = array(
'id' => array('1001', '1002'),
'name' => array('name1001', 'name1002')
);
$this->actual = SC_Utils::sfSwapArray($input_array);
$this->verify();
}
public function testSfSwapArray_カラム名なしの指定の場合_キーに名称が入らない()
{
$input_array = array(
array('id' => '1001', 'name' => 'name1001'),
array('id' => '1002', 'name' => 'name1002')
);
$this->expected = array(
array('1001', '1002'),
array('name1001', 'name1002')
);
$this->actual = SC_Utils::sfSwapArray($input_array, false);
$this->verify();
}
//////////////////////////////////////////
}
|
shoheiworks/Labo-EcCube
|
tests/class/util/SC_Utils/SC_Utils_sfSwapArrayTest.php
|
PHP
|
gpl-2.0
| 2,296
|
/*
* Scale.cpp - implementation of scale class
*
* Copyright (c) 2020 Martin Pavelek <he29.HS/at/gmail.com>
*
* This file is part of LMMS - https://lmms.io
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public
* License along with this program (see COPYING); if not, write to the
* Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301 USA.
*
*/
#include "Scale.h"
#include <QDomElement>
Interval::Interval(float cents) :
m_numerator(0),
m_denominator(0),
m_cents(cents)
{
m_ratio = powf(2.f, m_cents / 1200.f);
}
Interval::Interval(uint32_t numerator, uint32_t denominator) :
m_numerator(numerator),
m_denominator(denominator > 0 ? denominator : 1),
m_cents(0)
{
m_ratio = static_cast<float>(m_numerator) / m_denominator;
}
void Interval::saveSettings(QDomDocument &document, QDomElement &element)
{
if (m_denominator > 0)
{
element.setAttribute("num", QString::number(m_numerator));
element.setAttribute("den", QString::number(m_denominator));
}
else
{
element.setAttribute("cents", QString::number(m_cents));
}
}
void Interval::loadSettings(const QDomElement &element)
{
m_numerator = element.attribute("num", "0").toULong();
m_denominator = element.attribute("den", "0").toULong();
m_cents = element.attribute("cents", "0").toDouble();
if (m_denominator) {m_ratio = static_cast<float>(m_numerator) / m_denominator;}
else {m_ratio = powf(2.f, m_cents / 1200.f);}
}
Scale::Scale() :
m_description(tr("empty"))
{
m_intervals.push_back(Interval(1, 1));
}
Scale::Scale(QString description, std::vector<Interval> intervals) :
m_description(description),
m_intervals(std::move(intervals))
{
}
QString Scale::getDescription() const
{
return m_description;
}
void Scale::setDescription(QString description)
{
m_description = description;
}
void Scale::saveSettings(QDomDocument &document, QDomElement &element)
{
element.setAttribute("description", m_description);
for (auto& interval : m_intervals)
{
interval.saveState(document, element);
}
}
void Scale::loadSettings(const QDomElement &element)
{
m_description = element.attribute("description");
QDomNode node = element.firstChild();
m_intervals.clear();
for (int i = 0; !node.isNull(); i++)
{
Interval temp;
temp.restoreState(node.toElement());
m_intervals.push_back(temp);
node = node.nextSibling();
}
}
|
zonkmachine/lmms
|
src/core/Scale.cpp
|
C++
|
gpl-2.0
| 2,889
|
<?php
$dir = dirname(dirname(__FILE__));
function json2Array($json) {return json_decode($json, 1);}
function getCurrentAlias(){
$active = JFactory::getApplication()->getMenu()->getActive();
if($active) {
return ($active->alias);
}
}
global $s5_vertex_version, $s5_template_name;
$s5_vertex_version = '1.0';
function getTemplateName($template) {
$db = JFactory::getDBO();
$query = "SELECT * FROM #__template_styles WHERE template = '$template';";
$db->setQuery($query);
$result = $db->loadAssocList();
$titles = array();
$i = 0;
$home_id = 0;
foreach($result as $k => $style) {
$ids[] = $style['id'];
$titles[$style['id']] = $style['title'];
if($style['home'] == 1) {
$home_id = $style['id'];
}
$i++;
}
$ids = implode(",", $ids);
$u_main = JURI::root();
$u = JFactory::getURI();
$u = $u->toString();
$u = explode($u_main, $u);
$com = $u[1];
$alias = getCurrentAlias();
$query2 = "SELECT * FROM #__menu WHERE template_style_id IN (". $ids .") AND alias = '$alias'";
$db->setQuery($query2);
$result2 = $db->loadAssocList();
$i2 = 0;
$id = 0;
//print_r($result2);
foreach($result2 as $k => $item) {
if($item['link'] == $com || preg_match("/" . $item['alias'] . "/i", $alias)) {
$id = $item['template_style_id'];
$i2++;
}
}
//print_r($id);
if($i2 == 0) {
$id = $home_id;
}
//print_r($titles[$id]);
return $titles[$id];
}
function getVersion($dir) {
global $s5_vertex_version;
if(file_exists($dir . '/xml/Specific.xml')) {
$templateXml = simplexml_load_file($dir . '/xml/Specific.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
$s5_vertex_version = $templateXml->version;
} else {
exit('Template XML file not found');
}
}
function getJoomlaParams($dir = false) {
$admin_options = array();
if(file_exists($dir . '/xml/Specific.xml')) {
$templateXml = simplexml_load_file($dir . '/xml/Specific.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
$fieldsets = $templateXml->config->fields;
foreach($fieldsets->fieldset as $key => $fieldset){
foreach($fieldset as $key => $item){
$admin_options[(string)$item['name'][0]] = (string)$item['default'][0];
}
}
} else {
exit('Template XML file not found');
}
return $admin_options;
}
function getVertexParams($dir = false){
if(file_exists($dir . '/xml/Vertex.xml')) {
$vertexXml = simplexml_load_file($dir . '/xml/Vertex.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
$admin_options = array();
$fieldsets = $vertexXml->admin;
foreach($fieldsets->fieldset as $key => $fieldset){
foreach($fieldset as $key => $item){
$admin_options[(string)$item['name'][0]] = (string)$item['default'][0];
}
}
} else {
exit('Vertex XML file not found');
}
return $admin_options;
}
function handleJSONFile($file = false, $style = false, $dir = false) {
getVersion($dir);
$config = array();
if(file_exists($dir . '/' . $file)) {
$check = file_get_contents($dir . '/' . $file);
$file_data = json2Array($check);
if(isset($file_data['vertexFramework'][$style]) && is_array($file_data['vertexFramework'][$style])) {
$defaults = getJoomlaParams($dir);
$defaults = array_merge($defaults, getVertexParams($dir));
foreach($defaults as $key => $val){
$key = str_replace('xml_', '', $key);
$config[$key] = '';
}
foreach($file_data['vertexFramework'][$style] as $key => $val){
$key = str_replace('xml_', '', $key);
$config[$key] = preg_replace('/\\\/', '', $val);
}
} else {
$defaults = getJoomlaParams($dir);
$defaults = array_merge($defaults, getVertexParams($dir));
foreach($defaults as $key => $val){
$key = str_replace('xml_', '', $key);
$config[$key] = preg_replace('/\\\/', '', $val);
}
}
} else {
$defaults = getJoomlaParams($dir);
$defaults = array_merge($defaults, getVertexParams($dir));
foreach($defaults as $key => $val){
$key = str_replace('xml_', '', $key);
$config[$key] = preg_replace('/\\\/', '', $val);
}
}
return $config;
}
if (file_exists($dir . '/templateDetails.xml')) {
$template_xml = simplexml_load_file($dir . '/templateDetails.xml', 'SimpleXMLElement', LIBXML_NOCDATA);
$template_name = $template_xml->name;
$template_date = $template_xml->creationDate;
} else {
$template_name = 'blank';
}
$style_name = getTemplateName($template_name);
$file = 'vertex.json';
$params = handleJSONFile($file, $style_name, $dir);
foreach($params as $k => $v){$$k = $v;}
$s5_lr_tab1_text = str_replace(" "," ",$s5_lr_tab1_text);
$s5_lr_tab2_text = str_replace(" "," ",$s5_lr_tab2_text);
$s5_urlforSEO = $s5_seourl;
?>
|
lama604/cis4402
|
templates/shape5_vertex/vertex/parameters.php
|
PHP
|
gpl-2.0
| 4,750
|
# This file is part of Buildbot. Buildbot is free software: you can
# redistribute it and/or modify it under the terms of the GNU General Public
# License as published by the Free Software Foundation, version 2.
#
# This program is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# this program; if not, write to the Free Software Foundation, Inc., 51
# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# Copyright Buildbot Team Members
import os
from twisted.cred import credentials
from twisted.internet import defer
from twisted.internet import reactor
from twisted.internet.endpoints import clientFromString
from twisted.python import log
from twisted.python import util
from twisted.spread import pb
from twisted.trial import unittest
import buildbot
from buildbot import config
from buildbot import pbmanager
from buildbot import worker
from buildbot.process import botmaster
from buildbot.process import builder
from buildbot.process import factory
from buildbot.test.fake import fakemaster
from buildbot.test.util.misc import TestReactorMixin
from buildbot.util.eventual import eventually
from buildbot.worker import manager as workermanager
PKI_DIR = util.sibpath(__file__, 'pki')
class FakeWorkerForBuilder(pb.Referenceable):
"""
Fake worker-side WorkerForBuilder object
"""
class FakeWorkerWorker(pb.Referenceable):
"""
Fake worker-side Worker object
@ivar master_persp: remote perspective on the master
"""
def __init__(self, callWhenBuilderListSet):
self.callWhenBuilderListSet = callWhenBuilderListSet
self.master_persp = None
self._detach_deferreds = []
self._detached = False
def waitForDetach(self):
if self._detached:
return defer.succeed(None)
d = defer.Deferred()
self._detach_deferreds.append(d)
return d
def setMasterPerspective(self, persp):
self.master_persp = persp
# clear out master_persp on disconnect
def clear_persp():
self.master_persp = None
persp.broker.notifyOnDisconnect(clear_persp)
def fire_deferreds():
self._detached = True
self._detach_deferreds, deferreds = None, self._detach_deferreds
for d in deferreds:
d.callback(None)
persp.broker.notifyOnDisconnect(fire_deferreds)
def remote_print(self, message):
log.msg("WORKER-SIDE: remote_print(%r)" % (message,))
def remote_getWorkerInfo(self):
return {
'info': 'here',
'worker_commands': {
'x': 1,
},
'numcpus': 1,
'none': None,
'os_release': b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(),
b'\xe3\x83\xaa\xe3\x83\xaa\xe3\x83\xbc\xe3\x82\xb9\xe3'
b'\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode():
b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode(),
}
def remote_getVersion(self):
return buildbot.version
def remote_getCommands(self):
return {'x': 1}
def remote_setBuilderList(self, builder_info):
builder_names = [n for n, dir in builder_info]
slbuilders = [FakeWorkerForBuilder() for n in builder_names]
eventually(self.callWhenBuilderListSet)
return dict(zip(builder_names, slbuilders))
class FakeBuilder(builder.Builder):
def attached(self, worker, commands):
return defer.succeed(None)
def detached(self, worker):
pass
def getOldestRequestTime(self):
return 0
def maybeStartBuild(self):
return defer.succeed(None)
class MyWorker(worker.Worker):
def attached(self, conn):
self.detach_d = defer.Deferred()
return super().attached(conn)
def detached(self):
super().detached()
self.detach_d, d = None, self.detach_d
d.callback(None)
class TestWorkerComm(unittest.TestCase, TestReactorMixin):
"""
Test handling of connections from workers as integrated with
- Twisted Spread
- real TCP connections.
- PBManager
@ivar master: fake build master
@ivar pbamanger: L{PBManager} instance
@ivar botmaster: L{BotMaster} instance
@ivar worker: master-side L{Worker} instance
@ivar workerworker: worker-side L{FakeWorkerWorker} instance
@ivar port: TCP port to connect to
@ivar server_connection_string: description string for the server endpoint
@ivar client_connection_string_tpl: description string template for the client
endpoint (expects to passed 'port')
@ivar endpoint: endpoint controlling the outbound connection
from worker to master
"""
@defer.inlineCallbacks
def setUp(self):
self.setUpTestReactor()
self.master = fakemaster.make_master(self, wantMq=True, wantData=True,
wantDb=True)
# set the worker port to a loopback address with unspecified
# port
self.pbmanager = self.master.pbmanager = pbmanager.PBManager()
yield self.pbmanager.setServiceParent(self.master)
# remove the fakeServiceParent from fake service hierarchy, and replace
# by a real one
yield self.master.workers.disownServiceParent()
self.workers = self.master.workers = workermanager.WorkerManager(
self.master)
yield self.workers.setServiceParent(self.master)
self.botmaster = botmaster.BotMaster()
yield self.botmaster.setServiceParent(self.master)
self.master.botmaster = self.botmaster
self.master.data.updates.workerConfigured = lambda *a, **k: None
yield self.master.startService()
self.buildworker = None
self.port = None
self.workerworker = None
self.endpoint = None
self.broker = None
self._detach_deferreds = []
# patch in our FakeBuilder for the regular Builder class
self.patch(botmaster, 'Builder', FakeBuilder)
self.server_connection_string = "tcp:0:interface=127.0.0.1"
self.client_connection_string_tpl = "tcp:host=127.0.0.1:port={port}"
def tearDown(self):
if self.broker:
del self.broker
if self.endpoint:
del self.endpoint
deferreds = self._detach_deferreds + [
self.pbmanager.stopService(),
self.botmaster.stopService(),
self.workers.stopService(),
]
# if the worker is still attached, wait for it to detach, too
if self.buildworker and self.buildworker.detach_d:
deferreds.append(self.buildworker.detach_d)
return defer.gatherResults(deferreds)
@defer.inlineCallbacks
def addWorker(self, **kwargs):
"""
Create a master-side worker instance and add it to the BotMaster
@param **kwargs: arguments to pass to the L{Worker} constructor.
"""
self.buildworker = MyWorker("testworker", "pw", **kwargs)
# reconfig the master to get it set up
new_config = self.master.config
new_config.protocols = {"pb": {"port": self.server_connection_string}}
new_config.workers = [self.buildworker]
new_config.builders = [config.BuilderConfig(
name='bldr',
workername='testworker', factory=factory.BuildFactory())]
yield self.botmaster.reconfigServiceWithBuildbotConfig(new_config)
yield self.workers.reconfigServiceWithBuildbotConfig(new_config)
# as part of the reconfig, the worker registered with the pbmanager, so
# get the port it was assigned
self.port = self.buildworker.registration.getPBPort()
def connectWorker(self, waitForBuilderList=True):
"""
Connect a worker the master via PB
@param waitForBuilderList: don't return until the setBuilderList has
been called
@returns: L{FakeWorkerWorker} and a Deferred that will fire when it
is detached; via deferred
"""
factory = pb.PBClientFactory()
creds = credentials.UsernamePassword(b"testworker", b"pw")
setBuilderList_d = defer.Deferred()
workerworker = FakeWorkerWorker(
lambda: setBuilderList_d.callback(None))
login_d = factory.login(creds, workerworker)
@login_d.addCallback
def logged_in(persp):
workerworker.setMasterPerspective(persp)
# set up to hear when the worker side disconnects
workerworker.detach_d = defer.Deferred()
persp.broker.notifyOnDisconnect(
lambda: workerworker.detach_d.callback(None))
self._detach_deferreds.append(workerworker.detach_d)
return workerworker
self.endpoint = clientFromString(
reactor, self.client_connection_string_tpl.format(port=self.port))
connected_d = self.endpoint.connect(factory)
dlist = [connected_d, login_d]
if waitForBuilderList:
dlist.append(setBuilderList_d)
d = defer.DeferredList(dlist,
consumeErrors=True, fireOnOneErrback=True)
d.addCallback(lambda _: workerworker)
return d
def workerSideDisconnect(self, worker):
"""Disconnect from the worker side"""
worker.master_persp.broker.transport.loseConnection()
@defer.inlineCallbacks
def test_connect_disconnect(self):
"""Test a single worker connecting and disconnecting."""
yield self.addWorker()
# connect
worker = yield self.connectWorker()
# disconnect
self.workerSideDisconnect(worker)
# wait for the resulting detach
yield worker.waitForDetach()
@defer.inlineCallbacks
def test_tls_connect_disconnect(self):
"""Test with TLS or SSL endpoint.
According to the deprecation note for the SSL client endpoint,
the TLS endpoint is supported from Twistd 16.0.
TODO add certificate verification (also will require some conditionals
on various versions, including PyOpenSSL, service_identity. The CA used
to generate the testing cert is in ``PKI_DIR/ca``
"""
def escape_colon(path):
# on windows we can't have \ as it serves as the escape character for :
return path.replace('\\', '/').replace(':', '\\:')
self.server_connection_string = (
"ssl:port=0:certKey={pub}:privateKey={priv}:" +
"interface=127.0.0.1").format(
pub=escape_colon(os.path.join(PKI_DIR, '127.0.0.1.crt')),
priv=escape_colon(os.path.join(PKI_DIR, '127.0.0.1.key')))
self.client_connection_string_tpl = "ssl:host=127.0.0.1:port={port}"
yield self.addWorker()
# connect
worker = yield self.connectWorker()
# disconnect
self.workerSideDisconnect(worker)
# wait for the resulting detach
yield worker.waitForDetach()
@defer.inlineCallbacks
def test_worker_info(self):
yield self.addWorker()
worker = yield self.connectWorker()
props = self.buildworker.info
# check worker info passing
self.assertEqual(props.getProperty("info"),
"here")
# check worker info passing with UTF-8
self.assertEqual(props.getProperty("os_release"),
b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode())
self.assertEqual(props.getProperty(b'\xe3\x83\xaa\xe3\x83\xaa\xe3\x83\xbc\xe3\x82'
b'\xb9\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode()),
b'\xe3\x83\x86\xe3\x82\xb9\xe3\x83\x88'.decode())
self.assertEqual(props.getProperty("none"), None)
self.assertEqual(props.getProperty("numcpus"), 1)
self.workerSideDisconnect(worker)
yield worker.waitForDetach()
@defer.inlineCallbacks
def _test_duplicate_worker(self):
yield self.addWorker()
# connect first worker
worker1 = yield self.connectWorker()
# connect second worker; this should fail
try:
yield self.connectWorker(waitForBuilderList=False)
connect_failed = False
except Exception:
connect_failed = True
self.assertTrue(connect_failed)
# disconnect both and wait for that to percolate
self.workerSideDisconnect(worker1)
yield worker1.waitForDetach()
# flush the exception logged for this on the master
self.assertEqual(len(self.flushLoggedErrors(RuntimeError)), 1)
@defer.inlineCallbacks
def _test_duplicate_worker_old_dead(self):
yield self.addWorker()
# connect first worker
worker1 = yield self.connectWorker()
# monkeypatch that worker to fail with PBConnectionLost when its
# remote_print method is called
def remote_print(message):
worker1.master_persp.broker.transport.loseConnection()
raise pb.PBConnectionLost("fake!")
worker1.remote_print = remote_print
# connect second worker; this should succeed, and the old worker
# should be disconnected.
worker2 = yield self.connectWorker()
# disconnect both and wait for that to percolate
self.workerSideDisconnect(worker2)
yield worker1.waitForDetach()
# flush the exception logged for this on the worker
self.assertEqual(len(self.flushLoggedErrors(pb.PBConnectionLost)), 1)
|
tardyp/buildbot
|
master/buildbot/test/integration/test_worker_comm.py
|
Python
|
gpl-2.0
| 13,868
|
<?php
/**
* Portfolio justified grid shortcode.
*
*/
// File Security Check
if ( ! defined( 'ABSPATH' ) ) { exit; }
if ( ! class_exists( 'DT_Shortcode_Portfolio_Jgrid', false ) ) {
class DT_Shortcode_Portfolio_Jgrid extends DT_Masonry_Posts_Shortcode {
protected $shortcode_name = 'dt_portfolio_jgrid';
protected $post_type = 'dt_portfolio';
protected $taxonomy = 'dt_portfolio_category';
public static function get_instance() {
static $instance = null;
if ( null === $instance ) {
$instance = new self();
}
return $instance;
}
protected function __construct() {
add_shortcode( $this->shortcode_name, array( $this, 'shortcode' ) );
}
public function shortcode( $atts, $content = null ) {
parent::setup( $atts, $content );
// vc inline dummy
if ( $this->vc_is_inline ) {
$terms_title = _x( 'Display categories', 'vc inline dummy', 'the7mk2' );
return $this->vc_inline_dummy( array(
'class' => 'dt_vc-portfolio_jgrid',
'title' => _x( 'Portfolio Justified Grid', 'vc inline dummy', 'the7mk2' ),
'fields' => array(
$terms_title => presscore_get_terms_list_by_slug( array( 'slugs' => $this->atts['category'], 'taxonomy' => $this->taxonomy ) )
)
) );
}
return $this->shortcode_html();
}
protected function shortcode_html() {
$dt_query = $this->get_posts_by_terms( array(
'orderby' => $this->atts['orderby'],
'order' => $this->atts['order'],
'number' => $this->atts['number'],
'select' => $this->atts['select'],
'category' => $this->atts['category']
) );
$output = '';
if ( $dt_query->have_posts() ) {
$this->backup_post_object();
$this->backup_theme_config();
$this->setup_config();
$output = $this->the_loop( array(
'masonry_container_class' => array( 'wf-container', 'dt-portfolio-shortcode', 'jgrid-shortcode' ),
'post_template_callback' => array( $this, 'post_template' ),
'query' => $dt_query,
'full_width' => $this->atts['full_width'],
'select' => $this->atts['select'],
'show_filter' => $this->atts['show_filter'],
'posts_per_page' => $this->atts['posts_per_page']
) );
$this->restore_theme_config();
$this->restore_post_object();
}
return $output;
}
protected function post_template() {
presscore_populate_portfolio_config();
dt_get_template_part( 'portfolio/masonry/portfolio-masonry-post' );
}
protected function sanitize_attributes( &$atts ) {
$default_atts = array(
'category' => '',
'order' => 'desc',
'orderby' => 'date',
'number' => '12',
'show_title' => '',
'show_excerpt' => '',
'show_details' => '',
'show_link' => '',
'show_zoom' => '',
'show_categories' => '',
'show_date' => '',
'show_author' => '',
'show_comments' => '',
'target_height' => '240',
'hide_last_row' => '',
'padding' => '20',
'descriptions' => 'on_hover_centered',
'hover_bg_color' => 'accent',
'bg_under_projects' => 'disabled',
'content_aligment' => 'left',
'hover_animation' => 'fade',
'hover_content_visibility' => 'on_hover',
'loading_effect' => 'none',
'proportion' => '',
'full_width' => '',
'show_filter' => '',
'posts_per_page' => '-1'
);
$attributes = shortcode_atts( $default_atts, $atts );
// sanitize attributes
$attributes['descriptions'] = sanitize_key( $attributes['descriptions'] );
$attributes['descriptions'] = str_replace( 'hover', 'hoover', $attributes['descriptions'] );
$attributes['hover_content_visibility'] = sanitize_key( $attributes['hover_content_visibility'] );
$attributes['hover_content_visibility'] = str_replace('hover', 'hoover', $attributes['hover_content_visibility']);
$attributes['hover_bg_color'] = sanitize_key( $attributes['hover_bg_color'] );
$attributes['hover_animation'] = sanitize_key( $attributes['hover_animation'] );
$attributes['loading_effect'] = sanitize_key( $attributes['loading_effect'] );
$attributes['order'] = apply_filters('dt_sanitize_order', $attributes['order']);
$attributes['orderby'] = apply_filters('dt_sanitize_orderby', $attributes['orderby']);
$attributes['number'] = apply_filters('dt_sanitize_posts_per_page', $attributes['number']);
$attributes['posts_per_page'] = apply_filters('dt_sanitize_posts_per_page', $attributes['posts_per_page'], $attributes['number']);
$attributes['show_title'] = apply_filters('dt_sanitize_flag', $attributes['show_title']);
$attributes['show_excerpt'] = apply_filters('dt_sanitize_flag', $attributes['show_excerpt']);
$attributes['show_details'] = apply_filters('dt_sanitize_flag', $attributes['show_details']);
$attributes['show_link'] = apply_filters('dt_sanitize_flag', $attributes['show_link']);
$attributes['show_zoom'] = apply_filters('dt_sanitize_flag', $attributes['show_zoom']);
$attributes['show_categories'] = apply_filters('dt_sanitize_flag', $attributes['show_categories']);
$attributes['show_date'] = apply_filters('dt_sanitize_flag', $attributes['show_date']);
$attributes['show_author'] = apply_filters('dt_sanitize_flag', $attributes['show_author']);
$attributes['show_comments'] = apply_filters('dt_sanitize_flag', $attributes['show_comments']);
$attributes['show_filter'] = apply_filters('dt_sanitize_flag', $attributes['show_filter']);
$attributes['hide_last_row'] = apply_filters('dt_sanitize_flag', $attributes['hide_last_row']);
$attributes['full_width'] = apply_filters('dt_sanitize_flag', $attributes['full_width']);
$attributes['padding'] = intval($attributes['padding']);
$attributes['target_height'] = intval($attributes['target_height']);
if ( $attributes['category'] ) {
$attributes['category'] = presscore_sanitize_explode_string( $attributes['category'] );
$attributes['select'] = 'only';
} else {
$attributes['select'] = 'all';
}
if ( $attributes['proportion'] ) {
$wh = array_map( 'absint', explode(':', $attributes['proportion']) );
if ( 2 == count($wh) && !empty($wh[0]) && !empty($wh[1]) ) {
$attributes['proportion'] = array( 'width' => $wh[0], 'height' => $wh[1] );
} else {
$attributes['proportion'] = '';
}
}
return $attributes;
}
protected function setup_config() {
$config = &$this->config;
$atts = &$this->atts;
$config->set( 'layout', 'grid' );
$config->set( 'template', 'portfolio' );
$config->set( 'load_style', 'default' );
$config->set( 'justified_grid', true );
$config->set( 'all_the_same_width', true );
$config->set( 'post.preview.buttons.details.enabled', false );
$config->set( 'post.preview.background.enabled', false );
$config->set( 'post.preview.background.style', false );
$config->set( 'image_layout', $atts['proportion'] ? 'resize' : 'original' );
$config->set( 'thumb_proportions', $atts['proportion'] );
$config->set( 'target_height', $atts['target_height'] );
$config->set( 'item_padding', $atts['padding'] );
$config->set( 'post.preview.description.style', $atts['descriptions'] );
$config->set( 'post.preview.description.alignment', $atts['content_aligment'] );
$config->set( 'post.preview.hover.animation', $atts['hover_animation'] );
$config->set( 'post.preview.hover.color', $atts['hover_bg_color'] );
$config->set( 'post.preview.hover.content.visibility', $atts['hover_content_visibility'] );
$config->set( 'post.preview.load.effect', $atts['loading_effect'], 'fade_in' );
$config->set( 'show_links', $atts['show_link'] );
$config->set( 'show_titles', $atts['show_title'] );
$config->set( 'show_details', $atts['show_details'] );
$config->set( 'show_excerpts', $atts['show_excerpt'] );
$config->set( 'show_zoom', $atts['show_zoom'] );
$config->set( 'hide_last_row', $atts['hide_last_row'] );
$config->set( 'post.meta.fields.date', $atts['show_date'] );
$config->set( 'post.meta.fields.categories', $atts['show_categories'] );
$config->set( 'post.meta.fields.comments', $atts['show_comments'] );
$config->set( 'post.meta.fields.author', $atts['show_author'] );
$config->set( 'template.posts_filter.orderby.enabled', false );
$config->set( 'template.posts_filter.order.enabled', false );
$config->set( 'order', $atts['order'] );
$config->set( 'orderby', $atts['orderby'] );
}
}
// create shortcode
DT_Shortcode_Portfolio_Jgrid::get_instance();
}
|
julia26/puppy
|
wp-content/themes/puppy/inc/shortcodes/includes/portfolio-jgrid/portfolio-jgrid.php
|
PHP
|
gpl-2.0
| 8,645
|
"""Tests for the unparse.py script in the Tools/parser directory."""
import unittest
import test.support
import io
import os
import random
import tokenize
import ast
from test.test_tools import basepath, toolsdir, skip_if_missing
skip_if_missing()
parser_path = os.path.join(toolsdir, "parser")
with test.support.DirsOnSysPath(parser_path):
import unparse
def read_pyfile(filename):
"""Read and return the contents of a Python source file (as a
string), taking into account the file encoding."""
with open(filename, "rb") as pyfile:
encoding = tokenize.detect_encoding(pyfile.readline)[0]
with open(filename, "r", encoding=encoding) as pyfile:
source = pyfile.read()
return source
for_else = """\
def f():
for x in range(10):
break
else:
y = 2
z = 3
"""
while_else = """\
def g():
while True:
break
else:
y = 2
z = 3
"""
relative_import = """\
from . import fred
from .. import barney
from .australia import shrimp as prawns
"""
nonlocal_ex = """\
def f():
x = 1
def g():
nonlocal x
x = 2
y = 7
def h():
nonlocal x, y
"""
# also acts as test for 'except ... as ...'
raise_from = """\
try:
1 / 0
except ZeroDivisionError as e:
raise ArithmeticError from e
"""
class_decorator = """\
@f1(arg)
@f2
class Foo: pass
"""
elif1 = """\
if cond1:
suite1
elif cond2:
suite2
else:
suite3
"""
elif2 = """\
if cond1:
suite1
elif cond2:
suite2
"""
try_except_finally = """\
try:
suite1
except ex1:
suite2
except ex2:
suite3
else:
suite4
finally:
suite5
"""
with_simple = """\
with f():
suite1
"""
with_as = """\
with f() as x:
suite1
"""
with_two_items = """\
with f() as x, g() as y:
suite1
"""
class ASTTestCase(unittest.TestCase):
def assertASTEqual(self, ast1, ast2):
self.assertEqual(ast.dump(ast1), ast.dump(ast2))
def check_roundtrip(self, code1, filename="internal"):
ast1 = compile(code1, filename, "exec", ast.PyCF_ONLY_AST)
unparse_buffer = io.StringIO()
unparse.Unparser(ast1, unparse_buffer)
code2 = unparse_buffer.getvalue()
ast2 = compile(code2, filename, "exec", ast.PyCF_ONLY_AST)
self.assertASTEqual(ast1, ast2)
class UnparseTestCase(ASTTestCase):
# Tests for specific bugs found in earlier versions of unparse
def test_fstrings(self):
# See issue 25180
self.check_roundtrip(r"""f'{f"{0}"*3}'""")
self.check_roundtrip(r"""f'{f"{y}"*3}'""")
def test_del_statement(self):
self.check_roundtrip("del x, y, z")
def test_shifts(self):
self.check_roundtrip("45 << 2")
self.check_roundtrip("13 >> 7")
def test_for_else(self):
self.check_roundtrip(for_else)
def test_while_else(self):
self.check_roundtrip(while_else)
def test_unary_parens(self):
self.check_roundtrip("(-1)**7")
self.check_roundtrip("(-1.)**8")
self.check_roundtrip("(-1j)**6")
self.check_roundtrip("not True or False")
self.check_roundtrip("True or not False")
def test_integer_parens(self):
self.check_roundtrip("3 .__abs__()")
def test_huge_float(self):
self.check_roundtrip("1e1000")
self.check_roundtrip("-1e1000")
self.check_roundtrip("1e1000j")
self.check_roundtrip("-1e1000j")
def test_min_int(self):
self.check_roundtrip(str(-2**31))
self.check_roundtrip(str(-2**63))
def test_imaginary_literals(self):
self.check_roundtrip("7j")
self.check_roundtrip("-7j")
self.check_roundtrip("0j")
self.check_roundtrip("-0j")
def test_lambda_parentheses(self):
self.check_roundtrip("(lambda: int)()")
def test_chained_comparisons(self):
self.check_roundtrip("1 < 4 <= 5")
self.check_roundtrip("a is b is c is not d")
def test_function_arguments(self):
self.check_roundtrip("def f(): pass")
self.check_roundtrip("def f(a): pass")
self.check_roundtrip("def f(b = 2): pass")
self.check_roundtrip("def f(a, b): pass")
self.check_roundtrip("def f(a, b = 2): pass")
self.check_roundtrip("def f(a = 5, b = 2): pass")
self.check_roundtrip("def f(*, a = 1, b = 2): pass")
self.check_roundtrip("def f(*, a = 1, b): pass")
self.check_roundtrip("def f(*, a, b = 2): pass")
self.check_roundtrip("def f(a, b = None, *, c, **kwds): pass")
self.check_roundtrip("def f(a=2, *args, c=5, d, **kwds): pass")
self.check_roundtrip("def f(*args, **kwargs): pass")
def test_relative_import(self):
self.check_roundtrip(relative_import)
def test_nonlocal(self):
self.check_roundtrip(nonlocal_ex)
def test_raise_from(self):
self.check_roundtrip(raise_from)
def test_bytes(self):
self.check_roundtrip("b'123'")
def test_annotations(self):
self.check_roundtrip("def f(a : int): pass")
self.check_roundtrip("def f(a: int = 5): pass")
self.check_roundtrip("def f(*args: [int]): pass")
self.check_roundtrip("def f(**kwargs: dict): pass")
self.check_roundtrip("def f() -> None: pass")
def test_set_literal(self):
self.check_roundtrip("{'a', 'b', 'c'}")
def test_set_comprehension(self):
self.check_roundtrip("{x for x in range(5)}")
def test_dict_comprehension(self):
self.check_roundtrip("{x: x*x for x in range(10)}")
def test_class_decorators(self):
self.check_roundtrip(class_decorator)
def test_class_definition(self):
self.check_roundtrip("class A(metaclass=type, *[], **{}): pass")
def test_elifs(self):
self.check_roundtrip(elif1)
self.check_roundtrip(elif2)
def test_try_except_finally(self):
self.check_roundtrip(try_except_finally)
def test_starred_assignment(self):
self.check_roundtrip("a, *b, c = seq")
self.check_roundtrip("a, (*b, c) = seq")
self.check_roundtrip("a, *b[0], c = seq")
self.check_roundtrip("a, *(b, c) = seq")
def test_with_simple(self):
self.check_roundtrip(with_simple)
def test_with_as(self):
self.check_roundtrip(with_as)
def test_with_two_items(self):
self.check_roundtrip(with_two_items)
def test_dict_unpacking_in_dict(self):
# See issue 26489
self.check_roundtrip(r"""{**{'y': 2}, 'x': 1}""")
self.check_roundtrip(r"""{**{'y': 2}, **{'x': 1}}""")
class DirectoryTestCase(ASTTestCase):
"""Test roundtrip behaviour on all files in Lib and Lib/test."""
NAMES = None
# test directories, relative to the root of the distribution
test_directories = 'Lib', os.path.join('Lib', 'test')
@classmethod
def get_names(cls):
if cls.NAMES is not None:
return cls.NAMES
names = []
for d in cls.test_directories:
test_dir = os.path.join(basepath, d)
for n in os.listdir(test_dir):
if n.endswith('.py') and not n.startswith('bad'):
names.append(os.path.join(test_dir, n))
# Test limited subset of files unless the 'cpu' resource is specified.
if not test.support.is_resource_enabled("cpu"):
names = random.sample(names, 10)
# bpo-31174: Store the names sample to always test the same files.
# It prevents false alarms when hunting reference leaks.
cls.NAMES = names
return names
def test_files(self):
# get names of files to test
names = self.get_names()
for filename in names:
if test.support.verbose:
print('Testing %s' % filename)
# Some f-strings are not correctly round-tripped by
# Tools/parser/unparse.py. See issue 28002 for details.
# We need to skip files that contain such f-strings.
if os.path.basename(filename) in ('test_fstring.py', ):
if test.support.verbose:
print(f'Skipping {filename}: see issue 28002')
continue
with self.subTest(filename=filename):
source = read_pyfile(filename)
self.check_roundtrip(source)
if __name__ == '__main__':
unittest.main()
|
FFMG/myoddweb.piger
|
monitor/api/python/Python-3.7.2/Lib/test/test_tools/test_unparse.py
|
Python
|
gpl-2.0
| 8,393
|
<?php
global $smof_data;
global $blog_post_type;
?>
<div id="post-<?php the_ID(); ?>" <?php post_class('post clearfix'); ?>>
<div class="post-audio">
<?php echo get_post_meta($post->ID, 'rnr_blogaudiourl', true); ?>
</div>
<div class="post-title">
<a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__('Permalink to %s', 'rocknrolla'), the_title_attribute('echo=0') ); ?>" rel="bookmark"><h2><?php the_title(); ?></h2></a>
</div><!-- End of Title -->
<div class="post-meta">
<?php _e('<i class="fa fa-tasks"></i> ', 'rocknrolla'); the_category(', '); ?>, <i class="fa fa-time"></i> <?php the_time('d'); ?> <?php the_time('M'); ?>, <?php the_time('Y'); ?> <span><?php if ( comments_open() ) { comments_popup_link(__('<i class="fa fa-comments-o"></i> 0', 'rocknrolla'), __('<i class="fa fa-comments-o"></i> 1', 'rocknrolla'), __('<i class="fa fa-comments-o"></i> %', 'rocknrolla'), 'comments-link', ''); } ?></span>
</div><!-- End of Meta Date -->
<div class="post-content">
<?php the_excerpt(); ?>
<?php wp_link_pages(array('before' => 'Pages: ', 'next_or_number' => 'number')); ?>
</div><!-- End of Content -->
<div class="post-tags styled-list">
<ul>
<?php the_tags( '<ul><li><i class="fa fa-tags"></i>', '</li><li><i class="fa fa-tags"></i>', '</li></ul>'); ?>
</ul>
</div><!-- End of Tags -->
</div><!-- End of Post -->
|
pjoosen/cc-websolutions-new
|
wp-content/themes/jarvis_wp/post-format/content-audio.php
|
PHP
|
gpl-2.0
| 1,467
|
package com.j03.mobileinput.Canvas;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import com.j03.mobileinput.R;
import java.util.Timer;
import java.util.TimerTask;
import Settings.AppSettings;
import Common.SystemInfo;
import Common.Toast.Toaster;
import Settings.Enums.ConnectionMode;
import Gesture.Binding.Actions.Trigger;
import Layout.Enums.PositioningMode;
@TargetApi(19)
@SuppressLint("InlinedApi")
public class CanvasActivity
extends ActionBarActivity
{
public static Activity mainActivityContext;
public static Runnable mHideRunnable;
private boolean waiting = false;
private Timer countdown;
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
final MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
AppSettings.getInstanceSetContext(this);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.action_keyboard:
InputMethodManager imm =
(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(
InputMethodManager.SHOW_FORCED,
InputMethodManager.HIDE_IMPLICIT_ONLY);
return true;
case R.id.action_cut:
AppSettings.getInstance().getConnectionManager().send(Trigger.CUT);
Toaster.getInstance().showToast("Cut", getApplicationContext());
return true;
case R.id.action_copy:
AppSettings.getInstance().getConnectionManager().send(Trigger.COPY);
Toaster.getInstance().showToast("Copy", getApplicationContext());
return true;
case R.id.action_paste:
AppSettings.getInstance().getConnectionManager().send(Trigger.PASTE);
Toaster.getInstance().showToast("Paste", getApplicationContext());
return true;
case R.id.action_hide:
// Hide actionbar when not starting from the top
if (AppSettings.getInstance().getSystemSettings().getKitKat())
{
hideUi(CanvasActivity.mainActivityContext);
}
return true;
case R.id.show_settings:
AppSettings.getInstance().getSettingsElements().getPrefConnectionStatus().setEnabled(true);
AppSettings.getInstance().getSettingsElements().getPrefConnectionStatus().setTitle("Tap to resume");
if (AppSettings.getInstance().getConnectionManager().getConnectionMode() == ConnectionMode.WIFI)
{
final SystemInfo ipv4 = AppSettings.getInstance().getSystemSettings().getSystemInfo();
AppSettings.getInstance().getSettingsElements().getPrefConnectionStatus().setSummary(
"Connected via WiFi (" + ipv4.ipv4Address().get(0).getHostAddress() + ")");
} else if (AppSettings.getInstance().getConnectionManager().getConnectionMode() == ConnectionMode.USB)
{
AppSettings.getInstance().getSettingsElements().getPrefConnectionStatus().setSummary(
"Connected via USB");
}
finish();
return true;
case R.id.action_close:
closeConnection();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
mainActivityContext = this;
/*
Controller c = new Controller(this);*/
if (AppSettings.getInstance().getSettingsElements().getPositioningMode() == PositioningMode.ABSOLUTE)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}
if (getSupportActionBar() != null)
{
if (AppSettings.getInstance().getSettingsElements().getActionBarEnabled())
{
getSupportActionBar().show();
} else
{
getSupportActionBar().hide();
}
}
countdown = new Timer();
final CanvasView dv = new CanvasView(this);
setContentView(dv); //show the drawing view
}
@SuppressLint("InlinedApi")
public static void hideUi(Activity a)
{
a.getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_IMMERSIVE
);
mHideRunnable = new Runnable()
{
@Override
public void run()
{
hideUi(mainActivityContext);
}
};
}
@Override
public boolean onKeyDown(final int keyCode, final KeyEvent event)
{
if ((keyCode == KeyEvent.KEYCODE_BACK) &&
(event.getRepeatCount() == 0))
{
if (!waiting)
{
Toaster.getInstance().showToast("Press back again to close the connection",
getApplicationContext());
waiting = true;
countdown.schedule(
new TimerTask()
{
@Override
public void run()
{
waiting = false;
}
}, 2000);
} else
{
closeConnection();
}
return true;
} else
{
final short[] KEYBOARD = {10000 + 9, 100};
if (keyCode == KeyEvent.KEYCODE_SHIFT_LEFT
|| keyCode == KeyEvent.KEYCODE_SHIFT_RIGHT)
{
AppSettings.getInstance().getConnectionManager().send(KEYBOARD);
}
}
return super.onKeyDown(keyCode, event);
}
@Override
public boolean onKeyUp(final int keyCode, final KeyEvent event)
{
if (keyCode != KeyEvent.KEYCODE_BACK && keyCode != KeyEvent.KEYCODE_MENU)
{
final short[] KEYBOARD = {10000 + 9, (short) keyCode};
AppSettings.getInstance().getConnectionManager().send(KEYBOARD);
}
return super.onKeyUp(keyCode, event);
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private void closeConnection()
{
if (AppSettings.getInstance().getConnectionManager().getConnectionMode() == ConnectionMode.WIFI)
{
//this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
AppSettings.getInstance().getConnectionManager().getNetworkConnectionManager().close();
} else if (AppSettings.getInstance().getConnectionManager().getConnectionMode() == ConnectionMode.USB)
{
//this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
AppSettings.getInstance().getConnectionManager().getUsbConnectionManager().close();
}
AppSettings.getInstance().getConnectionManager().reinitializeServers();
finish();
}
public Context getContext()
{
return this;
}
}
|
itstar4tech/slide-android
|
app/src/main/java/com/j03/mobileinput/Canvas/CanvasActivity.java
|
Java
|
gpl-2.0
| 8,440
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/1999/REC-html401-19991224/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>{shop_name}</title>
</head>
<body>
<table style="font-family: Verdana,sans-serif; font-size: 11px; color: #374953; width: 550px;">
<tbody>
<tr>
<td align="left"><a title="{shop_name}" href="{shop_url}"><img style="border: none;" src="{shop_logo}" alt="{shop_name}" /></a></td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td align="left">Olá, <strong style="color: #db3484;">{firstname} {lastname}</strong>,</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td style="background-color: #db3484; color: #fff; font-size: 12px; font-weight: bold; padding: 0.5em 1em;" align="left">Seu pedido, {order_name} - Aguardando confirmação de pagamento</td>
</tr>
<tr>
<td> </td>
</tr>
<tr>
<td align="left">Muito obrigado por ter comprado na {shop_name}!<br /><br /> Seu pedido, {order_name} foi processado com sucesso e nós <strong>estamos aguardando a confirmação do pagamento</strong>.</td>
</tr>
<tr>
<td> </td>
<tr>
<td align="left">Se quiser rever ou visualizar o seu pedido por favor entre "<span style="color: #ff00ff;">Histórico de pedidos</span>" dentro da sua conta.<br /><br /></td>
</tr>
<tr>
<td align="left">Se a sua conta for convidado, por favor acompanhe o seu pedido pelo link <a style="color: #db3484; font-weight: bold; text-decoration: none;" href="{shop_url}?controller=guest-tracking">"Guest Tracking"</a>.</td>
</tr>
<tr>
<td> </td>
<tr>
<tr>
<td style="font-size: 10px; border-top: 1px solid #D9DADE;" align="center"><a style="color: #db3484; font-weight: bold; text-decoration: none;" href="{shop_url}">{shop_name}</a></td>
</tr>
</tbody>
</table>
</body>
</html>
|
fernandaos12/ateliebambolina
|
modules/pagseguro/mails/awaiting_payment.html
|
HTML
|
gpl-2.0
| 1,844
|
/**
* Copyright 2014 @ to2.net.
* name :
* author : jarryliu
* date : 2013-12-03 21:04
* description :
* history :
*/
package promotion
import (
"go2o/core/domain/interface/member"
)
// 优惠券促销
type ICouponPromotion interface {
GetDomainId() int32
// 获取促销内容
GetDetailsValue() ValueCoupon
// 设置促销内容
SetDetailsValue(*ValueCoupon) error
// 获取绑定
GetBinds() []ValueCouponBind
// 获取占用
GetTakes() []ValueCouponTake
// 保存
Save() (id int32, err error)
// 获取优惠券描述
GetDescribe() string
// 获取优惠的金额
GetCouponFee(orderFee float32) float32
// 是否可用,传递会员及订单金额
// error返回不适用的详细信息
CanUse(member.IMember, float32) (bool, error)
// 是否允许占用
CanTake() bool
// 获取占用
GetTake(memberId int64) (*ValueCouponTake, error)
//占用
Take(memberId int64) error
// 应用到订单
ApplyTake(couponTakeId int32) error
// 绑定
Bind(memberId int64) error
//获取绑定
GetBind(memberId int64) (*ValueCouponBind, error)
//绑定
Binds(memberIds []string) error
//使用优惠券
UseCoupon(couponBindId int32) error
}
type (
ValueCoupon struct {
// 优惠券编号
Id int32 `db:"id" pk:"yes"`
//优惠码
Code string `db:"code"`
// 优惠码可用数量
Amount int `db:"amount"`
// 优惠码数量
TotalAmount int `db:"total_amount"`
//优惠金额
Fee int `db:"fee"`
//赠送积分
Integral int `db:"integral"`
//订单折扣(不打折为100)
Discount int `db:"discount"`
//等级限制
MinLevel int `db:"min_level"`
//订单金额限制
MinFee int `db:"min_fee"`
BeginTime int64 `db:"begin_time"`
OverTime int64 `db:"over_time"`
//是否需要绑定。反之可以直接使用
NeedBind int `db:"need_bind"`
CreateTime int64 `db:"create_time"`
}
//优惠券绑定
ValueCouponBind struct {
Id int32 `db:"id" auto:"yes" pk:"yes"`
//会员编号
MemberId int64 `db:"member_id"`
//优惠券编号
CouponId int32 `db:"coupon_id"`
//绑定时间
BindTime int64 `db:"bind_time"`
//是否使用
IsUsed int `db:"is_used"`
//使用时间
UseTime int64 `db:"use_time"`
}
ValueCouponTake struct {
Id int32 `db:"id" auto:"yes" pk:"yes"`
//会员编号
MemberId int64 `db:"member_id"`
//优惠券编号
CouponId int32 `db:"coupon_id"`
//占用时间
TakeTime int64 `db:"take_time"`
//释放时间,超过该时间,优惠券释放
ExtraTime int64 `db:"extra_time"`
//是否应用到订单
IsApply int `db:"is_apply"`
//更新时间
ApplyTime int64 `db:"apply_time"`
}
)
|
jsix/go2o
|
core/domain/interface/promotion/coupon.go
|
GO
|
gpl-2.0
| 2,654
|
/* Copyright (c) 2014 The Chromium OS Authors. All rights reserved.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
/* APIs between calling firmware and vboot_reference
*
* DO NOT INCLUDE THE HEADERS BELOW DIRECTLY! ONLY INCLUDE THIS FILE!
*
* Using vb2api.h as the single point of contact between calling firmware and
* vboot allows subsequent refactoring of vboot (renaming of headers, etc.)
* without churning other projects' source code.
*/
#ifndef VBOOT_VB2_API_H_
#define VBOOT_VB2_API_H_
/* Standard APIs */
#include "../2lib/include/2api.h"
/* SHA library */
#ifdef NEED_VB2_SHA_LIBRARY
#include "../2lib/include/2sha.h"
#endif
/*
* Coreboot should not need access to vboot2 internals. But right now it does.
* At least this forces it to do so through a relatively narrow hole so vboot2
* refactoring can continue.
*
* Please do not rip this into a wider hole, or expect this hole to continue.
*
* TODO: Make cleaner APIs to this stuff.
*/
#ifdef NEED_VB20_INTERNALS
#include "../2lib/include/2nvstorage_fields.h"
#include "../2lib/include/2struct.h"
#include "../lib20/include/vb2_struct.h"
#endif
#endif /* VBOOT_VB2_API_H_ */
|
RafaelRMachado/Coreboot
|
3rdparty/vboot/firmware/include/vb2_api.h
|
C
|
gpl-2.0
| 1,221
|
/*
* Copyright 2006-2018 The MZmine 2 Development Team
*
* This file is part of MZmine 2.
*
* MZmine 2 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.
*
* MZmine 2 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 MZmine 2; if not,
* write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301
* USA
*/
package net.sf.mzmine.modules.visualization.peaklisttable.table;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.table.TableCellRenderer;
import net.sf.mzmine.datamodel.PeakIdentity;
/**
* Table cell renderer
*/
public class CompoundIdentityCellRenderer implements TableCellRenderer {
static final Font defaultFont = new Font("SansSerif", Font.PLAIN, 10);
/**
* @see javax.swing.table.TableCellRenderer#getTableCellRendererComponent(javax.swing.JTable,
* java.lang.Object, boolean, boolean, int, int)
*/
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column) {
JLabel newLabel = new JLabel();
newLabel.setHorizontalAlignment(JLabel.LEFT);
newLabel.setFont(defaultFont);
newLabel.setOpaque(true);
Color bgColor;
if (isSelected)
bgColor = table.getSelectionBackground();
else
bgColor = table.getBackground();
newLabel.setBackground(bgColor);
if (hasFocus) {
Border border = null;
if (isSelected)
border = UIManager.getBorder("Table.focusSelectedCellHighlightBorder");
if (border == null)
border = UIManager.getBorder("Table.focusCellHighlightBorder");
/*
* The "border.getBorderInsets(newPanel) != null" is a workaround for OpenJDK 1.6.0 bug,
* otherwise setBorder() may throw a NullPointerException
*/
if ((border != null) && (border.getBorderInsets(newLabel) != null)) {
newLabel.setBorder(border);
}
}
if (value instanceof PeakIdentity) {
PeakIdentity identity = (PeakIdentity) value;
newLabel.setText(identity.getName());
String toolTipText = identity.getDescription();
newLabel.setToolTipText(toolTipText);
}
return newLabel;
}
}
|
du-lab/mzmine2
|
src/main/java/net/sf/mzmine/modules/visualization/peaklisttable/table/CompoundIdentityCellRenderer.java
|
Java
|
gpl-2.0
| 2,791
|
using System;
using Server.Engines.Quests;
using Server.Mobiles;
namespace Server.Items
{
public class BedlamTele : Item
{
[Constructable]
public BedlamTele()
: base(0x124D)
{
Movable = false;
}
public BedlamTele(Serial serial)
: base(serial)
{
}
public override int LabelNumber
{
get
{
return 1074161;
}
}// Access to Bedlam by invitation only
public override bool ForceShowProperties { get { return ObjectPropertyList.Enabled; } }
public virtual Type Quest
{
get
{
return typeof(MistakenIdentityQuest);
}
}
public override void OnDoubleClick(Mobile from)
{
if (from.NetState == null || !from.NetState.SupportsExpansion(Expansion.ML))
{
from.SendLocalizedMessage(1072608); // You must upgrade to the Mondain's Legacy expansion in order to enter here.
return;
}
else if (!MondainsLegacy.Bedlam && (int)from.AccessLevel < (int)AccessLevel.GameMaster)
{
from.SendLocalizedMessage(1042753, "Bedlam"); // ~1_SOMETHING~ has been temporarily disabled.
return;
}
if (from is PlayerMobile)
{
PlayerMobile player = (PlayerMobile)from;
if (player.Bedlam)
{
BaseCreature.TeleportPets(player, new Point3D(121, 1682, 0), this.Map);
player.MoveToWorld(new Point3D(121, 1682, 0), this.Map);
}
else
{
player.SendLocalizedMessage(1074276); // You press and push on the iron maiden, but nothing happens.
}
}
}
public override void Serialize(GenericWriter writer)
{
base.Serialize(writer);
writer.Write((int)0); // version
}
public override void Deserialize(GenericReader reader)
{
base.Deserialize(reader);
int version = reader.ReadInt();
}
}
}
|
A2152225/ServUO
|
Scripts/Items/Internal/BedlamTeleporters.cs
|
C#
|
gpl-2.0
| 2,295
|
/*
* jit-elf-read.c - Routines to read ELF-format binaries.
*
* Copyright (C) 2004 Southern Storm Software, Pty Ltd.
*
* This file is part of the libjit library.
*
* The libjit library is free software: you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation, either version 2.1 of
* the License, or (at your option) any later version.
*
* The libjit library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with the libjit library. If not, see
* <http://www.gnu.org/licenses/>.
*/
#include "jit-internal.h"
#include "jit-rules.h"
#include "jit-elf-defs.h"
#include "jit-memory.h"
#include <config.h>
#ifdef JIT_WIN32_PLATFORM
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#include <windows.h>
#include <io.h>
#include <fcntl.h>
#else
#ifdef HAVE_SYS_TYPES_H
#include <sys/types.h>
#endif
#ifdef HAVE_SYS_STAT_H
#include <sys/stat.h>
#endif
#ifdef HAVE_FCNTL_H
#include <fcntl.h>
#endif
#ifdef HAVE_UNISTD_H
#include <unistd.h>
#endif
#ifdef HAVE_SYS_MMAN_H
#include <sys/mman.h>
#if defined(HAVE_MMAP) && defined(HAVE_MUNMAP) && defined(HAVE_MPROTECT)
#define JIT_USE_MMAP_TO_LOAD 1
#ifndef MAP_ANON
#ifdef MAP_ANONYMOUS
#define MAP_ANON MAP_ANONYMOUS
#else
#define MAP_ANON 0
#endif
#endif
#ifndef MAP_FIXED
#define MAP_FIXED 0
#endif
#ifndef MAP_COPY
#define MAP_COPY MAP_PRIVATE
#endif
#endif
#endif
#endif
#include <stdio.h>
/*@
The @code{libjit} library contains routines that permit pre-compiling
JIT'ed functions into an on-disk representation. This representation
can be loaded at some future time, to avoid the overhead of compiling
the functions at runtime.
We use the ELF format for this purpose, which is a common binary format
used by modern operating systems and compilers.
It isn't necessary for your operating system to be based on ELF natively.
We use our own routines to read and write ELF binaries. We chose ELF
because it has all of the features that we require, and reusing an
existing format was better than inventing a completely new one.
@section Reading ELF binaries
@*/
/*
* Determine whether we should be using the 32-bit or 64-bit ELF structures.
*/
#ifdef JIT_NATIVE_INT32
typedef Elf32_Ehdr Elf_Ehdr;
typedef Elf32_Shdr Elf_Shdr;
typedef Elf32_Phdr Elf_Phdr;
typedef Elf32_Addr Elf_Addr;
typedef Elf32_Word Elf_Word;
typedef Elf32_Xword Elf_Xword;
typedef Elf32_Off Elf_Off;
typedef Elf32_Dyn Elf_Dyn;
typedef Elf32_Sym Elf_Sym;
typedef Elf32_Rel Elf_Rel;
typedef Elf32_Rela Elf_Rela;
#define ELF_R_SYM(val) ELF32_R_SYM((val))
#define ELF_R_TYPE(val) ELF32_R_TYPE((val))
#else
typedef Elf64_Ehdr Elf_Ehdr;
typedef Elf64_Shdr Elf_Shdr;
typedef Elf64_Phdr Elf_Phdr;
typedef Elf64_Addr Elf_Addr;
typedef Elf64_Word Elf_Word;
typedef Elf64_Xword Elf_Xword;
typedef Elf64_Off Elf_Off;
typedef Elf64_Dyn Elf_Dyn;
typedef Elf64_Sym Elf_Sym;
typedef Elf64_Rel Elf_Rel;
typedef Elf64_Rela Elf_Rela;
#define ELF_R_SYM(val) ELF64_R_SYM((val))
#define ELF_R_TYPE(val) ELF64_R_TYPE((val))
#endif
/*
* Deal with platform differences in the file descriptor routines.
*/
#ifdef JIT_WIN32_NATIVE
#define sys_open _open
#define sys_close _close
#define sys_read _read
#define sys_lseek _lseek
#else
#define sys_open open
#define sys_close close
#define sys_read read
#define sys_lseek lseek
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
/*
* Define the relocation function type.
*/
typedef int (*jit_reloc_func)(jit_readelf_t readelf, void *address,
int type, jit_nuint value, int has_addend,
jit_nuint addend);
/*
* Get the relocation function for a particular machine type.
*/
static jit_reloc_func get_reloc(unsigned int machine);
/*
* Structure of an ELF binary once it has been loaded into memory.
*/
struct jit_readelf
{
jit_readelf_t next;
int resolved;
Elf_Ehdr ehdr;
unsigned char *phdrs;
unsigned char *shdrs;
char *regular_strings;
jit_nuint regular_strings_size;
char *dynamic_strings;
jit_nuint dynamic_strings_size;
Elf_Sym *symbol_table;
jit_nuint symbol_table_size;
Elf_Word *symbol_hash;
jit_nuint symbol_hash_size;
Elf_Word symbol_hash_buckets;
jit_reloc_func reloc_func;
void *map_address;
jit_nuint map_size;
int free_with_munmap;
};
/*
* Flag that indicates that an auxillary section was malloc'ed,
* and isn't part of the main memory range at "map_address".
*/
#define JIT_ELF_IS_MALLOCED 0x01000000
/*
* Get the address of a particular phdr.
*/
static Elf_Phdr *get_phdr(jit_readelf_t readelf, unsigned int index)
{
if(index < readelf->ehdr.e_phnum &&
readelf->ehdr.e_phentsize >= sizeof(Elf_Phdr))
{
return (Elf_Phdr *)
(readelf->phdrs +
index * ((unsigned int)(readelf->ehdr.e_phentsize)));
}
else
{
return 0;
}
}
/*
* Get the address of a particular shdr.
*/
static Elf_Shdr *get_shdr(jit_readelf_t readelf, unsigned int index)
{
if(index < readelf->ehdr.e_shnum &&
readelf->ehdr.e_shentsize >= sizeof(Elf_Shdr))
{
return (Elf_Shdr *)
(readelf->shdrs +
index * ((unsigned int)(readelf->ehdr.e_shentsize)));
}
else
{
return 0;
}
}
/*
* Find a specific string in the regular string table.
*/
static const char *get_string(jit_readelf_t readelf, Elf_Word _index)
{
jit_nuint index = (jit_nuint)_index;
if(index < readelf->regular_strings_size)
{
return readelf->regular_strings + index;
}
else
{
return 0;
}
}
/*
* Find a specific string in the dynamic string table.
*/
static const char *get_dyn_string(jit_readelf_t readelf, Elf_Addr _index)
{
jit_nuint index = (jit_nuint)_index;
if(index < readelf->dynamic_strings_size)
{
return readelf->dynamic_strings + index;
}
else
{
return 0;
}
}
/*
* Map all of the program segments into memory and set up the bss section.
*/
static int map_program(jit_readelf_t readelf, int fd)
{
Elf_Off file_size;
Elf_Off memory_size;
Elf_Off start, end;
Elf_Phdr *phdr;
unsigned int index;
void *base_address;
unsigned char *segment_address;
/* Get the maximum file and memory sizes for the program.
The bytes between "file_size" and "memory_size" are bss */
file_size = 0;
memory_size = 0;
for(index = 0; index < readelf->ehdr.e_phnum; ++index)
{
phdr = get_phdr(readelf, index);
if(!phdr)
{
continue;
}
start = phdr->p_offset;
end = start + phdr->p_filesz;
if(end > file_size)
{
file_size = end;
}
start = phdr->p_vaddr;
end = start + phdr->p_memsz;
if(end > memory_size)
{
memory_size = end;
}
}
if(memory_size < file_size)
{
memory_size = file_size;
}
/* Try to map the program segments into memory using mmap */
base_address = 0;
#ifdef JIT_USE_MMAP_TO_LOAD
{
Elf_Off page_size;
Elf_Off rounded_file_size;
Elf_Off temp_start;
Elf_Off temp_end;
int zero_fd, prot;
/* Round the total memory and file sizes up to the CPU page size */
page_size = (Elf_Off)(jit_exec_page_size());
end = memory_size;
if((end % page_size) != 0)
{
end += page_size - (end % page_size);
}
rounded_file_size = file_size;
if((rounded_file_size % page_size) != 0)
{
rounded_file_size += page_size - (rounded_file_size % page_size);
}
/* Allocate memory for the program from /dev/zero. Once we have
the memory, we will overlay the program segments on top */
zero_fd = sys_open("/dev/zero", O_RDWR, 0);
if(zero_fd < -1)
{
goto failed_mmap;
}
base_address = mmap(0, (size_t)end, PROT_READ | PROT_WRITE,
MAP_ANON | MAP_PRIVATE, zero_fd, 0);
close(zero_fd);
if(base_address == (void *)(jit_nint)(-1))
{
base_address = 0;
goto failed_mmap;
}
/* Lay down the program sections at their mapped locations */
for(index = 0; index < readelf->ehdr.e_phnum; ++index)
{
phdr = get_phdr(readelf, index);
if(phdr)
{
temp_start = phdr->p_offset;
temp_end = temp_start + phdr->p_filesz;
temp_start -= (temp_start % page_size);
if((temp_end % page_size) != 0)
{
temp_end += page_size - (temp_end % page_size);
}
start = phdr->p_vaddr;
start -= (start % page_size);
if(temp_start < temp_end)
{
segment_address =
((unsigned char *)base_address) + (jit_nuint)start;
prot = 0;
if((phdr->p_flags & PF_X) != 0)
{
prot |= PROT_EXEC;
}
if((phdr->p_flags & PF_W) != 0)
{
prot |= PROT_WRITE;
}
if((phdr->p_flags & PF_R) != 0)
{
prot |= PROT_READ;
}
if(mmap(segment_address, (size_t)(temp_end - temp_start),
prot, MAP_COPY | MAP_FILE | MAP_FIXED, fd,
(off_t)temp_start) == (void *)(jit_nint)(-1))
{
munmap(base_address, (size_t)end);
base_address = 0;
goto failed_mmap;
}
}
}
}
/* We need to free the memory with munmap when the program is closed */
readelf->free_with_munmap = 1;
/* Clear the left-over ".bss" bits that did not get cleared above */
for(index = 0; index < readelf->ehdr.e_phnum; ++index)
{
phdr = get_phdr(readelf, index);
if(phdr && phdr->p_filesz < phdr->p_memsz)
{
temp_start = phdr->p_vaddr + phdr->p_filesz;
start = (temp_start % page_size);
temp_start -= start;
if(start != 0)
{
segment_address =
((unsigned char *)base_address) +
(jit_nuint)temp_start;
mprotect(segment_address, (size_t)page_size,
PROT_READ | PROT_WRITE);
jit_memzero(segment_address + (jit_nuint)start,
(unsigned int)(page_size - start));
prot = 0;
if((phdr->p_flags & PF_X) != 0)
{
prot |= PROT_EXEC;
}
if((phdr->p_flags & PF_W) != 0)
{
prot |= PROT_WRITE;
}
if((phdr->p_flags & PF_R) != 0)
{
prot |= PROT_READ;
}
mprotect(segment_address, (size_t)page_size, prot);
}
}
}
}
failed_mmap:
#endif /* JIT_USE_MMAP_TO_LOAD */
/* If we haven't mapped the file yet, then fall back to "malloc" */
if(!base_address)
{
base_address = jit_malloc_exec(memory_size);
if(!base_address)
{
return 0;
}
for(index = 0; index < readelf->ehdr.e_phnum; ++index)
{
phdr = get_phdr(readelf, index);
if(phdr)
{
segment_address = ((unsigned char *)base_address) +
(jit_nuint)(phdr->p_vaddr);
if(lseek(fd, (off_t)(phdr->p_offset), 0) !=
(off_t)(phdr->p_offset) ||
read(fd, segment_address, (size_t)(phdr->p_filesz))
!= (int)(size_t)(phdr->p_filesz))
{
jit_free_exec(base_address, memory_size);
return 0;
}
}
}
}
/* Record the mapped address and size for later */
readelf->map_address = base_address;
readelf->map_size = memory_size;
return 1;
}
/*
* Map an auxillary section into memory and return its base address.
* Returns NULL if we ran out of memory.
*/
static void *map_section(int fd, Elf_Off offset, Elf_Xword file_size,
Elf_Xword memory_size, Elf_Word flags)
{
void *address;
if(memory_size < file_size)
{
memory_size = file_size;
}
address = jit_malloc_exec(memory_size);
if(!address)
{
return 0;
}
if(lseek(fd, (off_t)offset, 0) != (off_t)offset)
{
jit_free_exec(address, memory_size);
return 0;
}
if(read(fd, address, (size_t)file_size) != (int)(size_t)file_size)
{
jit_free_exec(address, memory_size);
return 0;
}
return address;
}
/*
* Unmap an auxillary section from memory.
*/
static void unmap_section(void *address, Elf_Xword file_size,
Elf_Xword memory_size, Elf_Word flags)
{
if(memory_size < file_size)
{
memory_size = file_size;
}
if((flags & JIT_ELF_IS_MALLOCED) != 0)
{
jit_free_exec(address, (unsigned int)memory_size);
}
}
/*
* Iterate over the contents of the ".dynamic" section.
*/
typedef struct
{
Elf_Dyn *dyn;
jit_nuint size;
} jit_dynamic_iter_t;
static void dynamic_iter_init(jit_dynamic_iter_t *iter, jit_readelf_t readelf)
{
iter->dyn = jit_readelf_get_section_by_type
(readelf, SHT_DYNAMIC, &(iter->size));
}
static int dynamic_iter_next
(jit_dynamic_iter_t *iter, jit_uint *type, Elf_Addr *value)
{
if(iter->size >= sizeof(Elf_Dyn))
{
*type = (jit_uint)(iter->dyn->d_tag);
*value = iter->dyn->d_un.d_ptr;
if(*type == DT_NULL)
{
/* Explicitly-marked end of the list */
return 0;
}
++(iter->dyn);
iter->size -= sizeof(Elf_Dyn);
return 1;
}
else
{
/* Implicitly-marked end of the list */
return 0;
}
}
static int dynamic_for_type
(jit_readelf_t readelf, jit_uint type, Elf_Addr *value)
{
Elf_Addr temp_value;
jit_dynamic_iter_t iter;
jit_uint iter_type;
dynamic_iter_init(&iter, readelf);
while(dynamic_iter_next(&iter, &iter_type, &temp_value))
{
if(iter_type == type)
{
if(value)
{
*value = temp_value;
}
return 1;
}
}
return 0;
}
/*
* Load interesting values from the ".dynamic" section, for quicker lookups.
*/
static void load_dynamic_section(jit_readelf_t readelf, int flags)
{
Elf_Addr value;
Elf_Addr value2;
jit_dynamic_iter_t iter;
jit_uint type;
jit_nuint size;
/* Get the position and size of the dynamic string table */
if(dynamic_for_type(readelf, DT_STRTAB, &value) &&
dynamic_for_type(readelf, DT_STRSZ, &value2))
{
readelf->dynamic_strings = jit_readelf_map_vaddr
(readelf, (jit_nuint)value);
if(readelf->dynamic_strings)
{
readelf->dynamic_strings_size = (jit_nuint)value2;
}
}
/* Get the position and size of the dynamic symbol table */
readelf->symbol_table = jit_readelf_get_section_by_type
(readelf, SHT_DYNSYM, &size);
if(readelf->symbol_table)
{
if(dynamic_for_type(readelf, DT_SYMENT, &value) &&
value == sizeof(Elf_Sym))
{
readelf->symbol_table_size = size / sizeof(Elf_Sym);
readelf->symbol_hash = jit_readelf_get_section_by_type
(readelf, SHT_HASH, &size);
if(readelf->symbol_hash)
{
readelf->symbol_hash_size = size / sizeof(Elf_Word);
if(readelf->symbol_hash_size >= 2)
{
readelf->symbol_hash_buckets = readelf->symbol_hash[0];
}
}
}
else
{
readelf->symbol_table = 0;
}
}
/* Bail out if we don't need to print debugging information */
if((flags & JIT_READELF_FLAG_DEBUG) == 0)
{
return;
}
/* Iterate through the ".dynamic" section, dumping all that we find */
dynamic_iter_init(&iter, readelf);
while(dynamic_iter_next(&iter, &type, &value))
{
switch(type)
{
case DT_NEEDED:
{
printf("needed library: %s\n", get_dyn_string(readelf, value));
}
break;
case DT_PLTRELSZ:
{
printf("total size of PLT relocs: %ld\n", (long)value);
}
break;
case DT_PLTGOT:
{
printf("address of PLTGOT table: 0x%lx\n", (long)value);
}
break;
case DT_HASH:
{
printf("address of symbol hash table: 0x%lx\n", (long)value);
}
break;
case DT_STRTAB:
{
printf("address of string table: 0x%lx\n", (long)value);
}
break;
case DT_SYMTAB:
{
printf("address of symbol table: 0x%lx\n", (long)value);
}
break;
case DT_STRSZ:
{
printf("size of string table: %ld\n", (long)value);
}
break;
case DT_SYMENT:
{
printf("size of one symbol table entry: %ld\n", (long)value);
}
break;
case DT_INIT:
{
printf("address of init function: 0x%lx\n", (long)value);
}
break;
case DT_FINI:
{
printf("address of fini function: 0x%lx\n", (long)value);
}
break;
case DT_SONAME:
{
printf("library name: %s\n", get_dyn_string(readelf, value));
}
break;
case DT_REL:
{
printf("address of Rel relocs: 0x%lx\n", (long)value);
}
break;
case DT_RELSZ:
{
printf("total size of Rel relocs: %ld\n", (long)value);
}
break;
case DT_RELENT:
{
printf("size of one Rel reloc: %ld\n", (long)value);
}
break;
case DT_RELA:
{
printf("address of Rela relocs: 0x%lx\n", (long)value);
}
break;
case DT_RELASZ:
{
printf("total size of Rela relocs: %ld\n", (long)value);
}
break;
case DT_RELAENT:
{
printf("size of one Rela reloc: %ld\n", (long)value);
}
break;
case DT_PLTREL:
{
printf("type of PLT relocs: %ld\n", (long)value);
}
break;
case DT_JMPREL:
{
printf("address of PLT relocs: 0x%lx\n", (long)value);
}
break;
default:
{
printf("dynamic info of type 0x%x: 0x%lx\n",
(int)type, (long)value);
}
break;
}
}
/* Iterate through the symbol table, dumping all of the entries */
for(size = 0; size < readelf->symbol_table_size; ++size)
{
printf("%08lX %02X%02X %2d %s\n",
(long)(readelf->symbol_table[size].st_value),
(int)(readelf->symbol_table[size].st_info),
(int)(readelf->symbol_table[size].st_other),
(int)(readelf->symbol_table[size].st_shndx),
get_dyn_string(readelf, readelf->symbol_table[size].st_name));
}
printf("number of symbols: %ld\n", (long)(readelf->symbol_table_size));
printf("number of symbol hash entries: %ld\n",
(long)(readelf->symbol_hash_size));
}
/*@
* @deftypefun int jit_readelf_open (jit_readelf_t *@var{readelf}, const char *@var{filename}, int @var{force})
* Open the specified @var{filename} and load the ELF binary that is
* contained within it. Returns one of the following result codes:
*
* @table @code
* @vindex JIT_READELF_OK
* @item JIT_READELF_OK
* The ELF binary was opened successfully.
*
* @vindex JIT_READELF_CANNOT_OPEN
* @item JIT_READELF_CANNOT_OPEN
* Could not open the file at the filesystem level (reason in @code{errno}).
*
* @vindex JIT_READELF_NOT_ELF
* @item JIT_READELF_NOT_ELF
* The file was opened, but it is not an ELF binary.
*
* @vindex JIT_READELF_WRONG_ARCH
* @item JIT_READELF_WRONG_ARCH
* The file is an ELF binary, but it does not pertain to the architecture
* of this machine.
*
* @vindex JIT_READELF_BAD_FORMAT
* @item JIT_READELF_BAD_FORMAT
* The file is an ELF binary, but the format is corrupted in some fashion.
*
* @vindex JIT_READELF_MEMORY
* @item JIT_READELF_MEMORY
* There is insufficient memory to open the ELF binary.
* @end table
*
* The following flags may be supplied to alter the manner in which
* the ELF binary is loaded:
*
* @table @code
* @vindex JIT_READELF_FLAG_FORCE
* @item JIT_READELF_FLAG_FORCE
* Force @code{jit_readelf_open} to open the ELF binary, even if
* the architecture does not match this machine. Useful for debugging.
*
* @vindex JIT_READELF_FLAG_DEBUG
* @item JIT_READELF_FLAG_DEBUG
* Print additional debug information to stdout.
* @end table
* @end deftypefun
@*/
int jit_readelf_open(jit_readelf_t *_readelf, const char *filename, int flags)
{
int fd;
Elf_Ehdr ehdr;
Elf_Phdr *phdr;
Elf_Shdr *shdr;
jit_elf_info_t elf_info;
jit_readelf_t readelf;
unsigned int phdr_size;
unsigned int shdr_size;
unsigned int index;
void *address;
union
{
jit_ushort value;
unsigned char bytes[2];
} un;
/* Get the machine and ABI values that we expect in the header */
_jit_gen_get_elf_info(&elf_info);
/* Open the file and read the ELF magic number information */
if((fd = sys_open(filename, O_RDONLY | O_BINARY, 0)) < 0)
{
return JIT_READELF_CANNOT_OPEN;
}
if(sys_read(fd, ehdr.e_ident, EI_NIDENT) != EI_NIDENT)
{
sys_close(fd);
return JIT_READELF_NOT_ELF;
}
/* Determine if the magic number matches what we expect to see */
if(ehdr.e_ident[EI_MAG0] != ELFMAG0 || ehdr.e_ident[EI_MAG1] != ELFMAG1 ||
ehdr.e_ident[EI_MAG2] != ELFMAG2 || ehdr.e_ident[EI_MAG3] != ELFMAG3)
{
sys_close(fd);
return JIT_READELF_NOT_ELF;
}
#ifdef JIT_NATIVE_INT32
if(ehdr.e_ident[EI_CLASS] != ELFCLASS32)
{
sys_close(fd);
return JIT_READELF_WRONG_ARCH;
}
#else
if(ehdr.e_ident[EI_CLASS] != ELFCLASS64)
{
sys_close(fd);
return JIT_READELF_WRONG_ARCH;
}
#endif
un.value = 0x0102;
if(un.bytes[0] == 0x01)
{
/* Looking for a big-endian binary */
if(ehdr.e_ident[EI_DATA] != ELFDATA2MSB)
{
sys_close(fd);
return JIT_READELF_WRONG_ARCH;
}
}
else
{
/* Looking for a little-endian binary */
if(ehdr.e_ident[EI_DATA] != ELFDATA2LSB)
{
sys_close(fd);
return JIT_READELF_WRONG_ARCH;
}
}
if(ehdr.e_ident[EI_VERSION] != EV_CURRENT)
{
sys_close(fd);
return JIT_READELF_BAD_FORMAT;
}
/* Read the rest of the ELF header and validate it */
if(sys_read(fd, &(ehdr.e_type), sizeof(Elf_Ehdr) - EI_NIDENT)
!= (sizeof(Elf_Ehdr) - EI_NIDENT))
{
sys_close(fd);
return JIT_READELF_BAD_FORMAT;
}
if(ehdr.e_type != ET_DYN)
{
/* We can only load files that are marked as dynamic shared objects */
sys_close(fd);
return JIT_READELF_WRONG_ARCH;
}
if((flags & JIT_READELF_FLAG_FORCE) == 0)
{
if(ehdr.e_machine != elf_info.machine ||
ehdr.e_ident[EI_OSABI] != elf_info.abi ||
ehdr.e_ident[EI_ABIVERSION] != elf_info.abi_version)
{
/* The ELF binary does not pertain to this machine or ABI type */
sys_close(fd);
return JIT_READELF_WRONG_ARCH;
}
}
if(ehdr.e_version != EV_CURRENT)
{
sys_close(fd);
return JIT_READELF_BAD_FORMAT;
}
if(ehdr.e_ehsize < sizeof(ehdr))
{
sys_close(fd);
return JIT_READELF_BAD_FORMAT;
}
/* Allocate space for the ELF reader object */
if((readelf = jit_cnew(struct jit_readelf)) == 0)
{
sys_close(fd);
return JIT_READELF_MEMORY;
}
readelf->ehdr = ehdr;
phdr_size = ((unsigned int)(ehdr.e_phnum)) *
((unsigned int)(ehdr.e_phentsize));
shdr_size = ((unsigned int)(ehdr.e_shnum)) *
((unsigned int)(ehdr.e_shentsize));
if(phdr_size > 0)
{
readelf->phdrs = (unsigned char *)jit_malloc(phdr_size);
if(!(readelf->phdrs))
{
jit_free(readelf);
sys_close(fd);
return JIT_READELF_MEMORY;
}
}
if(shdr_size > 0)
{
readelf->shdrs = (unsigned char *)jit_malloc(shdr_size);
if(!(readelf->shdrs))
{
jit_free(readelf->phdrs);
jit_free(readelf);
sys_close(fd);
return JIT_READELF_MEMORY;
}
}
/* Seek to the program and section header tables and read them */
if(phdr_size > 0)
{
if(lseek(fd, (off_t)(ehdr.e_phoff), 0) != (off_t)(ehdr.e_phoff) ||
read(fd, readelf->phdrs, phdr_size) != (int)phdr_size)
{
jit_free(readelf->shdrs);
jit_free(readelf->phdrs);
jit_free(readelf);
sys_close(fd);
return JIT_READELF_BAD_FORMAT;
}
}
if(shdr_size > 0)
{
if(lseek(fd, (off_t)(ehdr.e_shoff), 0) != (off_t)(ehdr.e_shoff) ||
read(fd, readelf->shdrs, shdr_size) != (int)shdr_size)
{
jit_free(readelf->shdrs);
jit_free(readelf->phdrs);
jit_free(readelf);
sys_close(fd);
return JIT_READELF_BAD_FORMAT;
}
}
/* Load the program segments */
if(!map_program(readelf, fd))
{
jit_readelf_close(readelf);
sys_close(fd);
return JIT_READELF_MEMORY;
}
/* Load the auxillary sections */
if(shdr_size > 0)
{
for(index = 0; index < ehdr.e_shnum; ++index)
{
shdr = get_shdr(readelf, index);
if(!shdr)
{
continue;
}
if((shdr->sh_flags & SHF_ALLOC) != 0 || shdr->sh_addr != 0)
{
/* This may be mapped inside one of the program segments.
If so, we don't want to load a second copy of it */
address = jit_readelf_map_vaddr(readelf, shdr->sh_addr);
if(address)
{
continue;
}
}
if(shdr->sh_size == 0)
{
/* Ignore zero-sized segments */
continue;
}
address = map_section
(fd, shdr->sh_offset, shdr->sh_size, shdr->sh_size,
((shdr->sh_flags & SHF_WRITE) != 0 ? (PF_W | PF_R) : PF_R));
if(!address)
{
jit_readelf_close(readelf);
sys_close(fd);
return JIT_READELF_MEMORY;
}
shdr->sh_offset = (Elf_Off)(jit_nuint)address;
shdr->sh_flags |= JIT_ELF_IS_MALLOCED;
}
}
/* Close the file descriptor because we don't need it any more */
sys_close(fd);
/* Find the regular string table */
shdr = get_shdr(readelf, ehdr.e_shstrndx);
if(shdr)
{
if((shdr->sh_flags & JIT_ELF_IS_MALLOCED) != 0)
{
readelf->regular_strings = (char *)(jit_nuint)(shdr->sh_offset);
}
else
{
readelf->regular_strings =
(char *)jit_readelf_map_vaddr(readelf, shdr->sh_addr);
}
if(readelf->regular_strings)
{
readelf->regular_strings_size = (jit_nuint)(shdr->sh_size);
}
}
/* Dump debug information about the program segments and sections */
if((flags & JIT_READELF_FLAG_DEBUG) != 0)
{
printf("header: machine=%d, abi=%d, abi_version=%d\n",
(int)(ehdr.e_machine), (int)(ehdr.e_ident[EI_OSABI]),
(int)(ehdr.e_ident[EI_ABIVERSION]));
for(index = 0; index < ehdr.e_phnum; ++index)
{
phdr = get_phdr(readelf, index);
if(phdr)
{
printf("program segment: type=%d, flags=0x%x, "
"vaddr=0x%lx, file_size=%ld, memory_size=%ld\n",
(int)(phdr->p_type),
(int)(phdr->p_flags & ~JIT_ELF_IS_MALLOCED),
(long)(phdr->p_vaddr),
(long)(phdr->p_filesz),
(long)(phdr->p_memsz));
}
}
for(index = 0; index < ehdr.e_shnum; ++index)
{
shdr = get_shdr(readelf, index);
if(shdr)
{
printf("section %2d: name=\"%s\", type=%d, flags=0x%x, "
"vaddr=0x%lx, size=%ld\n",
index,
get_string(readelf, shdr->sh_name),
(int)(shdr->sh_type),
(int)(shdr->sh_flags & ~JIT_ELF_IS_MALLOCED),
(long)(shdr->sh_addr),
(long)(shdr->sh_size));
}
}
}
/* Get the relocation function for this machine type */
readelf->reloc_func = get_reloc((unsigned int)(ehdr.e_machine));
/* Load useful values from the dynamic section that we want to cache */
load_dynamic_section(readelf, flags);
/* The ELF binary is loaded and ready to go */
*_readelf = readelf;
return JIT_READELF_OK;
}
/*@
* @deftypefun void jit_readelf_close (jit_readelf_t @var{readelf})
* Close an ELF reader, reclaiming all of the memory that was used.
* @end deftypefun
@*/
void jit_readelf_close(jit_readelf_t readelf)
{
unsigned int index;
Elf_Shdr *shdr;
if(!readelf)
{
return;
}
#ifdef JIT_USE_MMAP_TO_LOAD
if(readelf->free_with_munmap)
{
munmap(readelf->map_address, (size_t)(readelf->map_size));
}
else
#endif
{
jit_free_exec(readelf->map_address, readelf->map_size);
}
for(index = 0; index < readelf->ehdr.e_shnum; ++index)
{
shdr = get_shdr(readelf, index);
if(shdr && (shdr->sh_flags & JIT_ELF_IS_MALLOCED) != 0)
{
unmap_section
((void *)(jit_nuint)(shdr->sh_offset),
shdr->sh_size, shdr->sh_size, shdr->sh_flags);
}
}
jit_free(readelf->phdrs);
jit_free(readelf->shdrs);
jit_free(readelf);
}
/*@
* @deftypefun {const char *} jit_readelf_get_name (jit_readelf_t @var{readelf})
* Get the library name that is embedded inside an ELF binary.
* ELF binaries can refer to each other using this name.
* @end deftypefun
@*/
const char *jit_readelf_get_name(jit_readelf_t readelf)
{
Elf_Addr value;
if(dynamic_for_type(readelf, DT_SONAME, &value))
{
return get_dyn_string(readelf, value);
}
else
{
return 0;
}
}
/*@
* @deftypefun void *jit_readelf_get_symbol (jit_readelf_t @var{readelf}, const char *@var{name})
* Look up the symbol called @var{name} in the ELF binary represented
* by @var{readelf}. Returns NULL if the symbol is not present.
*
* External references from this ELF binary to others are not resolved
* until the ELF binary is loaded into a JIT context using
* @code{jit_readelf_add_to_context} and @code{jit_readelf_resolve_all}.
* You should not call functions within this ELF binary until after you
* have fully resolved it.
* @end deftypefun
@*/
void *jit_readelf_get_symbol(jit_readelf_t readelf, const char *name)
{
unsigned long hash;
unsigned long temp;
unsigned int index;
jit_nuint num_symbols;
Elf_Sym *symbol;
const char *symbol_name;
/* Bail out if we have insufficient information to resolve the name */
if(!readelf || !name || !(readelf->symbol_table))
{
return 0;
}
/* Hash the name to get the starting index in the symbol hash */
hash = 0;
index = 0;
while(name[index] != 0)
{
hash = (hash << 4) + (unsigned long)(name[index] & 0xFF);
temp = (hash & 0xF0000000);
if(temp != 0)
{
hash ^= temp | (temp >> 24);
}
++index;
}
/* Look in the hash table for the name */
if(readelf->symbol_hash_buckets != 0)
{
hash %= (unsigned long)(readelf->symbol_hash_buckets);
temp = (unsigned long)(readelf->symbol_hash[hash + 2]);
while(temp != 0 && temp < readelf->symbol_table_size)
{
symbol = &(readelf->symbol_table[temp]);
symbol_name = get_dyn_string(readelf, symbol->st_name);
if(symbol_name && !jit_strcmp(symbol_name, name))
{
/* Ignore symbols in section 0, as they are external */
if(symbol->st_shndx)
{
return jit_readelf_map_vaddr
(readelf, (jit_nuint)(symbol->st_value));
}
break;
}
temp = (unsigned long)(readelf->symbol_hash
[temp + readelf->symbol_hash_buckets + 2]);
}
return 0;
}
/* There is no hash table, so search for the symbol the hard way */
symbol = readelf->symbol_table;
for(num_symbols = readelf->symbol_table_size;
num_symbols > 0; --num_symbols)
{
symbol_name = get_dyn_string(readelf, symbol->st_name);
if(symbol_name && !jit_strcmp(symbol_name, name))
{
/* Ignore symbols in section 0, as they are external */
if(symbol->st_shndx)
{
return jit_readelf_map_vaddr
(readelf, (jit_nuint)(symbol->st_value));
}
}
++symbol;
}
return 0;
}
/*@
* @deftypefun {void *} jit_readelf_get_section (jit_readelf_t @var{readelf}, const char *@var{name}, jit_nuint *@var{size})
* Get the address and size of a particular section from an ELF binary.
* Returns NULL if the section is not present in the ELF binary.
*
* The virtual machine may have stored auxillary information
* in the section when the binary was first generated. This function
* allows the virtual machine to retrieve its auxillary information.
*
* Examples of such information may be version numbers, timestamps,
* checksums, and other identifying information for the bytecode that
* was previously compiled by the virtual machine. The virtual machine
* can use this to determine if the ELF binary is up to date and
* relevant to its needs.
*
* It is recommended that virtual machines prefix their special sections
* with a unique string (e.g. @code{.foovm}) to prevent clashes with
* system-defined section names. The prefix @code{.libjit} is reserved
* for use by @code{libjit} itself.
* @end deftypefun
@*/
void *jit_readelf_get_section
(jit_readelf_t readelf, const char *name, jit_nuint *size)
{
unsigned int index;
Elf_Shdr *shdr;
const char *temp_name;
if(!readelf || !name)
{
return 0;
}
for(index = 0; index < readelf->ehdr.e_shnum; ++index)
{
shdr = get_shdr(readelf, index);
if(shdr)
{
temp_name = get_string(readelf, shdr->sh_name);
if(temp_name && !jit_strcmp(name, temp_name))
{
if(size)
{
*size = (jit_nuint)(shdr->sh_size);
}
if((shdr->sh_flags & JIT_ELF_IS_MALLOCED) != 0)
{
return (void *)(jit_nuint)(shdr->sh_offset);
}
else
{
return jit_readelf_map_vaddr
(readelf, (jit_nuint)(shdr->sh_addr));
}
}
}
}
return 0;
}
/*@
* @deftypefun {void *} jit_readelf_get_section_by_type (jit_readelf_t @var{readelf}, jit_int @var{type}, jit_nuint *@var{size})
* Get a particular section using its raw ELF section type (i.e. one of
* the @code{SHT_*} constants in @code{jit-elf-defs.h}). This is mostly
* for internal use, but some virtual machines may find it useful for
* debugging purposes.
* @end deftypefun
@*/
void *jit_readelf_get_section_by_type
(jit_readelf_t readelf, jit_int type, jit_nuint *size)
{
unsigned int index;
Elf_Shdr *shdr;
if(!readelf)
{
return 0;
}
for(index = 0; index < readelf->ehdr.e_shnum; ++index)
{
shdr = get_shdr(readelf, index);
if(shdr && type == (jit_int)(shdr->sh_type))
{
if(size)
{
*size = (jit_nuint)(shdr->sh_size);
}
if((shdr->sh_flags & JIT_ELF_IS_MALLOCED) != 0)
{
return (void *)(jit_nuint)(shdr->sh_offset);
}
else
{
return jit_readelf_map_vaddr
(readelf, (jit_nuint)(shdr->sh_addr));
}
}
}
return 0;
}
/*@
* @deftypefun {void *} jit_readelf_map_vaddr (jit_readelf_t @var{readelf}, jit_nuint @var{vaddr})
* Map a virtual address to an actual address in a loaded ELF binary.
* Returns NULL if @var{vaddr} could not be mapped.
* @end deftypefun
@*/
void *jit_readelf_map_vaddr(jit_readelf_t readelf, jit_nuint vaddr)
{
unsigned int index;
Elf_Phdr *phdr;
if(!readelf)
{
return 0;
}
for(index = 0; index < readelf->ehdr.e_phnum; ++index)
{
phdr = get_phdr(readelf, index);
if(phdr && vaddr >= phdr->p_vaddr &&
vaddr < (phdr->p_vaddr + phdr->p_memsz))
{
return (void *)(((unsigned char *)(readelf->map_address)) + vaddr);
}
}
return 0;
}
/*@
* @deftypefun {unsigned int} jit_readelf_num_needed (jit_readelf_t @var{readelf})
* Get the number of dependent libraries that are needed by this
* ELF binary. The virtual machine will normally need to arrange
* to load these libraries with @code{jit_readelf_open} as well,
* so that all of the necessary symbols can be resolved.
* @end deftypefun
@*/
unsigned int jit_readelf_num_needed(jit_readelf_t readelf)
{
jit_dynamic_iter_t iter;
unsigned int count = 0;
jit_int type;
Elf_Addr value;
dynamic_iter_init(&iter, readelf);
while(dynamic_iter_next(&iter, &type, &value))
{
if(type == DT_NEEDED)
{
++count;
}
}
return count;
}
/*@
* @deftypefun {const char *} jit_readelf_get_needed (jit_readelf_t @var{readelf}, unsigned int @var{index})
* Get the name of the dependent library at position @var{index} within
* the needed libraries list of this ELF binary. Returns NULL if
* the @var{index} is invalid.
* @end deftypefun
@*/
const char *jit_readelf_get_needed(jit_readelf_t readelf, unsigned int index)
{
jit_dynamic_iter_t iter;
jit_int type;
Elf_Addr value;
dynamic_iter_init(&iter, readelf);
while(dynamic_iter_next(&iter, &type, &value))
{
if(type == DT_NEEDED)
{
if(index == 0)
{
return get_dyn_string(readelf, value);
}
--index;
}
}
return 0;
}
/*@
* @deftypefun void jit_readelf_add_to_context (jit_readelf_t @var{readelf}, jit_context_t @var{context})
* Add this ELF binary to a JIT context, so that its contents can be used
* when executing JIT-managed code. The binary will be closed automatically
* if the context is destroyed and @code{jit_readelf_close} has not been
* called explicitly yet.
*
* The functions in the ELF binary cannot be used until you also call
* @code{jit_readelf_resolve_all} to resolve cross-library symbol references.
* The reason why adding and resolution are separate steps is to allow for
* resolving circular dependencies between ELF binaries.
* @end deftypefun
@*/
void jit_readelf_add_to_context(jit_readelf_t readelf, jit_context_t context)
{
if(!readelf || !context)
{
return;
}
jit_mutex_lock(&(context->cache_lock));
readelf->next = context->elf_binaries;
context->elf_binaries = readelf;
jit_mutex_unlock(&(context->cache_lock));
}
/*
* Import the internal symbol table from "jit-symbol.c".
*/
typedef struct
{
const char *name;
void *value;
} jit_internalsym;
extern jit_internalsym const _jit_internal_symbols[];
extern int const _jit_num_internal_symbols;
/*
* Resolve a symbol to an address.
*/
static void *resolve_symbol
(jit_context_t context, jit_readelf_t readelf,
int print_failures, const char *name, jit_nuint symbol)
{
Elf_Sym *sym;
void *value;
const char *symbol_name;
jit_readelf_t library;
int index, left, right, cmp;
/* Find the actual symbol details */
if(symbol >= readelf->symbol_table_size)
{
if(print_failures)
{
printf("%s: invalid symbol table index %lu\n",
name, (unsigned long)symbol);
}
return 0;
}
sym = &(readelf->symbol_table[symbol]);
/* Does the symbol have a locally-defined value? */
if(sym->st_value)
{
value = jit_readelf_map_vaddr(readelf, (jit_nuint)(sym->st_value));
if(!value)
{
if(print_failures)
{
printf("%s: could not map virtual address 0x%lx\n",
name, (long)(sym->st_value));
}
}
return value;
}
/* Get the symbol's name, so that we can look it up in other libraries */
symbol_name = get_dyn_string(readelf, sym->st_name);
if(!symbol_name)
{
if(print_failures)
{
printf("%s: symbol table index %lu does not have a valid name\n",
name, (unsigned long)symbol);
}
return 0;
}
/* Look for "before" symbols that are registered with the context */
for(index = 0; index < context->num_registered_symbols; ++index)
{
if(!jit_strcmp(symbol_name, context->registered_symbols[index]->name) &&
!(context->registered_symbols[index]->after))
{
return context->registered_symbols[index]->value;
}
}
/* Search all loaded ELF libraries for the name */
library = context->elf_binaries;
while(library != 0)
{
value = jit_readelf_get_symbol(library, symbol_name);
if(value)
{
return value;
}
library = library->next;
}
/* Look for libjit internal symbols (i.e. intrinsics) */
left = 0;
right = _jit_num_internal_symbols - 1;
while(left <= right)
{
index = (left + right) / 2;
cmp = jit_strcmp(symbol_name, _jit_internal_symbols[index].name);
if(cmp == 0)
{
return _jit_internal_symbols[index].value;
}
else if(cmp < 0)
{
right = index - 1;
}
else
{
left = index + 1;
}
}
/* Look for "after" symbols that are registered with the context */
for(index = 0; index < context->num_registered_symbols; ++index)
{
if(!jit_strcmp(symbol_name, context->registered_symbols[index]->name) &&
context->registered_symbols[index]->after)
{
return context->registered_symbols[index]->value;
}
}
/* If we get here, then we could not resolve the symbol */
printf("%s: could not resolve `%s'\n", name, symbol_name);
return 0;
}
/*
* Perform a DT_REL style relocation on an ELF binary.
*/
static int perform_rel
(jit_context_t context, jit_readelf_t readelf,
int print_failures, const char *name, Elf_Rel *reloc)
{
void *address;
void *value;
/* Get the address to apply the relocation at */
address = jit_readelf_map_vaddr(readelf, (jit_nuint)(reloc->r_offset));
if(!address)
{
if(print_failures)
{
printf("%s: cannot map virtual address 0x%lx\n",
name, (long)(reloc->r_offset));
}
return 0;
}
/* Resolve the designated symbol to its actual value */
value = resolve_symbol
(context, readelf, print_failures, name,
(jit_nuint)ELF_R_SYM(reloc->r_info));
if(!value)
{
return 0;
}
/* Perform the relocation */
if(!(*(readelf->reloc_func))
(readelf, address, (int)(ELF_R_TYPE(reloc->r_info)),
(jit_nuint)value, 0, 0))
{
if(print_failures)
{
printf("%s: relocation type %d was not recognized\n",
name, (int)(ELF_R_TYPE(reloc->r_info)));
}
return 0;
}
return 1;
}
/*
* Perform a DT_RELA style relocation on an ELF binary.
*/
static int perform_rela
(jit_context_t context, jit_readelf_t readelf,
int print_failures, const char *name, Elf_Rela *reloc)
{
void *address;
void *value;
/* Get the address to apply the relocation at */
address = jit_readelf_map_vaddr(readelf, (jit_nuint)(reloc->r_offset));
if(!address)
{
if(print_failures)
{
printf("%s: cannot map virtual address 0x%lx\n",
name, (long)(reloc->r_offset));
}
return 0;
}
/* Resolve the designated symbol to its actual value */
value = resolve_symbol
(context, readelf, print_failures, name,
(jit_nuint)ELF_R_SYM(reloc->r_info));
if(!value)
{
return 0;
}
/* Perform the relocation */
if(!(*(readelf->reloc_func))
(readelf, address, (int)(ELF_R_TYPE(reloc->r_info)),
(jit_nuint)value, 1, (jit_nuint)(reloc->r_addend)))
{
if(print_failures)
{
printf("%s: relocation type %d was not recognized\n",
name, (int)(ELF_R_TYPE(reloc->r_info)));
}
return 0;
}
return 1;
}
/*
* Perform relocations on an ELF binary. Returns zero on failure.
*/
static int perform_relocations
(jit_context_t context, jit_readelf_t readelf, int print_failures)
{
Elf_Addr address;
Elf_Addr table_size;
Elf_Addr entry_size;
unsigned char *table;
const char *name;
int ok = 1;
/* Get the library name, for printing diagnostic messages */
name = jit_readelf_get_name(readelf);
if(!name)
{
name = "unknown-elf-binary";
}
/* Bail out if we don't know how to perform relocations */
if(!(readelf->reloc_func))
{
if(print_failures)
{
printf("%s: do not know how to perform relocations\n", name);
}
return 0;
}
/* Apply the "Rel" relocations in the dynamic section */
if(dynamic_for_type(readelf, DT_REL, &address) &&
dynamic_for_type(readelf, DT_RELSZ, &table_size) &&
dynamic_for_type(readelf, DT_RELENT, &entry_size) && entry_size)
{
table = (unsigned char *)jit_readelf_map_vaddr
(readelf, (jit_nuint)address);
while(table && table_size >= entry_size)
{
if(!perform_rel(context, readelf, print_failures, name,
(Elf_Rel *)table))
{
ok = 0;
}
table += (jit_nuint)entry_size;
table_size -= entry_size;
}
}
/* Apply the "Rela" relocations in the dynamic section */
if(dynamic_for_type(readelf, DT_RELA, &address) &&
dynamic_for_type(readelf, DT_RELASZ, &table_size) &&
dynamic_for_type(readelf, DT_RELAENT, &entry_size) && entry_size)
{
table = (unsigned char *)jit_readelf_map_vaddr
(readelf, (jit_nuint)address);
while(table && table_size >= entry_size)
{
if(!perform_rela(context, readelf, print_failures, name,
(Elf_Rela *)table))
{
ok = 0;
}
table += (jit_nuint)entry_size;
table_size -= entry_size;
}
}
/* Apply the "PLT" relocations in the dynamic section, which
may be either DT_REL or DT_RELA style relocations */
if(dynamic_for_type(readelf, DT_JMPREL, &address) &&
dynamic_for_type(readelf, DT_PLTRELSZ, &table_size) &&
dynamic_for_type(readelf, DT_PLTREL, &entry_size))
{
if(entry_size == DT_REL)
{
if(dynamic_for_type(readelf, DT_RELENT, &entry_size) && entry_size)
{
table = (unsigned char *)jit_readelf_map_vaddr
(readelf, (jit_nuint)address);
while(table && table_size >= entry_size)
{
if(!perform_rel(context, readelf, print_failures, name,
(Elf_Rel *)table))
{
ok = 0;
}
table += (jit_nuint)entry_size;
table_size -= entry_size;
}
}
}
else if(entry_size == DT_RELA)
{
if(dynamic_for_type(readelf, DT_RELAENT, &entry_size) && entry_size)
{
table = (unsigned char *)jit_readelf_map_vaddr
(readelf, (jit_nuint)address);
while(table && table_size >= entry_size)
{
if(!perform_rela(context, readelf, print_failures, name,
(Elf_Rela *)table))
{
ok = 0;
}
table += (jit_nuint)entry_size;
table_size -= entry_size;
}
}
}
}
/* Return to the caller */
return ok;
}
/*@
* @deftypefun int jit_readelf_resolve_all (jit_context_t @var{context}, int @var{print_failures})
* Resolve all of the cross-library symbol references in ELF binaries
* that have been added to @var{context} but which were not resolved
* in the previous call to this function. If @var{print_failures}
* is non-zero, then diagnostic messages will be written to stdout
* for any symbol resolutions that fail.
*
* Returns zero on failure, or non-zero if all symbols were successfully
* resolved. If there are no ELF binaries awaiting resolution, then
* this function will return a non-zero result.
* @end deftypefun
@*/
int jit_readelf_resolve_all(jit_context_t context, int print_failures)
{
jit_readelf_t readelf;
int ok = 1;
if(!context)
{
return 0;
}
jit_mutex_lock(&(context->cache_lock));
readelf = context->elf_binaries;
while(readelf != 0)
{
if(!(readelf->resolved))
{
readelf->resolved = 1;
if(!perform_relocations(context, readelf, print_failures))
{
ok = 0;
}
}
readelf = readelf->next;
}
jit_mutex_unlock(&(context->cache_lock));
return ok;
}
/*@
* @deftypefun int jit_readelf_register_symbol (jit_context_t @var{context}, const char *@var{name}, void *@var{value}, int @var{after})
* Register @var{value} with @var{name} on the specified @var{context}.
* Whenever symbols are resolved with @code{jit_readelf_resolve_all},
* and the symbol @var{name} is encountered, @var{value} will be
* substituted. Returns zero if out of memory or there is something
* wrong with the parameters.
*
* If @var{after} is non-zero, then @var{name} will be resolved after all
* other ELF libraries; otherwise it will be resolved before the ELF
* libraries.
*
* This function is used to register intrinsic symbols that are specific to
* the front end virtual machine. References to intrinsics within
* @code{libjit} itself are resolved automatically.
* @end deftypefun
@*/
int jit_readelf_register_symbol
(jit_context_t context, const char *name, void *value, int after)
{
jit_regsym_t sym;
jit_regsym_t *new_list;
/* Bail out if there is something wrong with the parameters */
if(!context || !name || !value)
{
return 0;
}
/* Allocate and populate the symbol information block */
sym = (jit_regsym_t)jit_malloc
(sizeof(struct jit_regsym) + jit_strlen(name));
if(!sym)
{
return 0;
}
sym->value = value;
sym->after = after;
jit_strcpy(sym->name, name);
/* Add the symbol details to the registered list */
new_list = (jit_regsym_t *)jit_realloc
(context->registered_symbols,
sizeof(jit_regsym_t) * (context->num_registered_symbols + 1));
if(!new_list)
{
jit_free(sym);
return 0;
}
new_list[(context->num_registered_symbols)++] = sym;
context->registered_symbols = new_list;
return 1;
}
/************************************************************************
Warning! Warning! Warning!
The following code is very system-dependent, as every ELF target has its
own peculiar mechanism for performing relocations. Consult your target's
documentation for the precise details.
To make things a little easier, you only need to support the relocation
types that you intend to use in the JIT's ELF writer. And many types
only pertain to ELF executable or object files, which we don't use.
************************************************************************/
#if defined(__i386) || defined(__i386__) || defined(_M_IX86)
/*
* Apply relocations for i386 platforms.
*/
static int i386_reloc(jit_readelf_t readelf, void *address, int type,
jit_nuint value, int has_addend, jit_nuint addend)
{
if(type == R_386_32)
{
if(has_addend)
{
*((jit_nuint *)address) = value + addend;
}
else
{
*((jit_nuint *)address) += value;
}
return 1;
}
else if(type == R_386_PC32)
{
value -= (jit_nuint)address;
if(has_addend)
{
*((jit_nuint *)address) = value + addend;
}
else
{
*((jit_nuint *)address) += value;
}
return 1;
}
return 0;
}
#endif /* i386 */
#if defined(__arm) || defined(__arm__)
/*
* Apply relocations for ARM platforms.
*/
static int arm_reloc(jit_readelf_t readelf, void *address, int type,
jit_nuint value, int has_addend, jit_nuint addend)
{
if(type == R_ARM_PC24)
{
value -= (jit_nuint)address;
if(has_addend)
{
*((jit_nuint *)address) =
(*((jit_nuint *)address) & 0xFF000000) + value + addend;
}
else
{
*((jit_nuint *)address) += value;
}
return 1;
}
else if(type == R_ARM_ABS32)
{
if(has_addend)
{
*((jit_nuint *)address) = value + addend;
}
else
{
*((jit_nuint *)address) += value;
}
return 1;
}
else if(type == R_ARM_REL32)
{
value -= (jit_nuint)address;
if(has_addend)
{
*((jit_nuint *)address) = value + addend;
}
else
{
*((jit_nuint *)address) += value;
}
return 1;
}
return 0;
}
#endif /* arm */
/*
* Apply relocations for the interpreted platform.
*/
static int interp_reloc(jit_readelf_t readelf, void *address, int type,
jit_nuint value, int has_addend, jit_nuint addend)
{
/* We only have one type of relocation for the interpreter: direct */
if(type == 1)
{
*((jit_nuint *)address) = value;
return 1;
}
else
{
return 0;
}
}
/*
* Get the relocation function for a particular machine type.
*/
static jit_reloc_func get_reloc(unsigned int machine)
{
#if defined(__i386) || defined(__i386__) || defined(_M_IX86)
if(machine == EM_386)
{
return i386_reloc;
}
#endif
#if defined(__arm) || defined(__arm__)
if(machine == EM_ARM)
{
return arm_reloc;
}
#endif
if(machine == 0x4C6A) /* "Lj" for the libjit interpreter */
{
return interp_reloc;
}
return 0;
}
|
DragonL/YAC6xSim
|
p3/libjit/libjit-0.1.2/jit/jit-elf-read.c
|
C
|
gpl-2.0
| 48,749
|
/* $OpenBSD: tty_tb.c,v 1.5 2003/08/11 09:56:49 mickey Exp $ */
/* $NetBSD: tty_tb.c,v 1.18 1996/02/04 02:17:36 christos Exp $ */
/*-
* Copyright (c) 1982, 1986, 1991, 1993
* The Regents of the University of California. 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.
* 3. 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.
*
* @(#)tty_tb.c 8.1 (Berkeley) 6/10/93
*/
#include "tb.h"
/*
* Line discipline for RS232 tablets;
* supplies binary coordinate data.
*/
#include <sys/param.h>
#include <sys/tablet.h>
#include <sys/systm.h>
#include <sys/ioctl.h>
#include <sys/ioctl_compat.h>
#include <sys/tty.h>
#include <sys/proc.h>
union tbpos {
struct hitpos hitpos;
struct gtcopos gtcopos;
struct polpos polpos;
};
/*
* Tablet configuration table.
*/
struct tbconf {
short tbc_recsize; /* input record size in bytes */
short tbc_uiosize; /* size of data record returned user */
int tbc_sync; /* mask for finding sync byte/bit */
/* decoding routine */
void (*tbc_decode)(const struct tbconf *, char *, union tbpos *);
u_char *tbc_run; /* enter run mode sequence */
u_char *tbc_point; /* enter point mode sequence */
u_char *tbc_stop; /* stop sequence */
u_char *tbc_start; /* start/restart sequence */
int tbc_flags;
#define TBF_POL 0x1 /* polhemus hack */
#define TBF_INPROX 0x2 /* tablet has proximity info */
};
static void gtcodecode(const struct tbconf *, char *, union tbpos *);
static void tbolddecode(const struct tbconf *, char *, union tbpos *);
static void tblresdecode(const struct tbconf *, char *, union tbpos *);
static void tbhresdecode(const struct tbconf *, char *, union tbpos *);
static void poldecode(const struct tbconf *, char *, union tbpos *);
const struct tbconf tbconf[TBTYPE] = {
{ 0 },
{ 5, sizeof (struct hitpos), 0200, tbolddecode, "6", "4" },
{ 5, sizeof (struct hitpos), 0200, tbolddecode, "\1CN", "\1RT", "\2", "\4" },
{ 8, sizeof (struct gtcopos), 0200, gtcodecode },
{17, sizeof (struct polpos), 0200, poldecode, 0, 0, "\21", "\5\22\2\23",
TBF_POL },
{ 5, sizeof (struct hitpos), 0100, tblresdecode, "\1CN", "\1PT", "\2", "\4",
TBF_INPROX },
{ 6, sizeof (struct hitpos), 0200, tbhresdecode, "\1CN", "\1PT", "\2", "\4",
TBF_INPROX },
{ 5, sizeof (struct hitpos), 0100, tblresdecode, "\1CL\33", "\1PT\33", 0, 0},
{ 6, sizeof (struct hitpos), 0200, tbhresdecode, "\1CL\33", "\1PT\33", 0, 0},
};
/*
* Tablet state
*/
struct tb {
int tbflags; /* mode & type bits */
#define TBMAXREC 17 /* max input record size */
char cbuf[TBMAXREC]; /* input buffer */
int tbinbuf;
char *tbcp;
union tbpos tbpos;
} tb[NTB];
int tbopen(dev_t, struct tty *);
void tbclose(struct tty *);
int tbread(struct tty *, struct uio *);
void tbinput(int, struct tty *);
int tbtioctl(struct tty *, u_long, caddr_t, int, struct proc *);
void tbattach(int);
/*
* Open as tablet discipline; called on discipline change.
*/
/*ARGSUSED*/
int
tbopen(dev, tp)
dev_t dev;
register struct tty *tp;
{
register struct tb *tbp;
if (tp->t_line == TABLDISC)
return (ENODEV);
ttywflush(tp);
for (tbp = tb; tbp < &tb[NTB]; tbp++)
if (tbp->tbflags == 0)
break;
if (tbp >= &tb[NTB])
return (EBUSY);
tbp->tbflags = TBTIGER|TBPOINT; /* default */
tbp->tbcp = tbp->cbuf;
tbp->tbinbuf = 0;
bzero((caddr_t)&tbp->tbpos, sizeof (tbp->tbpos));
tp->t_sc = (caddr_t)tbp;
tp->t_flags |= LITOUT;
return (0);
}
/*
* Line discipline change or last device close.
*/
void
tbclose(tp)
register struct tty *tp;
{
int modebits = TBPOINT|TBSTOP;
tbtioctl(tp, BIOSMODE, (caddr_t) &modebits, 0, curproc);
}
/*
* Read from a tablet line.
* Characters have been buffered in a buffer and decoded.
*/
int
tbread(tp, uio)
register struct tty *tp;
struct uio *uio;
{
struct tb *tbp = (struct tb *)tp->t_sc;
const struct tbconf *tc = &tbconf[tbp->tbflags & TBTYPE];
int ret;
if ((tp->t_state&TS_CARR_ON) == 0)
return (EIO);
ret = uiomove((caddr_t) &tbp->tbpos, tc->tbc_uiosize, uio);
if (tc->tbc_flags&TBF_POL)
tbp->tbpos.polpos.p_key = ' ';
return (ret);
}
/*
* Low level character input routine.
* Stuff the character in the buffer, and decode
* if all the chars are there.
*
* This routine could be expanded in-line in the receiver
* interrupt routine to make it run as fast as possible.
*/
void
tbinput(c, tp)
register int c;
register struct tty *tp;
{
struct tb *tbp = (struct tb *)tp->t_sc;
const struct tbconf *tc = &tbconf[tbp->tbflags & TBTYPE];
if (tc->tbc_recsize == 0 || tc->tbc_decode == 0) /* paranoid? */
return;
/*
* Locate sync bit/byte or reset input buffer.
*/
if (c&tc->tbc_sync || tbp->tbinbuf == tc->tbc_recsize) {
tbp->tbcp = tbp->cbuf;
tbp->tbinbuf = 0;
}
*tbp->tbcp++ = c&0177;
/*
* Call decode routine only if a full record has been collected.
*/
if (++tbp->tbinbuf == tc->tbc_recsize)
(*tc->tbc_decode)(tc, tbp->cbuf, &tbp->tbpos);
}
/*
* Decode GTCO 8 byte format (high res, tilt, and pressure).
*/
static void
gtcodecode(tc, cp, u)
const struct tbconf *tc;
register char *cp;
register union tbpos *u;
{
struct gtcopos *pos = &u->gtcopos;
pos->pressure = *cp >> 2;
pos->status = (pos->pressure > 16) | TBINPROX; /* half way down */
pos->xpos = (*cp++ & 03) << 14;
pos->xpos |= *cp++ << 7;
pos->xpos |= *cp++;
pos->ypos = (*cp++ & 03) << 14;
pos->ypos |= *cp++ << 7;
pos->ypos |= *cp++;
pos->xtilt = *cp++;
pos->ytilt = *cp++;
pos->scount++;
}
/*
* Decode old Hitachi 5 byte format (low res).
*/
static void
tbolddecode(tc, cp, u)
const struct tbconf *tc;
register char *cp;
register union tbpos *u;
{
struct hitpos *pos = &u->hitpos;
register char byte;
byte = *cp++;
pos->status = (byte&0100) ? TBINPROX : 0;
byte &= ~0100;
if (byte > 036)
pos->status |= 1 << ((byte-040)/2);
pos->xpos = *cp++ << 7;
pos->xpos |= *cp++;
if (pos->xpos < 256) /* tablet wraps around at 256 */
pos->status &= ~TBINPROX; /* make it out of proximity */
pos->ypos = *cp++ << 7;
pos->ypos |= *cp++;
pos->scount++;
}
/*
* Decode new Hitach 5-byte format (low res).
*/
static void
tblresdecode(tc, cp, u)
const struct tbconf *tc;
register char *cp;
register union tbpos *u;
{
struct hitpos *pos = &u->hitpos;
*cp &= ~0100; /* mask sync bit */
pos->status = (*cp++ >> 2) | TBINPROX;
if (tc->tbc_flags&TBF_INPROX && pos->status&020)
pos->status &= ~(020|TBINPROX);
pos->xpos = *cp++;
pos->xpos |= *cp++ << 6;
pos->ypos = *cp++;
pos->ypos |= *cp++ << 6;
pos->scount++;
}
/*
* Decode new Hitach 6-byte format (high res).
*/
static void
tbhresdecode(tc, cp, u)
const struct tbconf *tc;
register char *cp;
register union tbpos *u;
{
struct hitpos *pos = &u->hitpos;
char byte;
byte = *cp++;
pos->xpos = (byte & 03) << 14;
pos->xpos |= *cp++ << 7;
pos->xpos |= *cp++;
pos->ypos = *cp++ << 14;
pos->ypos |= *cp++ << 7;
pos->ypos |= *cp++;
pos->status = (byte >> 2) | TBINPROX;
if (tc->tbc_flags&TBF_INPROX && pos->status&020)
pos->status &= ~(020|TBINPROX);
pos->scount++;
}
/*
* Polhemus decode.
*/
static void
poldecode(tc, cp, u)
const struct tbconf *tc;
register char *cp;
register union tbpos *u;
{
struct polpos *pos = &u->polpos;
pos->p_x = cp[4] | cp[3]<<7 | (cp[9] & 0x03) << 14;
pos->p_y = cp[6] | cp[5]<<7 | (cp[9] & 0x0c) << 12;
pos->p_z = cp[8] | cp[7]<<7 | (cp[9] & 0x30) << 10;
pos->p_azi = cp[11] | cp[10]<<7 | (cp[16] & 0x03) << 14;
pos->p_pit = cp[13] | cp[12]<<7 | (cp[16] & 0x0c) << 12;
pos->p_rol = cp[15] | cp[14]<<7 | (cp[16] & 0x30) << 10;
pos->p_stat = cp[1] | cp[0]<<7;
if (cp[2] != ' ')
pos->p_key = cp[2];
}
/*ARGSUSED*/
int
tbtioctl(tp, cmd, data, flag, p)
struct tty *tp;
u_long cmd;
caddr_t data;
int flag;
struct proc *p;
{
register struct tb *tbp = (struct tb *)tp->t_sc;
switch (cmd) {
case BIOGMODE:
*(int *)data = tbp->tbflags & TBMODE;
break;
case BIOSTYPE:
if (tbconf[*(int *)data & TBTYPE].tbc_recsize == 0 ||
tbconf[*(int *)data & TBTYPE].tbc_decode == 0)
return (EINVAL);
tbp->tbflags &= ~TBTYPE;
tbp->tbflags |= *(int *)data & TBTYPE;
/* fall thru... to set mode bits */
case BIOSMODE: {
const struct tbconf *tc;
u_char *c;
tbp->tbflags &= ~TBMODE;
tbp->tbflags |= *(int *)data & TBMODE;
tc = &tbconf[tbp->tbflags & TBTYPE];
if (tbp->tbflags & TBSTOP) {
if (tc->tbc_stop)
for (c = tc->tbc_stop; *c != '\0'; c++)
ttyoutput(*c, tp);
} else if (tc->tbc_start)
for (c = tc->tbc_start; *c != '\0'; c++)
ttyoutput(*c, tp);
if (tbp->tbflags & TBPOINT) {
if (tc->tbc_point)
for (c = tc->tbc_point; *c != '\0'; c++)
ttyoutput(*c, tp);
} else if (tc->tbc_run)
for (c = tc->tbc_run; *c != '\0'; c++)
ttyoutput(*c, tp);
ttstart(tp);
break;
}
case BIOGTYPE:
*(int *)data = tbp->tbflags & TBTYPE;
break;
case TIOCSETD:
case TIOCGETD:
case TIOCGETP:
case TIOCGETC:
return (-1); /* pass thru... */
default:
return (ENOTTY);
}
return (0);
}
void
tbattach(dummy)
int dummy;
{
/* stub to handle side effect of new config */
}
|
binhqnguyen/ln
|
nsc/openbsd3/kern/tty_tb.c
|
C
|
gpl-2.0
| 10,385
|
<?php
/**
* NoNumber Framework Helper File: Assignments: ZOO
*
* @package NoNumber Framework
* @version 12.5.1
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2012 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
// No direct access
defined('_JEXEC') or die;
/**
* Assignments: ZOO
*/
class NNFrameworkAssignmentsZOO
{
var $_version = '12.5.1';
/**
* passCategories_Zoo
*
* @param <object> $params
* inc_children
* inc_categories
* inc_items
* @param <array> $selection
* @param <string> $assignment
*
* @return <bool>
*/
function passCategories_ZOO(&$main, &$params, $selection = array(), $assignment = 'all', $article = 0)
{
if ($main->_params->option != 'com_zoo') {
return ($assignment == 'exclude');
}
if (!$main->_params->view) {
$main->_params->view = $main->_params->task;
}
$pass = (
($params->inc_apps && $main->_params->view == 'frontpage')
|| ($params->inc_categories && $main->_params->view == 'category')
|| ($params->inc_items && $main->_params->view == 'item')
);
if (!$pass) {
return ($assignment == 'exclude');
}
$selection = $main->makeArray($selection);
$cats = array();
if ($article && isset($article->catid)) {
$cats = $article->catid;
} else {
switch ($main->_params->view) {
case 'frontpage':
if ($main->_params->id) {
$cats[] = $main->_params->id;
} else {
$menuparams = $main->getMenuItemParams($main->_params->Itemid);
if (isset($menuparams->application)) {
$cats[] = 'app'.$menuparams->application;
}
}
break;
case 'category':
if ($main->_params->id) {
$cats[] = $main->_params->id;
} else {
$menuparams = $main->getMenuItemParams($main->_params->Itemid);
if (isset($menuparams->category)) {
$cats[] = $menuparams->category;
}
}
if ($cats['0']) {
$query = 'SELECT application_id'
.' FROM #__zoo_category'
.' WHERE id = '.(int) $cats['0']
.' LIMIT 1';
$main->_db->setQuery($query);
if ($main->_db->loadResult()) {
$cats[] = 'app'.$main->_db->loadResult();
}
}
break;
case 'item':
$id = $main->_params->id;
if (!$id) {
$menuparams = $main->getMenuItemParams($main->_params->Itemid);
$id = isset($menuparams->item_id) ? $menuparams->item_id : '';
}
if ($id) {
$query = 'SELECT category_id'
.' FROM #__zoo_category_item'
.' WHERE item_id = '.(int) $id
.' AND category_id != 0';
$main->_db->setQuery($query);
$cats = $main->_db->loadResultArray();
$query = 'SELECT application_id'
.' FROM #__zoo_item'
.' WHERE id = '.(int) $id
.' LIMIT 1';
$main->_db->setQuery($query);
$cats[] = 'app'.$main->_db->loadResult();
}
break;
default:
return ($assignment == 'exclude');
break;
}
}
$cats = $main->makeArray($cats);
$pass = $main->passSimple($cats, $selection, 'include');
if ($pass && $params->inc_children == 2) {
return ($assignment == 'exclude');
} else if (!$pass && $params->inc_children) {
foreach ($cats as $cat) {
$cats = array_merge($cats, NNFrameworkAssignmentsZOO::getCatParentIds($main, $cat));
}
}
return $main->passSimple($cats, $selection, $assignment);
}
function getCatParentIds(&$main, $id = 0)
{
$parent_ids = array();
if (!$id) {
return $parent_ids;
}
while ($id) {
if (substr($id, 0, 3) == 'app') {
$parent_ids[] = $id;
break;
} else {
$query = 'SELECT parent'
.' FROM #__zoo_category'
.' WHERE id = '.(int) $id
.' LIMIT 1';
$main->_db->setQuery($query);
$pid = $main->_db->loadResult();
if ($pid) {
$parent_ids[] = $pid;
} else {
$query = 'SELECT application_id'
.' FROM #__zoo_category'
.' WHERE id = '.(int) $id
.' LIMIT 1';
$main->_db->setQuery($query);
$app = $main->_db->loadResult();
if ($app) {
$parent_ids[] = 'app'.$app;
}
break;
}
$id = $pid;
}
}
return $parent_ids;
}
}
|
ashaury/sanlexb
|
plugins/system/nnframework/helpers/assignments/zoo.php
|
PHP
|
gpl-2.0
| 4,212
|
/***************************************************************************
testqgsvectorfilewriter.cpp
--------------------------------------
Date : Frida Nov 23 2007
Copyright : (C) 2007 by Tim Sutton
Email : tim@linfiniti.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. *
* *
***************************************************************************/
#include <QApplication>
#include <QObject>
#include <QSplashScreen>
#include <QString>
#include <QStringList>
#include <QtTest/QtTest>
#include <qgisapp.h>
#include <qgsapplication.h>
#include <qgsfeature.h>
#include <qgsfield.h>
#include <qgsclipboard.h>
#include <qgsmaplayerregistry.h>
#include <qgsvectorlayer.h>
/** \ingroup UnitTests
* This is a unit test for the QgisApp clipboard.
*/
class TestQgisAppClipboard : public QObject
{
Q_OBJECT
public:
TestQgisAppClipboard();
private slots:
void initTestCase();// will be called before the first testfunction is executed.
void cleanupTestCase();// will be called after the last testfunction was executed.
void init() {} // will be called before each testfunction is executed.
void cleanup() {} // will be called after every testfunction.
void copyPaste();
private:
QgisApp * mQgisApp;
QString mTestDataDir;
};
TestQgisAppClipboard::TestQgisAppClipboard()
: mQgisApp( nullptr )
{
}
//runs before all tests
void TestQgisAppClipboard::initTestCase()
{
qDebug() << "TestQgisAppClipboard::initTestCase()";
// init QGIS's paths - true means that all path will be inited from prefix
QgsApplication::init();
QgsApplication::initQgis();
mTestDataDir = QString( TEST_DATA_DIR ) + '/'; //defined in CmakeLists.txt
mQgisApp = new QgisApp();
}
//runs after all tests
void TestQgisAppClipboard::cleanupTestCase()
{
QgsApplication::exitQgis();
}
void TestQgisAppClipboard::copyPaste()
{
qDebug() << "TestQgisAppClipboard::copyPaste()";
QMap<QString, int> filesCounts;
filesCounts.insert( "points.shp", 17 );
filesCounts.insert( "lines.shp", 6 );
filesCounts.insert( "polys.shp", 10 );
Q_FOREACH ( const QString& fileName, filesCounts.keys() )
{
// add vector layer
QString filePath = mTestDataDir + fileName;
qDebug() << "add vector layer: " << filePath;
QgsVectorLayer *inputLayer = mQgisApp->addVectorLayer( filePath, fileName, "ogr" );
QVERIFY( inputLayer->isValid() );
// copy all features to clipboard
inputLayer->selectAll();
mQgisApp->editCopy( inputLayer );
QgsFeatureList features = mQgisApp->clipboard()->copyOf();
qDebug() << features.size() << " features copied to clipboard";
QVERIFY( features.size() == filesCounts.value( fileName ) );
QgsVectorLayer *pastedLayer = mQgisApp->pasteAsNewMemoryVector( "pasted" );
QVERIFY( pastedLayer );
QVERIFY( pastedLayer->isValid() );
qDebug() << pastedLayer->featureCount() << " features in pasted layer";
QVERIFY( pastedLayer->featureCount() == filesCounts.value( fileName ) );
}
}
QTEST_MAIN( TestQgisAppClipboard )
#include "testqgisappclipboard.moc"
|
NINAnor/QGIS
|
tests/src/app/testqgisappclipboard.cpp
|
C++
|
gpl-2.0
| 3,616
|
#
# Makefile for G3D
#
# Copyright(c) 2004-2006, Samsung Electronics, Co., Ltd.
#
obj-y += s3c_g3d.o
|
hillbeast/Kyorakernel-G3
|
drivers/media/s5p6442/g3d_drv/Makefile
|
Makefile
|
gpl-2.0
| 106
|
#include <string.h>
#include <stdio.h>
#include "product_config.h"
#include "osl_types.h"
#include "bsp_sram.h"
#include "bsp_shared_ddr.h"
#include "drv_memory.h"
#include "MemoryMap.h"
#include "ptable_com.h"
#include <bsp_dump_drv.h>
/*lint -e545*/
/* È«¾ÖµÄ½á¹¹Ì壬¼Ç¼AXIÄÚ´æ¶Î·ÖÅäÐÅÏ¢ */
const BSP_AXI_SECT_INFO g_stAxiSectInfo[BSP_AXI_SECT_TYPE_BUTTOM] =
{
{BSP_AXI_SECT_TYPE_TEMPERATURE, SRAM_TEMP_PROTECT_ADDR, SRAM_TEMP_PROTECT_ADDR, SRAM_TEMP_PROTECT_SIZE},
{BSP_AXI_SECT_TYPE_DICC, (u32)MEMORY_AXI_DICC_ADDR, (u32)MEMORY_AXI_DICC_ADDR, 8},
{BSP_AXI_SECT_TYPE_HIFI, SHM_MEM_HIFI_ADDR, SHM_MEM_HIFI_ADDR, SHM_MEM_HIFI_SIZE},
{BSP_AXI_SECT_TYPE_TTF_BBP, SRAM_GU_MAC_HEADER_ADDR, SRAM_V2P(SRAM_GU_MAC_HEADER_ADDR), SRAM_GU_MAC_HEADER_SIZE},
};
/* È«¾ÖµÄ½á¹¹Ì壬¼Ç¼DDRÄÚ´æ¶Î·ÖÅäÐÅÏ¢ */
const BSP_DDR_SECT_INFO g_stDdrSectInfo[BSP_DDR_SECT_TYPE_BUTTOM] = {
{BSP_DDR_SECT_TYPE_TTF, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_TTF_BASE_ADDR, ECS_TTF_BASE_ADDR, ECS_TTF_SIZE},
{BSP_DDR_SECT_TYPE_ARMDSP, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_ARM_DSP_BUFFER_BASE_ADDR, ECS_ARM_DSP_BUFFER_BASE_ADDR, ECS_ARM_DSP_BUFFER_SIZE},
{BSP_DDR_SECT_TYPE_UPA, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_UPA_BASE_ADDR, ECS_UPA_BASE_ADDR, ECS_UPA_SIZE},
{BSP_DDR_SECT_TYPE_CQI, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_CQI_BASE_ADDR, ECS_CQI_BASE_ADDR, ECS_CQI_SIZE},
{BSP_DDR_SECT_TYPE_APT, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_APT_BASE_ADDR, ECS_APT_BASE_ADDR, ECS_APT_SIZE},
{BSP_DDR_SECT_TYPE_ET, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_ET_BASE_ADDR, ECS_ET_BASE_ADDR, ECS_ET_SIZE},
{BSP_DDR_SECT_TYPE_BBPMASTER, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_BBP_MASTER_BASE_ADDR, ECS_BBP_MASTER_BASE_ADDR, ECS_BBP_MASTER_SIZE},
/* GU NV/DICCÄÚ´æÉϲãÒªÇóC/AºËÐ鵨ַ±ØÐëÒ»Ö£¬by ³ÂÓ¹ú */
{BSP_DDR_SECT_TYPE_NV, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_NV_BASE_ADDR_VIRT, ECS_NV_BASE_ADDR, ECS_NV_SIZE},
{BSP_DDR_SECT_TYPE_DICC, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_TTF_DICC_ADDR_VIRT, ECS_TTF_DICC_ADDR, ECS_TTF_DICC_SIZE},
{BSP_DDR_SECT_TYPE_WAN, BSP_DDR_SECT_ATTR_NONCACHEABLE, SHM_MEM_WAN_ADDR, SHM_MEM_WAN_ADDR, SHM_MEM_WAN_SIZE},
{BSP_DDR_SECT_TYPE_SHARE_MEM, BSP_DDR_SECT_ATTR_NONCACHEABLE, DDR_SHARED_MEM_ADDR, DDR_SHARED_MEM_ADDR, DDR_SHARED_MEM_SIZE},
{BSP_DDR_SECT_TYPE_EXCP, BSP_DDR_SECT_ATTR_NONCACHEABLE, DDR_MNTN_ADDR, DDR_MNTN_ADDR, DDR_MNTN_SIZE},
{BSP_DDR_SECT_TYPE_HIFI, BSP_DDR_SECT_ATTR_NONCACHEABLE, DDR_HIFI_ADDR, DDR_HIFI_ADDR, DDR_HIFI_SIZE},
{BSP_DDR_SECT_TYPE_ZSP_UP, BSP_DDR_SECT_ATTR_NONCACHEABLE, ZSP_UP_ADDR, ZSP_UP_ADDR, ZSP_UP_SIZE},
/* GU BBPHACÄÚ´æÉϲãÒªÇóC/AºËÐ鵨ַ±ØÐëÒ»Ö£¬by ³ÂÓ¹ú */
{BSP_DDR_SECT_TYPE_HARQ, BSP_DDR_SECT_ATTR_NONCACHEABLE, ECS_BBPHAC_BASE_ADDR_VIRT, ECS_BBPHAC_BASE_ADDR, ECS_BBPHAC_SIZE},
{BSP_DDR_SECT_TYPE_BBPSAMPLE, BSP_DDR_SECT_ATTR_NONCACHEABLE, 0, 0,0},
};
BSP_VOID BSP_DDR_ShowSectInfo(BSP_VOID);
void show_global_ddr_status(void);
void show_sram_status(void);
void show_shared_ddr_status(void);
void writeM(UINT32 pAddr, UINT32 value);
void memRead32 (unsigned int * uiMemAddr32);
void r(unsigned int * newMemAddr32);
/*****************************************************************************
º¯ Êý Ãû : BSP_AXI_GetSectInfo
¹¦ÄÜÃèÊö : AXIÄÚ´æ¶Î²éѯ½Ó¿Ú
ÊäÈë²ÎÊý : enSectType: ÐèÒª²éѯµÄÄÚ´æ¶ÎÀàÐÍ
Êä³ö²ÎÊý : pstSectInfo: ²éѯµ½µÄÄÚ´æ¶ÎÐÅÏ¢
·µ»ØÖµ £ºBSP_OK/BSP_ERROR
*****************************************************************************/
s32 BSP_AXI_GetSectInfo(BSP_AXI_SECT_TYPE_E enSectType, BSP_AXI_SECT_INFO *pstSectInfo)
{
if(BSP_NULL == pstSectInfo)
{
return BSP_ERROR;
}
memcpy((void *)pstSectInfo, (const void *)(&g_stAxiSectInfo[enSectType]), sizeof(BSP_AXI_SECT_INFO));
return BSP_OK;
}
/*****************************************************************************
º¯ Êý Ãû : BSP_DDR_GetSectInfo
¹¦ÄÜÃèÊö : DDRÄÚ´æ¶Î²éѯ½Ó¿Ú
ÊäÈë²ÎÊý : pstSectQuery: ÐèÒª²éѯµÄÄÚ´æ¶ÎÀàÐÍ¡¢ÊôÐÔ
Êä³ö²ÎÊý : pstSectInfo: ²éѯµ½µÄÄÚ´æ¶ÎÐÅÏ¢
·µ»ØÖµ £ºBSP_OK/BSP_ERROR
*****************************************************************************/
s32 BSP_DDR_GetSectInfo(BSP_DDR_SECT_QUERY *pstSectQuery, BSP_DDR_SECT_INFO *pstSectInfo)
{
if((BSP_NULL == pstSectQuery) || (BSP_NULL == pstSectInfo))
{
return BSP_ERROR;
}
memcpy((void *)pstSectInfo, (const void *)(&g_stDdrSectInfo[pstSectQuery->enSectType]), sizeof(BSP_DDR_SECT_INFO));
return BSP_OK;
}
/*****************************************************************************
º¯ Êý Ãû : BSP_DDR_ShowSectInfo
¹¦ÄÜÃèÊö : ´òÓ¡DDRÄÚ´æ¶ÎÐÅÏ¢
ÊäÈë²ÎÊý : ÎÞ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÎÞ
*****************************************************************************/
BSP_VOID BSP_DDR_ShowSectInfo(BSP_VOID)
{
BSP_DDR_SECT_TYPE_E enSectTypeIndex = (BSP_DDR_SECT_TYPE_E)0;
printk("\ntype paddr vaddr size attr\n");
for(; enSectTypeIndex < BSP_DDR_SECT_TYPE_BUTTOM; enSectTypeIndex++)
{
printk("0x%-8.8x 0x%-8.8x 0x%-8.8x 0x%-8.8x 0x%-8.8x\n\n", \
g_stDdrSectInfo[enSectTypeIndex].enSectType, \
g_stDdrSectInfo[enSectTypeIndex].ulSectPhysAddr, \
g_stDdrSectInfo[enSectTypeIndex].ulSectVirtAddr, \
g_stDdrSectInfo[enSectTypeIndex].ulSectSize, \
g_stDdrSectInfo[enSectTypeIndex].enSectAttr);
}
}
/*************************ÄÚ´æÐéʵת»» start*********************************/
/*****************************************************************************
º¯ Êý Ãû : DRV_DDR_VIRT_TO_PHY
¹¦ÄÜÃèÊö : DDRÄÚ´æÐ鵨ַÍùʵµØÖ·×ª»»
ÊäÈë²ÎÊý : ulVAddr£»Ð鵨ַ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÊµµØÖ·
*****************************************************************************/
unsigned int DRV_DDR_VIRT_TO_PHY(unsigned int ulVAddr)
{
if((ulVAddr >= DDR_SHARED_MEM_VIRT_ADDR)
&& (ulVAddr < SHM_MEM_TOP_ADDR))
{
return SHD_DDR_V2P(ulVAddr);
}
/* coverity[unsigned_compare] */
if((ulVAddr >= DDR_GU_ADDR_VIRT)/*lint !e685 !e568 */
&& (ulVAddr <= DDR_GU_ADDR_VIRT + DDR_GU_SIZE))
{
return (ulVAddr - DDR_GU_ADDR_VIRT + DDR_GU_ADDR);
}
printk("DRV_DDR_VIRT_TO_PHY: ulVAddr(0x%x) is invalid!\n", ulVAddr);
return 0;
}
/*****************************************************************************
º¯ Êý Ãû : DRV_DDR_PHY_TO_VIRT
¹¦ÄÜÃèÊö : DDRÄÚ´æÐ鵨ַÍùʵµØÖ·×ª»»
ÊäÈë²ÎÊý : ulPAddr£»ÊµµØÖ·
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÐ鵨ַ
*****************************************************************************/
unsigned int DRV_DDR_PHY_TO_VIRT(unsigned int ulPAddr)
{
if((ulPAddr >= DDR_SHARED_MEM_ADDR)
&& (ulPAddr < DDR_SHARED_MEM_ADDR + DDR_SHARED_MEM_SIZE))
{
return SHD_DDR_P2V(ulPAddr);
}
if((ulPAddr >= DDR_GU_ADDR)
&& (ulPAddr < DDR_GU_ADDR + DDR_GU_SIZE))
{
return (ulPAddr - DDR_GU_ADDR + DDR_GU_ADDR_VIRT);
}
printk("DRV_DDR_PHY_TO_VIRT: ulVAddr(0x%x) is invalid!\n",ulPAddr);
return 0;
}
/*****************************************************************************
º¯ Êý Ãû : TTF_VIRT_TO_PHY
¹¦ÄÜÃèÊö : TTFÄÚ´æÐ鵨ַÍùʵµØÖ·×ª»»
ÊäÈë²ÎÊý : ulVAddr£»Ð鵨ַ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÊµµØÖ·
*****************************************************************************/
unsigned int TTF_VIRT_TO_PHY(unsigned int ulVAddr)
{
return (ulVAddr - ECS_TTF_BASE_ADDR_VIRT + ECS_TTF_BASE_ADDR);
}
/*****************************************************************************
º¯ Êý Ãû : TTF_PHY_TO_VIRT
¹¦ÄÜÃèÊö : TTFÄÚ´æÊµµØÖ·ÍùÐéµØÖ·×ª»»
ÊäÈë²ÎÊý : ulPAddr£»ÊµµØÖ·
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÐ鵨ַ
*****************************************************************************/
unsigned int TTF_PHY_TO_VIRT(unsigned int ulPAddr)
{
return (ulPAddr - ECS_TTF_BASE_ADDR + ECS_TTF_BASE_ADDR_VIRT);
}
/*****************************************************************************
º¯ Êý Ãû : DRV_AXI_VIRT_TO_PHY
¹¦ÄÜÃèÊö : AXIÄÚÐ鵨ַÍùʵµØÖ·×ª»»
ÊäÈë²ÎÊý : ulVAddr£»Ð鵨ַ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÐ鵨ַ
*****************************************************************************/
unsigned int DRV_AXI_VIRT_TO_PHY(unsigned int ulVAddr)
{
return (ulVAddr - HI_SRAM_MEM_ADDR_VIRT + HI_SRAM_MEM_ADDR);
}
/*****************************************************************************
º¯ Êý Ãû : DRV_AXI_PHY_TO_VIRT
¹¦ÄÜÃèÊö : AXIÄÚʵµØÖ·ÍùÐéµØÖ·×ª»»
ÊäÈë²ÎÊý : ulVAddr£»ÊµµØÖ·
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÐ鵨ַ
*****************************************************************************/
unsigned int DRV_AXI_PHY_TO_VIRT(unsigned int ulPAddr)
{
return (ulPAddr - HI_SRAM_MEM_ADDR + HI_SRAM_MEM_ADDR_VIRT);
}
/*****************************************************************************
º¯ Êý Ãû : show_global_ddr_status
¹¦ÄÜÃèÊö : DDRÄÚ´æ¶ÎÐÅÏ¢´òÓ¡
ÊäÈë²ÎÊý : ÎÞ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÎÞ
*****************************************************************************/
void show_global_ddr_status(void)
{
printf("%-30s%10s%10s\t\n", "name", "phy addr", "size");
printf("%-30s%10x%10x\n", "DDR_APP_ACP_ADDR", DDR_APP_ACP_ADDR, DDR_APP_ACP_SIZE);
printf("%-30s%10x%10x\n", "DDR_ACORE_ADDR", DDR_ACORE_ADDR, DDR_ACORE_SIZE);
printf("%-30s%10x%10x\n", "DDR_MCORE_ADDR", DDR_MCORE_ADDR, DDR_MCORE_SIZE);
printf("%-30s%10x%10x\n", "DDR_SHARED_MEM_ADDR", DDR_SHARED_MEM_ADDR, DDR_SHARED_MEM_SIZE);
printf("%-30s%10x%10x\n", "DDR_MNTN_ADDR", DDR_MNTN_ADDR, DDR_MNTN_SIZE);
printf("%-30s%10x%10x\n", "DDR_GU_ADDR", DDR_GU_ADDR, DDR_GU_SIZE);
printf("%-30s%10x%10x\n", "DDR_TLPHY_IMAGE_ADDR", DDR_TLPHY_IMAGE_ADDR, DDR_TLPHY_IMAGE_SIZE);
printf("%-30s%10x%10x\n", "DDR_LPHY_SDR_ADDR", DDR_LPHY_SDR_ADDR, DDR_LPHY_SDR_SIZE);
printf("%-30s%10x%10x\n", "DDR_SOCP_ADDR", DDR_SOCP_ADDR, DDR_SOCP_SIZE);
printf("%-30s%10x%10x\n", "DDR_LCS_ADDR", DDR_LCS_ADDR, DDR_LCS_SIZE);
printf("%-30s%10x%10x\n", "DDR_HIFI_ADDR", DDR_HIFI_ADDR, DDR_HIFI_SIZE);
printf("%-30s%10x%10x\n", "DDR_MDM_ACP_ADDR", DDR_MDM_ACP_ADDR, DDR_MDM_ACP_SIZE);
}
/*****************************************************************************
º¯ Êý Ãû : show_sram_status
¹¦ÄÜÃèÊö : SRAMÄÚ´æ¶ÎÐÅÏ¢´òÓ¡
ÊäÈë²ÎÊý : ÎÞ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÎÞ
*****************************************************************************/
void show_sram_status(void)
{
/*ÇëÒÀÕÕÏȺó˳ÐòÔö¼Ó´òÓ¡Êä³öÏî*/
int total_size = SRAM_TOP_RESERVE_SIZE + SRAM_MCU_RESERVE_SIZE + SRAM_ICC_SIZE + SRAM_RTT_SLEEP_FLAG_SIZE +
SRAM_GU_MAC_HEADER_SIZE + SRAM_DYNAMIC_SEC_ADDR;/*lint !e569 */
printf("%-30s%10s%10s%10s\n", "name", "phy addr", "virt addr", "size");
printf("%-30s%10x%10x%10x\n", "SRAM_TOP_RESERVE_ADDR", SRAM_V2P(SRAM_TOP_RESERVE_ADDR),SRAM_TOP_RESERVE_ADDR, SRAM_TOP_RESERVE_SIZE);/*lint !e778 */
printf("%-30s%10x%10x%10x\n", "SRAM_MCU_RESERVE_ADDR", SRAM_V2P(SRAM_MCU_RESERVE_ADDR),SRAM_MCU_RESERVE_ADDR, SRAM_MCU_RESERVE_SIZE);
printf("%-30s%10x%10x%10x\n", "SRAM_ICC_ADDR", SRAM_V2P(SRAM_ICC_ADDR),SRAM_ICC_ADDR, SRAM_ICC_SIZE);
printf("%-30s%10x%10x%10x\n", "SRAM_RTT_SLEEP_FLAG_ADDR", SRAM_V2P(SRAM_RTT_SLEEP_FLAG_ADDR),SRAM_RTT_SLEEP_FLAG_ADDR, SRAM_RTT_SLEEP_FLAG_SIZE);
printf("%-30s%10x%10x%10x\n", "SRAM_GU_MAC_HEADER_ADDR", SRAM_V2P(SRAM_GU_MAC_HEADER_ADDR), SRAM_GU_MAC_HEADER_ADDR, SRAM_GU_MAC_HEADER_SIZE);
printf("%-30s%10x%10x%10x\n", "SRAM_TLPHY_ADDR", SRAM_V2P(SRAM_TLPHY_ADDR), SRAM_TLPHY_ADDR, SRAM_TLPHY_SIZE);
printf("%-30s%10x%10x%10x\n", "SRAM_DYNAMIC_SEC_ADDR", SRAM_V2P(SRAM_DYNAMIC_SEC_ADDR), SRAM_DYNAMIC_SEC_ADDR, SRAM_DYNAMIC_SEC_SIZE);
#ifdef CONFIG_MODULE_BUSSTRESS
printf("%-30s%10x%10x%10x\n", "SRAM_BUSSTRESS_ADDR", SRAM_V2P(SRAM_BUSSTRESS_ADDR), SRAM_BUSSTRESS_ADDR, SRAM_BUSSTRESS_SIZE);
#endif
printf("total size: 0x%x\n", total_size);
printf("detailed info of SRAM_TOP_RESERVE_ADDR: \n");
printf("%-30s%10x%10x\n", "SRAM_USB_ASHELL_ADDR", SRAM_V2P(SRAM_USB_ASHELL_ADDR), SRAM_USB_ASHELL_ADDR);
printf("%-30s%10x%10x\n", "SRAM_UART_INFO_ADDR", SRAM_V2P(SRAM_UART_INFO_ADDR), SRAM_UART_INFO_ADDR);
printf("%-30s%10x%10x\n", "SRAM_ONOFF_ADDR", SRAM_V2P(SRAM_ONOFF_ADDR), SRAM_ONOFF_ADDR);
printf("%-30s%10x%10x\n", "MEMORY_AXI_DICC_ADDR", SRAM_V2P(MEMORY_AXI_DICC_ADDR), MEMORY_AXI_DICC_ADDR);
printf("%-30s%10x%10x\n", "SRAM_DSP_DRV_ADDR", SRAM_V2P(SRAM_DSP_DRV_ADDR), SRAM_DSP_DRV_ADDR);
printf("%-30s%10x%10x\n", "SRAM_PCIE_INFO_ADDR", SRAM_V2P(SRAM_PCIE_INFO_ADDR), SRAM_PCIE_INFO_ADDR);
printf("%-30s%10x%10x\n", "SRAM_SEC_ROOTCA_ADDR", SRAM_V2P(SRAM_SEC_ROOTCA_ADDR), SRAM_SEC_ROOTCA_ADDR);
printf("%-30s%10x%10x\n", "SRAM_WDT_AM_FLAG_ADDR", SRAM_V2P(SRAM_WDT_AM_FLAG_ADDR), SRAM_WDT_AM_FLAG_ADDR);
printf("%-30s%10x%10x\n", "SRAM_WDT_CM_FLAG_ADDR", SRAM_V2P(SRAM_WDT_CM_FLAG_ADDR), SRAM_WDT_CM_FLAG_ADDR);
printf("%-30s%10x%10x\n", "SRAM_BUCK3_ACORE_ONOFF_FLAG_ADDR", SRAM_V2P(SRAM_BUCK3_ACORE_ONOFF_FLAG_ADDR), SRAM_BUCK3_ACORE_ONOFF_FLAG_ADDR);
printf("%-30s%10x%10x\n", "SRAM_BUCK3_CCORE_ONOFF_FLAG_ADDR", SRAM_V2P(SRAM_BUCK3_CCORE_ONOFF_FLAG_ADDR), SRAM_BUCK3_CCORE_ONOFF_FLAG_ADDR);
printf("%-30s%10x%10x\n", "SRAM_CUR_CPUFREQ_PROFILE_ADDR", SRAM_V2P(SRAM_CUR_CPUFREQ_PROFILE_ADDR), SRAM_CUR_CPUFREQ_PROFILE_ADDR);
printf("%-30s%10x%10x\n", "SRAM_MAX_CPUFREQ_PROFILE_ADDR", SRAM_V2P(SRAM_MAX_CPUFREQ_PROFILE_ADDR), SRAM_MAX_CPUFREQ_PROFILE_ADDR);
printf("%-30s%10x%10x\n", "SRAM_MIN_CPUFREQ_PROFILE_ADDR", SRAM_V2P(SRAM_MIN_CPUFREQ_PROFILE_ADDR), SRAM_MIN_CPUFREQ_PROFILE_ADDR);
printf("%-30s%10x%10x\n", "SRAM_REBOOT_ADDR", SRAM_V2P(SRAM_REBOOT_ADDR), SRAM_REBOOT_ADDR);
printf("%-30s%10x%10x\n", "SRAM_TEMP_PROTECT_ADDR", SRAM_V2P(SRAM_TEMP_PROTECT_ADDR), SRAM_TEMP_PROTECT_ADDR);
printf("%-30s%10x%10x\n", "SRAM_DLOAD_ADDR", SRAM_V2P(SRAM_DLOAD_ADDR), SRAM_DLOAD_ADDR);
printf("%-30s%10x%10x\n", "SRAM_SEC_SHARE", SRAM_V2P(SRAM_SEC_SHARE), SRAM_SEC_SHARE);
printf("%-30s%10x%10x\n", "SRAM_DSP_MNTN_INFO", SRAM_V2P(SRAM_DSP_MNTN_INFO_ADDR), SRAM_DSP_MNTN_INFO_ADDR);
printf("%-30s%10x%10x\n", "SRAM_DUMP_POWER_OFF_FLAG_ADDR", SRAM_V2P(SRAM_DUMP_POWER_OFF_FLAG_ADDR), SRAM_DUMP_POWER_OFF_FLAG_ADDR);
}
/*****************************************************************************
º¯ Êý Ãû : show_shared_ddr_status
¹¦ÄÜÃèÊö : ¹²ÏíÄÚ´æÄÚ´æ¶ÎÐÅÏ¢´òÓ¡
ÊäÈë²ÎÊý : ÎÞ
Êä³ö²ÎÊý : ÎÞ
·µ»ØÖµ £ºÎÞ
*****************************************************************************/
void show_shared_ddr_status(void)
{
/*ÇëÒÀÕÕÏȺó˳ÐòÔö¼Ó´òÓ¡Êä³öÏî*/
int total_size = SHM_MEM_APPA9_PM_BOOT_SIZE + SHM_MEM_MDMA9_PM_BOOT_SIZE + SHM_MEM_SYNC_SIZE + SHM_MEM_ICC_SIZE +
SHM_MEM_IPF_SIZE + SHM_MEM_WAN_SIZE + SHM_MEM_NV_SIZE + SHM_MEM_M3_MNTN_SIZE +
SHM_MEM_HIFI_SIZE + SHM_MEM_HIFI_MBX_SIZE + SHM_DDM_LOAD_SIZE + SHM_TIMESTAMP_SIZE +
SHM_MEM_IOS_SIZE + SHM_MEM_MODEM_PINTRL_SIZE + SHM_MEM_TEMPERATURE_SIZE +SHM_MEM_RESTORE_AXI_SIZE +
SHM_MEMMGR_FLAG_SIZE + SHM_PMU_OCP_INFO_SIZE + SHM_PMU_VOLTTABLE_SIZE + SHM_MEM_HW_VER_SIZE +
SHM_MEM_PTABLE_SIZE + SHM_MEM_MEMMGR_SIZE + SHM_MEM_NAND_SPEC_SIZE +CORESHARE_MEM_TENCILICA_MULT_BAND_SIZE;
printf("%-30s%10s%10s%10s\n", "name", "phy addr", "virt addr", "size");
printf("%-30s%10x%10x%10x\n", "SHM_MEM_APPA9_PM_BOOT_ADDR", SHD_DDR_V2P(SHM_MEM_APPA9_PM_BOOT_ADDR), SHM_MEM_APPA9_PM_BOOT_ADDR, SHM_MEM_APPA9_PM_BOOT_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_MDMA9_PM_BOOT_ADDR", SHD_DDR_V2P(SHM_MEM_MDMA9_PM_BOOT_ADDR), SHM_MEM_MDMA9_PM_BOOT_ADDR, SHM_MEM_MDMA9_PM_BOOT_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_SYNC_ADDR", SHD_DDR_V2P(SHM_MEM_SYNC_ADDR), SHM_MEM_SYNC_ADDR, SHM_MEM_SYNC_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_ICC_ADDR", SHD_DDR_V2P(SHM_MEM_ICC_ADDR), SHM_MEM_ICC_ADDR, SHM_MEM_ICC_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_IPF_ADDR", SHD_DDR_V2P(SHM_MEM_IPF_ADDR),SHM_MEM_IPF_ADDR, SHM_MEM_IPF_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_WAN_ADDR", SHD_DDR_V2P(SHM_MEM_WAN_ADDR), SHM_MEM_WAN_ADDR, SHM_MEM_WAN_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_NV_ADDR", SHD_DDR_V2P(SHM_MEM_NV_ADDR), SHM_MEM_NV_ADDR, SHM_MEM_NV_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_M3_MNTN_ADDR", SHD_DDR_V2P(SHM_MEM_M3_MNTN_ADDR), SHM_MEM_M3_MNTN_ADDR, SHM_MEM_M3_MNTN_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_HIFI_ADDR", SHD_DDR_V2P(SHM_MEM_HIFI_ADDR), SHM_MEM_HIFI_ADDR, SHM_MEM_HIFI_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_HIFI_MBX_ADDR", SHD_DDR_V2P(SHM_MEM_HIFI_MBX_ADDR), SHM_MEM_HIFI_MBX_ADDR, SHM_MEM_HIFI_MBX_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_DDM_LOAD_ADDR", SHD_DDR_V2P(SHM_DDM_LOAD_ADDR), SHM_DDM_LOAD_ADDR, SHM_DDM_LOAD_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_TIMESTAMP_ADDR", SHD_DDR_V2P(SHM_TIMESTAMP_ADDR), SHM_TIMESTAMP_ADDR, SHM_TIMESTAMP_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_IOS_ADDR", SHD_DDR_V2P(SHM_MEM_IOS_ADDR), SHM_MEM_IOS_ADDR, SHM_MEM_IOS_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_MODEM_PINTRL_ADDR", SHD_DDR_V2P(SHM_MEM_MODEM_PINTRL_ADDR), SHM_MEM_MODEM_PINTRL_ADDR, SHM_MEM_MODEM_PINTRL_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_TEMPERATURE_ADDR", SHD_DDR_V2P(SHM_MEM_TEMPERATURE_ADDR), SHM_MEM_TEMPERATURE_ADDR, SHM_MEM_TEMPERATURE_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_RESTORE_AXI_ADDR", SHD_DDR_V2P(SHM_MEM_RESTORE_AXI_ADDR), SHM_MEM_RESTORE_AXI_ADDR, SHM_MEM_RESTORE_AXI_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEMMGR_FLAG_ADDR", SHD_DDR_V2P(SHM_MEMMGR_FLAG_ADDR), SHM_MEMMGR_FLAG_ADDR, SHM_MEMMGR_FLAG_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_PMU_OCP_INFO_ADDR", SHD_DDR_V2P(SHM_PMU_OCP_INFO_ADDR), SHM_PMU_OCP_INFO_ADDR, SHM_PMU_OCP_INFO_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_PMU_VOLTTABLE_ADDR", SHD_DDR_V2P(SHM_PMU_VOLTTABLE_ADDR), SHM_PMU_VOLTTABLE_ADDR, SHM_PMU_VOLTTABLE_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_HW_VER_ADDR", SHD_DDR_V2P(SHM_MEM_HW_VER_ADDR), SHM_MEM_HW_VER_ADDR, SHM_MEM_HW_VER_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_DSP_FLAG_ADDR", SHD_DDR_V2P(SHM_MEM_DSP_FLAG_ADDR), SHM_MEM_DSP_FLAG_ADDR, SHM_MEM_DSP_FLAG_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_PTABLE_ADDR", SHD_DDR_V2P(SHM_MEM_PTABLE_ADDR), SHM_MEM_PTABLE_ADDR, SHM_MEM_PTABLE_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_PASTAR_DPM_INFO_ADDR", SHD_DDR_V2P(SHM_MEM_PASTAR_DPM_INFO_ADDR), SHM_MEM_PASTAR_DPM_INFO_ADDR, SHM_MEM_PASTAR_DPM_INFO_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_LOADM_ADDR", SHD_DDR_V2P(SHM_MEM_LOADM_ADDR), SHM_MEM_LOADM_ADDR, SHM_MEM_LOADM_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_NAND_SPEC_ADDR", SHD_DDR_V2P(SHM_MEM_NAND_SPEC_ADDR), SHM_MEM_NAND_SPEC_ADDR, SHM_MEM_NAND_SPEC_SIZE);
printf("%-30s%10x%10x%10x\n", "SHM_MEM_MEMMGR_ADDR", SHD_DDR_V2P(SHM_MEM_MEMMGR_ADDR), SHM_MEM_MEMMGR_ADDR, SHM_MEM_MEMMGR_SIZE);
printf("%-30s%10x%10x%10x\n", "CORESHARE_MEM_TENCILICA_MULT_BAND_ADDR", CORESHARE_MEM_TENCILICA_MULT_BAND_ADDR, SHD_DDR_P2V(CORESHARE_MEM_TENCILICA_MULT_BAND_ADDR), CORESHARE_MEM_TENCILICA_MULT_BAND_SIZE);/*lint !e778 */
printf("total size: 0x%x\n", total_size);
}
/*
* adpt for gu
*/
unsigned int * MemAddr32 = 0x00000000;
/*******************************************************************************
* writeM - write a UINT32 value to perihical address
* adpt for gu
* RETURNS: N/A
*/
void writeM(UINT32 pAddr, UINT32 value)
{
*(volatile UINT32 *)(pAddr)=value;
}
/***********************************************************
Function: memRead32--read memory and display the value
adpt for gu
Input: the start address
return: void
************************************************************/
void memRead32 (unsigned int * uiMemAddr32)
{
if (0 != uiMemAddr32)
{
MemAddr32 = (unsigned int *)((unsigned int)uiMemAddr32 & 0xFFFFFFFC);
}
printf("0x%.8X: 0x%.8X 0x%.8X 0x%.8X 0x%.8X\n",
(UINT32)(MemAddr32+0x0), *(MemAddr32+0x0), *(MemAddr32+0x1), *(MemAddr32+0x2), *(MemAddr32+0x3));
printf("0x%.8X: 0x%.8X 0x%.8X 0x%.8X 0x%.8X\n",
(UINT32)(MemAddr32+0x4), *(MemAddr32+0x4), *(MemAddr32+0x5), *(MemAddr32+0x6), *(MemAddr32+0x7));
printf("0x%.8X: 0x%.8X 0x%.8X 0x%.8X 0x%.8X\n",
(UINT32)(MemAddr32+0x8), *(MemAddr32+0x8), *(MemAddr32+0x9), *(MemAddr32+0xa), *(MemAddr32+0xb));
printf("0x%.8X: 0x%.8X 0x%.8X 0x%.8X 0x%.8X\n",
(UINT32)(MemAddr32+0xc), *(MemAddr32+0xc), *(MemAddr32+0xd), *(MemAddr32+0xe), *(MemAddr32+0xf));
MemAddr32 += 0x10;
}
/***********************************************************
Function: r--simple read memory command
adpt for gu
Input: the start address
return: void
************************************************************/
void r(unsigned int * newMemAddr32)
{
memRead32(newMemAddr32);
}
void show_hpm_temp(void)
{
#ifndef BSP_CONFIG_HI3630
struct hpm_tem_print *hpm_ptr = (struct hpm_tem_print *)DUMP_EXT_BOOST_MCORE_ADDR;
printf("****************hpm_temperature****************\n");
printf("hpm_uhvt_opc: 0x%x\n", hpm_ptr->hpm_uhvt_opc);
printf("hpm_hvt_opc : 0x%x\n", hpm_ptr->hpm_hvt_opc);
printf("hpm_svt_opc : 0x%x\n", hpm_ptr->hpm_svt_opc);
printf("temperature : %d\n", hpm_ptr->temperature);
printf("up_volt : %d\n", hpm_ptr->up_volt);
#endif
}
/*lint +e545*/
#ifdef __cplusplus
}
#endif
|
asyan4ik/android_kernel_huawei_h60
|
drivers/vendor/hisi/modem/drv/ccore/drivers/hwadp/hwadp_memory.c
|
C
|
gpl-2.0
| 22,455
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using Microsoft.Practices.CompositeUI.SmartParts;
using Microsoft.Practices.ObjectBuilder;
using Uniframework.Services;
using Uniframework.SmartClient;
namespace Uniframework.Upgrade.Views
{
public partial class UpgradeBuilderView : DevExpress.XtraEditors.XtraUserControl, ISmartPartInfoProvider
{
private bool upgradeItemChanged = false;
private bool upgradeUrl;
public UpgradeBuilderView()
{
InitializeComponent();
}
private UpgradeBuilderPresenter presenter;
[CreateNew]
public UpgradeBuilderPresenter Presenter
{
get { return presenter; }
set {
presenter = value;
presenter.View = this;
}
}
public void BindingUpgradeGroup(UpgradeGroup group)
{
Guard.ArgumentNotNull(group, "Upgrade group.");
txtGroupName.Text = group.Name;
txtTarget.Text = group.Target;
lvItems.Items.Clear();
foreach (UpgradeItem upItem in group.Items) {
ListViewItem item = new ListViewItem(upItem.Name, 1);
item.Tag = upItem;
lvItems.Items.Add(item);
}
}
public UpgradeProject WrapUpgradeProject()
{
UpgradeProject proj = new UpgradeProject();
proj.StartUpApp = txtStartUpApp.Text.Trim();
proj.UpgradeServer = txtUpgradeUrl.Text.Trim();
proj.Product = txtProduct.Text.Trim();
proj.Version = txtVersion.Text.Trim();
proj.Description = txtDescription.Text;
foreach (ListViewItem item in lvGroups.Items)
{
UpgradeGroup group = item.Tag as UpgradeGroup;
if (group != null)
proj.Groups.Add(group);
}
return proj;
}
/// <summary>
/// Åжϵ±Ç°Éý¼¶°üÊÇ·ñ×¼±¸ºÃ
/// </summary>
/// <returns></returns>
public bool UpgradeProjectIsValid()
{
if (String.IsNullOrEmpty(txtStartUpApp.Text))
{
XtraMessageBox.Show("δÉèÖÃÉý¼¶Íê³ÉºóµÄÆô¶¯Ö÷³ÌÐòÃû×Ö¡£");
txtStartUpApp.Focus();
return false;
}
if (String.IsNullOrEmpty(txtUpgradeUrl.Text))
{
XtraMessageBox.Show("δÉèÖñ£´æÉý¼¶ÏîÄ¿µÄ·þÎñÆ÷µØÖ·¡£");
txtUpgradeUrl.Focus();
return false;
}
if (String.IsNullOrEmpty(txtProduct.Text))
{
XtraMessageBox.Show("δÉèÖñ¾´ÎÉý¼¶ÏîÄ¿µÄÈí¼þÃû³Æ¡£");
txtProduct.Focus();
return false;
}
if (String.IsNullOrEmpty(txtVersion.Text))
{
XtraMessageBox.Show("δÉèÖñ¾´ÎÉý¼¶µÄÈí¼þ°æ±¾ºÅ¡£");
txtVersion.Focus();
return false;
}
if (lvGroups.Items.Count < 1)
{
XtraMessageBox.Show("ûÓÐΪ±¾´ÎÉý¼¶Ìí¼ÓÏà¹ØµÄÉý¼¶×é¡£");
return false;
}
UpgradeProject proj = Presenter.UpgradeService.GetUpgradeProject(txtProduct.Text);
if (proj != null)
{
Version newVer = new Version(txtVersion.Text);
Version oldVer = new Version(proj.Version);
if (newVer == oldVer)
{
if (XtraMessageBox.Show("·þÎñÆ÷ÒѾ´æÔڰ汾Ϊ\"" + proj.Version + "\"µÄÉý¼¶ÏîÄ¿£¬ÄúÒÀȻҪÉÏ´«±¾´ÎÉý¼¶ÏîÄ¿Âð£¿",
"Ìáʾ", MessageBoxButtons.YesNo) == DialogResult.No)
return false;
}
if (newVer < oldVer)
{
XtraMessageBox.Show("±¾´ÎÉý¼¶µÄ°æ±¾ºÅ±È·þÎñÆ÷¶ËµÄ°æ±¾µÍ¿Í»§¶Ë½«µÃ²»µ½¸üС£");
return false;
}
}
return true;
}
#region Assistant functions
private void UpdateUpgradeGroup()
{
if (String.IsNullOrEmpty(txtGroupName.Text) || String.IsNullOrEmpty(txtTarget.Text))
{
XtraMessageBox.Show("±ØÐëΪ¸üÐÂÏîÄ¿×éÌṩһ¸öÃû³ÆºÍÄ¿±êÎļþ¼ÐλÖá£");
txtGroupName.Focus();
return;
}
int index = -1;
foreach (ListViewItem item in lvGroups.Items)
{
if (item.Text == txtGroupName.Text)
{
index = item.Index;
lvGroups.Items.Remove(item);
break;
}
}
UpgradeGroup group = new UpgradeGroup(txtGroupName.Text.Trim(), txtTarget.Text.Trim());
foreach (ListViewItem item in lvItems.Items)
group.Items.Add(item.Tag as UpgradeItem);
ListViewItem groupItem = new ListViewItem(group.Name, 0);
groupItem.Tag = group;
if (index != -1)
lvGroups.Items.Insert(index, groupItem);
else
lvGroups.Items.Add(groupItem);
upgradeItemChanged = false;
}
/// <summary>
/// Clears the upgrade group detail.
/// </summary>
private void ClearUpgradeGroupDetail()
{
txtGroupName.Text = "";
txtTarget.Text = "";
lvItems.Items.Clear();
txtGroupName.Focus();
}
/// <summary>
/// Ñ¡ÔñÉý¼¶ÏîÄ¿µÄÈë¿Ú³ÌÐò
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="DevExpress.XtraEditors.Controls.ButtonPressedEventArgs"/> instance containing the event data.</param>
private void txtStartUpApp_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
{
OpenFileDialog opendlg = new OpenFileDialog();
opendlg.Multiselect = false;
opendlg.Title = "Ñ¡Ôñ";
opendlg.Filter = "¿ÉÖ´ÐгÌÐò(*.exe)|*.exe";
if (opendlg.ShowDialog() == DialogResult.OK) {
txtStartUpApp.Text = Path.GetFileName(opendlg.FileName);
txtProduct.Text = Path.GetFileNameWithoutExtension(opendlg.FileName);
// ÏòÉý¼¶ÏîÄ¿ÖвåÈëÆô¶¯×éµÄÄÚÈÝ
UpgradeGroup group = new UpgradeGroup("StartUp", "${RootPath}");
group.Items.Add(new UpgradeItem(opendlg.FileName));
foreach (ListViewItem item in lvGroups.Items) {
UpgradeGroup gr = item.Tag as UpgradeGroup;
if (gr != null && gr.Name == "StartUp") {
lvGroups.Items.Remove(item);
break;
}
}
ListViewItem groupItem = new ListViewItem(group.Name);
groupItem.Tag = group;
lvGroups.Items.Insert(0, groupItem);
BindingUpgradeGroup(group);
try {
AssemblyName assemblyName = Assembly.ReflectionOnlyLoadFrom(opendlg.FileName).GetName();
txtVersion.Text = assemblyName.Version.ToString();
}
catch {
UpgradeProject proj = Presenter.UpgradeService.GetUpgradeProject(txtProduct.Text.Trim()); // ´Ó·þÎñÆ÷Éý¼¶Êý¾Ý¿âÖлñȡеİ汾ºÅ
if (proj != null) {
Version ver = new Version(proj.Version);
txtVersion.Text = String.Format("{0}.{1}.{2}.{3}", ver.Major, ver.Minor, ver.Build, ver.Revision + 1);
}
else
txtVersion.Text = "1.0.0.0";
}
}
txtUpgradeUrl.Text = Presenter.UpgradeSetting.UpgradeUrl;
txtUpgradeUrl.SelectAll();
txtUpgradeUrl.Focus();
}
private void EnumDirectory(string path)
{
List<string> files = FileUtility.SearchDirectory(path, "*.*");
foreach (string file in files)
{
if (FileUtility.IsDirectory(file))
EnumDirectory(file);
else
{
UpgradeItem upItem = new UpgradeItem(file);
ListViewItem item = new ListViewItem(upItem.Name, 1);
item.Tag = upItem;
lvItems.Items.Add(item);
}
}
}
#endregion
private void lvGroups_SelectedIndexChanged(object sender, EventArgs e)
{
if (lvGroups.SelectedItems.Count > 0) {
UpgradeGroup group = lvGroups.SelectedItems[0].Tag as UpgradeGroup;
if (group != null)
BindingUpgradeGroup(group);
}
btngDelete.Enabled = lvGroups.Items.Count > 0;
}
private void btniAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
OpenFileDialog opendlg = new OpenFileDialog();
opendlg.Multiselect = true;
opendlg.Title = "Ñ¡Ôñ¸üÐÂÏîÄ¿";
opendlg.Filter = "ËùÓгÌÐò(*.*)|*.*";
if (opendlg.ShowDialog() == DialogResult.OK)
{
foreach (string file in opendlg.FileNames)
{
if (FileUtility.IsDirectory(file))
{
EnumDirectory(file);
}
else
{
UpgradeItem upItem = new UpgradeItem(file);
ListViewItem item = new ListViewItem(upItem.Name, 1);
item.Tag = upItem;
lvItems.Items.Add(item);
}
}
upgradeItemChanged = true;
}
}
private void btniDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (lvItems.SelectedItems.Count == 0)
return;
foreach (ListViewItem item in lvItems.SelectedItems)
lvItems.Items.Remove(item);
upgradeItemChanged = true;
}
private void lvItems_SelectedIndexChanged(object sender, EventArgs e)
{
btniDelete.Enabled = lvItems.Items.Count > 0;
}
private void btniRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
UpdateUpgradeGroup();
}
private void btngAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
UpdateUpgradeGroup();
ClearUpgradeGroupDetail();
txtTarget.Text = "${RootPath}";
}
private void btngDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
{
if (lvGroups.SelectedItems.Count <= 0)
return;
lvGroups.Items.RemoveAt(0);
}
private void btnUpload_Click(object sender, EventArgs e)
{
Presenter.UploadProject();
}
public Microsoft.Practices.CompositeUI.SmartParts.ISmartPartInfo GetSmartPartInfo(Type smartPartInfoType)
{
// Implement ISmartPartInfoProvider in the containing smart part. Required in order for contained smart part infos to work.
Microsoft.Practices.CompositeUI.SmartParts.ISmartPartInfoProvider ensureProvider = this;
return this.infoProvider.GetSmartPartInfo(smartPartInfoType);
}
#region ISmartPartInfoProvider Members
ISmartPartInfo ISmartPartInfoProvider.GetSmartPartInfo(Type smartPartInfoType)
{
ISmartPartInfoProvider ensureProvider = this;
return this.infoProvider.GetSmartPartInfo(smartPartInfoType);
}
#endregion
}
}
|
tws67/uniframework
|
sources/Uniframework.Upgrade/Views/UpgradeBuilderView.cs
|
C#
|
gpl-2.0
| 12,516
|
using MediaBrowser.Common.Configuration;
using MediaBrowser.Common.IO;
using MediaBrowser.Common.Net;
using MediaBrowser.Controller.Library;
using MediaBrowser.Controller.Notifications;
using MediaBrowser.Controller.Plugins;
using MediaBrowser.Model.Logging;
using MediaBrowser.Model.Notifications;
using MediaBrowser.Model.Serialization;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CommonIO;
namespace MediaBrowser.Server.Implementations.EntryPoints.Notifications
{
public class RemoteNotifications : IServerEntryPoint
{
private const string Url = "http://www.mb3admin.com/admin/service/MB3ServerNotifications.json";
private Timer _timer;
private readonly IHttpClient _httpClient;
private readonly IApplicationPaths _appPaths;
private readonly ILogger _logger;
private readonly IJsonSerializer _json;
private readonly IUserManager _userManager;
private readonly IFileSystem _fileSystem;
private readonly TimeSpan _frequency = TimeSpan.FromHours(6);
private readonly TimeSpan _maxAge = TimeSpan.FromDays(31);
private readonly INotificationManager _notificationManager;
public RemoteNotifications(IApplicationPaths appPaths, ILogger logger, IHttpClient httpClient, IJsonSerializer json, IUserManager userManager, IFileSystem fileSystem, INotificationManager notificationManager)
{
_appPaths = appPaths;
_logger = logger;
_httpClient = httpClient;
_json = json;
_userManager = userManager;
_fileSystem = fileSystem;
_notificationManager = notificationManager;
}
/// <summary>
/// Runs this instance.
/// </summary>
public void Run()
{
_timer = new Timer(OnTimerFired, null, TimeSpan.FromMilliseconds(500), _frequency);
}
/// <summary>
/// Called when [timer fired].
/// </summary>
/// <param name="state">The state.</param>
private async void OnTimerFired(object state)
{
var dataPath = Path.Combine(_appPaths.DataPath, "remotenotifications.json");
var lastRunTime = _fileSystem.FileExists(dataPath) ? _fileSystem.GetLastWriteTimeUtc(dataPath) : DateTime.MinValue;
try
{
await DownloadNotifications(dataPath, lastRunTime).ConfigureAwait(false);
}
catch (Exception ex)
{
_logger.ErrorException("Error downloading remote notifications", ex);
}
}
/// <summary>
/// Downloads the notifications.
/// </summary>
/// <param name="dataPath">The data path.</param>
/// <param name="lastRunTime">The last run time.</param>
/// <returns>Task.</returns>
private async Task DownloadNotifications(string dataPath, DateTime lastRunTime)
{
using (var stream = await _httpClient.Get(new HttpRequestOptions
{
Url = Url
}).ConfigureAwait(false))
{
var notifications = _json.DeserializeFromStream<RemoteNotification[]>(stream);
_fileSystem.WriteAllText(dataPath, string.Empty);
await CreateNotifications(notifications, lastRunTime).ConfigureAwait(false);
}
}
/// <summary>
/// Creates the notifications.
/// </summary>
/// <param name="notifications">The notifications.</param>
/// <param name="lastRunTime">The last run time.</param>
/// <returns>Task.</returns>
private async Task CreateNotifications(IEnumerable<RemoteNotification> notifications, DateTime lastRunTime)
{
// Only show notifications that are active, new since last download, and not older than max age
var notificationList = notifications
.Where(i => string.Equals(i.active, "1") && i.date.ToUniversalTime() > lastRunTime && (DateTime.UtcNow - i.date.ToUniversalTime()) <= _maxAge)
.ToList();
var userIds = _userManager.Users.Select(i => i.Id.ToString("N")).ToList();
foreach (var notification in notificationList)
{
await _notificationManager.SendNotification(new NotificationRequest
{
Date = notification.date,
Name = notification.name,
Description = notification.description,
Url = notification.url,
UserIds = userIds
}, CancellationToken.None).ConfigureAwait(false);
}
}
public void Dispose()
{
if (_timer != null)
{
_timer.Dispose();
_timer = null;
}
}
private class RemoteNotification
{
public string id { get; set; }
public DateTime date { get; set; }
public string name { get; set; }
public string description { get; set; }
public string category { get; set; }
public string url { get; set; }
public object imageUrl { get; set; }
public string active { get; set; }
}
}
}
|
TomGillen/MediaBrowser
|
MediaBrowser.Server.Implementations/EntryPoints/Notifications/RemoteNotifications.cs
|
C#
|
gpl-2.0
| 5,410
|
/***************************************************************************
qgsalgorithmrescaleraster.cpp
---------------------
begin : July 2020
copyright : (C) 2020 by Alexander Bruy
email : alexander dot bruy 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 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include <limits>
#include "math.h"
#include "qgsalgorithmrescaleraster.h"
#include "qgsrasterfilewriter.h"
///@cond PRIVATE
QString QgsRescaleRasterAlgorithm::name() const
{
return QStringLiteral( "rescaleraster" );
}
QString QgsRescaleRasterAlgorithm::displayName() const
{
return QObject::tr( "Rescale raster" );
}
QStringList QgsRescaleRasterAlgorithm::tags() const
{
return QObject::tr( "raster,rescale,minimum,maximum,range" ).split( ',' );
}
QString QgsRescaleRasterAlgorithm::group() const
{
return QObject::tr( "Raster analysis" );
}
QString QgsRescaleRasterAlgorithm::groupId() const
{
return QStringLiteral( "rasteranalysis" );
}
QString QgsRescaleRasterAlgorithm::shortHelpString() const
{
return QObject::tr( "Rescales raster layer to a new value range, while preserving the shape "
"(distribution) of the raster's histogram (pixel values). Input values "
"are mapped using a linear interpolation from the source raster's minimum "
"and maximum pixel values to the destination minimum and maximum pixel range.\n\n"
"By default the algorithm preserves original the NODATA value, but there is "
"an option to override it." );
}
QgsRescaleRasterAlgorithm *QgsRescaleRasterAlgorithm::createInstance() const
{
return new QgsRescaleRasterAlgorithm();
}
void QgsRescaleRasterAlgorithm::initAlgorithm( const QVariantMap & )
{
addParameter( new QgsProcessingParameterRasterLayer( QStringLiteral( "INPUT" ), QStringLiteral( "Input raster" ) ) );
addParameter( new QgsProcessingParameterBand( QStringLiteral( "BAND" ), QObject::tr( "Band number" ), 1, QStringLiteral( "INPUT" ) ) );
addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MINIMUM" ), QObject::tr( "New minimum value" ), QgsProcessingParameterNumber::Double, 0 ) );
addParameter( new QgsProcessingParameterNumber( QStringLiteral( "MAXIMUM" ), QObject::tr( "New maximum value" ), QgsProcessingParameterNumber::Double, 255 ) );
addParameter( new QgsProcessingParameterNumber( QStringLiteral( "NODATA" ), QObject::tr( "New NODATA value" ), QgsProcessingParameterNumber::Double, QVariant(), true ) );
addParameter( new QgsProcessingParameterRasterDestination( QStringLiteral( "OUTPUT" ), QObject::tr( "Rescaled" ) ) );
}
bool QgsRescaleRasterAlgorithm::prepareAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
Q_UNUSED( feedback );
QgsRasterLayer *layer = parameterAsRasterLayer( parameters, QStringLiteral( "INPUT" ), context );
if ( !layer )
throw QgsProcessingException( invalidRasterError( parameters, QStringLiteral( "INPUT" ) ) );
mBand = parameterAsInt( parameters, QStringLiteral( "BAND" ), context );
if ( mBand < 1 || mBand > layer->bandCount() )
throw QgsProcessingException( QObject::tr( "Invalid band number for BAND (%1): Valid values for input raster are 1 to %2" )
.arg( mBand )
.arg( layer->bandCount() ) );
mMinimum = parameterAsDouble( parameters, QStringLiteral( "MINIMUM" ), context );
mMaximum = parameterAsDouble( parameters, QStringLiteral( "MAXIMUM" ), context );
mInterface.reset( layer->dataProvider()->clone() );
mCrs = layer->crs();
mLayerWidth = layer->width();
mLayerHeight = layer->height();
mExtent = layer->extent();
if ( parameters.value( QStringLiteral( "NODATA" ) ).isValid() )
{
mNoData = parameterAsDouble( parameters, QStringLiteral( "NODATA" ), context );
}
else
{
mNoData = layer->dataProvider()->sourceNoDataValue( mBand );
}
if ( std::isfinite( mNoData ) )
{
// Clamp nodata to float32 range, since that's the type of the raster
if ( mNoData < std::numeric_limits<float>::lowest() )
mNoData = std::numeric_limits<float>::lowest();
else if ( mNoData > std::numeric_limits<float>::max() )
mNoData = std::numeric_limits<float>::max();
}
mXSize = mInterface->xSize();
mYSize = mInterface->ySize();
return true;
}
QVariantMap QgsRescaleRasterAlgorithm::processAlgorithm( const QVariantMap ¶meters, QgsProcessingContext &context, QgsProcessingFeedback *feedback )
{
feedback->pushInfo( QObject::tr( "Calculating raster minimum and maximum values…" ) );
QgsRasterBandStats stats = mInterface->bandStatistics( mBand, QgsRasterBandStats::Min | QgsRasterBandStats::Max, QgsRectangle(), 0 );
feedback->pushInfo( QObject::tr( "Rescaling values…" ) );
const QString outputFile = parameterAsOutputLayer( parameters, QStringLiteral( "OUTPUT" ), context );
QFileInfo fi( outputFile );
const QString outputFormat = QgsRasterFileWriter::driverForExtension( fi.suffix() );
std::unique_ptr< QgsRasterFileWriter > writer = std::make_unique< QgsRasterFileWriter >( outputFile );
writer->setOutputProviderKey( QStringLiteral( "gdal" ) );
writer->setOutputFormat( outputFormat );
std::unique_ptr<QgsRasterDataProvider > provider( writer->createOneBandRaster( Qgis::DataType::Float32, mXSize, mYSize, mExtent, mCrs ) );
if ( !provider )
throw QgsProcessingException( QObject::tr( "Could not create raster output: %1" ).arg( outputFile ) );
if ( !provider->isValid() )
throw QgsProcessingException( QObject::tr( "Could not create raster output %1: %2" ).arg( outputFile, provider->error().message( QgsErrorMessage::Text ) ) );
QgsRasterDataProvider *destProvider = provider.get();
destProvider->setEditable( true );
destProvider->setNoDataValue( 1, mNoData );
int blockWidth = QgsRasterIterator::DEFAULT_MAXIMUM_TILE_WIDTH;
int blockHeight = QgsRasterIterator::DEFAULT_MAXIMUM_TILE_HEIGHT;
int numBlocksX = static_cast< int >( std::ceil( 1.0 * mLayerWidth / blockWidth ) );
int numBlocksY = static_cast< int >( std::ceil( 1.0 * mLayerHeight / blockHeight ) );
int numBlocks = numBlocksX * numBlocksY;
QgsRasterIterator iter( mInterface.get() );
iter.startRasterRead( mBand, mLayerWidth, mLayerHeight, mExtent );
int iterLeft = 0;
int iterTop = 0;
int iterCols = 0;
int iterRows = 0;
std::unique_ptr< QgsRasterBlock > inputBlock;
while ( iter.readNextRasterPart( mBand, iterCols, iterRows, inputBlock, iterLeft, iterTop ) )
{
std::unique_ptr< QgsRasterBlock > outputBlock( new QgsRasterBlock( destProvider->dataType( 1 ), iterCols, iterRows ) );
feedback->setProgress( 100 * ( ( iterTop / blockHeight * numBlocksX ) + iterLeft / blockWidth ) / numBlocks );
for ( int row = 0; row < iterRows; row++ )
{
if ( feedback->isCanceled() )
break;
for ( int col = 0; col < iterCols; col++ )
{
bool isNoData = false;
double val = inputBlock->valueAndNoData( row, col, isNoData );
if ( isNoData )
{
outputBlock->setValue( row, col, mNoData );
}
else
{
double newValue = ( ( val - stats.minimumValue ) * ( mMaximum - mMinimum ) / ( stats.maximumValue - stats.minimumValue ) ) + mMinimum;
outputBlock->setValue( row, col, newValue );
}
}
}
destProvider->writeBlock( outputBlock.get(), mBand, iterLeft, iterTop );
}
destProvider->setEditable( false );
QVariantMap outputs;
outputs.insert( QStringLiteral( "OUTPUT" ), outputFile );
return outputs;
}
///@endcond
|
pblottiere/QGIS
|
src/analysis/processing/qgsalgorithmrescaleraster.cpp
|
C++
|
gpl-2.0
| 8,379
|
/*
* Copyright (c) 2015, 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 org.graalvm.compiler.replacements.test;
import org.graalvm.compiler.core.test.GraalCompilerTest;
import org.graalvm.compiler.replacements.ReplacementsImpl;
import org.graalvm.compiler.replacements.classfile.ClassfileBytecodeProvider;
import jdk.vm.ci.meta.MetaAccessProvider;
public abstract class ReplacementsTest extends GraalCompilerTest {
/**
* Gets a {@link ClassfileBytecodeProvider} that enables snippets and intrinsics to be loaded
* from the system class path (instead of from the JVMCI class path or Graal module).
*/
protected final ClassfileBytecodeProvider getSystemClassLoaderBytecodeProvider() {
ReplacementsImpl d = (ReplacementsImpl) getReplacements();
MetaAccessProvider metaAccess = d.providers.getMetaAccess();
ClassfileBytecodeProvider bytecodeProvider = new ClassfileBytecodeProvider(metaAccess, d.snippetReflection, ClassLoader.getSystemClassLoader());
return bytecodeProvider;
}
}
|
graalvm/graal-core
|
graal/org.graalvm.compiler.replacements.test/src/org/graalvm/compiler/replacements/test/ReplacementsTest.java
|
Java
|
gpl-2.0
| 2,028
|
<?php
/**
* Magento
*
* NOTICE OF LICENSE
*
* This source file is subject to the Open Software License (OSL 3.0)
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/osl-3.0.php
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@magento.com so we can send you a copy immediately.
*
* DISCLAIMER
*
* Do not edit or add to this file if you wish to upgrade Magento to newer
* versions in the future. If you wish to customize Magento for your
* needs please refer to http://www.magento.com for more information.
*
* @category Mage
* @package Mage_Adminhtml
* @copyright Copyright (c) 2006-2017 X.commerce, Inc. and affiliates (http://www.magento.com)
* @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0)
*/
/**
* Product in category grid
*
* @category Mage
* @package Mage_Adminhtml
* @author Magento Core Team <core@magentocommerce.com>
*/
class Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Group extends Mage_Adminhtml_Block_Widget_Grid
implements Mage_Adminhtml_Block_Widget_Tab_Interface
{
public function __construct()
{
parent::__construct();
$this->setId('super_product_grid');
$this->setDefaultSort('entity_id');
$this->setSkipGenerateContent(true);
$this->setUseAjax(true);
if ($this->_getProduct()->getId()) {
$this->setDefaultFilter(array('in_products'=>1));
}
}
public function getTabUrl()
{
return $this->getUrl('*/*/superGroup', array('_current'=>true));
}
public function getTabClass()
{
return 'ajax';
}
/**
* Retrieve currently edited product model
*
* @return Mage_Catalog_Model_Product
*/
protected function _getProduct()
{
return Mage::registry('current_product');
}
protected function _addColumnFilterToCollection($column)
{
// Set custom filter for in product flag
if ($column->getId() == 'in_products') {
$productIds = $this->_getSelectedProducts();
if (empty($productIds)) {
$productIds = 0;
}
if ($column->getFilter()->getValue()) {
$this->getCollection()->addFieldToFilter('entity_id', array('in'=>$productIds));
}
else {
$this->getCollection()->addFieldToFilter('entity_id', array('nin'=>$productIds));
}
}
else {
parent::_addColumnFilterToCollection($column);
}
return $this;
}
/**
* Prepare collection
*
* @return Mage_Adminhtml_Block_Catalog_Product_Edit_Tab_Super_Group
*/
protected function _prepareCollection()
{
$allowProductTypes = array();
$allowProductTypeNodes = Mage::getConfig()
->getNode('global/catalog/product/type/grouped/allow_product_types')->children();
foreach ($allowProductTypeNodes as $type) {
$allowProductTypes[] = $type->getName();
}
$collection = Mage::getModel('catalog/product_link')->useGroupedLinks()
->getProductCollection()
->setProduct($this->_getProduct())
->addAttributeToSelect('*')
->addFilterByRequiredOptions()
->addAttributeToFilter('type_id', $allowProductTypes);
if ($this->getIsReadonly() === true) {
$collection->addFieldToFilter('entity_id', array('in' => $this->_getSelectedProducts()));
}
$this->setCollection($collection);
return parent::_prepareCollection();
}
protected function _prepareColumns()
{
$this->addColumn('in_products', array(
'header_css_class' => 'a-center',
'type' => 'checkbox',
'name' => 'in_products',
'values' => $this->_getSelectedProducts(),
'align' => 'center',
'index' => 'entity_id'
));
$this->addColumn('entity_id', array(
'header' => Mage::helper('catalog')->__('ID'),
'sortable' => true,
'width' => '60px',
'index' => 'entity_id'
));
$this->addColumn('name', array(
'header' => Mage::helper('catalog')->__('Name'),
'index' => 'name'
));
$this->addColumn('sku', array(
'header' => Mage::helper('catalog')->__('SKU'),
'width' => '80px',
'index' => 'sku'
));
$this->addColumn('price', array(
'header' => Mage::helper('catalog')->__('Price'),
'type' => 'currency',
'currency_code' => (string) Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE),
'index' => 'price'
));
$this->addColumn('qty', array(
'header' => Mage::helper('catalog')->__('Default Qty'),
'name' => 'qty',
'type' => 'number',
'validate_class' => 'validate-number',
'index' => 'qty',
'width' => '1',
'editable' => true,
'filter_condition_callback' => array($this, '_addLinkModelFilterCallback')
));
$this->addColumn('position', array(
'header' => Mage::helper('catalog')->__('Position'),
'name' => 'position',
'type' => 'number',
'validate_class' => 'validate-number',
'index' => 'position',
'width' => '1',
'editable' => true,
'edit_only' => !$this->_getProduct()->getId(),
'filter_condition_callback' => array($this, '_addLinkModelFilterCallback')
));
return parent::_prepareColumns();
}
/**
* Get Grid Url
*
* @return string
*/
public function getGridUrl()
{
return $this->_getData('grid_url')
? $this->_getData('grid_url') : $this->getUrl('*/*/superGroupGridOnly', array('_current'=>true));
}
/**
* Retrieve selected grouped products
*
* @return array
*/
protected function _getSelectedProducts()
{
$products = $this->getProductsGrouped();
if (!is_array($products)) {
$products = array_keys($this->getSelectedGroupedProducts());
}
return $products;
}
/**
* Retrieve grouped products
*
* @return array
*/
public function getSelectedGroupedProducts()
{
$associatedProducts = Mage::registry('current_product')->getTypeInstance(true)
->getAssociatedProducts(Mage::registry('current_product'));
$products = array();
foreach ($associatedProducts as $product) {
$products[$product->getId()] = array(
'qty' => $product->getQty(),
'position' => $product->getPosition()
);
}
return $products;
}
public function getTabLabel()
{
return Mage::helper('catalog')->__('Associated Products');
}
public function getTabTitle()
{
return Mage::helper('catalog')->__('Associated Products');
}
public function canShowTab()
{
return true;
}
public function isHidden()
{
return false;
}
}
|
miguelangelramirez/magento.dev
|
app/code/core/Mage/Adminhtml/Block/Catalog/Product/Edit/Tab/Super/Group.php
|
PHP
|
gpl-2.0
| 7,569
|
/*
* ARM-NEON-optimized IDCT functions
* Copyright (c) 2008 Mans Rullgard <mans@mansr.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include "libavutil/attributes.h"
#include "libavcodec/avcodec.h"
#include "libavcodec/idctdsp.h"
#include "idct.h"
#include "idctdsp_arm.h"
void ff_add_pixels_clamped_neon(const int16_t *, uint8_t *, int);
void ff_put_pixels_clamped_neon(const int16_t *, uint8_t *, int);
void ff_put_signed_pixels_clamped_neon(const int16_t *, uint8_t *, int);
av_cold void ff_idctdsp_init_neon(IDCTDSPContext *c, AVCodecContext *avctx,
unsigned high_bit_depth)
{
if (!avctx->lowres && !high_bit_depth) {
if (avctx->idct_algo == FF_IDCT_AUTO ||
avctx->idct_algo == FF_IDCT_SIMPLEAUTO ||
avctx->idct_algo == FF_IDCT_SIMPLENEON) {
c->idct_put = ff_simple_idct_put_neon;
c->idct_add = ff_simple_idct_add_neon;
c->idct = ff_simple_idct_neon;
c->perm_type = FF_IDCT_PERM_PARTTRANS;
}
}
c->add_pixels_clamped = ff_add_pixels_clamped_neon;
c->put_pixels_clamped = ff_put_pixels_clamped_neon;
c->put_signed_pixels_clamped = ff_put_signed_pixels_clamped_neon;
}
|
AreaScout/vice-gles2
|
src/lib/libffmpeg/libavcodec/arm/idctdsp_init_neon.c
|
C
|
gpl-2.0
| 1,982
|
/* gdb-stub.h: FRV GDB stub
*
* Copyright (C) 2003 Red Hat, Inc. All Rights Reserved.
* Written by David Howells (dhowells@redhat.com)
* - Derived from asm-mips/gdb-stub.h (c) 1995 Andreas Busse
*
* 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 __ASM_GDB_STUB_H
#define __ASM_GDB_STUB_H
#undef GDBSTUB_DEBUG_PROTOCOL
#include <asm/ptrace.h>
/*
* important register numbers in GDB protocol
* - GR0, GR1, GR2, GR3, GR4, GR5, GR6, GR7,
* - GR8, GR9, GR10, GR11, GR12, GR13, GR14, GR15,
* - GR16, GR17, GR18, GR19, GR20, GR21, GR22, GR23,
* - GR24, GR25, GR26, GR27, GR28, GR29, GR30, GR31,
* - GR32, GR33, GR34, GR35, GR36, GR37, GR38, GR39,
* - GR40, GR41, GR42, GR43, GR44, GR45, GR46, GR47,
* - GR48, GR49, GR50, GR51, GR52, GR53, GR54, GR55,
* - GR56, GR57, GR58, GR59, GR60, GR61, GR62, GR63,
* - FR0, FR1, FR2, FR3, FR4, FR5, FR6, FR7,
* - FR8, FR9, FR10, FR11, FR12, FR13, FR14, FR15,
* - FR16, FR17, FR18, FR19, FR20, FR21, FR22, FR23,
* - FR24, FR25, FR26, FR27, FR28, FR29, FR30, FR31,
* - FR32, FR33, FR34, FR35, FR36, FR37, FR38, FR39,
* - FR40, FR41, FR42, FR43, FR44, FR45, FR46, FR47,
* - FR48, FR49, FR50, FR51, FR52, FR53, FR54, FR55,
* - FR56, FR57, FR58, FR59, FR60, FR61, FR62, FR63,
* - PC, PSR, CCR, CCCR,
* - _X132, _X133, _X134
* - TBR, BRR, DBAR0, DBAR1, DBAR2, DBAR3,
* - SCR0, SCR1, SCR2, SCR3,
* - LR, LCR,
* - IACC0H, IACC0L,
* - FSR0,
* - ACC0, ACC1, ACC2, ACC3, ACC4, ACC5, ACC6, ACC7,
* - ACCG0123, ACCG4567,
* - MSR0, MSR1,
* - GNER0, GNER1,
* - FNER0, FNER1,
*/
#define GDB_REG_GR(N) (N)
#define GDB_REG_FR(N) (64+(N))
#define GDB_REG_PC 128
#define GDB_REG_PSR 129
#define GDB_REG_CCR 130
#define GDB_REG_CCCR 131
#define GDB_REG_TBR 135
#define GDB_REG_BRR 136
#define GDB_REG_DBAR(N) (137+(N))
#define GDB_REG_SCR(N) (141+(N))
#define GDB_REG_LR 145
#define GDB_REG_LCR 146
#define GDB_REG_FSR0 149
#define GDB_REG_ACC(N) (150+(N))
#define GDB_REG_ACCG(N) (158+(N)/4)
#define GDB_REG_MSR(N) (160+(N))
#define GDB_REG_GNER(N) (162+(N))
#define GDB_REG_FNER(N) (164+(N))
#define GDB_REG_SP GDB_REG_GR(1)
#define GDB_REG_FP GDB_REG_GR(2)
#ifndef _LANGUAGE_ASSEMBLY
/*
* Prototypes
*/
extern void show_registers_only(struct pt_regs *regs);
extern void gdbstub_init(void);
extern void gdbstub(int type);
extern void gdbstub_exit(int status);
extern void gdbstub_io_init(void);
extern void gdbstub_set_baud(unsigned baud);
extern int gdbstub_rx_char(unsigned char *_ch, int nonblock);
extern void gdbstub_tx_char(unsigned char ch);
extern void gdbstub_tx_flush(void);
extern void gdbstub_do_rx(void);
extern asmlinkage void __debug_stub_init_break(void);
extern asmlinkage void start_kernel(void);
extern asmlinkage void gdbstub_rx_handler(void);
extern asmlinkage void gdbstub_rx_irq(void);
extern asmlinkage void gdbstub_intercept(void);
extern uint32_t __entry_usertrap_table[];
extern uint32_t __entry_kerneltrap_table[];
extern volatile u8 gdbstub_rx_buffer[PAGE_SIZE];
extern volatile u32 gdbstub_rx_inp;
extern volatile u32 gdbstub_rx_outp;
extern volatile u8 gdbstub_rx_overflow;
extern u8 gdbstub_rx_unget;
extern void gdbstub_printk(const char *fmt, ...);
extern void debug_to_serial(const char *p, int n);
extern void console_set_baud(unsigned baud);
#ifdef GDBSTUB_DEBUG_PROTOCOL
#define gdbstub_proto(FMT,...) gdbstub_printk(FMT,##__VA_ARGS__)
#else
#define gdbstub_proto(FMT,...) ({ 0; })
#endif
#endif /* _LANGUAGE_ASSEMBLY */
#endif /* __ASM_GDB_STUB_H */
|
ysei/linux-2.4.32-ipod
|
include/asm-frv/gdb-stub.h
|
C
|
gpl-2.0
| 3,687
|
//>>built
define("dojox/mvc/StatefulSeries",["dojo/_base/array","dojo/_base/declare","dojo/_base/lang","dojox/mvc/at"],function(_1,_2,_3,at){
return _2("dojox.mvc.StatefulSeries",null,{constructor:function(_4){
var _5=this;
function _6(){
if(_5.series){
_5.series.chart.updateSeries(_5.series.name,_5);
_5.series.chart.delayedRender();
}
};
this._handles=[];
this.data=_1.map(_4,function(_7,_8){
if((_7||{}).atsignature=="dojox.mvc.at"){
var _9=_7.target,_a=_7.targetProp;
if(_3.isString(_9)){
throw new Error("Literal-based dojox/mvc/at is not supported in dojox/mvc/StatefulSeries.");
}
if(_7.bindDirection&&!(_7.bindDirection&at.from)){
console.warn("Data binding bindDirection option is ignored in dojox/mvc/StatefulSeries.");
}
if(_a&&_3.isFunction(_9.set)&&_3.isFunction(_9.watch)){
var _b=_7.converter,_c=(_b||{}).format&&_3.hitch({target:_9,source:this},_b.format);
this._handles.push(_9.watch(_a,function(_d,_e,_f){
_5.data[_8]=_c?_c(_f):_f;
_6();
}));
}
return !_a?_9:_3.isFunction(_9.get)?_9.get(_a):_9[_a];
}else{
return _7;
}
},this);
_6();
},destroy:function(){
for(var h=null;h=this._handles.pop();){
h.unwatch();
}
},setSeriesObject:function(_10){
this.series=_10;
}});
});
|
hariomkumarmth/champaranexpress
|
wp-content/plugins/dojo/dojox/mvc/StatefulSeries.js
|
JavaScript
|
gpl-2.0
| 1,231
|
/*
* MMU fault handling support.
*
* Copyright (C) 1998-2002 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
*/
#include <linux/sched.h>
#include <linux/kernel.h>
#include <linux/mm.h>
#include <linux/smp_lock.h>
#include <linux/interrupt.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/system.h>
#include <asm/uaccess.h>
extern void die (char *, struct pt_regs *, long);
/*
* This routine is analogous to expand_stack() but instead grows the
* register backing store (which grows towards higher addresses).
* Since the register backing store is access sequentially, we
* disallow growing the RBS by more than a page at a time. Note that
* the VM_GROWSUP flag can be set on any VM area but that's fine
* because the total process size is still limited by RLIMIT_STACK and
* RLIMIT_AS.
*/
static inline long
expand_backing_store (struct vm_area_struct *vma, unsigned long address)
{
unsigned long grow;
grow = PAGE_SIZE >> PAGE_SHIFT;
if (address - vma->vm_start > current->signal->rlim[RLIMIT_STACK].rlim_cur
|| (((vma->vm_mm->total_vm + grow) << PAGE_SHIFT) > current->signal->rlim[RLIMIT_AS].rlim_cur))
return -ENOMEM;
vma->vm_end += PAGE_SIZE;
vma->vm_mm->total_vm += grow;
if (vma->vm_flags & VM_LOCKED)
vma->vm_mm->locked_vm += grow;
__vm_stat_account(vma->vm_mm, vma->vm_flags, vma->vm_file, grow);
return 0;
}
/*
* Return TRUE if ADDRESS points at a page in the kernel's mapped segment
* (inside region 5, on ia64) and that page is present.
*/
static int
mapped_kernel_page_is_present (unsigned long address)
{
pgd_t *pgd;
pud_t *pud;
pmd_t *pmd;
pte_t *ptep, pte;
pgd = pgd_offset_k(address);
if (pgd_none(*pgd) || pgd_bad(*pgd))
return 0;
pud = pud_offset(pgd, address);
if (pud_none(*pud) || pud_bad(*pud))
return 0;
pmd = pmd_offset(pud, address);
if (pmd_none(*pmd) || pmd_bad(*pmd))
return 0;
ptep = pte_offset_kernel(pmd, address);
if (!ptep)
return 0;
pte = *ptep;
return pte_present(pte);
}
void
ia64_do_page_fault (unsigned long address, unsigned long isr, struct pt_regs *regs)
{
int signal = SIGSEGV, code = SEGV_MAPERR;
struct vm_area_struct *vma, *prev_vma;
struct mm_struct *mm = current->mm;
struct siginfo si;
unsigned long mask;
/*
* If we're in an interrupt or have no user context, we must not take the fault..
*/
if (in_atomic() || !mm)
goto no_context;
#ifdef CONFIG_VIRTUAL_MEM_MAP
/*
* If fault is in region 5 and we are in the kernel, we may already
* have the mmap_sem (pfn_valid macro is called during mmap). There
* is no vma for region 5 addr's anyway, so skip getting the semaphore
* and go directly to the exception handling code.
*/
if ((REGION_NUMBER(address) == 5) && !user_mode(regs))
goto bad_area_no_up;
#endif
down_read(&mm->mmap_sem);
vma = find_vma_prev(mm, address, &prev_vma);
if (!vma)
goto bad_area;
/* find_vma_prev() returns vma such that address < vma->vm_end or NULL */
if (address < vma->vm_start)
goto check_expansion;
good_area:
code = SEGV_ACCERR;
/* OK, we've got a good vm_area for this memory area. Check the access permissions: */
# define VM_READ_BIT 0
# define VM_WRITE_BIT 1
# define VM_EXEC_BIT 2
# if (((1 << VM_READ_BIT) != VM_READ || (1 << VM_WRITE_BIT) != VM_WRITE) \
|| (1 << VM_EXEC_BIT) != VM_EXEC)
# error File is out of sync with <linux/mm.h>. Please update.
# endif
mask = ( (((isr >> IA64_ISR_X_BIT) & 1UL) << VM_EXEC_BIT)
| (((isr >> IA64_ISR_W_BIT) & 1UL) << VM_WRITE_BIT)
| (((isr >> IA64_ISR_R_BIT) & 1UL) << VM_READ_BIT));
if ((vma->vm_flags & mask) != mask)
goto bad_area;
survive:
/*
* If for any reason at all we couldn't handle the fault, make
* sure we exit gracefully rather than endlessly redo the
* fault.
*/
switch (handle_mm_fault(mm, vma, address, (mask & VM_WRITE) != 0)) {
case VM_FAULT_MINOR:
++current->min_flt;
break;
case VM_FAULT_MAJOR:
++current->maj_flt;
break;
case VM_FAULT_SIGBUS:
/*
* We ran out of memory, or some other thing happened
* to us that made us unable to handle the page fault
* gracefully.
*/
signal = SIGBUS;
goto bad_area;
case VM_FAULT_OOM:
goto out_of_memory;
default:
BUG();
}
up_read(&mm->mmap_sem);
return;
check_expansion:
if (!(prev_vma && (prev_vma->vm_flags & VM_GROWSUP) && (address == prev_vma->vm_end))) {
if (!(vma->vm_flags & VM_GROWSDOWN))
goto bad_area;
if (REGION_NUMBER(address) != REGION_NUMBER(vma->vm_start)
|| REGION_OFFSET(address) >= RGN_MAP_LIMIT)
goto bad_area;
if (expand_stack(vma, address))
goto bad_area;
} else {
vma = prev_vma;
if (REGION_NUMBER(address) != REGION_NUMBER(vma->vm_start)
|| REGION_OFFSET(address) >= RGN_MAP_LIMIT)
goto bad_area;
if (expand_backing_store(vma, address))
goto bad_area;
}
goto good_area;
bad_area:
up_read(&mm->mmap_sem);
#ifdef CONFIG_VIRTUAL_MEM_MAP
bad_area_no_up:
#endif
if ((isr & IA64_ISR_SP)
|| ((isr & IA64_ISR_NA) && (isr & IA64_ISR_CODE_MASK) == IA64_ISR_CODE_LFETCH))
{
/*
* This fault was due to a speculative load or lfetch.fault, set the "ed"
* bit in the psr to ensure forward progress. (Target register will get a
* NaT for ld.s, lfetch will be canceled.)
*/
ia64_psr(regs)->ed = 1;
return;
}
if (user_mode(regs)) {
si.si_signo = signal;
si.si_errno = 0;
si.si_code = code;
si.si_addr = (void __user *) address;
si.si_isr = isr;
si.si_flags = __ISR_VALID;
force_sig_info(signal, &si, current);
return;
}
no_context:
if ((isr & IA64_ISR_SP)
|| ((isr & IA64_ISR_NA) && (isr & IA64_ISR_CODE_MASK) == IA64_ISR_CODE_LFETCH))
{
/*
* This fault was due to a speculative load or lfetch.fault, set the "ed"
* bit in the psr to ensure forward progress. (Target register will get a
* NaT for ld.s, lfetch will be canceled.)
*/
ia64_psr(regs)->ed = 1;
return;
}
if (ia64_done_with_exception(regs))
return;
/*
* Since we have no vma's for region 5, we might get here even if the address is
* valid, due to the VHPT walker inserting a non present translation that becomes
* stale. If that happens, the non present fault handler already purged the stale
* translation, which fixed the problem. So, we check to see if the translation is
* valid, and return if it is.
*/
if (REGION_NUMBER(address) == 5 && mapped_kernel_page_is_present(address))
return;
/*
* Oops. The kernel tried to access some bad page. We'll have to terminate things
* with extreme prejudice.
*/
bust_spinlocks(1);
if (address < PAGE_SIZE)
printk(KERN_ALERT "Unable to handle kernel NULL pointer dereference (address %016lx)\n", address);
else
printk(KERN_ALERT "Unable to handle kernel paging request at "
"virtual address %016lx\n", address);
die("Oops", regs, isr);
bust_spinlocks(0);
do_exit(SIGKILL);
return;
out_of_memory:
up_read(&mm->mmap_sem);
if (current->pid == 1) {
yield();
down_read(&mm->mmap_sem);
goto survive;
}
printk(KERN_CRIT "VM: killing process %s\n", current->comm);
if (user_mode(regs))
do_exit(SIGKILL);
goto no_context;
}
|
xtreamerdev/linux-xtr
|
arch/ia64/mm/fault.c
|
C
|
gpl-2.0
| 7,149
|
/*
* Copyright (C) 2005-2015 Team Kodi
* http://kodi.tv
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Kodi; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
#include "MusicDatabase.h"
#include "addons/Addon.h"
#include "addons/AddonManager.h"
#include "addons/Scraper.h"
#include "Album.h"
#include "Application.h"
#include "Artist.h"
#include "CueInfoLoader.h"
#include "dbwrappers/dataset.h"
#include "dialogs/GUIDialogKaiToast.h"
#include "dialogs/GUIDialogOK.h"
#include "dialogs/GUIDialogProgress.h"
#include "dialogs/GUIDialogSelect.h"
#include "FileItem.h"
#include "filesystem/DirectoryCache.h"
#include "filesystem/File.h"
#include "filesystem/MusicDatabaseDirectory/DirectoryNode.h"
#include "filesystem/MusicDatabaseDirectory/QueryParams.h"
#include "guiinfo/GUIInfoLabels.h"
#include "GUIInfoManager.h"
#include "guilib/GUIWindowManager.h"
#include "guilib/LocalizeStrings.h"
#include "interfaces/AnnouncementManager.h"
#include "messaging/helpers/DialogHelper.h"
#include "music/tags/MusicInfoTag.h"
#include "network/cddb.h"
#include "network/Network.h"
#include "playlists/SmartPlayList.h"
#include "profiles/ProfilesManager.h"
#include "settings/AdvancedSettings.h"
#include "settings/MediaSettings.h"
#include "settings/Settings.h"
#include "Song.h"
#include "storage/MediaManager.h"
#include "system.h"
#include "TextureCache.h"
#include "threads/SystemClock.h"
#include "URL.h"
#include "utils/FileUtils.h"
#include "utils/LegacyPathTranslation.h"
#include "utils/log.h"
#include "utils/StringUtils.h"
#include "utils/URIUtils.h"
#include "TextureCache.h"
#include "interfaces/AnnouncementManager.h"
#include "dbwrappers/dataset.h"
#include "utils/XMLUtils.h"
using namespace XFILE;
using namespace MUSICDATABASEDIRECTORY;
using namespace KODI::MESSAGING;
using ADDON::AddonPtr;
using KODI::MESSAGING::HELPERS::DialogResponse;
#define RECENTLY_PLAYED_LIMIT 25
#define MIN_FULL_SEARCH_LENGTH 3
#ifdef HAS_DVD_DRIVE
using namespace CDDB;
using namespace MEDIA_DETECT;
#endif
static void AnnounceRemove(const std::string& content, int id)
{
CVariant data;
data["type"] = content;
data["id"] = id;
if (g_application.IsMusicScanning())
data["transaction"] = true;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnRemove", data);
}
static void AnnounceUpdate(const std::string& content, int id)
{
CVariant data;
data["type"] = content;
data["id"] = id;
if (g_application.IsMusicScanning())
data["transaction"] = true;
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnUpdate", data);
}
CMusicDatabase::CMusicDatabase(void)
{
}
CMusicDatabase::~CMusicDatabase(void)
{
EmptyCache();
}
bool CMusicDatabase::Open()
{
return CDatabase::Open(g_advancedSettings.m_databaseMusic);
}
void CMusicDatabase::CreateTables()
{
CLog::Log(LOGINFO, "create artist table");
m_pDS->exec("CREATE TABLE artist ( idArtist integer primary key, "
" strArtist varchar(256), strMusicBrainzArtistID text, "
" strBorn text, strFormed text, strGenres text, strMoods text, "
" strStyles text, strInstruments text, strBiography text, "
" strDied text, strDisbanded text, strYearsActive text, "
" strImage text, strFanart text, "
" lastScraped varchar(20) default NULL)");
CLog::Log(LOGINFO, "create album table");
m_pDS->exec("CREATE TABLE album (idAlbum integer primary key, "
" strAlbum varchar(256), strMusicBrainzAlbumID text, "
" strArtists text, strGenres text, "
" iYear integer, idThumb integer, "
" bCompilation integer not null default '0', "
" strMoods text, strStyles text, strThemes text, "
" strReview text, strImage text, strLabel text, "
" strType text, "
" fRating FLOAT NOT NULL DEFAULT 0, "
" iUserrating INTEGER NOT NULL DEFAULT 0, "
" lastScraped varchar(20) default NULL, "
" strReleaseType text, "
" iVotes INTEGER NOT NULL DEFAULT 0)");
CLog::Log(LOGINFO, "create album_artist table");
m_pDS->exec("CREATE TABLE album_artist (idArtist integer, idAlbum integer, strJoinPhrase text, boolFeatured integer, iOrder integer, strArtist text)");
CLog::Log(LOGINFO, "create album_genre table");
m_pDS->exec("CREATE TABLE album_genre (idGenre integer, idAlbum integer, iOrder integer)");
CLog::Log(LOGINFO, "create genre table");
m_pDS->exec("CREATE TABLE genre (idGenre integer primary key, strGenre varchar(256))");
CLog::Log(LOGINFO, "create path table");
m_pDS->exec("CREATE TABLE path (idPath integer primary key, strPath varchar(512), strHash text)");
CLog::Log(LOGINFO, "create song table");
m_pDS->exec("CREATE TABLE song (idSong integer primary key, "
" idAlbum integer, idPath integer, "
" strArtists text, strGenres text, strTitle varchar(512), "
" iTrack integer, iDuration integer, iYear integer, "
" dwFileNameCRC text, "
" strFileName text, strMusicBrainzTrackID text, "
" iTimesPlayed integer, iStartOffset integer, iEndOffset integer, "
" idThumb integer, "
" lastplayed varchar(20) default NULL, "
" rating FLOAT NOT NULL DEFAULT 0, userrating INTEGER NOT NULL DEFAULT 0, "
" comment text, mood text, dateAdded text, votes INTEGER NOT NULL DEFAULT 0)");
CLog::Log(LOGINFO, "create song_artist table");
m_pDS->exec("CREATE TABLE song_artist (idArtist integer, idSong integer, strJoinPhrase text, boolFeatured integer, iOrder integer, strArtist text)");
CLog::Log(LOGINFO, "create song_genre table");
m_pDS->exec("CREATE TABLE song_genre (idGenre integer, idSong integer, iOrder integer)");
CLog::Log(LOGINFO, "create albuminfosong table");
m_pDS->exec("CREATE TABLE albuminfosong (idAlbumInfoSong integer primary key, idAlbumInfo integer, iTrack integer, strTitle text, iDuration integer)");
CLog::Log(LOGINFO, "create content table");
m_pDS->exec("CREATE TABLE content (strPath text, strScraperPath text, strContent text, strSettings text)");
CLog::Log(LOGINFO, "create discography table");
m_pDS->exec("CREATE TABLE discography (idArtist integer, strAlbum text, strYear text)");
CLog::Log(LOGINFO, "create art table");
m_pDS->exec("CREATE TABLE art(art_id INTEGER PRIMARY KEY, media_id INTEGER, media_type TEXT, type TEXT, url TEXT)");
CLog::Log(LOGINFO, "create cue table");
m_pDS->exec("CREATE TABLE cue (idPath integer, strFileName text, strCuesheet text)");
}
void CMusicDatabase::CreateAnalytics()
{
CLog::Log(LOGINFO, "%s - creating indices", __FUNCTION__);
m_pDS->exec("CREATE INDEX idxAlbum ON album(strAlbum(255))");
m_pDS->exec("CREATE INDEX idxAlbum_1 ON album(bCompilation)");
m_pDS->exec("CREATE UNIQUE INDEX idxAlbum_2 ON album(strMusicBrainzAlbumID(36))");
m_pDS->exec("CREATE UNIQUE INDEX idxAlbumArtist_1 ON album_artist ( idAlbum, idArtist )");
m_pDS->exec("CREATE UNIQUE INDEX idxAlbumArtist_2 ON album_artist ( idArtist, idAlbum )");
m_pDS->exec("CREATE INDEX idxAlbumArtist_3 ON album_artist ( boolFeatured )");
m_pDS->exec("CREATE UNIQUE INDEX idxAlbumGenre_1 ON album_genre ( idAlbum, idGenre )");
m_pDS->exec("CREATE UNIQUE INDEX idxAlbumGenre_2 ON album_genre ( idGenre, idAlbum )");
m_pDS->exec("CREATE INDEX idxGenre ON genre(strGenre(255))");
m_pDS->exec("CREATE INDEX idxArtist ON artist(strArtist(255))");
m_pDS->exec("CREATE UNIQUE INDEX idxArtist1 ON artist(strMusicBrainzArtistID(36))");
m_pDS->exec("CREATE INDEX idxPath ON path(strPath(255))");
m_pDS->exec("CREATE INDEX idxSong ON song(strTitle(255))");
m_pDS->exec("CREATE INDEX idxSong1 ON song(iTimesPlayed)");
m_pDS->exec("CREATE INDEX idxSong2 ON song(lastplayed)");
m_pDS->exec("CREATE INDEX idxSong3 ON song(idAlbum)");
m_pDS->exec("CREATE INDEX idxSong6 ON song( idPath, strFileName(255) )");
m_pDS->exec("CREATE UNIQUE INDEX idxSong7 ON song( idAlbum, strMusicBrainzTrackID(36) )");
m_pDS->exec("CREATE UNIQUE INDEX idxSongArtist_1 ON song_artist ( idSong, idArtist )");
m_pDS->exec("CREATE UNIQUE INDEX idxSongArtist_2 ON song_artist ( idArtist, idSong )");
m_pDS->exec("CREATE INDEX idxSongArtist_3 ON song_artist ( boolFeatured )");
m_pDS->exec("CREATE UNIQUE INDEX idxSongGenre_1 ON song_genre ( idSong, idGenre )");
m_pDS->exec("CREATE UNIQUE INDEX idxSongGenre_2 ON song_genre ( idGenre, idSong )");
m_pDS->exec("CREATE INDEX idxAlbumInfoSong_1 ON albuminfosong ( idAlbumInfo )");
m_pDS->exec("CREATE INDEX idxDiscography_1 ON discography ( idArtist )");
m_pDS->exec("CREATE INDEX ix_art ON art(media_id, media_type(20), type(20))");
m_pDS->exec("CREATE UNIQUE INDEX idxCue ON cue(idPath, strFileName(255))");
CLog::Log(LOGINFO, "create triggers");
m_pDS->exec("CREATE TRIGGER tgrDeleteAlbum AFTER delete ON album FOR EACH ROW BEGIN"
" DELETE FROM song WHERE song.idAlbum = old.idAlbum;"
" DELETE FROM album_artist WHERE album_artist.idAlbum = old.idAlbum;"
" DELETE FROM album_genre WHERE album_genre.idAlbum = old.idAlbum;"
" DELETE FROM albuminfosong WHERE albuminfosong.idAlbumInfo=old.idAlbum;"
" DELETE FROM art WHERE media_id=old.idAlbum AND media_type='album';"
" END");
m_pDS->exec("CREATE TRIGGER tgrDeleteArtist AFTER delete ON artist FOR EACH ROW BEGIN"
" DELETE FROM album_artist WHERE album_artist.idArtist = old.idArtist;"
" DELETE FROM song_artist WHERE song_artist.idArtist = old.idArtist;"
" DELETE FROM discography WHERE discography.idArtist = old.idArtist;"
" DELETE FROM art WHERE media_id=old.idArtist AND media_type='artist';"
" END");
m_pDS->exec("CREATE TRIGGER tgrDeleteSong AFTER delete ON song FOR EACH ROW BEGIN"
" DELETE FROM song_artist WHERE song_artist.idSong = old.idSong;"
" DELETE FROM song_genre WHERE song_genre.idSong = old.idSong;"
" DELETE FROM art WHERE media_id=old.idSong AND media_type='song';"
" END");
m_pDS->exec("CREATE TRIGGER tgrDeletePath AFTER delete ON path FOR EACH ROW BEGIN"
" DELETE FROM cue WHERE cue.idPath = old.idPath;"
" END");
// we create views last to ensure all indexes are rolled in
CreateViews();
}
void CMusicDatabase::CreateViews()
{
CLog::Log(LOGINFO, "create song view");
m_pDS->exec("CREATE VIEW songview AS SELECT "
" song.idSong AS idSong, "
" song.strArtists AS strArtists,"
" song.strGenres AS strGenres,"
" strTitle, "
" iTrack, iDuration, "
" song.iYear AS iYear, "
" strFileName, "
" strMusicBrainzTrackID, "
" iTimesPlayed, iStartOffset, iEndOffset, "
" lastplayed, "
" song.rating, "
" song.userrating, "
" song.votes, "
" comment, "
" song.idAlbum AS idAlbum, "
" strAlbum, "
" strPath, "
" album.bCompilation AS bCompilation,"
" album.strArtists AS strAlbumArtists,"
" album.strReleaseType AS strAlbumReleaseType,"
" song.mood as mood,"
" song.dateAdded as dateAdded "
"FROM song"
" JOIN album ON"
" song.idAlbum=album.idAlbum"
" JOIN path ON"
" song.idPath=path.idPath");
CLog::Log(LOGINFO, "create album view");
m_pDS->exec("CREATE VIEW albumview AS SELECT "
" album.idAlbum AS idAlbum, "
" strAlbum, "
" strMusicBrainzAlbumID, "
" album.strArtists AS strArtists, "
" album.strGenres AS strGenres, "
" album.iYear AS iYear, "
" album.strMoods AS strMoods, "
" album.strStyles AS strStyles, "
" strThemes, "
" strReview, "
" strLabel, "
" strType, "
" album.strImage as strImage, "
" album.fRating, "
" album.iUserrating, "
" album.iVotes, "
" bCompilation, "
" (SELECT MIN(song.iTimesPlayed) FROM song WHERE song.idAlbum = album.idAlbum) AS iTimesPlayed, "
" strReleaseType, "
" (SELECT MAX(song.dateAdded) FROM song WHERE song.idAlbum = album.idAlbum) AS dateAdded, "
" (SELECT MAX(song.lastplayed) FROM song WHERE song.idAlbum = album.idAlbum) AS lastplayed "
"FROM album"
);
CLog::Log(LOGINFO, "create artist view");
m_pDS->exec("CREATE VIEW artistview AS SELECT"
" idArtist, strArtist, "
" strMusicBrainzArtistID, "
" strBorn, strFormed, strGenres,"
" strMoods, strStyles, strInstruments, "
" strBiography, strDied, strDisbanded, "
" strYearsActive, strImage, strFanart, "
" (SELECT MAX(song.dateAdded) FROM song_artist INNER JOIN song ON song.idSong = song_artist.idSong "
" WHERE song_artist.idArtist = artist.idArtist) AS dateAdded "
"FROM artist");
CLog::Log(LOGINFO, "create albumartist view");
m_pDS->exec("CREATE VIEW albumartistview AS SELECT"
" album_artist.idAlbum AS idAlbum, "
" album_artist.idArtist AS idArtist, "
" artist.strArtist AS strArtist, "
" artist.strMusicBrainzArtistID AS strMusicBrainzArtistID, "
" album_artist.boolFeatured AS boolFeatured, "
" album_artist.strJoinPhrase AS strJoinPhrase, "
" album_artist.iOrder AS iOrder "
"FROM album_artist "
"JOIN artist ON "
" album_artist.idArtist = artist.idArtist");
CLog::Log(LOGINFO, "create songartist view");
m_pDS->exec("CREATE VIEW songartistview AS SELECT"
" song_artist.idSong AS idSong, "
" song_artist.idArtist AS idArtist, "
" artist.strArtist AS strArtist, "
" artist.strMusicBrainzArtistID AS strMusicBrainzArtistID, "
" song_artist.boolFeatured AS boolFeatured, "
" song_artist.strJoinPhrase AS strJoinPhrase, "
" song_artist.iOrder AS iOrder "
"FROM song_artist "
"JOIN artist ON "
" song_artist.idArtist = artist.idArtist");
}
int CMusicDatabase::AddAlbumInfoSong(int idAlbum, const CSong& song)
{
std::string strSQL = PrepareSQL("SELECT idAlbumInfoSong FROM albuminfosong WHERE idAlbumInfo = %i and iTrack = %i", idAlbum, song.iTrack);
int idAlbumInfoSong = (int)strtol(GetSingleValue(strSQL).c_str(), NULL, 10);
if (idAlbumInfoSong > 0)
{
strSQL = PrepareSQL("UPDATE albuminfosong SET strTitle = '%s', iDuration = %i WHERE idAlbumInfoSong = %i", song.strTitle.c_str(), song.iDuration, idAlbumInfoSong);
return ExecuteQuery(strSQL);
}
else
{
strSQL = PrepareSQL("INSERT INTO albuminfosong (idAlbumInfoSong,idAlbumInfo,iTrack,strTitle,iDuration) VALUES (NULL,%i,%i,'%s',%i)",
idAlbum,
song.iTrack,
song.strTitle.c_str(),
song.iDuration);
return ExecuteQuery(strSQL);
}
}
void CMusicDatabase::SaveCuesheet(const std::string& fullSongPath, const std::string& strCuesheet)
{
std::string strPath, strFileName;
URIUtils::Split(fullSongPath, strPath, strFileName);
int idPath = AddPath(strPath);
if (idPath == -1)
return;
std::string strSQL;
try
{
CueCache::const_iterator it;
it = m_cueCache.find(fullSongPath);
if (it != m_cueCache.end() && it->second == strCuesheet)
return;
if (NULL == m_pDB.get())
return;
if (NULL == m_pDS.get())
return;
strSQL = PrepareSQL("SELECT * FROM cue WHERE idPath=%i AND strFileName='%s'", idPath, strFileName.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() == 0)
{
if (strCuesheet.empty())
{
m_pDS->close();
m_cueCache.insert(CueCache::value_type(fullSongPath, strCuesheet));
return;
}
strSQL = PrepareSQL("INSERT INTO cue (idPath, strFileName, strCuesheet) VALUES(%i, '%s', '%s')",
idPath, strFileName.c_str(), strCuesheet.c_str());
}
else
{
if (strCuesheet.empty())
{
strSQL = PrepareSQL("DELETE FROM cue SET WHERE idPath=%i AND strFileName='%s'", idPath, strFileName.c_str());
}
else
{
strSQL = PrepareSQL("UPDATE cue SET strCuesheet='%s') WHERE idPath=%i AND strFileName='%s'",
strCuesheet.c_str(), idPath, strFileName.c_str());
}
}
m_pDS->close();
m_pDS->exec(strSQL);
m_cueCache.insert(CueCache::value_type(fullSongPath, strCuesheet));
}
catch (...)
{
CLog::Log(LOGERROR, "musicdatabase:unable to addcue (%s)", strSQL.c_str());
}
}
std::string CMusicDatabase::LoadCuesheet(const std::string& fullSongPath)
{
CueCache::const_iterator it;
it = m_cueCache.find(fullSongPath);
if (it != m_cueCache.end())
return it->second;
std::string strCuesheet;
std::string strPath, strFileName;
URIUtils::Split(fullSongPath, strPath, strFileName);
int idPath = AddPath(strPath);
if (idPath == -1)
return strCuesheet;
std::string strSQL;
try
{
if (NULL == m_pDB.get())
return strCuesheet;
if (NULL == m_pDS.get())
return strCuesheet;
strSQL = PrepareSQL("select strCuesheet from cue where idPath=%i AND strFileName='%s'", idPath, strFileName.c_str());
m_pDS->query(strSQL);
if (0 < m_pDS->num_rows())
strCuesheet = m_pDS->get_sql_record()->at(0).get_asString();
m_pDS->close();
}
catch (...)
{
CLog::Log(LOGERROR, "musicdatabase:unable to loadcue (%s)", strSQL.c_str());
}
return strCuesheet;
}
bool CMusicDatabase::AddAlbum(CAlbum& album)
{
BeginTransaction();
album.idAlbum = AddAlbum(album.strAlbum,
album.strMusicBrainzAlbumID,
album.GetAlbumArtistString(),
album.GetGenreString(),
album.iYear,
album.bCompilation, album.releaseType);
// Add the album artists
for (VECARTISTCREDITS::iterator artistCredit = album.artistCredits.begin(); artistCredit != album.artistCredits.end(); ++artistCredit)
{
artistCredit->idArtist = AddArtist(artistCredit->GetArtist(), artistCredit->GetMusicBrainzArtistID());
AddAlbumArtist(artistCredit->idArtist,
album.idAlbum,
artistCredit->GetArtist(),
artistCredit->GetJoinPhrase(),
artistCredit == album.artistCredits.begin() ? false : true,
std::distance(album.artistCredits.begin(), artistCredit));
}
for (VECSONGS::iterator song = album.songs.begin(); song != album.songs.end(); ++song)
{
song->idAlbum = album.idAlbum;
song->idSong = AddSong(song->idAlbum,
song->strTitle, song->strMusicBrainzTrackID,
song->strFileName, song->strComment,
song->strMood, song->strThumb,
song->GetArtistString(), song->genre,
song->iTrack, song->iDuration, song->iYear,
song->iTimesPlayed, song->iStartOffset,
song->iEndOffset,
song->lastPlayed,
song->rating,
song->userrating,
song->votes);
for (VECARTISTCREDITS::iterator artistCredit = song->artistCredits.begin(); artistCredit != song->artistCredits.end(); ++artistCredit)
{
artistCredit->idArtist = AddArtist(artistCredit->GetArtist(),
artistCredit->GetMusicBrainzArtistID());
AddSongArtist(artistCredit->idArtist,
song->idSong,
artistCredit->GetArtist(),
artistCredit->GetJoinPhrase(), // we don't have song artist breakdowns from scrapers, yet
artistCredit == song->artistCredits.begin() ? false : true,
std::distance(song->artistCredits.begin(), artistCredit));
}
SaveCuesheet(song->strFileName, song->strCueSheet);
}
for (VECSONGS::const_iterator infoSong = album.infoSongs.begin(); infoSong != album.infoSongs.end(); ++infoSong)
AddAlbumInfoSong(album.idAlbum, *infoSong);
for (std::map<std::string, std::string>::const_iterator albumArt = album.art.begin();
albumArt != album.art.end();
++albumArt)
SetArtForItem(album.idAlbum, MediaTypeAlbum, albumArt->first, albumArt->second);
CommitTransaction();
return true;
}
bool CMusicDatabase::UpdateAlbum(CAlbum& album, bool OverrideTagData /* = true*/)
{
BeginTransaction();
UpdateAlbum(album.idAlbum,
album.strAlbum, album.strMusicBrainzAlbumID,
album.GetAlbumArtistString(), album.GetGenreString(),
StringUtils::Join(album.moods, g_advancedSettings.m_musicItemSeparator).c_str(),
StringUtils::Join(album.styles, g_advancedSettings.m_musicItemSeparator).c_str(),
StringUtils::Join(album.themes, g_advancedSettings.m_musicItemSeparator).c_str(),
album.strReview,
album.thumbURL.m_xml.c_str(),
album.strLabel, album.strType,
album.fRating, album.iUserrating, album.iVotes, album.iYear, album.bCompilation, album.releaseType);
if (OverrideTagData)
{
// Add the album artists
DeleteAlbumArtistsByAlbum(album.idAlbum);
for (VECARTISTCREDITS::iterator artistCredit = album.artistCredits.begin(); artistCredit != album.artistCredits.end(); ++artistCredit)
{
artistCredit->idArtist = AddArtist(artistCredit->GetArtist(),
artistCredit->GetMusicBrainzArtistID());
AddAlbumArtist(artistCredit->idArtist,
album.idAlbum,
artistCredit->GetArtist(),
artistCredit->GetJoinPhrase(),
artistCredit == album.artistCredits.begin() ? false : true,
std::distance(album.artistCredits.begin(), artistCredit));
}
for (VECSONGS::iterator song = album.songs.begin(); song != album.songs.end(); ++song)
{
UpdateSong(song->idSong,
song->strTitle,
song->strMusicBrainzTrackID,
song->strFileName,
song->strComment,
song->strMood,
song->strThumb,
song->GetArtistString(),
song->genre,
song->iTrack,
song->iDuration,
song->iYear,
song->iTimesPlayed,
song->iStartOffset,
song->iEndOffset,
song->lastPlayed,
song->rating,
song->userrating,
song->votes);
DeleteSongArtistsBySong(song->idSong);
for (VECARTISTCREDITS::iterator artistCredit = song->artistCredits.begin(); artistCredit != song->artistCredits.end(); ++artistCredit)
{
artistCredit->idArtist = AddArtist(artistCredit->GetArtist(),
artistCredit->GetMusicBrainzArtistID());
AddSongArtist(artistCredit->idArtist,
song->idSong,
artistCredit->GetArtist(),
artistCredit->GetJoinPhrase(),
artistCredit == song->artistCredits.begin() ? false : true,
std::distance(song->artistCredits.begin(), artistCredit));
}
SaveCuesheet(song->strFileName, song->strCueSheet);
}
}
for (VECSONGS::const_iterator infoSong = album.infoSongs.begin(); infoSong != album.infoSongs.end(); ++infoSong)
AddAlbumInfoSong(album.idAlbum, *infoSong);
if (!album.art.empty())
SetArtForItem(album.idAlbum, MediaTypeAlbum, album.art);
CommitTransaction();
return true;
}
int CMusicDatabase::AddSong(const int idAlbum,
const std::string& strTitle, const std::string& strMusicBrainzTrackID,
const std::string& strPathAndFileName, const std::string& strComment,
const std::string& strMood, const std::string& strThumb,
const std::string &artistString, const std::vector<std::string>& genres,
int iTrack, int iDuration, int iYear,
const int iTimesPlayed, int iStartOffset, int iEndOffset,
const CDateTime& dtLastPlayed, float rating, int userrating, int votes)
{
int idSong = -1;
std::string strSQL;
try
{
// We need at least the title
if (strTitle.empty())
return -1;
if (NULL == m_pDB.get()) return -1;
if (NULL == m_pDS.get()) return -1;
std::string strPath, strFileName;
URIUtils::Split(strPathAndFileName, strPath, strFileName);
int idPath = AddPath(strPath);
if (!strMusicBrainzTrackID.empty())
strSQL = PrepareSQL("SELECT * FROM song WHERE idAlbum = %i AND strMusicBrainzTrackID = '%s'",
idAlbum,
strMusicBrainzTrackID.c_str());
else
strSQL = PrepareSQL("SELECT * FROM song WHERE idAlbum=%i AND strFileName='%s' AND strTitle='%s' AND iTrack=%i AND strMusicBrainzTrackID IS NULL",
idAlbum,
strFileName.c_str(),
strTitle.c_str(),
iTrack);
if (!m_pDS->query(strSQL))
return -1;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
strSQL=PrepareSQL("INSERT INTO song ("
"idSong,idAlbum,idPath,strArtists,strGenres,"
"strTitle,iTrack,iDuration,iYear,strFileName,"
"strMusicBrainzTrackID,iTimesPlayed,iStartOffset,"
"iEndOffset,lastplayed,rating,userrating,votes,comment,mood"
") values (NULL, %i, %i, '%s', '%s', '%s', %i, %i, %i, '%s'",
idAlbum,
idPath,
artistString.c_str(),
StringUtils::Join(genres, g_advancedSettings.m_musicItemSeparator).c_str(),
strTitle.c_str(),
iTrack, iDuration, iYear,
strFileName.c_str());
if (strMusicBrainzTrackID.empty())
strSQL += PrepareSQL(",NULL");
else
strSQL += PrepareSQL(",'%s'", strMusicBrainzTrackID.c_str());
if (dtLastPlayed.IsValid())
strSQL += PrepareSQL(",%i,%i,%i,'%s', %.1f, %i, %i, '%s','%s')",
iTimesPlayed, iStartOffset, iEndOffset, dtLastPlayed.GetAsDBDateTime().c_str(), rating, userrating, votes, strComment.c_str(), strMood.c_str());
else
strSQL += PrepareSQL(",%i,%i,%i,NULL, %.1f, %i, %i,'%s', '%s')",
iTimesPlayed, iStartOffset, iEndOffset, rating, userrating, votes, strComment.c_str(), strMood.c_str());
m_pDS->exec(strSQL);
idSong = (int)m_pDS->lastinsertid();
}
else
{
idSong = m_pDS->fv("idSong").get_asInt();
m_pDS->close();
UpdateSong( idSong, strTitle, strMusicBrainzTrackID, strPathAndFileName, strComment, strMood, strThumb,
artistString, genres, iTrack, iDuration, iYear, iTimesPlayed, iStartOffset, iEndOffset,
dtLastPlayed, rating, userrating, votes);
}
if (!strThumb.empty())
SetArtForItem(idSong, MediaTypeSong, "thumb", strThumb);
unsigned int index = 0;
for (std::vector<std::string>::const_iterator i = genres.begin(); i != genres.end(); ++i)
{
// index will be wrong for albums, but ordering is not all that relevant
// for genres anyway
int idGenre = AddGenre(*i);
AddSongGenre(idGenre, idSong, index);
AddAlbumGenre(idGenre, idAlbum, index++);
}
UpdateFileDateAdded(idSong, strPathAndFileName);
AnnounceUpdate(MediaTypeSong, idSong);
}
catch (...)
{
CLog::Log(LOGERROR, "musicdatabase:unable to addsong (%s)", strSQL.c_str());
}
return idSong;
}
bool CMusicDatabase::GetSong(int idSong, CSong& song)
{
try
{
song.Clear();
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL=PrepareSQL("SELECT songview.*,songartistview.* FROM songview "
" LEFT JOIN songartistview ON songview.idSong = songartistview.idSong "
" WHERE songview.idSong = %i", idSong);
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return false;
}
int songArtistOffset = song_enumCount;
std::set<int> artistcredits;
song = GetSongFromDataset(m_pDS.get()->get_sql_record());
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS.get()->get_sql_record();
int idSongArtist = record->at(songArtistOffset + artistCredit_idArtist).get_asInt();
if (artistcredits.find(idSongArtist) == artistcredits.end())
{
song.artistCredits.push_back(GetArtistCreditFromDataset(record, songArtistOffset));
artistcredits.insert(idSongArtist);
}
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idSong);
}
return false;
}
int CMusicDatabase::UpdateSong(int idSong, const CSong &song)
{
return UpdateSong(idSong,
song.strTitle,
song.strMusicBrainzTrackID,
song.strFileName,
song.strComment,
song.strMood,
song.strThumb,
song.GetArtistString(), // NOTE: Don't call this function internally!!!
song.genre,
song.iTrack,
song.iDuration,
song.iYear,
song.iTimesPlayed,
song.iStartOffset,
song.iEndOffset,
song.lastPlayed,
song.rating,
song.userrating,
song.votes);
}
int CMusicDatabase::UpdateSong(int idSong,
const std::string& strTitle, const std::string& strMusicBrainzTrackID,
const std::string& strPathAndFileName, const std::string& strComment,
const std::string& strMood, const std::string& strThumb,
const std::string& artistString, const std::vector<std::string>& genres,
int iTrack, int iDuration, int iYear,
int iTimesPlayed, int iStartOffset, int iEndOffset,
const CDateTime& dtLastPlayed, float rating, int userrating, int votes)
{
if (idSong < 0)
return -1;
std::string strSQL;
std::string strPath, strFileName;
URIUtils::Split(strPathAndFileName, strPath, strFileName);
int idPath = AddPath(strPath);
strSQL = PrepareSQL("UPDATE song SET idPath = %i, strArtists = '%s', strGenres = '%s', strTitle = '%s', iTrack = %i, iDuration = %i, iYear = %i, strFileName = '%s'",
idPath,
artistString.c_str(),
StringUtils::Join(genres, g_advancedSettings.m_musicItemSeparator).c_str(),
strTitle.c_str(),
iTrack, iDuration, iYear,
strFileName.c_str());
if (strMusicBrainzTrackID.empty())
strSQL += PrepareSQL(", strMusicBrainzTrackID = NULL");
else
strSQL += PrepareSQL(", strMusicBrainzTrackID = '%s'", strMusicBrainzTrackID.c_str());
if (dtLastPlayed.IsValid())
strSQL += PrepareSQL(", iTimesPlayed = %i, iStartOffset = %i, iEndOffset = %i, lastplayed = '%s', rating = %.1f, userrating = %i, votes = %i, comment = '%s', mood = '%s'",
iTimesPlayed, iStartOffset, iEndOffset, dtLastPlayed.GetAsDBDateTime().c_str(), rating, userrating, votes, strComment.c_str(), strMood.c_str());
else
strSQL += PrepareSQL(", iTimesPlayed = %i, iStartOffset = %i, iEndOffset = %i, lastplayed = NULL, rating = %.1f, userrating = %i, votes = %i, comment = '%s', mood = '%s'",
iTimesPlayed, iStartOffset, iEndOffset, rating, userrating, votes, strComment.c_str(), strMood.c_str());
strSQL += PrepareSQL(" WHERE idSong = %i", idSong);
bool status = ExecuteQuery(strSQL);
UpdateFileDateAdded(idSong, strPathAndFileName);
if (status)
AnnounceUpdate(MediaTypeSong, idSong);
return idSong;
}
int CMusicDatabase::AddAlbum(const std::string& strAlbum, const std::string& strMusicBrainzAlbumID,
const std::string& strArtist, const std::string& strGenre, int year,
bool bCompilation, CAlbum::ReleaseType releaseType)
{
std::string strSQL;
try
{
if (NULL == m_pDB.get()) return -1;
if (NULL == m_pDS.get()) return -1;
if (!strMusicBrainzAlbumID.empty())
strSQL = PrepareSQL("SELECT * FROM album WHERE strMusicBrainzAlbumID = '%s'",
strMusicBrainzAlbumID.c_str());
else
strSQL = PrepareSQL("SELECT * FROM album WHERE strArtists LIKE '%s' AND strAlbum LIKE '%s' AND strMusicBrainzAlbumID IS NULL",
strArtist.c_str(),
strAlbum.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
// doesnt exists, add it
if (strMusicBrainzAlbumID.empty())
strSQL=PrepareSQL("insert into album (idAlbum, strAlbum, strMusicBrainzAlbumID, strArtists, strGenres, iYear, bCompilation, strReleaseType) values( NULL, '%s', NULL, '%s', '%s', %i, %i, '%s')",
strAlbum.c_str(),
strArtist.c_str(),
strGenre.c_str(),
year,
bCompilation,
CAlbum::ReleaseTypeToString(releaseType).c_str());
else
strSQL=PrepareSQL("insert into album (idAlbum, strAlbum, strMusicBrainzAlbumID, strArtists, strGenres, iYear, bCompilation, strReleaseType) values( NULL, '%s', '%s', '%s', '%s', %i, %i, '%s')",
strAlbum.c_str(),
strMusicBrainzAlbumID.c_str(),
strArtist.c_str(),
strGenre.c_str(),
year,
bCompilation,
CAlbum::ReleaseTypeToString(releaseType).c_str());
m_pDS->exec(strSQL);
return (int)m_pDS->lastinsertid();
}
else
{
/* Exists in our database and being re-scanned from tags, so we should update it as the details
may have changed.
Note that for multi-folder albums this will mean the last folder scanned will have the information
stored for it. Most values here should be the same across all songs anyway, but it does mean
that if there's any inconsistencies then only the last folders information will be taken.
We make sure we clear out the link tables (album artists, album genres) and we reset
the last scraped time to make sure that online metadata is re-fetched. */
int idAlbum = m_pDS->fv("idAlbum").get_asInt();
m_pDS->close();
if (strMusicBrainzAlbumID.empty())
strSQL=PrepareSQL("UPDATE album SET strGenres = '%s', iYear=%i, bCompilation=%i, strReleaseType = '%s', lastScraped = NULL WHERE idAlbum=%i",
strGenre.c_str(),
year,
bCompilation,
CAlbum::ReleaseTypeToString(releaseType).c_str(),
idAlbum);
else
strSQL=PrepareSQL("UPDATE album SET strAlbum = '%s', strArtists = '%s', strGenres = '%s', iYear=%i, bCompilation=%i, strReleaseType = '%s', lastScraped = NULL WHERE idAlbum=%i",
strAlbum.c_str(),
strArtist.c_str(),
strGenre.c_str(),
year,
bCompilation,
CAlbum::ReleaseTypeToString(releaseType).c_str(),
idAlbum);
m_pDS->exec(strSQL);
DeleteAlbumArtistsByAlbum(idAlbum);
DeleteAlbumGenresByAlbum(idAlbum);
return idAlbum;
}
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed with query (%s)", __FUNCTION__, strSQL.c_str());
}
return -1;
}
int CMusicDatabase::UpdateAlbum(int idAlbum,
const std::string& strAlbum, const std::string& strMusicBrainzAlbumID,
const std::string& strArtist, const std::string& strGenre,
const std::string& strMoods, const std::string& strStyles,
const std::string& strThemes, const std::string& strReview,
const std::string& strImage, const std::string& strLabel,
const std::string& strType,
float fRating, int iUserrating, int iVotes, int iYear, bool bCompilation,
CAlbum::ReleaseType releaseType)
{
if (idAlbum < 0)
return -1;
std::string strSQL;
strSQL = PrepareSQL("UPDATE album SET "
" strAlbum = '%s', strArtists = '%s', strGenres = '%s', "
" strMoods = '%s', strStyles = '%s', strThemes = '%s', "
" strReview = '%s', strImage = '%s', strLabel = '%s', "
" strType = '%s', fRating = %f, iUserrating = %i, iVotes = %i,"
" iYear = %i, bCompilation = %i, strReleaseType = '%s', "
" lastScraped = '%s'",
strAlbum.c_str(), strArtist.c_str(), strGenre.c_str(),
strMoods.c_str(), strStyles.c_str(), strThemes.c_str(),
strReview.c_str(), strImage.c_str(), strLabel.c_str(),
strType.c_str(), fRating, iUserrating, iVotes,
iYear, bCompilation,
CAlbum::ReleaseTypeToString(releaseType).c_str(),
CDateTime::GetCurrentDateTime().GetAsDBDateTime().c_str());
if (strMusicBrainzAlbumID.empty())
strSQL += PrepareSQL(", strMusicBrainzAlbumID = NULL");
else
strSQL += PrepareSQL(", strMusicBrainzAlbumID = '%s'", strMusicBrainzAlbumID.c_str());
strSQL += PrepareSQL(" WHERE idAlbum = %i", idAlbum);
bool status = ExecuteQuery(strSQL);
if (status)
AnnounceUpdate(MediaTypeAlbum, idAlbum);
return idAlbum;
}
bool CMusicDatabase::GetAlbum(int idAlbum, CAlbum& album, bool getSongs /* = true */)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
if (idAlbum == -1)
return false; // not in the database
std::string sql;
if (getSongs)
{
sql = PrepareSQL("SELECT albumview.*,albumartistview.*,songview.*,songartistview.*,albuminfosong.* "
" FROM albumview "
" LEFT JOIN albumartistview ON albumview.idAlbum = albumartistview.idAlbum "
" JOIN songview ON albumview.idAlbum = songview.idAlbum "
" LEFT JOIN songartistview ON songview.idSong = songartistview.idSong "
" LEFT JOIN albuminfosong ON albumview.idAlbum = albuminfosong.idAlbumInfo "
" WHERE albumview.idAlbum = %ld "
" ORDER BY albumartistview.iOrder, songview.iTrack, songartistview.iOrder", idAlbum);
}
else
{
sql = PrepareSQL("SELECT albumview.*,albumartistview.* "
" FROM albumview "
" LEFT JOIN albumartistview ON albumview.idAlbum = albumartistview.idAlbum "
" WHERE albumview.idAlbum = %ld "
" ORDER BY albumartistview.iOrder", idAlbum);
}
CLog::Log(LOGDEBUG, "%s", sql.c_str());
if (!m_pDS->query(sql)) return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
int albumArtistOffset = album_enumCount;
int songOffset = albumArtistOffset + artistCredit_enumCount;
int songArtistOffset = songOffset + song_enumCount;
int infoSongOffset = songArtistOffset + artistCredit_enumCount;
std::set<int> artistcredits;
std::set<int> songs;
std::set<std::pair<int, int> > songartistcredits;
std::set<int> infosongs;
album = GetAlbumFromDataset(m_pDS.get()->get_sql_record(), 0, true); // true to grab and parse the imageURL
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS->get_sql_record();
// Because rows repeat in the joined query (cartesian join) we may see each
// entity (album artist, song, song artist) multiple times in the result set.
// Since there should never be a song with the same artist twice, or an album
// with the same song (by id) listed twice, we key on the entity ID and only
// create an entity for the first occurence of each entity in the data set.
int idAlbumArtist = record->at(albumArtistOffset + artistCredit_idArtist).get_asInt();
if (artistcredits.find(idAlbumArtist) == artistcredits.end())
{
album.artistCredits.push_back(GetArtistCreditFromDataset(record, albumArtistOffset));
artistcredits.insert(idAlbumArtist);
}
if (getSongs)
{
int idSong = record->at(songOffset + song_idSong).get_asInt();
if (songs.find(idSong) == songs.end())
{
album.songs.push_back(GetSongFromDataset(record, songOffset));
songs.insert(idSong);
}
int idSongArtistSong = record->at(songArtistOffset + artistCredit_idEntity).get_asInt();
int idSongArtistArtist = record->at(songArtistOffset + artistCredit_idArtist).get_asInt();
if (songartistcredits.find(std::make_pair(idSongArtistSong, idSongArtistArtist)) == songartistcredits.end())
{
for (VECSONGS::iterator si = album.songs.begin(); si != album.songs.end(); ++si)
if (si->idSong == idSongArtistSong)
si->artistCredits.push_back(GetArtistCreditFromDataset(record, songArtistOffset));
songartistcredits.insert(std::make_pair(idSongArtistSong, idSongArtistArtist));
}
int idAlbumInfoSong = m_pDS.get()->get_sql_record()->at(infoSongOffset + albumInfoSong_idAlbumInfoSong).get_asInt();
if (infosongs.find(idAlbumInfoSong) == infosongs.end())
{
album.infoSongs.push_back(GetAlbumInfoSongFromDataset(record, infoSongOffset));
infosongs.insert(idAlbumInfoSong);
}
}
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idAlbum);
}
return false;
}
bool CMusicDatabase::ClearAlbumLastScrapedTime(int idAlbum)
{
std::string strSQL = PrepareSQL("UPDATE album SET lastScraped = NULL WHERE idAlbum = %i", idAlbum);
return ExecuteQuery(strSQL);
}
bool CMusicDatabase::HasAlbumBeenScraped(int idAlbum)
{
std::string strSQL = PrepareSQL("SELECT idAlbum FROM album WHERE idAlbum = %i AND lastScraped IS NULL", idAlbum);
return GetSingleValue(strSQL).empty();
}
int CMusicDatabase::AddGenre(const std::string& strGenre1)
{
std::string strSQL;
try
{
std::string strGenre = strGenre1;
StringUtils::Trim(strGenre);
if (strGenre.empty())
strGenre=g_localizeStrings.Get(13205); // Unknown
if (NULL == m_pDB.get()) return -1;
if (NULL == m_pDS.get()) return -1;
std::map<std::string, int>::const_iterator it;
it = m_genreCache.find(strGenre);
if (it != m_genreCache.end())
return it->second;
strSQL=PrepareSQL("select * from genre where strGenre like '%s'", strGenre.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
// doesnt exists, add it
strSQL=PrepareSQL("insert into genre (idGenre, strGenre) values( NULL, '%s' )", strGenre.c_str());
m_pDS->exec(strSQL);
int idGenre = (int)m_pDS->lastinsertid();
m_genreCache.insert(std::pair<std::string, int>(strGenre1, idGenre));
return idGenre;
}
else
{
int idGenre = m_pDS->fv("idGenre").get_asInt();
m_genreCache.insert(std::pair<std::string, int>(strGenre1, idGenre));
m_pDS->close();
return idGenre;
}
}
catch (...)
{
CLog::Log(LOGERROR, "musicdatabase:unable to addgenre (%s)", strSQL.c_str());
}
return -1;
}
bool CMusicDatabase::UpdateArtist(const CArtist& artist)
{
UpdateArtist(artist.idArtist,
artist.strArtist, artist.strMusicBrainzArtistID,
artist.strBorn, artist.strFormed,
StringUtils::Join(artist.genre, g_advancedSettings.m_musicItemSeparator),
StringUtils::Join(artist.moods, g_advancedSettings.m_musicItemSeparator),
StringUtils::Join(artist.styles, g_advancedSettings.m_musicItemSeparator),
StringUtils::Join(artist.instruments, g_advancedSettings.m_musicItemSeparator),
artist.strBiography, artist.strDied,
artist.strDisbanded,
StringUtils::Join(artist.yearsActive, g_advancedSettings.m_musicItemSeparator).c_str(),
artist.thumbURL.m_xml.c_str(),
artist.fanart.m_xml.c_str());
DeleteArtistDiscography(artist.idArtist);
std::vector<std::pair<std::string,std::string> >::const_iterator disc;
for (disc = artist.discography.begin(); disc != artist.discography.end(); ++disc)
{
AddArtistDiscography(artist.idArtist, disc->first, disc->second);
}
return true;
}
int CMusicDatabase::AddArtist(const std::string& strArtist, const std::string& strMusicBrainzArtistID)
{
std::string strSQL;
try
{
if (NULL == m_pDB.get()) return -1;
if (NULL == m_pDS.get()) return -1;
// 1) MusicBrainz
if (!strMusicBrainzArtistID.empty())
{
// 1.a) Match on a MusicBrainz ID
strSQL = PrepareSQL("SELECT * FROM artist WHERE strMusicBrainzArtistID = '%s'",
strMusicBrainzArtistID.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() > 0)
{
int idArtist = (int)m_pDS->fv("idArtist").get_asInt();
bool update = m_pDS->fv("strArtist").get_asString().compare(strMusicBrainzArtistID) == 0;
m_pDS->close();
if (update)
{
strSQL = PrepareSQL( "UPDATE artist SET strArtist = '%s' WHERE idArtist = %i", strArtist.c_str(), idArtist);
m_pDS->exec(strSQL);
m_pDS->close();
}
return idArtist;
}
m_pDS->close();
// 1.b) No match on MusicBrainz ID. Look for a previously added artist with no MusicBrainz ID
// and update that if it exists.
strSQL = PrepareSQL("SELECT * FROM artist WHERE strArtist LIKE '%s' AND strMusicBrainzArtistID IS NULL", strArtist.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() > 0)
{
int idArtist = (int)m_pDS->fv("idArtist").get_asInt();
m_pDS->close();
// 1.b.a) We found an artist by name but with no MusicBrainz ID set, update it and assume it is our artist
strSQL = PrepareSQL("UPDATE artist SET strArtist = '%s', strMusicBrainzArtistID = '%s' WHERE idArtist = %i",
strArtist.c_str(),
strMusicBrainzArtistID.c_str(),
idArtist);
m_pDS->exec(strSQL);
return idArtist;
}
// 2) No MusicBrainz - search for any artist (MB ID or non) with the same name.
// With MusicBrainz IDs this could return multiple artists and is non-determinstic
// Always pick the first artist ID returned by the DB to return.
}
else
{
strSQL = PrepareSQL("SELECT * FROM artist WHERE strArtist LIKE '%s'",
strArtist.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() > 0)
{
int idArtist = (int)m_pDS->fv("idArtist").get_asInt();
m_pDS->close();
return idArtist;
}
m_pDS->close();
}
// 3) No artist exists at all - add it
if (strMusicBrainzArtistID.empty())
strSQL = PrepareSQL("INSERT INTO artist (idArtist, strArtist, strMusicBrainzArtistID) VALUES( NULL, '%s', NULL )",
strArtist.c_str());
else
strSQL = PrepareSQL("INSERT INTO artist (idArtist, strArtist, strMusicBrainzArtistID) VALUES( NULL, '%s', '%s' )",
strArtist.c_str(),
strMusicBrainzArtistID.c_str());
m_pDS->exec(strSQL);
int idArtist = (int)m_pDS->lastinsertid();
return idArtist;
}
catch (...)
{
CLog::Log(LOGERROR, "musicdatabase:unable to addartist (%s)", strSQL.c_str());
}
return -1;
}
int CMusicDatabase::UpdateArtist(int idArtist,
const std::string& strArtist, const std::string& strMusicBrainzArtistID,
const std::string& strBorn, const std::string& strFormed,
const std::string& strGenres, const std::string& strMoods,
const std::string& strStyles, const std::string& strInstruments,
const std::string& strBiography, const std::string& strDied,
const std::string& strDisbanded, const std::string& strYearsActive,
const std::string& strImage, const std::string& strFanart)
{
CScraperUrl thumbURL;
CFanart fanart;
if (idArtist < 0)
return -1;
std::string strSQL;
strSQL = PrepareSQL("UPDATE artist SET "
" strArtist = '%s', "
" strBorn = '%s', strFormed = '%s', strGenres = '%s', "
" strMoods = '%s', strStyles = '%s', strInstruments = '%s', "
" strBiography = '%s', strDied = '%s', strDisbanded = '%s', "
" strYearsActive = '%s', strImage = '%s', strFanart = '%s', "
" lastScraped = '%s'",
strArtist.c_str(), /* strMusicBrainzArtistID.c_str(), */
strBorn.c_str(), strFormed.c_str(), strGenres.c_str(),
strMoods.c_str(), strStyles.c_str(), strInstruments.c_str(),
strBiography.c_str(), strDied.c_str(), strDisbanded.c_str(),
strYearsActive.c_str(), strImage.c_str(), strFanart.c_str(),
CDateTime::GetCurrentDateTime().GetAsDBDateTime().c_str());
if (strMusicBrainzArtistID.empty())
strSQL += PrepareSQL(", strMusicBrainzArtistID = NULL");
else
strSQL += PrepareSQL(", strMusicBrainzArtistID = '%s'", strMusicBrainzArtistID.c_str());
strSQL += PrepareSQL(" WHERE idArtist = %i", idArtist);
bool status = ExecuteQuery(strSQL);
if (status)
AnnounceUpdate(MediaTypeArtist, idArtist);
return idArtist;
}
bool CMusicDatabase::GetArtist(int idArtist, CArtist &artist, bool fetchAll /* = false */)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
if (idArtist == -1)
return false; // not in the database
std::string strSQL;
if (fetchAll)
strSQL = PrepareSQL("SELECT * FROM artistview LEFT JOIN discography ON artistview.idArtist = discography.idArtist WHERE artistview.idArtist = %i", idArtist);
else
strSQL = PrepareSQL("SELECT * FROM artistview WHERE artistview.idArtist = %i", idArtist);
if (!m_pDS->query(strSQL)) return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
int discographyOffset = artist_enumCount;
artist.discography.clear();
artist = GetArtistFromDataset(m_pDS.get()->get_sql_record(), 0, fetchAll);
if (fetchAll)
{
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS.get()->get_sql_record();
artist.discography.push_back(std::make_pair(record->at(discographyOffset + 1).get_asString(), record->at(discographyOffset + 2).get_asString()));
m_pDS->next();
}
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idArtist);
}
return false;
}
bool CMusicDatabase::HasArtistBeenScraped(int idArtist)
{
std::string strSQL = PrepareSQL("SELECT idArtist FROM artist WHERE idArtist = %i AND lastScraped IS NULL", idArtist);
return GetSingleValue(strSQL).empty();
}
bool CMusicDatabase::ClearArtistLastScrapedTime(int idArtist)
{
std::string strSQL = PrepareSQL("UPDATE artist SET lastScraped = NULL WHERE idArtist = %i", idArtist);
return ExecuteQuery(strSQL);
}
int CMusicDatabase::AddArtistDiscography(int idArtist, const std::string& strAlbum, const std::string& strYear)
{
std::string strSQL=PrepareSQL("INSERT INTO discography (idArtist, strAlbum, strYear) values(%i, '%s', '%s')",
idArtist,
strAlbum.c_str(),
strYear.c_str());
return ExecuteQuery(strSQL);
}
bool CMusicDatabase::DeleteArtistDiscography(int idArtist)
{
std::string strSQL = PrepareSQL("DELETE FROM discography WHERE idArtist = %i", idArtist);
return ExecuteQuery(strSQL);
}
bool CMusicDatabase::AddSongArtist(int idArtist, int idSong, std::string strArtist, std::string joinPhrase, bool featured, int iOrder)
{
std::string strSQL;
strSQL=PrepareSQL("replace into song_artist (idArtist, idSong, strArtist, strJoinPhrase, boolFeatured, iOrder) values(%i,%i,'%s','%s',%i,%i)",
idArtist, idSong, strArtist.c_str(), joinPhrase.c_str(), featured == true ? 1 : 0, iOrder);
return ExecuteQuery(strSQL);
};
bool CMusicDatabase::DeleteSongArtistsBySong(int idSong)
{
return ExecuteQuery(PrepareSQL("DELETE FROM song_artist WHERE idSong = %i", idSong));
}
bool CMusicDatabase::AddAlbumArtist(int idArtist, int idAlbum, std::string strArtist, std::string joinPhrase, bool featured, int iOrder)
{
std::string strSQL;
strSQL=PrepareSQL("replace into album_artist (idArtist, idAlbum, strArtist, strJoinPhrase, boolFeatured, iOrder) values(%i,%i,'%s','%s',%i,%i)",
idArtist, idAlbum, strArtist.c_str(), joinPhrase.c_str(), featured == true ? 1 : 0, iOrder);
return ExecuteQuery(strSQL);
};
bool CMusicDatabase::DeleteAlbumArtistsByAlbum(int idAlbum)
{
return ExecuteQuery(PrepareSQL("DELETE FROM album_artist WHERE idAlbum = %i", idAlbum));
}
bool CMusicDatabase::AddSongGenre(int idGenre, int idSong, int iOrder)
{
if (idGenre == -1 || idSong == -1)
return true;
std::string strSQL;
strSQL=PrepareSQL("replace into song_genre (idGenre, idSong, iOrder) values(%i,%i,%i)",
idGenre, idSong, iOrder);
return ExecuteQuery(strSQL);
};
bool CMusicDatabase::DeleteSongGenresBySong(int idSong)
{
return ExecuteQuery(PrepareSQL("DELETE FROM song_genre WHERE idSong = %i", idSong));
}
bool CMusicDatabase::AddAlbumGenre(int idGenre, int idAlbum, int iOrder)
{
if (idGenre == -1 || idAlbum == -1)
return true;
std::string strSQL;
strSQL=PrepareSQL("replace into album_genre (idGenre, idAlbum, iOrder) values(%i,%i,%i)",
idGenre, idAlbum, iOrder);
return ExecuteQuery(strSQL);
};
bool CMusicDatabase::DeleteAlbumGenresByAlbum(int idAlbum)
{
return ExecuteQuery(PrepareSQL("DELETE FROM album_genre WHERE idAlbum = %i", idAlbum));
}
bool CMusicDatabase::GetAlbumsByArtist(int idArtist, bool includeFeatured, std::vector<int> &albums)
{
try
{
std::string strSQL, strPrepSQL;
strPrepSQL = "select idAlbum from album_artist where idArtist=%i";
if (includeFeatured == false)
strPrepSQL += " AND boolFeatured = 0";
strSQL=PrepareSQL(strPrepSQL, idArtist);
if (!m_pDS->query(strSQL))
return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
while (!m_pDS->eof())
{
albums.push_back(m_pDS->fv("idAlbum").get_asInt());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idArtist);
}
return false;
}
bool CMusicDatabase::GetArtistsByAlbum(int idAlbum, CFileItem* item)
{
try
{
std::string strSQL, strPrepSQL;
strSQL = PrepareSQL("SELECT * FROM albumartistview WHERE idAlbum = %i", idAlbum);
if (!m_pDS->query(strSQL))
return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
// Get album artist credits
VECARTISTCREDITS artistCredits;
while (!m_pDS->eof())
{
artistCredits.push_back(GetArtistCreditFromDataset(m_pDS->get_sql_record(), 0));
m_pDS->next();
}
m_pDS->close();
// Populate item with song albumartist credits
std::vector<std::string> musicBrainzID;
std::vector<std::string> albumartists;
CVariant artistidObj(CVariant::VariantTypeArray);
for (VECARTISTCREDITS::const_iterator artistCredit = artistCredits.begin(); artistCredit != artistCredits.end(); ++artistCredit)
{
artistidObj.push_back(artistCredit->GetArtistId());
albumartists.push_back(artistCredit->GetArtist());
if (!artistCredit->GetMusicBrainzArtistID().empty())
musicBrainzID.push_back(artistCredit->GetMusicBrainzArtistID());
}
item->GetMusicInfoTag()->SetAlbumArtist(albumartists);
item->GetMusicInfoTag()->SetMusicBrainzAlbumArtistID(musicBrainzID);
// Add song albumartistIds as separate property as not part of CMusicInfoTag
item->SetProperty("albumartistid", artistidObj);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idAlbum);
}
return false;
}
bool CMusicDatabase::GetSongsByArtist(int idArtist, bool includeFeatured, std::vector<int> &songs)
{
try
{
std::string strSQL, strPrepSQL;
strPrepSQL = "select idSong from song_artist where idArtist=%i";
if (includeFeatured == false)
strPrepSQL += " AND boolFeatured = 0";
strSQL=PrepareSQL(strPrepSQL, idArtist);
if (!m_pDS->query(strSQL))
return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
while (!m_pDS->eof())
{
songs.push_back(m_pDS->fv("idSong").get_asInt());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idArtist);
}
return false;
};
bool CMusicDatabase::GetArtistsBySong(int idSong, bool includeFeatured, std::vector<int> &artists)
{
try
{
std::string strSQL, strPrepSQL;
strPrepSQL = "select idArtist from song_artist where idSong=%i";
if (includeFeatured == false)
strPrepSQL += " AND boolFeatured = 0";
strSQL=PrepareSQL(strPrepSQL, idSong);
if (!m_pDS->query(strSQL))
return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
while (!m_pDS->eof())
{
artists.push_back(m_pDS->fv("idArtist").get_asInt());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idSong);
}
return false;
}
bool CMusicDatabase::GetGenresByAlbum(int idAlbum, std::vector<int>& genres)
{
try
{
std::string strSQL = PrepareSQL("select idGenre from album_genre where idAlbum = %i ORDER BY iOrder ASC", idAlbum);
if (!m_pDS->query(strSQL))
return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return true;
}
while (!m_pDS->eof())
{
genres.push_back(m_pDS->fv("idGenre").get_asInt());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idAlbum);
}
return false;
}
bool CMusicDatabase::GetGenresBySong(int idSong, std::vector<int>& genres)
{
try
{
std::string strSQL = PrepareSQL("select idGenre from song_genre where idSong = %i ORDER BY iOrder ASC", idSong);
if (!m_pDS->query(strSQL))
return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return true;
}
while (!m_pDS->eof())
{
genres.push_back(m_pDS->fv("idGenre").get_asInt());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idSong);
}
return false;
}
int CMusicDatabase::AddPath(const std::string& strPath1)
{
std::string strSQL;
try
{
std::string strPath(strPath1);
if (!URIUtils::HasSlashAtEnd(strPath))
URIUtils::AddSlashAtEnd(strPath);
if (NULL == m_pDB.get()) return -1;
if (NULL == m_pDS.get()) return -1;
std::map<std::string, int>::const_iterator it;
it = m_pathCache.find(strPath);
if (it != m_pathCache.end())
return it->second;
strSQL=PrepareSQL( "select * from path where strPath='%s'", strPath.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
// doesnt exists, add it
strSQL=PrepareSQL("insert into path (idPath, strPath) values( NULL, '%s' )", strPath.c_str());
m_pDS->exec(strSQL);
int idPath = (int)m_pDS->lastinsertid();
m_pathCache.insert(std::pair<std::string, int>(strPath, idPath));
return idPath;
}
else
{
int idPath = m_pDS->fv("idPath").get_asInt();
m_pathCache.insert(std::pair<std::string, int>(strPath, idPath));
m_pDS->close();
return idPath;
}
}
catch (...)
{
CLog::Log(LOGERROR, "musicdatabase:unable to addpath (%s)", strSQL.c_str());
}
return -1;
}
CSong CMusicDatabase::GetSongFromDataset()
{
return GetSongFromDataset(m_pDS->get_sql_record());
}
CSong CMusicDatabase::GetSongFromDataset(const dbiplus::sql_record* const record, int offset /* = 0 */)
{
CSong song;
song.idSong = record->at(offset + song_idSong).get_asInt();
// Note this function does not populate artist credits, this must be done separately.
// However artist names are held as a descriptive string
song.strArtistDesc = record->at(offset + song_strArtists).get_asString();
// Get the full genre string
song.genre = StringUtils::Split(record->at(offset + song_strGenres).get_asString(), g_advancedSettings.m_musicItemSeparator);
// and the rest...
song.strAlbum = record->at(offset + song_strAlbum).get_asString();
song.idAlbum = record->at(offset + song_idAlbum).get_asInt();
song.iTrack = record->at(offset + song_iTrack).get_asInt() ;
song.iDuration = record->at(offset + song_iDuration).get_asInt() ;
song.iYear = record->at(offset + song_iYear).get_asInt() ;
song.strTitle = record->at(offset + song_strTitle).get_asString();
song.iTimesPlayed = record->at(offset + song_iTimesPlayed).get_asInt();
song.lastPlayed.SetFromDBDateTime(record->at(offset + song_lastplayed).get_asString());
song.dateAdded.SetFromDBDateTime(record->at(offset + song_dateAdded).get_asString());
song.iStartOffset = record->at(offset + song_iStartOffset).get_asInt();
song.iEndOffset = record->at(offset + song_iEndOffset).get_asInt();
song.strMusicBrainzTrackID = record->at(offset + song_strMusicBrainzTrackID).get_asString();
song.rating = record->at(offset + song_rating).get_asFloat();
song.userrating = record->at(offset + song_userrating).get_asInt();
song.votes = record->at(offset + song_votes).get_asInt();
song.strComment = record->at(offset + song_comment).get_asString();
song.strMood = record->at(offset + song_mood).get_asString();
song.bCompilation = record->at(offset + song_bCompilation).get_asInt() == 1;
// Get filename with full path
song.strFileName = URIUtils::AddFileToFolder(record->at(offset + song_strPath).get_asString(), record->at(offset + song_strFileName).get_asString());
return song;
}
void CMusicDatabase::GetFileItemFromDataset(CFileItem* item, const CMusicDbUrl &baseUrl)
{
GetFileItemFromDataset(m_pDS->get_sql_record(), item, baseUrl);
}
void CMusicDatabase::GetFileItemFromDataset(const dbiplus::sql_record* const record, CFileItem* item, const CMusicDbUrl &baseUrl)
{
// get the artist string from songview (not the song_artist and artist tables)
item->GetMusicInfoTag()->SetArtistDesc(record->at(song_strArtists).get_asString());
// and the full genre string
item->GetMusicInfoTag()->SetGenre(record->at(song_strGenres).get_asString());
// and the rest...
item->GetMusicInfoTag()->SetAlbum(record->at(song_strAlbum).get_asString());
item->GetMusicInfoTag()->SetAlbumId(record->at(song_idAlbum).get_asInt());
item->GetMusicInfoTag()->SetTrackAndDiscNumber(record->at(song_iTrack).get_asInt());
item->GetMusicInfoTag()->SetDuration(record->at(song_iDuration).get_asInt());
item->GetMusicInfoTag()->SetDatabaseId(record->at(song_idSong).get_asInt(), MediaTypeSong);
SYSTEMTIME stTime;
stTime.wYear = (WORD)record->at(song_iYear).get_asInt();
item->GetMusicInfoTag()->SetReleaseDate(stTime);
item->GetMusicInfoTag()->SetTitle(record->at(song_strTitle).get_asString());
item->SetLabel(record->at(song_strTitle).get_asString());
item->m_lStartOffset = record->at(song_iStartOffset).get_asInt();
item->SetProperty("item_start", item->m_lStartOffset);
item->m_lEndOffset = record->at(song_iEndOffset).get_asInt();
item->GetMusicInfoTag()->SetMusicBrainzTrackID(record->at(song_strMusicBrainzTrackID).get_asString());
item->GetMusicInfoTag()->SetRating(record->at(song_rating).get_asFloat());
item->GetMusicInfoTag()->SetUserrating(record->at(song_userrating).get_asInt());
item->GetMusicInfoTag()->SetVotes(record->at(song_votes).get_asInt());
item->GetMusicInfoTag()->SetComment(record->at(song_comment).get_asString());
item->GetMusicInfoTag()->SetMood(record->at(song_mood).get_asString());
item->GetMusicInfoTag()->SetPlayCount(record->at(song_iTimesPlayed).get_asInt());
item->GetMusicInfoTag()->SetLastPlayed(record->at(song_lastplayed).get_asString());
item->GetMusicInfoTag()->SetDateAdded(record->at(song_dateAdded).get_asString());
std::string strRealPath = URIUtils::AddFileToFolder(record->at(song_strPath).get_asString(), record->at(song_strFileName).get_asString());
item->GetMusicInfoTag()->SetURL(strRealPath);
item->GetMusicInfoTag()->SetCompilation(record->at(song_bCompilation).get_asInt() == 1);
// get the album artist string from songview (not the album_artist and artist tables)
item->GetMusicInfoTag()->SetAlbumArtist(record->at(song_strAlbumArtists).get_asString());
item->GetMusicInfoTag()->SetAlbumReleaseType(CAlbum::ReleaseTypeFromString(record->at(song_strAlbumReleaseType).get_asString()));
item->GetMusicInfoTag()->SetLoaded(true);
// Get filename with full path
if (!baseUrl.IsValid())
item->SetPath(strRealPath);
else
{
CMusicDbUrl itemUrl = baseUrl;
std::string strFileName = record->at(song_strFileName).get_asString();
std::string strExt = URIUtils::GetExtension(strFileName);
std::string path = StringUtils::Format("%i%s", record->at(song_idSong).get_asInt(), strExt.c_str());
itemUrl.AppendPath(path);
item->SetPath(itemUrl.ToString());
}
}
void CMusicDatabase::GetFileItemFromArtistCredits(VECARTISTCREDITS& artistCredits, CFileItem* item)
{
// Populate fileitem with artists from vector of artist credits
std::vector<std::string> musicBrainzID;
std::vector<std::string> songartists;
CVariant artistidObj(CVariant::VariantTypeArray);
for (VECARTISTCREDITS::const_iterator artistCredit = artistCredits.begin(); artistCredit != artistCredits.end(); ++artistCredit)
{
artistidObj.push_back(artistCredit->GetArtistId());
songartists.push_back(artistCredit->GetArtist());
if (!artistCredit->GetMusicBrainzArtistID().empty())
musicBrainzID.push_back(artistCredit->GetMusicBrainzArtistID());
}
item->GetMusicInfoTag()->SetArtist(songartists);
item->GetMusicInfoTag()->SetMusicBrainzArtistID(musicBrainzID);
// Add album artistIds as separate property as not part of CMusicInfoTag
item->SetProperty("artistid", artistidObj);
}
CAlbum CMusicDatabase::GetAlbumFromDataset(dbiplus::Dataset* pDS, int offset /* = 0 */, bool imageURL /* = false*/)
{
return GetAlbumFromDataset(pDS->get_sql_record(), offset, imageURL);
}
CAlbum CMusicDatabase::GetAlbumFromDataset(const dbiplus::sql_record* const record, int offset /* = 0 */, bool imageURL /* = false*/)
{
CAlbum album;
album.idAlbum = record->at(offset + album_idAlbum).get_asInt();
album.strAlbum = record->at(offset + album_strAlbum).get_asString();
if (album.strAlbum.empty())
album.strAlbum = g_localizeStrings.Get(1050);
album.strMusicBrainzAlbumID = record->at(offset + album_strMusicBrainzAlbumID).get_asString();
album.strArtistDesc = record->at(offset + album_strArtists).get_asString();
album.genre = StringUtils::Split(record->at(offset + album_strGenres).get_asString(), g_advancedSettings.m_musicItemSeparator);
album.iYear = record->at(offset + album_iYear).get_asInt();
if (imageURL)
album.thumbURL.ParseString(record->at(offset + album_strThumbURL).get_asString());
album.fRating = record->at(offset + album_fRating).get_asFloat();
album.iUserrating = record->at(offset + album_iUserrating).get_asInt();
album.iVotes = record->at(offset + album_iVotes).get_asInt();
album.iYear = record->at(offset + album_iYear).get_asInt();
album.strReview = record->at(offset + album_strReview).get_asString();
album.styles = StringUtils::Split(record->at(offset + album_strStyles).get_asString(), g_advancedSettings.m_musicItemSeparator);
album.moods = StringUtils::Split(record->at(offset + album_strMoods).get_asString(), g_advancedSettings.m_musicItemSeparator);
album.themes = StringUtils::Split(record->at(offset + album_strThemes).get_asString(), g_advancedSettings.m_musicItemSeparator);
album.strLabel = record->at(offset + album_strLabel).get_asString();
album.strType = record->at(offset + album_strType).get_asString();
album.bCompilation = record->at(offset + album_bCompilation).get_asInt() == 1;
album.iTimesPlayed = record->at(offset + album_iTimesPlayed).get_asInt();
album.SetReleaseType(record->at(offset + album_strReleaseType).get_asString());
album.SetDateAdded(record->at(offset + album_dtDateAdded).get_asString());
album.SetLastPlayed(record->at(offset + album_dtLastPlayed).get_asString());
return album;
}
CArtistCredit CMusicDatabase::GetArtistCreditFromDataset(const dbiplus::sql_record* const record, int offset /* = 0 */)
{
CArtistCredit artistCredit;
artistCredit.idArtist = record->at(offset + artistCredit_idArtist).get_asInt();
artistCredit.m_strArtist = record->at(offset + artistCredit_strArtist).get_asString();
artistCredit.m_strMusicBrainzArtistID = record->at(offset + artistCredit_strMusicBrainzArtistID).get_asString();
artistCredit.m_boolFeatured = record->at(offset + artistCredit_bFeatured).get_asBool();
artistCredit.m_strJoinPhrase = record->at(offset + artistCredit_strJoinPhrase).get_asString();
return artistCredit;
}
CArtist CMusicDatabase::GetArtistFromDataset(dbiplus::Dataset* pDS, int offset /* = 0 */, bool needThumb /* = true */)
{
return GetArtistFromDataset(pDS->get_sql_record(), offset, needThumb);
}
CArtist CMusicDatabase::GetArtistFromDataset(const dbiplus::sql_record* const record, int offset /* = 0 */, bool needThumb /* = true */)
{
CArtist artist;
artist.idArtist = record->at(offset + artist_idArtist).get_asInt();
artist.strArtist = record->at(offset + artist_strArtist).get_asString();
artist.strMusicBrainzArtistID = record->at(offset + artist_strMusicBrainzArtistID).get_asString();
artist.genre = StringUtils::Split(record->at(offset + artist_strGenres).get_asString(), g_advancedSettings.m_musicItemSeparator);
artist.strBiography = record->at(offset + artist_strBiography).get_asString();
artist.styles = StringUtils::Split(record->at(offset + artist_strStyles).get_asString(), g_advancedSettings.m_musicItemSeparator);
artist.moods = StringUtils::Split(record->at(offset + artist_strMoods).get_asString(), g_advancedSettings.m_musicItemSeparator);
artist.strBorn = record->at(offset + artist_strBorn).get_asString();
artist.strFormed = record->at(offset + artist_strFormed).get_asString();
artist.strDied = record->at(offset + artist_strDied).get_asString();
artist.strDisbanded = record->at(offset + artist_strDisbanded).get_asString();
artist.yearsActive = StringUtils::Split(record->at(offset + artist_strYearsActive).get_asString(), g_advancedSettings.m_musicItemSeparator);
artist.instruments = StringUtils::Split(record->at(offset + artist_strInstruments).get_asString(), g_advancedSettings.m_musicItemSeparator);
artist.SetDateAdded(record->at(offset + artist_dtDateAdded).get_asString());
if (needThumb)
{
artist.fanart.m_xml = record->at(artist_strFanart).get_asString();
artist.fanart.Unpack();
artist.thumbURL.ParseString(record->at(artist_strImage).get_asString());
}
return artist;
}
CSong CMusicDatabase::GetAlbumInfoSongFromDataset(const dbiplus::sql_record* const record, int offset /* = 0 */)
{
CSong song;
song.iTrack = record->at(offset + albumInfoSong_iTrack).get_asInt();
song.iDuration = record->at(offset + albumInfoSong_iDuration).get_asInt();
song.strTitle = record->at(offset + albumInfoSong_strTitle).get_asString();
return song;
}
bool CMusicDatabase::GetSongByFileName(const std::string& strFileNameAndPath, CSong& song, int startOffset)
{
song.Clear();
CURL url(strFileNameAndPath);
if (url.IsProtocol("musicdb"))
{
std::string strFile = URIUtils::GetFileName(strFileNameAndPath);
URIUtils::RemoveExtension(strFile);
return GetSong(atol(strFile.c_str()), song);
}
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strPath, strFileName;
URIUtils::Split(strFileNameAndPath, strPath, strFileName);
URIUtils::AddSlashAtEnd(strPath);
std::string strSQL = PrepareSQL("select idSong from songview "
"where strFileName='%s' and strPath='%s'",
strFileName.c_str(), strPath.c_str());
if (startOffset)
strSQL += PrepareSQL(" AND iStartOffset=%i", startOffset);
int idSong = (int)strtol(GetSingleValue(strSQL).c_str(), NULL, 10);
if (idSong > 0)
return GetSong(idSong, song);
return false;
}
int CMusicDatabase::GetAlbumIdByPath(const std::string& strPath)
{
try
{
std::string strSQL=PrepareSQL("select distinct idAlbum from song join path on song.idPath = path.idPath where path.strPath='%s'", strPath.c_str());
m_pDS->query(strSQL);
if (m_pDS->eof())
return -1;
int idAlbum = m_pDS->fv(0).get_asInt();
m_pDS->close();
return idAlbum;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, strPath.c_str());
}
return false;
}
int CMusicDatabase::GetSongByArtistAndAlbumAndTitle(const std::string& strArtist, const std::string& strAlbum, const std::string& strTitle)
{
try
{
std::string strSQL=PrepareSQL("select idSong from songview "
"where strArtists like '%s' and strAlbum like '%s' and "
"strTitle like '%s'",strArtist.c_str(),strAlbum.c_str(),strTitle.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return -1;
}
int lResult = m_pDS->fv(0).get_asInt();
m_pDS->close(); // cleanup recordset data
return lResult;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s,%s,%s) failed", __FUNCTION__, strArtist.c_str(),strAlbum.c_str(),strTitle.c_str());
}
return -1;
}
bool CMusicDatabase::SearchArtists(const std::string& search, CFileItemList &artists)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strVariousArtists = g_localizeStrings.Get(340).c_str();
std::string strSQL;
if (search.size() >= MIN_FULL_SEARCH_LENGTH)
strSQL=PrepareSQL("select * from artist "
"where (strArtist like '%s%%' or strArtist like '%% %s%%') and strArtist <> '%s' "
, search.c_str(), search.c_str(), strVariousArtists.c_str() );
else
strSQL=PrepareSQL("select * from artist "
"where strArtist like '%s%%' and strArtist <> '%s' "
, search.c_str(), strVariousArtists.c_str() );
if (!m_pDS->query(strSQL)) return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return false;
}
std::string artistLabel(g_localizeStrings.Get(557)); // Artist
while (!m_pDS->eof())
{
std::string path = StringUtils::Format("musicdb://artists/%i/", m_pDS->fv(0).get_asInt());
CFileItemPtr pItem(new CFileItem(path, true));
std::string label = StringUtils::Format("[%s] %s", artistLabel.c_str(), m_pDS->fv(1).get_asString().c_str());
pItem->SetLabel(label);
label = StringUtils::Format("A %s", m_pDS->fv(1).get_asString().c_str()); // sort label is stored in the title tag
pItem->GetMusicInfoTag()->SetTitle(label);
pItem->GetMusicInfoTag()->SetDatabaseId(m_pDS->fv(0).get_asInt(), MediaTypeArtist);
artists.Add(pItem);
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetTop100(const std::string& strBaseDir, CFileItemList& items)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
CMusicDbUrl baseUrl;
if (!strBaseDir.empty() && !baseUrl.FromString(strBaseDir))
return false;
std::string strSQL="select * from songview "
"where iTimesPlayed>0 "
"order by iTimesPlayed desc "
"limit 100";
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
items.Reserve(iRowsFound);
while (!m_pDS->eof())
{
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(item.get(), baseUrl);
items.Add(item);
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetTop100Albums(VECALBUMS& albums)
{
try
{
albums.erase(albums.begin(), albums.end());
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// Get data from album and album_artist tables to fully populate albums
std::string strSQL = "SELECT albumview.*, albumartistview.* FROM albumview "
"LEFT JOIN albumartistview ON albumview.idAlbum = albumartistview.idAlbum "
"WHERE albumartistview.idAlbum in "
"(SELECT albumview.idAlbum FROM albumview "
"WHERE albumview.strAlbum != '' AND albumview.iTimesPlayed>0 "
"ORDER BY albumview.iTimesPlayed DESC LIMIT 100) "
"ORDER BY albumview.iTimesPlayed DESC, albumartistview.iOrder";
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
int albumArtistOffset = album_enumCount;
int albumId = -1;
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS->get_sql_record();
if (albumId != record->at(album_idAlbum).get_asInt())
{ // New album
albumId = record->at(album_idAlbum).get_asInt();
albums.push_back(GetAlbumFromDataset(record));
}
// Get artist details
albums.back().artistCredits.push_back(GetArtistCreditFromDataset(record, albumArtistOffset));
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetTop100AlbumSongs(const std::string& strBaseDir, CFileItemList& items)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
CMusicDbUrl baseUrl;
if (!strBaseDir.empty() && baseUrl.FromString(strBaseDir))
return false;
std::string strSQL = StringUtils::Format("SELECT songview.*, albumview.* FROM songview JOIN albumview ON (songview.idAlbum = albumview.idAlbum) JOIN (SELECT song.idAlbum, SUM(song.iTimesPlayed) AS iTimesPlayedSum FROM song WHERE song.iTimesPlayed > 0 GROUP BY idAlbum ORDER BY iTimesPlayedSum DESC LIMIT 100) AS _albumlimit ON (songview.idAlbum = _albumlimit.idAlbum) ORDER BY _albumlimit.iTimesPlayedSum DESC");
CLog::Log(LOGDEBUG,"GetTop100AlbumSongs() query: %s", strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// get data from returned rows
items.Reserve(iRowsFound);
while (!m_pDS->eof())
{
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(item.get(), baseUrl);
items.Add(item);
m_pDS->next();
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetRecentlyPlayedAlbums(VECALBUMS& albums)
{
try
{
albums.erase(albums.begin(), albums.end());
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// Get data from album and album_artist tables to fully populate albums
std::string strSQL = PrepareSQL("SELECT albumview.*, albumartistview.* FROM "
"(SELECT idAlbum FROM albumview WHERE albumview.lastplayed IS NOT NULL "
"ORDER BY albumview.lastplayed DESC LIMIT %u) as playedalbums "
"JOIN albumview ON albumview.idAlbum = playedalbums.idAlbum "
"LEFT JOIN albumartistview ON albumview.idAlbum = albumartistview.idAlbum "
"ORDER BY albumview.lastplayed DESC, albumartistview.iorder ", RECENTLY_PLAYED_LIMIT);
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
int albumArtistOffset = album_enumCount;
int albumId = -1;
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS->get_sql_record();
if (albumId != record->at(album_idAlbum).get_asInt())
{ // New album
albumId = record->at(album_idAlbum).get_asInt();
albums.push_back(GetAlbumFromDataset(record));
}
// Get artist details
albums.back().artistCredits.push_back(GetArtistCreditFromDataset(record, albumArtistOffset));
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetRecentlyPlayedAlbumSongs(const std::string& strBaseDir, CFileItemList& items)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
CMusicDbUrl baseUrl;
if (!strBaseDir.empty() && !baseUrl.FromString(strBaseDir))
return false;
std::string strSQL = PrepareSQL("SELECT songview.*, songartistview.* FROM "
"(SELECT idAlbum FROM albumview WHERE albumview.lastplayed IS NOT NULL "
"ORDER BY albumview.lastplayed DESC LIMIT %u) as playedalbums "
"JOIN songview ON songview.idAlbum = playedalbums.idAlbum "
"LEFT JOIN songartistview ON songview.idSong = songartistview.idSong ",
g_advancedSettings.m_iMusicLibraryRecentlyAddedItems);
CLog::Log(LOGDEBUG,"GetRecentlyPlayedAlbumSongs() query: %s", strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// Needs a separate query to determine number of songs to set items size.
// Get songs from returned rows. Join means there is a row for every song artist
int songArtistOffset = song_enumCount;
int songId = -1;
VECARTISTCREDITS artistCredits;
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS->get_sql_record();
if (songId != record->at(song_idSong).get_asInt())
{ //New song
if (songId > 0 && !artistCredits.empty())
{
//Store artist credits for previous song
GetFileItemFromArtistCredits(artistCredits, items[items.Size() - 1].get());
artistCredits.clear();
}
songId = record->at(song_idSong).get_asInt();
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(record, item.get(), baseUrl);
items.Add(item);
}
// Get song artist credits
artistCredits.push_back(GetArtistCreditFromDataset(record, songArtistOffset));
m_pDS->next();
}
if (!artistCredits.empty())
{
//Store artist credits for final song
GetFileItemFromArtistCredits(artistCredits, items[items.Size() - 1].get());
artistCredits.clear();
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetRecentlyAddedAlbums(VECALBUMS& albums, unsigned int limit)
{
try
{
albums.erase(albums.begin(), albums.end());
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// Get data from album and album_artist tables to fully populate albums
// Use idAlbum to determine the recently added albums
// (not "dateAdded" as this is file time stamp and nothing to do with when albums added to library)
std::string strSQL = PrepareSQL("SELECT albumview.*, albumartistview.* FROM "
"(SELECT idAlbum FROM album WHERE strAlbum != '' ORDER BY idAlbum DESC LIMIT %u) AS recentalbums "
"JOIN albumview ON albumview.idAlbum = recentalbums.idAlbum "
"LEFT JOIN albumartistview ON albumview.idAlbum = albumartistview.idAlbum "
"ORDER BY albumview.idAlbum desc, albumartistview.iOrder ",
limit ? limit : g_advancedSettings.m_iMusicLibraryRecentlyAddedItems);
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
int albumArtistOffset = album_enumCount;
int albumId = -1;
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS->get_sql_record();
if (albumId != record->at(album_idAlbum).get_asInt())
{ // New album
albumId = record->at(album_idAlbum).get_asInt();
albums.push_back(GetAlbumFromDataset(record));
}
// Get artist details
albums.back().artistCredits.push_back(GetArtistCreditFromDataset(record, albumArtistOffset));
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetRecentlyAddedAlbumSongs(const std::string& strBaseDir, CFileItemList& items, unsigned int limit)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
CMusicDbUrl baseUrl;
if (!strBaseDir.empty() && !baseUrl.FromString(strBaseDir))
return false;
// Get data from song and song_artist tables to fully populate songs
// Use idAlbum to determine the recently added albums
// (not "dateAdded" as this is file time stamp and nothing to do with when albums added to library)
std::string strSQL;
strSQL = PrepareSQL("SELECT songview.*, songartistview.* FROM "
"(SELECT idAlbum FROM album ORDER BY idAlbum DESC LIMIT %u) AS recentalbums "
"JOIN songview ON songview.idAlbum = recentalbums.idAlbum "
"JOIN songartistview ON songview.idSong = songartistview.idSong "
"ORDER BY songview.idAlbum desc, songview.itrack, songartistview.iOrder ",
limit ? limit : g_advancedSettings.m_iMusicLibraryRecentlyAddedItems);
CLog::Log(LOGDEBUG,"GetRecentlyAddedAlbumSongs() query: %s", strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// Needs a separate query to determine number of songs to set items size.
// Get songs from returned rows. Join means there is a row for every song artist
int songArtistOffset = song_enumCount;
int songId = -1;
VECARTISTCREDITS artistCredits;
while (!m_pDS->eof())
{
const dbiplus::sql_record* const record = m_pDS->get_sql_record();
if (songId != record->at(song_idSong).get_asInt())
{ //New song
if (songId > 0 && !artistCredits.empty())
{
//Store artist credits for previous song
GetFileItemFromArtistCredits(artistCredits, items[items.Size() - 1].get());
artistCredits.clear();
}
songId = record->at(song_idSong).get_asInt();
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(record, item.get(), baseUrl);
items.Add(item);
}
// Get song artist credits
artistCredits.push_back(GetArtistCreditFromDataset(record, songArtistOffset));
m_pDS->next();
}
if (!artistCredits.empty())
{
//Store artist credits for final song
GetFileItemFromArtistCredits(artistCredits, items[items.Size() - 1].get());
artistCredits.clear();
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
void CMusicDatabase::IncrementPlayCount(const CFileItem& item)
{
try
{
if (NULL == m_pDB.get()) return;
if (NULL == m_pDS.get()) return;
int idSong = GetSongIDFromPath(item.GetPath());
std::string sql=PrepareSQL("UPDATE song SET iTimesPlayed=iTimesPlayed+1, lastplayed=CURRENT_TIMESTAMP where idSong=%i", idSong);
m_pDS->exec(sql);
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, item.GetPath().c_str());
}
}
bool CMusicDatabase::GetSongsByPath(const std::string& strPath1, MAPSONGS& songs, bool bAppendToMap)
{
std::string strPath(strPath1);
try
{
if (!URIUtils::HasSlashAtEnd(strPath))
URIUtils::AddSlashAtEnd(strPath);
if (!bAppendToMap)
songs.clear();
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL=PrepareSQL("select * from songview where strPath='%s'", strPath.c_str() );
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return false;
}
while (!m_pDS->eof())
{
CSong song = GetSongFromDataset();
songs.insert(std::make_pair(song.strFileName, song));
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, strPath.c_str());
}
return false;
}
void CMusicDatabase::EmptyCache()
{
m_artistCache.erase(m_artistCache.begin(), m_artistCache.end());
m_genreCache.erase(m_genreCache.begin(), m_genreCache.end());
m_pathCache.erase(m_pathCache.begin(), m_pathCache.end());
m_albumCache.erase(m_albumCache.begin(), m_albumCache.end());
m_thumbCache.erase(m_thumbCache.begin(), m_thumbCache.end());
}
bool CMusicDatabase::Search(const std::string& search, CFileItemList &items)
{
unsigned int time = XbmcThreads::SystemClockMillis();
// first grab all the artists that match
SearchArtists(search, items);
CLog::Log(LOGDEBUG, "%s Artist search in %i ms",
__FUNCTION__, XbmcThreads::SystemClockMillis() - time); time = XbmcThreads::SystemClockMillis();
// then albums that match
SearchAlbums(search, items);
CLog::Log(LOGDEBUG, "%s Album search in %i ms",
__FUNCTION__, XbmcThreads::SystemClockMillis() - time); time = XbmcThreads::SystemClockMillis();
// and finally songs
SearchSongs(search, items);
CLog::Log(LOGDEBUG, "%s Songs search in %i ms",
__FUNCTION__, XbmcThreads::SystemClockMillis() - time); time = XbmcThreads::SystemClockMillis();
return true;
}
bool CMusicDatabase::SearchSongs(const std::string& search, CFileItemList &items)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
CMusicDbUrl baseUrl;
if (!baseUrl.FromString("musicdb://songs/"))
return false;
std::string strSQL;
if (search.size() >= MIN_FULL_SEARCH_LENGTH)
strSQL=PrepareSQL("select * from songview where strTitle like '%s%%' or strTitle like '%% %s%%' limit 1000", search.c_str(), search.c_str());
else
strSQL=PrepareSQL("select * from songview where strTitle like '%s%%' limit 1000", search.c_str());
if (!m_pDS->query(strSQL)) return false;
if (m_pDS->num_rows() == 0) return false;
std::string songLabel = g_localizeStrings.Get(179); // Song
while (!m_pDS->eof())
{
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(item.get(), baseUrl);
items.Add(item);
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::SearchAlbums(const std::string& search, CFileItemList &albums)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL;
if (search.size() >= MIN_FULL_SEARCH_LENGTH)
strSQL=PrepareSQL("select * from albumview where strAlbum like '%s%%' or strAlbum like '%% %s%%'", search.c_str(), search.c_str());
else
strSQL=PrepareSQL("select * from albumview where strAlbum like '%s%%'", search.c_str());
if (!m_pDS->query(strSQL)) return false;
std::string albumLabel(g_localizeStrings.Get(558)); // Album
while (!m_pDS->eof())
{
CAlbum album = GetAlbumFromDataset(m_pDS.get());
std::string path = StringUtils::Format("musicdb://albums/%ld/", album.idAlbum);
CFileItemPtr pItem(new CFileItem(path, album));
std::string label = StringUtils::Format("[%s] %s", albumLabel.c_str(), album.strAlbum.c_str());
pItem->SetLabel(label);
label = StringUtils::Format("B %s", album.strAlbum.c_str()); // sort label is stored in the title tag
pItem->GetMusicInfoTag()->SetTitle(label);
albums.Add(pItem);
m_pDS->next();
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::CleanupSongsByIds(const std::string &strSongIds)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// ok, now find all idSong's
std::string strSQL=PrepareSQL("select * from song join path on song.idPath = path.idPath where song.idSong in %s", strSongIds.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
std::vector<std::string> songsToDelete;
while (!m_pDS->eof())
{ // get the full song path
std::string strFileName = URIUtils::AddFileToFolder(m_pDS->fv("path.strPath").get_asString(), m_pDS->fv("song.strFileName").get_asString());
// Special case for streams inside an ogg file. (oggstream)
// The last dir in the path is the ogg file that
// contains the stream, so test if its there
if (URIUtils::HasExtension(strFileName, ".oggstream|.nsfstream"))
{
strFileName = URIUtils::GetDirectory(strFileName);
// we are dropping back to a file, so remove the slash at end
URIUtils::RemoveSlashAtEnd(strFileName);
}
if (!CFile::Exists(strFileName, false))
{ // file no longer exists, so add to deletion list
songsToDelete.push_back(m_pDS->fv("song.idSong").get_asString());
}
m_pDS->next();
}
m_pDS->close();
if (!songsToDelete.empty())
{
std::string strSongsToDelete = "(" + StringUtils::Join(songsToDelete, ",") + ")";
// ok, now delete these songs + all references to them from the linked tables
strSQL = "delete from song where idSong in " + strSongsToDelete;
m_pDS->exec(strSQL);
m_pDS->close();
}
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "Exception in CMusicDatabase::CleanupSongsFromPaths()");
}
return false;
}
bool CMusicDatabase::CleanupSongs()
{
try
{
// run through all songs and get all unique path ids
int iLIMIT = 1000;
for (int i=0;;i+=iLIMIT)
{
std::string strSQL=PrepareSQL("select song.idSong from song order by song.idSong limit %i offset %i",iLIMIT,i);
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
// keep going until no rows are left!
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
std::vector<std::string> songIds;
while (!m_pDS->eof())
{
songIds.push_back(m_pDS->fv("song.idSong").get_asString());
m_pDS->next();
}
m_pDS->close();
std::string strSongIds = "(" + StringUtils::Join(songIds, ",") + ")";
CLog::Log(LOGDEBUG,"Checking songs from song ID list: %s",strSongIds.c_str());
if (!CleanupSongsByIds(strSongIds)) return false;
}
return true;
}
catch(...)
{
CLog::Log(LOGERROR, "Exception in CMusicDatabase::CleanupSongs()");
}
return false;
}
bool CMusicDatabase::CleanupAlbums()
{
try
{
// This must be run AFTER songs have been cleaned up
// delete albums with no reference to songs
std::string strSQL = "select * from album where album.idAlbum not in (select idAlbum from song)";
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
std::vector<std::string> albumIds;
while (!m_pDS->eof())
{
albumIds.push_back(m_pDS->fv("album.idAlbum").get_asString());
m_pDS->next();
}
m_pDS->close();
std::string strAlbumIds = "(" + StringUtils::Join(albumIds, ",") + ")";
// ok, now we can delete them and the references in the linked tables
strSQL = "delete from album where idAlbum in " + strAlbumIds;
m_pDS->exec(strSQL);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "Exception in CMusicDatabase::CleanupAlbums()");
}
return false;
}
bool CMusicDatabase::CleanupPaths()
{
try
{
// needs to be done AFTER the songs and albums have been cleaned up.
// we can happily delete any path that has no reference to a song
// but we must keep all paths that have been scanned that may contain songs in subpaths
// first create a temporary table of song paths
m_pDS->exec("CREATE TEMPORARY TABLE songpaths (idPath integer, strPath varchar(512))\n");
m_pDS->exec("INSERT INTO songpaths select idPath,strPath from path where idPath in (select idPath from song)\n");
// grab all paths that aren't immediately connected with a song
std::string sql = "select * from path where idPath not in (select idPath from song)";
if (!m_pDS->query(sql)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// and construct a list to delete
std::vector<std::string> pathIds;
while (!m_pDS->eof())
{
// anything that isn't a parent path of a song path is to be deleted
std::string path = m_pDS->fv("strPath").get_asString();
std::string sql = PrepareSQL("select count(idPath) from songpaths where SUBSTR(strPath,1,%i)='%s'", StringUtils::utf8_strlen(path.c_str()), path.c_str());
if (m_pDS2->query(sql) && m_pDS2->num_rows() == 1 && m_pDS2->fv(0).get_asInt() == 0)
pathIds.push_back(m_pDS->fv("idPath").get_asString()); // nothing found, so delete
m_pDS2->close();
m_pDS->next();
}
m_pDS->close();
if (!pathIds.empty())
{
// do the deletion, and drop our temp table
std::string deleteSQL = "DELETE FROM path WHERE idPath IN (" + StringUtils::Join(pathIds, ",") + ")";
m_pDS->exec(deleteSQL);
}
m_pDS->exec("drop table songpaths");
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "Exception in CMusicDatabase::CleanupPaths() or was aborted");
}
return false;
}
bool CMusicDatabase::InsideScannedPath(const std::string& path)
{
std::string sql = PrepareSQL("select idPath from path where SUBSTR(strPath,1,%i)='%s' LIMIT 1", path.size(), path.c_str());
return !GetSingleValue(sql).empty();
}
bool CMusicDatabase::CleanupArtists()
{
try
{
// (nested queries by Bobbin007)
// must be executed AFTER the song, album and their artist link tables are cleaned.
// don't delete the "Various Artists" string
// Create temp table to avoid 1442 trigger hell on mysql
m_pDS->exec("CREATE TEMPORARY TABLE tmp_delartists (idArtist integer)");
m_pDS->exec("INSERT INTO tmp_delartists select idArtist from song_artist");
m_pDS->exec("INSERT INTO tmp_delartists select idArtist from album_artist");
m_pDS->exec("delete from artist where idArtist not in (select idArtist from tmp_delartists)");
m_pDS->exec("DROP TABLE tmp_delartists");
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "Exception in CMusicDatabase::CleanupArtists() or was aborted");
}
return false;
}
bool CMusicDatabase::CleanupGenres()
{
try
{
// Cleanup orphaned genres (ie those that don't belong to a song or an album entry)
// (nested queries by Bobbin007)
// Must be executed AFTER the song, song_genre, album and album_genre tables have been cleaned.
std::string strSQL = "delete from genre where idGenre not in (select idGenre from song_genre) and";
strSQL += " idGenre not in (select idGenre from album_genre)";
m_pDS->exec(strSQL);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "Exception in CMusicDatabase::CleanupGenres() or was aborted");
}
return false;
}
bool CMusicDatabase::CleanupOrphanedItems()
{
// paths aren't cleaned up here - they're cleaned up in RemoveSongsFromPath()
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
if (!CleanupAlbums()) return false;
if (!CleanupArtists()) return false;
if (!CleanupGenres()) return false;
return true;
}
int CMusicDatabase::Cleanup(bool bShowProgress /* = true */)
{
if (NULL == m_pDB.get()) return ERROR_DATABASE;
if (NULL == m_pDS.get()) return ERROR_DATABASE;
int ret = ERROR_OK;
CGUIDialogProgress* pDlgProgress = NULL;
unsigned int time = XbmcThreads::SystemClockMillis();
CLog::Log(LOGNOTICE, "%s: Starting musicdatabase cleanup ..", __FUNCTION__);
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnCleanStarted");
// first cleanup any songs with invalid paths
if (bShowProgress)
{
pDlgProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
if (pDlgProgress)
{
pDlgProgress->SetHeading(CVariant{700});
pDlgProgress->SetLine(0, CVariant{""});
pDlgProgress->SetLine(1, CVariant{318});
pDlgProgress->SetLine(2, CVariant{330});
pDlgProgress->SetPercentage(0);
pDlgProgress->Open();
pDlgProgress->ShowProgressBar(true);
}
}
if (!CleanupSongs())
{
ret = ERROR_REORG_SONGS;
goto error;
}
// then the albums that are not linked to a song or to album, or whose path is removed
if (pDlgProgress)
{
pDlgProgress->SetLine(1, CVariant{326});
pDlgProgress->SetPercentage(20);
pDlgProgress->Progress();
}
if (!CleanupAlbums())
{
ret = ERROR_REORG_ALBUM;
goto error;
}
// now the paths
if (pDlgProgress)
{
pDlgProgress->SetLine(1, CVariant{324});
pDlgProgress->SetPercentage(40);
pDlgProgress->Progress();
}
if (!CleanupPaths())
{
ret = ERROR_REORG_PATH;
goto error;
}
// and finally artists + genres
if (pDlgProgress)
{
pDlgProgress->SetLine(1, CVariant{320});
pDlgProgress->SetPercentage(60);
pDlgProgress->Progress();
}
if (!CleanupArtists())
{
ret = ERROR_REORG_ARTIST;
goto error;
}
if (pDlgProgress)
{
pDlgProgress->SetLine(1, CVariant{322});
pDlgProgress->SetPercentage(80);
pDlgProgress->Progress();
}
if (!CleanupGenres())
{
ret = ERROR_REORG_GENRE;
goto error;
}
// commit transaction
if (pDlgProgress)
{
pDlgProgress->SetLine(1, CVariant{328});
pDlgProgress->SetPercentage(90);
pDlgProgress->Progress();
}
if (!CommitTransaction())
{
ret = ERROR_WRITING_CHANGES;
goto error;
}
// and compress the database
if (pDlgProgress)
{
pDlgProgress->SetLine(1, CVariant{331});
pDlgProgress->SetPercentage(100);
pDlgProgress->Progress();
pDlgProgress->Close();
}
time = XbmcThreads::SystemClockMillis() - time;
CLog::Log(LOGNOTICE, "%s: Cleaning musicdatabase done. Operation took %s", __FUNCTION__, StringUtils::SecondsToTimeString(time / 1000).c_str());
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnCleanFinished");
if (!Compress(false))
{
return ERROR_COMPRESSING;
}
return ERROR_OK;
error:
RollbackTransaction();
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnCleanFinished");
return ret;
}
bool CMusicDatabase::LookupCDDBInfo(bool bRequery/*=false*/)
{
#ifdef HAS_DVD_DRIVE
if (!CSettings::GetInstance().GetBool(CSettings::SETTING_AUDIOCDS_USECDDB))
return false;
// check network connectivity
if (!g_application.getNetwork().IsAvailable())
return false;
// Get information for the inserted disc
CCdInfo* pCdInfo = g_mediaManager.GetCdInfo();
if (pCdInfo == NULL)
return false;
// If the disc has no tracks, we are finished here.
int nTracks = pCdInfo->GetTrackCount();
if (nTracks <= 0)
return false;
// Delete old info if any
if (bRequery)
{
std::string strFile = StringUtils::Format("%x.cddb", pCdInfo->GetCddbDiscId());
CFile::Delete(URIUtils::AddFileToFolder(CProfilesManager::GetInstance().GetCDDBFolder(), strFile));
}
// Prepare cddb
Xcddb cddb;
cddb.setCacheDir(CProfilesManager::GetInstance().GetCDDBFolder());
// Do we have to look for cddb information
if (pCdInfo->HasCDDBInfo() && !cddb.isCDCached(pCdInfo))
{
CGUIDialogProgress* pDialogProgress = (CGUIDialogProgress*)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
CGUIDialogSelect *pDlgSelect = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT);
if (!pDialogProgress) return false;
if (!pDlgSelect) return false;
// Show progress dialog if we have to connect to freedb.org
pDialogProgress->SetHeading(CVariant{255}); //CDDB
pDialogProgress->SetLine(0, CVariant{""}); // Querying freedb for CDDB info
pDialogProgress->SetLine(1, CVariant{256});
pDialogProgress->SetLine(2, CVariant{""});
pDialogProgress->ShowProgressBar(false);
pDialogProgress->Open();
// get cddb information
if (!cddb.queryCDinfo(pCdInfo))
{
pDialogProgress->Close();
int lasterror = cddb.getLastError();
// Have we found more then on match in cddb for this disc,...
if (lasterror == E_WAIT_FOR_INPUT)
{
// ...yes, show the matches found in a select dialog
// and let the user choose an entry.
pDlgSelect->Reset();
pDlgSelect->SetHeading(CVariant{255});
int i = 1;
while (1)
{
std::string strTitle = cddb.getInexactTitle(i);
if (strTitle == "") break;
std::string strArtist = cddb.getInexactArtist(i);
if (!strArtist.empty())
strTitle += " - " + strArtist;
pDlgSelect->Add(strTitle);
i++;
}
pDlgSelect->Open();
// Has the user selected a match...
int iSelectedCD = pDlgSelect->GetSelectedItem();
if (iSelectedCD >= 0)
{
// ...query cddb for the inexact match
if (!cddb.queryCDinfo(pCdInfo, 1 + iSelectedCD))
pCdInfo->SetNoCDDBInfo();
}
else
pCdInfo->SetNoCDDBInfo();
}
else if (lasterror == E_NO_MATCH_FOUND)
{
pCdInfo->SetNoCDDBInfo();
}
else
{
pCdInfo->SetNoCDDBInfo();
// ..no, an error occured, display it to the user
std::string strErrorText = StringUtils::Format("[%d] %s", cddb.getLastError(), cddb.getLastErrorText());
CGUIDialogOK::ShowAndGetInput(CVariant{255}, CVariant{257}, CVariant{std::move(strErrorText)}, CVariant{0});
}
} // if ( !cddb.queryCDinfo( pCdInfo ) )
else
pDialogProgress->Close();
}
// Filling the file items with cddb info happens in CMusicInfoTagLoaderCDDA
return pCdInfo->HasCDDBInfo();
#else
return false;
#endif
}
void CMusicDatabase::DeleteCDDBInfo()
{
#ifdef HAS_DVD_DRIVE
CFileItemList items;
if (!CDirectory::GetDirectory(CProfilesManager::GetInstance().GetCDDBFolder(), items, ".cddb", DIR_FLAG_NO_FILE_DIRS))
{
CGUIDialogOK::ShowAndGetInput(CVariant{313}, CVariant{426});
return ;
}
// Show a selectdialog that the user can select the album to delete
CGUIDialogSelect *pDlg = (CGUIDialogSelect*)g_windowManager.GetWindow(WINDOW_DIALOG_SELECT);
if (pDlg)
{
pDlg->SetHeading(CVariant{g_localizeStrings.Get(181)});
pDlg->Reset();
std::map<ULONG, std::string> mapCDDBIds;
for (int i = 0; i < items.Size(); ++i)
{
if (items[i]->m_bIsFolder)
continue;
std::string strFile = URIUtils::GetFileName(items[i]->GetPath());
strFile.erase(strFile.size() - 5, 5);
ULONG lDiscId = strtoul(strFile.c_str(), NULL, 16);
Xcddb cddb;
cddb.setCacheDir(CProfilesManager::GetInstance().GetCDDBFolder());
if (!cddb.queryCache(lDiscId))
continue;
std::string strDiskTitle, strDiskArtist;
cddb.getDiskTitle(strDiskTitle);
cddb.getDiskArtist(strDiskArtist);
std::string str;
if (strDiskArtist.empty())
str = strDiskTitle;
else
str = strDiskTitle + " - " + strDiskArtist;
pDlg->Add(str);
mapCDDBIds.insert(std::pair<ULONG, std::string>(lDiscId, str));
}
pDlg->Sort();
pDlg->Open();
// and wait till user selects one
int iSelectedAlbum = pDlg->GetSelectedItem();
if (iSelectedAlbum < 0)
{
mapCDDBIds.erase(mapCDDBIds.begin(), mapCDDBIds.end());
return ;
}
std::string strSelectedAlbum = pDlg->GetSelectedFileItem()->GetLabel();
std::map<ULONG, std::string>::iterator it;
for (it = mapCDDBIds.begin();it != mapCDDBIds.end();++it)
{
if (it->second == strSelectedAlbum)
{
std::string strFile = StringUtils::Format("%x.cddb", (unsigned int) it->first);
CFile::Delete(URIUtils::AddFileToFolder(CProfilesManager::GetInstance().GetCDDBFolder(), strFile));
break;
}
}
mapCDDBIds.erase(mapCDDBIds.begin(), mapCDDBIds.end());
}
#endif
}
void CMusicDatabase::Clean()
{
// If we are scanning for music info in the background,
// other writing access to the database is prohibited.
if (g_application.IsMusicScanning())
{
CGUIDialogOK::ShowAndGetInput(CVariant{189}, CVariant{14057});
return;
}
if (HELPERS::ShowYesNoDialogText(CVariant{313}, CVariant{333}) == DialogResponse::YES)
{
CMusicDatabase musicdatabase;
if (musicdatabase.Open())
{
int iReturnString = musicdatabase.Cleanup();
musicdatabase.Close();
if (iReturnString != ERROR_OK)
{
CGUIDialogOK::ShowAndGetInput(CVariant{313}, CVariant{iReturnString});
}
}
}
}
bool CMusicDatabase::GetGenresNav(const std::string& strBaseDir, CFileItemList& items, const Filter &filter /* = Filter() */, bool countOnly /* = false */)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// get primary genres for songs - could be simplified to just SELECT * FROM genre?
std::string strSQL = "SELECT %s FROM genre ";
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting;
if (!musicUrl.FromString(strBaseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// if there are extra WHERE conditions we might need access
// to songview or albumview for these conditions
if (!extFilter.where.empty())
{
if (extFilter.where.find("artistview") != std::string::npos)
extFilter.AppendJoin("JOIN song_genre ON song_genre.idGenre = genre.idGenre JOIN songview ON songview.idSong = song_genre.idSong "
"JOIN song_artist ON song_artist.idSong = songview.idSong JOIN artistview ON artistview.idArtist = song_artist.idArtist");
else if (extFilter.where.find("songview") != std::string::npos)
extFilter.AppendJoin("JOIN song_genre ON song_genre.idGenre = genre.idGenre JOIN songview ON songview.idSong = song_genre.idSong");
else if (extFilter.where.find("albumview") != std::string::npos)
extFilter.AppendJoin("JOIN album_genre ON album_genre.idGenre = genre.idGenre JOIN albumview ON albumview.idAlbum = album_genre.idAlbum");
extFilter.AppendGroup("genre.idGenre");
}
extFilter.AppendWhere("genre.strGenre != ''");
if (countOnly)
{
extFilter.fields = "COUNT(DISTINCT genre.idGenre)";
extFilter.group.clear();
extFilter.order.clear();
}
std::string strSQLExtra;
if (!BuildSQL(strSQLExtra, extFilter, strSQLExtra))
return false;
strSQL = PrepareSQL(strSQL.c_str(), !extFilter.fields.empty() && extFilter.fields.compare("*") != 0 ? extFilter.fields.c_str() : "genre.*") + strSQLExtra;
// run query
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL.c_str()))
return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
if (countOnly)
{
CFileItemPtr pItem(new CFileItem());
pItem->SetProperty("total", iRowsFound == 1 ? m_pDS->fv(0).get_asInt() : iRowsFound);
items.Add(pItem);
m_pDS->close();
return true;
}
// get data from returned rows
while (!m_pDS->eof())
{
CFileItemPtr pItem(new CFileItem(m_pDS->fv("genre.strGenre").get_asString()));
pItem->GetMusicInfoTag()->SetGenre(m_pDS->fv("genre.strGenre").get_asString());
pItem->GetMusicInfoTag()->SetDatabaseId(m_pDS->fv("genre.idGenre").get_asInt(), "genre");
CMusicDbUrl itemUrl = musicUrl;
std::string strDir = StringUtils::Format("%i/", m_pDS->fv("genre.idGenre").get_asInt());
itemUrl.AppendPath(strDir);
pItem->SetPath(itemUrl.ToString());
pItem->m_bIsFolder = true;
items.Add(pItem);
m_pDS->next();
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetYearsNav(const std::string& strBaseDir, CFileItemList& items, const Filter &filter /* = Filter() */)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting;
if (!musicUrl.FromString(strBaseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// get years from album list
std::string strSQL = "SELECT DISTINCT albumview.iYear FROM albumview ";
extFilter.AppendWhere("albumview.iYear <> 0");
if (!BuildSQL(strSQL, extFilter, strSQL))
return false;
// run query
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL))
return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// get data from returned rows
while (!m_pDS->eof())
{
CFileItemPtr pItem(new CFileItem(m_pDS->fv(0).get_asString()));
SYSTEMTIME stTime;
stTime.wYear = (WORD)m_pDS->fv(0).get_asInt();
pItem->GetMusicInfoTag()->SetReleaseDate(stTime);
CMusicDbUrl itemUrl = musicUrl;
std::string strDir = StringUtils::Format("%i/", m_pDS->fv(0).get_asInt());
itemUrl.AppendPath(strDir);
pItem->SetPath(itemUrl.ToString());
pItem->m_bIsFolder = true;
items.Add(pItem);
m_pDS->next();
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetAlbumsByYear(const std::string& strBaseDir, CFileItemList& items, int year)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
musicUrl.AddOption("year", year);
musicUrl.AddOption("show_singles", true); // allow singles to be listed
Filter filter;
return GetAlbumsByWhere(musicUrl.ToString(), filter, items);
}
bool CMusicDatabase::GetCommonNav(const std::string &strBaseDir, const std::string &table, const std::string &labelField, CFileItemList &items, const Filter &filter /* = Filter() */, bool countOnly /* = false */)
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
if (table.empty() || labelField.empty())
return false;
try
{
Filter extFilter = filter;
std::string strSQL = "SELECT %s FROM " + table + " ";
extFilter.AppendGroup(labelField);
extFilter.AppendWhere(labelField + " != ''");
if (countOnly)
{
extFilter.fields = "COUNT(DISTINCT " + labelField + ")";
extFilter.group.clear();
extFilter.order.clear();
}
CMusicDbUrl musicUrl;
if (!BuildSQL(strBaseDir, strSQL, extFilter, strSQL, musicUrl))
return false;
strSQL = PrepareSQL(strSQL, !extFilter.fields.empty() ? extFilter.fields.c_str() : labelField.c_str());
// run query
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL))
return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound <= 0)
{
m_pDS->close();
return false;
}
if (countOnly)
{
CFileItemPtr pItem(new CFileItem());
pItem->SetProperty("total", iRowsFound == 1 ? m_pDS->fv(0).get_asInt() : iRowsFound);
items.Add(pItem);
m_pDS->close();
return true;
}
// get data from returned rows
while (!m_pDS->eof())
{
std::string labelValue = m_pDS->fv(labelField.c_str()).get_asString();
CFileItemPtr pItem(new CFileItem(labelValue));
CMusicDbUrl itemUrl = musicUrl;
std::string strDir = StringUtils::Format("%s/", labelValue.c_str());
itemUrl.AppendPath(strDir);
pItem->SetPath(itemUrl.ToString());
pItem->m_bIsFolder = true;
items.Add(pItem);
m_pDS->next();
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetAlbumTypesNav(const std::string &strBaseDir, CFileItemList &items, const Filter &filter /* = Filter() */, bool countOnly /* = false */)
{
return GetCommonNav(strBaseDir, "albumview", "albumview.strType", items, filter, countOnly);
}
bool CMusicDatabase::GetMusicLabelsNav(const std::string &strBaseDir, CFileItemList &items, const Filter &filter /* = Filter() */, bool countOnly /* = false */)
{
return GetCommonNav(strBaseDir, "albumview", "albumview.strLabel", items, filter, countOnly);
}
bool CMusicDatabase::GetArtistsNav(const std::string& strBaseDir, CFileItemList& items, bool albumArtistsOnly /* = false */, int idGenre /* = -1 */, int idAlbum /* = -1 */, int idSong /* = -1 */, const Filter &filter /* = Filter() */, const SortDescription &sortDescription /* = SortDescription() */, bool countOnly /* = false */)
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
try
{
unsigned int time = XbmcThreads::SystemClockMillis();
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
if (idGenre > 0)
musicUrl.AddOption("genreid", idGenre);
else if (idAlbum > 0)
musicUrl.AddOption("albumid", idAlbum);
else if (idSong > 0)
musicUrl.AddOption("songid", idSong);
// Override albumArtistsOnly parameter (usually externally set to SETTING_MUSICLIBRARY_SHOWCOMPILATIONARTISTS)
// when local option already present in muscic URL thus allowing it to be an option in custom nodes
if (!musicUrl.HasOption("albumartistsonly"))
musicUrl.AddOption("albumartistsonly", albumArtistsOnly);
bool result = GetArtistsByWhere(musicUrl.ToString(), filter, items, sortDescription, countOnly);
CLog::Log(LOGDEBUG,"Time to retrieve artists from dataset = %i", XbmcThreads::SystemClockMillis() - time);
return result;
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetArtistsByWhere(const std::string& strBaseDir, const Filter &filter, CFileItemList& items, const SortDescription &sortDescription /* = SortDescription() */, bool countOnly /* = false */)
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
try
{
int total = -1;
std::string strSQL = "SELECT %s FROM artistview ";
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting = sortDescription;
if (!musicUrl.FromString(strBaseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// if there are extra WHERE conditions we might need access
// to songview or albumview for these conditions
if (!extFilter.where.empty())
{
bool extended = false;
if (extFilter.where.find("songview") != std::string::npos)
{
extended = true;
extFilter.AppendJoin("JOIN song_artist ON song_artist.idArtist = artistview.idArtist JOIN songview ON songview.idSong = song_artist.idSong");
}
else if (extFilter.where.find("albumview") != std::string::npos)
{
extended = true;
extFilter.AppendJoin("JOIN album_artist ON album_artist.idArtist = artistview.idArtist JOIN albumview ON albumview.idAlbum = album_artist.idAlbum");
}
if (extended)
extFilter.AppendGroup("artistview.idArtist");
}
if (countOnly)
{
extFilter.fields = "COUNT(DISTINCT artistview.idArtist)";
extFilter.group.clear();
extFilter.order.clear();
}
std::string strSQLExtra;
if (!BuildSQL(strSQLExtra, extFilter, strSQLExtra))
return false;
// Apply the limiting directly here if there's no special sorting but limiting
if (extFilter.limit.empty() &&
sortDescription.sortBy == SortByNone &&
(sortDescription.limitStart > 0 || sortDescription.limitEnd > 0))
{
total = (int)strtol(GetSingleValue(PrepareSQL(strSQL, "COUNT(1)") + strSQLExtra, m_pDS).c_str(), NULL, 10);
strSQLExtra += DatabaseUtils::BuildLimitClause(sortDescription.limitEnd, sortDescription.limitStart);
}
strSQL = PrepareSQL(strSQL.c_str(), !extFilter.fields.empty() && extFilter.fields.compare("*") != 0 ? extFilter.fields.c_str() : "artistview.*") + strSQLExtra;
// run query
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
if (countOnly)
{
CFileItemPtr pItem(new CFileItem());
pItem->SetProperty("total", iRowsFound == 1 ? m_pDS->fv(0).get_asInt() : iRowsFound);
items.Add(pItem);
m_pDS->close();
return true;
}
// store the total value of items as a property
if (total < iRowsFound)
total = iRowsFound;
items.SetProperty("total", total);
DatabaseResults results;
results.reserve(iRowsFound);
if (!SortUtils::SortFromDataset(sortDescription, MediaTypeArtist, m_pDS, results))
return false;
// get data from returned rows
items.Reserve(results.size());
const dbiplus::query_data &data = m_pDS->get_result_set().records;
for (DatabaseResults::const_iterator it = results.begin(); it != results.end(); ++it)
{
unsigned int targetRow = (unsigned int)it->at(FieldRow).asInteger();
const dbiplus::sql_record* const record = data.at(targetRow);
try
{
CArtist artist = GetArtistFromDataset(record, false);
CFileItemPtr pItem(new CFileItem(artist));
CMusicDbUrl itemUrl = musicUrl;
std::string path = StringUtils::Format("%ld/", artist.idArtist);
itemUrl.AppendPath(path);
pItem->SetPath(itemUrl.ToString());
pItem->GetMusicInfoTag()->SetDatabaseId(artist.idArtist, MediaTypeArtist);
pItem->SetIconImage("DefaultArtist.png");
SetPropertiesFromArtist(*pItem, artist);
items.Add(pItem);
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s - out of memory getting listing (got %i)", __FUNCTION__, items.Size());
}
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetAlbumFromSong(int idSong, CAlbum &album)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL = PrepareSQL("select albumview.* from song join albumview on song.idAlbum = albumview.idAlbum where song.idSong='%i'", idSong);
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound != 1)
{
m_pDS->close();
return false;
}
album = GetAlbumFromDataset(m_pDS.get());
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::GetAlbumsNav(const std::string& strBaseDir, CFileItemList& items, int idGenre /* = -1 */, int idArtist /* = -1 */, const Filter &filter /* = Filter() */, const SortDescription &sortDescription /* = SortDescription() */, bool countOnly /* = false */)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
// where clause
if (idGenre > 0)
musicUrl.AddOption("genreid", idGenre);
if (idArtist > 0)
musicUrl.AddOption("artistid", idArtist);
return GetAlbumsByWhere(musicUrl.ToString(), filter, items, sortDescription, countOnly);
}
bool CMusicDatabase::GetAlbumsByWhere(const std::string &baseDir, const Filter &filter, CFileItemList &items, const SortDescription &sortDescription /* = SortDescription() */, bool countOnly /* = false */)
{
if (m_pDB.get() == NULL || m_pDS.get() == NULL)
return false;
try
{
int total = -1;
std::string strSQL = "SELECT %s FROM albumview ";
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting = sortDescription;
if (!musicUrl.FromString(baseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// if there are extra WHERE conditions we might need access
// to songview for these conditions
if (extFilter.where.find("songview") != std::string::npos)
{
extFilter.AppendJoin("JOIN songview ON songview.idAlbum = albumview.idAlbum");
extFilter.AppendGroup("albumview.idAlbum");
}
std::string strSQLExtra;
if (!BuildSQL(strSQLExtra, extFilter, strSQLExtra))
return false;
// Apply the limiting directly here if there's no special sorting but limiting
if (extFilter.limit.empty() &&
sortDescription.sortBy == SortByNone &&
(sortDescription.limitStart > 0 || sortDescription.limitEnd > 0))
{
total = (int)strtol(GetSingleValue(PrepareSQL(strSQL, "COUNT(1)") + strSQLExtra, m_pDS).c_str(), NULL, 10);
strSQLExtra += DatabaseUtils::BuildLimitClause(sortDescription.limitEnd, sortDescription.limitStart);
}
strSQL = PrepareSQL(strSQL, !filter.fields.empty() && filter.fields.compare("*") != 0 ? filter.fields.c_str() : "albumview.*") + strSQLExtra;
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
// run query
unsigned int time = XbmcThreads::SystemClockMillis();
if (!m_pDS->query(strSQL))
return false;
CLog::Log(LOGDEBUG, "%s - query took %i ms",
__FUNCTION__, XbmcThreads::SystemClockMillis() - time); time = XbmcThreads::SystemClockMillis();
int iRowsFound = m_pDS->num_rows();
if (iRowsFound <= 0)
{
m_pDS->close();
return true;
}
// store the total value of items as a property
if (total < iRowsFound)
total = iRowsFound;
items.SetProperty("total", total);
if (countOnly)
{
CFileItemPtr pItem(new CFileItem());
pItem->SetProperty("total", total);
items.Add(pItem);
m_pDS->close();
return true;
}
DatabaseResults results;
results.reserve(iRowsFound);
if (!SortUtils::SortFromDataset(sortDescription, MediaTypeAlbum, m_pDS, results))
return false;
// get data from returned rows
items.Reserve(results.size());
const dbiplus::query_data &data = m_pDS->get_result_set().records;
for (DatabaseResults::const_iterator it = results.begin(); it != results.end(); ++it)
{
unsigned int targetRow = (unsigned int)it->at(FieldRow).asInteger();
const dbiplus::sql_record* const record = data.at(targetRow);
try
{
CMusicDbUrl itemUrl = musicUrl;
std::string path = StringUtils::Format("%i/", record->at(album_idAlbum).get_asInt());
itemUrl.AppendPath(path);
CFileItemPtr pItem(new CFileItem(itemUrl.ToString(), GetAlbumFromDataset(record)));
pItem->SetIconImage("DefaultAlbumCover.png");
items.Add(pItem);
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s - out of memory getting listing (got %i)", __FUNCTION__, items.Size());
}
}
// cleanup
m_pDS->close();
return true;
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s (%s) failed", __FUNCTION__, filter.where.c_str());
}
return false;
}
bool CMusicDatabase::GetAlbumsByWhere(const std::string &baseDir, const Filter &filter, VECALBUMS& albums, int& total, const SortDescription &sortDescription /* = SortDescription() */, bool countOnly /* = false */)
{
albums.erase(albums.begin(), albums.end());
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
try
{
total = -1;
// Get data from album and album_artist tables to fully populate albums
std::string strSQL = "SELECT %s FROM albumview LEFT JOIN albumartistview on albumartistview.idalbum = albumview.idalbum ";
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting = sortDescription;
if (!musicUrl.FromString(baseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// if there are extra WHERE conditions we might need access
// to songview for these conditions
if (extFilter.where.find("songview") != std::string::npos)
{
extFilter.AppendJoin("JOIN songview ON songview.idAlbum = albumview.idAlbum");
extFilter.AppendGroup("albumview.idAlbum");
}
std::string strSQLExtra;
if (!BuildSQL(strSQLExtra, extFilter, strSQLExtra))
return false;
// Count and return number of albums that satisfy selection criteria
total = (int)strtol(GetSingleValue("SELECT COUNT(1) FROM albumview " + strSQLExtra, m_pDS).c_str(), NULL, 10);
if (countOnly)
return true;
// Apply the limiting directly here if there's no special sorting but limiting
if (extFilter.limit.empty() &&
sortDescription.sortBy == SortByNone &&
(sortDescription.limitStart > 0 || sortDescription.limitEnd > 0))
{
strSQLExtra += DatabaseUtils::BuildLimitClause(sortDescription.limitEnd, sortDescription.limitStart);
albums.reserve(sortDescription.limitEnd - sortDescription.limitStart);
}
else
albums.reserve(total);
strSQL = PrepareSQL(strSQL, !filter.fields.empty() && filter.fields.compare("*") != 0 ? filter.fields.c_str() : "albumview.*, albumartistview.* ") + strSQLExtra;
CLog::Log(LOGDEBUG, "%s query: %s", __FUNCTION__, strSQL.c_str());
// run query
unsigned int time = XbmcThreads::SystemClockMillis();
if (!m_pDS->query(strSQL))
return false;
CLog::Log(LOGDEBUG, "%s - query took %i ms",
__FUNCTION__, XbmcThreads::SystemClockMillis() - time); time = XbmcThreads::SystemClockMillis();
int iRowsFound = m_pDS->num_rows();
if (iRowsFound <= 0)
{
m_pDS->close();
return true;
}
//Sort the results set - need to add sort by iOrder to maintain artist name order??
DatabaseResults results;
results.reserve(iRowsFound);
if (!SortUtils::SortFromDataset(sortDescription, MediaTypeAlbum, m_pDS, results))
return false;
// Get albums from returned rows. Join means there is a row for every album artist
int albumArtistOffset = album_enumCount;
int albumId = -1;
const dbiplus::query_data &data = m_pDS->get_result_set().records;
for (DatabaseResults::const_iterator it = results.begin(); it != results.end(); ++it)
{
unsigned int targetRow = (unsigned int)it->at(FieldRow).asInteger();
const dbiplus::sql_record* const record = data.at(targetRow);
if (albumId != record->at(album_idAlbum).get_asInt())
{ // New album
albumId = record->at(album_idAlbum).get_asInt();
albums.push_back(GetAlbumFromDataset(record));
}
// Get album artist credits
albums.back().artistCredits.push_back(GetArtistCreditFromDataset(record, albumArtistOffset));
}
m_pDS->close(); // cleanup recordset data
return true;
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s (%s) failed", __FUNCTION__, filter.where.c_str());
}
return false;
}
bool CMusicDatabase::GetSongsFullByWhere(const std::string &baseDir, const Filter &filter, CFileItemList &items, const SortDescription &sortDescription /* = SortDescription() */, bool artistData /* = false*/)
{
if (m_pDB.get() == NULL || m_pDS.get() == NULL)
return false;
try
{
unsigned int time = XbmcThreads::SystemClockMillis();
int total = -1;
std::string strSQL = "SELECT %s FROM songview ";
if (artistData) // Get data from song and song_artist tables to fully populate songs with artists
strSQL = "SELECT %s FROM songview JOIN songartistview on songartistview.idsong = songview.idsong ";
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting = sortDescription;
if (!musicUrl.FromString(baseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// if there are extra WHERE conditions we might need access
// to songview for these conditions
if (extFilter.where.find("albumview") != std::string::npos)
{
extFilter.AppendJoin("JOIN albumview ON albumview.idAlbum = songview.idAlbum");
extFilter.AppendGroup("songview.idSong");
}
std::string strSQLExtra;
if (!BuildSQL(strSQLExtra, extFilter, strSQLExtra))
return false;
// Count number of songs that satisfy selection criteria
total = (int)strtol(GetSingleValue("SELECT COUNT(1) FROM songview " + strSQLExtra, m_pDS).c_str(), NULL, 10);
// Apply the limiting directly here if there's no special sorting but limiting
if (extFilter.limit.empty() &&
sortDescription.sortBy == SortByNone &&
(sortDescription.limitStart > 0 || sortDescription.limitEnd > 0))
strSQLExtra += DatabaseUtils::BuildLimitClause(sortDescription.limitEnd, sortDescription.limitStart);
if (artistData)
strSQL = PrepareSQL(strSQL, !filter.fields.empty() && filter.fields.compare("*") != 0 ? filter.fields.c_str() : "songview.*, songartistview.* ") + strSQLExtra;
else
strSQL = PrepareSQL(strSQL, !filter.fields.empty() && filter.fields.compare("*") != 0 ? filter.fields.c_str() : "songview.* ") + strSQLExtra;
CLog::Log(LOGDEBUG, "%s query = %s", __FUNCTION__, strSQL.c_str());
// run query
if (!m_pDS->query(strSQL))
return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// Store the total number of songs as a property
items.SetProperty("total", total);
DatabaseResults results;
results.reserve(iRowsFound);
if (!SortUtils::SortFromDataset(sortDescription, MediaTypeSong, m_pDS, results))
return false;
// Get songs from returned rows. If join songartistview then there is a row for every album artist
items.Reserve(total);
int songArtistOffset = song_enumCount;
int songId = -1;
VECARTISTCREDITS artistCredits;
const dbiplus::query_data &data = m_pDS->get_result_set().records;
int count = 0;
for (DatabaseResults::const_iterator it = results.begin(); it != results.end(); ++it)
{
unsigned int targetRow = (unsigned int)it->at(FieldRow).asInteger();
const dbiplus::sql_record* const record = data.at(targetRow);
try
{
if (songId != record->at(song_idSong).get_asInt())
{ //New song
if (songId > 0 && !artistCredits.empty())
{
//Store artist credits for previous song
GetFileItemFromArtistCredits(artistCredits, items[items.Size()-1].get());
artistCredits.clear();
}
songId = record->at(song_idSong).get_asInt();
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(record, item.get(), musicUrl);
// HACK for sorting by database returned order
item->m_iprogramCount = ++count;
items.Add(item);
}
// Get song artist credits
if (artistData)
artistCredits.push_back(GetArtistCreditFromDataset(record, songArtistOffset));
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s: out of memory loading query: %s", __FUNCTION__, filter.where.c_str());
return (items.Size() > 0);
}
}
if (!artistCredits.empty())
{
//Store artist credits for final song
GetFileItemFromArtistCredits(artistCredits, items[items.Size() - 1].get());
artistCredits.clear();
}
// cleanup
m_pDS->close();
// Load some info from embedded cuesheet if present (now only ReplayGain)
CueInfoLoader cueLoader;
for (int i = 0; i < items.Size(); ++i)
cueLoader.Load(LoadCuesheet(items[i]->GetMusicInfoTag()->GetURL()), items[i]);
CLog::Log(LOGDEBUG, "%s(%s) - took %d ms", __FUNCTION__, filter.where.c_str(), XbmcThreads::SystemClockMillis() - time);
return true;
}
catch (...)
{
// cleanup
m_pDS->close();
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, filter.where.c_str());
}
return false;
}
bool CMusicDatabase::GetSongsByWhere(const std::string &baseDir, const Filter &filter, CFileItemList &items, const SortDescription &sortDescription /* = SortDescription() */)
{
if (m_pDB.get() == NULL || m_pDS.get() == NULL)
return false;
try
{
unsigned int time = XbmcThreads::SystemClockMillis();
int total = -1;
std::string strSQL = "SELECT %s FROM songview ";
Filter extFilter = filter;
CMusicDbUrl musicUrl;
SortDescription sorting = sortDescription;
if (!musicUrl.FromString(baseDir) || !GetFilter(musicUrl, extFilter, sorting))
return false;
// if there are extra WHERE conditions we might need access
// to songview for these conditions
if (extFilter.where.find("albumview") != std::string::npos)
{
extFilter.AppendJoin("JOIN albumview ON albumview.idAlbum = songview.idAlbum");
extFilter.AppendGroup("songview.idSong");
}
std::string strSQLExtra;
if (!BuildSQL(strSQLExtra, extFilter, strSQLExtra))
return false;
// Apply the limiting directly here if there's no special sorting but limiting
if (extFilter.limit.empty() &&
sortDescription.sortBy == SortByNone &&
(sortDescription.limitStart > 0 || sortDescription.limitEnd > 0))
{
total = (int)strtol(GetSingleValue(PrepareSQL(strSQL, "COUNT(1)") + strSQLExtra, m_pDS).c_str(), NULL, 10);
strSQLExtra += DatabaseUtils::BuildLimitClause(sortDescription.limitEnd, sortDescription.limitStart);
}
strSQL = PrepareSQL(strSQL, !filter.fields.empty() && filter.fields.compare("*") != 0 ? filter.fields.c_str() : "songview.*") + strSQLExtra;
CLog::Log(LOGDEBUG, "%s query = %s", __FUNCTION__, strSQL.c_str());
// run query
if (!m_pDS->query(strSQL))
return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
// store the total value of items as a property
if (total < iRowsFound)
total = iRowsFound;
items.SetProperty("total", total);
DatabaseResults results;
results.reserve(iRowsFound);
if (!SortUtils::SortFromDataset(sortDescription, MediaTypeSong, m_pDS, results))
return false;
// get data from returned rows
items.Reserve(results.size());
const dbiplus::query_data &data = m_pDS->get_result_set().records;
int count = 0;
for (DatabaseResults::const_iterator it = results.begin(); it != results.end(); ++it)
{
unsigned int targetRow = (unsigned int)it->at(FieldRow).asInteger();
const dbiplus::sql_record* const record = data.at(targetRow);
try
{
CFileItemPtr item(new CFileItem);
GetFileItemFromDataset(record, item.get(), musicUrl);
// HACK for sorting by database returned order
item->m_iprogramCount = ++count;
items.Add(item);
}
catch (...)
{
m_pDS->close();
CLog::Log(LOGERROR, "%s: out of memory loading query: %s", __FUNCTION__, filter.where.c_str());
return (items.Size() > 0);
}
}
// cleanup
m_pDS->close();
// Load some info from embedded cuesheet if present (now only ReplayGain)
CueInfoLoader cueLoader;
for (int i = 0; i < items.Size(); ++i)
cueLoader.Load(LoadCuesheet(items[i]->GetMusicInfoTag()->GetURL()), items[i]);
CLog::Log(LOGDEBUG, "%s(%s) - took %d ms", __FUNCTION__, filter.where.c_str(), XbmcThreads::SystemClockMillis() - time);
return true;
}
catch (...)
{
// cleanup
m_pDS->close();
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, filter.where.c_str());
}
return false;
}
bool CMusicDatabase::GetSongsByYear(const std::string& baseDir, CFileItemList& items, int year)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(baseDir))
return false;
musicUrl.AddOption("year", year);
Filter filter;
return GetSongsByWhere(baseDir, filter, items);
}
bool CMusicDatabase::GetSongsNav(const std::string& strBaseDir, CFileItemList& items, int idGenre, int idArtist, int idAlbum, const SortDescription &sortDescription /* = SortDescription() */)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
if (idAlbum > 0)
musicUrl.AddOption("albumid", idAlbum);
if (idGenre > 0)
musicUrl.AddOption("genreid", idGenre);
if (idArtist > 0)
musicUrl.AddOption("artistid", idArtist);
Filter filter;
return GetSongsByWhere(musicUrl.ToString(), filter, items, sortDescription);
}
void CMusicDatabase::UpdateTables(int version)
{
CLog::Log(LOGINFO, "%s - updating tables", __FUNCTION__);
if (version < 34)
{
m_pDS->exec("ALTER TABLE artist ADD strMusicBrainzArtistID text\n");
m_pDS->exec("ALTER TABLE album ADD strMusicBrainzAlbumID text\n");
m_pDS->exec("CREATE TABLE song_new ( idSong integer primary key, idAlbum integer, idPath integer, strArtists text, strGenres text, strTitle varchar(512), iTrack integer, iDuration integer, iYear integer, dwFileNameCRC text, strFileName text, strMusicBrainzTrackID text, iTimesPlayed integer, iStartOffset integer, iEndOffset integer, idThumb integer, lastplayed varchar(20) default NULL, rating char default '0', comment text)\n");
m_pDS->exec("INSERT INTO song_new ( idSong, idAlbum, idPath, strArtists, strTitle, iTrack, iDuration, iYear, dwFileNameCRC, strFileName, strMusicBrainzTrackID, iTimesPlayed, iStartOffset, iEndOffset, idThumb, lastplayed, rating, comment) SELECT idSong, idAlbum, idPath, strArtists, strTitle, iTrack, iDuration, iYear, dwFileNameCRC, strFileName, strMusicBrainzTrackID, iTimesPlayed, iStartOffset, iEndOffset, idThumb, lastplayed, rating, comment FROM song");
m_pDS->exec("DROP TABLE song");
m_pDS->exec("ALTER TABLE song_new RENAME TO song");
m_pDS->exec("UPDATE song SET strMusicBrainzTrackID = NULL");
}
if (version < 35)
{
m_pDS->exec("ALTER TABLE album_artist ADD strJoinPhrase text\n");
m_pDS->exec("ALTER TABLE song_artist ADD strJoinPhrase text\n");
CMediaSettings::GetInstance().SetMusicNeedsUpdate(35);
CSettings::GetInstance().Save();
}
if (version < 36)
{
// translate legacy musicdb:// paths
if (m_pDS->query("SELECT strPath FROM content"))
{
std::vector<std::string> contentPaths;
while (!m_pDS->eof())
{
contentPaths.push_back(m_pDS->fv(0).get_asString());
m_pDS->next();
}
m_pDS->close();
for (std::vector<std::string>::const_iterator it = contentPaths.begin(); it != contentPaths.end(); ++it)
{
std::string originalPath = *it;
std::string path = CLegacyPathTranslation::TranslateMusicDbPath(originalPath);
m_pDS->exec(PrepareSQL("UPDATE content SET strPath='%s' WHERE strPath='%s'", path.c_str(), originalPath.c_str()));
}
}
}
if (version < 39)
{
m_pDS->exec("CREATE TABLE album_new "
"(idAlbum integer primary key, "
" strAlbum varchar(256), strMusicBrainzAlbumID text, "
" strArtists text, strGenres text, "
" iYear integer, idThumb integer, "
" bCompilation integer not null default '0', "
" strMoods text, strStyles text, strThemes text, "
" strReview text, strImage text, strLabel text, "
" strType text, "
" iRating integer, "
" lastScraped varchar(20) default NULL, "
" dateAdded varchar (20) default NULL)");
m_pDS->exec("INSERT INTO album_new "
"(idAlbum, "
" strAlbum, strMusicBrainzAlbumID, "
" strArtists, strGenres, "
" iYear, idThumb, "
" bCompilation, "
" strMoods, strStyles, strThemes, "
" strReview, strImage, strLabel, "
" strType, "
" iRating) "
" SELECT "
" album.idAlbum, "
" strAlbum, strMusicBrainzAlbumID, "
" strArtists, strGenres, "
" album.iYear, idThumb, "
" bCompilation, "
" strMoods, strStyles, strThemes, "
" strReview, strImage, strLabel, "
" strType, iRating "
" FROM album LEFT JOIN albuminfo ON album.idAlbum = albuminfo.idAlbum");
m_pDS->exec("UPDATE albuminfosong SET idAlbumInfo = (SELECT idAlbum FROM albuminfo WHERE albuminfo.idAlbumInfo = albuminfosong.idAlbumInfo)");
m_pDS->exec(PrepareSQL("UPDATE album_new SET lastScraped='%s' WHERE idAlbum IN (SELECT idAlbum FROM albuminfo)", CDateTime::GetCurrentDateTime().GetAsDBDateTime().c_str()));
m_pDS->exec("DROP TABLE album");
m_pDS->exec("DROP TABLE albuminfo");
m_pDS->exec("ALTER TABLE album_new RENAME TO album");
}
if (version < 40)
{
m_pDS->exec("CREATE TABLE artist_new ( idArtist integer primary key, "
" strArtist varchar(256), strMusicBrainzArtistID text, "
" strBorn text, strFormed text, strGenres text, strMoods text, "
" strStyles text, strInstruments text, strBiography text, "
" strDied text, strDisbanded text, strYearsActive text, "
" strImage text, strFanart text, "
" lastScraped varchar(20) default NULL, "
" dateAdded varchar (20) default NULL)");
m_pDS->exec("INSERT INTO artist_new "
"(idArtist, strArtist, strMusicBrainzArtistID, "
" strBorn, strFormed, strGenres, strMoods, "
" strStyles , strInstruments , strBiography , "
" strDied, strDisbanded, strYearsActive, "
" strImage, strFanart) "
" SELECT "
" artist.idArtist, "
" strArtist, strMusicBrainzArtistID, "
" strBorn, strFormed, strGenres, strMoods, "
" strStyles, strInstruments, strBiography, "
" strDied, strDisbanded, strYearsActive, "
" strImage, strFanart "
" FROM artist "
" LEFT JOIN artistinfo ON artist.idArtist = artistinfo.idArtist");
m_pDS->exec(PrepareSQL("UPDATE artist_new SET lastScraped='%s' WHERE idArtist IN (SELECT idArtist FROM artistinfo)", CDateTime::GetCurrentDateTime().GetAsDBDateTime().c_str()));
m_pDS->exec("DROP TABLE artist");
m_pDS->exec("DROP TABLE artistinfo");
m_pDS->exec("ALTER TABLE artist_new RENAME TO artist");
}
if (version < 42)
{
m_pDS->exec("ALTER TABLE album_artist ADD strArtist text\n");
m_pDS->exec("ALTER TABLE song_artist ADD strArtist text\n");
// populate these
std::string sql = "select idArtist,strArtist from artist";
m_pDS->query(sql);
while (!m_pDS->eof())
{
m_pDS2->exec(PrepareSQL("UPDATE song_artist SET strArtist='%s' where idArtist=%i", m_pDS->fv(1).get_asString().c_str(), m_pDS->fv(0).get_asInt()));
m_pDS2->exec(PrepareSQL("UPDATE album_artist SET strArtist='%s' where idArtist=%i", m_pDS->fv(1).get_asString().c_str(), m_pDS->fv(0).get_asInt()));
m_pDS->next();
}
// drop the last separator if more than one
m_pDS->exec("UPDATE song_artist SET strJoinPhrase = '' WHERE 100*idSong+iOrder IN (SELECT id FROM (SELECT 100*idSong+max(iOrder) AS id FROM song_artist GROUP BY idSong) AS sub)");
m_pDS->exec("UPDATE album_artist SET strJoinPhrase = '' WHERE 100*idAlbum+iOrder IN (SELECT id FROM (SELECT 100*idAlbum+max(iOrder) AS id FROM album_artist GROUP BY idAlbum) AS sub)");
}
if (version < 48)
{ // null out columns that are no longer used
m_pDS->exec("UPDATE song SET dwFileNameCRC=NULL, idThumb=NULL");
m_pDS->exec("UPDATE album SET idThumb=NULL");
}
if (version < 49)
{
m_pDS->exec("CREATE TABLE cue (idPath integer, strFileName text, strCuesheet text)");
}
if (version < 50)
{
// add a new column strReleaseType for albums
m_pDS->exec("ALTER TABLE album ADD strReleaseType text\n");
// set strReleaseType based on album name
m_pDS->exec(PrepareSQL("UPDATE album SET strReleaseType = '%s' WHERE strAlbum IS NOT NULL AND strAlbum <> ''", CAlbum::ReleaseTypeToString(CAlbum::Album).c_str()));
m_pDS->exec(PrepareSQL("UPDATE album SET strReleaseType = '%s' WHERE strAlbum IS NULL OR strAlbum = ''", CAlbum::ReleaseTypeToString(CAlbum::Single).c_str()));
}
if (version < 51)
{
m_pDS->exec("ALTER TABLE song ADD mood text\n");
}
if (version < 53)
{
m_pDS->exec("ALTER TABLE song ADD dateAdded text");
CMediaSettings::GetInstance().SetMusicNeedsUpdate(53);
CSettings::GetInstance().Save();
}
if (version < 54)
{
//Remove dateAdded from artist table
m_pDS->exec("CREATE TABLE artist_new ( idArtist integer primary key, "
" strArtist varchar(256), strMusicBrainzArtistID text, "
" strBorn text, strFormed text, strGenres text, strMoods text, "
" strStyles text, strInstruments text, strBiography text, "
" strDied text, strDisbanded text, strYearsActive text, "
" strImage text, strFanart text, "
" lastScraped varchar(20) default NULL)");
m_pDS->exec("INSERT INTO artist_new "
"(idArtist, strArtist, strMusicBrainzArtistID, "
" strBorn, strFormed, strGenres, strMoods, "
" strStyles , strInstruments , strBiography , "
" strDied, strDisbanded, strYearsActive, "
" strImage, strFanart, lastScraped) "
" SELECT "
" idArtist, "
" strArtist, strMusicBrainzArtistID, "
" strBorn, strFormed, strGenres, strMoods, "
" strStyles, strInstruments, strBiography, "
" strDied, strDisbanded, strYearsActive, "
" strImage, strFanart, lastScraped "
" FROM artist");
m_pDS->exec("DROP TABLE artist");
m_pDS->exec("ALTER TABLE artist_new RENAME TO artist");
//Remove dateAdded from album table
m_pDS->exec("CREATE TABLE album_new (idAlbum integer primary key, "
" strAlbum varchar(256), strMusicBrainzAlbumID text, "
" strArtists text, strGenres text, "
" iYear integer, idThumb integer, "
" bCompilation integer not null default '0', "
" strMoods text, strStyles text, strThemes text, "
" strReview text, strImage text, strLabel text, "
" strType text, "
" iRating integer, "
" lastScraped varchar(20) default NULL, "
" strReleaseType text)");
m_pDS->exec("INSERT INTO album_new "
"(idAlbum, "
" strAlbum, strMusicBrainzAlbumID, "
" strArtists, strGenres, "
" iYear, idThumb, "
" bCompilation, "
" strMoods, strStyles, strThemes, "
" strReview, strImage, strLabel, "
" strType, iRating, lastScraped, "
" strReleaseType) "
" SELECT "
" album.idAlbum, "
" strAlbum, strMusicBrainzAlbumID, "
" strArtists, strGenres, "
" iYear, idThumb, "
" bCompilation, "
" strMoods, strStyles, strThemes, "
" strReview, strImage, strLabel, "
" strType, iRating, lastScraped, "
" strReleaseType"
" FROM album");
m_pDS->exec("DROP TABLE album");
m_pDS->exec("ALTER TABLE album_new RENAME TO album");
}
if (version < 55)
{
m_pDS->exec("DROP TABLE karaokedata");
}
if (version < 57)
{
m_pDS->exec("ALTER TABLE song ADD userrating INTEGER NOT NULL DEFAULT 0");
m_pDS->exec("UPDATE song SET rating = 0 WHERE rating < 0 or rating IS NULL");
m_pDS->exec("UPDATE song SET userrating = rating * 2");
m_pDS->exec("UPDATE song SET rating = 0");
m_pDS->exec("CREATE TABLE song_new (idSong INTEGER PRIMARY KEY, "
" idAlbum INTEGER, idPath INTEGER, "
" strArtists TEXT, strGenres TEXT, strTitle VARCHAR(512), "
" iTrack INTEGER, iDuration INTEGER, iYear INTEGER, "
" dwFileNameCRC TEXT, "
" strFileName TEXT, strMusicBrainzTrackID TEXT, "
" iTimesPlayed INTEGER, iStartOffset INTEGER, iEndOffset INTEGER, "
" idThumb INTEGER, "
" lastplayed VARCHAR(20) DEFAULT NULL, "
" rating FLOAT DEFAULT 0, "
" userrating INTEGER DEFAULT 0, "
" comment TEXT, mood TEXT, dateAdded TEXT)");
m_pDS->exec("INSERT INTO song_new "
"(idSong, "
" idAlbum, idPath, "
" strArtists, strGenres, strTitle, "
" iTrack, iDuration, iYear, "
" dwFileNameCRC, "
" strFileName, strMusicBrainzTrackID, "
" iTimesPlayed, iStartOffset, iEndOffset, "
" idThumb, "
" lastplayed,"
" rating, userrating, "
" comment, mood, dateAdded)"
" SELECT "
" idSong, "
" idAlbum, idPath, "
" strArtists, strGenres, strTitle, "
" iTrack, iDuration, iYear, "
" dwFileNameCRC, "
" strFileName, strMusicBrainzTrackID, "
" iTimesPlayed, iStartOffset, iEndOffset, "
" idThumb, "
" lastplayed,"
" rating, "
" userrating, "
" comment, mood, dateAdded"
" FROM song");
m_pDS->exec("DROP TABLE song");
m_pDS->exec("ALTER TABLE song_new RENAME TO song");
m_pDS->exec("ALTER TABLE album ADD iUserrating INTEGER NOT NULL DEFAULT 0");
m_pDS->exec("UPDATE album SET iRating = 0 WHERE iRating < 0 or iRating IS NULL");
m_pDS->exec("CREATE TABLE album_new (idAlbum INTEGER PRIMARY KEY, "
" strAlbum VARCHAR(256), strMusicBrainzAlbumID TEXT, "
" strArtists TEXT, strGenres TEXT, "
" iYear INTEGER, idThumb INTEGER, "
" bCompilation INTEGER NOT NULL DEFAULT '0', "
" strMoods TEXT, strStyles TEXT, strThemes TEXT, "
" strReview TEXT, strImage TEXT, strLabel TEXT, "
" strType TEXT, "
" fRating FLOAT NOT NULL DEFAULT 0, "
" iUserrating INTEGER NOT NULL DEFAULT 0, "
" lastScraped VARCHAR(20) DEFAULT NULL, "
" strReleaseType TEXT)");
m_pDS->exec("INSERT INTO album_new "
"(idAlbum, "
" strAlbum, strMusicBrainzAlbumID, "
" strArtists, strGenres, "
" iYear, idThumb, "
" bCompilation, "
" strMoods, strStyles, strThemes, "
" strReview, strImage, strLabel, "
" strType, "
" fRating, "
" iUserrating, "
" lastScraped, "
" strReleaseType)"
" SELECT "
" idAlbum, "
" strAlbum, strMusicBrainzAlbumID, "
" strArtists, strGenres, "
" iYear, idThumb, "
" bCompilation, "
" strMoods, strStyles, strThemes, "
" strReview, strImage, strLabel, "
" strType, "
" iRating, "
" iUserrating, "
" lastScraped, "
" strReleaseType"
" FROM album");
m_pDS->exec("DROP TABLE album");
m_pDS->exec("ALTER TABLE album_new RENAME TO album");
m_pDS->exec("ALTER TABLE album ADD iVotes INTEGER NOT NULL DEFAULT 0");
m_pDS->exec("ALTER TABLE song ADD votes INTEGER NOT NULL DEFAULT 0");
}
if (version < 58)
{
m_pDS->exec("UPDATE album SET fRating = fRating * 2");
}
}
int CMusicDatabase::GetSchemaVersion() const
{
return 58;
}
unsigned int CMusicDatabase::GetSongIDs(const Filter &filter, std::vector<std::pair<int,int> > &songIDs)
{
try
{
if (NULL == m_pDB.get()) return 0;
if (NULL == m_pDS.get()) return 0;
std::string strSQL = "select idSong from songview ";
if (!CDatabase::BuildSQL(strSQL, filter, strSQL))
return false;
if (!m_pDS->query(strSQL)) return 0;
songIDs.clear();
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return 0;
}
songIDs.reserve(m_pDS->num_rows());
while (!m_pDS->eof())
{
songIDs.push_back(std::make_pair<int,int>(1,m_pDS->fv(song_idSong).get_asInt()));
m_pDS->next();
} // cleanup
m_pDS->close();
return songIDs.size();
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, filter.where.c_str());
}
return 0;
}
int CMusicDatabase::GetSongsCount(const Filter &filter)
{
try
{
if (NULL == m_pDB.get()) return 0;
if (NULL == m_pDS.get()) return 0;
std::string strSQL = "select count(idSong) as NumSongs from songview ";
if (!CDatabase::BuildSQL(strSQL, filter, strSQL))
return false;
if (!m_pDS->query(strSQL)) return false;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return 0;
}
int iNumSongs = m_pDS->fv("NumSongs").get_asInt();
// cleanup
m_pDS->close();
return iNumSongs;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, filter.where.c_str());
}
return 0;
}
bool CMusicDatabase::GetAlbumPath(int idAlbum, std::string& path)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS2.get()) return false;
path.clear();
std::string strSQL=PrepareSQL("select strPath from song join path on song.idPath = path.idPath where song.idAlbum=%ld", idAlbum);
if (!m_pDS2->query(strSQL)) return false;
int iRowsFound = m_pDS2->num_rows();
if (iRowsFound == 0)
{
m_pDS2->close();
return false;
}
// if this returns more than one path, we just grab the first one. It's just for determining where to obtain + place
// a local thumbnail
path = m_pDS2->fv("strPath").get_asString();
m_pDS2->close(); // cleanup recordset data
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%i) failed", __FUNCTION__, idAlbum);
}
return false;
}
bool CMusicDatabase::SaveAlbumThumb(int idAlbum, const std::string& strThumb)
{
SetArtForItem(idAlbum, MediaTypeAlbum, "thumb", strThumb);
// TODO: We should prompt the user to update the art for songs
std::string sql = PrepareSQL("UPDATE art"
" SET url='-'"
" WHERE media_type='song'"
" AND type='thumb'"
" AND media_id IN"
" (SELECT idSong FROM song WHERE idAlbum=%ld)", idAlbum);
ExecuteQuery(sql);
return true;
}
bool CMusicDatabase::GetArtistPath(int idArtist, std::string &basePath)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS2.get()) return false;
// find all albums from this artist, and all the paths to the songs from those albums
std::string strSQL=PrepareSQL("SELECT strPath"
" FROM album_artist"
" JOIN song "
" ON album_artist.idAlbum = song.idAlbum"
" JOIN path"
" ON song.idPath = path.idPath"
" WHERE album_artist.idArtist = %i"
" GROUP BY song.idPath", idArtist);
// run query
if (!m_pDS2->query(strSQL)) return false;
int iRowsFound = m_pDS2->num_rows();
if (iRowsFound == 0)
{
m_pDS2->close();
return false;
}
// special case for single path - assume that we're in an artist/album/songs filesystem
if (iRowsFound == 1)
{
URIUtils::GetParentPath(m_pDS2->fv("strPath").get_asString(), basePath);
m_pDS2->close();
return true;
}
// find the common path (if any) to these albums
basePath.clear();
while (!m_pDS2->eof())
{
std::string path = m_pDS2->fv("strPath").get_asString();
if (basePath.empty())
basePath = path;
else
URIUtils::GetCommonPath(basePath,path);
m_pDS2->next();
}
// cleanup
m_pDS2->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
int CMusicDatabase::GetArtistByName(const std::string& strArtist)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL=PrepareSQL("select idArtist from artist where artist.strArtist like '%s'", strArtist.c_str());
// run query
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound != 1)
{
m_pDS->close();
return -1;
}
int lResult = m_pDS->fv("artist.idArtist").get_asInt();
m_pDS->close();
return lResult;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return -1;
}
int CMusicDatabase::GetAlbumByName(const std::string& strAlbum, const std::string& strArtist)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL;
if (strArtist.empty())
strSQL=PrepareSQL("SELECT idAlbum FROM album WHERE album.strAlbum LIKE '%s'", strAlbum.c_str());
else
strSQL=PrepareSQL("SELECT album.idAlbum FROM album WHERE album.strAlbum LIKE '%s' AND album.strArtists LIKE '%s'", strAlbum.c_str(),strArtist.c_str());
// run query
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound != 1)
{
m_pDS->close();
return -1;
}
return m_pDS->fv("album.idAlbum").get_asInt();
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return -1;
}
int CMusicDatabase::GetAlbumByName(const std::string& strAlbum, const std::vector<std::string>& artist)
{
return GetAlbumByName(strAlbum, StringUtils::Join(artist, g_advancedSettings.m_musicItemSeparator));
}
std::string CMusicDatabase::GetGenreById(int id)
{
return GetSingleValue("genre", "strGenre", PrepareSQL("idGenre=%i", id));
}
std::string CMusicDatabase::GetArtistById(int id)
{
return GetSingleValue("artist", "strArtist", PrepareSQL("idArtist=%i", id));
}
std::string CMusicDatabase::GetAlbumById(int id)
{
return GetSingleValue("album", "strAlbum", PrepareSQL("idAlbum=%i", id));
}
int CMusicDatabase::GetGenreByName(const std::string& strGenre)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL;
strSQL=PrepareSQL("select idGenre from genre where genre.strGenre like '%s'", strGenre.c_str());
// run query
if (!m_pDS->query(strSQL)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound != 1)
{
m_pDS->close();
return -1;
}
return m_pDS->fv("genre.idGenre").get_asInt();
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return -1;
}
bool CMusicDatabase::GetRandomSong(CFileItem* item, int& idSong, const Filter &filter)
{
try
{
idSong = -1;
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// We don't use PrepareSQL here, as the WHERE clause is already formatted
std::string strSQL = PrepareSQL("select %s from songview ", !filter.fields.empty() ? filter.fields.c_str() : "*");
Filter extFilter = filter;
extFilter.AppendOrder(PrepareSQL("RANDOM()"));
extFilter.limit = "1";
if (!CDatabase::BuildSQL(strSQL, extFilter, strSQL))
return false;
CLog::Log(LOGDEBUG, "%s query = %s", __FUNCTION__, strSQL.c_str());
// run query
if (!m_pDS->query(strSQL))
return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound != 1)
{
m_pDS->close();
return false;
}
GetFileItemFromDataset(item, CMusicDbUrl());
idSong = m_pDS->fv("songview.idSong").get_asInt();
m_pDS->close();
return true;
}
catch(...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, filter.where.c_str());
}
return false;
}
bool CMusicDatabase::GetCompilationAlbums(const std::string& strBaseDir, CFileItemList& items)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
musicUrl.AddOption("compilation", true);
Filter filter;
return GetAlbumsByWhere(musicUrl.ToString(), filter, items);
}
bool CMusicDatabase::GetCompilationSongs(const std::string& strBaseDir, CFileItemList& items)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
musicUrl.AddOption("compilation", true);
Filter filter;
return GetSongsByWhere(musicUrl.ToString(), filter, items);
}
int CMusicDatabase::GetCompilationAlbumsCount()
{
return strtol(GetSingleValue("album", "count(idAlbum)", "bCompilation = 1").c_str(), NULL, 10);
}
int CMusicDatabase::GetSinglesCount()
{
CDatabase::Filter filter(PrepareSQL("songview.idAlbum IN (SELECT idAlbum FROM album WHERE strReleaseType = '%s')", CAlbum::ReleaseTypeToString(CAlbum::Single).c_str()));
return GetSongsCount(filter);
}
bool CMusicDatabase::SetPathHash(const std::string &path, const std::string &hash)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
if (hash.empty())
{ // this is an empty folder - we need only add it to the path table
// if the path actually exists
if (!CDirectory::Exists(path))
return false;
}
int idPath = AddPath(path);
if (idPath < 0) return false;
std::string strSQL=PrepareSQL("update path set strHash='%s' where idPath=%ld", hash.c_str(), idPath);
m_pDS->exec(strSQL);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s, %s) failed", __FUNCTION__, path.c_str(), hash.c_str());
}
return false;
}
bool CMusicDatabase::GetPathHash(const std::string &path, std::string &hash)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL=PrepareSQL("select strHash from path where strPath='%s'", path.c_str());
m_pDS->query(strSQL);
if (m_pDS->num_rows() == 0)
return false;
hash = m_pDS->fv("strHash").get_asString();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s) failed", __FUNCTION__, path.c_str());
}
return false;
}
bool CMusicDatabase::RemoveSongsFromPath(const std::string &path1, MAPSONGS& songs, bool exact)
{
// We need to remove all songs from this path, as their tags are going
// to be re-read. We need to remove all songs from the song table + all links to them
// from the song link tables (as otherwise if a song is added back
// to the table with the same idSong, these tables can't be cleaned up properly later)
// TODO: SQLite probably doesn't allow this, but can we rely on that??
// We don't need to remove orphaned albums at this point as in AddAlbum() we check
// first whether the album has already been read during this scan, and if it hasn't
// we check whether it's in the table and update accordingly at that point, removing the entries from
// the album link tables. The only failure point for this is albums
// that span multiple folders, where just the files in one folder have been changed. In this case
// any linked fields that are only in the files that haven't changed will be removed. Clearly
// the primary albumartist still matches (as that's what we looked up based on) so is this really
// an issue? I don't think it is, as those artists will still have links to the album via the songs
// which is generally what we rely on, so the only failure point is albumartist lookup. In this
// case, it will return only things in the album_artist table from the newly updated songs (and
// only if they have additional artists). I think the effect of this is minimal at best, as ALL
// songs in the album should have the same albumartist!
// we also remove the path at this point as it will be added later on if the
// path still exists.
// After scanning we then remove the orphaned artists, genres and thumbs.
// Note: when used to remove all songs from a path and its subpath (exact=false), this
// does miss archived songs.
std::string path(path1);
try
{
if (!URIUtils::HasSlashAtEnd(path))
URIUtils::AddSlashAtEnd(path);
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string where;
if (exact)
where = PrepareSQL(" where strPath='%s'", path.c_str());
else
where = PrepareSQL(" where SUBSTR(strPath,1,%i)='%s'", StringUtils::utf8_strlen(path.c_str()), path.c_str());
std::string sql = "select * from songview" + where;
if (!m_pDS->query(sql)) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound > 0)
{
std::vector<std::string> songIds;
while (!m_pDS->eof())
{
CSong song = GetSongFromDataset();
song.strThumb = GetArtForItem(song.idSong, MediaTypeSong, "thumb");
songs.insert(std::make_pair(song.strFileName, song));
songIds.push_back(PrepareSQL("%i", song.idSong));
m_pDS->next();
}
m_pDS->close();
//TODO: move this below the m_pDS->exec block, once UPnP doesn't rely on this anymore
for (MAPSONGS::iterator songit = songs.begin(); songit != songs.end(); ++songit)
AnnounceRemove(MediaTypeSong, songit->second.idSong);
// and delete all songs, and anything linked to them
sql = "delete from song where idSong in (" + StringUtils::Join(songIds, ",") + ")";
m_pDS->exec(sql);
}
// and remove the path as well (it'll be re-added later on with the new hash if it's non-empty)
sql = "delete from path" + where;
m_pDS->exec(sql);
return iRowsFound > 0;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s) failed", __FUNCTION__, path.c_str());
}
return false;
}
bool CMusicDatabase::GetPaths(std::set<std::string> &paths)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
paths.clear();
// find all paths
if (!m_pDS->query("select strPath from path")) return false;
int iRowsFound = m_pDS->num_rows();
if (iRowsFound == 0)
{
m_pDS->close();
return true;
}
while (!m_pDS->eof())
{
paths.insert(m_pDS->fv("strPath").get_asString());
m_pDS->next();
}
m_pDS->close();
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
}
return false;
}
bool CMusicDatabase::SetSongUserrating(const std::string &filePath, int userrating)
{
try
{
if (filePath.empty()) return false;
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
int songID = GetSongIDFromPath(filePath);
if (-1 == songID) return false;
std::string sql = PrepareSQL("UPDATE song SET userrating='%i' WHERE idSong = %i", userrating, songID);
m_pDS->exec(sql);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s,%i) failed", __FUNCTION__, filePath.c_str(), userrating);
}
return false;
}
bool CMusicDatabase::SetAlbumUserrating(const std::string &filePath, int userrating)
{
try
{
if (filePath.empty()) return false;
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
int albumID = GetAlbumIdByPath(filePath);
if (-1 == albumID) return false;
std::string sql = PrepareSQL("UPDATE album SET iUserrating='%i' WHERE idAlbum = %i", userrating, albumID);
m_pDS->exec(sql);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s,%i) failed", __FUNCTION__, filePath.c_str(), userrating);
}
return false;
}
bool CMusicDatabase::SetSongVotes(const std::string &filePath, int votes)
{
try
{
if (filePath.empty()) return false;
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
int songID = GetSongIDFromPath(filePath);
if (-1 == songID) return false;
std::string sql = PrepareSQL("UPDATE song SET votes='%i' WHERE idSong = %i", votes, songID);
m_pDS->exec(sql);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s,%i) failed", __FUNCTION__, filePath.c_str(), votes);
}
return false;
}
bool CMusicDatabase::SetAlbumVotes(const std::string &filePath, int votes)
{
try
{
if (filePath.empty()) return false;
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
int albumID = GetAlbumIdByPath(filePath);
if (-1 == albumID) return false;
std::string sql = PrepareSQL("UPDATE album SET iVotes='%i' WHERE idAlbum = %i", votes, albumID);
m_pDS->exec(sql);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s,%i) failed", __FUNCTION__, filePath.c_str(), votes);
}
return false;
}
int CMusicDatabase::GetSongIDFromPath(const std::string &filePath)
{
// grab the where string to identify the song id
CURL url(filePath);
if (url.IsProtocol("musicdb"))
{
std::string strFile=URIUtils::GetFileName(filePath);
URIUtils::RemoveExtension(strFile);
return atol(strFile.c_str());
}
// hit the db
try
{
if (NULL == m_pDB.get()) return -1;
if (NULL == m_pDS.get()) return -1;
std::string strPath, strFileName;
URIUtils::Split(filePath, strPath, strFileName);
URIUtils::AddSlashAtEnd(strPath);
std::string sql = PrepareSQL("select idSong from song join path on song.idPath = path.idPath where song.strFileName='%s' and path.strPath='%s'", strFileName.c_str(), strPath.c_str());
if (!m_pDS->query(sql)) return -1;
if (m_pDS->num_rows() == 0)
{
m_pDS->close();
return -1;
}
int songID = m_pDS->fv("idSong").get_asInt();
m_pDS->close();
return songID;
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s) failed", __FUNCTION__, filePath.c_str());
}
return -1;
}
bool CMusicDatabase::CommitTransaction()
{
if (CDatabase::CommitTransaction())
{ // number of items in the db has likely changed, so reset the infomanager cache
g_infoManager.SetLibraryBool(LIBRARY_HAS_MUSIC, GetSongsCount() > 0);
return true;
}
return false;
}
bool CMusicDatabase::SetScraperForPath(const std::string& strPath, const ADDON::ScraperPtr& scraper)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
// wipe old settings
std::string strSQL = PrepareSQL("delete from content where strPath='%s'",strPath.c_str());
m_pDS->exec(strSQL);
// insert new settings
strSQL = PrepareSQL("insert into content (strPath, strScraperPath, strContent, strSettings) values ('%s','%s','%s','%s')",
strPath.c_str(), scraper->ID().c_str(), ADDON::TranslateContent(scraper->Content()).c_str(), scraper->GetPathSettings().c_str());
m_pDS->exec(strSQL);
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s - (%s) failed", __FUNCTION__, strPath.c_str());
}
return false;
}
bool CMusicDatabase::GetScraperForPath(const std::string& strPath, ADDON::ScraperPtr& info, const ADDON::TYPE &type)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string strSQL = PrepareSQL("select * from content where strPath='%s'",strPath.c_str());
m_pDS->query(strSQL);
if (m_pDS->eof()) // no info set for path - fallback logic commencing
{
CQueryParams params;
CDirectoryNode::GetDatabaseInfo(strPath, params);
if (params.GetGenreId() != -1) // check genre
{
strSQL = PrepareSQL("select * from content where strPath='musicdb://genres/%i/'",params.GetGenreId());
m_pDS->query(strSQL);
}
if (m_pDS->eof() && params.GetAlbumId() != -1) // check album
{
strSQL = PrepareSQL("select * from content where strPath='musicdb://albums/%i/'",params.GetAlbumId());
m_pDS->query(strSQL);
if (m_pDS->eof()) // general albums setting
{
strSQL = PrepareSQL("select * from content where strPath='musicdb://albums/'");
m_pDS->query(strSQL);
}
}
if (m_pDS->eof() && params.GetArtistId() != -1) // check artist
{
strSQL = PrepareSQL("select * from content where strPath='musicdb://artists/%i/'",params.GetArtistId());
m_pDS->query(strSQL);
if (m_pDS->eof()) // general artist setting
{
strSQL = PrepareSQL("select * from content where strPath='musicdb://artists/'");
m_pDS->query(strSQL);
}
}
}
if (!m_pDS->eof())
{ // try and ascertain scraper for this path
CONTENT_TYPE content = ADDON::TranslateContent(m_pDS->fv("content.strContent").get_asString());
std::string scraperUUID = m_pDS->fv("content.strScraperPath").get_asString();
if (content != CONTENT_NONE)
{ // content set, use pre configured or default scraper
ADDON::AddonPtr addon;
if (!scraperUUID.empty() && ADDON::CAddonMgr::GetInstance().GetAddon(scraperUUID, addon) && addon)
{
info = std::dynamic_pointer_cast<ADDON::CScraper>(addon->Clone());
if (!info)
return false;
// store this path's settings
info->SetPathSettings(content, m_pDS->fv("content.strSettings").get_asString());
}
}
else
{ // use default scraper of the requested type
ADDON::AddonPtr defaultScraper;
if (ADDON::CAddonMgr::GetInstance().GetDefault(type, defaultScraper))
{
info = std::dynamic_pointer_cast<ADDON::CScraper>(defaultScraper->Clone());
}
}
}
m_pDS->close();
if (!info)
{ // use default music scraper instead
ADDON::AddonPtr addon;
if(ADDON::CAddonMgr::GetInstance().GetDefault(type, addon))
{
info = std::dynamic_pointer_cast<ADDON::CScraper>(addon);
return info != NULL;
}
else
return false;
}
return true;
}
catch (...)
{
CLog::Log(LOGERROR, "%s -(%s) failed", __FUNCTION__, strPath.c_str());
}
return false;
}
bool CMusicDatabase::ScraperInUse(const std::string &scraperID) const
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS.get()) return false;
std::string sql = PrepareSQL("select count(1) from content where strScraperPath='%s'",scraperID.c_str());
if (!m_pDS->query(sql) || m_pDS->num_rows() == 0)
return false;
bool found = m_pDS->fv(0).get_asInt() > 0;
m_pDS->close();
return found;
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%s) failed", __FUNCTION__, scraperID.c_str());
}
return false;
}
bool CMusicDatabase::GetItems(const std::string &strBaseDir, CFileItemList &items, const Filter &filter /* = Filter() */, const SortDescription &sortDescription /* = SortDescription() */)
{
CMusicDbUrl musicUrl;
if (!musicUrl.FromString(strBaseDir))
return false;
return GetItems(strBaseDir, musicUrl.GetType(), items, filter, sortDescription);
}
bool CMusicDatabase::GetItems(const std::string &strBaseDir, const std::string &itemType, CFileItemList &items, const Filter &filter /* = Filter() */, const SortDescription &sortDescription /* = SortDescription() */)
{
if (StringUtils::EqualsNoCase(itemType, "genres"))
return GetGenresNav(strBaseDir, items, filter);
else if (StringUtils::EqualsNoCase(itemType, "years"))
return GetYearsNav(strBaseDir, items, filter);
else if (StringUtils::EqualsNoCase(itemType, "artists"))
return GetArtistsNav(strBaseDir, items, !CSettings::GetInstance().GetBool(CSettings::SETTING_MUSICLIBRARY_SHOWCOMPILATIONARTISTS), -1, -1, -1, filter, sortDescription);
else if (StringUtils::EqualsNoCase(itemType, "albums"))
return GetAlbumsByWhere(strBaseDir, filter, items, sortDescription);
else if (StringUtils::EqualsNoCase(itemType, "songs"))
return GetSongsByWhere(strBaseDir, filter, items, sortDescription);
return false;
}
std::string CMusicDatabase::GetItemById(const std::string &itemType, int id)
{
if (StringUtils::EqualsNoCase(itemType, "genres"))
return GetGenreById(id);
else if (StringUtils::EqualsNoCase(itemType, "years"))
return StringUtils::Format("%d", id);
else if (StringUtils::EqualsNoCase(itemType, "artists"))
return GetArtistById(id);
else if (StringUtils::EqualsNoCase(itemType, "albums"))
return GetAlbumById(id);
return "";
}
void CMusicDatabase::ExportToXML(const std::string &xmlFile, bool singleFile, bool images, bool overwrite)
{
int iFailCount = 0;
CGUIDialogProgress *progress=NULL;
try
{
if (NULL == m_pDB.get()) return;
if (NULL == m_pDS.get()) return;
if (NULL == m_pDS2.get()) return;
// find all albums
std::vector<int> albumIds;
std::string sql = "select idAlbum FROM album WHERE lastScraped IS NOT NULL";
m_pDS->query(sql);
int total = m_pDS->num_rows();
int current = 0;
albumIds.reserve(total);
while (!m_pDS->eof())
{
albumIds.push_back(m_pDS->fv("idAlbum").get_asInt());
m_pDS->next();
}
m_pDS->close();
progress = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
if (progress)
{
progress->SetHeading(CVariant{20196});
progress->SetLine(0, CVariant{650});
progress->SetLine(1, CVariant{""});
progress->SetLine(2, CVariant{""});
progress->SetPercentage(0);
progress->Open();
progress->ShowProgressBar(true);
}
// create our xml document
CXBMCTinyXML xmlDoc;
TiXmlDeclaration decl("1.0", "UTF-8", "yes");
xmlDoc.InsertEndChild(decl);
TiXmlNode *pMain = NULL;
if (!singleFile)
pMain = &xmlDoc;
else
{
TiXmlElement xmlMainElement("musicdb");
pMain = xmlDoc.InsertEndChild(xmlMainElement);
}
for (std::vector<int>::iterator albumId = albumIds.begin(); albumId != albumIds.end(); ++albumId)
{
CAlbum album;
GetAlbum(*albumId, album);
std::string strPath;
GetAlbumPath(*albumId, strPath);
album.Save(pMain, "album", strPath);
if (!singleFile)
{
if (!CDirectory::Exists(strPath))
CLog::Log(LOGDEBUG, "%s - Not exporting item %s as it does not exist", __FUNCTION__, strPath.c_str());
else
{
std::string nfoFile = URIUtils::AddFileToFolder(strPath, "album.nfo");
if (overwrite || !CFile::Exists(nfoFile))
{
if (!xmlDoc.SaveFile(nfoFile))
{
CLog::Log(LOGERROR, "%s: Album nfo export failed! ('%s')", __FUNCTION__, nfoFile.c_str());
CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(20302), nfoFile);
iFailCount++;
}
}
if (images)
{
std::string thumb = GetArtForItem(album.idAlbum, MediaTypeAlbum, "thumb");
if (!thumb.empty() && (overwrite || !CFile::Exists(URIUtils::AddFileToFolder(strPath,"folder.jpg"))))
CTextureCache::GetInstance().Export(thumb, URIUtils::AddFileToFolder(strPath,"folder.jpg"));
}
xmlDoc.Clear();
TiXmlDeclaration decl("1.0", "UTF-8", "yes");
xmlDoc.InsertEndChild(decl);
}
}
if ((current % 50) == 0 && progress)
{
progress->SetLine(1, CVariant{album.strAlbum});
progress->SetPercentage(current * 100 / total);
progress->Progress();
if (progress->IsCanceled())
{
progress->Close();
m_pDS->close();
return;
}
}
current++;
}
// find all artists
std::vector<int> artistIds;
std::string artistSQL = "SELECT idArtist FROM artist where lastScraped IS NOT NULL";
m_pDS->query(artistSQL);
total = m_pDS->num_rows();
current = 0;
artistIds.reserve(total);
while (!m_pDS->eof())
{
artistIds.push_back(m_pDS->fv("idArtist").get_asInt());
m_pDS->next();
}
m_pDS->close();
for (std::vector<int>::iterator artistId = artistIds.begin(); artistId != artistIds.end(); ++artistId)
{
CArtist artist;
GetArtist(*artistId, artist);
std::string strPath;
GetArtistPath(artist.idArtist,strPath);
artist.Save(pMain, "artist", strPath);
std::map<std::string, std::string> artwork;
if (GetArtForItem(artist.idArtist, MediaTypeArtist, artwork) && singleFile)
{ // append to the XML
TiXmlElement additionalNode("art");
for (std::map<std::string, std::string>::const_iterator i = artwork.begin(); i != artwork.end(); ++i)
XMLUtils::SetString(&additionalNode, i->first.c_str(), i->second);
pMain->LastChild()->InsertEndChild(additionalNode);
}
if (!singleFile)
{
if (!CDirectory::Exists(strPath))
CLog::Log(LOGDEBUG, "%s - Not exporting item %s as it does not exist", __FUNCTION__, strPath.c_str());
else
{
std::string nfoFile = URIUtils::AddFileToFolder(strPath, "artist.nfo");
if (overwrite || !CFile::Exists(nfoFile))
{
if (!xmlDoc.SaveFile(nfoFile))
{
CLog::Log(LOGERROR, "%s: Artist nfo export failed! ('%s')", __FUNCTION__, nfoFile.c_str());
CGUIDialogKaiToast::QueueNotification(CGUIDialogKaiToast::Error, g_localizeStrings.Get(20302), nfoFile);
iFailCount++;
}
}
if (images && !artwork.empty())
{
std::string savedThumb = URIUtils::AddFileToFolder(strPath,"folder.jpg");
std::string savedFanart = URIUtils::AddFileToFolder(strPath,"fanart.jpg");
if (artwork.find("thumb") != artwork.end() && (overwrite || !CFile::Exists(savedThumb)))
CTextureCache::GetInstance().Export(artwork["thumb"], savedThumb);
if (artwork.find("fanart") != artwork.end() && (overwrite || !CFile::Exists(savedFanart)))
CTextureCache::GetInstance().Export(artwork["fanart"], savedFanart);
}
xmlDoc.Clear();
TiXmlDeclaration decl("1.0", "UTF-8", "yes");
xmlDoc.InsertEndChild(decl);
}
}
if ((current % 50) == 0 && progress)
{
progress->SetLine(1, CVariant{artist.strArtist});
progress->SetPercentage(current * 100 / total);
progress->Progress();
if (progress->IsCanceled())
{
progress->Close();
m_pDS->close();
return;
}
}
current++;
}
xmlDoc.SaveFile(xmlFile);
CVariant data;
if (singleFile)
{
data["file"] = xmlFile;
if (iFailCount > 0)
data["failcount"] = iFailCount;
}
ANNOUNCEMENT::CAnnouncementManager::GetInstance().Announce(ANNOUNCEMENT::AudioLibrary, "xbmc", "OnExport", data);
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
iFailCount++;
}
if (progress)
progress->Close();
if (iFailCount > 0)
CGUIDialogOK::ShowAndGetInput(CVariant{20196}, CVariant{StringUtils::Format(g_localizeStrings.Get(15011).c_str(), iFailCount)});
}
void CMusicDatabase::ImportFromXML(const std::string &xmlFile)
{
CGUIDialogProgress *progress = (CGUIDialogProgress *)g_windowManager.GetWindow(WINDOW_DIALOG_PROGRESS);
try
{
if (NULL == m_pDB.get()) return;
if (NULL == m_pDS.get()) return;
CXBMCTinyXML xmlDoc;
if (!xmlDoc.LoadFile(xmlFile))
return;
TiXmlElement *root = xmlDoc.RootElement();
if (!root) return;
if (progress)
{
progress->SetHeading(CVariant{20197});
progress->SetLine(0, CVariant{649});
progress->SetLine(1, CVariant{330});
progress->SetLine(2, CVariant{""});
progress->SetPercentage(0);
progress->Open();
progress->ShowProgressBar(true);
}
TiXmlElement *entry = root->FirstChildElement();
int current = 0;
int total = 0;
// first count the number of items...
while (entry)
{
if (strnicmp(entry->Value(), "artist", 6)==0 ||
strnicmp(entry->Value(), "album", 5)==0)
total++;
entry = entry->NextSiblingElement();
}
BeginTransaction();
entry = root->FirstChildElement();
while (entry)
{
std::string strTitle;
if (strnicmp(entry->Value(), "artist", 6) == 0)
{
CArtist importedArtist;
importedArtist.Load(entry);
strTitle = importedArtist.strArtist;
int idArtist = GetArtistByName(importedArtist.strArtist);
if (idArtist > -1)
{
CArtist artist;
GetArtist(idArtist, artist);
artist.MergeScrapedArtist(importedArtist, true);
UpdateArtist(artist);
}
current++;
}
else if (strnicmp(entry->Value(), "album", 5) == 0)
{
CAlbum importedAlbum;
importedAlbum.Load(entry);
strTitle = importedAlbum.strAlbum;
int idAlbum = GetAlbumByName(importedAlbum.strAlbum, importedAlbum.GetAlbumArtistString());
if (idAlbum > -1)
{
CAlbum album;
GetAlbum(idAlbum, album, true);
album.MergeScrapedAlbum(importedAlbum, true);
UpdateAlbum(album);
}
current++;
}
entry = entry ->NextSiblingElement();
if (progress && total)
{
progress->SetPercentage(current * 100 / total);
progress->SetLine(2, CVariant{std::move(strTitle)});
progress->Progress();
if (progress->IsCanceled())
{
progress->Close();
RollbackTransaction();
return;
}
}
}
CommitTransaction();
g_infoManager.ResetLibraryBools();
}
catch (...)
{
CLog::Log(LOGERROR, "%s failed", __FUNCTION__);
RollbackTransaction();
}
if (progress)
progress->Close();
}
void CMusicDatabase::SetPropertiesFromArtist(CFileItem& item, const CArtist& artist)
{
item.SetProperty("artist_instrument", StringUtils::Join(artist.instruments, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("artist_instrument_array", artist.instruments);
item.SetProperty("artist_style", StringUtils::Join(artist.styles, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("artist_style_array", artist.styles);
item.SetProperty("artist_mood", StringUtils::Join(artist.moods, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("artist_mood_array", artist.moods);
item.SetProperty("artist_born", artist.strBorn);
item.SetProperty("artist_formed", artist.strFormed);
item.SetProperty("artist_description", artist.strBiography);
item.SetProperty("artist_genre", StringUtils::Join(artist.genre, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("artist_genre_array", artist.genre);
item.SetProperty("artist_died", artist.strDied);
item.SetProperty("artist_disbanded", artist.strDisbanded);
item.SetProperty("artist_yearsactive", StringUtils::Join(artist.yearsActive, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("artist_yearsactive_array", artist.yearsActive);
}
void CMusicDatabase::SetPropertiesFromAlbum(CFileItem& item, const CAlbum& album)
{
item.SetProperty("album_description", album.strReview);
item.SetProperty("album_theme", StringUtils::Join(album.themes, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("album_theme_array", album.themes);
item.SetProperty("album_mood", StringUtils::Join(album.moods, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("album_mood_array", album.moods);
item.SetProperty("album_style", StringUtils::Join(album.styles, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("album_style_array", album.styles);
item.SetProperty("album_type", album.strType);
item.SetProperty("album_label", album.strLabel);
item.SetProperty("album_artist", album.GetAlbumArtistString());
item.SetProperty("album_artist_array", album.GetAlbumArtist());
item.SetProperty("album_genre", StringUtils::Join(album.genre, g_advancedSettings.m_musicItemSeparator));
item.SetProperty("album_genre_array", album.genre);
item.SetProperty("album_title", album.strAlbum);
if (album.fRating > 0)
item.SetProperty("album_rating", album.fRating);
if (album.iUserrating > 0)
item.SetProperty("album_userrating", album.iUserrating);
if (album.iVotes > 0)
item.SetProperty("album_votes", album.iVotes);
item.SetProperty("album_releasetype", CAlbum::ReleaseTypeToString(album.releaseType));
}
void CMusicDatabase::SetPropertiesForFileItem(CFileItem& item)
{
if (!item.HasMusicInfoTag())
return;
int idArtist = GetArtistByName(item.GetMusicInfoTag()->GetArtistString());
if (idArtist > -1)
{
CArtist artist;
if (GetArtist(idArtist, artist))
SetPropertiesFromArtist(item,artist);
}
int idAlbum = item.GetMusicInfoTag()->GetAlbumId();
if (idAlbum <= 0)
idAlbum = GetAlbumByName(item.GetMusicInfoTag()->GetAlbum(),
item.GetMusicInfoTag()->GetArtistString());
if (idAlbum > -1)
{
CAlbum album;
if (GetAlbum(idAlbum, album, false))
SetPropertiesFromAlbum(item,album);
}
}
void CMusicDatabase::SetArtForItem(int mediaId, const std::string &mediaType, const std::map<std::string, std::string> &art)
{
for (std::map<std::string, std::string>::const_iterator i = art.begin(); i != art.end(); ++i)
SetArtForItem(mediaId, mediaType, i->first, i->second);
}
void CMusicDatabase::SetArtForItem(int mediaId, const std::string &mediaType, const std::string &artType, const std::string &url)
{
try
{
if (NULL == m_pDB.get()) return;
if (NULL == m_pDS.get()) return;
// don't set <foo>.<bar> art types - these are derivative types from parent items
if (artType.find('.') != std::string::npos)
return;
std::string sql = PrepareSQL("SELECT art_id FROM art WHERE media_id=%i AND media_type='%s' AND type='%s'", mediaId, mediaType.c_str(), artType.c_str());
m_pDS->query(sql);
if (!m_pDS->eof())
{ // update
int artId = m_pDS->fv(0).get_asInt();
m_pDS->close();
sql = PrepareSQL("UPDATE art SET url='%s' where art_id=%d", url.c_str(), artId);
m_pDS->exec(sql);
}
else
{ // insert
m_pDS->close();
sql = PrepareSQL("INSERT INTO art(media_id, media_type, type, url) VALUES (%d, '%s', '%s', '%s')", mediaId, mediaType.c_str(), artType.c_str(), url.c_str());
m_pDS->exec(sql);
}
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%d, '%s', '%s', '%s') failed", __FUNCTION__, mediaId, mediaType.c_str(), artType.c_str(), url.c_str());
}
}
bool CMusicDatabase::GetArtForItem(int mediaId, const std::string &mediaType, std::map<std::string, std::string> &art)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS2.get()) return false; // using dataset 2 as we're likely called in loops on dataset 1
std::string sql = PrepareSQL("SELECT type,url FROM art WHERE media_id=%i AND media_type='%s'", mediaId, mediaType.c_str());
m_pDS2->query(sql);
while (!m_pDS2->eof())
{
art.insert(std::make_pair(m_pDS2->fv(0).get_asString(), m_pDS2->fv(1).get_asString()));
m_pDS2->next();
}
m_pDS2->close();
return !art.empty();
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%d) failed", __FUNCTION__, mediaId);
}
return false;
}
std::string CMusicDatabase::GetArtForItem(int mediaId, const std::string &mediaType, const std::string &artType)
{
std::string query = PrepareSQL("SELECT url FROM art WHERE media_id=%i AND media_type='%s' AND type='%s'", mediaId, mediaType.c_str(), artType.c_str());
return GetSingleValue(query, m_pDS2);
}
bool CMusicDatabase::GetArtistArtForItem(int mediaId, const std::string &mediaType, std::map<std::string, std::string> &art)
{
try
{
if (NULL == m_pDB.get()) return false;
if (NULL == m_pDS2.get()) return false; // using dataset 2 as we're likely called in loops on dataset 1
std::string sql = PrepareSQL("SELECT type,url FROM art WHERE media_id=(SELECT idArtist from %s_artist WHERE id%s=%i AND iOrder=0) AND media_type='artist'", mediaType.c_str(), mediaType.c_str(), mediaId);
m_pDS2->query(sql);
while (!m_pDS2->eof())
{
art.insert(std::make_pair(m_pDS2->fv(0).get_asString(), m_pDS2->fv(1).get_asString()));
m_pDS2->next();
}
m_pDS2->close();
return !art.empty();
}
catch (...)
{
CLog::Log(LOGERROR, "%s(%d) failed", __FUNCTION__, mediaId);
}
return false;
}
std::string CMusicDatabase::GetArtistArtForItem(int mediaId, const std::string &mediaType, const std::string &artType)
{
std::string query = PrepareSQL("SELECT url FROM art WHERE media_id=(SELECT idArtist from %s_artist WHERE id%s=%i AND iOrder=0) AND media_type='artist' AND type='%s'", mediaType.c_str(), mediaType.c_str(), mediaId, artType.c_str());
return GetSingleValue(query, m_pDS2);
}
bool CMusicDatabase::GetFilter(CDbUrl &musicUrl, Filter &filter, SortDescription &sorting)
{
if (!musicUrl.IsValid())
return false;
std::string type = musicUrl.GetType();
const CUrlOptions::UrlOptions& options = musicUrl.GetOptions();
CUrlOptions::UrlOptions::const_iterator option;
if (type == "artists")
{
int idArtist = -1, idGenre = -1, idAlbum = -1, idSong = -1;
bool albumArtistsOnly = false;
option = options.find("artistid");
if (option != options.end())
idArtist = (int)option->second.asInteger();
option = options.find("genreid");
if (option != options.end())
idGenre = (int)option->second.asInteger();
else
{
option = options.find("genre");
if (option != options.end())
idGenre = GetGenreByName(option->second.asString());
}
option = options.find("albumid");
if (option != options.end())
idAlbum = (int)option->second.asInteger();
else
{
option = options.find("album");
if (option != options.end())
idAlbum = GetAlbumByName(option->second.asString());
}
option = options.find("songid");
if (option != options.end())
idSong = (int)option->second.asInteger();
option = options.find("albumartistsonly");
if (option != options.end())
albumArtistsOnly = option->second.asBoolean();
std::string strSQL = "(artistview.idArtist IN ";
if (idArtist > 0)
strSQL += PrepareSQL("(%d)", idArtist);
else if (idAlbum > 0)
strSQL += PrepareSQL("(SELECT album_artist.idArtist FROM album_artist WHERE album_artist.idAlbum = %i)", idAlbum);
else if (idSong > 0)
strSQL += PrepareSQL("(SELECT song_artist.idArtist FROM song_artist WHERE song_artist.idSong = %i)", idSong);
else if (idGenre > 0)
{ // same statements as below, but limit to the specified genre
// in this case we show the whole lot always - there is no limitation to just album artists
if (!albumArtistsOnly) // show all artists in this case (ie those linked to a song)
strSQL+=PrepareSQL("(SELECT song_artist.idArtist FROM song_artist" // All artists linked to extra genres
" JOIN song_genre ON song_artist.idSong = song_genre.idSong"
" WHERE song_genre.idGenre = %i)"
" OR idArtist IN ", idGenre);
// and add any artists linked to an album (may be different from above due to album artist tag)
strSQL += PrepareSQL("(SELECT album_artist.idArtist FROM album_artist" // All album artists linked to extra genres
" JOIN album_genre ON album_artist.idAlbum = album_genre.idAlbum"
" WHERE album_genre.idGenre = %i)", idGenre);
}
else
{
if (!albumArtistsOnly) // show all artists in this case (ie those linked to a song)
strSQL += "(SELECT song_artist.idArtist FROM song_artist)"
" OR artistview.idArtist IN ";
// and always show any artists linked to an album (may be different from above due to album artist tag)
strSQL += "(SELECT album_artist.idArtist FROM album_artist)"; // Includes compliation albums hence "Various artists"
}
// remove the null string
strSQL += ") and artistview.strArtist != ''";
// and the various artist entry if applicable
if (!albumArtistsOnly)
{
std::string strVariousArtists = g_localizeStrings.Get(340);
strSQL += PrepareSQL(" and artistview.strArtist <> '%s'", strVariousArtists.c_str());
}
filter.AppendWhere(strSQL);
}
else if (type == "albums")
{
option = options.find("year");
if (option != options.end())
filter.AppendWhere(PrepareSQL("albumview.iYear = %i", (int)option->second.asInteger()));
option = options.find("compilation");
if (option != options.end())
filter.AppendWhere(PrepareSQL("albumview.bCompilation = %i", option->second.asBoolean() ? 1 : 0));
option = options.find("genreid");
if (option != options.end())
filter.AppendWhere(PrepareSQL("albumview.idAlbum IN (SELECT song.idAlbum FROM song JOIN song_genre ON song.idSong = song_genre.idSong WHERE song_genre.idGenre = %i)", (int)option->second.asInteger()));
option = options.find("genre");
if (option != options.end())
filter.AppendWhere(PrepareSQL("albumview.idAlbum IN (SELECT song.idAlbum FROM song JOIN song_genre ON song.idSong = song_genre.idSong JOIN genre ON genre.idGenre = song_genre.idGenre WHERE genre.strGenre like '%s')", option->second.asString().c_str()));
option = options.find("artistid");
if (option != options.end())
{
int idArtist = static_cast<int>(option->second.asInteger());
filter.AppendWhere(PrepareSQL(
"(EXISTS ( "
" SELECT 1 "
" FROM song "
" JOIN song_artist ON song.idSong = song_artist.idSong "
" WHERE song.idAlbum = albumview.idAlbum"
" AND song_artist.idArtist = %i "
") OR "
"EXISTS ( "
" SELECT 1 "
" FROM album_artist "
" WHERE album_artist.idAlbum = albumview.idAlbum "
" AND album_artist.idArtist = %i "
"))",
idArtist,
idArtist
));
}
else
{
option = options.find("artist");
if (option != options.end())
filter.AppendWhere(PrepareSQL("albumview.idAlbum IN (SELECT song.idAlbum FROM song JOIN song_artist ON song.idSong = song_artist.idSong JOIN artist ON artist.idArtist = song_artist.idArtist WHERE artist.strArtist like '%s')" // All albums linked to this artist via songs
" OR albumview.idAlbum IN (SELECT album_artist.idAlbum FROM album_artist JOIN artist ON artist.idArtist = album_artist.idArtist WHERE artist.strArtist like '%s')", // All albums where album artists fit
option->second.asString().c_str(), option->second.asString().c_str()));
// no artist given, so exclude any single albums (aka empty tagged albums)
else
{
option = options.find("show_singles");
if (option == options.end() || !option->second.asBoolean())
filter.AppendWhere(PrepareSQL("albumview.strReleaseType = '%s'", CAlbum::ReleaseTypeToString(CAlbum::Album).c_str()));
}
}
}
else if (type == "songs" || type == "singles")
{
option = options.find("singles");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.idAlbum %sIN (SELECT idAlbum FROM album WHERE strReleaseType = '%s')",
option->second.asBoolean() ? "" : "NOT ",
CAlbum::ReleaseTypeToString(CAlbum::Single).c_str()));
option = options.find("year");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.iYear = %i", (int)option->second.asInteger()));
option = options.find("compilation");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.bCompilation = %i", option->second.asBoolean() ? 1 : 0));
option = options.find("albumid");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.idAlbum = %i", (int)option->second.asInteger()));
option = options.find("album");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.strAlbum like '%s'", option->second.asString().c_str()));
option = options.find("genreid");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.idSong IN (SELECT song_genre.idSong FROM song_genre WHERE song_genre.idGenre = %i)", (int)option->second.asInteger()));
option = options.find("genre");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.idSong IN (SELECT song_genre.idSong FROM song_genre JOIN genre ON genre.idGenre = song_genre.idGenre WHERE genre.strGenre like '%s')", option->second.asString().c_str()));
option = options.find("artistid");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.idSong IN (SELECT song_artist.idSong FROM song_artist WHERE song_artist.idArtist = %i)" // song artists
" OR songview.idSong IN (SELECT song.idSong FROM song JOIN album_artist ON song.idAlbum=album_artist.idAlbum WHERE album_artist.idArtist = %i)", // album artists
(int)option->second.asInteger(), (int)option->second.asInteger()));
option = options.find("artist");
if (option != options.end())
filter.AppendWhere(PrepareSQL("songview.idSong IN (SELECT song_artist.idSong FROM song_artist JOIN artist ON artist.idArtist = song_artist.idArtist WHERE artist.strArtist like '%s')" // song artists
" OR songview.idSong IN (SELECT song.idSong FROM song JOIN album_artist ON song.idAlbum=album_artist.idAlbum JOIN artist ON artist.idArtist = album_artist.idArtist WHERE artist.strArtist like '%s')", // album artists
option->second.asString().c_str(), option->second.asString().c_str()));
}
option = options.find("xsp");
if (option != options.end())
{
CSmartPlaylist xsp;
if (!xsp.LoadFromJson(option->second.asString()))
return false;
// check if the filter playlist matches the item type
if (xsp.GetType() == type ||
(xsp.GetGroup() == type && !xsp.IsGroupMixed()))
{
std::set<std::string> playlists;
filter.AppendWhere(xsp.GetWhereClause(*this, playlists));
if (xsp.GetLimit() > 0)
sorting.limitEnd = xsp.GetLimit();
if (xsp.GetOrder() != SortByNone)
sorting.sortBy = xsp.GetOrder();
sorting.sortOrder = xsp.GetOrderAscending() ? SortOrderAscending : SortOrderDescending;
if (CSettings::GetInstance().GetBool(CSettings::SETTING_FILELISTS_IGNORETHEWHENSORTING))
sorting.sortAttributes = SortAttributeIgnoreArticle;
}
}
option = options.find("filter");
if (option != options.end())
{
CSmartPlaylist xspFilter;
if (!xspFilter.LoadFromJson(option->second.asString()))
return false;
// check if the filter playlist matches the item type
if (xspFilter.GetType() == type)
{
std::set<std::string> playlists;
filter.AppendWhere(xspFilter.GetWhereClause(*this, playlists));
}
// remove the filter if it doesn't match the item type
else
musicUrl.RemoveOption("filter");
}
return true;
}
void CMusicDatabase::UpdateFileDateAdded(int songId, const std::string& strFileNameAndPath)
{
if (songId < 0 || strFileNameAndPath.empty())
return;
CDateTime dateAdded;
try
{
if (NULL == m_pDB.get()) return;
if (NULL == m_pDS.get()) return;
// 1 prefering to use the files mtime(if it's valid) and only using the file's ctime if the mtime isn't valid
if (g_advancedSettings.m_iMusicLibraryDateAdded == 1)
dateAdded = CFileUtils::GetModificationDate(strFileNameAndPath, false);
//2 using the newer datetime of the file's mtime and ctime
else if (g_advancedSettings.m_iMusicLibraryDateAdded == 2)
dateAdded = CFileUtils::GetModificationDate(strFileNameAndPath, true);
//0 using the current datetime if non of the above matches or one returns an invalid datetime
if (!dateAdded.IsValid())
dateAdded = CDateTime::GetCurrentDateTime();
m_pDS->exec(PrepareSQL("UPDATE song SET dateAdded='%s' WHERE idSong=%d", dateAdded.GetAsDBDateTime().c_str(), songId));
}
catch (...)
{
CLog::Log(LOGERROR, "%s (%s, %s) failed", __FUNCTION__, CURL::GetRedacted(strFileNameAndPath).c_str(), dateAdded.GetAsDBDateTime().c_str());
}
}
|
EraYaN/xbmc
|
xbmc/music/MusicDatabase.cpp
|
C++
|
gpl-2.0
| 214,318
|
/*
* Copyright (C) NXP Semiconductors (PLMA)
*
* 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.
*/
#define DEBUG
#define pr_fmt(fmt) "%s(): " fmt, __func__
#include <linux/cdev.h>
#include <linux/clk.h>
#include <linux/delay.h>
#include <linux/firmware.h>
#include <linux/init.h>
#include <linux/i2c.h>
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/pm.h>
#include <linux/slab.h>
#include <linux/crc32.h>
#include <sound/sounddebug.h>
#include "tfa98xx-core.h"
#include "tfa98xx-regs.h"
#include "tfa_container.h"
#include "tfa_dsp.h"
int tfa_get_profile_count(struct nxpTfaDevice *dev)
{
int i, hit = 0;
if (!dev)
return 0;
for (i = 0, hit = 0; i < dev->length; i++)
if (dev->list[i].type == dscProfile)
hit++;
return hit;
}
struct nxpTfaVolumeStep2File *tfa_get_vsteps(struct tfa98xx *tfa98xx, struct nxpTfaProfile *prof)
{
u8 *base = tfa98xx->fw.base;
int i;
// pr_debug("\n");
for(i = 0; i < prof->length; i++) {
if ( prof->list[i].type == dscFile ) {
struct nxpTfaFileDsc *file = (struct nxpTfaFileDsc *)(prof->list[i].offset + base);
struct nxpTfaHeader *hdr = (struct nxpTfaHeader *)file->data;
if (hdr->id == volstepHdr) {
struct nxpTfaVolumeStep2File *vp = (struct nxpTfaVolumeStep2File *)hdr;
pr_debug("vsteps: %d\n", vp->vsteps);
return vp;
}
}
}
return NULL;
}
int tfa_init_profile(struct tfa98xx *tfa98xx, struct nxpTfaProfile *prof, int hit)
{
struct nxpTfaVolumeStep2File *vp;
u8 *base = tfa98xx->fw.base;
vp = tfa_get_vsteps(tfa98xx, prof);
if (vp) {
tfa98xx->profiles[hit].vp = vp;
tfa98xx->profiles[hit].vsteps = vp->vsteps;
}
tfa98xx->profiles[hit].profile = prof;
tfa98xx->profiles[hit].name = base + prof->name.offset;
tfa98xx->profiles[hit].index = hit;
pr_debug("Init profile %d: %s\n", hit, tfa98xx->profiles[hit].name);
return 0;
}
static char *filename = "tfa98xx.cnt";
module_param(filename, charp, 0);
int tfa98xx_cnt_loadfile(struct tfa98xx *tfa98xx, int index)
{
struct snd_soc_codec *codec = tfa98xx->codec;
u16 addr = tfa98xx->i2c->addr;
const struct firmware *container = NULL;
struct nxpTfaContainer *data;
int i, j, hit, ret;
u32 crc32;
u8 *base;
pr_debug("I2C device: 0x%x\n", addr);
/* Load DSP config and firmware files */
ret = request_firmware(&container, filename, codec->dev);
if (ret) {
pr_err("Failed to read %s", filename);
return ret;
}
pr_debug("loaded %s - size: %lu\n", filename, container ? container->size : 0);
data = (struct nxpTfaContainer *)container->data;
pr_debug("%.2s%.2s\n", data->version, data->subversion);
pr_debug("%.8s\n", data->customer);
pr_debug("%.8s\n", data->application);
pr_debug("%.8s\n", data->type);
pr_debug("%d ndev\n", data->ndev);
pr_debug("%d nprof\n", data->nprof);
if (*(u16*)data->id != params) {
pr_err("Wrong container type %.2s", (char *)&data->id);
return -EINVAL;
}
crc32 = ~crc32_le(~0, ((u8*)container->data)+14, container->size-14);
if (crc32 != data->CRC) {
pr_err("fw checksum test failed %x\n", crc32);
return -ENOEXEC;
}
base = (u8 *) data;
tfa98xx->fw.base = data;
for (i = 0; i < data->ndev; i++) {
struct nxpTfaDevice *dev;
struct nxpTfaProfile *prof;
struct nxpTfaFileDsc *dsc;
base = (u8*)data + data->index[i].offset;
dev = (struct nxpTfaDevice *)base;
/* Check if this is the proper device addr */
if (dev->dev != addr)
continue;
pr_debug("dev[0x%02x]: %s\n", dev->dev, (u8 *)data + dev->name.offset);
tfa98xx->fw.dev = (struct nxpTfaDevice *)base;
tfa98xx->fw.name = (u8 *)data + dev->name.offset;
tfa98xx->profile_count = tfa_get_profile_count(tfa98xx->fw.dev);
tfa98xx->profiles = devm_kzalloc(tfa98xx->codec->dev, tfa98xx->profile_count * sizeof(struct tfaprofile), GFP_KERNEL);
if (!tfa98xx->profiles)
return -ENOMEM;
for (j = 0, hit = 0; j < dev->length; j++) {
switch (dev->list[j].type) {
case dscProfile:
prof = (struct nxpTfaProfile *)((u8 *)data + dev->list[j].offset);
pr_debug("[%d] profile: %s\n", j, (u8 *)data + prof->name.offset);
tfa_init_profile(tfa98xx, prof, hit++);
break;
case dscFile:
case dscPatch:
dsc = (struct nxpTfaFileDsc *)((u8 *)data + dev->list[j].offset);
pr_debug("[%d] file: %s\n", j, (u8 *)data + dsc->name.offset);
break;
default:
//pr_debug("[%d] %d\n", j, dev->list[j].type);
break;
}
}
}
if (!tfa98xx->profiles) {
pr_err("[0x%02x] No profile data for the device\n", addr);
return -EINVAL;
}
return 0;
}
int tfa_get_vstep_count(struct tfa98xx *tfa98xx, struct nxpTfaProfile *prof)
{
u8 *base = tfa98xx->fw.base;
int i;
pr_debug("\n");
for(i = 0; i < prof->length; i++) {
if ( prof->list[i].type == dscFile ) {
struct nxpTfaFileDsc *file = (struct nxpTfaFileDsc *)(prof->list[i].offset + base);
struct nxpTfaHeader *hdr = (struct nxpTfaHeader *)file->data;
if (hdr->id == volstepHdr) {
struct nxpTfaVolumeStep2File *vp = (struct nxpTfaVolumeStep2File *)hdr;
pr_debug("vsteps: %d\n", vp->vsteps);
return vp->vsteps;
}
}
}
return 0;
}
struct nxpTfaProfile *tfaContProfile(struct tfa98xx *tfa98xx, int index)
{
struct nxpTfaDevice *dev = tfa98xx->fw.dev;
struct nxpTfaProfile *prof;
char *base = tfa98xx->fw.base;
int j, hit;
pr_debug("%d\n", index);
for (j = 0, hit = 0; j < dev->length; j++) {
if (dev->list[j].type == dscProfile) {
prof = (struct nxpTfaProfile *)(base + dev->list[j].offset);
if (hit++ == index) {
pr_debug("select profile[%d]='%s'\n", index, base + prof->name.offset);
return prof;
}
}
}
return NULL;
}
/*
* return the bitfield
*/
struct nxpTfaBitfield tfaContDsc2Bf(struct nxpTfaDescPtr dsc)
{
u32 *ptr = (u32 *) (&dsc);
union {
struct nxpTfaBitfield bf;
u32 num;
} num_bf;
num_bf.num = *ptr & TFA_BITFIELDDSCMSK;
return num_bf.bf;
}
TFA_NAMETABLE
char *tfaContBfName(u16 num)
{
int n = 0;
do {
if (TfaBfNames[n].bfEnum == num)
return TfaBfNames[n].bfName;
}
while (TfaBfNames[n++].bfEnum != 0xffff);
return TfaBfNames[n-1].bfName;
}
/*
* write reg and bitfield items in the profilelist the target
*/
int tfaContWriteRegsProf(struct tfa98xx *tfa98xx, int profile)
{
struct nxpTfaProfile *prof = tfaContProfile(tfa98xx, profile);
u8 *base = tfa98xx->fw.base;
int i;
int err = 0;
pr_debug("profile: %d\n", profile);
if (!prof) {
return -EINVAL;
}
/* process the list until a patch, file of profile is encountered */
for (i = 0; i < prof->length; i++) {
if ( prof->list[i].type == dscPatch ||
prof->list[i].type ==dscFile ||
prof->list[i].type ==dscProfile )
break;
if (prof->list[i].type & dscBitfieldBase) {
err = tfaRunWriteBitfield(tfa98xx, tfaContDsc2Bf(prof->list[i]));
}
if (prof->list[i].type & dscRegister) {
err = tfaRunWriteRegister(tfa98xx, (struct nxpTfaRegpatch *)(base + prof->list[i].offset));
}
if (err)
break;
}
return err;
}
/*
* write reg and bitfield items in the devicelist to the target
*/
int tfaContWriteRegsDev(struct tfa98xx *tfa98xx)
{
struct nxpTfaDevice *dev = tfa98xx->fw.dev;
u8 *base = tfa98xx->fw.base;
int i;
int err = 0;
pr_debug("\n");
if (!dev)
return -EINVAL;
/* process the list until a patch, file of profile is encountered */
for (i = 0; i < dev->length; i++) {
if (dev->list[i].type == dscPatch ||
dev->list[i].type ==dscFile ||
dev->list[i].type ==dscProfile)
break;
if (dev->list[i].type & dscBitfieldBase) {
err = tfaRunWriteBitfield(tfa98xx, tfaContDsc2Bf(dev->list[i]));
}
if (dev->list[i].type == dscRegister) {
pr_debug("reg %x\n", dev->list[i].type);
err = tfaRunWriteRegister(tfa98xx, (struct nxpTfaRegpatch *)(dev->list[i].offset + base));
}
if (err)
break;
}
return err;
}
/*
* show the contents of the header
*/
void tfaContShowHeader(struct tfa98xx *tfa98xx, struct nxpTfaHeader *hdr)
{
char id[2];
pr_debug("File header\n");
id[1] = hdr->id >> 8;
id[0] = hdr->id & 0xff;
pr_debug(" id:%.2s version:%.2s subversion:%.2s\n", id, hdr->version, hdr->subversion);
pr_debug(" size:%d CRC:0x%08x \n", hdr->size, hdr->CRC);
pr_debug(" customer:%.8s application:%.8s type:%.8s\n", hdr->customer, hdr->application, hdr->type);
}
/*
* write patchfile in the devicelist to the target
*/
int tfaContWritePatch(struct tfa98xx *tfa98xx)
{
struct nxpTfaDevice *dev = tfa98xx->fw.dev;
u8 *base = tfa98xx->fw.base;
struct nxpTfaFileDsc *file;
struct nxpTfaPatch *patchfile;
int size;
int i;
pr_debug("\n");
/* process the list until a patch is encountered */
for(i = 0; i < dev->length; i++) {
if (dev->list[i].type == dscPatch) {
file = (struct nxpTfaFileDsc *)(dev->list[i].offset + base);
patchfile =(struct nxpTfaPatch *)&file->data;
tfaContShowHeader(tfa98xx, &patchfile->hdr);
/* size is total length including header */
size = patchfile->hdr.size - sizeof(struct nxpTfaPatch);
return tfa98xx_dsp_patch(tfa98xx, size, (const u8*) patchfile->data);
}
}
return -EINVAL;
}
int tfaContWriteFilterbank(struct tfa98xx *tfa98xx, struct nxpTfaFilter *filter)
{
unsigned char biquad_index;
int ret = 0;
for (biquad_index = 0; biquad_index < 10; biquad_index++) {
if (filter[biquad_index].enabled) {
ret = tfa98xx_dsp_biquad_set_coeff(tfa98xx, biquad_index + 1, // start @1
sizeof(filter[biquad_index].biquad.bytes),
filter[biquad_index].biquad.bytes);
} else {
ret = tfa98xx_dsp_biquad_disable(tfa98xx, biquad_index+1);
}
if (ret) {
pr_err("Error %d\n", ret);
return ret;
}
}
return 0;
}
int tfaContWriteEq(struct tfa98xx *tfa98xx, struct nxpTfaEqualizerFile *eqf)
{
return tfaContWriteFilterbank(tfa98xx, eqf->filter);
}
/*
* write a parameter file to de device
*/
int tfaContWriteVstep(struct tfa98xx *tfa98xx, struct nxpTfaVolumeStep2File *vp)
{
int vstep;
int err = 0;
vstep = tfa98xx->vstep_current;
pr_debug("vstep[%d/%d]\n", vstep, vp->vsteps - 1);
if (vstep < vp->vsteps) {
tfa98xx_set_volume(tfa98xx, vp->vstep[vstep].attenuation);
err = tfa98xx_dsp_write_preset(tfa98xx, sizeof(vp->vstep[0].preset), vp->vstep[vstep].preset);
if (err)
return err;
err = tfaContWriteFilterbank(tfa98xx, vp->vstep[vstep].filter);
if (err)
return err;
} else {
pr_err("vstep[%d] > %d\n", vstep , vp->vsteps - 1);
return -EINVAL;
}
return err;
}
/*
* write a parameter file to the device
*/
int tfaContWriteFile(struct tfa98xx *tfa98xx, struct nxpTfaFileDsc *file)
{
int size;
struct nxpTfaHeader *hdr = (struct nxpTfaHeader *)file->data;
enum tfa_cnt_header_type type;
int err = 0;
type = hdr->id;
switch (type) {
case volstepHdr:
pr_debug("volstep\n");
err = tfaContWriteVstep(tfa98xx, (struct nxpTfaVolumeStep2File *)hdr);
break;
case speakerHdr:
pr_debug("speaker\n");
size = hdr->size - sizeof(struct nxpTfaSpeakerFile);
err = tfa98xx_dsp_write_speaker_parameters(tfa98xx, size, (const u8 *)((struct nxpTfaSpeakerFile *)hdr)->data);
break;
case presetHdr:
pr_debug("preset\n");
size = hdr->size - sizeof(struct nxpTfaPresetFile);
err = tfa98xx_dsp_write_preset(tfa98xx, size, (const u8 *)((struct nxpTfaPresetFile *)hdr)->data);
break;
case configHdr:
pr_debug("config\n");
size = hdr->size - sizeof(struct nxpTfaConfigFile);
err = tfa98xx_dsp_write_config(tfa98xx, size, (const u8 *)((struct nxpTfaConfigFile *)hdr)->data);
break;
case equalizerHdr:
pr_debug("equalizer\n");
tfaContWriteEq(tfa98xx, (struct nxpTfaEqualizerFile *) hdr);
break;
case patchHdr:
pr_debug("patch\n");
size = hdr->size - sizeof(struct nxpTfaPatch );
err = tfa98xx_dsp_patch(tfa98xx, size, (const u8 *)((struct nxpTfaPatch *)hdr)->data);
break;
case drcHdr:
/*
* The DRC file is split as:
* 36 bytes for generic header (customer, application, and type)
* 127x3 (381) bytes first block contains the device and sample rate
* independent settings
* 127x3 (381) bytes block the device and sample rate specific values.
* The second block can always be recalculated from the first block,
* if vlsCal and the sample rate are known.
*/
size = sizeof(struct drcParamBlock);
/* fixed size for first block */
err = tfa98xx_dsp_write_drc(tfa98xx, size, (const u8 *)((struct nxpTfaDrcFile *)hdr)->data);
break;
default:
pr_err("Header is of unknown type: 0x%x\n", type);
return -EINVAL;
}
return err;
}
int tfaContWriteItem(struct tfa98xx *tfa98xx, struct nxpTfaDescPtr * dsc)
{
struct nxpTfaFileDsc *file;
struct nxpTfaRegpatch *reg;
struct nxpTfaMode *mode;
u8 *base = tfa98xx->fw.base;
int ret = 0;
pr_debug("\n");
switch (dsc->type) {
case dscDevice:
case dscProfile:
/* ignore device and profile list */
break;
case dscRegister:
reg = (struct nxpTfaRegpatch *)(dsc->offset + base);
pr_debug("$0x%2x=0x%02x,0x%02x\n", reg->address, reg->mask, reg->value);
return tfaRunWriteRegister(tfa98xx, reg);
case dscString:
/* zero terminated string */
pr_debug(";string: %s\n", dsc->offset + base);
break;
case dscFile:
case dscPatch:
/* filename + file contents */
file = (struct nxpTfaFileDsc *)(dsc->offset + base);
pr_debug("file: %s\n", file->name.offset + base);
break;
case dscMode:
mode = (struct nxpTfaMode *)(dsc->offset + base);
if (mode->value == Tfa98xx_Mode_RCV)
tfa98xx_select_mode(tfa98xx, Tfa98xx_Mode_RCV);
else
tfa98xx_select_mode(tfa98xx, Tfa98xx_Mode_Normal);
pr_debug("mode = %d\n", mode->value);
break;
case dscCfMem:
ret = tfa98xx_write_dsp_mem(tfa98xx, (struct nxpTfaDspMem *)(dsc->offset + base));
if (ret)
ret = -EINVAL;
break;
case dscFilter:
ret = tfa98xx_write_filter(tfa98xx, (struct nxpTfaBiquadSettings *)(dsc->offset + base));
break;
default:
if (dsc->type & dscBitfieldBase)
return tfaRunWriteBitfield(tfa98xx , tfaContDsc2Bf(*dsc));
}
return ret;
}
/*
* process all items in the profilelist
* NOTE an error return during processing will leave the device muted
*/
int tfaContWriteProfile(struct tfa98xx *tfa98xx, int profile, int vstep)
{
struct nxpTfaProfile *prof = tfaContProfile(tfa98xx, profile);
struct nxpTfaFileDsc *file;
u8 *base = tfa98xx->fw.base;
int i;
pr_debug("\n");
if (!prof) {
return -EINVAL;
}
tfa98xx_mute(tfa98xx); /* this will wait for SWS */
tfa98xx_powerdown(tfa98xx, 1);
/* process and write registers first */
for(i=0; i<prof->length; i++) {
if ((prof->list[i].type == dscRegister)
|| (prof->list[i].type >= dscBitfieldBase)) {
if (tfaContWriteItem(tfa98xx, &prof->list[i]))
return -EINVAL;
}
}
/* power up CF */
tfa98xx_dsp_power_up(tfa98xx);
/* process and write all other items after power up of CF */
for(i=0; i<prof->length; i++) {
if ( prof->list[i].type == dscFile ) {
file = (struct nxpTfaFileDsc *)(prof->list[i].offset + base);
if (tfaContWriteFile(tfa98xx, file))
return -EINVAL;
} else if ((prof->list[i].type != dscRegister) &&
(prof->list[i].type < dscBitfieldBase)) {
if (tfaContWriteItem(tfa98xx, &prof->list[i]))
return -EINVAL;
}
}
return 0;
}
/*
* process only vstep in the profilelist
*
*/
int tfaContWriteFilesVstep(struct tfa98xx *tfa98xx, int profile, int vstep)
{
struct nxpTfaProfile *prof = tfaContProfile(tfa98xx, profile);
struct nxpTfaFileDsc *file;
struct nxpTfaHeader *hdr;
u8 *base = tfa98xx->fw.base;
unsigned int i;
int pwdn=-1;
int ret = 0;
if (!prof)
return -EINVAL;
for(i=0; i<prof->length; i++) {
if (prof->list[i].type == dscFile) {
if (pwdn<0)
pwdn = tfa98xx_is_pwdn(tfa98xx); // cache the value
if (pwdn) {
tfa98xx_dsp_power_up(tfa98xx);
pwdn=0;
}
file = (struct nxpTfaFileDsc *)(prof->list[i].offset + base);
hdr = (struct nxpTfaHeader *)file->data;
switch (hdr->id) {
case volstepHdr:
/* set current volume step to TFA */
ret = tfaContWriteVstep(tfa98xx, (struct nxpTfaVolumeStep2File *)hdr);
if (ret)
return ret;
break;
default:
break;
}
}
}
return ret;
}
/*
* write all param files in the profilelist to the target
* this is used during startup when may be ACS is set
*/
int tfaContWriteFilesProf(struct tfa98xx *tfa98xx, int profile, int vstep)
{
struct nxpTfaProfile *prof = tfaContProfile(tfa98xx, profile);
struct nxpTfaFileDsc *file;
u8 *base = tfa98xx->fw.base;
int i;
int ret = 0;
pr_debug("\n");
if (!prof) {
return -EINVAL;
}
/* process the list and write all files */
for(i = 0; i < prof->length; i++) {
switch (prof->list[i].type) {
case dscFile:
file = (struct nxpTfaFileDsc *)(prof->list[i].offset + base);
if (tfaContWriteFile(tfa98xx, file)) {
return -EINVAL;
}
break;
case dscCfMem:
ret = tfa98xx_write_dsp_mem(tfa98xx, (struct nxpTfaDspMem *)(prof->list[i].offset + base));
if (ret)
return -EINVAL;
break;
case dscFilter:
ret = tfa98xx_write_filter(tfa98xx, (struct nxpTfaBiquadSettings *)(prof->list[i].offset + base));
if (ret)
return ret;
break;
default:
/* ignore any other type */
break;
}
}
return 0;
}
/*
* write all param files in the devicelist to the target
*/
int tfaContWriteFiles(struct tfa98xx *tfa98xx)
{
struct nxpTfaDevice *dev = tfa98xx->fw.dev;
u8 *base = tfa98xx->fw.base;
struct nxpTfaFileDsc *file;
int ret = 0;
int i;
pr_debug("\n");
/* process the list and write all files */
for(i = 0; i < dev->length; i++) {
switch (dev->list[i].type) {
case dscFile:
file = (struct nxpTfaFileDsc *)(dev->list[i].offset + base);
if (tfaContWriteFile(tfa98xx, file)) {
pr_err("error\n");
return -EINVAL;
}
break;
case dscCfMem:
ret = tfa98xx_write_dsp_mem(tfa98xx, (struct nxpTfaDspMem *)(dev->list[i].offset + base));
if (ret)
return -EINVAL;
break;
default:
/* ignore any other type */
break;
}
}
return 0;
}
|
jcadduono/android_kernel_oneplus_msm8996
|
sound/soc/codecs/tfa9890/tfa_container.c
|
C
|
gpl-2.0
| 18,300
|
/*
* Copyright (c) 2009, 2013, 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.oracle.graal.compiler.hsail.test;
import org.junit.*;
import com.oracle.graal.compiler.hsail.test.infra.*;
/**
* Tests intrinsic for call to Math.abs(int). Generates an abs_s32 instruction.
*/
public class IntAbsTest extends GraalKernelTester {
static final int num = 20;
// Output array storing the results of negation operations.
@Result protected int[] outArray = new int[num];
/**
* The static "kernel" method we will be testing. This method calls Math.abs( ) on an element of
* an input array and writes the result to the corresponding index of an output array. By
* convention the gid is the last parameter.
*
* @param out the output array.
* @param ina the input array.
* @param gid the parameter used to index into the input and output arrays.
*/
public static void run(int[] out, int[] ina, int gid) {
out[gid] = Math.abs(ina[gid]);
}
/**
* Tests the HSAIL code generated for this unit test by comparing the result of executing this
* code with the result of executing a sequential Java version of this unit test.
*/
@Test
public void test() {
super.testGeneratedHsail();
}
/**
* Initializes the input and output arrays passed to the run routine.
*
* @param in the input array.
*/
void setupArrays(int[] in) {
// initialize input array with a mix of positive and negative values and any corner cases.
for (int i = 0; i < num; i++) {
if (i == 1) {
in[i] = Integer.MIN_VALUE;
} else {
in[i] = i < num / 2 ? i : -i;
}
outArray[i] = 0;
}
}
/**
* Dispatches the HSAIL kernel for this test case.
*/
@Override
public void runTest() {
int[] inArray = new int[num];
setupArrays(inArray);
dispatchMethodKernel(num, outArray, inArray);
}
}
|
smarr/graal
|
graal/com.oracle.graal.compiler.hsail.test/src/com/oracle/graal/compiler/hsail/test/IntAbsTest.java
|
Java
|
gpl-2.0
| 3,017
|
#ifndef _INET_DIAG_H_
#define _INET_DIAG_H_ 1
#include <specific_includes/uapi/linux/inet_diag.h>
struct sock;
struct inet_hashinfo;
struct nlattr;
struct nlmsghdr;
struct sk_buff;
struct netlink_callback;
struct inet_diag_handler {
void (*dump)(struct sk_buff *skb,
struct netlink_callback *cb,
struct inet_diag_req_v2 *r,
struct nlattr *bc);
int (*dump_one)(struct sk_buff *in_skb,
const struct nlmsghdr *nlh,
struct inet_diag_req_v2 *req);
void (*idiag_get_info)(struct sock *sk,
struct inet_diag_msg *r,
void *info);
__u16 idiag_type;
};
struct inet_connection_sock;
int inet_sk_diag_fill(struct sock *sk, struct inet_connection_sock *icsk,
struct sk_buff *skb, struct inet_diag_req_v2 *req,
struct user_namespace *user_ns,
u32 pid, u32 seq, u16 nlmsg_flags,
const struct nlmsghdr *unlh);
void inet_diag_dump_icsk(struct inet_hashinfo *h, struct sk_buff *skb,
struct netlink_callback *cb, struct inet_diag_req_v2 *r,
struct nlattr *bc);
int inet_diag_dump_one_icsk(struct inet_hashinfo *hashinfo,
struct sk_buff *in_skb, const struct nlmsghdr *nlh,
struct inet_diag_req_v2 *req);
int inet_diag_bc_sk(const struct nlattr *_bc, struct sock *sk);
extern int inet_diag_register(const struct inet_diag_handler *handler);
extern void inet_diag_unregister(const struct inet_diag_handler *handler);
#endif /* _INET_DIAG_H_ */
|
vadimsu/ipaugenblick
|
stack_and_service/specific_includes/linux/inet_diag.h
|
C
|
gpl-2.0
| 1,444
|
#!/usr/bin/env python
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from marvin.cloudstackTestCase import cloudstackTestCase, unittest
from marvin.cloudstackAPI import deleteAffinityGroup
from marvin.lib.utils import (cleanup_resources,
random_gen)
from marvin.lib.base import (Account,
Project,
ServiceOffering,
VirtualMachine,
AffinityGroup,
Domain)
from marvin.lib.common import (get_zone,
get_domain,
get_template,
list_hosts,
list_virtual_machines,
wait_for_cleanup)
from nose.plugins.attrib import attr
class Services:
"""Test Account Services
"""
def __init__(self):
self.services = {
"domain": {
"name": "NonRootDomain"
},
"domain_admin_account": {
"email": "newtest@test.com",
"firstname": "Test",
"lastname": "User",
"username": "doadmintest",
"password": "password"
},
"account": {
"email": "newtest@test.com",
"firstname": "Test",
"lastname": "User",
"username": "acc",
"password": "password"
},
"account_not_in_project": {
"email": "newtest@test.com",
"firstname": "Test",
"lastname": "User",
"username": "account_not_in_project",
"password": "password"
},
"project": {
"name": "Project",
"displaytext": "Project"
},
"project2": {
"name": "Project2",
"displaytext": "Project2"
},
"service_offering": {
"name": "Tiny Instance",
"displaytext": "Tiny Instance",
"cpunumber": 1,
"cpuspeed": 100,
"memory": 64
},
"ostype": 'CentOS 5.3 (64-bit)',
"host_anti_affinity": {
"name": "",
"type": "host anti-affinity"
},
"virtual_machine" : {
}
}
class TestCreateAffinityGroup(cloudstackTestCase):
"""
Test various scenarios for Create Affinity Group API for projects
"""
@classmethod
def setUpClass(cls):
cls.testClient = super(TestCreateAffinityGroup, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
#Get Zone, Domain and templates
cls.rootdomain = get_domain(cls.api_client)
cls.domain = Domain.create(cls.api_client, cls.services["domain"])
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.domain_admin_account = Account.create(
cls.api_client,
cls.services["domain_admin_account"],
domainid=cls.domain.id,
admin=True
)
cls.domain_api_client = cls.testClient.getUserApiClient(cls.domain_admin_account.name, cls.domain.name, 2)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.account_api_client = cls.testClient.getUserApiClient(cls.account.name, cls.domain.name, 0)
cls.account_not_in_project = Account.create(
cls.api_client,
cls.services["account_not_in_project"],
domainid=cls.domain.id
)
cls.account_not_in_project_api_client = cls.testClient.getUserApiClient(cls.account_not_in_project.name, cls.domain.name, 0)
cls.project = Project.create(
cls.api_client,
cls.services["project"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.project2 = Project.create(
cls.api_client,
cls.services["project2"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.debug("Created project with ID: %s" % cls.project.id)
cls.debug("Created project2 with ID: %s" % cls.project2.id)
# Add user to the project
cls.project.addAccount(
cls.api_client,
cls.account.name
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"],
domainid=cls.account.domainid
)
cls._cleanup = []
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
# #Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.apiclient, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
#Clean up, terminate the created templates
cls.domain.delete(cls.api_client, cleanup=True)
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def create_aff_grp(self, api_client=None, aff_grp=None, aff_grp_name=None, projectid=None):
if not api_client:
api_client = self.api_client
if aff_grp is None:
aff_grp = self.services["host_anti_affinity"]
if aff_grp_name is None:
aff_grp["name"] = "aff_grp_" + random_gen(size=6)
else:
aff_grp["name"] = aff_grp_name
if projectid is None:
projectid = self.project.id
try:
return AffinityGroup.create(api_client, aff_grp, None, None, projectid)
except Exception as e:
raise Exception("Error: Creation of Affinity Group failed : %s" % e)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_01_admin_create_aff_grp_for_project(self):
"""
Test create affinity group as admin in project
@return:
"""
aff_grp = self.create_aff_grp()
self.debug("Created Affinity Group: %s" % aff_grp.name)
list_aff_grps = AffinityGroup.list(self.api_client, id=aff_grp.id)
self.assert_(isinstance(list_aff_grps, list) and len(list_aff_grps) > 0)
self.assert_(list_aff_grps[0].id == aff_grp.id)
self.assert_(list_aff_grps[0].projectid == self.project.id)
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_02_doadmin_create_aff_grp_for_project(self):
"""
Test create affinity group as domain admin for projects
@return:
"""
aff_grp = self.create_aff_grp(api_client=self.domain_api_client)
list_aff_grps = AffinityGroup.list(self.domain_api_client, id=aff_grp.id)
self.assert_(isinstance(list_aff_grps, list) and len(list_aff_grps) > 0)
self.assert_(list_aff_grps[0].id == aff_grp.id)
self.assert_(list_aff_grps[0].projectid == self.project.id)
self.cleanup.append(aff_grp)
@attr(tags=["vogxn", "simulator", "basic", "advanced"], required_hardware="false")
def test_03_user_create_aff_grp_for_project(self):
"""
Test create affinity group as user for projects
@return:
"""
aff_grp = self.create_aff_grp(api_client=self.account_api_client)
list_aff_grps = AffinityGroup.list(self.api_client, id=aff_grp.id)
self.assert_(isinstance(list_aff_grps, list) and len(list_aff_grps) > 0)
self.assert_(list_aff_grps[0].id == aff_grp.id)
self.assert_(list_aff_grps[0].projectid == self.project.id)
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_4_user_create_aff_grp_existing_name_for_project(self):
"""
Test create affinity group that exists (same name) for projects
@return:
"""
failed_aff_grp = None
aff_grp = self.create_aff_grp(api_client=self.account_api_client)
with self.assertRaises(Exception):
failed_aff_grp = self.create_aff_grp(api_client=self.account_api_client,aff_grp_name = aff_grp.name)
if failed_aff_grp:
self.cleanup.append(failed_aff_grp)
self.cleanup.append(aff_grp)
class TestListAffinityGroups(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestListAffinityGroups, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
#Get Zone, Domain and templates
cls.rootdomain = get_domain(cls.api_client)
cls.domain = Domain.create(cls.api_client, cls.services["domain"])
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.domain_admin_account = Account.create(
cls.api_client,
cls.services["domain_admin_account"],
domainid=cls.domain.id,
admin=True
)
cls.domain_api_client = cls.testClient.getUserApiClient(cls.domain_admin_account.name, cls.domain.name, 2)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.account_api_client = cls.testClient.getUserApiClient(cls.account.name, cls.domain.name, 0)
cls.account_not_in_project = Account.create(
cls.api_client,
cls.services["account_not_in_project"],
domainid=cls.domain.id
)
cls.account_not_in_project_api_client = cls.testClient.getUserApiClient(cls.account_not_in_project.name, cls.domain.name, 0)
cls.project = Project.create(
cls.api_client,
cls.services["project"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.project2 = Project.create(
cls.api_client,
cls.services["project2"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.debug("Created project with ID: %s" % cls.project.id)
cls.debug("Created project2 with ID: %s" % cls.project2.id)
# Add user to the project
cls.project.addAccount(
cls.api_client,
cls.account.name
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"],
domainid=cls.account.domainid
)
cls._cleanup = []
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
# #Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
cls.domain.delete(cls.api_client, cleanup=True)
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def create_aff_grp(self, api_client=None, aff_grp=None, aff_grp_name=None, projectid=None):
if not api_client:
api_client = self.api_client
if aff_grp is None:
aff_grp = self.services["host_anti_affinity"]
if aff_grp_name is None:
aff_grp["name"] = "aff_grp_" + random_gen(size=6)
else:
aff_grp["name"] = aff_grp_name
if projectid is None:
projectid = self.project.id
try:
return AffinityGroup.create(api_client, aff_grp, None, None, projectid)
except Exception as e:
raise Exception("Error: Creation of Affinity Group failed : %s" % e)
def create_vm_in_aff_grps(self, api_client=None, ag_list=[], projectid=None):
self.debug('Creating VM in AffinityGroups=%s' % ag_list)
if api_client is None:
api_client = self.api_client
if projectid is None:
projectid = self.project.id
vm = VirtualMachine.create(
api_client,
self.services["virtual_machine"],
projectid=projectid,
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
affinitygroupnames=ag_list
)
self.debug('Created VM=%s in Affinity Group=%s' % (vm.id, tuple(ag_list)))
list_vm = list_virtual_machines(api_client, id=vm.id, projectid=projectid)
self.assertEqual(isinstance(list_vm, list), True,"Check list response returns a valid list")
self.assertNotEqual(len(list_vm),0, "Check VM available in List Virtual Machines")
vm_response = list_vm[0]
self.assertEqual(vm_response.state, 'Running',msg="VM is not in Running state")
self.assertEqual(vm_response.projectid, projectid,msg="VM is not in project")
return vm, vm_response.hostid
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_01_list_aff_grps_for_vm(self):
"""
List affinity group for a vm for projects
"""
aff_grps = []
aff_grps.append(self.create_aff_grp(self.domain_api_client, projectid=self.project.id))
vm, hostid = self.create_vm_in_aff_grps(self.account_api_client,ag_list=[aff_grps[0].name])
list_aff_grps = AffinityGroup.list(self.api_client,virtualmachineid=vm.id)
self.assertEqual(list_aff_grps[0].name, aff_grps[0].name,"Listing Affinity Group by VM id failed")
self.assertEqual(list_aff_grps[0].projectid, self.project.id,"Listing Affinity Group by VM id failed, vm was not in project")
vm.delete(self.api_client)
#Wait for expunge interval to cleanup VM
wait_for_cleanup(self.apiclient, ["expunge.delay", "expunge.interval"])
self.cleanup.append(aff_grps[0])
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_02_list_multiple_aff_grps_for_vm(self):
"""
List multiple affinity groups associated with a vm for projects
"""
aff_grp_01 = self.create_aff_grp(self.account_api_client)
aff_grp_02 = self.create_aff_grp(self.account_api_client)
aff_grps_names = [aff_grp_01.name, aff_grp_02.name]
vm, hostid = self.create_vm_in_aff_grps(ag_list=aff_grps_names)
list_aff_grps = AffinityGroup.list(self.api_client,
virtualmachineid=vm.id)
list_aff_grps_names = [list_aff_grps[0].name, list_aff_grps[1].name]
aff_grps_names.sort()
list_aff_grps_names.sort()
self.assertEqual(aff_grps_names, list_aff_grps_names,"One of the Affinity Groups is missing %s" % list_aff_grps_names)
vm.delete(self.api_client)
#Wait for expunge interval to cleanup VM
wait_for_cleanup(self.apiclient, ["expunge.delay", "expunge.interval"])
self.cleanup.append(aff_grp_01)
self.cleanup.append(aff_grp_02)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_03_list_aff_grps_by_id(self):
"""
List affinity groups by id for projects
"""
aff_grp = self.create_aff_grp(self.account_api_client)
list_aff_grps = AffinityGroup.list(self.account_api_client, id=aff_grp.id, projectid=self.project.id)
self.assertEqual(list_aff_grps[0].id, aff_grp.id,"Listing Affinity Group by id failed")
with self.assertRaises(Exception):
AffinityGroup.list(self.account_not_in_project_api_client, id=aff_grp.id, projectid=self.project.id)
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_04_list_aff_grps_by_name(self):
"""
List Affinity Groups by name for projects
"""
aff_grp = self.create_aff_grp(self.account_api_client)
list_aff_grps = AffinityGroup.list(self.account_api_client, name=aff_grp.name, projectid=self.project.id)
self.assertEqual(list_aff_grps[0].name, aff_grp.name,"Listing Affinity Group by name failed")
with self.assertRaises(Exception):
AffinityGroup.list(self.account_not_in_project_api_client, id=aff_grp.id, projectid=self.project.id)
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_05_list_aff_grps_by_non_existing_id(self):
"""
List Affinity Groups by non-existing id for projects
"""
aff_grp = self.create_aff_grp(self.account_api_client)
list_aff_grps = AffinityGroup.list(self.account_api_client, id=1234, projectid=self.project.id)
self.assertEqual(list_aff_grps, None, "Listing Affinity Group by non-existing id succeeded.")
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_06_list_aff_grps_by_non_existing_name(self):
"""
List Affinity Groups by non-existing name for projects
"""
aff_grp = self.create_aff_grp(self.account_api_client)
list_aff_grps = AffinityGroup.list(self.account_api_client, name="inexistantName", projectid=self.project.id)
self.assertEqual(list_aff_grps, None, "Listing Affinity Group by non-existing name succeeded.")
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_07_list_all_vms_in_aff_grp(self):
"""
List affinity group should list all for a vms associated with that group for projects
"""
aff_grp = self.create_aff_grp(self.account_api_client)
vm1, hostid1 = self.create_vm_in_aff_grps(ag_list=[aff_grp.name])
vm2, hostid2 = self.create_vm_in_aff_grps(ag_list=[aff_grp.name])
list_aff_grps = AffinityGroup.list(self.api_client, id=aff_grp.id, projectid=self.project.id)
self.assertEqual(list_aff_grps[0].name, aff_grp.name, "Listing Affinity Group by id failed")
self.assertEqual(list_aff_grps[0].virtualmachineIds[0], vm1.id, "List affinity group response.virtualmachineIds for group: %s doesn't contain vmid : %s" % (aff_grp.name, vm1.id))
self.assertEqual(list_aff_grps[0].virtualmachineIds[1], vm2.id, "List affinity group response.virtualmachineIds for group: %s doesn't contain vmid : %s" % (aff_grp.name, vm2.id))
vm1.delete(self.api_client)
vm2.delete(self.api_client)
#Wait for expunge interval to cleanup VM
wait_for_cleanup(self.apiclient, ["expunge.delay", "expunge.interval"])
self.cleanup.append(aff_grp)
class TestDeleteAffinityGroups(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestDeleteAffinityGroups, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
#Get Zone, Domain and templates
cls.rootdomain = get_domain(cls.api_client)
cls.domain = Domain.create(cls.api_client, cls.services["domain"])
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.domain_admin_account = Account.create(
cls.api_client,
cls.services["domain_admin_account"],
domainid=cls.domain.id,
admin=True
)
cls.domain_api_client = cls.testClient.getUserApiClient(cls.domain_admin_account.name, cls.domain.name, 2)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.account_api_client = cls.testClient.getUserApiClient(cls.account.name, cls.domain.name, 0)
cls.account_not_in_project = Account.create(
cls.api_client,
cls.services["account_not_in_project"],
domainid=cls.domain.id
)
cls.account_not_in_project_api_client = cls.testClient.getUserApiClient(cls.account_not_in_project.name, cls.domain.name, 0)
cls.project = Project.create(
cls.api_client,
cls.services["project"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.project2 = Project.create(
cls.api_client,
cls.services["project2"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.debug("Created project with ID: %s" % cls.project.id)
cls.debug("Created project2 with ID: %s" % cls.project2.id)
# Add user to the project
cls.project.addAccount(
cls.api_client,
cls.account.name
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"],
domainid=cls.account.domainid
)
cls._cleanup = []
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
# #Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
cls.domain.delete(cls.api_client, cleanup=True)
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def create_aff_grp(self, api_client=None, aff_grp=None, aff_grp_name=None, projectid=None):
if not api_client:
api_client = self.api_client
if aff_grp is None:
aff_grp = self.services["host_anti_affinity"]
if aff_grp_name is None:
aff_grp["name"] = "aff_grp_" + random_gen(size=6)
else:
aff_grp["name"] = aff_grp_name
if projectid is None:
projectid = self.project.id
try:
return AffinityGroup.create(api_client, aff_grp, None, None, projectid)
except Exception as e:
raise Exception("Error: Creation of Affinity Group failed : %s" % e)
def create_vm_in_aff_grps(self, api_client=None, ag_list=[], projectid=None):
self.debug('Creating VM in AffinityGroups=%s' % ag_list)
if api_client is None:
api_client = self.api_client
if projectid is None:
projectid = self.project.id
vm = VirtualMachine.create(
api_client,
self.services["virtual_machine"],
projectid=projectid,
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
affinitygroupnames=ag_list
)
self.debug('Created VM=%s in Affinity Group=%s' % (vm.id, tuple(ag_list)))
list_vm = list_virtual_machines(self.api_client, id=vm.id, projectid=projectid)
self.assertEqual(isinstance(list_vm, list), True,"Check list response returns an invalid list %s" % list_vm)
self.assertNotEqual(len(list_vm),0, "Check VM available in TestDeployVMAffinityGroups")
self.assertEqual(list_vm[0].id, vm.id,"Listed vm does not have the same ids")
vm_response = list_vm[0]
self.assertEqual(vm.state, 'Running',msg="VM is not in Running state")
self.assertEqual(vm.projectid, projectid,msg="VM is not in project")
self.assertNotEqual(vm_response.hostid, None, "Host id was null for vm %s" % vm_response)
return vm, vm_response.hostid
def delete_aff_group(self, apiclient, **kwargs):
cmd = deleteAffinityGroup.deleteAffinityGroupCmd()
[setattr(cmd, k, v) for k, v in kwargs.items()]
return apiclient.deleteAffinityGroup(cmd)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_01_delete_aff_grp_by_id(self):
"""
#Delete Affinity Group by id.
"""
aff_grp1 = self.create_aff_grp(self.account_api_client)
aff_grp2 = self.create_aff_grp(self.account_api_client)
aff_grp1.delete(self.account_api_client)
with self.assertRaises(Exception):
list_aff_grps = AffinityGroup.list(self.api_client, id=aff_grp1.id)
self.cleanup.append(aff_grp2)
@attr(tags=["simulator", "basic", "advanced"], required_hardware="false")
def test_02_delete_aff_grp_by_id_another_user(self):
"""
#Delete Affinity Group by id should fail for user not in project
"""
aff_grp1 = self.create_aff_grp(self.account_api_client)
aff_grp2 = self.create_aff_grp(self.account_api_client)
with self.assertRaises(Exception):
aff_grp1.delete(self.account_not_in_project_api_client)
self.cleanup.append(aff_grp1)
self.cleanup.append(aff_grp2)
class TestUpdateVMAffinityGroups(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestUpdateVMAffinityGroups, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
#Get Zone, Domain and templates
cls.rootdomain = get_domain(cls.api_client)
cls.domain = Domain.create(cls.api_client, cls.services["domain"])
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.domain_admin_account = Account.create(
cls.api_client,
cls.services["domain_admin_account"],
domainid=cls.domain.id,
admin=True
)
cls.domain_api_client = cls.testClient.getUserApiClient(cls.domain_admin_account.name, cls.domain.name, 2)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.account_api_client = cls.testClient.getUserApiClient(cls.account.name, cls.domain.name, 0)
cls.account_not_in_project = Account.create(
cls.api_client,
cls.services["account_not_in_project"],
domainid=cls.domain.id
)
cls.account_not_in_project_api_client = cls.testClient.getUserApiClient(cls.account_not_in_project.name, cls.domain.name, 0)
cls.project = Project.create(
cls.api_client,
cls.services["project"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.project2 = Project.create(
cls.api_client,
cls.services["project2"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.debug("Created project with ID: %s" % cls.project.id)
cls.debug("Created project2 with ID: %s" % cls.project2.id)
# Add user to the project
cls.project.addAccount(
cls.api_client,
cls.account.name
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"],
domainid=cls.account.domainid
)
cls._cleanup = []
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
# #Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
cls.domain.delete(cls.api_client, cleanup=True)
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def create_aff_grp(self, api_client=None, aff_grp=None, aff_grp_name=None, projectid=None):
if not api_client:
api_client = self.api_client
if aff_grp is None:
aff_grp = self.services["host_anti_affinity"]
if aff_grp_name is None:
aff_grp["name"] = "aff_grp_" + random_gen(size=6)
else:
aff_grp["name"] = aff_grp_name
if projectid is None:
projectid = self.project.id
try:
return AffinityGroup.create(api_client, aff_grp, None, None, projectid)
except Exception as e:
raise Exception("Error: Creation of Affinity Group failed : %s" % e)
def create_vm_in_aff_grps(self, api_client=None, ag_list=[], projectid=None):
self.debug('Creating VM in AffinityGroups=%s' % ag_list)
if api_client is None:
api_client = self.api_client
if projectid is None:
projectid = self.project.id
vm = VirtualMachine.create(
api_client,
self.services["virtual_machine"],
projectid=projectid,
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
affinitygroupnames=ag_list
)
self.debug('Created VM=%s in Affinity Group=%s' % (vm.id, tuple(ag_list)))
list_vm = list_virtual_machines(self.api_client, id=vm.id, projectid=projectid)
self.assertEqual(isinstance(list_vm, list), True,"Check list response returns an invalid list %s" % list_vm)
self.assertNotEqual(len(list_vm),0, "Check VM available in TestDeployVMAffinityGroups")
self.assertEqual(list_vm[0].id, vm.id,"Listed vm does not have the same ids")
vm_response = list_vm[0]
self.assertEqual(vm.state, 'Running',msg="VM is not in Running state")
self.assertEqual(vm.projectid, projectid,msg="VM is not in project")
self.assertNotEqual(vm_response.hostid, None, "Host id was null for vm %s" % vm_response)
return vm, vm_response.hostid
@attr(tags=["simulator", "basic", "advanced", "multihost"], required_hardware="false")
def test_01_update_aff_grp_by_ids(self):
"""
Update the list of affinityGroups by using affinity groupids
"""
aff_grp1 = self.create_aff_grp(self.account_api_client)
aff_grp2 = self.create_aff_grp(self.account_api_client)
vm1, hostid1 = self.create_vm_in_aff_grps(ag_list=[aff_grp1.name])
vm2, hostid2 = self.create_vm_in_aff_grps(ag_list=[aff_grp1.name])
vm1.stop(self.api_client)
list_aff_grps = AffinityGroup.list(self.api_client, projectid=self.project.id)
self.assertEqual(len(list_aff_grps), 2 , "2 affinity groups should be present")
vm1.update_affinity_group(self.api_client,affinitygroupids=[list_aff_grps[0].id,list_aff_grps[1].id])
list_aff_grps = AffinityGroup.list(self.api_client,virtualmachineid=vm1.id)
list_aff_grps_names = [list_aff_grps[0].name, list_aff_grps[1].name]
aff_grps_names = [aff_grp1.name, aff_grp2.name]
aff_grps_names.sort()
list_aff_grps_names.sort()
self.assertEqual(aff_grps_names, list_aff_grps_names,"One of the Affinity Groups is missing %s" % list_aff_grps_names)
vm1.start(self.api_client)
vm_status = VirtualMachine.list(self.api_client, id=vm1.id)
self.assertNotEqual(vm_status[0].hostid, hostid2, "The virtual machine started on host %s violating the host anti-affinity rule" %vm_status[0].hostid)
vm1.delete(self.api_client)
vm2.delete(self.api_client)
#Wait for expunge interval to cleanup VM
wait_for_cleanup(self.apiclient, ["expunge.delay", "expunge.interval"])
aff_grp1.delete(self.api_client)
aff_grp2.delete(self.api_client)
class TestDeployVMAffinityGroups(cloudstackTestCase):
@classmethod
def setUpClass(cls):
cls.testClient = super(TestDeployVMAffinityGroups, cls).getClsTestClient()
cls.api_client = cls.testClient.getApiClient()
cls.services = Services().services
#Get Zone, Domain and templates
cls.rootdomain = get_domain(cls.api_client)
cls.domain = Domain.create(cls.api_client, cls.services["domain"])
cls.zone = get_zone(cls.api_client, cls.testClient.getZoneForTests())
cls.template = get_template(
cls.api_client,
cls.zone.id,
cls.services["ostype"]
)
cls.services["virtual_machine"]["zoneid"] = cls.zone.id
cls.services["template"] = cls.template.id
cls.services["zoneid"] = cls.zone.id
cls.domain_admin_account = Account.create(
cls.api_client,
cls.services["domain_admin_account"],
domainid=cls.domain.id,
admin=True
)
cls.domain_api_client = cls.testClient.getUserApiClient(cls.domain_admin_account.name, cls.domain.name, 2)
cls.account = Account.create(
cls.api_client,
cls.services["account"],
domainid=cls.domain.id
)
cls.account_api_client = cls.testClient.getUserApiClient(cls.account.name, cls.domain.name, 0)
cls.account_not_in_project = Account.create(
cls.api_client,
cls.services["account_not_in_project"],
domainid=cls.domain.id
)
cls.account_not_in_project_api_client = cls.testClient.getUserApiClient(cls.account_not_in_project.name, cls.domain.name, 0)
cls.project = Project.create(
cls.api_client,
cls.services["project"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.project2 = Project.create(
cls.api_client,
cls.services["project2"],
account=cls.domain_admin_account.name,
domainid=cls.domain_admin_account.domainid
)
cls.debug("Created project with ID: %s" % cls.project.id)
cls.debug("Created project2 with ID: %s" % cls.project2.id)
# Add user to the project
cls.project.addAccount(
cls.api_client,
cls.account.name
)
cls.service_offering = ServiceOffering.create(
cls.api_client,
cls.services["service_offering"],
domainid=cls.account.domainid
)
cls._cleanup = []
return
def setUp(self):
self.apiclient = self.testClient.getApiClient()
self.dbclient = self.testClient.getDbConnection()
self.cleanup = []
def tearDown(self):
try:
# #Clean up, terminate the created instance, volumes and snapshots
cleanup_resources(self.api_client, self.cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
return
@classmethod
def tearDownClass(cls):
try:
cls.domain.delete(cls.api_client, cleanup=True)
cleanup_resources(cls.api_client, cls._cleanup)
except Exception as e:
raise Exception("Warning: Exception during cleanup : %s" % e)
def create_aff_grp(self, api_client=None, aff_grp=None, aff_grp_name=None, projectid=None):
if not api_client:
api_client = self.api_client
if aff_grp is None:
aff_grp = self.services["host_anti_affinity"]
if aff_grp_name is None:
aff_grp["name"] = "aff_grp_" + random_gen(size=6)
else:
aff_grp["name"] = aff_grp_name
if projectid is None:
projectid = self.project.id
try:
return AffinityGroup.create(api_client, aff_grp, None, None, projectid)
except Exception as e:
raise Exception("Error: Creation of Affinity Group failed : %s" % e)
def create_vm_in_aff_grps(self, api_client=None, ag_list=[], projectid=None):
self.debug('Creating VM in AffinityGroups=%s' % ag_list)
if api_client is None:
api_client = self.api_client
if projectid is None:
projectid = self.project.id
vm = VirtualMachine.create(
api_client,
self.services["virtual_machine"],
projectid=projectid,
templateid=self.template.id,
serviceofferingid=self.service_offering.id,
affinitygroupnames=ag_list
)
self.debug('Created VM=%s in Affinity Group=%s' % (vm.id, tuple(ag_list)))
list_vm = list_virtual_machines(self.api_client, id=vm.id, projectid=projectid)
self.assertEqual(isinstance(list_vm, list), True,"Check list response returns an invalid list %s" % list_vm)
self.assertNotEqual(len(list_vm),0, "Check VM available in TestDeployVMAffinityGroups")
self.assertEqual(list_vm[0].id, vm.id,"Listed vm does not have the same ids")
vm_response = list_vm[0]
self.assertEqual(vm.state, 'Running',msg="VM is not in Running state")
self.assertEqual(vm.projectid, projectid,msg="VM is not in project")
self.assertNotEqual(vm_response.hostid, None, "Host id was null for vm %s" % vm_response)
return vm, vm_response.hostid
@attr(tags=["simulator", "basic", "advanced", "multihost"], required_hardware="false")
def test_01_deploy_vm_anti_affinity_group(self):
"""
test DeployVM in anti-affinity groups
deploy VM1 and VM2 in the same host-anti-affinity groups
Verify that the vms are deployed on separate hosts
"""
aff_grp = self.create_aff_grp(self.account_api_client)
vm1, hostid1 = self.create_vm_in_aff_grps(self.account_api_client,ag_list=[aff_grp.name])
vm2, hostid2 = self.create_vm_in_aff_grps(self.account_api_client, ag_list=[aff_grp.name])
self.assertNotEqual(hostid1, hostid2, msg="Both VMs of affinity group %s are on the same host: %s , %s, %s, %s" % (aff_grp.name, vm1, hostid1, vm2, hostid2))
vm1.delete(self.api_client)
vm2.delete(self.api_client)
wait_for_cleanup(self.api_client, ["expunge.delay", "expunge.interval"])
self.cleanup.append(aff_grp)
@attr(tags=["simulator", "basic", "advanced", "multihost"], required_hardware="false")
def test_02_deploy_vm_anti_affinity_group_fail_on_not_enough_hosts(self):
"""
test DeployVM in anti-affinity groups with more vms than hosts.
"""
hosts = list_hosts(self.api_client, type="routing")
aff_grp = self.create_aff_grp(self.account_api_client)
vms = []
for host in hosts:
vms.append(self.create_vm_in_aff_grps(self.account_api_client,ag_list=[aff_grp.name]))
vm_failed = None
with self.assertRaises(Exception):
vm_failed = self.create_vm_in_aff_grps(self.account_api_client,ag_list=[aff_grp.name])
self.assertEqual(len(hosts), len(vms), "Received %s and %s " % (hosts, vms))
if vm_failed:
vm_failed.expunge(self.api_client)
self.cleanup.append(aff_grp)
|
ikoula/cloudstack
|
test/integration/component/test_affinity_groups_projects.py
|
Python
|
gpl-2.0
| 41,778
|
/*
* Copyright (c) 1997, 2012, 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. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* 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.xml.internal.xsom.impl.util;
import com.sun.xml.internal.xsom.XSAnnotation;
import com.sun.xml.internal.xsom.XSAttGroupDecl;
import com.sun.xml.internal.xsom.XSAttributeDecl;
import com.sun.xml.internal.xsom.XSAttributeUse;
import com.sun.xml.internal.xsom.XSComplexType;
import com.sun.xml.internal.xsom.XSContentType;
import com.sun.xml.internal.xsom.XSElementDecl;
import com.sun.xml.internal.xsom.XSFacet;
import com.sun.xml.internal.xsom.XSIdentityConstraint;
import com.sun.xml.internal.xsom.XSListSimpleType;
import com.sun.xml.internal.xsom.XSModelGroup;
import com.sun.xml.internal.xsom.XSModelGroupDecl;
import com.sun.xml.internal.xsom.XSNotation;
import com.sun.xml.internal.xsom.XSParticle;
import com.sun.xml.internal.xsom.XSRestrictionSimpleType;
import com.sun.xml.internal.xsom.XSSchema;
import com.sun.xml.internal.xsom.XSSchemaSet;
import com.sun.xml.internal.xsom.XSSimpleType;
import com.sun.xml.internal.xsom.XSType;
import com.sun.xml.internal.xsom.XSUnionSimpleType;
import com.sun.xml.internal.xsom.XSWildcard;
import com.sun.xml.internal.xsom.XSXPath;
import com.sun.xml.internal.xsom.impl.Const;
import com.sun.xml.internal.xsom.visitor.XSSimpleTypeVisitor;
import com.sun.xml.internal.xsom.visitor.XSTermVisitor;
import com.sun.xml.internal.xsom.visitor.XSVisitor;
import org.xml.sax.Locator;
import javax.swing.Box;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTree;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellRenderer;
import java.awt.Color;
import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.math.BigInteger;
import java.text.MessageFormat;
import java.util.Iterator;
/**
* Generates approximated tree model for XML from a schema component. This is
* not intended to be a fully-fledged round-trippable tree model.
*
* <h2>Usage of this class</h2>
*
* <ol> <li>Create a new instance.</li> <li>Call {@link
* #visit(com.sun.xml.internal.xsom.XSSchemaSet)} function on your schema set.>/li>
* <li>Retrieve the model using {@link #getModel()}. </li></ol>
*
* Every node in the resulting tree is a {@link SchemaTreeTraverser.SchemaTreeNode},
* and the model itself is {@link SchemaTreeTraverser.SchemaTreeModel}. You can
* use {@link SchemaTreeTraverser.SchemaTreeCellRenderer} as a cell renderer for
* your tree.
*
* @author Kirill Grouchnikov (kirillcool@yahoo.com)
*/
public class SchemaTreeTraverser implements XSVisitor, XSSimpleTypeVisitor {
/**
* The associated tree model.
*/
private SchemaTreeModel model;
/**
* The current node in the tree.
*/
private SchemaTreeNode currNode;
/**
* Tree model for schema hierarchy tree.
*
* @author Kirill Grouchnikov
*/
public static final class SchemaTreeModel extends DefaultTreeModel {
/**
* A simple constructor. Is made private to allow creating the root node
* first.
*
* @param root The root node.
*/
private SchemaTreeModel(SchemaRootNode root) {
super(root);
}
/**
* A factory method for creating a new empty tree.
*
* @return New empty tree model.
*/
public static SchemaTreeModel getInstance() {
SchemaRootNode root = new SchemaRootNode();
return new SchemaTreeModel(root);
}
public void addSchemaNode(SchemaTreeNode node) {
((SchemaRootNode) this.root).add(node);
}
}
/**
* The node of the schema hierarchy tree.
*
* @author Kirill Grouchnikov
*/
public static class SchemaTreeNode extends DefaultMutableTreeNode {
/**
* File name of the corresponding schema artifact.
*/
private String fileName;
/**
* Line number of the corresponding schema artifact.
*/
private int lineNumber;
/**
* The caption of the corresponding artifact.
*/
private String artifactName;
/**
* Simple constructor.
*
* @param artifactName Artifact name.
* @param locator Artifact locator.
*/
public SchemaTreeNode(String artifactName, Locator locator) {
this.artifactName = artifactName;
if (locator == null) {
this.fileName = null;
}
else {
String filename = locator.getSystemId();
filename = filename.replaceAll("\u002520", " ");
// strip leading protocol
if (filename.startsWith("file:/")) {
filename = filename.substring(6);
}
this.fileName = filename;
this.lineNumber = locator.getLineNumber() - 1;
}
}
/**
* Returns the caption for <code>this</code> node.
*
* @return The caption for <code>this</code> node.
*/
public String getCaption() {
return this.artifactName;
}
/**
* @return Returns the file name of the corresponding schema artifact.
*/
public String getFileName() {
return fileName;
}
/**
* @param fileName The file name of the corresponding schema artifact to
* set.
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @return Returns the line number of the corresponding schema
* artifact.
*/
public int getLineNumber() {
return lineNumber;
}
/**
* @param lineNumber The line number of the corresponding schema
* artifact to set.
*/
public void setLineNumber(int lineNumber) {
this.lineNumber = lineNumber;
}
}
/**
* The root node of the schema hierarchy tree.
*
* @author Kirill Grouchnikov
*/
public static class SchemaRootNode extends SchemaTreeNode {
/**
* A simple constructor.
*/
public SchemaRootNode() {
super("Schema set", null);
}
}
/**
* Sample cell renderer for the schema tree.
*
* @author Kirill Grouchnikov
*/
public static class SchemaTreeCellRenderer extends JPanel implements
TreeCellRenderer {
/**
* The icon label.
*/
protected final JLabel iconLabel;
/**
* The text label
*/
protected final JLabel nameLabel;
/**
* The selection indicator.
*/
private boolean isSelected;
/**
* Background color for selected cells (light brown).
*/
public final Color selectedBackground = new Color(255, 244, 232);
/**
* Foreground color for selected cells, both text and border (dark
* brown).
*/
public final Color selectedForeground = new Color(64, 32, 0);
/**
* Default font for the text label.
*/
public final Font nameFont = new Font("Arial", Font.BOLD, 12);
/**
* Simple constructor.
*/
public SchemaTreeCellRenderer() {
FlowLayout fl = new FlowLayout(FlowLayout.LEFT, 1, 1);
this.setLayout(fl);
this.iconLabel = new JLabel();
this.iconLabel.setOpaque(false);
this.iconLabel.setBorder(null);
this.add(this.iconLabel);
// add some space
this.add(Box.createHorizontalStrut(5));
this.nameLabel = new JLabel();
this.nameLabel.setOpaque(false);
this.nameLabel.setBorder(null);
this.nameLabel.setFont(nameFont);
this.add(this.nameLabel);
this.isSelected = false;
this.setOpaque(false);
this.setBorder(null);
}
/*
* (non-Javadoc)
*
* @see javax.swing.JComponent#paintComponent(java.awt.Graphics)
*/
public final void paintComponent(Graphics g) {
int width = this.getWidth();
int height = this.getHeight();
if (this.isSelected) {
g.setColor(selectedBackground);
g.fillRect(0, 0, width - 1, height - 1);
g.setColor(selectedForeground);
g.drawRect(0, 0, width - 1, height - 1);
}
super.paintComponent(g);
}
/**
* Sets values for the icon and text of <code>this</code> renderer.
*
* @param icon Icon to show.
* @param caption Text to show.
* @param selected Selection indicator. If <code>true</code>, the
* renderer will be shown with different background and
* border settings.
*/
protected final void setValues(Icon icon, String caption,
boolean selected) {
this.iconLabel.setIcon(icon);
this.nameLabel.setText(caption);
this.isSelected = selected;
if (selected) {
this.nameLabel.setForeground(selectedForeground);
}
else {
this.nameLabel.setForeground(Color.black);
}
}
/* (non-Javadoc)
* @see javax.swing.tree.TreeCellRenderer#getTreeCellRendererComponent(javax.swing.JTree, java.lang.Object, boolean, boolean, boolean, int, boolean)
*/
public final Component getTreeCellRendererComponent(JTree tree, Object value,
boolean selected, boolean expanded, boolean leaf, int row,
boolean hasFocus) {
if (value instanceof SchemaTreeNode) {
SchemaTreeNode stn = (SchemaTreeNode) value;
this.setValues(null, stn.getCaption(), selected);
return this;
}
throw new IllegalStateException("Unknown node");
}
}
/**
* Simple constructor.
*/
public SchemaTreeTraverser() {
this.model = SchemaTreeModel.getInstance();
this.currNode = (SchemaTreeNode) this.model.getRoot();
}
/**
* Retrieves the tree model of <code>this</code> traverser.
*
* @return Tree model of <code>this</code> traverser.
*/
public SchemaTreeModel getModel() {
return model;
}
/**
* Visits the root schema set.
*
* @param s Root schema set.
*/
public void visit(XSSchemaSet s) {
for (XSSchema schema : s.getSchemas()) {
schema(schema);
}
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#schema(com.sun.xml.internal.xsom.XSSchema)
*/
public void schema(XSSchema s) {
// QUICK HACK: don't print the built-in components
if (s.getTargetNamespace().equals(Const.schemaNamespace)) {
return;
}
SchemaTreeNode newNode = new SchemaTreeNode("Schema "
+ s.getLocator().getSystemId(), s.getLocator());
this.currNode = newNode;
this.model.addSchemaNode(newNode);
for (XSAttGroupDecl groupDecl : s.getAttGroupDecls().values()) {
attGroupDecl(groupDecl);
}
for (XSAttributeDecl attrDecl : s.getAttributeDecls().values()) {
attributeDecl(attrDecl);
}
for (XSComplexType complexType : s.getComplexTypes().values()) {
complexType(complexType);
}
for (XSElementDecl elementDecl : s.getElementDecls().values()) {
elementDecl(elementDecl);
}
for (XSModelGroupDecl modelGroupDecl : s.getModelGroupDecls().values()) {
modelGroupDecl(modelGroupDecl);
}
for (XSSimpleType simpleType : s.getSimpleTypes().values()) {
simpleType(simpleType);
}
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#attGroupDecl(com.sun.xml.internal.xsom.XSAttGroupDecl)
*/
public void attGroupDecl(XSAttGroupDecl decl) {
SchemaTreeNode newNode = new SchemaTreeNode("Attribute group \""
+ decl.getName() + "\"", decl.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
Iterator itr;
itr = decl.iterateAttGroups();
while (itr.hasNext()) {
dumpRef((XSAttGroupDecl) itr.next());
}
itr = decl.iterateDeclaredAttributeUses();
while (itr.hasNext()) {
attributeUse((XSAttributeUse) itr.next());
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/**
* Creates node of attribute group decalration reference.
*
* @param decl Attribute group decalration reference.
*/
public void dumpRef(XSAttGroupDecl decl) {
SchemaTreeNode newNode = new SchemaTreeNode("Attribute group ref \"{"
+ decl.getTargetNamespace() + "}" + decl.getName() + "\"", decl
.getLocator());
this.currNode.add(newNode);
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#attributeUse(com.sun.xml.internal.xsom.XSAttributeUse)
*/
public void attributeUse(XSAttributeUse use) {
XSAttributeDecl decl = use.getDecl();
String additionalAtts = "";
if (use.isRequired()) {
additionalAtts += " use=\"required\"";
}
if (use.getFixedValue() != null
&& use.getDecl().getFixedValue() == null) {
additionalAtts += " fixed=\"" + use.getFixedValue() + "\"";
}
if (use.getDefaultValue() != null
&& use.getDecl().getDefaultValue() == null) {
additionalAtts += " default=\"" + use.getDefaultValue() + "\"";
}
if (decl.isLocal()) {
// this is anonymous attribute use
dump(decl, additionalAtts);
}
else {
// reference to a global one
String str = MessageFormat.format(
"Attribute ref \"'{'{0}'}'{1}{2}\"", new Object[]{
decl.getTargetNamespace(), decl.getName(),
additionalAtts});
SchemaTreeNode newNode = new SchemaTreeNode(str, decl.getLocator());
this.currNode.add(newNode);
}
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#attributeDecl(com.sun.xml.internal.xsom.XSAttributeDecl)
*/
public void attributeDecl(XSAttributeDecl decl) {
dump(decl, "");
}
/**
* Creates node for attribute declaration with additional attributes.
*
* @param decl Attribute declaration.
* @param additionalAtts Additional attributes.
*/
private void dump(XSAttributeDecl decl, String additionalAtts) {
XSSimpleType type = decl.getType();
String str = MessageFormat.format("Attribute \"{0}\"{1}{2}{3}{4}",
new Object[]{
decl.getName(),
additionalAtts,
type.isLocal() ? "" : MessageFormat.format(
" type=\"'{'{0}'}'{1}\"", new Object[]{
type.getTargetNamespace(),
type.getName()}),
decl.getFixedValue() == null ? "" : " fixed=\""
+ decl.getFixedValue() + "\"",
decl.getDefaultValue() == null ? "" : " default=\""
+ decl.getDefaultValue() + "\""});
SchemaTreeNode newNode = new SchemaTreeNode(str, decl.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
if (type.isLocal()) {
simpleType(type);
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSContentTypeVisitor#simpleType(com.sun.xml.internal.xsom.XSSimpleType)
*/
public void simpleType(XSSimpleType type) {
String str = MessageFormat.format("Simple type {0}",
new Object[]{type.isLocal() ? "" : " name=\""
+ type.getName() + "\""});
SchemaTreeNode newNode = new SchemaTreeNode(str, type.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
type.visit((XSSimpleTypeVisitor) this);
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSSimpleTypeVisitor#listSimpleType(com.sun.xml.internal.xsom.XSListSimpleType)
*/
public void listSimpleType(XSListSimpleType type) {
XSSimpleType itemType = type.getItemType();
if (itemType.isLocal()) {
SchemaTreeNode newNode = new SchemaTreeNode("List", type
.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
simpleType(itemType);
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
else {
// global type
String str = MessageFormat.format("List itemType=\"'{'{0}'}'{1}\"",
new Object[]{itemType.getTargetNamespace(),
itemType.getName()});
SchemaTreeNode newNode = new SchemaTreeNode(str, itemType
.getLocator());
this.currNode.add(newNode);
}
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSSimpleTypeVisitor#unionSimpleType(com.sun.xml.internal.xsom.XSUnionSimpleType)
*/
public void unionSimpleType(XSUnionSimpleType type) {
final int len = type.getMemberSize();
StringBuffer ref = new StringBuffer();
for (int i = 0; i < len; i++) {
XSSimpleType member = type.getMember(i);
if (member.isGlobal()) {
ref.append(MessageFormat.format(" '{'{0}'}'{1}",
new Object[]{
member.getTargetNamespace(),
member.getName()}));
}
}
String name = (ref.length() == 0) ? "Union" : ("Union memberTypes=\""
+ ref + "\"");
SchemaTreeNode newNode = new SchemaTreeNode(name, type.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
for (int i = 0; i < len; i++) {
XSSimpleType member = type.getMember(i);
if (member.isLocal()) {
simpleType(member);
}
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSSimpleTypeVisitor#restrictionSimpleType(com.sun.xml.internal.xsom.XSRestrictionSimpleType)
*/
public void restrictionSimpleType(XSRestrictionSimpleType type) {
if (type.getBaseType() == null) {
// don't print anySimpleType
if (!type.getName().equals("anySimpleType")) {
throw new InternalError();
}
if (!Const.schemaNamespace.equals(type.getTargetNamespace())) {
throw new InternalError();
}
return;
}
XSSimpleType baseType = type.getSimpleBaseType();
String str = MessageFormat.format("Restriction {0}",
new Object[]{baseType.isLocal() ? "" : " base=\"{"
+ baseType.getTargetNamespace() + "}"
+ baseType.getName() + "\""});
SchemaTreeNode newNode = new SchemaTreeNode(str, baseType.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
if (baseType.isLocal()) {
simpleType(baseType);
}
Iterator itr = type.iterateDeclaredFacets();
while (itr.hasNext()) {
facet((XSFacet) itr.next());
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#facet(com.sun.xml.internal.xsom.XSFacet)
*/
public void facet(XSFacet facet) {
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat.format(
"{0} value=\"{1}\"", new Object[]{facet.getName(),
facet.getValue(), }),
facet.getLocator());
this.currNode.add(newNode);
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#notation(com.sun.xml.internal.xsom.XSNotation)
*/
public void notation(XSNotation notation) {
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat.format(
"Notation name='\"0}\" public =\"{1}\" system=\"{2}\"",
new Object[]{notation.getName(), notation.getPublicId(),
notation.getSystemId()}), notation.getLocator());
this.currNode.add(newNode);
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#complexType(com.sun.xml.internal.xsom.XSComplexType)
*/
public void complexType(XSComplexType type) {
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat.format(
"ComplexType {0}", new Object[]{type.isLocal() ? ""
: " name=\"" + type.getName() + "\""}), type
.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
// TODO: wildcard
if (type.getContentType().asSimpleType() != null) {
// simple content
SchemaTreeNode newNode2 = new SchemaTreeNode("Simple content", type
.getContentType().getLocator());
this.currNode.add(newNode2);
this.currNode = newNode2;
XSType baseType = type.getBaseType();
if (type.getDerivationMethod() == XSType.RESTRICTION) {
// restriction
String str = MessageFormat.format(
"Restriction base=\"<{0}>{1}\"", new Object[]{
baseType.getTargetNamespace(),
baseType.getName()});
SchemaTreeNode newNode3 = new SchemaTreeNode(str, baseType
.getLocator());
this.currNode.add(newNode3);
this.currNode = newNode3;
dumpComplexTypeAttribute(type);
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
else {
// extension
String str = MessageFormat.format(
"Extension base=\"<{0}>{1}\"", new Object[]{
baseType.getTargetNamespace(),
baseType.getName()});
SchemaTreeNode newNode3 = new SchemaTreeNode(str, baseType
.getLocator());
this.currNode.add(newNode3);
this.currNode = newNode3;
// check if have redefine tag
if ((type.getTargetNamespace().compareTo(
baseType.getTargetNamespace()) ==
0)
&& (type.getName().compareTo(baseType.getName()) == 0)) {
SchemaTreeNode newNodeRedefine = new SchemaTreeNode(
"redefine", type
.getLocator());
this.currNode.add(newNodeRedefine);
this.currNode = newNodeRedefine;
baseType.visit(this);
this.currNode =
(SchemaTreeNode) newNodeRedefine.getParent();
}
dumpComplexTypeAttribute(type);
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
else {
// complex content
SchemaTreeNode newNode2 = new SchemaTreeNode("Complex content",
type.getContentType().getLocator());
this.currNode.add(newNode2);
this.currNode = newNode2;
XSComplexType baseType = type.getBaseType().asComplexType();
if (type.getDerivationMethod() == XSType.RESTRICTION) {
// restriction
String str = MessageFormat.format(
"Restriction base=\"<{0}>{1}\"", new Object[]{
baseType.getTargetNamespace(),
baseType.getName()});
SchemaTreeNode newNode3 = new SchemaTreeNode(str,
baseType.getLocator());
this.currNode.add(newNode3);
this.currNode = newNode3;
type.getContentType().visit(this);
dumpComplexTypeAttribute(type);
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
else {
// extension
String str = MessageFormat.format(
"Extension base=\"'{'{0}'}'{1}\"", new Object[]{
baseType.getTargetNamespace(),
baseType.getName()});
SchemaTreeNode newNode3 = new SchemaTreeNode(str,
baseType.getLocator());
this.currNode.add(newNode3);
this.currNode = newNode3;
// check if have redefine tag
if ((type.getTargetNamespace().compareTo(
baseType.getTargetNamespace()) ==
0)
&& (type.getName().compareTo(baseType.getName()) == 0)) {
SchemaTreeNode newNodeRedefine = new SchemaTreeNode(
"redefine", type
.getLocator());
this.currNode.add(newNodeRedefine);
this.currNode = newNodeRedefine;
baseType.visit(this);
this.currNode =
(SchemaTreeNode) newNodeRedefine.getParent();
}
type.getExplicitContent().visit(this);
dumpComplexTypeAttribute(type);
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/**
* Creates node for complex type.
*
* @param type Complex type.
*/
private void dumpComplexTypeAttribute(XSComplexType type) {
Iterator itr;
itr = type.iterateAttGroups();
while (itr.hasNext()) {
dumpRef((XSAttGroupDecl) itr.next());
}
itr = type.iterateDeclaredAttributeUses();
while (itr.hasNext()) {
attributeUse((XSAttributeUse) itr.next());
}
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSTermVisitor#elementDecl(com.sun.xml.internal.xsom.XSElementDecl)
*/
public void elementDecl(XSElementDecl decl) {
elementDecl(decl, "");
}
/**
* Creates node for element declaration with additional attributes.
*
* @param decl Element declaration.
* @param extraAtts Additional attributes.
*/
private void elementDecl(XSElementDecl decl, String extraAtts) {
XSType type = decl.getType();
// TODO: various other attributes
String str = MessageFormat.format("Element name=\"{0}\"{1}{2}",
new Object[]{
decl.getName(),
type.isLocal() ? "" : " type=\"{"
+ type.getTargetNamespace() + "}"
+ type.getName() + "\"", extraAtts});
SchemaTreeNode newNode = new SchemaTreeNode(str, decl.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
if (type.isLocal()) {
if (type.isLocal()) {
type.visit(this);
}
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSTermVisitor#modelGroupDecl(com.sun.xml.internal.xsom.XSModelGroupDecl)
*/
public void modelGroupDecl(XSModelGroupDecl decl) {
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat.format(
"Group name=\"{0}\"", new Object[]{decl.getName()}),
decl.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
modelGroup(decl.getModelGroup());
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSTermVisitor#modelGroup(com.sun.xml.internal.xsom.XSModelGroup)
*/
public void modelGroup(XSModelGroup group) {
modelGroup(group, "");
}
/**
* Creates node for model group with additional attributes.
*
* @param group Model group.
* @param extraAtts Additional attributes.
*/
private void modelGroup(XSModelGroup group, String extraAtts) {
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat.format(
"{0}{1}", new Object[]{group.getCompositor(), extraAtts}),
group.getLocator());
this.currNode.add(newNode);
this.currNode = newNode;
final int len = group.getSize();
for (int i = 0; i < len; i++) {
particle(group.getChild(i));
}
this.currNode = (SchemaTreeNode) this.currNode.getParent();
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSContentTypeVisitor#particle(com.sun.xml.internal.xsom.XSParticle)
*/
public void particle(XSParticle part) {
BigInteger i;
StringBuffer buf = new StringBuffer();
i = part.getMaxOccurs();
if (i.equals(BigInteger.valueOf(XSParticle.UNBOUNDED))) {
buf.append(" maxOccurs=\"unbounded\"");
}
else {
if (!i.equals(BigInteger.ONE)) {
buf.append(" maxOccurs=\"" + i + "\"");
}
}
i = part.getMinOccurs();
if (!i.equals(BigInteger.ONE)) {
buf.append(" minOccurs=\"" + i + "\"");
}
final String extraAtts = buf.toString();
part.getTerm().visit(new XSTermVisitor() {
public void elementDecl(XSElementDecl decl) {
if (decl.isLocal()) {
SchemaTreeTraverser.this.elementDecl(decl, extraAtts);
}
else {
// reference
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat
.format("Element ref=\"'{'{0}'}'{1}\"{2}",
new Object[]{decl.getTargetNamespace(),
decl.getName(), extraAtts}),
decl.getLocator());
currNode.add(newNode);
}
}
public void modelGroupDecl(XSModelGroupDecl decl) {
// reference
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat
.format("Group ref=\"'{'{0}'}'{1}\"{2}", new Object[]{
decl.getTargetNamespace(), decl.getName(),
extraAtts}), decl.getLocator());
currNode.add(newNode);
}
public void modelGroup(XSModelGroup group) {
SchemaTreeTraverser.this.modelGroup(group, extraAtts);
}
public void wildcard(XSWildcard wc) {
SchemaTreeTraverser.this.wildcard(wc, extraAtts);
}
});
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSTermVisitor#wildcard(com.sun.xml.internal.xsom.XSWildcard)
*/
public void wildcard(XSWildcard wc) {
wildcard(wc, "");
}
/**
* Creates node for wild card with additional attributes.
*
* @param wc Wild card.
* @param extraAtts Additional attributes.
*/
private void wildcard(XSWildcard wc, String extraAtts) {
// TODO
SchemaTreeNode newNode = new SchemaTreeNode(MessageFormat.format(
"Any ", new Object[]{extraAtts}), wc.getLocator());
currNode.add(newNode);
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#annotation(com.sun.xml.internal.xsom.XSAnnotation)
*/
public void annotation(XSAnnotation ann) {
// TODO: it would be nice even if we just put <xs:documentation>
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSContentTypeVisitor#empty(com.sun.xml.internal.xsom.XSContentType)
*/
public void empty(XSContentType t) {
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#identityConstraint(com.sun.xml.internal.xsom.XSIdentityConstraint)
*/
public void identityConstraint(XSIdentityConstraint ic) {
}
/* (non-Javadoc)
* @see com.sun.xml.internal.xsom.visitor.XSVisitor#xpath(com.sun.xml.internal.xsom.XSXPath)
*/
public void xpath(XSXPath xp) {
}
}
|
universsky/openjdk
|
jaxws/src/jdk.xml.bind/share/classes/com/sun/xml/internal/xsom/impl/util/SchemaTreeTraverser.java
|
Java
|
gpl-2.0
| 35,056
|
#!/bin/bash
# ----------------------------------------------------------------------
# Start up the Editra application bundle, passing along any
# command-line args. (Mac OS X only)
# ----------------------------------------------------------------------
#set -o xtrace
if [ "$1" = "-c" ]; then
# Use AppleScript to load the file(s) into a currently running Editra
shift
for f in "$@"; do
ABSPATH=`readlink -f $f`
osascript -e "tell app \"Editra\" to open (POSIX file \"$ABSPATH\")"
done
exit 0
fi
# Otherwise, start a new instance of Editra, passing the files on the command
# line. First find the app bundle.
if [ -z "$EDITRA_APP_DIR" ]; then
myDir=`dirname "$0"`
for i in ~/Applications $myDir $myDir/dist /Applications /Applications/MyApps/Editors; do
if [ -x "$i/Editra.app" ]; then
EDITRA_APP_DIR="$i"
break
fi
done
fi
if [ -z "$EDITRA_APP_DIR" ];then
echo "Sorry, cannot find Edita.app. Try setting the EDITRA_APP_DIR"
echo "environment variable to the folder containing Editra.app."
exit 1
fi
binary="$EDITRA_APP_DIR/Editra.app/Contents/MacOS/Editra"
# Use readlink to ensure that we have absolute pathnames for each arg,
# adding each result to an array
declare -a A
for f in ${1:+"$@"}; do
A=( "${A[@]}" "`readlink -f "$f"`" )
done
# Execute the binary, expanding the array on the command line.
exec "$binary" "${A[@]}"
# ----------------------------------------------------------------------
|
garrettcap/Bulletproof-Backup
|
wx/tools/Editra/scripts/editramac.sh
|
Shell
|
gpl-2.0
| 1,462
|
//===-- sanitizer_platform_interceptors.h -----------------------*- C++ -*-===//
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines macro telling whether sanitizer tools can/should intercept
// given library functions on a given platform.
//
//===----------------------------------------------------------------------===//
#ifndef SANITIZER_PLATFORM_INTERCEPTORS_H
#define SANITIZER_PLATFORM_INTERCEPTORS_H
#include "sanitizer_internal_defs.h"
#if !SANITIZER_WINDOWS
# define SI_NOT_WINDOWS 1
# include "sanitizer_platform_limits_posix.h"
#else
# define SI_NOT_WINDOWS 0
#endif
#if SANITIZER_LINUX && !SANITIZER_ANDROID
# define SI_LINUX_NOT_ANDROID 1
#else
# define SI_LINUX_NOT_ANDROID 0
#endif
#if SANITIZER_LINUX
# define SI_LINUX 1
#else
# define SI_LINUX 0
#endif
#if SANITIZER_MAC
# define SI_MAC 1
#else
# define SI_MAC 0
#endif
# define SANITIZER_INTERCEPT_STRCMP 1
# define SANITIZER_INTERCEPT_STRCASECMP SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_READ SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_PREAD SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_WRITE SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_PWRITE SI_NOT_WINDOWS
#define SANITIZER_INTERCEPT_PREAD64 SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_PWRITE64 SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_READV SI_NOT_WINDOWS
#define SANITIZER_INTERCEPT_WRITEV SI_NOT_WINDOWS
#define SANITIZER_INTERCEPT_PREADV SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_PWRITEV SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_PREADV64 SI_LINUX_NOT_ANDROID
#define SANITIZER_INTERCEPT_PWRITEV64 SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_PRCTL SI_LINUX
# define SANITIZER_INTERCEPT_LOCALTIME_AND_FRIENDS SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_SCANF SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_ISOC99_SCANF SI_LINUX
# define SANITIZER_INTERCEPT_FREXP 1
# define SANITIZER_INTERCEPT_FREXPF_FREXPL SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETPWNAM_AND_FRIENDS SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETPWNAM_R_AND_FRIENDS \
SI_MAC || SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_CLOCK_GETTIME SI_LINUX
# define SANITIZER_INTERCEPT_GETITIMER SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_TIME SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GLOB SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_WAIT SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_INET SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_PTHREAD_GETSCHEDPARAM SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETADDRINFO SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETNAMEINFO SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETSOCKNAME SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETHOSTBYNAME SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETHOSTBYNAME_R SI_LINUX
# define SANITIZER_INTERCEPT_GETSOCKOPT SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_ACCEPT SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_ACCEPT4 SI_LINUX
# define SANITIZER_INTERCEPT_MODF SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_RECVMSG SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETPEERNAME SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_IOCTL SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_INET_ATON SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_SYSINFO SI_LINUX
# define SANITIZER_INTERCEPT_READDIR SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_READDIR64 SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_PTRACE SI_LINUX_NOT_ANDROID && \
(defined(__i386) || defined (__x86_64)) // NOLINT
# define SANITIZER_INTERCEPT_SETLOCALE SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GETCWD SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_GET_CURRENT_DIR_NAME SI_LINUX
# define SANITIZER_INTERCEPT_STRTOIMAX SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_MBSTOWCS SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_MBSNRTOWCS SI_MAC || SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_WCSTOMBS SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_WCSNRTOMBS SI_MAC || SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_TCGETATTR SI_LINUX
# define SANITIZER_INTERCEPT_REALPATH SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_CANONICALIZE_FILE_NAME SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_CONFSTR SI_MAC || SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_SCHED_GETAFFINITY SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_STRERROR SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_STRERROR_R SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_SCANDIR SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_SCANDIR64 SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_GETGROUPS SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_POLL SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_PPOLL SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_WORDEXP SI_MAC || SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_SIGWAIT SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_SIGWAITINFO SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_SIGTIMEDWAIT SI_LINUX_NOT_ANDROID
# define SANITIZER_INTERCEPT_SIGSETOPS SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_SIGPENDING SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_SIGPROCMASK SI_NOT_WINDOWS
# define SANITIZER_INTERCEPT_BACKTRACE SI_LINUX_NOT_ANDROID
#endif // #ifndef SANITIZER_PLATFORM_INTERCEPTORS_H
|
cameron581/sabermod_rom_toolchain
|
libsanitizer/sanitizer_common/sanitizer_platform_interceptors.h
|
C
|
gpl-2.0
| 5,254
|
/*-
* Copyright (c) 1982, 1988, 1991, 1993
* The Regents of the University of California. All rights reserved.
* (c) UNIX System Laboratories, Inc.
* All or some portions of this file are derived from material licensed
* to the University of California by American Telephone and Telegraph
* Co. or Unix System Laboratories, Inc. and are reproduced herein with
* the permission of UNIX System Laboratories, Inc.
*
* 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.
* 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.
*
* @(#)systm.h 8.7 (Berkeley) 3/29/95
* $FreeBSD: src/sys/sys/systm.h,v 1.213.2.4 2005/03/03 00:46:32 wes Exp $
*/
#ifndef _SYS_SYSTM_H_
#define _SYS_SYSTM_H_
#include <machine/atomic.h>
#include <machine/cpufunc.h>
#include <sys/callout.h>
#include <sys/cdefs.h>
#include <sys/queue.h>
#include <sys/stdint.h> /* for people using printf mainly */
extern int securelevel; /* system security level (see init(8)) */
extern int suser_enabled; /* suser() is permitted to return 0 */
extern int cold; /* nonzero if we are doing a cold boot */
extern const char *panicstr; /* panic message */
extern char version[]; /* system version */
extern char copyright[]; /* system copyright */
extern int kstack_pages; /* number of kernel stack pages */
extern int nswap; /* size of swap space */
extern u_int nselcoll; /* select collisions since boot */
extern struct mtx sellock; /* select lock variable */
extern struct cv selwait; /* select conditional variable */
extern long physmem; /* physical memory */
extern long realmem; /* 'real' memory */
extern struct cdev *rootdev; /* root device */
extern char *rootdevnames[2]; /* names of possible root devices */
extern int boothowto; /* reboot flags, from console subsystem */
extern int bootverbose; /* nonzero to print verbose messages */
extern int maxusers; /* system tune hint */
#ifdef INVARIANTS /* The option is always available */
#define KASSERT(exp,msg) do { \
if (__predict_false(!(exp))) \
panic msg; \
} while (0)
#else
#define KASSERT(exp,msg)
#endif
#ifndef CTASSERT /* Allow lint to override */
#define CTASSERT(x) _CTASSERT(x, __LINE__)
#define _CTASSERT(x, y) __CTASSERT(x, y)
#define __CTASSERT(x, y) typedef char __assert ## y[(x) ? 1 : -1]
#endif
/*
* XXX the hints declarations are even more misplaced than most declarations
* in this file, since they are needed in one file (per arch) and only used
* in two files.
* XXX most of these variables should be const.
*/
extern int envmode;
extern int hintmode; /* 0 = off. 1 = config, 2 = fallback */
extern int dynamic_kenv;
extern struct sx kenv_lock;
extern char *kern_envp;
extern char static_env[];
extern char static_hints[]; /* by config for now */
extern char **kenvp;
/*
* General function declarations.
*/
struct clockframe;
struct malloc_type;
struct mtx;
struct proc;
struct kse;
struct socket;
struct thread;
struct tty;
struct ucred;
struct uio;
struct _jmp_buf;
int setjmp(struct _jmp_buf *);
void longjmp(struct _jmp_buf *, int) __dead2;
int dumpstatus(vm_offset_t addr, off_t count);
int nullop(void);
int eopnotsupp(void);
int ureadc(int, struct uio *);
void hashdestroy(void *, struct malloc_type *, u_long);
void *hashinit(int count, struct malloc_type *type, u_long *hashmask);
void *phashinit(int count, struct malloc_type *type, u_long *nentries);
void g_waitidle(void);
#ifdef RESTARTABLE_PANICS
void panic(const char *, ...) __printflike(1, 2);
#else
void panic(const char *, ...) __dead2 __printflike(1, 2);
#endif
void cpu_boot(int);
void cpu_rootconf(void);
extern uint32_t crc32_tab[];
uint32_t crc32(const void *buf, size_t size);
void critical_enter(void);
void critical_exit(void);
void init_param1(void);
void init_param2(long physpages);
void init_param3(long kmempages);
void tablefull(const char *);
int kvprintf(char const *, void (*)(int, void*), void *, int,
__va_list) __printflike(1, 0);
void log(int, const char *, ...) __printflike(2, 3);
void log_console(struct uio *);
int printf(const char *, ...) __printflike(1, 2);
int snprintf(char *, size_t, const char *, ...) __printflike(3, 4);
int sprintf(char *buf, const char *, ...) __printflike(2, 3);
int uprintf(const char *, ...) __printflike(1, 2);
int vprintf(const char *, __va_list) __printflike(1, 0);
int vsnprintf(char *, size_t, const char *, __va_list) __printflike(3, 0);
int vsnrprintf(char *, size_t, int, const char *, __va_list) __printflike(4, 0);
int vsprintf(char *buf, const char *, __va_list) __printflike(2, 0);
int ttyprintf(struct tty *, const char *, ...) __printflike(2, 3);
int sscanf(const char *, char const *, ...) __nonnull(1) __nonnull(2);
int vsscanf(const char *, char const *, __va_list) __nonnull(1) __nonnull(2);
long strtol(const char *, char **, int) __nonnull(1);
u_long strtoul(const char *, char **, int) __nonnull(1);
quad_t strtoq(const char *, char **, int) __nonnull(1);
u_quad_t strtouq(const char *, char **, int) __nonnull(1);
void tprintf(struct proc *p, int pri, const char *, ...) __printflike(3, 4);
void hexdump(void *ptr, int length, const char *hdr, int flags);
#define HD_COLUMN_MASK 0xff
#define HD_DELIM_MASK 0xff00
#define HD_OMIT_COUNT (1 << 16)
#define HD_OMIT_HEX (1 << 17)
#define HD_OMIT_CHARS (1 << 18)
#define ovbcopy(f, t, l) bcopy((f), (t), (l))
void bcopy(const void *from, void *to, size_t len) __nonnull(1) __nonnull(2);
void bzero(void *buf, size_t len) __nonnull(1);
void *memcpy(void *to, const void *from, size_t len) __nonnull(1) __nonnull(2);
int copystr(const void * __restrict kfaddr, void * __restrict kdaddr,
size_t len, size_t * __restrict lencopied)
__nonnull(1) __nonnull(2);
int copyinstr(const void * __restrict udaddr, void * __restrict kaddr,
size_t len, size_t * __restrict lencopied)
__nonnull(1) __nonnull(2);
int copyin(const void * __restrict udaddr, void * __restrict kaddr,
size_t len) __nonnull(1) __nonnull(2);
int copyout(const void * __restrict kaddr, void * __restrict udaddr,
size_t len) __nonnull(1) __nonnull(2);
int fubyte(const void *base);
long fuword(const void *base);
int fuword16(void *base);
int32_t fuword32(const void *base);
int64_t fuword64(const void *base);
int subyte(void *base, int byte);
int suword(void *base, long word);
int suword16(void *base, int word);
int suword32(void *base, int32_t word);
int suword64(void *base, int64_t word);
intptr_t casuptr(intptr_t *p, intptr_t old, intptr_t new);
void realitexpire(void *);
void hardclock(struct clockframe *frame);
void hardclock_process(struct clockframe *frame);
void softclock(void *);
void statclock(struct clockframe *frame);
void profclock(struct clockframe *frame);
void startprofclock(struct proc *);
void stopprofclock(struct proc *);
void cpu_startprofclock(void);
void cpu_stopprofclock(void);
/* flags for suser() and suser_cred() */
#define SUSER_ALLOWJAIL 1
#define SUSER_RUID 2
int suser(struct thread *td);
int suser_cred(struct ucred *cred, int flag);
int cr_cansee(struct ucred *u1, struct ucred *u2);
int cr_canseesocket(struct ucred *cred, struct socket *so);
char *getenv(const char *name);
void freeenv(char *env);
int getenv_int(const char *name, int *data);
long getenv_long(const char *name, long *data);
unsigned long getenv_ulong(const char *name, unsigned long *data);
int getenv_string(const char *name, char *data, int size);
int getenv_quad(const char *name, quad_t *data);
int setenv(const char *name, const char *value);
int unsetenv(const char *name);
int testenv(const char *name);
#ifdef APM_FIXUP_CALLTODO
struct timeval;
void adjust_timeout_calltodo(struct timeval *time_change);
#endif /* APM_FIXUP_CALLTODO */
#include <sys/libkern.h>
/* Initialize the world */
void consinit(void);
void cpu_initclocks(void);
void usrinfoinit(void);
/* Finalize the world. */
void shutdown_nice(int);
/*
* Kernel to clock driver interface.
*/
void inittodr(time_t base);
void resettodr(void);
void startrtclock(void);
/* Timeouts */
typedef void timeout_t(void *); /* timeout function type */
#define CALLOUT_HANDLE_INITIALIZER(handle) \
{ NULL }
void callout_handle_init(struct callout_handle *);
struct callout_handle timeout(timeout_t *, void *, int);
void untimeout(timeout_t *, void *, struct callout_handle);
caddr_t kern_timeout_callwheel_alloc(caddr_t v);
void kern_timeout_callwheel_init(void);
/* Stubs for obsolete functions that used to be for interrupt management */
static __inline void spl0(void) { return; }
static __inline intrmask_t splbio(void) { return 0; }
static __inline intrmask_t splcam(void) { return 0; }
static __inline intrmask_t splclock(void) { return 0; }
static __inline intrmask_t splhigh(void) { return 0; }
static __inline intrmask_t splimp(void) { return 0; }
static __inline intrmask_t splnet(void) { return 0; }
static __inline intrmask_t splsoftcam(void) { return 0; }
static __inline intrmask_t splsoftclock(void) { return 0; }
static __inline intrmask_t splsofttty(void) { return 0; }
static __inline intrmask_t splsoftvm(void) { return 0; }
static __inline intrmask_t splsofttq(void) { return 0; }
static __inline intrmask_t splstatclock(void) { return 0; }
static __inline intrmask_t spltty(void) { return 0; }
static __inline intrmask_t splvm(void) { return 0; }
static __inline void splx(intrmask_t ipl __unused) { return; }
/*
* Various callout lists.
*/
/*
* Not exactly a callout LIST, but a callout entry.
* Allow an external module to define a hardware watchdog tickler.
* Normally a process would do this, but there are times when the
* kernel needs to be able to hold off the watchdog, when the process
* is not active, e.g., when dumping core.
*/
typedef void (*watchdog_tickle_fn)(void);
extern watchdog_tickle_fn wdog_tickler;
/*
* Common `proc' functions are declared here so that proc.h can be included
* less often.
*/
int msleep(void *chan, struct mtx *mtx, int pri, const char *wmesg,
int timo);
#define tsleep(chan, pri, wmesg, timo) msleep(chan, NULL, pri, wmesg, timo)
void wakeup(void *chan) __nonnull(1);
void wakeup_one(void *chan) __nonnull(1);
/*
* Common `struct cdev *' stuff are declared here to avoid #include poisoning
*/
int major(struct cdev *x);
int minor(struct cdev *x);
dev_t dev2udev(struct cdev *x);
struct cdev *findcdev(dev_t x);
int uminor(dev_t dev);
int umajor(dev_t dev);
/* XXX: Should be void nanodelay(u_int nsec); */
void DELAY(int usec);
#endif /* !_SYS_SYSTM_H_ */
|
binhqnguyen/lena
|
nsc/freebsd5/freebsd/usr/src/sys/sys/systm.h
|
C
|
gpl-2.0
| 11,828
|
<?php
add_action( 'admin_menu', 'bearded_theme_admin_setup' );
function bearded_theme_admin_setup() {
/* Get the theme prefix. */
$prefix = hybrid_get_prefix();
/* Create a settings meta box only on the theme settings page. */
add_action( 'load-appearance_page_theme-settings', 'bearded_theme_settings_meta_boxes' );
/* Add a filter to validate/sanitize your settings. */
add_filter( "sanitize_option_{$prefix}_theme_settings", 'bearded_theme_validate_settings' );
}
/* Adds custom meta boxes to the theme settings page. */
function bearded_theme_settings_meta_boxes() {
/* Add a custom meta box. */
add_meta_box(
'bearded-social-meta-box', // Custom meta box ID
__( 'Social Settings', 'bearded' ), // Custom label
'bearded_social_meta_box', // Custom callback function
'appearance_page_theme-settings', // Page to load on, leave as is
'normal', // normal / advanced / side
'high' // high / low
);
/* Add additional add_meta_box() calls here. */
}
/* Validates theme settings. */
function bearded_theme_validate_settings( $input ) {
$socials = bearded_get_social_lists();
foreach($socials as $key => $val ) {
$input[$val] = wp_filter_nohtml_kses( $input[$val] );
}
/* Return the array of theme settings. */
return $input;
}
/* Function for displaying the meta box. */
function bearded_social_meta_box() { ?>
<table class="form-table">
<!-- Add custom form elements below here. -->
<!-- Text input box -->
<?php $socials = bearded_get_social_lists(); ?>
<?php foreach( $socials as $key => $val ) { ?>
<tr>
<th>
<label for="<?php echo hybrid_settings_field_id( 'bearded_social_'.$key ); ?>">
<?php printf( __('%1$s URL' ,'bearded'), ucwords(str_replace('-', ' ', $key)) ); ?>
</label>
</th>
<td>
<p>
<input type="text" id="<?php echo hybrid_settings_field_id( 'bearded_social_'.$key ); ?>" name="<?php echo hybrid_settings_field_name( 'bearded_social_'.$key ); ?>" size="80" value="<?php echo $val; ?>" />
</p>
</td>
</tr>
<?php } ?>
<!-- End custom form elements. -->
</table><!-- .form-table -->
<?php
}
function bearded_theme_customizer( $wp_customize ) {
$wp_customize->add_section( 'bearded_logo_section' , array(
'title' => __( 'Logo', 'bearded' ),
'priority' => 30,
'description' => 'Upload a logo to replace the default site name and description in the header',
) );
$wp_customize->add_setting( 'bearded_logo' );
$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'bearded_logo', array(
'label' => __( 'Logo', 'bearded' ),
'section' => 'bearded_logo_section',
'settings' => 'bearded_logo',
) ) );
}
add_action('customize_register', 'bearded_theme_customizer');
?>
|
bryanerayner/bryanerayner-old
|
wp-content/themes/bearded/inc/functions-admin.php
|
PHP
|
gpl-2.0
| 2,788
|
/******************************************************************************/
/* Да се испечатат сите броеви кои се деливи со своите цифри во зададен */
/* интервал. Почетокот и крајот на интервалот се внесуваат преку тастатура. */
/* */
/* Пример влез: */
/* 20 30 */
/* */
/* Пример излез: */
/* 20 22 24 30 */
/******************************************************************************/
int main()
{
return 0;
}
|
gdarko/CProgrammingExercises
|
zbirka_1/broevi/zad_5.c
|
C
|
gpl-2.0
| 979
|
"""Support functions for loading the reference count data file."""
__version__ = '$Revision: 1.2 $'
import os
import string
import sys
# Determine the expected location of the reference count file:
try:
p = os.path.dirname(__file__)
except NameError:
p = sys.path[0]
p = os.path.normpath(os.path.join(os.getcwd(), p, os.pardir,
"api", "refcounts.dat"))
DEFAULT_PATH = p
del p
def load(path=DEFAULT_PATH):
return loadfile(open(path))
def loadfile(fp):
d = {}
while 1:
line = fp.readline()
if not line:
break
line = string.strip(line)
if line[:1] in ("", "#"):
# blank lines and comments
continue
parts = string.split(line, ":", 4)
function, type, arg, refcount, comment = parts
if refcount == "null":
refcount = None
elif refcount:
refcount = int(refcount)
else:
refcount = None
#
# Get the entry, creating it if needed:
#
try:
entry = d[function]
except KeyError:
entry = d[function] = Entry(function)
#
# Update the entry with the new parameter or the result information.
#
if arg:
entry.args.append((arg, type, refcount))
else:
entry.result_type = type
entry.result_refs = refcount
return d
class Entry:
def __init__(self, name):
self.name = name
self.args = []
self.result_type = ''
self.result_refs = None
def dump(d):
"""Dump the data in the 'canonical' format, with functions in
sorted order."""
items = d.items()
items.sort()
first = 1
for k, entry in items:
if first:
first = 0
else:
print
s = entry.name + ":%s:%s:%s:"
if entry.result_refs is None:
r = ""
else:
r = entry.result_refs
print s % (entry.result_type, "", r)
for t, n, r in entry.args:
if r is None:
r = ""
print s % (t, n, r)
def main():
d = load()
dump(d)
if __name__ == "__main__":
main()
|
atmark-techno/atmark-dist
|
user/python/Doc/tools/refcounts.py
|
Python
|
gpl-2.0
| 2,236
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.5.0_15) on Thu Jan 08 18:20:49 PST 2009 -->
<TITLE>
HttpConnection (Connection Manager 3.6.3 Javadoc)
</TITLE>
<META NAME="keywords" CONTENT="org.jivesoftware.multiplexer.net.http.HttpConnection class">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
parent.document.title="HttpConnection (Connection Manager 3.6.3 Javadoc)";
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Connection Manager 3.6.3 Javadoc</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpBindServlet.html" title="class in org.jivesoftware.multiplexer.net.http"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnectionClosedException.html" title="class in org.jivesoftware.multiplexer.net.http"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/jivesoftware/multiplexer/net/http/HttpConnection.html" target="_top"><B>FRAMES</B></A>
<A HREF="HttpConnection.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
org.jivesoftware.multiplexer.net.http</FONT>
<BR>
Class HttpConnection</H2>
<PRE>
java.lang.Object
<IMG SRC="../../../../../resources/inherit.gif" ALT="extended by "><B>org.jivesoftware.multiplexer.net.http.HttpConnection</B>
</PRE>
<HR>
<DL>
<DT><PRE>public class <B>HttpConnection</B><DT>extends java.lang.Object</DL>
</PRE>
<P>
Represents one HTTP connection with a client using the HTTP Binding service. The client will wait
on <A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#getResponse()"><CODE>getResponse()</CODE></A> until the server forwards a message to it or the wait time on the
session timesout.
<P>
<P>
<DL>
<DT><B>Author:</B></DT>
<DD>Alexander Wenckus</DD>
</DL>
<HR>
<P>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#HttpConnection(long, boolean)">HttpConnection</A></B>(long requestId,
boolean isSecure)</CODE>
<BR>
Constructs an HTTP Connection.</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="2"><FONT SIZE="+2">
<B>Method Summary</B></FONT></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#close()">close</A></B>()</CODE>
<BR>
The connection should be closed without delivering a stanza to the requestor.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#deliverBody(java.lang.String)">deliverBody</A></B>(java.lang.String body)</CODE>
<BR>
Delivers content to the client.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> long</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#getRequestId()">getRequestId</A></B>()</CODE>
<BR>
Returns the ID which uniquely identifies this connection.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#getResponse()">getResponse</A></B>()</CODE>
<BR>
A call that will cause a wait, or in the case of Jetty the thread to be freed, if there is no
deliverable currently available.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> <A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpSession.html" title="class in org.jivesoftware.multiplexer.net.http">HttpSession</A></CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#getSession()">getSession</A></B>()</CODE>
<BR>
Returns the session that this connection belongs to.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#isClosed()">isClosed</A></B>()</CODE>
<BR>
Returns true if this connection has been closed, either a response was delivered to the
client or the server closed the connection aburbtly.</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#isDelivered()">isDelivered</A></B>()</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> boolean</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnection.html#isSecure()">isSecure</A></B>()</CODE>
<BR>
Returns true if this connection is using HTTPS.</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#EEEEFF" CLASS="TableSubHeadingColor">
<TH ALIGN="left"><B>Methods inherited from class java.lang.Object</B></TH>
</TR>
<TR BGCOLOR="white" CLASS="TableRowColor">
<TD><CODE>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="HttpConnection(long, boolean)"><!-- --></A><H3>
HttpConnection</H3>
<PRE>
public <B>HttpConnection</B>(long requestId,
boolean isSecure)</PRE>
<DL>
<DD>Constructs an HTTP Connection.
<P>
<DL>
<DT><B>Parameters:</B><DD><CODE>requestId</CODE> - the ID which uniquely identifies this request.<DD><CODE>isSecure</CODE> - true if this connection is using HTTPS</DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" WIDTH="100%" CELLPADDING="3" CELLSPACING="0" SUMMARY="">
<TR BGCOLOR="#CCCCFF" CLASS="TableHeadingColor">
<TH ALIGN="left" COLSPAN="1"><FONT SIZE="+2">
<B>Method Detail</B></FONT></TH>
</TR>
</TABLE>
<A NAME="close()"><!-- --></A><H3>
close</H3>
<PRE>
public void <B>close</B>()</PRE>
<DL>
<DD>The connection should be closed without delivering a stanza to the requestor.
<P>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="isClosed()"><!-- --></A><H3>
isClosed</H3>
<PRE>
public boolean <B>isClosed</B>()</PRE>
<DL>
<DD>Returns true if this connection has been closed, either a response was delivered to the
client or the server closed the connection aburbtly.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>true if this connection has been closed.</DL>
</DD>
</DL>
<HR>
<A NAME="isSecure()"><!-- --></A><H3>
isSecure</H3>
<PRE>
public boolean <B>isSecure</B>()</PRE>
<DL>
<DD>Returns true if this connection is using HTTPS.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>true if this connection is using HTTPS.</DL>
</DD>
</DL>
<HR>
<A NAME="isDelivered()"><!-- --></A><H3>
isDelivered</H3>
<PRE>
public boolean <B>isDelivered</B>()</PRE>
<DL>
<DD><DL>
</DL>
</DD>
</DL>
<HR>
<A NAME="deliverBody(java.lang.String)"><!-- --></A><H3>
deliverBody</H3>
<PRE>
public void <B>deliverBody</B>(java.lang.String body)
throws <A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnectionClosedException.html" title="class in org.jivesoftware.multiplexer.net.http">HttpConnectionClosedException</A></PRE>
<DL>
<DD>Delivers content to the client. The content should be valid XMPP wrapped inside of a body.
A <i>null</i> value for body indicates that the connection should be closed and the client
sent an empty body.
<P>
<DD><DL>
<DT><B>Parameters:</B><DD><CODE>body</CODE> - the XMPP content to be forwarded to the client inside of a body tag.
<DT><B>Throws:</B>
<DD><CODE><A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnectionClosedException.html" title="class in org.jivesoftware.multiplexer.net.http">HttpConnectionClosedException</A></CODE> - when this connection to the client has already recieved
a deliverable to forward to the client</DL>
</DD>
</DL>
<HR>
<A NAME="getResponse()"><!-- --></A><H3>
getResponse</H3>
<PRE>
public java.lang.String <B>getResponse</B>()
throws org.jivesoftware.multiplexer.net.http.HttpBindTimeoutException</PRE>
<DL>
<DD>A call that will cause a wait, or in the case of Jetty the thread to be freed, if there is no
deliverable currently available. Once the response becomes available, it is returned.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the deliverable to send to the client
<DT><B>Throws:</B>
<DD><CODE>HttpBindTimeoutException</CODE> - to indicate that the maximum wait time requested by the
client has been surpassed and an empty response should be returned.</DL>
</DD>
</DL>
<HR>
<A NAME="getRequestId()"><!-- --></A><H3>
getRequestId</H3>
<PRE>
public long <B>getRequestId</B>()</PRE>
<DL>
<DD>Returns the ID which uniquely identifies this connection.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the ID which uniquely identifies this connection.</DL>
</DD>
</DL>
<HR>
<A NAME="getSession()"><!-- --></A><H3>
getSession</H3>
<PRE>
public <A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpSession.html" title="class in org.jivesoftware.multiplexer.net.http">HttpSession</A> <B>getSession</B>()</PRE>
<DL>
<DD>Returns the session that this connection belongs to.
<P>
<DD><DL>
<DT><B>Returns:</B><DD>the session that this connection belongs to.</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
<b>Connection Manager 3.6.3 Javadoc</b></EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpBindServlet.html" title="class in org.jivesoftware.multiplexer.net.http"><B>PREV CLASS</B></A>
<A HREF="../../../../../org/jivesoftware/multiplexer/net/http/HttpConnectionClosedException.html" title="class in org.jivesoftware.multiplexer.net.http"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html?org/jivesoftware/multiplexer/net/http/HttpConnection.html" target="_top"><B>FRAMES</B></A>
<A HREF="HttpConnection.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../../../../../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
<TR>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
SUMMARY: NESTED | FIELD | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" CLASS="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
<i>Copyright © 2003-2006 Jive Software.</i>
</BODY>
</HTML>
|
onlychoice/ws-xmpp-proxy
|
documentation/docs/javadoc/org/jivesoftware/multiplexer/net/http/HttpConnection.html
|
HTML
|
gpl-2.0
| 17,158
|
/*******************************************************************************
*
* McStas, neutron ray-tracing package
* Copyright 1997-2002, All rights reserved
* Risoe National Laboratory, Roskilde, Denmark
* Institut Laue Langevin, Grenoble, France
*
* Kernel: cexp.c
*
* %Identification
* Written by: K.N.
* Date: Aug 7, 1997
* Origin: Risoe
* Release: McStas 1.6
* Version: $Revision$
*
* Handle expressions used as arguments to components etc.
*
*******************************************************************************/
#include <stdarg.h>
#include <stdio.h>
#include "mccode.h"
/* The internal structure implementing a C expression. */
struct cexp
{
char *s; /* String representation */
int isvalue; /* True if identifier or string/number constant */
int lineno; /* Starting line number, or zero */
};
/* Create an expression from a string representing a value (either identifier,
constant number, or constant string). */
static CExp
mkvalueexp(char *s)
{
CExp e;
palloc(e);
e->s = s;
e->isvalue = 1;
e->lineno = 0; /* Initially no line number set */
return e;
}
/* Create an expression from a string not representing a value. */
static CExp
mknonvalueexp(char *s)
{
CExp e;
palloc(e);
e->s = s;
e->isvalue = 0;
e->lineno = 0; /* Initially no line number set */
return e;
}
/*******************************************************************************
* Handle identifiers used as arguments to components.
* There are two types of identifiers: normal and extern. Normal identifiers
* refer to formal arguments of the instrument, and are always of type
* double. These can be varied eg. to perform a scan. Extern identifiers refer
* to user-supplied C identifiers that is typically put in the declaration and
* initialization sections of the instrument definition.
*
* The final version will distinguish (using a union) between these two types,
* and will maintain a mapping from formal parameters of the instrument to
* generated names in the generated simulation (the extern names must be
* copied unchanged). But in this first version a simpler scheme is used: all
* identifier expressions are simply strings, and all normal identifiers refer
* to instrument parameters (which have ID_PRE and "ip" prepended).
*******************************************************************************/
CExp
exp_id(char *id)
{
return mkvalueexp(str_cat(ID_PRE, "ip", id, NULL));
}
CExp
exp_extern_id(char *id)
{
return mkvalueexp(str_dup(id));
}
CExp
exp_number(char *n)
{
return mkvalueexp(str_dup(n));
}
CExp
exp_string(char *s)
{
char *quoted, *result;
quoted = str_quote(s);
result = str_cat("\"", s, "\"", NULL);
str_free(quoted);
return mkvalueexp(result);
}
CExp
exp_ctoken(char *s)
{
return mknonvalueexp(str_dup(s));
}
CExp
exp_compound(int n, ...)
{
char *result, *new;
CExp e;
va_list ap;
char *separator = ""; /* Token separator, initially empty */
va_start(ap, n);
result = str_dup("");
while(n-- > 0)
{
e = va_arg(ap, CExp);
new = str_cat(result, separator, e->s, NULL);
str_free(result);
result = new;
separator = " "; /* Now use space separator for rest. */
}
return mknonvalueexp(result);
}
void
exp_free(CExp e)
{
str_free(e->s);
memfree(e);
}
char *
exp_tostring(CExp e)
{
char *s = e->s;
if(s == NULL)
{
s = "";
debugn((DEBUG_HIGH, "exp_tostring(): NULL cexp received.\n"));
}
return str_dup(s);
}
void
exp_fprint(FILE *f, CExp e)
{
fputs(e->s, f);
}
int
exp_isvalue(CExp e)
{
return e->isvalue;
}
void
exp_setlineno(CExp e, int n)
{
e->lineno = n;
}
int
exp_getlineno(CExp e)
{
return e->lineno;
}
|
mads-bertelsen/McCode
|
mcstas/src/cexp.c
|
C
|
gpl-2.0
| 3,722
|
<?php
/**
* Opening Border Control Markup
*
* Outputs the opening html markup for the
* border controls.
*
* @package Easy_Google_Fonts
* @author Sunny Johal - Titanium Themes <support@titaniumthemes.com>
* @license GPL-2.0+
* @link http://wordpress.org/plugins/easy-google-fonts/
* @copyright Copyright (c) 2015, Titanium Themes
* @version 1.3.6
*
*/
?>
<div class="egf-font-toggle">
<div class="toggle-section-title">
<span class="customize-control-title inner-control-title"><?php _e( 'Border', 'easy-google-fonts' ); ?></span>
</div>
<div class="toggle-section-content">
<span class="customize-control-title"><?php _e( 'Select Border to Control', 'easy-google-fonts' ); ?></span>
<select class="egf-switch-border-control">
<option value="top"><?php _e( 'Top', 'easy-google-fonts' ); ?></option>
<option value="bottom"><?php _e( 'Bottom', 'easy-google-fonts' ); ?></option>
<option value="left"><?php _e( 'Left', 'easy-google-fonts' ); ?></option>
<option value="right"><?php _e( 'Right', 'easy-google-fonts' ); ?></option>
</select>
|
StabbyMcDuck/skillcrush_wordpress_starter_theme
|
wp-content/plugins/easy-google-fonts/views/customizer/control/positioning/border/start.php
|
PHP
|
gpl-2.0
| 1,089
|
/*
* Copyright (C) 2008-2019 TrinityCore <https://www.trinitycore.org/>
* Copyright (C) 2006-2009 ScriptDev2 <https://scriptdev2.svn.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, see <http://www.gnu.org/licenses/>.
*/
/* ScriptData
SDName: Boss_Ragnaros
SD%Complete: 95
SDComment: some spells doesnt work correctly
SDCategory: Molten Core
EndScriptData */
#include "ScriptMgr.h"
#include "InstanceScript.h"
#include "molten_core.h"
#include "ObjectAccessor.h"
#include "ScriptedCreature.h"
#include "TemporarySummon.h"
enum Texts
{
SAY_SUMMON_MAJ = 0,
SAY_ARRIVAL1_RAG = 1,
SAY_ARRIVAL2_MAJ = 2,
SAY_ARRIVAL3_RAG = 3,
SAY_ARRIVAL5_RAG = 4,
SAY_REINFORCEMENTS1 = 5,
SAY_REINFORCEMENTS2 = 6,
SAY_HAND = 7,
SAY_WRATH = 8,
SAY_KILL = 9,
SAY_MAGMABURST = 10
};
enum Spells
{
SPELL_HAND_OF_RAGNAROS = 19780,
SPELL_WRATH_OF_RAGNAROS = 20566,
SPELL_LAVA_BURST = 21158,
SPELL_MAGMA_BLAST = 20565, // Ranged attack
SPELL_SONS_OF_FLAME_DUMMY = 21108, // Server side effect
SPELL_RAGSUBMERGE = 21107, // Stealth aura
SPELL_RAGEMERGE = 20568,
SPELL_MELT_WEAPON = 21388,
SPELL_ELEMENTAL_FIRE = 20564,
SPELL_ERRUPTION = 17731
};
enum Events
{
EVENT_ERUPTION = 1,
EVENT_WRATH_OF_RAGNAROS = 2,
EVENT_HAND_OF_RAGNAROS = 3,
EVENT_LAVA_BURST = 4,
EVENT_ELEMENTAL_FIRE = 5,
EVENT_MAGMA_BLAST = 6,
EVENT_SUBMERGE = 7,
EVENT_INTRO_1 = 8,
EVENT_INTRO_2 = 9,
EVENT_INTRO_3 = 10,
EVENT_INTRO_4 = 11,
EVENT_INTRO_5 = 12
};
class boss_ragnaros : public CreatureScript
{
public:
boss_ragnaros() : CreatureScript("boss_ragnaros") { }
struct boss_ragnarosAI : public BossAI
{
boss_ragnarosAI(Creature* creature) : BossAI(creature, BOSS_RAGNAROS)
{
Initialize();
_introState = 0;
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE);
SetCombatMovement(false);
}
void Initialize()
{
_emergeTimer = 90000;
_hasYelledMagmaBurst = false;
_hasSubmergedOnce = false;
_isBanished = false;
}
void Reset() override
{
BossAI::Reset();
Initialize();
me->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0);
}
void EnterCombat(Unit* victim) override
{
BossAI::EnterCombat(victim);
events.ScheduleEvent(EVENT_ERUPTION, 15000);
events.ScheduleEvent(EVENT_WRATH_OF_RAGNAROS, 30000);
events.ScheduleEvent(EVENT_HAND_OF_RAGNAROS, 25000);
events.ScheduleEvent(EVENT_LAVA_BURST, 10000);
events.ScheduleEvent(EVENT_ELEMENTAL_FIRE, 3000);
events.ScheduleEvent(EVENT_MAGMA_BLAST, 2000);
events.ScheduleEvent(EVENT_SUBMERGE, 180000);
}
void KilledUnit(Unit* /*victim*/) override
{
if (urand(0, 99) < 25)
Talk(SAY_KILL);
}
void UpdateAI(uint32 diff) override
{
if (_introState != 2)
{
if (!_introState)
{
me->HandleEmoteCommand(EMOTE_ONESHOT_EMERGE);
events.ScheduleEvent(EVENT_INTRO_1, 4000);
events.ScheduleEvent(EVENT_INTRO_2, 23000);
events.ScheduleEvent(EVENT_INTRO_3, 42000);
events.ScheduleEvent(EVENT_INTRO_4, 43000);
events.ScheduleEvent(EVENT_INTRO_5, 53000);
_introState = 1;
}
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_INTRO_1:
Talk(SAY_ARRIVAL1_RAG);
break;
case EVENT_INTRO_2:
Talk(SAY_ARRIVAL3_RAG);
break;
case EVENT_INTRO_3:
me->HandleEmoteCommand(EMOTE_ONESHOT_ATTACK1H);
break;
case EVENT_INTRO_4:
Talk(SAY_ARRIVAL5_RAG);
if (Creature* executus = ObjectAccessor::GetCreature(*me, instance->GetGuidData(BOSS_MAJORDOMO_EXECUTUS)))
me->Kill(executus);
break;
case EVENT_INTRO_5:
me->SetReactState(REACT_AGGRESSIVE);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NON_ATTACKABLE | UNIT_FLAG_IMMUNE_TO_PC);
_introState = 2;
break;
default:
break;
}
}
}
else
{
if (_isBanished && ((_emergeTimer <= diff) || (instance->GetData(DATA_RAGNAROS_ADDS)) > 8))
{
//Become unbanished again
me->SetReactState(REACT_AGGRESSIVE);
me->setFaction(14);
me->RemoveFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetUInt32Value(UNIT_NPC_EMOTESTATE, 0);
me->HandleEmoteCommand(EMOTE_ONESHOT_EMERGE);
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
AttackStart(target);
instance->SetData(DATA_RAGNAROS_ADDS, 0);
//DoCast(me, SPELL_RAGEMERGE); //"phase spells" didnt worked correctly so Ive commented them and wrote solution witch doesnt need core support
_isBanished = false;
}
else if (_isBanished)
{
_emergeTimer -= diff;
//Do nothing while banished
return;
}
//Return since we have no target
if (!UpdateVictim())
return;
events.Update(diff);
while (uint32 eventId = events.ExecuteEvent())
{
switch (eventId)
{
case EVENT_ERUPTION:
DoCastVictim(SPELL_ERRUPTION);
events.ScheduleEvent(EVENT_ERUPTION, urand(20000, 45000));
break;
case EVENT_WRATH_OF_RAGNAROS:
DoCastVictim(SPELL_WRATH_OF_RAGNAROS);
if (urand(0, 1))
Talk(SAY_WRATH);
events.ScheduleEvent(EVENT_WRATH_OF_RAGNAROS, 25000);
break;
case EVENT_HAND_OF_RAGNAROS:
DoCast(me, SPELL_HAND_OF_RAGNAROS);
if (urand(0, 1))
Talk(SAY_HAND);
events.ScheduleEvent(EVENT_HAND_OF_RAGNAROS, 20000);
break;
case EVENT_LAVA_BURST:
DoCastVictim(SPELL_LAVA_BURST);
events.ScheduleEvent(EVENT_LAVA_BURST, 10000);
break;
case EVENT_ELEMENTAL_FIRE:
DoCastVictim(SPELL_ELEMENTAL_FIRE);
events.ScheduleEvent(EVENT_ELEMENTAL_FIRE, urand(10000, 14000));
break;
case EVENT_MAGMA_BLAST:
if (!me->IsWithinMeleeRange(me->GetVictim()))
{
DoCastVictim(SPELL_MAGMA_BLAST);
if (!_hasYelledMagmaBurst)
{
//Say our dialog
Talk(SAY_MAGMABURST);
_hasYelledMagmaBurst = true;
}
}
events.ScheduleEvent(EVENT_MAGMA_BLAST, 2500);
break;
case EVENT_SUBMERGE:
{
if (!_isBanished)
{
//Creature spawning and ragnaros becomming unattackable
//is not very well supported in the core //no it really isnt
//so added normaly spawning and banish workaround and attack again after 90 secs.
me->AttackStop();
DoResetThreat();
me->SetReactState(REACT_PASSIVE);
me->InterruptNonMeleeSpells(false);
//Root self
//DoCast(me, 23973);
me->setFaction(35);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
me->SetUInt32Value(UNIT_NPC_EMOTESTATE, EMOTE_STATE_SUBMERGED);
me->HandleEmoteCommand(EMOTE_ONESHOT_SUBMERGE);
instance->SetData(DATA_RAGNAROS_ADDS, 0);
if (!_hasSubmergedOnce)
{
Talk(SAY_REINFORCEMENTS1);
// summon 8 elementals
for (uint8 i = 0; i < 8; ++i)
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
if (Creature* summoned = me->SummonCreature(12143, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 900000))
summoned->AI()->AttackStart(target);
_hasSubmergedOnce = true;
_isBanished = true;
//DoCast(me, SPELL_RAGSUBMERGE);
_emergeTimer = 90000;
}
else
{
Talk(SAY_REINFORCEMENTS2);
for (uint8 i = 0; i < 8; ++i)
if (Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0))
if (Creature* summoned = me->SummonCreature(12143, target->GetPositionX(), target->GetPositionY(), target->GetPositionZ(), 0.0f, TEMPSUMMON_TIMED_OR_CORPSE_DESPAWN, 900000))
summoned->AI()->AttackStart(target);
_isBanished = true;
//DoCast(me, SPELL_RAGSUBMERGE);
_emergeTimer = 90000;
}
}
events.ScheduleEvent(EVENT_SUBMERGE, 180000);
break;
}
default:
break;
}
}
DoMeleeAttackIfReady();
}
}
private:
uint32 _emergeTimer;
uint8 _introState;
bool _hasYelledMagmaBurst;
bool _hasSubmergedOnce;
bool _isBanished;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetMoltenCoreAI<boss_ragnarosAI>(creature);
}
};
class npc_son_of_flame : public CreatureScript
{
public:
npc_son_of_flame() : CreatureScript("npc_SonOfFlame") { }
struct npc_son_of_flameAI : public ScriptedAI //didnt work correctly in EAI for me...
{
npc_son_of_flameAI(Creature* creature) : ScriptedAI(creature)
{
instance = me->GetInstanceScript();
}
void JustDied(Unit* /*killer*/) override
{
instance->SetData(DATA_RAGNAROS_ADDS, 1);
}
void UpdateAI(uint32 /*diff*/) override
{
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
private:
InstanceScript* instance;
};
CreatureAI* GetAI(Creature* creature) const override
{
return GetMoltenCoreAI<npc_son_of_flameAI>(creature);
}
};
void AddSC_boss_ragnaros()
{
new boss_ragnaros();
new npc_son_of_flame();
}
|
jameyboor/TrinityCore
|
src/server/scripts/EasternKingdoms/BlackrockMountain/MoltenCore/boss_ragnaros.cpp
|
C++
|
gpl-2.0
| 14,752
|
################################################################################
#
# CMake target configuration file for Xilinx Microblaze
#
# 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.
################################################################################
################################################################################
# Name of the target platform
SET(CMAKE_SYSTEM Xilinx-Microblaze)
SET(CMAKE_SYSTEM_NAME Generic)
SET(CMAKE_SYSTEM_PROCESSOR Microblaze)
# Version of the system
SET(CMAKE_SYSTEM_VERSION 1)
# specify the cross compiler
SET(CMAKE_C_COMPILER mb-gcc)
SET(CMAKE_CXX_COMPILER mb-g++)
SET(CMAKE_ASM-ATT_COMPILER mb-as)
# search for programs in the build host directories
SET(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
# for libraries and headers in the target directories
SET(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
SET(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
|
SylvainLesne/openPOWERLINK_V2
|
cmake/toolchain-xilinx-microblaze-gnu.cmake
|
CMake
|
gpl-2.0
| 2,446
|
// -*- mode:c++; tab-width:2; indent-tabs-mode:nil; c-basic-offset:2 -*-
/*
* Binarizer.cpp
* zxing
*
* Created by Ralf Kistner on 16/10/2009.
* Copyright 2008 ZXing authors All rights reserved.
* Modified by Lukasz Warchol on 02/02/2010.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "Binarizer.h"
namespace zxing {
Binarizer::Binarizer(Ref<LuminanceSource> source) : source_(source) {
}
Binarizer::~Binarizer() {
}
Ref<LuminanceSource> Binarizer::getLuminanceSource() const {
return source_;
}
}
|
codenameone/codenameone-demos
|
ZXing/native/ios/Binarizer.cpp
|
C++
|
gpl-2.0
| 1,054
|
/*
This file is part of iprohc.
iprohc 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.
iprohc 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 iprohc. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef ROHC_IPIP_TUNH_H
#define ROHC_IPIP_TUNH_H
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
int create_tun(const char *const name,
const char *const basedev,
int *const tun_itf_id,
size_t *const basedev_mtu,
size_t *const tun_itf_mtu)
__attribute__((warn_unused_result));
bool set_ip4(int iface_index, uint32_t address, uint8_t network);
int create_raw(const int fwmark);
#endif
|
umbrellashield/ipcompress
|
src/common/tun_helpers.h
|
C
|
gpl-2.0
| 1,079
|
/*
* libretroshare/src/services/p3banlist.h
*
* Exchange list of Peers for Banning / Whitelisting.
*
* Copyright 2011 by Robert Fernie.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License Version 2 as published by the Free Software Foundation.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA.
*
* Please report all bugs and problems to "retroshare@lunamutt.com".
*
*/
#ifndef SERVICE_RSBANLIST_HEADER
#define SERVICE_RSBANLIST_HEADER
#include <string>
#include <list>
#include <map>
#include "serialiser/rsbanlistitems.h"
#include "services/p3service.h"
#include "retroshare/rsbanlist.h"
class p3ServiceControl;
class p3NetMgr;
class BanList
{
public:
RsPeerId mPeerId; /* from */
time_t mLastUpdate;
std::map<struct sockaddr_storage, BanListPeer> mBanPeers;
};
//!The RS BanList service.
/**
*
* Exchange list of Banned IP addresses with peers.
*/
class p3BanList: public RsBanList, public p3Service, public pqiNetAssistPeerShare, public p3Config /*, public pqiMonitor */
{
public:
p3BanList(p3ServiceControl *sc, p3NetMgr *nm);
virtual RsServiceInfo getServiceInfo();
/***** overloaded from RsBanList *****/
virtual bool isAddressAccepted(const struct sockaddr_storage& addr, uint32_t checking_flags,uint32_t *check_result=NULL) ;
virtual void getBannedIps(std::list<BanListPeer>& list) ;
virtual void getWhiteListedIps(std::list<BanListPeer>& list) ;
virtual bool addIpRange(const struct sockaddr_storage& addr,int masked_bytes,uint32_t list_type,const std::string& comment) ;
virtual bool removeIpRange(const sockaddr_storage &addr, int masked_bytes, uint32_t list_type);
virtual void enableIPFiltering(bool b) ;
virtual bool ipFilteringEnabled() ;
virtual bool autoRangeEnabled() { return mAutoRangeIps ; }
virtual void enableAutoRange(bool b) ;
virtual int autoRangeLimit() { return mAutoRangeLimit ; }
virtual void setAutoRangeLimit(int b) ;
virtual void enableIPsFromFriends(bool b) ;
virtual bool IPsFromFriendsEnabled() { return mIPFriendGatheringEnabled ;}
virtual void enableIPsFromDHT(bool b) ;
virtual bool iPsFromDHTEnabled() { return mIPDHTGatheringEnabled ;}
/***** overloaded from pqiNetAssistPeerShare *****/
virtual void updatePeer(const RsPeerId& id, const struct sockaddr_storage &addr, int type, int reason, int time_stamp);
/*********************** p3config ******************************/
virtual RsSerialiser *setupSerialiser();
virtual bool saveList(bool &cleanup, std::list<RsItem *>& itemlist);
virtual bool loadList(std::list<RsItem *>& load);
/***** overloaded from p3Service *****/
/*!
* This retrieves all chat msg items and also (important!)
* processes chat-status items that are in service item queue. chat msg item requests are also processed and not returned
* (important! also) notifications sent to notify base on receipt avatar, immediate status and custom status
* : notifyCustomState, notifyChatStatus, notifyPeerHasNewAvatar
* @see NotifyBase
*/
virtual int tick();
virtual int status();
int sendPackets();
bool processIncoming();
bool recvBanItem(RsBanListItem *item);
bool addBanEntry(const RsPeerId &peerId, const struct sockaddr_storage &addr, int level, uint32_t reason, time_t time_stamp);
void sendBanLists();
int sendBanSet(const RsPeerId& peerid);
/*!
* Interface stuff.
*/
/*************** pqiMonitor callback ***********************/
//virtual void statusChange(const std::list<pqipeer> &plist);
/************* from p3Config *******************/
//virtual RsSerialiser *setupSerialiser() ;
//virtual bool saveList(bool& cleanup, std::list<RsItem*>&) ;
//virtual void saveDone();
//virtual bool loadList(std::list<RsItem*>& load) ;
private:
void getDhtInfo() ;
RsMutex mBanMtx;
bool acceptedBanSet_locked(const BanListPeer &blp);
bool acceptedBanRanges_locked(const BanListPeer &blp);
void autoFigureOutBanRanges();
int condenseBanSources_locked();
int printBanSources_locked(std::ostream &out);
int printBanSet_locked(std::ostream &out);
bool isWhiteListed_locked(const sockaddr_storage &addr);
time_t mSentListTime;
std::map<RsPeerId, BanList> mBanSources;
std::map<struct sockaddr_storage, BanListPeer> mBanSet;
std::map<struct sockaddr_storage, BanListPeer> mBanRanges;
std::map<struct sockaddr_storage, BanListPeer> mWhiteListedRanges;
p3ServiceControl *mServiceCtrl;
p3NetMgr *mNetMgr;
time_t mLastDhtInfoRequest ;
bool mIPFilteringEnabled ;
bool mIPFriendGatheringEnabled ;
bool mIPDHTGatheringEnabled ;
uint32_t mAutoRangeLimit ;
bool mAutoRangeIps ;
};
#endif // SERVICE_RSBANLIST_HEADER
|
zeners/RetroShare
|
libretroshare/src/services/p3banlist.h
|
C
|
gpl-2.0
| 5,346
|
//! \example tutorial-barcode-detector.cpp
//! [Include]
#include <visp3/detection/vpDetectorDataMatrixCode.h>
#include <visp3/detection/vpDetectorQRCode.h>
//! [Include]
#include <visp3/gui/vpDisplayGDI.h>
#include <visp3/gui/vpDisplayOpenCV.h>
#include <visp3/gui/vpDisplayX.h>
#include <visp3/io/vpImageIo.h>
int main(int argc, const char **argv)
{
//! [Macro defined]
#if (defined(VISP_HAVE_ZBAR) || defined(VISP_HAVE_DMTX)) && \
(defined(VISP_HAVE_X11) || defined(VISP_HAVE_GDI) || defined(VISP_HAVE_OPENCV))
//! [Macro defined]
try {
vpImage<unsigned char> I;
vpImageIo::read(I, "bar-code.pgm");
#ifdef VISP_HAVE_X11
vpDisplayX d(I);
#elif defined(VISP_HAVE_GDI)
vpDisplayGDI d(I);
#elif defined(VISP_HAVE_OPENCV)
vpDisplayOpenCV d(I);
#endif
//! [Create base detector]
vpDetectorBase *detector = NULL;
//! [Create base detector]
#if (defined(VISP_HAVE_ZBAR) && defined(VISP_HAVE_DMTX))
int opt_barcode = 0; // 0=QRCode, 1=DataMatrix
for (int i = 0; i < argc; i++) {
if (std::string(argv[i]) == "--code-type")
opt_barcode = atoi(argv[i + 1]);
else if (std::string(argv[i]) == "--help") {
std::cout << "Usage: " << argv[0] << " [--code-type <0 for QRcode | 1 for DataMatrix>] [--help]" << std::endl;
return 0;
}
}
//! [Create detector]
if (opt_barcode == 0)
detector = new vpDetectorQRCode;
else
detector = new vpDetectorDataMatrixCode;
//! [Create detector]
#elif defined(VISP_HAVE_ZBAR)
detector = new vpDetectorQRCode;
(void)argc;
(void)argv;
#elif defined(VISP_HAVE_DMTX)
detector = new vpDetectorDataMatrixCode;
(void)argc;
(void)argv;
#endif
vpDisplay::display(I);
//! [Detection]
bool status = detector->detect(I);
//! [Detection]
std::ostringstream legend;
legend << detector->getNbObjects() << " bar code detected";
vpDisplay::displayText(I, (int)I.getHeight() - 30, 10, legend.str(), vpColor::red);
//! [Parse detected codes]
if (status) {
for (size_t i = 0; i < detector->getNbObjects(); i++) {
//! [Parse detected codes]
//! [Get location]
std::vector<vpImagePoint> p = detector->getPolygon(i);
vpRect bbox = detector->getBBox(i);
//! [Get location]
vpDisplay::displayRectangle(I, bbox, vpColor::green);
//! [Get message]
vpDisplay::displayText(I, (int)(bbox.getTop() - 10), (int)bbox.getLeft(),
"Message: \"" + detector->getMessage(i) + "\"", vpColor::red);
//! [Get message]
for (size_t j = 0; j < p.size(); j++) {
vpDisplay::displayCross(I, p[j], 14, vpColor::red, 3);
std::ostringstream number;
number << j;
vpDisplay::displayText(I, p[j] + vpImagePoint(15, 5), number.str(), vpColor::blue);
}
}
vpDisplay::displayText(I, (int)I.getHeight() - 15, 10, "A click to quit...", vpColor::red);
vpDisplay::flush(I);
vpDisplay::getClick(I);
}
delete detector;
} catch (const vpException &e) {
std::cout << "Catch an exception: " << e.getMessage() << std::endl;
}
#else
(void)argc;
(void)argv;
#endif
}
|
MarcPouliquenInria/visp
|
tutorial/detection/barcode/tutorial-barcode-detector.cpp
|
C++
|
gpl-2.0
| 3,266
|
/*!
* Font Awesome 4.7.0 by @davegandy - http://fontawesome.io - @fontawesome
* License - http://fontawesome.io/license (Font: SIL OFL 1.1, CSS: MIT License)
*/
/* FONT PATH
* -------------------------- */
@font-face {
font-family: 'FontAwesome';
src: url('../fonts/fontawesome-webfont.eot?v=4.7.0');
src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.7.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff2?v=4.7.0') format('woff2'), url('../fonts/fontawesome-webfont.woff?v=4.7.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.7.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.7.0#fontawesomeregular') format('svg');
font-weight: normal;
font-style: normal;
}
.fa {
display: inline-block;
font: normal normal normal 14px/1 FontAwesome;
font-size: inherit;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* makes the font 33% larger relative to the icon container */
.fa-lg {
font-size: 1.33333333em;
line-height: 0.75em;
vertical-align: -15%;
}
.fa-2x {
font-size: 2em;
}
.fa-3x {
font-size: 3em;
}
.fa-4x {
font-size: 4em;
}
.fa-5x {
font-size: 5em;
}
.fa-fw {
width: 1.28571429em;
text-align: center;
}
.fa-ul {
padding-left: 0;
margin-left: 2.14285714em;
list-style-type: none;
}
.fa-ul > li {
position: relative;
}
.fa-li {
position: absolute;
left: -2.14285714em;
width: 2.14285714em;
top: 0.14285714em;
text-align: center;
}
.fa-li.fa-lg {
left: -1.85714286em;
}
.fa-border {
padding: .2em .25em .15em;
border: solid 0.08em #eee;
border-radius: .1em;
}
.fa-pull-left {
float: left;
}
.fa-pull-right {
float: right;
}
.fa.fa-pull-left {
margin-right: .3em;
}
.fa.fa-pull-right {
margin-left: .3em;
}
/* Deprecated as of 4.4.0 */
.pull-right {
float: right;
}
.pull-left {
float: left;
}
.fa.pull-left {
margin-right: .3em;
}
.fa.pull-right {
margin-left: .3em;
}
.fa-spin {
-webkit-animation: fa-spin 2s infinite linear;
animation: fa-spin 2s infinite linear;
}
.fa-pulse {
-webkit-animation: fa-spin 1s infinite steps(8);
animation: fa-spin 1s infinite steps(8);
}
@-webkit-keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
@keyframes fa-spin {
0% {
-webkit-transform: rotate(0deg);
transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(359deg);
transform: rotate(359deg);
}
}
.fa-rotate-90 {
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)";
-webkit-transform: rotate(90deg);
-ms-transform: rotate(90deg);
transform: rotate(90deg);
}
.fa-rotate-180 {
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2)";
-webkit-transform: rotate(180deg);
-ms-transform: rotate(180deg);
transform: rotate(180deg);
}
.fa-rotate-270 {
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=3)";
-webkit-transform: rotate(270deg);
-ms-transform: rotate(270deg);
transform: rotate(270deg);
}
.fa-flip-horizontal {
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=0, mirror=1)";
-webkit-transform: scale(-1, 1);
-ms-transform: scale(-1, 1);
transform: scale(-1, 1);
}
.fa-flip-vertical {
-ms-filter: "progid:DXImageTransform.Microsoft.BasicImage(rotation=2, mirror=1)";
-webkit-transform: scale(1, -1);
-ms-transform: scale(1, -1);
transform: scale(1, -1);
}
:root .fa-rotate-90,
:root .fa-rotate-180,
:root .fa-rotate-270,
:root .fa-flip-horizontal,
:root .fa-flip-vertical {
filter: none;
}
.fa-stack {
position: relative;
display: inline-block;
width: 2em;
height: 2em;
line-height: 2em;
vertical-align: middle;
}
.fa-stack-1x,
.fa-stack-2x {
position: absolute;
left: 0;
width: 100%;
text-align: center;
}
.fa-stack-1x {
line-height: inherit;
}
.fa-stack-2x {
font-size: 2em;
}
.fa-inverse {
color: #fff;
}
/* Font Awesome uses the Unicode Private Use Area (PUA) to ensure screen
readers do not read off random characters that represent icons */
.fa-glass:before {
content: "\f000";
}
.fa-music:before {
content: "\f001";
}
.fa-search:before {
content: "\f002";
}
.fa-envelope-o:before {
content: "\f003";
}
.fa-heart:before {
content: "\f004";
}
.fa-star:before {
content: "\f005";
}
.fa-star-o:before {
content: "\f006";
}
.fa-user:before {
content: "\f007";
}
.fa-film:before {
content: "\f008";
}
.fa-th-large:before {
content: "\f009";
}
.fa-th:before {
content: "\f00a";
}
.fa-th-list:before {
content: "\f00b";
}
.fa-check:before {
content: "\f00c";
}
.fa-remove:before,
.fa-times:before,
.fa-times:before {
content: "\f00d";
}
.fa-search-plus:before {
content: "\f00e";
}
.fa-search-minus:before {
content: "\f010";
}
.fa-power-off:before {
content: "\f011";
}
.fa-signal:before {
content: "\f012";
}
.fa-gear:before,
.fa-cog:before {
content: "\f013";
}
.fa-trash-o:before {
content: "\f014";
}
.fa-home:before {
content: "\f015";
}
.fa-file-o:before {
content: "\f016";
}
.fa-clock-o:before {
content: "\f017";
}
.fa-road:before {
content: "\f018";
}
.fa-download:before {
content: "\f019";
}
.fa-arrow-circle-o-down:before {
content: "\f01a";
}
.fa-arrow-circle-o-up:before {
content: "\f01b";
}
.fa-inbox:before {
content: "\f01c";
}
.fa-play-circle-o:before {
content: "\f01d";
}
.fa-rotate-right:before,
.fa-repeat:before {
content: "\f01e";
}
.fa-refresh:before {
content: "\f021";
}
.fa-list-alt:before {
content: "\f022";
}
.fa-lock:before {
content: "\f023";
}
.fa-flag:before {
content: "\f024";
}
.fa-headphones:before {
content: "\f025";
}
.fa-volume-off:before {
content: "\f026";
}
.fa-volume-down:before {
content: "\f027";
}
.fa-volume-up:before {
content: "\f028";
}
.fa-qrcode:before {
content: "\f029";
}
.fa-barcode:before {
content: "\f02a";
}
.fa-tag:before {
content: "\f02b";
}
.fa-tags:before {
content: "\f02c";
}
.fa-book:before {
content: "\f02d";
}
.fa-bookmark:before {
content: "\f02e";
}
.fa-print:before {
content: "\f02f";
}
.fa-camera:before {
content: "\f030";
}
.fa-font:before {
content: "\f031";
}
.fa-bold:before {
content: "\f032";
}
.fa-italic:before {
content: "\f033";
}
.fa-text-height:before {
content: "\f034";
}
.fa-text-width:before {
content: "\f035";
}
.fa-align-left:before {
content: "\f036";
}
.fa-align-center:before {
content: "\f037";
}
.fa-align-right:before {
content: "\f038";
}
.fa-align-justify:before {
content: "\f039";
}
.fa-list:before {
content: "\f03a";
}
.fa-dedent:before,
.fa-outdent:before {
content: "\f03b";
}
.fa-indent:before {
content: "\f03c";
}
.fa-video-camera:before {
content: "\f03d";
}
.fa-photo:before,
.fa-image:before,
.fa-picture-o:before {
content: "\f03e";
}
.fa-pencil-alt:before {
content: "\f040";
}
.fa-map-marker:before {
content: "\f041";
}
.fa-adjust:before {
content: "\f042";
}
.fa-tint:before {
content: "\f043";
}
.fa-edit:before,
.fa-pencil-alt-square-o:before {
content: "\f044";
}
.fa-share-square-o:before {
content: "\f045";
}
.fa-check-square-o:before {
content: "\f046";
}
.fa-arrows:before {
content: "\f047";
}
.fa-step-backward:before {
content: "\f048";
}
.fa-fast-backward:before {
content: "\f049";
}
.fa-backward:before {
content: "\f04a";
}
.fa-play:before {
content: "\f04b";
}
.fa-pause:before {
content: "\f04c";
}
.fa-stop:before {
content: "\f04d";
}
.fa-forward:before {
content: "\f04e";
}
.fa-fast-forward:before {
content: "\f050";
}
.fa-step-forward:before {
content: "\f051";
}
.fa-eject:before {
content: "\f052";
}
.fa-chevron-left:before {
content: "\f053";
}
.fa-chevron-right:before {
content: "\f054";
}
.fa-plus-circle:before {
content: "\f055";
}
.fa-minus-circle:before {
content: "\f056";
}
.fa-times-circle:before {
content: "\f057";
}
.fa-check-circle:before {
content: "\f058";
}
.fa-question-circle:before {
content: "\f059";
}
.fa-info-circle:before {
content: "\f05a";
}
.fa-crosshairs:before {
content: "\f05b";
}
.fa-times-circle-o:before {
content: "\f05c";
}
.fa-check-circle-o:before {
content: "\f05d";
}
.fa-ban:before {
content: "\f05e";
}
.fa-arrow-left:before {
content: "\f060";
}
.fa-arrow-right:before {
content: "\f061";
}
.fa-arrow-up:before {
content: "\f062";
}
.fa-arrow-down:before {
content: "\f063";
}
.fa-share:before,
.fa-share:before {
content: "\f064";
}
.fa-expand:before {
content: "\f065";
}
.fa-compress:before {
content: "\f066";
}
.fa-plus:before {
content: "\f067";
}
.fa-minus:before {
content: "\f068";
}
.fa-asterisk:before {
content: "\f069";
}
.fa-exclamation-circle:before {
content: "\f06a";
}
.fa-gift:before {
content: "\f06b";
}
.fa-leaf:before {
content: "\f06c";
}
.fa-fire:before {
content: "\f06d";
}
.fa-eye:before {
content: "\f06e";
}
.fa-eye-slash:before {
content: "\f070";
}
.fa-warning:before,
.fa-exclamation-triangle:before {
content: "\f071";
}
.fa-plane:before {
content: "\f072";
}
.fa-calendar:before {
content: "\f073";
}
.fa-random:before {
content: "\f074";
}
.fa-comment:before {
content: "\f075";
}
.fa-magnet:before {
content: "\f076";
}
.fa-chevron-up:before {
content: "\f077";
}
.fa-chevron-down:before {
content: "\f078";
}
.fa-retweet:before {
content: "\f079";
}
.fa-shopping-cart:before {
content: "\f07a";
}
.fa-folder:before {
content: "\f07b";
}
.fa-folder-open:before {
content: "\f07c";
}
.fa-arrows-v:before {
content: "\f07d";
}
.fa-arrows-h:before {
content: "\f07e";
}
.fa-bar-chart-o:before,
.fa-bar-chart:before {
content: "\f080";
}
.fa-twitter-square:before {
content: "\f081";
}
.fa-facebook-square:before {
content: "\f082";
}
.fa-camera-retro:before {
content: "\f083";
}
.fa-key:before {
content: "\f084";
}
.fa-gears:before,
.fa-cogs:before {
content: "\f085";
}
.fa-comments:before {
content: "\f086";
}
.fa-thumbs-o-up:before {
content: "\f087";
}
.fa-thumbs-o-down:before {
content: "\f088";
}
.fa-star-half:before {
content: "\f089";
}
.fa-heart-o:before {
content: "\f08a";
}
.fa-sign-out:before {
content: "\f08b";
}
.fa-linkedin-square:before {
content: "\f08c";
}
.fa-thumb-tack:before {
content: "\f08d";
}
.fa-external-link:before {
content: "\f08e";
}
.fa-sign-in:before {
content: "\f090";
}
.fa-trophy:before {
content: "\f091";
}
.fa-github-square:before {
content: "\f092";
}
.fa-upload:before {
content: "\f093";
}
.fa-lemon-o:before {
content: "\f094";
}
.fa-phone:before {
content: "\f095";
}
.fa-square-o:before {
content: "\f096";
}
.fa-bookmark-o:before {
content: "\f097";
}
.fa-phone-square:before {
content: "\f098";
}
.fa-twitter:before {
content: "\f099";
}
.fa-facebook-f:before,
.fa-facebook:before {
content: "\f09a";
}
.fa-github:before {
content: "\f09b";
}
.fa-unlock:before {
content: "\f09c";
}
.fa-credit-card:before {
content: "\f09d";
}
.fa-feed:before,
.fa-rss:before {
content: "\f09e";
}
.fa-hdd-o:before {
content: "\f0a0";
}
.fa-bullhorn:before {
content: "\f0a1";
}
.fa-bell:before {
content: "\f0f3";
}
.fa-certificate:before {
content: "\f0a3";
}
.fa-hand-o-right:before {
content: "\f0a4";
}
.fa-hand-o-left:before {
content: "\f0a5";
}
.fa-hand-o-up:before {
content: "\f0a6";
}
.fa-hand-o-down:before {
content: "\f0a7";
}
.fa-arrow-circle-left:before {
content: "\f0a8";
}
.fa-arrow-circle-right:before {
content: "\f0a9";
}
.fa-arrow-circle-up:before {
content: "\f0aa";
}
.fa-arrow-circle-down:before {
content: "\f0ab";
}
.fa-globe:before {
content: "\f0ac";
}
.fa-wrench:before {
content: "\f0ad";
}
.fa-tasks:before {
content: "\f0ae";
}
.fa-filter:before {
content: "\f0b0";
}
.fa-briefcase:before {
content: "\f0b1";
}
.fa-arrows-alt:before {
content: "\f0b2";
}
.fa-group:before,
.fa-users:before {
content: "\f0c0";
}
.fa-chain:before,
.fa-link:before {
content: "\f0c1";
}
.fa-cloud:before {
content: "\f0c2";
}
.fa-flask:before {
content: "\f0c3";
}
.fa-cut:before,
.fa-scissors:before {
content: "\f0c4";
}
.fa-copy:before,
.fa-files-o:before {
content: "\f0c5";
}
.fa-paperclip:before {
content: "\f0c6";
}
.fa-save:before,
.fa-floppy-o:before {
content: "\f0c7";
}
.fa-square:before {
content: "\f0c8";
}
.fa-navicon:before,
.fa-reorder:before,
.fa-bars:before {
content: "\f0c9";
}
.fa-list-ul:before {
content: "\f0ca";
}
.fa-list-ol:before {
content: "\f0cb";
}
.fa-strikethrough:before {
content: "\f0cc";
}
.fa-underline:before {
content: "\f0cd";
}
.fa-table:before {
content: "\f0ce";
}
.fa-magic:before {
content: "\f0d0";
}
.fa-truck:before {
content: "\f0d1";
}
.fa-pinterest:before {
content: "\f0d2";
}
.fa-pinterest-square:before {
content: "\f0d3";
}
.fa-google-plus-square:before {
content: "\f0d4";
}
.fa-google-plus:before {
content: "\f0d5";
}
.fa-money:before {
content: "\f0d6";
}
.fa-caret-down:before {
content: "\f0d7";
}
.fa-caret-up:before {
content: "\f0d8";
}
.fa-caret-left:before {
content: "\f0d9";
}
.fa-caret-right:before {
content: "\f0da";
}
.fa-columns:before {
content: "\f0db";
}
.fa-unsorted:before,
.fa-sort:before {
content: "\f0dc";
}
.fa-sort-down:before,
.fa-sort-desc:before {
content: "\f0dd";
}
.fa-sort-up:before,
.fa-sort-asc:before {
content: "\f0de";
}
.fa-envelope:before {
content: "\f0e0";
}
.fa-linkedin:before {
content: "\f0e1";
}
.fa-rotate-left:before,
.fa-undo:before {
content: "\f0e2";
}
.fa-legal:before,
.fa-gavel:before {
content: "\f0e3";
}
.fa-dashboard:before,
.fa-tachometer:before {
content: "\f0e4";
}
.fa-comment-o:before {
content: "\f0e5";
}
.fa-comments-o:before {
content: "\f0e6";
}
.fa-flash:before,
.fa-bolt:before {
content: "\f0e7";
}
.fa-sitemap:before {
content: "\f0e8";
}
.fa-umbrella:before {
content: "\f0e9";
}
.fa-paste:before,
.fa-clipboard:before {
content: "\f0ea";
}
.fa-lightbulb-o:before {
content: "\f0eb";
}
.fa-exchange:before {
content: "\f0ec";
}
.fa-cloud-download:before {
content: "\f0ed";
}
.fa-cloud-upload:before {
content: "\f0ee";
}
.fa-user-md:before {
content: "\f0f0";
}
.fa-stethoscope:before {
content: "\f0f1";
}
.fa-suitcase:before {
content: "\f0f2";
}
.fa-bell-o:before {
content: "\f0a2";
}
.fa-coffee:before {
content: "\f0f4";
}
.fa-cutlery:before {
content: "\f0f5";
}
.fa-file-text-o:before {
content: "\f0f6";
}
.fa-building-o:before {
content: "\f0f7";
}
.fa-hospital-o:before {
content: "\f0f8";
}
.fa-ambulance:before {
content: "\f0f9";
}
.fa-medkit:before {
content: "\f0fa";
}
.fa-fighter-jet:before {
content: "\f0fb";
}
.fa-beer:before {
content: "\f0fc";
}
.fa-h-square:before {
content: "\f0fd";
}
.fa-plus-square:before {
content: "\f0fe";
}
.fa-angle-double-left:before {
content: "\f100";
}
.fa-angle-double-right:before {
content: "\f101";
}
.fa-angle-double-up:before {
content: "\f102";
}
.fa-angle-double-down:before {
content: "\f103";
}
.fa-angle-left:before {
content: "\f104";
}
.fa-angle-right:before {
content: "\f105";
}
.fa-angle-up:before {
content: "\f106";
}
.fa-angle-down:before {
content: "\f107";
}
.fa-desktop:before {
content: "\f108";
}
.fa-laptop:before {
content: "\f109";
}
.fa-tablet:before {
content: "\f10a";
}
.fa-mobile-phone:before,
.fa-mobile:before {
content: "\f10b";
}
.fa-circle-o:before {
content: "\f10c";
}
.fa-quote-left:before {
content: "\f10d";
}
.fa-quote-right:before {
content: "\f10e";
}
.fa-spinner:before {
content: "\f110";
}
.fa-circle:before {
content: "\f111";
}
.fa-mail-reply:before,
.fa-reply:before {
content: "\f112";
}
.fa-github-alt:before {
content: "\f113";
}
.fa-folder-o:before {
content: "\f114";
}
.fa-folder-open-o:before {
content: "\f115";
}
.fa-smile-o:before {
content: "\f118";
}
.fa-frown-o:before {
content: "\f119";
}
.fa-meh-o:before {
content: "\f11a";
}
.fa-gamepad:before {
content: "\f11b";
}
.fa-keyboard-o:before {
content: "\f11c";
}
.fa-flag-o:before {
content: "\f11d";
}
.fa-flag-checkered:before {
content: "\f11e";
}
.fa-terminal:before {
content: "\f120";
}
.fa-code:before {
content: "\f121";
}
.fa-mail-reply-all:before,
.fa-reply-all:before {
content: "\f122";
}
.fa-star-half-empty:before,
.fa-star-half-full:before,
.fa-star-half-o:before {
content: "\f123";
}
.fa-location-arrow:before {
content: "\f124";
}
.fa-crop:before {
content: "\f125";
}
.fa-code-fork:before {
content: "\f126";
}
.fa-unlink:before,
.fa-chain-broken:before {
content: "\f127";
}
.fa-question:before {
content: "\f128";
}
.fa-info:before {
content: "\f129";
}
.fa-exclamation:before {
content: "\f12a";
}
.fa-superscript:before {
content: "\f12b";
}
.fa-subscript:before {
content: "\f12c";
}
.fa-eraser:before {
content: "\f12d";
}
.fa-puzzle-piece:before {
content: "\f12e";
}
.fa-microphone:before {
content: "\f130";
}
.fa-microphone-slash:before {
content: "\f131";
}
.fa-shield:before {
content: "\f132";
}
.fa-calendar-o:before {
content: "\f133";
}
.fa-fire-extinguisher:before {
content: "\f134";
}
.fa-rocket:before {
content: "\f135";
}
.fa-maxcdn:before {
content: "\f136";
}
.fa-chevron-circle-left:before {
content: "\f137";
}
.fa-chevron-circle-right:before {
content: "\f138";
}
.fa-chevron-circle-up:before {
content: "\f139";
}
.fa-chevron-circle-down:before {
content: "\f13a";
}
.fa-html5:before {
content: "\f13b";
}
.fa-css3:before {
content: "\f13c";
}
.fa-anchor:before {
content: "\f13d";
}
.fa-unlock-alt:before {
content: "\f13e";
}
.fa-bullseye:before {
content: "\f140";
}
.fa-ellipsis-h:before {
content: "\f141";
}
.fa-ellipsis-v:before {
content: "\f142";
}
.fa-rss-square:before {
content: "\f143";
}
.fa-play-circle:before {
content: "\f144";
}
.fa-ticket:before {
content: "\f145";
}
.fa-minus-square:before {
content: "\f146";
}
.fa-minus-square-o:before {
content: "\f147";
}
.fa-level-up:before {
content: "\f148";
}
.fa-level-down:before {
content: "\f149";
}
.fa-check-square:before {
content: "\f14a";
}
.fa-pencil-alt-square:before {
content: "\f14b";
}
.fa-external-link-square:before {
content: "\f14c";
}
.fa-share-square:before {
content: "\f14d";
}
.fa-compass:before {
content: "\f14e";
}
.fa-toggle-down:before,
.fa-caret-square-o-down:before {
content: "\f150";
}
.fa-toggle-up:before,
.fa-caret-square-o-up:before {
content: "\f151";
}
.fa-toggle-right:before,
.fa-caret-square-o-right:before {
content: "\f152";
}
.fa-euro:before,
.fa-eur:before {
content: "\f153";
}
.fa-gbp:before {
content: "\f154";
}
.fa-dollar:before,
.fa-usd:before {
content: "\f155";
}
.fa-rupee:before,
.fa-inr:before {
content: "\f156";
}
.fa-cny:before,
.fa-rmb:before,
.fa-yen:before,
.fa-jpy:before {
content: "\f157";
}
.fa-ruble:before,
.fa-rouble:before,
.fa-rub:before {
content: "\f158";
}
.fa-won:before,
.fa-krw:before {
content: "\f159";
}
.fa-bitcoin:before,
.fa-btc:before {
content: "\f15a";
}
.fa-file:before {
content: "\f15b";
}
.fa-file-text:before {
content: "\f15c";
}
.fa-sort-alpha-asc:before {
content: "\f15d";
}
.fa-sort-alpha-desc:before {
content: "\f15e";
}
.fa-sort-amount-asc:before {
content: "\f160";
}
.fa-sort-amount-desc:before {
content: "\f161";
}
.fa-sort-numeric-asc:before {
content: "\f162";
}
.fa-sort-numeric-desc:before {
content: "\f163";
}
.fa-thumbs-up:before {
content: "\f164";
}
.fa-thumbs-down:before {
content: "\f165";
}
.fa-youtube-square:before {
content: "\f166";
}
.fa-youtube:before {
content: "\f167";
}
.fa-xing:before {
content: "\f168";
}
.fa-xing-square:before {
content: "\f169";
}
.fa-youtube-play:before {
content: "\f16a";
}
.fa-dropbox:before {
content: "\f16b";
}
.fa-stack-overflow:before {
content: "\f16c";
}
.fa-instagram:before {
content: "\f16d";
}
.fa-flickr:before {
content: "\f16e";
}
.fa-adn:before {
content: "\f170";
}
.fa-bitbucket:before {
content: "\f171";
}
.fa-bitbucket-square:before {
content: "\f172";
}
.fa-tumblr:before {
content: "\f173";
}
.fa-tumblr-square:before {
content: "\f174";
}
.fa-long-arrow-down:before {
content: "\f175";
}
.fa-long-arrow-up:before {
content: "\f176";
}
.fa-long-arrow-left:before {
content: "\f177";
}
.fa-long-arrow-right:before {
content: "\f178";
}
.fa-apple:before {
content: "\f179";
}
.fa-windows:before {
content: "\f17a";
}
.fa-android:before {
content: "\f17b";
}
.fa-linux:before {
content: "\f17c";
}
.fa-dribbble:before {
content: "\f17d";
}
.fa-skype:before {
content: "\f17e";
}
.fa-foursquare:before {
content: "\f180";
}
.fa-trello:before {
content: "\f181";
}
.fa-female:before {
content: "\f182";
}
.fa-male:before {
content: "\f183";
}
.fa-gittip:before,
.fa-gratipay:before {
content: "\f184";
}
.fa-sun-o:before {
content: "\f185";
}
.fa-moon-o:before {
content: "\f186";
}
.fa-archive:before {
content: "\f187";
}
.fa-bug:before {
content: "\f188";
}
.fa-vk:before {
content: "\f189";
}
.fa-weibo:before {
content: "\f18a";
}
.fa-renren:before {
content: "\f18b";
}
.fa-pagelines:before {
content: "\f18c";
}
.fa-stack-exchange:before {
content: "\f18d";
}
.fa-arrow-circle-o-right:before {
content: "\f18e";
}
.fa-arrow-circle-o-left:before {
content: "\f190";
}
.fa-toggle-left:before,
.fa-caret-square-o-left:before {
content: "\f191";
}
.fa-dot-circle-o:before {
content: "\f192";
}
.fa-wheelchair:before {
content: "\f193";
}
.fa-vimeo-square:before {
content: "\f194";
}
.fa-turkish-lira:before,
.fa-try:before {
content: "\f195";
}
.fa-plus-square-o:before {
content: "\f196";
}
.fa-space-shuttle:before {
content: "\f197";
}
.fa-slack:before {
content: "\f198";
}
.fa-envelope-square:before {
content: "\f199";
}
.fa-wordpress:before {
content: "\f19a";
}
.fa-openid:before {
content: "\f19b";
}
.fa-institution:before,
.fa-bank:before,
.fa-university:before {
content: "\f19c";
}
.fa-mortar-board:before,
.fa-graduation-cap:before {
content: "\f19d";
}
.fa-yahoo:before {
content: "\f19e";
}
.fa-google:before {
content: "\f1a0";
}
.fa-reddit:before {
content: "\f1a1";
}
.fa-reddit-square:before {
content: "\f1a2";
}
.fa-stumbleupon-circle:before {
content: "\f1a3";
}
.fa-stumbleupon:before {
content: "\f1a4";
}
.fa-delicious:before {
content: "\f1a5";
}
.fa-digg:before {
content: "\f1a6";
}
.fa-pied-piper-pp:before {
content: "\f1a7";
}
.fa-pied-piper-alt:before {
content: "\f1a8";
}
.fa-drupal:before {
content: "\f1a9";
}
.fa-joomla:before {
content: "\f1aa";
}
.fa-language:before {
content: "\f1ab";
}
.fa-fax:before {
content: "\f1ac";
}
.fa-building:before {
content: "\f1ad";
}
.fa-child:before {
content: "\f1ae";
}
.fa-paw:before {
content: "\f1b0";
}
.fa-spoon:before {
content: "\f1b1";
}
.fa-cube:before {
content: "\f1b2";
}
.fa-cubes:before {
content: "\f1b3";
}
.fa-behance:before {
content: "\f1b4";
}
.fa-behance-square:before {
content: "\f1b5";
}
.fa-steam:before {
content: "\f1b6";
}
.fa-steam-square:before {
content: "\f1b7";
}
.fa-recycle:before {
content: "\f1b8";
}
.fa-automobile:before,
.fa-car:before {
content: "\f1b9";
}
.fa-cab:before,
.fa-taxi:before {
content: "\f1ba";
}
.fa-tree:before {
content: "\f1bb";
}
.fa-spotify:before {
content: "\f1bc";
}
.fa-deviantart:before {
content: "\f1bd";
}
.fa-soundcloud:before {
content: "\f1be";
}
.fa-database:before {
content: "\f1c0";
}
.fa-file-pdf-o:before {
content: "\f1c1";
}
.fa-file-word-o:before {
content: "\f1c2";
}
.fa-file-excel-o:before {
content: "\f1c3";
}
.fa-file-powerpoint-o:before {
content: "\f1c4";
}
.fa-file-photo-o:before,
.fa-file-picture-o:before,
.fa-file-image-o:before {
content: "\f1c5";
}
.fa-file-zip-o:before,
.fa-file-archive-o:before {
content: "\f1c6";
}
.fa-file-sound-o:before,
.fa-file-audio-o:before {
content: "\f1c7";
}
.fa-file-movie-o:before,
.fa-file-video-o:before {
content: "\f1c8";
}
.fa-file-code-o:before {
content: "\f1c9";
}
.fa-vine:before {
content: "\f1ca";
}
.fa-codepen:before {
content: "\f1cb";
}
.fa-jsfiddle:before {
content: "\f1cc";
}
.fa-life-bouy:before,
.fa-life-buoy:before,
.fa-life-saver:before,
.fa-support:before,
.fa-life-ring:before {
content: "\f1cd";
}
.fa-circle-o-notch:before {
content: "\f1ce";
}
.fa-ra:before,
.fa-resistance:before,
.fa-rebel:before {
content: "\f1d0";
}
.fa-ge:before,
.fa-empire:before {
content: "\f1d1";
}
.fa-git-square:before {
content: "\f1d2";
}
.fa-git:before {
content: "\f1d3";
}
.fa-y-combinator-square:before,
.fa-yc-square:before,
.fa-hacker-news:before {
content: "\f1d4";
}
.fa-tencent-weibo:before {
content: "\f1d5";
}
.fa-qq:before {
content: "\f1d6";
}
.fa-wechat:before,
.fa-weixin:before {
content: "\f1d7";
}
.fa-send:before,
.fa-paper-plane:before {
content: "\f1d8";
}
.fa-send-o:before,
.fa-paper-plane-o:before {
content: "\f1d9";
}
.fa-history:before {
content: "\f1da";
}
.fa-circle-thin:before {
content: "\f1db";
}
.fa-header:before {
content: "\f1dc";
}
.fa-paragraph:before {
content: "\f1dd";
}
.fa-sliders:before {
content: "\f1de";
}
.fa-share-alt:before {
content: "\f1e0";
}
.fa-share-alt-square:before {
content: "\f1e1";
}
.fa-bomb:before {
content: "\f1e2";
}
.fa-soccer-ball-o:before,
.fa-futbol-o:before {
content: "\f1e3";
}
.fa-tty:before {
content: "\f1e4";
}
.fa-binoculars:before {
content: "\f1e5";
}
.fa-plug:before {
content: "\f1e6";
}
.fa-slideshare:before {
content: "\f1e7";
}
.fa-twitch:before {
content: "\f1e8";
}
.fa-yelp:before {
content: "\f1e9";
}
.fa-newspaper-o:before {
content: "\f1ea";
}
.fa-wifi:before {
content: "\f1eb";
}
.fa-calculator:before {
content: "\f1ec";
}
.fa-paypal:before {
content: "\f1ed";
}
.fa-google-wallet:before {
content: "\f1ee";
}
.fa-cc-visa:before {
content: "\f1f0";
}
.fa-cc-mastercard:before {
content: "\f1f1";
}
.fa-cc-discover:before {
content: "\f1f2";
}
.fa-cc-amex:before {
content: "\f1f3";
}
.fa-cc-paypal:before {
content: "\f1f4";
}
.fa-cc-stripe:before {
content: "\f1f5";
}
.fa-bell-slash:before {
content: "\f1f6";
}
.fa-bell-slash-o:before {
content: "\f1f7";
}
.fa-trash:before {
content: "\f1f8";
}
.fa-copyright:before {
content: "\f1f9";
}
.fa-at:before {
content: "\f1fa";
}
.fa-eyedropper:before {
content: "\f1fb";
}
.fa-paint-brush:before {
content: "\f1fc";
}
.fa-birthday-cake:before {
content: "\f1fd";
}
.fa-area-chart:before {
content: "\f1fe";
}
.fa-pie-chart:before {
content: "\f200";
}
.fa-line-chart:before {
content: "\f201";
}
.fa-lastfm:before {
content: "\f202";
}
.fa-lastfm-square:before {
content: "\f203";
}
.fa-toggle-off:before {
content: "\f204";
}
.fa-toggle-on:before {
content: "\f205";
}
.fa-bicycle:before {
content: "\f206";
}
.fa-bus:before {
content: "\f207";
}
.fa-ioxhost:before {
content: "\f208";
}
.fa-angellist:before {
content: "\f209";
}
.fa-cc:before {
content: "\f20a";
}
.fa-shekel:before,
.fa-sheqel:before,
.fa-ils:before {
content: "\f20b";
}
.fa-meanpath:before {
content: "\f20c";
}
.fa-buysellads:before {
content: "\f20d";
}
.fa-connectdevelop:before {
content: "\f20e";
}
.fa-dashcube:before {
content: "\f210";
}
.fa-forumbee:before {
content: "\f211";
}
.fa-leanpub:before {
content: "\f212";
}
.fa-sellsy:before {
content: "\f213";
}
.fa-shirtsinbulk:before {
content: "\f214";
}
.fa-simplybuilt:before {
content: "\f215";
}
.fa-skyatlas:before {
content: "\f216";
}
.fa-cart-plus:before {
content: "\f217";
}
.fa-cart-arrow-down:before {
content: "\f218";
}
.fa-diamond:before {
content: "\f219";
}
.fa-ship:before {
content: "\f21a";
}
.fa-user-secret:before {
content: "\f21b";
}
.fa-motorcycle:before {
content: "\f21c";
}
.fa-street-view:before {
content: "\f21d";
}
.fa-heartbeat:before {
content: "\f21e";
}
.fa-venus:before {
content: "\f221";
}
.fa-mars:before {
content: "\f222";
}
.fa-mercury:before {
content: "\f223";
}
.fa-intersex:before,
.fa-transgender:before {
content: "\f224";
}
.fa-transgender-alt:before {
content: "\f225";
}
.fa-venus-double:before {
content: "\f226";
}
.fa-mars-double:before {
content: "\f227";
}
.fa-venus-mars:before {
content: "\f228";
}
.fa-mars-stroke:before {
content: "\f229";
}
.fa-mars-stroke-v:before {
content: "\f22a";
}
.fa-mars-stroke-h:before {
content: "\f22b";
}
.fa-neuter:before {
content: "\f22c";
}
.fa-genderless:before {
content: "\f22d";
}
.fa-facebook-official:before {
content: "\f230";
}
.fa-pinterest-p:before {
content: "\f231";
}
.fa-whatsapp:before {
content: "\f232";
}
.fa-server:before {
content: "\f233";
}
.fa-user-plus:before {
content: "\f234";
}
.fa-user-times:before {
content: "\f235";
}
.fa-hotel:before,
.fa-bed:before {
content: "\f236";
}
.fa-viacoin:before {
content: "\f237";
}
.fa-train:before {
content: "\f238";
}
.fa-subway:before {
content: "\f239";
}
.fa-medium:before {
content: "\f23a";
}
.fa-yc:before,
.fa-y-combinator:before {
content: "\f23b";
}
.fa-optin-monster:before {
content: "\f23c";
}
.fa-opencart:before {
content: "\f23d";
}
.fa-expeditedssl:before {
content: "\f23e";
}
.fa-battery-4:before,
.fa-battery:before,
.fa-battery-full:before {
content: "\f240";
}
.fa-battery-3:before,
.fa-battery-three-quarters:before {
content: "\f241";
}
.fa-battery-2:before,
.fa-battery-half:before {
content: "\f242";
}
.fa-battery-1:before,
.fa-battery-quarter:before {
content: "\f243";
}
.fa-battery-0:before,
.fa-battery-empty:before {
content: "\f244";
}
.fa-mouse-pointer:before {
content: "\f245";
}
.fa-i-cursor:before {
content: "\f246";
}
.fa-object-group:before {
content: "\f247";
}
.fa-object-ungroup:before {
content: "\f248";
}
.fa-sticky-note:before {
content: "\f249";
}
.fa-sticky-note-o:before {
content: "\f24a";
}
.fa-cc-jcb:before {
content: "\f24b";
}
.fa-cc-diners-club:before {
content: "\f24c";
}
.fa-clone:before {
content: "\f24d";
}
.fa-balance-scale:before {
content: "\f24e";
}
.fa-hourglass-o:before {
content: "\f250";
}
.fa-hourglass-1:before,
.fa-hourglass-start:before {
content: "\f251";
}
.fa-hourglass-2:before,
.fa-hourglass-half:before {
content: "\f252";
}
.fa-hourglass-3:before,
.fa-hourglass-end:before {
content: "\f253";
}
.fa-hourglass:before {
content: "\f254";
}
.fa-hand-grab-o:before,
.fa-hand-rock-o:before {
content: "\f255";
}
.fa-hand-stop-o:before,
.fa-hand-paper-o:before {
content: "\f256";
}
.fa-hand-scissors-o:before {
content: "\f257";
}
.fa-hand-lizard-o:before {
content: "\f258";
}
.fa-hand-spock-o:before {
content: "\f259";
}
.fa-hand-pointer-o:before {
content: "\f25a";
}
.fa-hand-peace-o:before {
content: "\f25b";
}
.fa-trademark:before {
content: "\f25c";
}
.fa-registered:before {
content: "\f25d";
}
.fa-creative-commons:before {
content: "\f25e";
}
.fa-gg:before {
content: "\f260";
}
.fa-gg-circle:before {
content: "\f261";
}
.fa-tripadvisor:before {
content: "\f262";
}
.fa-odnoklassniki:before {
content: "\f263";
}
.fa-odnoklassniki-square:before {
content: "\f264";
}
.fa-get-pocket:before {
content: "\f265";
}
.fa-wikipedia-w:before {
content: "\f266";
}
.fa-safari:before {
content: "\f267";
}
.fa-chrome:before {
content: "\f268";
}
.fa-firefox:before {
content: "\f269";
}
.fa-opera:before {
content: "\f26a";
}
.fa-internet-explorer:before {
content: "\f26b";
}
.fa-tv:before,
.fa-television:before {
content: "\f26c";
}
.fa-contao:before {
content: "\f26d";
}
.fa-500px:before {
content: "\f26e";
}
.fa-amazon:before {
content: "\f270";
}
.fa-calendar-plus-o:before {
content: "\f271";
}
.fa-calendar-minus-o:before {
content: "\f272";
}
.fa-calendar-times-o:before {
content: "\f273";
}
.fa-calendar-check-o:before {
content: "\f274";
}
.fa-industry:before {
content: "\f275";
}
.fa-map-pin:before {
content: "\f276";
}
.fa-map-signs:before {
content: "\f277";
}
.fa-map-o:before {
content: "\f278";
}
.fa-map:before {
content: "\f279";
}
.fa-commenting:before {
content: "\f27a";
}
.fa-commenting-o:before {
content: "\f27b";
}
.fa-houzz:before {
content: "\f27c";
}
.fa-vimeo:before {
content: "\f27d";
}
.fa-black-tie:before {
content: "\f27e";
}
.fa-fonticons:before {
content: "\f280";
}
.fa-reddit-alien:before {
content: "\f281";
}
.fa-edge:before {
content: "\f282";
}
.fa-credit-card-alt:before {
content: "\f283";
}
.fa-codiepie:before {
content: "\f284";
}
.fa-modx:before {
content: "\f285";
}
.fa-fort-awesome:before {
content: "\f286";
}
.fa-usb:before {
content: "\f287";
}
.fa-product-hunt:before {
content: "\f288";
}
.fa-mixcloud:before {
content: "\f289";
}
.fa-scribd:before {
content: "\f28a";
}
.fa-pause-circle:before {
content: "\f28b";
}
.fa-pause-circle-o:before {
content: "\f28c";
}
.fa-stop-circle:before {
content: "\f28d";
}
.fa-stop-circle-o:before {
content: "\f28e";
}
.fa-shopping-bag:before {
content: "\f290";
}
.fa-shopping-basket:before {
content: "\f291";
}
.fa-hashtag:before {
content: "\f292";
}
.fa-bluetooth:before {
content: "\f293";
}
.fa-bluetooth-b:before {
content: "\f294";
}
.fa-percent:before {
content: "\f295";
}
.fa-gitlab:before {
content: "\f296";
}
.fa-wpbeginner:before {
content: "\f297";
}
.fa-wpforms:before {
content: "\f298";
}
.fa-envira:before {
content: "\f299";
}
.fa-universal-access:before {
content: "\f29a";
}
.fa-wheelchair-alt:before {
content: "\f29b";
}
.fa-question-circle-o:before {
content: "\f29c";
}
.fa-blind:before {
content: "\f29d";
}
.fa-audio-description:before {
content: "\f29e";
}
.fa-volume-control-phone:before {
content: "\f2a0";
}
.fa-braille:before {
content: "\f2a1";
}
.fa-assistive-listening-systems:before {
content: "\f2a2";
}
.fa-asl-interpreting:before,
.fa-american-sign-language-interpreting:before {
content: "\f2a3";
}
.fa-deafness:before,
.fa-hard-of-hearing:before,
.fa-deaf:before {
content: "\f2a4";
}
.fa-glide:before {
content: "\f2a5";
}
.fa-glide-g:before {
content: "\f2a6";
}
.fa-signing:before,
.fa-sign-language:before {
content: "\f2a7";
}
.fa-low-vision:before {
content: "\f2a8";
}
.fa-viadeo:before {
content: "\f2a9";
}
.fa-viadeo-square:before {
content: "\f2aa";
}
.fa-snapchat:before {
content: "\f2ab";
}
.fa-snapchat-ghost:before {
content: "\f2ac";
}
.fa-snapchat-square:before {
content: "\f2ad";
}
.fa-pied-piper:before {
content: "\f2ae";
}
.fa-first-order:before {
content: "\f2b0";
}
.fa-yoast:before {
content: "\f2b1";
}
.fa-themeisle:before {
content: "\f2b2";
}
.fa-google-plus-circle:before,
.fa-google-plus-official:before {
content: "\f2b3";
}
.fa-fa:before,
.fa-font-awesome:before {
content: "\f2b4";
}
.fa-handshake-o:before {
content: "\f2b5";
}
.fa-envelope-open:before {
content: "\f2b6";
}
.fa-envelope-open-o:before {
content: "\f2b7";
}
.fa-linode:before {
content: "\f2b8";
}
.fa-address-book:before {
content: "\f2b9";
}
.fa-address-book-o:before {
content: "\f2ba";
}
.fa-vcard:before,
.fa-address-card:before {
content: "\f2bb";
}
.fa-vcard-o:before,
.fa-address-card-o:before {
content: "\f2bc";
}
.fa-user-circle:before {
content: "\f2bd";
}
.fa-user-circle-o:before {
content: "\f2be";
}
.fa-user-o:before {
content: "\f2c0";
}
.fa-id-badge:before {
content: "\f2c1";
}
.fa-drivers-license:before,
.fa-id-card:before {
content: "\f2c2";
}
.fa-drivers-license-o:before,
.fa-id-card-o:before {
content: "\f2c3";
}
.fa-quora:before {
content: "\f2c4";
}
.fa-free-code-camp:before {
content: "\f2c5";
}
.fa-telegram:before {
content: "\f2c6";
}
.fa-thermometer-4:before,
.fa-thermometer:before,
.fa-thermometer-full:before {
content: "\f2c7";
}
.fa-thermometer-3:before,
.fa-thermometer-three-quarters:before {
content: "\f2c8";
}
.fa-thermometer-2:before,
.fa-thermometer-half:before {
content: "\f2c9";
}
.fa-thermometer-1:before,
.fa-thermometer-quarter:before {
content: "\f2ca";
}
.fa-thermometer-0:before,
.fa-thermometer-empty:before {
content: "\f2cb";
}
.fa-shower:before {
content: "\f2cc";
}
.fa-bathtub:before,
.fa-s15:before,
.fa-bath:before {
content: "\f2cd";
}
.fa-podcast:before {
content: "\f2ce";
}
.fa-window-maximize:before {
content: "\f2d0";
}
.fa-window-minimize:before {
content: "\f2d1";
}
.fa-window-restore:before {
content: "\f2d2";
}
.fa-times-rectangle:before,
.fa-window-close:before {
content: "\f2d3";
}
.fa-times-rectangle-o:before,
.fa-window-close-o:before {
content: "\f2d4";
}
.fa-bandcamp:before {
content: "\f2d5";
}
.fa-grav:before {
content: "\f2d6";
}
.fa-etsy:before {
content: "\f2d7";
}
.fa-imdb:before {
content: "\f2d8";
}
.fa-ravelry:before {
content: "\f2d9";
}
.fa-eercast:before {
content: "\f2da";
}
.fa-microchip:before {
content: "\f2db";
}
.fa-snowflake-o:before {
content: "\f2dc";
}
.fa-superpowers:before {
content: "\f2dd";
}
.fa-wpexplorer:before {
content: "\f2de";
}
.fa-meetup:before {
content: "\f2e0";
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
.sr-only-focusable:active,
.sr-only-focusable:focus {
position: static;
width: auto;
height: auto;
margin: 0;
overflow: visible;
clip: auto;
}
|
botswana-harvard/edc-call-manager
|
static/edc_base/css/font-awesome/css/font-awesome.css
|
CSS
|
gpl-2.0
| 37,413
|
/* Copyright (C) 2006 - 2012 ScriptDev2 <http://www.scriptdev2.com/>
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef DEF_TOC_H
#define DEF_TOC_H
enum
{
MAX_ENCOUNTER = 3,
TYPE_GRAND_CHAMPIONS = 0,
TYPE_ARGENT_CHALLENGE = 1,
TYPE_BLACK_KNIGHT = 2,
DATA_CHAMPION_1 = 3,
DATA_CHAMPION_2 = 4,
DATA_CHAMPION_3 = 5,
DATA_BLACK_KNIGHT = 6,
DATA_BLACK_KNIGHT_MINION = 7,
DATA_TOC5_ANNOUNCER = 8,
DATA_JAEREN = 9,
DATA_ARELAS = 10,
DATA_CHAMPIONID_1 = 11,
DATA_CHAMPIONID_2 = 12,
DATA_CHAMPIONID_3 = 13,
DATA_MEMORY = 14,
DATA_ARGENT_CHALLENGER = 15,
DATA_CHAMPIONS_COUNT = 16,
NPC_JACOB = 34705,
NPC_AMBROSE = 34702,
NPC_COLOSOS = 34701,
NPC_JAELYNE = 34657,
NPC_LANA = 34703,
NPC_MOKRA = 35572,
NPC_ERESSEA = 35569,
NPC_RUNOK = 35571,
NPC_ZULTORE = 35570,
NPC_VISCERI = 35617,
NPC_EADRIC = 35119,
NPC_PALETRESS = 34928,
NPC_BLACK_KNIGHT = 35451,
NPC_RISEN_JAEREN = 35545,
NPC_RISEN_ARELAS = 35564,
NPC_JAEREN = 35004,
NPC_ARELAS = 35005,
MEMORY_ALGALON = 35052,
MEMORY_ARCHIMONDE = 35041,
MEMORY_CHROMAGGUS = 35033,
MEMORY_CYANIGOSA = 35046,
MEMORY_DELRISSA = 35043,
MEMORY_ECK = 35047,
MEMORY_ENTROPIUS = 35044,
MEMORY_GRUUL = 35039,
MEMORY_HAKKAR = 35034,
MEMORY_HEIGAN = 35049,
MEMORY_HEROD = 35030,
MEMORY_HOGGER = 34942,
MEMORY_IGNIS = 35050,
MEMORY_ILLIDAN = 35042,
MEMORY_INGVAR = 35045,
MEMORY_KALITHRESH = 35037,
MEMORY_LUCIFRON = 35031,
MEMORY_MALCHEZAAR = 35038,
MEMORY_MUTANUS = 35029,
MEMORY_ONYXIA = 35048,
MEMORY_THUNDERAAN = 35032,
MEMORY_VANCLEEF = 35028,
MEMORY_VASHJ = 35040,
MEMORY_VEKNILASH = 35036,
MEMORY_VEZAX = 35051,
GO_CHAMPIONS_LOOT = 195709,
GO_CHAMPIONS_LOOT_H = 195710,
GO_EADRIC_LOOT = 195374,
GO_EADRIC_LOOT_H = 195375,
GO_PALETRESS_LOOT = 195323,
GO_PALETRESS_LOOT_H = 195324,
DESPAWN_TIME = 300000
};
#endif
|
Saitohimea/Mangos-3.3.5
|
src/modules/SD2/scripts/northrend/crusaders_coliseum/trial_of_the_champion/trial_of_the_champion.h
|
C
|
gpl-2.0
| 3,536
|
#pragma once
#include "zacdb.h"
#include "zdbmain.h"
class ZcDbViewport;
#pragma pack (push, 8)
class ZcDbAnnotativeObjectPE : public ZcRxObject
{
public:
ZCRX_DECLARE_MEMBERS(ZcDbAnnotativeObjectPE);
virtual bool annotative(ZcDbObject* pObject) const = 0;
virtual Zcad::ErrorStatus setAnnotative( ZcDbObject* pObject,
const bool bAnnotative ) = 0;
virtual Zcad::ErrorStatus setFromStyle(ZcDbObject* pObject,
bool& bUpdated) = 0;
virtual bool forceAnnoAllVisible(ZcDbObject* pObj) const { return false;} ;
virtual Zcad::ErrorStatus setForceAnnoAllVisible(ZcDbObject* pObj,
bool bForce) const
{return Zcad::eNotImplemented;}
virtual Zcad::ErrorStatus resetScaleDependentProperties (
ZcDbObject* pObject)
{return Zcad::eNotImplemented;}
};
class ZcDbPaperOrientationPE : public ZcRxObject
{
public:
ZCRX_DECLARE_MEMBERS(ZcDbPaperOrientationPE);
virtual bool paperOrientation(ZcDbObject* pObject) const = 0;
virtual Zcad::ErrorStatus setPaperOrientation(
ZcDbObject* pObject,
const bool bPaperOrientation ) = 0;
virtual Zcad::ErrorStatus applyPaperOrientationTransform (
ZcDbObject* pObject,
const ZcDbViewport *pVport ) const
{ return Zcad::eNotImplemented; }
};
#pragma pack (pop)
|
kevinzhwl/ZWCAD.DK
|
ZRXSDK/inc/zdbAnnotativeObjectPE.h
|
C
|
gpl-2.0
| 1,411
|
<?php
//$config['allowed'] = array_merge(
// Config::Get('menu.allowed'),
// array(
// 'blog_list',
// )
//);
$config['submenu'] = array(
'class' => 'dropdown-menu animated fadeIn dropdown-content-menu',
'options' => array(
'class' => 'dropdown dropdown-submenu',
'link_class' => 'dropdown-toggle',
'link_data' => array(
'toggle' => 'dropdown',
'role' => 'button',
'target' => '#',
),
),
);
/**
* Главное меню сайта + experience
* Настройки берутся из главного конфига меню common/config/menu.php
* Добавлены классы иконок
*/
$config['data']['main'] = array(
'list' => array(
'index' => array(
'options' => array(
// 'icon_class' => 'fa fa-file-text-o',
)
),
'blogs' => array(
'options' => array(
// 'icon_class' => 'fa fa-comment-o',
)
),
'people' => array(
'options' => array(
// 'icon_class' => 'fa fa-circle-o',
)
),
'stream' => array(
'options' => array(
// 'icon_class' => 'fa fa-signal',
)
),
)
);
/**
* Вход и регистрация + experience
*/
$config['data']['login'] = array(
'list' => array(
'login' => array(
'link' => '#',
'options' => array(
'link_class' => 'js-modal-auth-login'
),
),
'registration' => array(
'link' => '#',
'options' => array(
'link_class' => 'js-modal-auth-registration',
),
),
)
);
if (E::IsUser()) {
/**
* Меню пользователя + experience
*/
$config['data']['user'] = array(
'list' => array(
'userbar' => array(
'text' => array(
'user_name' => array(),
'count_messages' => array($sTemplate = '<span class="badge badge-danger badge-mail-counter">+{{count_messages}}</span>'),
' <span class="caret"></span>'
),
'options' => array(
'class' => 'dropdown',
'link_class' => 'dropdown-toggle user-button',
'image_url' => array('user_avatar_url' => array('32x32crop')),
'image_title' => array('user_name'),
'image_class' => 'user',
'link_data' => array(
'toggle' => 'dropdown',
'role' => 'button',
'target' => '#',
),
'data' => array(
'hidden-class' => 'btn',
),
),
),
'talk' => FALSE,
)
);
/**
* Меню пользователя + experience
*/
$config['data']['toolbar_user'] = array(
'init' => array(
'fill' => array(
'list' => array('*'),
),
),
'description' => '{{menu_user_description}}',
'list' => array(
'userbar' => array(
'text' => array(
'user_name' => array(),
'count_messages' => array('<span class="badge badge-danger badge-mail-counter">+{{count_messages}}</span>'),
),
'link' => E::User()->getProfileUrl(),
'options' => array(
'image_url' => array('user_avatar_url' => array('32x32crop')),
),
),
)
);
/**
* Подменю пользователя + experience
*/
$config['data']['toolbar_userbar'] = array(
'init' => array(
'fill' => array(
'list' => array('*'),
),
),
'description' => '{{menu_toolbar_userbar_description}}',
'class' => 'dropdown-menu dropdown-user-menu animated fadeIn',
'list' => array(
'user' => array(
'text' => '<span><i class="fa fa-user"></i></span><span>{{user_menu_profile}}</span>',
'link' => E::User()->getProfileUrl(),
'options' => array(
'class' => 'fixed-item',
)
),
'favourites' => array(
'text' => '<span><i class="fa fa-star"></i></span><span>{{user_menu_profile_favourites}}</span>',
'link' => E::User()->getProfileUrl() . 'favourites/topics/',
'options' => array(
'class' => 'fixed-item',
)
),
'talk' => array(
'text' => array(
'<span><i class="fa fa-envelope"></i></span><span>{{user_privat_messages}}</span>',
' <span class="new-messages">',
'new_talk_string' => array(),
'</span>'
),
'link' => Router::GetPath('talk'),
'options' => array(
'link_id' => 'new_messages',
'class' => 'fixed-item',
)
),
'settings' => array(
'text' => '<span><i class="fa fa-cog"></i></span><span>{{user_settings}}</span>',
'link' => '___path.root.url___/settings/',
'options' => array(
'class' => 'fixed-item',
)
),
'toolbar_userbar_item' => '',
'logout' => array(
'text' => '<span><i class="fa fa-sign-out"></i></span><span>{{exit}}</span>',
'link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey(),
'options' => array(
'class' => 'fixed-item',
)
),
)
);
/**
* Подменю пользователя + experience
*/
$config['data']['userbar'] = array(
'class' => 'dropdown-menu dropdown-user-menu animated fadeIn',
'list' => array(
'pre' => array(
'text' => FALSE,
'link' => FALSE,
'options' => array(
'class' => 'user_activity_items',
),
'submenu' => 'userinfo',
),
'user' => array(
'text' => '<i class="fa fa-user"></i> {{user_menu_profile}}',
'link' => E::User()->getProfileUrl(),
),
'create' => array(
'text' => '<i class="fa fa-pencil"></i> {{block_create}}',
'link' => '#',
'options' => array(
'data' => array(
'toggle' => 'modal',
'target' => '#modal-write',
),
),
),
'talk' => array(
'text' => array(
'<i class="fa fa-envelope-o"></i> {{user_privat_messages}}',
' <span class="new-messages">',
'new_talk_string' => array(),
'</span>'
),
'link' => Router::GetPath('talk'),
'options' => array(
'link_id' => 'new_messages',
)
),
'wall' => array(
'text' => '<i class="fa fa-bars"></i> {{user_menu_profile_wall}}',
'link' => E::User()->getProfileUrl() . 'wall/',
),
'publication' => array(
'text' => '<i class="fa fa-file-o"></i> {{user_menu_publication}}',
'link' => E::User()->getProfileUrl() . 'created/topics/',
),
'favourites' => array(
'text' => '<i class="fa fa-star-o"></i> {{user_menu_profile_favourites}}',
'link' => E::User()->getProfileUrl() . 'favourites/topics/',
),
'settings' => array(
'text' => '<i class="fa fa-cogs"></i> {{user_settings}}',
'link' => '___path.root.url___/settings/',
),
'userbar_item' => '',
'logout' => array(
'text' => '<i class="fa fa-sign-out"></i> {{exit}}',
'link' => Router::GetPath('login') . 'exit/?security_key=' . E::Security_GetSecurityKey(),
),
)
);
}
if (E::IsUser()) {
$config['data']['userinfo'] = array(
'init' => array(
'fill' => array(
'list' => array('*'),
),
),
'description' => 'Индикаторы пользователя',
'list' => array(
'user_rating' => array(
'text' => array(
'user_rating' => array('<i class="fa fa-bar-chart-o"></i>', 'negative'),
),
'link' => E::User()->getProfileUrl(),
'options' => array(
'class' => 'menu-item-user-rating',
),
),
'user_comments' => array(
'text' => array(
'count_track' => array('<i class="fa fa-bullhorn"></i>'),
),
'link' => Router::GetPath('feed') . 'track/',
'options' => array(
'class' => 'menu-item-user-comments',
),
),
'user_mails' => array(
'text' => array(
'new_talk_string' => array('<i class="fa fa-envelope-o"></i>'),
),
'link' => Router::GetPath('talk'),
'options' => array(
'class' => 'menu-item-user-talks',
),
),
)
);
}
/**
* Меню топиков
*/
C::Set('menu.data.topics.discussed.text', array(
'{{blog_menu_all_discussed}}',
' <i class="caret"></i>',
));
$config['data']['topics'] = array(
'class' => 'menu-topics',
'list' => array(
//'homepage' => array(
// 'options' => array(
// 'class' => '',
// )
//),
'good' => array(
'active' => array('topic_kind' => array('good')),
'options' => array(
'class' => 'menu-topics-good',
),
),
'new' => array(
'text' => array(
'{{blog_menu_all_new}}',
'new_topics_count' => array('red'),
),
'options' => array(
'class' => 'menu-topics-new',
'link_title' => '{{blog_menu_top_period_24h}}',
)
),
'newall' => array(
'options' => array(
'class' => 'menu-topics-all',
'link_title' => '{{blog_menu_top_period_24h}}',
)
),
'feed' => array(
'options' => array(
'class' => 'menu-topics-feed role-guest-hide',
)
),
'discussed' => array(
'text' => array(
'{{blog_menu_all_discussed}}',
' <i class="caret"></i>',
),
'submenu' => 'discussed',
'options' => array(
'class' => 'dropdown menu-topics-discussed',
'link_data' => array(
'toggle' => 'dropdown',
),
)
),
)
);
if (C::Get('rating.enabled')) {
$config['data']['topics']['list']['top'] = array(
'text' => array(
'{{blog_menu_all_top}}',
' <i class="caret"></i>',
),
'submenu' => 'top',
'options' => array(
'class' => 'dropdown menu-topics-top',
'link_data' => array(
'toggle' => 'dropdown',
),
),
);
}
/**
* Подменю обсуждаемых
*/
$config['data']['discussed'] = array(
'class' => 'dropdown-menu dropdown-content-menu animated fadeIn',
);
if (C::Get('rating.enabled')) {
/**
* Подменю топовых
*/
$config['data']['top'] = array(
'init' => array(
'fill' => array(
'list' => array('*'),
),
),
'class' => 'dropdown-menu dropdown-content-menu animated fadeIn',
'list' => array(
'24h' => array(
'text' => '{{blog_menu_top_period_24h}}',
'link' => '___path.root.url___/index/top/?period=1',
'active' => array('compare_get_param' => array('period', 1)),
),
'7d' => array(
'text' => '{{blog_menu_top_period_7d}}',
'link' => '___path.root.url___/index/top/?period=7',
'active' => array('compare_get_param' => array('period', 7)),
),
'30d' => array(
'text' => '{{blog_menu_top_period_30d}}',
'link' => '___path.root.url___/index/top/?period=30',
'active' => array('compare_get_param' => array('period', 30)),
),
'all' => array(
'text' => '{{blog_menu_top_period_all}}',
'link' => '___path.root.url___/index/top/?period=all',
'active' => array('compare_get_param' => array('period', 'all')),
),
)
);
}
$config['data']['image_insert'] = array(
'list' => array(
'insert_from_pc' => false,
'insert_from_link' => false,
)
);
$config['data']['footer_site_menu'] = array(
'class' => 'footer-column',
'list' => array(
'topic' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
'blogs' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
'people' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
'stream_menu' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
)
);
$config['data']['footer_info'] = array(
'class' => 'footer-column',
'list' => array(
'about' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
'rules' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
'advert' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
'help' => array(
'options' => array(
'link_class' => 'link link-dual link-lead link-clear',
)
),
)
);
|
shtrih/altocms
|
common/templates/skin/experience-simple/settings/config/menu.php
|
PHP
|
gpl-2.0
| 15,678
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Copyright (C) 1988-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Funding Free Software", the Front-Cover
Texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
"GNU Free Documentation License".
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development. -->
<!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Using the GNU Compiler Collection (GCC): Decimal Float</title>
<meta name="description" content="Using the GNU Compiler Collection (GCC): Decimal Float">
<meta name="keywords" content="Using the GNU Compiler Collection (GCC): Decimal Float">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="C-Extensions.html#C-Extensions" rel="up" title="C Extensions">
<link href="Hex-Floats.html#Hex-Floats" rel="next" title="Hex Floats">
<link href="Half_002dPrecision.html#Half_002dPrecision" rel="prev" title="Half-Precision">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="Decimal-Float"></a>
<div class="header">
<p>
Next: <a href="Hex-Floats.html#Hex-Floats" accesskey="n" rel="next">Hex Floats</a>, Previous: <a href="Half_002dPrecision.html#Half_002dPrecision" accesskey="p" rel="prev">Half-Precision</a>, Up: <a href="C-Extensions.html#C-Extensions" accesskey="u" rel="up">C Extensions</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Option-Index.html#Option-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Decimal-Floating-Types"></a>
<h3 class="section">6.13 Decimal Floating Types</h3>
<a name="index-decimal-floating-types"></a>
<a name="index-_005fDecimal32-data-type"></a>
<a name="index-_005fDecimal64-data-type"></a>
<a name="index-_005fDecimal128-data-type"></a>
<a name="index-df-integer-suffix"></a>
<a name="index-dd-integer-suffix"></a>
<a name="index-dl-integer-suffix"></a>
<a name="index-DF-integer-suffix"></a>
<a name="index-DD-integer-suffix"></a>
<a name="index-DL-integer-suffix"></a>
<p>As an extension, GNU C supports decimal floating types as
defined in the N1312 draft of ISO/IEC WDTR24732. Support for decimal
floating types in GCC will evolve as the draft technical report changes.
Calling conventions for any target might also change. Not all targets
support decimal floating types.
</p>
<p>The decimal floating types are <code>_Decimal32</code>, <code>_Decimal64</code>, and
<code>_Decimal128</code>. They use a radix of ten, unlike the floating types
<code>float</code>, <code>double</code>, and <code>long double</code> whose radix is not
specified by the C standard but is usually two.
</p>
<p>Support for decimal floating types includes the arithmetic operators
add, subtract, multiply, divide; unary arithmetic operators;
relational operators; equality operators; and conversions to and from
integer and other floating types. Use a suffix ‘<samp>df</samp>’ or
‘<samp>DF</samp>’ in a literal constant of type <code>_Decimal32</code>, ‘<samp>dd</samp>’
or ‘<samp>DD</samp>’ for <code>_Decimal64</code>, and ‘<samp>dl</samp>’ or ‘<samp>DL</samp>’ for
<code>_Decimal128</code>.
</p>
<p>GCC support of decimal float as specified by the draft technical report
is incomplete:
</p>
<ul>
<li> When the value of a decimal floating type cannot be represented in the
integer type to which it is being converted, the result is undefined
rather than the result value specified by the draft technical report.
</li><li> GCC does not provide the C library functionality associated with
<samp>math.h</samp>, <samp>fenv.h</samp>, <samp>stdio.h</samp>, <samp>stdlib.h</samp>, and
<samp>wchar.h</samp>, which must come from a separate C library implementation.
Because of this the GNU C compiler does not define macro
<code>__STDC_DEC_FP__</code> to indicate that the implementation conforms to
the technical report.
</li></ul>
<p>Types <code>_Decimal32</code>, <code>_Decimal64</code>, and <code>_Decimal128</code>
are supported by the DWARF 2 debug information format.
</p>
<hr>
<div class="header">
<p>
Next: <a href="Hex-Floats.html#Hex-Floats" accesskey="n" rel="next">Hex Floats</a>, Previous: <a href="Half_002dPrecision.html#Half_002dPrecision" accesskey="p" rel="prev">Half-Precision</a>, Up: <a href="C-Extensions.html#C-Extensions" accesskey="u" rel="up">C Extensions</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Option-Index.html#Option-Index" title="Index" rel="index">Index</a>]</p>
</div>
</body>
</html>
|
thanhphat11/android_kernel_xiaomi_msm8996
|
toolchains/share/doc/gcc/Decimal-Float.html
|
HTML
|
gpl-2.0
| 6,595
|
/*
* ircd-ratbox: A slightly useful ircd.
* m_nick.c: Sets a users nick.
*
* Copyright (C) 1990 Jarkko Oikarinen and University of Oulu, Co Center
* Copyright (C) 1996-2002 Hybrid Development Team
* Copyright (C) 2002-2005 ircd-ratbox development team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include "stdinc.h"
#include "client.h"
#include "hash.h"
#include "match.h"
#include "ircd.h"
#include "numeric.h"
#include "s_conf.h"
#include "s_stats.h"
#include "s_user.h"
#include "hash.h"
#include "whowas.h"
#include "s_serv.h"
#include "send.h"
#include "channel.h"
#include "logger.h"
#include "msg.h"
#include "parse.h"
#include "modules.h"
#include "packet.h"
#include "scache.h"
#include "s_newconf.h"
#include "monitor.h"
#include "s_assert.h"
/* Give all UID nicks the same TS. This ensures nick TS is always the same on
* all servers for each nick-user pair, also if a user with a UID nick changes
* their nick but is collided again (the server detecting the collision will
* not propagate the nick change further). -- jilles
*/
#define SAVE_NICKTS 100
static void mr_nick(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static void m_nick(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static void mc_nick(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static void ms_nick(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static void ms_uid(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static void ms_euid(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static void ms_save(struct MsgBuf *, struct Client *, struct Client *, int, const char **);
static bool can_save(struct Client *);
static void save_user(struct Client *, struct Client *, struct Client *);
static void bad_nickname(struct Client *, const char *);
static void change_remote_nick(struct Client *, struct Client *, time_t,
const char *, int);
static bool clean_username(const char *);
static bool clean_host(const char *);
static bool clean_uid(const char *uid, const char *sid);
static void set_initial_nick(struct Client *client_p, struct Client *source_p, char *nick);
static void change_local_nick(struct Client *client_p, struct Client *source_p, char *nick, int);
static void register_client(struct Client *client_p, struct Client *server,
const char *nick, time_t newts, int parc, const char *parv[]);
static void perform_nick_collides(struct Client *, struct Client *,
struct Client *, int, const char **,
time_t, const char *, const char *);
static void perform_nickchange_collides(struct Client *, struct Client *,
struct Client *, int, const char **, time_t, const char *);
static int h_local_nick_change;
static int h_remote_nick_change;
struct Message nick_msgtab = {
"NICK", 0, 0, 0, 0,
{{mr_nick, 0}, {m_nick, 0}, {mc_nick, 3}, {ms_nick, 0}, mg_ignore, {m_nick, 0}}
};
struct Message uid_msgtab = {
"UID", 0, 0, 0, 0,
{mg_ignore, mg_ignore, mg_ignore, {ms_uid, 9}, mg_ignore, mg_ignore}
};
struct Message euid_msgtab = {
"EUID", 0, 0, 0, 0,
{mg_ignore, mg_ignore, mg_ignore, {ms_euid, 12}, mg_ignore, mg_ignore}
};
struct Message save_msgtab = {
"SAVE", 0, 0, 0, 0,
{mg_ignore, mg_ignore, mg_ignore, {ms_save, 3}, mg_ignore, mg_ignore}
};
mapi_clist_av1 nick_clist[] = { &nick_msgtab, &uid_msgtab, &euid_msgtab,
&save_msgtab, NULL };
mapi_hlist_av1 nick_hlist[] = {
{ "local_nick_change", &h_local_nick_change },
{ "remote_nick_change", &h_remote_nick_change },
{ NULL, NULL }
};
static const char nick_desc[] =
"Provides the NICK client and server commands as well as the UID, EUID, and SAVE TS6 server commands";
DECLARE_MODULE_AV2(nick, NULL, NULL, nick_clist, nick_hlist, NULL, NULL, NULL, nick_desc);
/* mr_nick()
* parv[1] = nickname
*/
static void
mr_nick(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
struct Client *target_p;
char nick[NICKLEN];
if (strlen(client_p->id) == 3 || (source_p->preClient && !EmptyString(source_p->preClient->id)))
{
exit_client(client_p, client_p, client_p, "Mixing client and server protocol");
return;
}
if(parc < 2 || EmptyString(parv[1]))
{
sendto_one(source_p, form_str(ERR_NONICKNAMEGIVEN),
me.name, EmptyString(source_p->name) ? "*" : source_p->name);
return;
}
/* copy the nick and terminate it */
rb_strlcpy(nick, parv[1], ConfigFileEntry.nicklen);
/* check the nickname is ok */
if(!clean_nick(nick, 1))
{
sendto_one(source_p, form_str(ERR_ERRONEUSNICKNAME),
me.name, EmptyString(source_p->name) ? "*" : source_p->name, parv[1]);
return;
}
/* check if the nick is resv'd */
if(find_nick_resv(nick))
{
sendto_one(source_p, form_str(ERR_ERRONEUSNICKNAME),
me.name, EmptyString(source_p->name) ? "*" : source_p->name, nick);
return;
}
if(rb_dictionary_find(nd_dict, nick))
{
sendto_one(source_p, form_str(ERR_UNAVAILRESOURCE),
me.name, EmptyString(source_p->name) ? "*" : source_p->name, nick);
return;
}
if((target_p = find_named_client(nick)) == NULL)
set_initial_nick(client_p, source_p, nick);
else if(source_p == target_p)
rb_strlcpy(source_p->name, nick, sizeof(source_p->name));
else
sendto_one(source_p, form_str(ERR_NICKNAMEINUSE), me.name, "*", nick);
}
/* m_nick()
* parv[1] = nickname
*/
static void
m_nick(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
struct Client *target_p;
char nick[NICKLEN];
if(parc < 2 || EmptyString(parv[1]))
{
sendto_one(source_p, form_str(ERR_NONICKNAMEGIVEN), me.name, source_p->name);
return;
}
/* mark end of grace period, to prevent nickflooding */
if(!IsFloodDone(source_p))
flood_endgrace(source_p);
/* terminate nick to NICKLEN, we dont want clean_nick() to error! */
rb_strlcpy(nick, parv[1], ConfigFileEntry.nicklen);
/* check the nickname is ok */
if(!clean_nick(nick, 1))
{
sendto_one(source_p, form_str(ERR_ERRONEUSNICKNAME), me.name, source_p->name, nick);
return;
}
if(!IsExemptResv(source_p) && find_nick_resv(nick))
{
sendto_one(source_p, form_str(ERR_ERRONEUSNICKNAME), me.name, source_p->name, nick);
return;
}
if(rb_dictionary_find(nd_dict, nick))
{
sendto_one(source_p, form_str(ERR_UNAVAILRESOURCE),
me.name, EmptyString(source_p->name) ? "*" : source_p->name, nick);
return;
}
if((target_p = find_named_client(nick)))
{
/* If(target_p == source_p) the client is changing nicks between
* equivalent nicknames ie: [nick] -> {nick}
*/
if(target_p == source_p)
{
/* check the nick isnt exactly the same */
if(strcmp(target_p->name, nick))
change_local_nick(client_p, source_p, nick, 1);
}
/* drop unregged client */
else if(IsUnknown(target_p))
{
exit_client(NULL, target_p, &me, "Overridden");
change_local_nick(client_p, source_p, nick, 1);
}
else
sendto_one(source_p, form_str(ERR_NICKNAMEINUSE), me.name, source_p->name, nick);
return;
}
else
change_local_nick(client_p, source_p, nick, 1);
}
/* mc_nick()
*
* server -> server nick change
* parv[1] = nickname
* parv[2] = TS when nick change
*/
static void
mc_nick(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
struct Client *target_p;
time_t newts = 0;
/* if nicks erroneous, or too long, kill */
if(!clean_nick(parv[1], 0))
{
bad_nickname(client_p, parv[1]);
return;
}
newts = atol(parv[2]);
target_p = find_named_client(parv[1]);
/* if the nick doesnt exist, allow it and process like normal */
if(target_p == NULL)
{
change_remote_nick(client_p, source_p, newts, parv[1], 1);
}
else if(IsUnknown(target_p))
{
exit_client(NULL, target_p, &me, "Overridden");
change_remote_nick(client_p, source_p, newts, parv[1], 1);
}
else if(target_p == source_p)
{
/* client changing case of nick */
if(strcmp(target_p->name, parv[1]))
change_remote_nick(client_p, source_p, newts, parv[1], 1);
}
/* we've got a collision! */
else
perform_nickchange_collides(source_p, client_p, target_p,
parc, parv, newts, parv[1]);
}
static void
ms_nick(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
const char *nick, *server;
nick = parc > 1 ? parv[1] : "?";
server = parc > 7 ? parv[7] : "?";
sendto_wallops_flags(UMODE_WALLOP, &me,
"Link %s cancelled, TS5 nickname %s on %s introduced (old server?)",
client_p->name, nick, server);
sendto_server(NULL, NULL, CAP_TS6, NOCAPS,
":%s WALLOPS :Link %s cancelled, TS5 nickname %s on %s introduced (old server?)",
me.id, client_p->name, nick, server);
ilog(L_SERVER, "Link %s cancelled, TS5 nickname %s on %s introduced (old server?)",
client_p->name, nick, server);
exit_client(client_p, client_p, &me, "TS5 nickname introduced");
}
/* ms_uid()
* parv[1] - nickname
* parv[2] - hops
* parv[3] - TS
* parv[4] - umodes
* parv[5] - username
* parv[6] - hostname
* parv[7] - IP
* parv[8] - UID
* parv[9] - gecos
*/
static void
ms_uid(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
struct Client *target_p;
time_t newts = 0;
char squitreason[120];
newts = atol(parv[3]);
if(parc != 10)
{
sendto_realops_snomask(SNO_GENERAL, L_ALL,
"Dropping server %s due to (invalid) command 'UID' "
"with %d arguments (expecting 10)", client_p->name, parc);
ilog(L_SERVER, "Excess parameters (%d) for command 'UID' from %s.",
parc, client_p->name);
snprintf(squitreason, sizeof squitreason,
"Excess parameters (%d) to %s command, expecting %d",
parc, "UID", 10);
exit_client(client_p, client_p, client_p, squitreason);
return;
}
/* if nicks erroneous, or too long, kill */
if(!clean_nick(parv[1], 0))
{
bad_nickname(client_p, parv[1]);
return;
}
if(!clean_uid(parv[8], source_p->id))
{
snprintf(squitreason, sizeof squitreason,
"Invalid UID %s for nick %s on %s/%s",
parv[8], parv[1], source_p->name, source_p->id);
exit_client(client_p, client_p, client_p, squitreason);
return;
}
if(!clean_username(parv[5]) || !clean_host(parv[6]))
{
ServerStats.is_kill++;
sendto_realops_snomask(SNO_DEBUG, L_ALL,
"Bad user@host: %s@%s From: %s(via %s)",
parv[5], parv[6], source_p->name, client_p->name);
sendto_one(client_p, ":%s KILL %s :%s (Bad user@host)", me.id, parv[8], me.name);
return;
}
/* check length of clients gecos */
if(strlen(parv[9]) > REALLEN)
{
char *s = LOCAL_COPY(parv[9]);
sendto_realops_snomask(SNO_GENERAL, L_ALL, "Long realname from server %s for %s",
source_p->name, parv[1]);
s[REALLEN] = '\0';
parv[9] = s;
}
target_p = find_named_client(parv[1]);
if(target_p == NULL)
{
register_client(client_p, source_p, parv[1], newts, parc, parv);
}
else if(IsUnknown(target_p))
{
exit_client(NULL, target_p, &me, "Overridden");
register_client(client_p, source_p, parv[1], newts, parc, parv);
}
/* we've got a collision! */
else
perform_nick_collides(source_p, client_p, target_p, parc, parv,
newts, parv[1], parv[8]);
}
/* ms_euid()
* parv[1] - nickname
* parv[2] - hops
* parv[3] - TS
* parv[4] - umodes
* parv[5] - username
* parv[6] - hostname
* parv[7] - IP
* parv[8] - UID
* parv[9] - realhost
* parv[10] - account
* parv[11] - gecos
*/
static void
ms_euid(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
struct Client *target_p;
time_t newts = 0;
char squitreason[120];
newts = atol(parv[3]);
if(parc != 12)
{
sendto_realops_snomask(SNO_GENERAL, L_ALL,
"Dropping server %s due to (invalid) command 'EUID' "
"with %d arguments (expecting 12)", client_p->name, parc);
ilog(L_SERVER, "Excess parameters (%d) for command 'EUID' from %s.",
parc, client_p->name);
snprintf(squitreason, sizeof squitreason,
"Excess parameters (%d) to %s command, expecting %d",
parc, "EUID", 12);
exit_client(client_p, client_p, client_p, squitreason);
return;
}
/* if nicks erroneous, or too long, kill */
if(!clean_nick(parv[1], 0))
{
bad_nickname(client_p, parv[1]);
return;
}
if(!clean_uid(parv[8], source_p->id))
{
snprintf(squitreason, sizeof squitreason,
"Invalid UID %s for nick %s on %s/%s",
parv[8], parv[1], source_p->name, source_p->id);
exit_client(client_p, client_p, client_p, squitreason);
return;
}
if(!clean_username(parv[5]) || !clean_host(parv[6]))
{
ServerStats.is_kill++;
sendto_realops_snomask(SNO_DEBUG, L_ALL,
"Bad user@host: %s@%s From: %s(via %s)",
parv[5], parv[6], source_p->name, client_p->name);
sendto_one(client_p, ":%s KILL %s :%s (Bad user@host)", me.id, parv[8], me.name);
return;
}
if(strcmp(parv[9], "*") && !clean_host(parv[9]))
{
ServerStats.is_kill++;
sendto_realops_snomask(SNO_DEBUG, L_ALL,
"Bad realhost: %s From: %s(via %s)",
parv[9], source_p->name, client_p->name);
sendto_one(client_p, ":%s KILL %s :%s (Bad user@host)", me.id, parv[8], me.name);
return;
}
/* check length of clients gecos */
if(strlen(parv[11]) > REALLEN)
{
char *s = LOCAL_COPY(parv[11]);
sendto_realops_snomask(SNO_GENERAL, L_ALL, "Long realname from server %s for %s",
source_p->name, parv[1]);
s[REALLEN] = '\0';
parv[11] = s;
}
target_p = find_named_client(parv[1]);
if(target_p == NULL)
{
register_client(client_p, source_p, parv[1], newts, parc, parv);
}
else if(IsUnknown(target_p))
{
exit_client(NULL, target_p, &me, "Overridden");
register_client(client_p, source_p, parv[1], newts, parc, parv);
}
/* we've got a collision! */
else
perform_nick_collides(source_p, client_p, target_p, parc, parv,
newts, parv[1], parv[8]);
}
/* ms_save()
* parv[1] - UID
* parv[2] - TS
*/
static void
ms_save(struct MsgBuf *msgbuf_p, struct Client *client_p, struct Client *source_p, int parc, const char *parv[])
{
struct Client *target_p;
target_p = find_id(parv[1]);
if (target_p == NULL)
return;
if (!IsPerson(target_p))
sendto_realops_snomask(SNO_GENERAL, L_ALL,
"Ignored SAVE message for non-person %s from %s",
target_p->name, source_p->name);
else if (IsDigit(target_p->name[0]))
sendto_realops_snomask(SNO_DEBUG, L_ALL,
"Ignored noop SAVE message for %s from %s",
target_p->name, source_p->name);
else if (target_p->tsinfo == atol(parv[2]))
save_user(client_p, source_p, target_p);
else
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Ignored SAVE message for %s from %s",
target_p->name, source_p->name);
}
/* clean_username()
*
* input - username to check
* output - false if erroneous, else true
* side effects -
*/
static bool
clean_username(const char *username)
{
int len = 0;
for(; *username; username++)
{
len++;
if(!IsUserChar(*username))
return false;
}
if(len > USERLEN)
return false;
return true;
}
/* clean_host()
*
* input - host to check
* output - false if erroneous, else true
* side effects -
*/
static bool
clean_host(const char *host)
{
int len = 0;
for(; *host; host++)
{
len++;
if(!IsHostChar(*host))
return false;
}
if(len > HOSTLEN)
return false;
return true;
}
static bool
clean_uid(const char *uid, const char *sid)
{
int len = 1;
if(strncmp(uid, sid, strlen(sid)))
return false;
if(!IsDigit(*uid++))
return false;
for(; *uid; uid++)
{
len++;
if(!IsIdChar(*uid))
return false;
}
if(len != IDLEN - 1)
return false;
return true;
}
static void
set_initial_nick(struct Client *client_p, struct Client *source_p, char *nick)
{
char note[NICKLEN + 10];
/* This had to be copied here to avoid problems.. */
source_p->tsinfo = rb_current_time();
if(source_p->name[0])
del_from_client_hash(source_p->name, source_p);
rb_strlcpy(source_p->name, nick, sizeof(source_p->name));
add_to_client_hash(nick, source_p);
snprintf(note, sizeof(note), "Nick: %s", nick);
rb_note(client_p->localClient->F, note);
if(source_p->flags & FLAGS_SENTUSER)
{
/* got user, heres nick. */
register_local_user(client_p, source_p);
}
}
static void
change_local_nick(struct Client *client_p, struct Client *source_p,
char *nick, int dosend)
{
struct Client *target_p;
rb_dlink_node *ptr, *next_ptr;
struct Channel *chptr;
char note[NICKLEN + 10];
int samenick;
hook_cdata hook_info;
if (dosend)
{
chptr = find_bannickchange_channel(source_p);
if (chptr != NULL)
{
sendto_one_numeric(source_p, ERR_BANNICKCHANGE,
form_str(ERR_BANNICKCHANGE),
nick, chptr->chname);
return;
}
if((source_p->localClient->last_nick_change + ConfigFileEntry.max_nick_time) < rb_current_time())
source_p->localClient->number_of_nick_changes = 0;
source_p->localClient->last_nick_change = rb_current_time();
source_p->localClient->number_of_nick_changes++;
if(ConfigFileEntry.anti_nick_flood && !IsOper(source_p) &&
source_p->localClient->number_of_nick_changes > ConfigFileEntry.max_nick_changes)
{
sendto_one(source_p, form_str(ERR_NICKTOOFAST),
me.name, source_p->name, source_p->name,
nick, ConfigFileEntry.max_nick_time);
return;
}
}
samenick = irccmp(source_p->name, nick) ? 0 : 1;
/* dont reset TS if theyre just changing case of nick */
if(!samenick)
{
/* force the TS to increase -- jilles */
if (source_p->tsinfo >= rb_current_time())
source_p->tsinfo++;
else
source_p->tsinfo = rb_current_time();
monitor_signoff(source_p);
/* we only do bancache for local users -- jilles */
if(source_p->user)
invalidate_bancache_user(source_p);
}
hook_info.client = source_p;
hook_info.arg1 = source_p->name;
hook_info.arg2 = nick;
call_hook(h_local_nick_change, &hook_info);
sendto_realops_snomask(SNO_NCHANGE, L_ALL,
"Nick change: From %s to %s [%s@%s]",
source_p->name, nick, source_p->username, source_p->host);
/* send the nick change to the users channels */
sendto_common_channels_local(source_p, NOCAPS, NOCAPS, ":%s!%s@%s NICK :%s",
source_p->name, source_p->username, source_p->host, nick);
/* send the nick change to servers.. */
if(source_p->user)
{
whowas_add_history(source_p, 1);
if (dosend)
{
sendto_server(client_p, NULL, CAP_TS6, NOCAPS, ":%s NICK %s :%ld",
use_id(source_p), nick, (long) source_p->tsinfo);
}
}
/* Finally, add to hash */
del_from_client_hash(source_p->name, source_p);
rb_strlcpy(source_p->name, nick, sizeof(source_p->name));
add_to_client_hash(nick, source_p);
if(!samenick)
monitor_signon(source_p);
/* Make sure everyone that has this client on its accept list
* loses that reference.
*/
/* we used to call del_all_accepts() here, but theres no real reason
* to clear a clients own list of accepted clients. So just remove
* them from everyone elses list --anfl
*/
RB_DLINK_FOREACH_SAFE(ptr, next_ptr, source_p->on_allow_list.head)
{
target_p = ptr->data;
rb_dlinkFindDestroy(source_p, &target_p->localClient->allow_list);
rb_dlinkDestroy(ptr, &source_p->on_allow_list);
}
snprintf(note, sizeof(note), "Nick: %s", nick);
rb_note(client_p->localClient->F, note);
return;
}
/*
* change_remote_nick()
*/
static void
change_remote_nick(struct Client *client_p, struct Client *source_p,
time_t newts, const char *nick, int dosend)
{
struct nd_entry *nd;
int samenick = irccmp(source_p->name, nick) ? 0 : 1;
hook_cdata hook_info;
/* client changing their nick - dont reset ts if its same */
if(!samenick)
{
source_p->tsinfo = newts ? newts : rb_current_time();
monitor_signoff(source_p);
}
hook_info.client = source_p;
hook_info.arg1 = source_p->name;
hook_info.arg2 = nick;
call_hook(h_remote_nick_change, &hook_info);
sendto_common_channels_local(source_p, NOCAPS, NOCAPS, ":%s!%s@%s NICK :%s",
source_p->name, source_p->username, source_p->host, nick);
if(source_p->user)
{
whowas_add_history(source_p, 1);
if (dosend)
{
sendto_server(client_p, NULL, CAP_TS6, NOCAPS, ":%s NICK %s :%ld",
use_id(source_p), nick, (long) source_p->tsinfo);
}
}
del_from_client_hash(source_p->name, source_p);
/* invalidate nick delay when a remote client uses the nick.. */
if((nd = rb_dictionary_retrieve(nd_dict, nick)))
free_nd_entry(nd);
rb_strlcpy(source_p->name, nick, sizeof(source_p->name));
add_to_client_hash(nick, source_p);
if(!samenick)
monitor_signon(source_p);
/* remove all accepts pointing to the client */
del_all_accepts(source_p);
}
static void
perform_nick_collides(struct Client *source_p, struct Client *client_p,
struct Client *target_p, int parc, const char *parv[],
time_t newts, const char *nick, const char *uid)
{
int sameuser;
int use_save;
const char *action;
use_save = ConfigFileEntry.collision_fnc && can_save(target_p) &&
uid != NULL && can_save(source_p);
action = use_save ? "saved" : "killed";
/* if we dont have a ts, or their TS's are the same, kill both */
if(!newts || !target_p->tsinfo || (newts == target_p->tsinfo))
{
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick collision on %s(%s <- %s)(both %s)",
target_p->name, target_p->from->name, client_p->name, action);
if (use_save)
{
save_user(&me, &me, target_p);
ServerStats.is_save++;
sendto_one(client_p, ":%s SAVE %s %ld", me.id,
uid, (long)newts);
register_client(client_p, source_p,
uid, SAVE_NICKTS, parc, parv);
}
else
{
sendto_one_numeric(target_p, ERR_NICKCOLLISION,
form_str(ERR_NICKCOLLISION), target_p->name);
/* if the new client being introduced has a UID, we need to
* issue a KILL for it..
*/
if(uid)
sendto_one(client_p, ":%s KILL %s :%s (Nick collision (new))",
me.id, uid, me.name);
/* we then need to KILL the old client everywhere */
kill_client_serv_butone(NULL, target_p, "%s (Nick collision (new))", me.name);
ServerStats.is_kill++;
target_p->flags |= FLAGS_KILLED;
exit_client(client_p, target_p, &me, "Nick collision (new)");
}
return;
}
/* the timestamps are different */
else
{
sameuser = (target_p->user) && !irccmp(target_p->username, parv[5])
&& !irccmp(target_p->host, parv[6]);
if((sameuser && newts < target_p->tsinfo) ||
(!sameuser && newts > target_p->tsinfo))
{
/* if we have a UID, then we need to issue a KILL,
* otherwise we do nothing and hope that the other
* client will collide it..
*/
if (use_save)
{
sendto_one(client_p, ":%s SAVE %s %ld", me.id,
uid, (long)newts);
register_client(client_p, source_p,
uid, SAVE_NICKTS, parc, parv);
}
else if(uid)
sendto_one(client_p,
":%s KILL %s :%s (Nick collision (new))",
me.id, uid, me.name);
return;
}
else
{
if(sameuser)
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick collision on %s(%s <- %s)(older %s)",
target_p->name, target_p->from->name,
client_p->name, action);
else
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick collision on %s(%s <- %s)(newer %s)",
target_p->name, target_p->from->name,
client_p->name, action);
if (use_save)
{
ServerStats.is_save++;
save_user(&me, &me, target_p);
}
else
{
ServerStats.is_kill++;
sendto_one_numeric(target_p, ERR_NICKCOLLISION,
form_str(ERR_NICKCOLLISION), target_p->name);
/* now we just need to kill the existing client */
kill_client_serv_butone(client_p, target_p,
"%s (Nick collision (new))", me.name);
target_p->flags |= FLAGS_KILLED;
(void) exit_client(client_p, target_p, &me, "Nick collision");
}
register_client(client_p, source_p,
nick, newts, parc, parv);
}
}
}
static void
perform_nickchange_collides(struct Client *source_p, struct Client *client_p,
struct Client *target_p, int parc,
const char *parv[], time_t newts, const char *nick)
{
int sameuser;
int use_save;
const char *action;
use_save = ConfigFileEntry.collision_fnc && can_save(target_p) &&
can_save(source_p);
action = use_save ? "saved" : "killed";
/* its a client changing nick and causing a collide */
if(!newts || !target_p->tsinfo || (newts == target_p->tsinfo) || !source_p->user)
{
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick change collision from %s to %s(%s <- %s)(both %s)",
source_p->name, target_p->name, target_p->from->name,
client_p->name, action);
if (use_save)
{
ServerStats.is_save += 2;
save_user(&me, &me, target_p);
sendto_one(client_p, ":%s SAVE %s %ld", me.id,
source_p->id, (long)newts);
/* don't send a redundant nick change */
if (!IsDigit(source_p->name[0]))
change_remote_nick(client_p, source_p, SAVE_NICKTS, source_p->id, 1);
}
else
{
ServerStats.is_kill++;
sendto_one_numeric(target_p, ERR_NICKCOLLISION,
form_str(ERR_NICKCOLLISION), target_p->name);
kill_client_serv_butone(NULL, source_p, "%s (Nick change collision)", me.name);
ServerStats.is_kill++;
kill_client_serv_butone(NULL, target_p, "%s (Nick change collision)", me.name);
target_p->flags |= FLAGS_KILLED;
exit_client(NULL, target_p, &me, "Nick collision(new)");
source_p->flags |= FLAGS_KILLED;
exit_client(client_p, source_p, &me, "Nick collision(old)");
}
return;
}
else
{
sameuser = !irccmp(target_p->username, source_p->username) &&
!irccmp(target_p->host, source_p->host);
if((sameuser && newts < target_p->tsinfo) ||
(!sameuser && newts > target_p->tsinfo))
{
if(sameuser)
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick change collision from %s to %s(%s <- %s)(older %s)",
source_p->name, target_p->name,
target_p->from->name, client_p->name, action);
else
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick change collision from %s to %s(%s <- %s)(newer %s)",
source_p->name, target_p->name,
target_p->from->name, client_p->name, action);
if (use_save)
{
ServerStats.is_save++;
/* can't broadcast a SAVE because the
* nickchange has happened at client_p
* but not in other directions -- jilles */
sendto_one(client_p, ":%s SAVE %s %ld", me.id,
source_p->id, (long)newts);
/* send a :<id> NICK <id> <ts> (!) */
if (!IsDigit(source_p->name[0]))
change_remote_nick(client_p, source_p, SAVE_NICKTS, source_p->id, 1);
}
else
{
ServerStats.is_kill++;
sendto_one_numeric(source_p, ERR_NICKCOLLISION,
form_str(ERR_NICKCOLLISION), source_p->name);
/* kill the client issuing the nickchange */
kill_client_serv_butone(client_p, source_p,
"%s (Nick change collision)", me.name);
source_p->flags |= FLAGS_KILLED;
if(sameuser)
exit_client(client_p, source_p, &me, "Nick collision(old)");
else
exit_client(client_p, source_p, &me, "Nick collision(new)");
}
return;
}
else
{
if(sameuser)
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick collision on %s(%s <- %s)(older %s)",
target_p->name, target_p->from->name,
client_p->name, action);
else
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Nick collision on %s(%s <- %s)(newer %s)",
target_p->name, target_p->from->name,
client_p->name, action);
if (use_save)
{
ServerStats.is_save++;
save_user(&me, &me, target_p);
}
else
{
sendto_one_numeric(target_p, ERR_NICKCOLLISION,
form_str(ERR_NICKCOLLISION), target_p->name);
/* kill the client who existed before hand */
kill_client_serv_butone(client_p, target_p, "%s (Nick collision)", me.name);
ServerStats.is_kill++;
target_p->flags |= FLAGS_KILLED;
(void) exit_client(client_p, target_p, &me, "Nick collision");
}
}
}
change_remote_nick(client_p, source_p, newts, nick, 1);
}
static void
register_client(struct Client *client_p, struct Client *server,
const char *nick, time_t newts, int parc, const char *parv[])
{
struct Client *source_p;
struct User *user;
struct nd_entry *nd;
const char *m;
int flag;
source_p = make_client(client_p);
user = make_user(source_p);
rb_dlinkAddTail(source_p, &source_p->node, &global_client_list);
source_p->hopcount = atoi(parv[2]);
source_p->tsinfo = newts;
rb_strlcpy(source_p->name, nick, sizeof(source_p->name));
rb_strlcpy(source_p->username, parv[5], sizeof(source_p->username));
rb_strlcpy(source_p->host, parv[6], sizeof(source_p->host));
rb_strlcpy(source_p->orighost, source_p->host, sizeof(source_p->orighost));
if(parc == 12)
{
rb_strlcpy(source_p->info, parv[11], sizeof(source_p->info));
rb_strlcpy(source_p->sockhost, parv[7], sizeof(source_p->sockhost));
rb_strlcpy(source_p->id, parv[8], sizeof(source_p->id));
add_to_id_hash(source_p->id, source_p);
if (strcmp(parv[9], "*"))
{
rb_strlcpy(source_p->orighost, parv[9], sizeof(source_p->orighost));
if (irccmp(source_p->host, source_p->orighost))
SetDynSpoof(source_p);
}
if (strcmp(parv[10], "*"))
rb_strlcpy(source_p->user->suser, parv[10], sizeof(source_p->user->suser));
}
else if(parc == 10)
{
rb_strlcpy(source_p->info, parv[9], sizeof(source_p->info));
rb_strlcpy(source_p->sockhost, parv[7], sizeof(source_p->sockhost));
rb_strlcpy(source_p->id, parv[8], sizeof(source_p->id));
add_to_id_hash(source_p->id, source_p);
}
else
{
s_assert(0);
}
/* remove any nd entries for this nick */
if((nd = rb_dictionary_retrieve(nd_dict, nick)))
free_nd_entry(nd);
add_to_client_hash(nick, source_p);
add_to_hostname_hash(source_p->orighost, source_p);
monitor_signon(source_p);
m = &parv[4][1];
while(*m)
{
flag = user_modes[(unsigned char) *m];
if(flag & UMODE_SERVICE)
{
int hit = 0;
rb_dlink_node *ptr;
RB_DLINK_FOREACH(ptr, service_list.head)
{
if(!irccmp((const char *) ptr->data, server->name))
{
hit++;
break;
}
}
if(!hit)
{
m++;
continue;
}
}
/* increment +i count if theyre invis */
if(!(source_p->umodes & UMODE_INVISIBLE) && (flag & UMODE_INVISIBLE))
Count.invisi++;
/* increment opered count if theyre opered */
if(!(source_p->umodes & UMODE_OPER) && (flag & UMODE_OPER))
Count.oper++;
source_p->umodes |= flag;
m++;
}
if(IsOper(source_p) && !IsService(source_p))
rb_dlinkAddAlloc(source_p, &oper_list);
SetRemoteClient(source_p);
if(++Count.total > Count.max_tot)
Count.max_tot = Count.total;
source_p->servptr = server;
rb_dlinkAdd(source_p, &source_p->lnode, &source_p->servptr->serv->users);
call_hook(h_new_remote_user, source_p);
introduce_client(client_p, source_p, user, nick, parc == 12);
}
/* Check if we can do SAVE. target_p can be a client to save or a
* server introducing a client -- jilles */
static bool
can_save(struct Client *target_p)
{
struct Client *serv_p;
if (MyClient(target_p))
return true;
if (!has_id(target_p))
return false;
serv_p = IsServer(target_p) ? target_p : target_p->servptr;
while (serv_p != NULL && serv_p != &me)
{
if (!(serv_p->serv->caps & CAP_SAVE))
return false;
serv_p = serv_p->servptr;
}
return serv_p == &me;
}
static void
save_user(struct Client *client_p, struct Client *source_p,
struct Client *target_p)
{
if (!MyConnect(target_p) && (!has_id(target_p) || !IsCapable(target_p->from, CAP_SAVE)))
{
/* This shouldn't happen */
/* Note we only need SAVE support in this direction */
sendto_realops_snomask(SNO_GENERAL, L_ALL,
"Killed %s!%s@%s for nick collision detected by %s (%s does not support SAVE)",
target_p->name, target_p->username, target_p->host, source_p->name, target_p->from->name);
kill_client_serv_butone(NULL, target_p, "%s (Nick collision (no SAVE support))", me.name);
ServerStats.is_kill++;
target_p->flags |= FLAGS_KILLED;
(void) exit_client(NULL, target_p, &me, "Nick collision (no SAVE support)");
return;
}
sendto_server(client_p, NULL, CAP_SAVE|CAP_TS6, NOCAPS, ":%s SAVE %s %ld",
source_p->id, target_p->id, (long)target_p->tsinfo);
sendto_server(client_p, NULL, CAP_TS6, CAP_SAVE, ":%s NICK %s :%ld",
target_p->id, target_p->id, (long)SAVE_NICKTS);
if (!IsMe(client_p))
sendto_realops_snomask(SNO_SKILL, L_ALL,
"Received SAVE message for %s from %s",
target_p->name, source_p->name);
if (MyClient(target_p))
{
sendto_one_numeric(target_p, RPL_SAVENICK,
form_str(RPL_SAVENICK), target_p->id);
change_local_nick(target_p, target_p, target_p->id, 0);
target_p->tsinfo = SAVE_NICKTS;
}
else
change_remote_nick(target_p, target_p, SAVE_NICKTS, target_p->id, 0);
}
static void bad_nickname(struct Client *client_p, const char *nick)
{
char squitreason[100];
sendto_wallops_flags(UMODE_WALLOP, &me,
"Squitting %s because of bad nickname %s (NICKLEN mismatch?)",
client_p->name, nick);
sendto_server(NULL, NULL, CAP_TS6, NOCAPS,
":%s WALLOPS :Squitting %s because of bad nickname %s (NICKLEN mismatch?)",
me.id, client_p->name, nick);
ilog(L_SERVER, "Link %s cancelled, bad nickname %s sent (NICKLEN mismatch?)",
client_p->name, nick);
snprintf(squitreason, sizeof squitreason,
"Bad nickname introduced [%s]", nick);
exit_client(client_p, client_p, &me, squitreason);
}
|
ahf/charybdis
|
modules/core/m_nick.c
|
C
|
gpl-2.0
| 34,184
|
/* This file is part of the KDE project
Copyright (C) 2010 KO GmbH <jos.van.den.oever@kogmbh.com>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "combinedview.h"
#include <QtGui/QApplication>
#include <QtGui/QPixmap>
int
main(int argc, char** argv) {
//QApplication::setGraphicsSystem("opengl");
QApplication app(argc, argv);
// QPixmapCache::setCacheLimit(100000);
CombinedView cv;
cv.resize(630, 410);
cv.show();
if (argc > 1) {
cv.openFile(argv[1]);
}
return app.exec();
}
|
TheTypoMaster/calligra-history
|
tools/slidecompare/slidecompare.cpp
|
C++
|
gpl-2.0
| 1,258
|
// NO INCLUDE GUARDS, THE HEADER IS INTENDED FOR MULTIPLE INCLUSION
// Copyright Aleksey Gurtovoy 2000-2006
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id: include_preprocessed.hpp 49267 2008-10-11 06:19:02Z agurtovoy $
// $Date: 2008-10-11 02:19:02 -0400 (Sat, 11 Oct 2008) $
// $Revision: 49267 $
#include "boost/mpl/aux_/config/compiler.hpp"
#include "boost/mpl/aux_/config/preprocessor.hpp"
#include "boost/mpl/aux_/config/workaround.hpp"
#include "boost/preprocessor/cat.hpp"
#include "boost/preprocessor/stringize.hpp"
#if !defined(BOOST_NEEDS_TOKEN_PASTING_OP_FOR_TOKENS_JUXTAPOSING)
# define AUX778076_PREPROCESSED_HEADER \
BOOST_MPL_CFG_COMPILER_DIR/BOOST_MPL_PREPROCESSED_HEADER \
/**/
#else
# define AUX778076_PREPROCESSED_HEADER \
BOOST_PP_CAT(BOOST_MPL_CFG_COMPILER_DIR,/)##BOOST_MPL_PREPROCESSED_HEADER \
/**/
#endif
#if BOOST_WORKAROUND(__IBMCPP__, BOOST_TESTED_AT(700))
# define AUX778076_INCLUDE_STRING BOOST_PP_STRINGIZE(boost/mpl/aux_/preprocessed/AUX778076_PREPROCESSED_HEADER)
# include AUX778076_INCLUDE_STRING
# undef AUX778076_INCLUDE_STRING
#else
# include BOOST_PP_STRINGIZE(boost/mpl/aux_/preprocessed/AUX778076_PREPROCESSED_HEADER)
#endif
# undef AUX778076_PREPROCESSED_HEADER
#undef BOOST_MPL_PREPROCESSED_HEADER
|
pallamidessi/GridVis
|
easeaMultiIslandsOneMachine/boost/boost/mpl/aux_/include_preprocessed.hpp
|
C++
|
gpl-2.0
| 1,494
|
/*
JPC: An x86 PC Hardware Emulator for a pure Java Virtual Machine
Copyright (C) 2012-2013 Ian Preston
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as published by
the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Details (including contact information) can be found at:
jpc.sourceforge.net
or the developer website
sourceforge.net/projects/jpc/
End of licence header
*/
package org.jpc.emulator.execution.opcodes.pm;
import org.jpc.emulator.execution.*;
import org.jpc.emulator.execution.decoder.*;
import org.jpc.emulator.processor.*;
import org.jpc.emulator.processor.fpu64.*;
import static org.jpc.emulator.processor.Processor.*;
public class fmulp_ST3_ST3 extends Executable
{
public fmulp_ST3_ST3(int blockStart, int eip, int prefices, PeekableInputStream input)
{
super(blockStart, eip);
int modrm = input.readU8();
}
public Branch execute(Processor cpu)
{
double freg0 = cpu.fpu.ST(3);
double freg1 = cpu.fpu.ST(3);
if ((Double.isInfinite(freg0) && (freg1 == 0.0)) || (Double.isInfinite(freg1) && (freg0 == 0.0)))
cpu.fpu.setInvalidOperation();
cpu.fpu.setST(3, freg0*freg1);
cpu.fpu.pop();
return Branch.None;
}
public boolean isBranch()
{
return false;
}
public String toString()
{
return this.getClass().getName();
}
}
|
ianopolous/JPC
|
src/org/jpc/emulator/execution/opcodes/pm/fmulp_ST3_ST3.java
|
Java
|
gpl-2.0
| 1,960
|
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright (C) 2014 Tom Gundersen
Copyright (C) 2014 Susant Sahani
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <arpa/inet.h>
#include <net/ethernet.h>
#include <stdio.h>
#include <string.h>
#include "sd-event.h"
#include "sd-lldp.h"
#include "alloc-util.h"
#include "event-util.h"
#include "fd-util.h"
#include "lldp-network.h"
#include "lldp-tlv.h"
#include "lldp.h"
#include "macro.h"
#include "string-util.h"
#define TEST_LLDP_PORT "em1"
#define TEST_LLDP_TYPE_SYSTEM_NAME "systemd-lldp"
#define TEST_LLDP_TYPE_SYSTEM_DESC "systemd-lldp-desc"
static int test_fd[2];
static struct ether_addr mac_addr = {
.ether_addr_octet = {'A', 'B', 'C', '1', '2', '3'}
};
static int lldp_build_tlv_packet(tlv_packet **ret) {
_cleanup_lldp_packet_unref_ tlv_packet *m = NULL;
const uint8_t lldp_dst[] = LLDP_MULTICAST_ADDR;
struct ether_header ether = {
.ether_type = htons(ETHERTYPE_LLDP),
};
/* Append Ethernet header */
memcpy(ðer.ether_dhost, lldp_dst, ETHER_ADDR_LEN);
memcpy(ðer.ether_shost, &mac_addr, ETHER_ADDR_LEN);
assert_se(tlv_packet_new(&m) >= 0);
assert_se(tlv_packet_append_bytes(m, ðer, sizeof(struct ether_header)) >= 0);
assert_se(lldp_tlv_packet_open_container(m, LLDP_TYPE_CHASSIS_ID) >= 0);
assert_se(tlv_packet_append_u8(m, LLDP_CHASSIS_SUBTYPE_MAC_ADDRESS) >= 0);
assert_se(tlv_packet_append_bytes(m, &mac_addr, ETHER_ADDR_LEN) >= 0);
assert_se(lldp_tlv_packet_close_container(m) >= 0);
/* port name */
assert_se(lldp_tlv_packet_open_container(m, LLDP_TYPE_PORT_ID) >= 0);
assert_se(tlv_packet_append_u8(m, LLDP_PORT_SUBTYPE_INTERFACE_NAME) >= 0);
assert_se(tlv_packet_append_bytes(m, TEST_LLDP_PORT, strlen(TEST_LLDP_PORT) + 1) >= 0);
assert_se(lldp_tlv_packet_close_container(m) >= 0);
/* ttl */
assert_se(lldp_tlv_packet_open_container(m, LLDP_TYPE_TTL) >= 0);
assert_se(tlv_packet_append_u16(m, 170) >= 0);
assert_se(lldp_tlv_packet_close_container(m) >= 0);
/* system name */
assert_se(lldp_tlv_packet_open_container(m, LLDP_TYPE_SYSTEM_NAME) >= 0);
assert_se(tlv_packet_append_bytes(m, TEST_LLDP_TYPE_SYSTEM_NAME,
strlen(TEST_LLDP_TYPE_SYSTEM_NAME)) >= 0);
assert_se(lldp_tlv_packet_close_container(m) >= 0);
/* system descrition */
assert_se(lldp_tlv_packet_open_container(m, LLDP_TYPE_SYSTEM_DESCRIPTION) >= 0);
assert_se(tlv_packet_append_bytes(m, TEST_LLDP_TYPE_SYSTEM_DESC,
strlen(TEST_LLDP_TYPE_SYSTEM_DESC)) >= 0);
assert_se(lldp_tlv_packet_close_container(m) >= 0);
/* Mark end of packet */
assert_se(lldp_tlv_packet_open_container(m, LLDP_TYPE_END) >= 0);
assert_se(lldp_tlv_packet_close_container(m) >= 0);
*ret = m;
m = NULL;
return 0;
}
static int lldp_parse_chassis_tlv(tlv_packet *m, uint8_t *type) {
uint8_t *p, subtype;
uint16_t length;
assert_se(lldp_tlv_packet_enter_container(m, LLDP_TYPE_CHASSIS_ID) >= 0);
assert_se(tlv_packet_read_u8(m, &subtype) >= 0);
switch (subtype) {
case LLDP_CHASSIS_SUBTYPE_MAC_ADDRESS:
*type = LLDP_CHASSIS_SUBTYPE_MAC_ADDRESS;
assert_se(tlv_packet_read_bytes(m, &p, &length) >= 0);
assert_se(memcmp(p, &mac_addr.ether_addr_octet, ETHER_ADDR_LEN) == 0);
break;
default:
assert_not_reached("Unhandled option");
}
assert_se(lldp_tlv_packet_exit_container(m) >= 0);
return 0;
}
static int lldp_parse_port_id_tlv(tlv_packet *m) {
_cleanup_free_ char *p = NULL;
char *str = NULL;
uint16_t length;
uint8_t subtype;
assert_se(lldp_tlv_packet_enter_container(m, LLDP_TYPE_PORT_ID) >= 0);
assert_se(tlv_packet_read_u8(m, &subtype) >= 0);
switch (subtype) {
case LLDP_PORT_SUBTYPE_INTERFACE_NAME:
assert_se(tlv_packet_read_string(m, &str, &length) >= 0);
p = strndup(str, length-1);
assert_se(p);
assert_se(streq(p, TEST_LLDP_PORT) == 1);
break;
default:
assert_not_reached("Unhandled option");
}
assert_se(lldp_tlv_packet_exit_container(m) >= 0);
return 0;
}
static int lldp_parse_system_name_tlv(tlv_packet *m) {
_cleanup_free_ char *p = NULL;
char *str = NULL;
uint16_t length;
assert_se(lldp_tlv_packet_enter_container(m, LLDP_TYPE_SYSTEM_NAME) >= 0);
assert_se(tlv_packet_read_string(m, &str, &length) >= 0);
p = strndup(str, length);
assert_se(p);
assert_se(streq(p, TEST_LLDP_TYPE_SYSTEM_NAME) == 1);
assert_se(lldp_tlv_packet_exit_container(m) >= 0);
return 1;
}
static int lldp_parse_system_desc_tlv(tlv_packet *m) {
_cleanup_free_ char *p = NULL;
char *str = NULL;
uint16_t length;
assert_se(lldp_tlv_packet_enter_container(m, LLDP_TYPE_SYSTEM_DESCRIPTION) >= 0);
assert_se(tlv_packet_read_string(m, &str, &length) >= 0);
p = strndup(str, length);
assert_se(p);
assert_se(streq(p, TEST_LLDP_TYPE_SYSTEM_DESC) == 1);
assert_se(lldp_tlv_packet_exit_container(m) >= 0);
return 0;
}
static int lldp_parse_ttl_tlv(tlv_packet *m) {
uint16_t ttl;
assert_se(lldp_tlv_packet_enter_container(m, LLDP_TYPE_TTL) >= 0);
assert_se(tlv_packet_read_u16(m, &ttl) >= 0);
assert_se(ttl == 170);
assert_se(lldp_tlv_packet_exit_container(m) >= 0);
return 0;
}
static int lldp_get_destination_type(tlv_packet *m) {
int dest;
assert_se(sd_lldp_packet_get_destination_type(m, &dest) >= 0);
assert_se(dest == SD_LLDP_DESTINATION_TYPE_NEAREST_BRIDGE);
return 0;
}
static int lldp_parse_tlv_packet(tlv_packet *m, int len) {
uint8_t subtype;
assert_se(tlv_packet_parse_pdu(m, len) >= 0);
assert_se(lldp_parse_chassis_tlv(m, &subtype) >= 0);
assert_se(lldp_parse_port_id_tlv(m) >= 0);
assert_se(lldp_parse_system_name_tlv(m) >= 0);
assert_se(lldp_parse_ttl_tlv(m) >= 0);
assert_se(lldp_parse_system_desc_tlv(m) >= 0);
assert_se(lldp_get_destination_type(m) >= 0);
return 0;
}
static void test_parser(void) {
_cleanup_lldp_packet_unref_ tlv_packet *tlv = NULL;
/* form a packet */
lldp_build_tlv_packet(&tlv);
/* parse the packet */
tlv_packet_parse_pdu(tlv, tlv->length);
/* verify */
lldp_parse_tlv_packet(tlv, tlv->length);
}
int lldp_network_bind_raw_socket(int ifindex) {
if (socketpair(AF_UNIX, SOCK_DGRAM | SOCK_NONBLOCK, 0, test_fd) < 0)
return -errno;
return test_fd[0];
}
static int lldp_handler_calls;
static void lldp_handler (sd_lldp *lldp, int event, void *userdata) {
lldp_handler_calls++;
}
static int start_lldp(sd_lldp **lldp, sd_event *e, sd_lldp_cb_t cb, void *cb_data) {
int r;
r = sd_lldp_new(42, "dummy", &mac_addr, lldp);
if (r)
return r;
r = sd_lldp_attach_event(*lldp, e, 0);
if (r)
return r;
r = sd_lldp_set_callback(*lldp, cb, cb_data);
if (r)
return r;
r = sd_lldp_start(*lldp);
if (r)
return r;
return 0;
}
static int stop_lldp(sd_lldp *lldp) {
int r;
r = sd_lldp_stop(lldp);
if (r)
return r;
r = sd_lldp_detach_event(lldp);
if (r)
return r;
sd_lldp_free(lldp);
safe_close(test_fd[1]);
return 0;
}
static void test_receive_basic_packet(sd_event *e) {
sd_lldp *lldp;
sd_lldp_packet **packets;
uint8_t type, *data;
uint16_t length, ttl;
int dest_type;
char *str;
uint8_t frame[] = {
/* Ethernet header */
0x01, 0x80, 0xc2, 0x00, 0x00, 0x03, /* Destination MAC*/
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* Source MAC */
0x88, 0xcc, /* Ethertype */
/* LLDP mandatory TLVs */
0x02, 0x07, 0x04, 0x00, 0x01, 0x02, /* Chassis: MAC, 00:01:02:03:04:05 */
0x03, 0x04, 0x05,
0x04, 0x04, 0x05, 0x31, 0x2f, 0x33, /* Port: interface name, "1/3" */
0x06, 0x02, 0x00, 0x78, /* TTL: 120 seconds*/
/* LLDP optional TLVs */
0x08, 0x04, 0x50, 0x6f, 0x72, 0x74, /* Port Description: "Port" */
0x0a, 0x03, 0x53, 0x59, 0x53, /* System Name: "SYS" */
0x0c, 0x04, 0x66, 0x6f, 0x6f, 0x00, /* System Description: "foo" (NULL-terminated) */
0x00, 0x00 /* End Of LLDPDU */
};
lldp_handler_calls = 0;
assert_se(start_lldp(&lldp, e, lldp_handler, NULL) == 0);
assert_se(write(test_fd[1], frame, sizeof(frame)) == sizeof(frame));
sd_event_run(e, 0);
assert_se(lldp_handler_calls == 1);
assert_se(sd_lldp_get_packets(lldp, &packets) == 1);
assert_se(sd_lldp_packet_read_chassis_id(packets[0], &type, &data, &length) == 0);
assert_se(type == LLDP_CHASSIS_SUBTYPE_MAC_ADDRESS);
assert_se(length == ETH_ALEN);
assert_se(!memcmp(data, "\x00\x01\x02\x03\x04\x05", ETH_ALEN));
assert_se(sd_lldp_packet_read_port_id(packets[0], &type, &data, &length) == 0);
assert_se(type == LLDP_PORT_SUBTYPE_INTERFACE_NAME);
assert_se(length == 3);
assert_se(strneq((char *) data, "1/3", 3));
assert_se(sd_lldp_packet_read_port_description(packets[0], &str, &length) == 0);
assert_se(length == 4);
assert_se(strneq(str, "Port", 4));
assert_se(sd_lldp_packet_read_system_name(packets[0], &str, &length) == 0);
assert_se(length == 3);
assert_se(strneq(str, "SYS", 3));
assert_se(sd_lldp_packet_read_system_description(packets[0], &str, &length) == 0);
assert_se(length == 4); /* This is the real length in the TLV packet */
assert_se(strneq(str, "foo", 3));
assert_se(sd_lldp_packet_read_ttl(packets[0], &ttl) == 0);
assert_se(ttl == 120);
assert_se(sd_lldp_packet_get_destination_type(packets[0], &dest_type) == 0);
assert_se(dest_type == SD_LLDP_DESTINATION_TYPE_NEAREST_NON_TPMR_BRIDGE);
sd_lldp_packet_unref(packets[0]);
free(packets);
assert_se(stop_lldp(lldp) == 0);
}
static void test_receive_incomplete_packet(sd_event *e) {
sd_lldp *lldp;
sd_lldp_packet **packets;
uint8_t frame[] = {
/* Ethernet header */
0x01, 0x80, 0xc2, 0x00, 0x00, 0x03, /* Destination MAC*/
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* Source MAC */
0x88, 0xcc, /* Ethertype */
/* LLDP mandatory TLVs */
0x02, 0x07, 0x04, 0x00, 0x01, 0x02, /* Chassis: MAC, 00:01:02:03:04:05 */
0x03, 0x04, 0x05,
0x04, 0x04, 0x05, 0x31, 0x2f, 0x33, /* Port: interface name, "1/3" */
/* Missing TTL */
0x00, 0x00 /* End Of LLDPDU */
};
lldp_handler_calls = 0;
assert_se(start_lldp(&lldp, e, lldp_handler, NULL) == 0);
assert_se(write(test_fd[1], frame, sizeof(frame)) == sizeof(frame));
sd_event_run(e, 0);
assert_se(lldp_handler_calls == 0);
assert_se(sd_lldp_get_packets(lldp, &packets) == 0);
assert_se(stop_lldp(lldp) == 0);
}
static void test_receive_oui_packet(sd_event *e) {
sd_lldp *lldp;
sd_lldp_packet **packets;
uint32_t id32;
uint16_t id16, len;
uint8_t flags;
char *str;
uint8_t frame[] = {
/* Ethernet header */
0x01, 0x80, 0xc2, 0x00, 0x00, 0x03, /* Destination MAC*/
0x01, 0x02, 0x03, 0x04, 0x05, 0x06, /* Source MAC */
0x88, 0xcc, /* Ethertype */
/* LLDP mandatory TLVs */
0x02, 0x07, 0x04, 0x00, 0x01, 0x02, /* Chassis: MAC, 00:01:02:03:04:05 */
0x03, 0x04, 0x05,
0x04, 0x04, 0x05, 0x31, 0x2f, 0x33, /* Port TLV: interface name, "1/3" */
0x06, 0x02, 0x00, 0x78, /* TTL: 120 seconds*/
/* LLDP optional TLVs */
0xfe, 0x06, 0x00, 0x80, 0xc2, 0x01, /* Port VLAN ID: 0x1234 */
0x12, 0x34,
0xfe, 0x07, 0x00, 0x80, 0xc2, 0x02, /* Port and protocol: flag 1, PPVID 0x7788 */
0x01, 0x77, 0x88,
0xfe, 0x0d, 0x00, 0x80, 0xc2, 0x03, /* VLAN Name: ID 0x1234, name "Vlan51" */
0x12, 0x34, 0x06, 0x56, 0x6c, 0x61,
0x6e, 0x35, 0x31,
0xfe, 0x06, 0x00, 0x80, 0xc2, 0x06, /* Management VID: 0x0102 */
0x01, 0x02,
0xfe, 0x09, 0x00, 0x80, 0xc2, 0x07, /* Link aggregation: status 1, ID 0x00140012 */
0x01, 0x00, 0x14, 0x00, 0x12,
0x00, 0x00 /* End of LLDPDU */
};
lldp_handler_calls = 0;
assert_se(start_lldp(&lldp, e, lldp_handler, NULL) == 0);
assert_se(write(test_fd[1], frame, sizeof(frame)) == sizeof(frame));
sd_event_run(e, 0);
assert_se(lldp_handler_calls == 1);
assert_se(sd_lldp_get_packets(lldp, &packets) == 1);
assert_se(sd_lldp_packet_read_port_vlan_id(packets[0], &id16) == 0);
assert_se(id16 == 0x1234);
assert_se(sd_lldp_packet_read_port_protocol_vlan_id(packets[0], &flags, &id16) == 0);
assert_se(flags == 1);
assert_se(id16 == 0x7788);
assert_se(sd_lldp_packet_read_vlan_name(packets[0], &id16, &str, &len) == 0);
assert_se(id16 == 0x1234);
assert_se(len == 6);
assert_se(strneq(str, "Vlan51", 6));
assert_se(sd_lldp_packet_read_management_vid(packets[0], &id16) == 0);
assert_se(id16 == 0x0102);
assert_se(sd_lldp_packet_read_link_aggregation(packets[0], &flags, &id32) == 0);
assert_se(flags == 1);
assert_se(id32 == 0x00140012);
sd_lldp_packet_unref(packets[0]);
free(packets);
assert_se(stop_lldp(lldp) == 0);
}
int main(int argc, char *argv[]) {
_cleanup_event_unref_ sd_event *e = NULL;
test_parser();
/* LLDP reception tests */
assert_se(sd_event_new(&e) == 0);
test_receive_basic_packet(e);
test_receive_incomplete_packet(e);
test_receive_oui_packet(e);
return 0;
}
|
rhvgoyal/systemd
|
src/libsystemd-network/test-lldp.c
|
C
|
gpl-2.0
| 15,961
|
/*
* Copyright (C) 2008 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.result;
import android.app.Activity;
import android.telephony.PhoneNumberUtils;
import br.edu.ifpb.R;
import com.google.zxing.client.result.ParsedResult;
import com.google.zxing.client.result.SMSParsedResult;
/**
* Handles SMS addresses, offering a choice of composing a new SMS or MMS message.
*
* @author dswitkin@google.com (Daniel Switkin)
*/
public final class SMSResultHandler extends ResultHandler {
private static final int[] buttons = {
R.string.button_sms,
R.string.button_mms
};
public SMSResultHandler(Activity activity, ParsedResult result) {
super(activity, result);
}
@Override
public int getButtonCount() {
return buttons.length;
}
@Override
public int getButtonText(int index) {
return buttons[index];
}
@Override
public void handleButtonPress(int index) {
SMSParsedResult smsResult = (SMSParsedResult) getResult();
switch (index) {
case 0:
// Don't know of a way yet to express a SENDTO intent with multiple recipients
sendSMS(smsResult.getNumbers()[0], smsResult.getBody());
break;
case 1:
sendMMS(smsResult.getNumbers()[0], smsResult.getSubject(), smsResult.getBody());
break;
}
}
@Override
public CharSequence getDisplayContents() {
SMSParsedResult smsResult = (SMSParsedResult) getResult();
String[] rawNumbers = smsResult.getNumbers();
String[] formattedNumbers = new String[rawNumbers.length];
for (int i = 0; i < rawNumbers.length; i++) {
formattedNumbers[i] = PhoneNumberUtils.formatNumber(rawNumbers[i]);
}
StringBuilder contents = new StringBuilder(50);
ParsedResult.maybeAppend(formattedNumbers, contents);
ParsedResult.maybeAppend(smsResult.getSubject(), contents);
ParsedResult.maybeAppend(smsResult.getBody(), contents);
return contents.toString();
}
@Override
public int getDisplayTitle() {
return R.string.result_sms;
}
}
|
LADOSSIFPB/ReCDATA
|
ReCDATA-ANDROID/zxing-source/com/google/zxing/client/android/result/SMSResultHandler.java
|
Java
|
gpl-2.0
| 2,588
|
package net.oschina.app.ui;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import net.oschina.app.AppConfig;
import net.oschina.app.AppContext;
import net.oschina.app.AppException;
import net.oschina.app.R;
import net.oschina.app.adapter.ListViewCommentAdapter;
import net.oschina.app.bean.Comment;
import net.oschina.app.bean.CommentList;
import net.oschina.app.bean.FavoriteList;
import net.oschina.app.bean.Notice;
import net.oschina.app.bean.Post;
import net.oschina.app.bean.Result;
import net.oschina.app.common.StringUtils;
import net.oschina.app.common.UIHelper;
import net.oschina.app.widget.BadgeView;
import net.oschina.app.widget.PullToRefreshListView;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.ViewSwitcher;
/**
* 问答详情
* @author liux (http://my.oschina.net/liux)
* @version 1.0
* @created 2012-3-21
*/
public class QuestionDetail extends BaseActivity {
private FrameLayout mHeader;
private LinearLayout mFooter;
private ImageView mBack;
private ImageView mFavorite;
private ImageView mRefresh;
private TextView mHeadTitle;
private ProgressBar mProgressbar;
private ScrollView mScrollView;
private ViewSwitcher mViewSwitcher;
private BadgeView bv_comment;
private ImageView mDetail;
private ImageView mCommentList;
private ImageView mShare;
private TextView mTitle;
private TextView mAuthor;
private TextView mPubDate;
private TextView mCommentCount;
private WebView mWebView;
private Handler mHandler;
private Post postDetail;
private int postId;
private final static int VIEWSWITCH_TYPE_DETAIL = 0x001;
private final static int VIEWSWITCH_TYPE_COMMENTS = 0x002;
private final static int DATA_LOAD_ING = 0x001;
private final static int DATA_LOAD_COMPLETE = 0x002;
private final static int DATA_LOAD_FAIL = 0x003;
private PullToRefreshListView mLvComment;
private ListViewCommentAdapter lvCommentAdapter;
private List<Comment> lvCommentData = new ArrayList<Comment>();
private View lvComment_footer;
private TextView lvComment_foot_more;
private ProgressBar lvComment_foot_progress;
private Handler mCommentHandler;
private int lvSumData;
private int curId;
private int curCatalog;
private int curLvDataState;
private int curLvPosition;//当前listview选中的item位置
private ViewSwitcher mFootViewSwitcher;
private ImageView mFootEditebox;
private EditText mFootEditer;
private Button mFootPubcomment;
private ProgressDialog mProgress;
private InputMethodManager imm;
private String tempCommentKey = AppConfig.TEMP_COMMENT;
private int _catalog;
private int _id;
private int _uid;
private String _content;
private int _isPostToMyZone;
private GestureDetector gd;
private boolean isFullScreen;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question_detail);
this.initView();
this.initData();
//加载评论视图&数据
this.initCommentView();
this.initCommentData();
//注册双击全屏事件
this.regOnDoubleEvent();
}
//初始化视图控件
private void initView()
{
postId = getIntent().getIntExtra("post_id", 0);
if(postId > 0) tempCommentKey = AppConfig.TEMP_COMMENT + "_" + CommentList.CATALOG_POST + "_" + postId;
mHeader = (FrameLayout)findViewById(R.id.question_detail_header);
mFooter = (LinearLayout)findViewById(R.id.question_detail_footer);
mBack = (ImageView)findViewById(R.id.question_detail_back);
mRefresh = (ImageView)findViewById(R.id.question_detail_refresh);
mHeadTitle = (TextView)findViewById(R.id.question_detail_head_title);
mProgressbar = (ProgressBar)findViewById(R.id.question_detail_head_progress);
mViewSwitcher = (ViewSwitcher)findViewById(R.id.question_detail_viewswitcher);
mScrollView = (ScrollView)findViewById(R.id.question_detail_scrollview);
mDetail = (ImageView)findViewById(R.id.question_detail_footbar_detail);
mCommentList = (ImageView)findViewById(R.id.question_detail_footbar_commentlist);
mShare = (ImageView)findViewById(R.id.question_detail_footbar_share);
mFavorite = (ImageView)findViewById(R.id.question_detail_footbar_favorite);
mTitle = (TextView)findViewById(R.id.question_detail_title);
mAuthor = (TextView)findViewById(R.id.question_detail_author);
mPubDate = (TextView)findViewById(R.id.question_detail_date);
mCommentCount = (TextView)findViewById(R.id.question_detail_commentcount);
mDetail.setEnabled(false);
mWebView = (WebView)findViewById(R.id.question_detail_webview);
mWebView.getSettings().setSupportZoom(true);
mWebView.getSettings().setBuiltInZoomControls(true);
mWebView.getSettings().setDefaultFontSize(15);
UIHelper.addWebImageShow(this, mWebView);
mBack.setOnClickListener(UIHelper.finish(this));
mFavorite.setOnClickListener(favoriteClickListener);
mRefresh.setOnClickListener(refreshClickListener);
mShare.setOnClickListener(shareClickListener);
mDetail.setOnClickListener(detailClickListener);
mCommentList.setOnClickListener(commentlistClickListener);
mAuthor.setOnClickListener(authorClickListener);
bv_comment = new BadgeView(this, mCommentList);
bv_comment.setBackgroundResource(R.drawable.widget_count_bg2);
bv_comment.setIncludeFontPadding(false);
bv_comment.setGravity(Gravity.CENTER);
bv_comment.setTextSize(8f);
bv_comment.setTextColor(Color.WHITE);
imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
mFootViewSwitcher = (ViewSwitcher)findViewById(R.id.question_detail_foot_viewswitcher);
mFootPubcomment = (Button)findViewById(R.id.question_detail_foot_pubcomment);
mFootPubcomment.setOnClickListener(commentpubClickListener);
mFootEditebox = (ImageView)findViewById(R.id.question_detail_footbar_editebox);
mFootEditebox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mFootViewSwitcher.showNext();
mFootEditer.setVisibility(View.VISIBLE);
mFootEditer.requestFocus();
mFootEditer.requestFocusFromTouch();
}
});
mFootEditer = (EditText)findViewById(R.id.question_detail_foot_editer);
mFootEditer.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(hasFocus){
imm.showSoftInput(v, 0);
}
else{
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
mFootEditer.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if(mFootViewSwitcher.getDisplayedChild()==1){
mFootViewSwitcher.setDisplayedChild(0);
mFootEditer.clearFocus();
mFootEditer.setVisibility(View.GONE);
}
return true;
}
return false;
}
});
//编辑器添加文本监听
mFootEditer.addTextChangedListener(UIHelper.getTextWatcher(this, tempCommentKey));
//显示临时编辑内容
UIHelper.showTempEditContent(this, mFootEditer, tempCommentKey);
}
//初始化控件数据
private void initData()
{
mHandler = new Handler()
{
public void handleMessage(Message msg) {
headButtonSwitch(DATA_LOAD_COMPLETE);
if(msg.what == 1)
{
mTitle.setText(postDetail.getTitle());
mAuthor.setText(postDetail.getAuthor());
mPubDate.setText(StringUtils.friendly_time(postDetail.getPubDate()));
mCommentCount.setText(postDetail.getAnswerCount()+"回/"+postDetail.getViewCount()+"阅");
//是否收藏
if(postDetail.getFavorite() == 1)
mFavorite.setImageResource(R.drawable.widget_bar_favorite2);
else
mFavorite.setImageResource(R.drawable.widget_bar_favorite);
//显示评论数
if(postDetail.getAnswerCount() > 0){
bv_comment.setText(postDetail.getAnswerCount()+"");
bv_comment.show();
}else{
bv_comment.setText("");
bv_comment.hide();
}
//显示标签
String tags = getPostTags(postDetail.getTags());
String body = UIHelper.WEB_STYLE + postDetail.getBody() + tags + "<div style=\"margin-bottom: 80px\" />";
//读取用户设置:是否加载文章图片--默认有wifi下始终加载图片
boolean isLoadImage;
AppContext ac = (AppContext)getApplication();
if(AppContext.NETTYPE_WIFI == ac.getNetworkType()){
isLoadImage = true;
}else{
isLoadImage = ac.isLoadImage();
}
if(isLoadImage){
body = body.replaceAll("(<img[^>]*?)\\s+width\\s*=\\s*\\S+","$1");
body = body.replaceAll("(<img[^>]*?)\\s+height\\s*=\\s*\\S+","$1");
// 添加点击图片放大支持
body = body.replaceAll("(<img[^>]+src=\")(\\S+)\"",
"$1$2\" onClick=\"javascript:mWebViewImageListener.onImageClick('$2')\"");
}else{
body = body.replaceAll("<\\s*img\\s+([^>]*)\\s*>","");
}
mWebView.loadDataWithBaseURL(null, body, "text/html", "utf-8",null);
mWebView.setWebViewClient(UIHelper.getWebViewClient());
//发送通知广播
if(msg.obj != null){
UIHelper.sendBroadCast(QuestionDetail.this, (Notice)msg.obj);
}
}
else if(msg.what == 0)
{
headButtonSwitch(DATA_LOAD_FAIL);
UIHelper.ToastMessage(QuestionDetail.this, R.string.msg_load_is_null);
}
else if(msg.what == -1 && msg.obj != null)
{
headButtonSwitch(DATA_LOAD_FAIL);
((AppException)msg.obj).makeToast(QuestionDetail.this);
}
}
};
initData(postId, false);
}
private void initData(final int post_id, final boolean isRefresh)
{
headButtonSwitch(DATA_LOAD_ING);
new Thread(){
public void run() {
Message msg = new Message();
try {
postDetail = ((AppContext)getApplication()).getPost(post_id, isRefresh);
msg.what = (postDetail!=null && postDetail.getId()>0) ? 1 : 0;
msg.obj = (postDetail!=null) ? postDetail.getNotice() : null;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
mHandler.sendMessage(msg);
}
}.start();
}
private String getPostTags(List<String> taglist) {
if(taglist == null)
return "";
String tags = "";
for(String tag : taglist) {
tags += String.format("<a class='tag' href='http://www.oschina.net/question/tag/%s' > %s </a> ", URLEncoder.encode(tag), tag);
}
return String.format("<div style='margin-top:10px;'>%s</div>", tags);
}
/**
* 底部栏切换
* @param type
*/
private void viewSwitch(int type) {
switch (type) {
case VIEWSWITCH_TYPE_DETAIL:
mDetail.setEnabled(false);
mCommentList.setEnabled(true);
mHeadTitle.setText(R.string.question_detail_head_title);
mViewSwitcher.setDisplayedChild(0);
break;
case VIEWSWITCH_TYPE_COMMENTS:
mDetail.setEnabled(true);
mCommentList.setEnabled(false);
mHeadTitle.setText(R.string.comment_list_head_title);
mViewSwitcher.setDisplayedChild(1);
break;
}
}
/**
* 头部按钮展示
* @param type
*/
private void headButtonSwitch(int type) {
switch (type) {
case DATA_LOAD_ING:
mScrollView.setVisibility(View.GONE);
mProgressbar.setVisibility(View.VISIBLE);
mRefresh.setVisibility(View.GONE);
break;
case DATA_LOAD_COMPLETE:
mScrollView.setVisibility(View.VISIBLE);
mProgressbar.setVisibility(View.GONE);
mRefresh.setVisibility(View.VISIBLE);
break;
case DATA_LOAD_FAIL:
mScrollView.setVisibility(View.GONE);
mProgressbar.setVisibility(View.GONE);
mRefresh.setVisibility(View.VISIBLE);
break;
}
}
private View.OnClickListener refreshClickListener = new View.OnClickListener() {
public void onClick(View v) {
initData(postId, true);
loadLvCommentData(curId,curCatalog,0,mCommentHandler,UIHelper.LISTVIEW_ACTION_REFRESH);
}
};
private View.OnClickListener authorClickListener = new View.OnClickListener() {
public void onClick(View v) {
UIHelper.showUserCenter(v.getContext(), postDetail.getAuthorId(), postDetail.getAuthor());
}
};
private View.OnClickListener shareClickListener = new View.OnClickListener() {
public void onClick(View v) {
if(postDetail == null){
UIHelper.ToastMessage(v.getContext(), R.string.msg_read_detail_fail);
return;
}
//分享到
UIHelper.showShareDialog(QuestionDetail.this, postDetail.getTitle(), postDetail.getUrl());
}
};
private View.OnClickListener detailClickListener = new View.OnClickListener() {
public void onClick(View v) {
if(postId == 0){
return;
}
viewSwitch(VIEWSWITCH_TYPE_DETAIL);
}
};
private View.OnClickListener commentlistClickListener = new View.OnClickListener() {
public void onClick(View v) {
if(postId == 0){
return;
}
//切换显示评论
viewSwitch(VIEWSWITCH_TYPE_COMMENTS);
}
};
private View.OnClickListener favoriteClickListener = new View.OnClickListener() {
public void onClick(View v) {
if(postId == 0 || postDetail == null){
return;
}
final AppContext ac = (AppContext)getApplication();
if(!ac.isLogin()){
UIHelper.showLoginDialog(QuestionDetail.this);
return;
}
final int uid = ac.getLoginUid();
final Handler handler = new Handler(){
public void handleMessage(Message msg) {
if(msg.what == 1){
Result res = (Result)msg.obj;
if(res.OK()){
if(postDetail.getFavorite() == 1){
postDetail.setFavorite(0);
mFavorite.setImageResource(R.drawable.widget_bar_favorite);
}else{
postDetail.setFavorite(1);
mFavorite.setImageResource(R.drawable.widget_bar_favorite2);
}
//重新保存缓存
ac.saveObject(postDetail, postDetail.getCacheKey());
}
UIHelper.ToastMessage(QuestionDetail.this, res.getErrorMessage());
}else{
((AppException)msg.obj).makeToast(QuestionDetail.this);
}
}
};
new Thread(){
public void run() {
Message msg = new Message();
Result res = null;
try {
if(postDetail.getFavorite() == 1){
res = ac.delFavorite(uid, postId, FavoriteList.TYPE_POST);
}else{
res = ac.addFavorite(uid, postId, FavoriteList.TYPE_POST);
}
msg.what = 1;
msg.obj = res;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
handler.sendMessage(msg);
}
}.start();
}
};
//初始化视图控件
private void initCommentView()
{
lvComment_footer = getLayoutInflater().inflate(R.layout.listview_footer, null);
lvComment_foot_more = (TextView)lvComment_footer.findViewById(R.id.listview_foot_more);
lvComment_foot_progress = (ProgressBar)lvComment_footer.findViewById(R.id.listview_foot_progress);
lvCommentAdapter = new ListViewCommentAdapter(this, lvCommentData, R.layout.comment_listitem);
mLvComment = (PullToRefreshListView)findViewById(R.id.comment_list_listview);
mLvComment.addFooterView(lvComment_footer);//添加底部视图 必须在setAdapter前
mLvComment.setAdapter(lvCommentAdapter);
mLvComment.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//点击头部、底部栏无效
if(position == 0 || view == lvComment_footer) return;
Comment com = null;
//判断是否是TextView
if(view instanceof TextView){
com = (Comment)view.getTag();
}else{
ImageView img = (ImageView)view.findViewById(R.id.comment_listitem_userface);
com = (Comment)img.getTag();
}
if(com == null) return;
//跳转--回复评论界面
UIHelper.showCommentReply(QuestionDetail.this,curId, curCatalog, com.getId(), com.getAuthorId(), com.getAuthor(), com.getContent());
}
});
mLvComment.setOnScrollListener(new AbsListView.OnScrollListener() {
public void onScrollStateChanged(AbsListView view, int scrollState) {
mLvComment.onScrollStateChanged(view, scrollState);
//数据为空--不用继续下面代码了
if(lvCommentData.size() == 0) return;
//判断是否滚动到底部
boolean scrollEnd = false;
try {
if(view.getPositionForView(lvComment_footer) == view.getLastVisiblePosition())
scrollEnd = true;
} catch (Exception e) {
scrollEnd = false;
}
if(scrollEnd && curLvDataState==UIHelper.LISTVIEW_DATA_MORE)
{
mLvComment.setTag(UIHelper.LISTVIEW_DATA_LOADING);
lvComment_foot_more.setText(R.string.load_ing);
lvComment_foot_progress.setVisibility(View.VISIBLE);
//当前pageIndex
int pageIndex = lvSumData/20;
loadLvCommentData(curId, curCatalog, pageIndex, mCommentHandler, UIHelper.LISTVIEW_ACTION_SCROLL);
}
}
public void onScroll(AbsListView view, int firstVisibleItem,int visibleItemCount, int totalItemCount) {
mLvComment.onScroll(view, firstVisibleItem, visibleItemCount, totalItemCount);
}
});
mLvComment.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//点击头部、底部栏无效
if(position == 0 || view == lvComment_footer) return false;
Comment _com = null;
//判断是否是TextView
if(view instanceof TextView){
_com = (Comment)view.getTag();
}else{
ImageView img = (ImageView)view.findViewById(R.id.comment_listitem_userface);
_com = (Comment)img.getTag();
}
if(_com == null) return false;
final Comment com = _com;
curLvPosition = lvCommentData.indexOf(com);
final AppContext ac = (AppContext)getApplication();
//操作--回复 & 删除
int uid = ac.getLoginUid();
//判断该评论是否是当前登录用户发表的:true--有删除操作 false--没有删除操作
if(uid == com.getAuthorId())
{
final Handler handler = new Handler(){
public void handleMessage(Message msg) {
if(msg.what == 1){
Result res = (Result)msg.obj;
if(res.OK()){
lvSumData--;
bv_comment.setText(lvSumData+"");
bv_comment.show();
lvCommentData.remove(com);
lvCommentAdapter.notifyDataSetChanged();
}
UIHelper.ToastMessage(QuestionDetail.this, res.getErrorMessage());
}else{
((AppException)msg.obj).makeToast(QuestionDetail.this);
}
}
};
final Thread thread = new Thread(){
public void run() {
Message msg = new Message();
try {
Result res = ac.delComment(curId, curCatalog, com.getId(), com.getAuthorId());
msg.what = 1;
msg.obj = res;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
handler.sendMessage(msg);
}
};
UIHelper.showCommentOptionDialog(QuestionDetail.this, curId, curCatalog, com, thread);
}
else
{
UIHelper.showCommentOptionDialog(QuestionDetail.this, curId, curCatalog, com, null);
}
return true;
}
});
mLvComment.setOnRefreshListener(new PullToRefreshListView.OnRefreshListener() {
public void onRefresh() {
loadLvCommentData(curId, curCatalog, 0, mCommentHandler, UIHelper.LISTVIEW_ACTION_REFRESH);
}
});
}
//初始化评论数据
private void initCommentData()
{
curId = postId;
curCatalog = CommentList.CATALOG_POST;
mCommentHandler = new Handler()
{
public void handleMessage(Message msg)
{
if(msg.what >= 0){
CommentList list = (CommentList)msg.obj;
Notice notice = list.getNotice();
//处理listview数据
switch (msg.arg1) {
case UIHelper.LISTVIEW_ACTION_INIT:
case UIHelper.LISTVIEW_ACTION_REFRESH:
lvSumData = msg.what;
lvCommentData.clear();//先清除原有数据
lvCommentData.addAll(list.getCommentlist());
break;
case UIHelper.LISTVIEW_ACTION_SCROLL:
lvSumData += msg.what;
if(lvCommentData.size() > 0){
for(Comment com1 : list.getCommentlist()){
boolean b = false;
for(Comment com2 : lvCommentData){
if(com1.getId() == com2.getId() && com1.getAuthorId() == com2.getAuthorId()){
b = true;
break;
}
}
if(!b) lvCommentData.add(com1);
}
}else{
lvCommentData.addAll(list.getCommentlist());
}
break;
}
//评论数更新
if(postDetail != null && lvCommentData.size() > postDetail.getAnswerCount()){
postDetail.setAnswerCount(lvCommentData.size());
bv_comment.setText(lvCommentData.size()+"");
bv_comment.show();
}
if(msg.what < 20){
curLvDataState = UIHelper.LISTVIEW_DATA_FULL;
lvCommentAdapter.notifyDataSetChanged();
lvComment_foot_more.setText(R.string.load_full);
}else if(msg.what == 20){
curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
lvCommentAdapter.notifyDataSetChanged();
lvComment_foot_more.setText(R.string.load_more);
}
//发送通知广播
if(notice != null){
UIHelper.sendBroadCast(QuestionDetail.this, notice);
}
}
else if(msg.what == -1){
//有异常--显示加载出错 & 弹出错误消息
curLvDataState = UIHelper.LISTVIEW_DATA_MORE;
lvComment_foot_more.setText(R.string.load_error);
((AppException)msg.obj).makeToast(QuestionDetail.this);
}
if(lvCommentData.size()==0){
curLvDataState = UIHelper.LISTVIEW_DATA_EMPTY;
lvComment_foot_more.setText(R.string.load_empty);
}
lvComment_foot_progress.setVisibility(View.GONE);
if(msg.arg1 == UIHelper.LISTVIEW_ACTION_REFRESH){
mLvComment.onRefreshComplete(getString(R.string.pull_to_refresh_update) + new Date().toLocaleString());
mLvComment.setSelection(0);
}
}
};
this.loadLvCommentData(curId,curCatalog,0,mCommentHandler,UIHelper.LISTVIEW_ACTION_INIT);
}
/**
* 线程加载评论数据
* @param id 当前文章id
* @param catalog 分类
* @param pageIndex 当前页数
* @param handler 处理器
* @param action 动作标识
*/
private void loadLvCommentData(final int id,final int catalog,final int pageIndex,final Handler handler,final int action){
new Thread(){
public void run() {
Message msg = new Message();
boolean isRefresh = false;
if(action == UIHelper.LISTVIEW_ACTION_REFRESH || action == UIHelper.LISTVIEW_ACTION_SCROLL)
isRefresh = true;
try {
CommentList commentlist = ((AppContext)getApplication()).getCommentList(catalog, id, pageIndex, isRefresh);
msg.what = commentlist.getPageSize();
msg.obj = commentlist;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
msg.arg1 = action;//告知handler当前action
handler.sendMessage(msg);
}
}.start();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (resultCode != RESULT_OK) return;
if (data == null) return;
viewSwitch(VIEWSWITCH_TYPE_COMMENTS);//跳到评论列表
if (requestCode == UIHelper.REQUEST_CODE_FOR_RESULT)
{
Comment comm = (Comment)data.getSerializableExtra("COMMENT_SERIALIZABLE");
lvCommentData.add(0,comm);
lvCommentAdapter.notifyDataSetChanged();
mLvComment.setSelection(0);
//显示评论数
int count = postDetail.getAnswerCount() + 1;
postDetail.setAnswerCount(count);
bv_comment.setText(count+"");
bv_comment.show();
}
else if (requestCode == UIHelper.REQUEST_CODE_FOR_REPLY)
{
Comment comm = (Comment)data.getSerializableExtra("COMMENT_SERIALIZABLE");
lvCommentData.set(curLvPosition, comm);
lvCommentAdapter.notifyDataSetChanged();
}
}
private View.OnClickListener commentpubClickListener = new View.OnClickListener() {
public void onClick(View v) {
_id = curId;
if(curId == 0){
return;
}
_catalog = curCatalog;
_content = mFootEditer.getText().toString();
if(StringUtils.isEmpty(_content)){
UIHelper.ToastMessage(v.getContext(), "请输入回帖内容");
return;
}
final AppContext ac = (AppContext)getApplication();
if(!ac.isLogin()){
UIHelper.showLoginDialog(QuestionDetail.this);
return;
}
// if(mZone.isChecked())
// _isPostToMyZone = 1;
_uid = ac.getLoginUid();
mProgress = ProgressDialog.show(v.getContext(), null, "发表中···",true,true);
final Handler handler = new Handler(){
public void handleMessage(Message msg) {
if(mProgress!=null)mProgress.dismiss();
if(msg.what == 1){
Result res = (Result)msg.obj;
UIHelper.ToastMessage(QuestionDetail.this, res.getErrorMessage());
if(res.OK()){
//发送通知广播
if(res.getNotice() != null){
UIHelper.sendBroadCast(QuestionDetail.this, res.getNotice());
}
//恢复初始底部栏
mFootViewSwitcher.setDisplayedChild(0);
mFootEditer.clearFocus();
mFootEditer.setText("");
mFootEditer.setVisibility(View.GONE);
//跳到评论列表
viewSwitch(VIEWSWITCH_TYPE_COMMENTS);
//更新评论列表
lvCommentData.add(0,res.getComment());
lvCommentAdapter.notifyDataSetChanged();
mLvComment.setSelection(0);
//显示评论数
int count = postDetail.getAnswerCount() + 1;
postDetail.setAnswerCount(count);
bv_comment.setText(count+"");
bv_comment.show();
//清除之前保存的编辑内容
ac.removeProperty(tempCommentKey);
}
}
else {
((AppException)msg.obj).makeToast(QuestionDetail.this);
}
}
};
new Thread(){
public void run() {
Message msg = new Message();
Result res = new Result();
try {
//发表评论
res = ac.pubComment(_catalog, _id, _uid, _content, _isPostToMyZone);
msg.what = 1;
msg.obj = res;
} catch (AppException e) {
e.printStackTrace();
msg.what = -1;
msg.obj = e;
}
handler.sendMessage(msg);
}
}.start();
}
};
/**
* 注册双击全屏事件
*/
private void regOnDoubleEvent(){
gd = new GestureDetector(this,new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onDoubleTap(MotionEvent e) {
isFullScreen = !isFullScreen;
if (!isFullScreen) {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().setAttributes(params);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
mHeader.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
} else {
WindowManager.LayoutParams params = getWindow().getAttributes();
params.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
getWindow().setAttributes(params);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
mHeader.setVisibility(View.GONE);
mFooter.setVisibility(View.GONE);
}
return true;
}
});
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (isAllowFullScreen()) {
gd.onTouchEvent(event);
}
return super.dispatchTouchEvent(event);
}
}
|
jiangchanghong/oschina-android-app
|
src/net/oschina/app/ui/QuestionDetail.java
|
Java
|
gpl-2.0
| 30,517
|
#include "muscle.h"
#if !defined(__linux__) && !defined(_MSC_VER) && !defined(__MACH__)
double GetNAN()
{
return 0.0;
}
double g_dNAN = GetNAN();
void chkmem(const char szMsg[])
{
}
void Break()
{
}
char szCmdLine[4096];
const char *GetCmdLine()
{
return "muscle";
}
double GetMemUseMB()
{
return 100.0;
}
void SaveCmdLine(int argc, char *argv[])
{
for (int i = 0; i < argc; ++i)
{
if (i > 0)
strcat(szCmdLine, " ");
strcat(szCmdLine, argv[i]);
}
}
double GetPeakMemUseMB()
{
return 100.0;
}
double GetCPUGHz()
{
return 2.0;
}
void CheckMemUse()
{
}
double GetRAMSizeMB()
{
return 500.0;
}
#endif
|
mfursov/ugene
|
src/plugins_3rdparty/umuscle/src/muscle/globalsother.cpp
|
C++
|
gpl-2.0
| 651
|
<?php
/**
* Portable Contact Form
*
* Laborator.co
* www.laborator.co
*/
# Element Information
$lab_vc_element_path = dirname( __FILE__ ) . '/';
$lab_vc_element_url = site_url(str_replace(ABSPATH, '', $lab_vc_element_path));
$lab_vc_element_icon = $lab_vc_element_url . 'contact.png';
vc_map( array(
'base' => 'lab_contact_form',
'name' => __('Contact Form', 'lab_composer'),
"description" => __("Insert AJAX form", "lab_composer"),
'category' => __('Laborator', 'lab_composer'),
'icon' => $lab_vc_element_icon,
'params' => array(
array(
'type' => 'textfield',
'heading' => __( 'Name Title', 'lab_composer' ),
'param_name' => 'name_title',
'value' => 'Name:'
),
array(
'type' => 'textfield',
'heading' => __( 'Email Title', 'lab_composer' ),
'param_name' => 'email_title',
'value' => 'Email:'
),
array(
'type' => 'textfield',
'heading' => __( 'Subject Title', 'lab_composer' ),
'param_name' => 'subject_title',
'value' => 'Subject:',
'dependency' => array(
'element' => 'show_subject_field',
'value' => array('yes')
),
),
array(
'type' => 'textfield',
'heading' => __( 'Message Title', 'lab_composer' ),
'param_name' => 'message_title',
'value' => 'Message:'
),
array(
'type' => 'checkbox',
'heading' => __( 'Subject Field', 'lab_composer' ),
'param_name' => 'show_subject_field',
'std' => 'no',
'value' => array(
__('Show subject field', 'lab_composer') => 'yes',
),
'description' => __( 'Set spacing for logo columns.', 'lab_composer' )
),
array(
'type' => 'textfield',
'heading' => __( 'Submit Title', 'lab_composer' ),
'param_name' => 'submit_title',
'value' => 'Send Message'
),
array(
'type' => 'textfield',
'heading' => __( 'Success Message', 'lab_composer' ),
'param_name' => 'submit_success',
'value' => 'Thank you #, message sent!'
),
array(
'type' => 'checkbox',
'heading' => __( 'Show Error Alerts', 'lab_composer' ),
'param_name' => 'alert_errors',
'std' => 'no',
'value' => array(
__('Yes', 'lab_composer') => 'yes',
),
'description' => __( 'Show JavaScript alert message when required field is not filled.', 'lab_composer' )
),
array(
'type' => 'textfield',
'heading' => __( 'Receiver', 'lab_composer' ),
'description' => 'Enter an email to receive contact form messages. If empty default admin email will be used ('.get_option('admin_email').')',
'param_name' => 'email_receiver'
),
array(
'type' => 'textfield',
'heading' => __( 'Extra class name', 'lab_composer' ),
'param_name' => 'el_class',
'description' => __( 'If you wish to style particular content element differently, then use this field to add a class name and then refer to it in your css file.', 'lab_composer' )
),
array(
'type' => 'css_editor',
'heading' => __( 'Css', 'lab_composer' ),
'param_name' => 'css',
'group' => __( 'Design options', 'lab_composer' )
)
)
) );
class WPBakeryShortCode_Lab_Contact_Form extends WPBakeryShortCode {}
# Contact Form Processing
add_action('wp_ajax_lab_contact_form_request', 'lab_contact_form_request');
add_action('wp_ajax_nopriv_lab_contact_form_request', 'lab_contact_form_request');
function lab_contact_form_request()
{
$resp = array(
'success' => false
);
$id = post('id');
$check = post('check');
$name = post('name');
$email = post('email');
$subject = post('subject');
$message = post('message');
$details = post('request');
$details = (array)json_decode(base64_decode(str_rot13($details)));
$nonce_id = "cf_" . md5($id . json_encode($details));
if(wp_verify_nonce($check, $nonce_id)/* && is_email($email) */)
{
$resp['success'] = true;
$email_receiver = $details['email_receiver'];
if( ! is_email($email_receiver))
{
$email_receiver = get_option('admin_email');
}
# Message Body
$details['name_title'] .= strpos($details['name_title'], ':') == -1 ? ': ' : '';
$details['email_title'] .= strpos($details['email_title'], ':') == -1 ? ': ' : '';
$details['subject_title'] .= strpos($details['subject_title'], ':') == -1 ? ': ' : '';
$details['message_title'] .= strpos($details['message_title'], ':') == -1 ? ': ' : '';
$message_body = "You have received new contact form message.\n\n----- Message Details -----\n\n";
$message_body .= "{$details['name_title']} {$name}\n\n";
$message_body .= "{$details['email_title']} {$email}\n\n";
if($details['show_subject_field'] == 'yes')
{
if($subject)
{
$message_body .= "{$details['subject_title']} {$subject}\n\n";
}
}
$message_body .= "{$details['message_title']}\n\n{$message}\n\n";
$message_body .= "--\n\nThis message has been sent from IP: {$_SERVER['REMOTE_ADDR']}\n\nURL: " . home_url();
$headers = array();
$headers[] = "Reply-To: {$name} <{$email}>";
wp_mail($email_receiver, "[".get_bloginfo('name')."] New Contact Form Message has been received.", $message_body, $headers);
}
echo json_encode($resp);
die();
}
|
devquarks/quasiarte-wp
|
wp-content/themes/kalium/inc/lib/vc/lab_contact_form/init.php
|
PHP
|
gpl-2.0
| 5,445
|
/* The header file is generated by make_header.py from EMACM.json */
/* Current script's version can be found at: */
/* https://github.com/AoLaD/rtems-tms570-utils/tree/headers/headers/python */
/*
* Copyright (c) 2014-2015, Premysl Houdek <kom541000@gmail.com>
*
* Czech Technical University in Prague
* Zikova 1903/4
* 166 36 Praha 6
* Czech Republic
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the FreeBSD Project.
*/
#ifndef LIBBSP_ARM_TMS570_EMACM
#define LIBBSP_ARM_TMS570_EMACM
#include <bsp/utility.h>
typedef struct{
uint32_t TXREVID; /*Transmit Revision ID Register*/
uint32_t TXCONTROL; /*Transmit Control Register*/
uint32_t TXTEARDOWN; /*Transmit Teardown Register*/
uint8_t reserved1 [4];
uint32_t RXREVID; /*Receive Revision ID Register*/
uint32_t RXCONTROL; /*Receive Control Register*/
uint32_t RXTEARDOWN; /*Receive Teardown Register*/
uint8_t reserved2 [100];
uint32_t TXINTSTATRAW; /*Transmit Interrupt Status (Unmasked) Register*/
uint32_t TXINTSTATMASKED; /*Transmit Interrupt Status (Masked) Register*/
uint32_t TXINTMASKSET; /*Transmit Interrupt Mask Set Register*/
uint32_t TXINTMASKCLEAR; /*Transmit Interrupt Clear Register*/
uint32_t MACINVECTOR; /*MAC Input Vector Register*/
uint32_t MACEOIVECTOR; /*MAC End Of Interrupt Vector Register*/
uint8_t reserved3 [8];
uint32_t RXINTSTATRAW; /*Receive Interrupt Status (Unmasked) Register*/
uint32_t RXINTSTATMASKED; /*Receive Interrupt Status (Masked) Register*/
uint32_t RXINTMASKSET; /*Receive Interrupt Mask Set Register*/
uint32_t RXINTMASKCLEAR; /*Receive Interrupt Mask Clear Register*/
uint32_t MACINTSTATRAW; /*MAC Interrupt Status (Unmasked) Register*/
uint32_t MACINTSTATMASKED; /*MAC Interrupt Status (Masked) Register*/
uint32_t MACINTMASKSET; /*MAC Interrupt Mask Set Register*/
uint32_t MACINTMASKCLEAR; /*MAC Interrupt Mask Clear Register*/
uint8_t reserved4 [64];
uint32_t RXMBPENABLE; /*Receive Multicast/Broadcast/Promiscuous Channel Enable*/
uint32_t RXUNICASTSET; /*Receive Unicast Enable Set Register*/
uint32_t RXUNICASTCLEAR; /*Receive Unicast Clear Register*/
uint32_t RXMAXLEN; /*Receive Maximum Length Register*/
uint32_t RXBUFFEROFFSET; /*Receive Buffer Offset Register*/
uint32_t RXFILTERLOWTHRESH; /*Receive Filter Low Priority Frame Threshold Register*/
uint8_t reserved5 [8];
uint32_t RXFLOWTHRESH[8]; /*Receive Channel Flow Control Threshold Register*/
uint32_t RXFREEBUFFER[8]; /*Receive Channel Free Buffer Count Register*/
uint32_t MACCONTROL; /*MAC Control Register*/
uint32_t MACSTATUS; /*MAC Status Register*/
uint32_t EMCONTROL; /*Emulation Control Register*/
uint32_t FIFOCONTROL; /*FIFO Control Register*/
uint32_t MACCONFIG; /*MAC Configuration Register*/
uint32_t SOFTRESET; /*Soft Reset Register*/
uint8_t reserved6 [88];
uint32_t MACSRCADDRLO; /*MAC Source Address Low Bytes Register*/
uint32_t MACSRCADDRHI; /*MAC Source Address High Bytes Register*/
uint32_t MACHASH1; /*MAC Hash Address Register 1*/
uint32_t MACHASH2; /*MAC Hash Address Register 2*/
uint32_t BOFFTEST; /*Back Off Test Register*/
uint32_t TPACETEST; /*Transmit Pacing Algorithm Test Register*/
uint32_t RXPAUSE; /*Receive Pause Timer Register*/
uint32_t TXPAUSE; /*Transmit Pause Timer Register*/
uint8_t reserved7 [784];
uint32_t MACADDRLO; /*MAC Address Low Bytes Register*/
uint32_t MACADDRHI; /*MAC Address High Bytes Register*/
uint32_t MACINDEX; /*MAC Index Register*/
uint8_t reserved8 [244];
uint32_t TXHDP[8]; /*Transmit Channel DMA Head Descriptor Pointer Register*/
uint32_t RXHDP[8]; /*Receive Channel DMA Head Descriptor Pointer Register*/
uint32_t TXCP[8]; /*Transmit Channel Completion Pointer Register*/
uint32_t RXCP[8]; /*Receive Channel Completion Pointer Register*/
} tms570_emacm_t;
/*--------------------TMS570_EMACM_TXREVID--------------------*/
/* field: TXREV - Transmit module revision */
/* Whole 32 bits */
/*-------------------TMS570_EMACM_TXCONTROL-------------------*/
/* field: TXEN - Transmit enable */
#define TMS570_EMACM_TXCONTROL_TXEN BSP_BIT32(0)
/*------------------TMS570_EMACM_TXTEARDOWN------------------*/
/* field: TXTDNCH - Transmit teardown channel. */
#define TMS570_EMACM_TXTEARDOWN_TXTDNCH(val) BSP_FLD32(val,0, 2)
#define TMS570_EMACM_TXTEARDOWN_TXTDNCH_GET(reg) BSP_FLD32GET(reg,0, 2)
#define TMS570_EMACM_TXTEARDOWN_TXTDNCH_SET(reg,val) BSP_FLD32SET(reg, val,0, 2)
/*--------------------TMS570_EMACM_RXREVID--------------------*/
/* field: RXREV - Receive module revision */
/* Whole 32 bits */
/*-------------------TMS570_EMACM_RXCONTROL-------------------*/
/* field: RXEN - Receive enable */
#define TMS570_EMACM_RXCONTROL_RXEN BSP_BIT32(0)
/*------------------TMS570_EMACM_RXTEARDOWN------------------*/
/* field: RXTDNCH - Receive teardown channel. */
#define TMS570_EMACM_RXTEARDOWN_RXTDNCH(val) BSP_FLD32(val,0, 2)
#define TMS570_EMACM_RXTEARDOWN_RXTDNCH_GET(reg) BSP_FLD32GET(reg,0, 2)
#define TMS570_EMACM_RXTEARDOWN_RXTDNCH_SET(reg,val) BSP_FLD32SET(reg, val,0, 2)
/*-----------------TMS570_EMACM_TXINTSTATRAW-----------------*/
/* field: TX7PEND - TX7PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX7PEND BSP_BIT32(7)
/* field: TX6PEND - TX6PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX6PEND BSP_BIT32(6)
/* field: TX5PEND - TX5PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX5PEND BSP_BIT32(5)
/* field: TX4PEND - X4PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX4PEND BSP_BIT32(4)
/* field: TX3PEND - TX3PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX3PEND BSP_BIT32(3)
/* field: TX2PEND - TX2PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX2PEND BSP_BIT32(2)
/* field: TX1PEND - TX1PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX1PEND BSP_BIT32(1)
/* field: TX0PEND - TX0PEND raw interrupt read (before mask) */
#define TMS570_EMACM_TXINTSTATRAW_TX0PEND BSP_BIT32(0)
/*----------------TMS570_EMACM_TXINTSTATMASKED----------------*/
/* field: TX7PEND - TX7PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX7PEND BSP_BIT32(7)
/* field: TX6PEND - TX6PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX6PEND BSP_BIT32(6)
/* field: TX5PEND - TX5PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX5PEND BSP_BIT32(5)
/* field: TX4PEND - TX4PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX4PEND BSP_BIT32(4)
/* field: TX3PEND - TX3PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX3PEND BSP_BIT32(3)
/* field: TX2PEND - TX2PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX2PEND BSP_BIT32(2)
/* field: TX1PEND - TX1PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX1PEND BSP_BIT32(1)
/* field: TX0PEND - TX0PEND masked interrupt read */
#define TMS570_EMACM_TXINTSTATMASKED_TX0PEND BSP_BIT32(0)
/*-----------------TMS570_EMACM_TXINTMASKSET-----------------*/
/* field: TX7MASK - Transmit channel 7 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX7MASK BSP_BIT32(7)
/* field: TX6MASK - Transmit channel 6 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX6MASK BSP_BIT32(6)
/* field: TX5MASK - Transmit channel 5 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX5MASK BSP_BIT32(5)
/* field: TX4MASK - Transmit channel 4 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX4MASK BSP_BIT32(4)
/* field: TX3MASK - Transmit channel 3 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX3MASK BSP_BIT32(3)
/* field: TX2MASK - Transmit channel 2 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX2MASK BSP_BIT32(2)
/* field: TX1MASK - Transmit channel 1 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX1MASK BSP_BIT32(1)
/* field: TX0MASK - Transmit channel 0 interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKSET_TX0MASK BSP_BIT32(0)
/*----------------TMS570_EMACM_TXINTMASKCLEAR----------------*/
/* field: TX7MASK - Transmit channel 7 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX7MASK BSP_BIT32(7)
/* field: TX6MASK - Transmit channel 6 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX6MASK BSP_BIT32(6)
/* field: TX5MASK - Transmit channel 5 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX5MASK BSP_BIT32(5)
/* field: TX4MASK - Transmit channel 4 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX4MASK BSP_BIT32(4)
/* field: TX3MASK - Transmit channel 3 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX3MASK BSP_BIT32(3)
/* field: TX2MASK - Transmit channel 2 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX2MASK BSP_BIT32(2)
/* field: TX1MASK - Transmit channel 1 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX1MASK BSP_BIT32(1)
/* field: TX0MASK - Transmit channel 0 interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_TXINTMASKCLEAR_TX0MASK BSP_BIT32(0)
/*------------------TMS570_EMACM_MACINVECTOR------------------*/
/* field: STATPEND - EMAC module statistics interrupt (STATPEND) pending status bit */
#define TMS570_EMACM_MACINVECTOR_STATPEND BSP_BIT32(27)
/* field: HOSTPEND - EMAC module host error interrupt (HOSTPEND) pending status bit */
#define TMS570_EMACM_MACINVECTOR_HOSTPEND BSP_BIT32(26)
/* field: LINKINT0 - MDIO module USERPHYSEL0 (LINKINT0) status bit */
#define TMS570_EMACM_MACINVECTOR_LINKINT0 BSP_BIT32(25)
/* field: USERINT0 - MDIO module USERACCESS0 (USERINT0) status bit */
#define TMS570_EMACM_MACINVECTOR_USERINT0 BSP_BIT32(24)
/* field: TXPEND - Transmit channels 0-7 interrupt (TXnPEND) pending status. Bit 16 is TX0PEND. */
#define TMS570_EMACM_MACINVECTOR_TXPEND(val) BSP_FLD32(val,16, 23)
#define TMS570_EMACM_MACINVECTOR_TXPEND_GET(reg) BSP_FLD32GET(reg,16, 23)
#define TMS570_EMACM_MACINVECTOR_TXPEND_SET(reg,val) BSP_FLD32SET(reg, val,16, 23)
/* field: RXTHRESHPEND - Receive channels 0-7 interrupt (RXnTHRESHPEND) pending status. */
#define TMS570_EMACM_MACINVECTOR_RXTHRESHPEND(val) BSP_FLD32(val,8, 15)
#define TMS570_EMACM_MACINVECTOR_RXTHRESHPEND_GET(reg) BSP_FLD32GET(reg,8, 15)
#define TMS570_EMACM_MACINVECTOR_RXTHRESHPEND_SET(reg,val) BSP_FLD32SET(reg, val,8, 15)
/* field: RXPEND - Receive channels 0-7 interrupt (RXnPEND) pending status bit. Bit 0 is RX0PEND. */
#define TMS570_EMACM_MACINVECTOR_RXPEND(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_MACINVECTOR_RXPEND_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_MACINVECTOR_RXPEND_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-----------------TMS570_EMACM_MACEOIVECTOR-----------------*/
/* field: INTVECT - Acknowledge EMAC Control Module Interrupts */
#define TMS570_EMACM_MACEOIVECTOR_INTVECT(val) BSP_FLD32(val,0, 4)
#define TMS570_EMACM_MACEOIVECTOR_INTVECT_GET(reg) BSP_FLD32GET(reg,0, 4)
#define TMS570_EMACM_MACEOIVECTOR_INTVECT_SET(reg,val) BSP_FLD32SET(reg, val,0, 4)
/*-----------------TMS570_EMACM_RXINTSTATRAW-----------------*/
/* field: RX7THRESHPEND - RX7THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX7THRESHPEND BSP_BIT32(15)
/* field: RX6THRESHPEND - RX6THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX6THRESHPEND BSP_BIT32(14)
/* field: RX5THRESHPEND - RX5THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX5THRESHPEND BSP_BIT32(13)
/* field: RX4THRESHPEND - RX4THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX4THRESHPEND BSP_BIT32(12)
/* field: RX3THRESHPEND - RX3THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX3THRESHPEND BSP_BIT32(11)
/* field: RX2THRESHPEND - RX2THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX2THRESHPEND BSP_BIT32(10)
/* field: RX1THRESHPEND - RX1THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX1THRESHPEND BSP_BIT32(9)
/* field: RX0THRESHPEND - RX0THRESHPEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX0THRESHPEND BSP_BIT32(8)
/* field: RX7PEND - RX7PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX7PEND BSP_BIT32(7)
/* field: RX6PEND - RX6PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX6PEND BSP_BIT32(6)
/* field: RX5PEND - RX5PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX5PEND BSP_BIT32(5)
/* field: RX4PEND - RX4PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX4PEND BSP_BIT32(4)
/* field: RX3PEND - RX3PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX3PEND BSP_BIT32(3)
/* field: RX2PEND - RX2PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX2PEND BSP_BIT32(2)
/* field: RX1PEND - RX1PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX1PEND BSP_BIT32(1)
/* field: RX0PEND - RX0PEND raw interrupt read (before mask) */
#define TMS570_EMACM_RXINTSTATRAW_RX0PEND BSP_BIT32(0)
/*----------------TMS570_EMACM_RXINTSTATMASKED----------------*/
/* field: RX7THRESHPEND - RX7THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX7THRESHPEND BSP_BIT32(15)
/* field: RX6THRESHPEND - RX6THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX6THRESHPEND BSP_BIT32(14)
/* field: RX5THRESHPEND - RX5THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX5THRESHPEND BSP_BIT32(13)
/* field: RX4THRESHPEND - RX4THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX4THRESHPEND BSP_BIT32(12)
/* field: RX3THRESHPEND - RX3THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX3THRESHPEND BSP_BIT32(11)
/* field: RX2THRESHPEND - RX2THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX2THRESHPEND BSP_BIT32(10)
/* field: RX1THRESHPEND - RX1THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX1THRESHPEND BSP_BIT32(9)
/* field: RX0THRESHPEND - RX0THRESHPEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX0THRESHPEND BSP_BIT32(8)
/* field: RX7PEND - RX7PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX7PEND BSP_BIT32(7)
/* field: RX6PEND - RX6PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX6PEND BSP_BIT32(6)
/* field: RX5PEND - RX5PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX5PEND BSP_BIT32(5)
/* field: RX4PEND - RX4PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX4PEND BSP_BIT32(4)
/* field: RX3PEND - RX3PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX3PEND BSP_BIT32(3)
/* field: RX2PEND - RX2PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX2PEND BSP_BIT32(2)
/* field: RX1PEND - RX1PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX1PEND BSP_BIT32(1)
/* field: RX0PEND - RX0PEND masked interrupt read */
#define TMS570_EMACM_RXINTSTATMASKED_RX0PEND BSP_BIT32(0)
/*-----------------TMS570_EMACM_RXINTMASKSET-----------------*/
/* field: RX7THRESHMASK - Receive channel 7 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX7THRESHMASK BSP_BIT32(15)
/* field: RX6THRESHMASK - Receive channel 6 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX6THRESHMASK BSP_BIT32(14)
/* field: RX5THRESHMASK - Receive channel 5 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX5THRESHMASK BSP_BIT32(13)
/* field: RX4THRESHMASK - Receive channel 4 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX4THRESHMASK BSP_BIT32(12)
/* field: RX3THRESHMASK - Receive channel 3 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX3THRESHMASK BSP_BIT32(11)
/* field: RX2THRESHMASK - Receive channel 2 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX2THRESHMASK BSP_BIT32(10)
/* field: RX1THRESHMASK - Receive channel 1 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX1THRESHMASK BSP_BIT32(9)
/* field: RX0THRESHMASK - Receive channel 0 threshold mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX0THRESHMASK BSP_BIT32(8)
/* field: RX7MASK - Receive channel 7 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX7MASK BSP_BIT32(7)
/* field: RX6MASK - Receive channel 6 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX6MASK BSP_BIT32(6)
/* field: RX5MASK - Receive channel 5 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX5MASK BSP_BIT32(5)
/* field: RX4MASK - Receive channel 4 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX4MASK BSP_BIT32(4)
/* field: RX3MASK - Receive channel 3 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX3MASK BSP_BIT32(3)
/* field: RX2MASK - Receive channel 2 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX2MASK BSP_BIT32(2)
/* field: RX1MASK - Receive channel 1 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX1MASK BSP_BIT32(1)
/* field: RX0MASK - Receive channel 0 mask set bit. Write 1 to enable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKSET_RX0MASK BSP_BIT32(0)
/*----------------TMS570_EMACM_RXINTMASKCLEAR----------------*/
/* field: RX7THRESHMASK - Receive channel 7 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX7THRESHMASK BSP_BIT32(15)
/* field: RX6THRESHMASK - Receive channel 6 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX6THRESHMASK BSP_BIT32(14)
/* field: RX5THRESHMASK - Receive channel 5 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX5THRESHMASK BSP_BIT32(13)
/* field: RX4THRESHMASK - Receive channel 4 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX4THRESHMASK BSP_BIT32(12)
/* field: RX3THRESHMASK - Receive channel 3 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX3THRESHMASK BSP_BIT32(11)
/* field: RX2THRESHMASK - Receive channel 2 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX2THRESHMASK BSP_BIT32(10)
/* field: RX1THRESHMASK - Receive channel 1 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX1THRESHMASK BSP_BIT32(9)
/* field: RX0THRESHMASK - Receive channel 0 threshold mask clear bit. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX0THRESHMASK BSP_BIT32(8)
/* field: RX7MASK - Receive channel 7 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX7MASK BSP_BIT32(7)
/* field: RX6MASK - Receive channel 6 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX6MASK BSP_BIT32(6)
/* field: RX5MASK - Receive channel 5 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX5MASK BSP_BIT32(5)
/* field: RX4MASK - Receive channel 4 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX4MASK BSP_BIT32(4)
/* field: RX3MASK - Receive channel 3 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX3MASK BSP_BIT32(3)
/* field: RX2MASK - Receive channel 2 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX2MASK BSP_BIT32(2)
/* field: RX1MASK - Receive channel 1 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX1MASK BSP_BIT32(1)
/* field: RX0MASK - Receive channel 0 mask clear bit. Write 1 to disable interrupt; a write of 0 has no effect. */
#define TMS570_EMACM_RXINTMASKCLEAR_RX0MASK BSP_BIT32(0)
/*-----------------TMS570_EMACM_MACINTSTATRAW-----------------*/
/* field: HOSTPEND - Host pending interrupt (HOSTPEND); raw interrupt read (before mask). */
#define TMS570_EMACM_MACINTSTATRAW_HOSTPEND BSP_BIT32(1)
/* field: STATPEND - Statistics pending interrupt (STATPEND); raw interrupt read (before mask). */
#define TMS570_EMACM_MACINTSTATRAW_STATPEND BSP_BIT32(0)
/*---------------TMS570_EMACM_MACINTSTATMASKED---------------*/
/* field: HOSTPEND - Host pending interrupt (HOSTPEND); masked interrupt read. */
#define TMS570_EMACM_MACINTSTATMASKED_HOSTPEND BSP_BIT32(1)
/* field: STATPEND - Statistics pending interrupt (STATPEND); masked interrupt read. */
#define TMS570_EMACM_MACINTSTATMASKED_STATPEND BSP_BIT32(0)
/*-----------------TMS570_EMACM_MACINTMASKSET-----------------*/
/* field: HOSTMASK - Host error interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_MACINTMASKSET_HOSTMASK BSP_BIT32(1)
/* field: STATMASK - Statistics interrupt mask set bit. Write 1 to enable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_MACINTMASKSET_STATMASK BSP_BIT32(0)
/*----------------TMS570_EMACM_MACINTMASKCLEAR----------------*/
/* field: HOSTMASK - Host error interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_MACINTMASKCLEAR_HOSTMASK BSP_BIT32(1)
/* field: STATMASK - Statistics interrupt mask clear bit. Write 1 to disable interrupt, a write of 0 has no effect. */
#define TMS570_EMACM_MACINTMASKCLEAR_STATMASK BSP_BIT32(0)
/*------------------TMS570_EMACM_RXMBPENABLE------------------*/
/* field: RXPASSCRC - Pass receive CRC enable bit */
#define TMS570_EMACM_RXMBPENABLE_RXPASSCRC BSP_BIT32(30)
/* field: RXQOSEN - Receive quality of service enable bit */
#define TMS570_EMACM_RXMBPENABLE_RXQOSEN BSP_BIT32(29)
/* field: RXNOCHAIN - Receive no buffer chaining bit */
#define TMS570_EMACM_RXMBPENABLE_RXNOCHAIN BSP_BIT32(28)
/* field: RXCMFEN - Receive copy MAC control frames enable bit. */
#define TMS570_EMACM_RXMBPENABLE_RXCMFEN BSP_BIT32(24)
/* field: RXCSFEN - Receive copy short frames enable bit. */
#define TMS570_EMACM_RXMBPENABLE_RXCSFEN BSP_BIT32(23)
/* field: RXCEFEN - Receive copy error frames enable bit. */
#define TMS570_EMACM_RXMBPENABLE_RXCEFEN BSP_BIT32(22)
/* field: RXCAFEN - Receive copy all frames enable bit. */
#define TMS570_EMACM_RXMBPENABLE_RXCAFEN BSP_BIT32(21)
/* field: RXPROMCH - Receive promiscuous channel select */
#define TMS570_EMACM_RXMBPENABLE_RXPROMCH(val) BSP_FLD32(val,16, 18)
#define TMS570_EMACM_RXMBPENABLE_RXPROMCH_GET(reg) BSP_FLD32GET(reg,16, 18)
#define TMS570_EMACM_RXMBPENABLE_RXPROMCH_SET(reg,val) BSP_FLD32SET(reg, val,16, 18)
/* field: RXBROADEN - Receive broadcast enable. */
#define TMS570_EMACM_RXMBPENABLE_RXBROADEN BSP_BIT32(13)
/* field: RXBROADCH - Receive broadcast channel select */
#define TMS570_EMACM_RXMBPENABLE_RXBROADCH(val) BSP_FLD32(val,8, 10)
#define TMS570_EMACM_RXMBPENABLE_RXBROADCH_GET(reg) BSP_FLD32GET(reg,8, 10)
#define TMS570_EMACM_RXMBPENABLE_RXBROADCH_SET(reg,val) BSP_FLD32SET(reg, val,8, 10)
/* field: RXMULTEN - RX multicast enable. */
#define TMS570_EMACM_RXMBPENABLE_RXMULTEN BSP_BIT32(5)
/*-----------------TMS570_EMACM_RXUNICASTSET-----------------*/
/* field: RXCH7EN - Receive channel 7 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH7EN BSP_BIT32(7)
/* field: RXCH6EN - Receive channel 6 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH6EN BSP_BIT32(6)
/* field: RXCH5EN - Receive channel 5 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH5EN BSP_BIT32(5)
/* field: RXCH4EN - Receive channel 4 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH4EN BSP_BIT32(4)
/* field: RXCH3EN - Receive channel 3 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH3EN BSP_BIT32(3)
/* field: RXCH2EN - Receive channel 2 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH2EN BSP_BIT32(2)
/* field: RXCH1EN - Receive channel 1 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH1EN BSP_BIT32(1)
/* field: RXCH0EN - Receive channel 0 unicast enable set bit. Write 1 to set the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTSET_RXCH0EN BSP_BIT32(0)
/*----------------TMS570_EMACM_RXUNICASTCLEAR----------------*/
/* field: RXCH7EN - Receive channel 7 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH7EN BSP_BIT32(7)
/* field: RXCH6EN - Receive channel 6 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH6EN BSP_BIT32(6)
/* field: RXCH5EN - Receive channel 5 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH5EN BSP_BIT32(5)
/* field: RXCH4EN - Receive channel 4 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH4EN BSP_BIT32(4)
/* field: RXCH3EN - Receive channel 3 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH3EN BSP_BIT32(3)
/* field: RXCH2EN - Receive channel 2 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH2EN BSP_BIT32(2)
/* field: RXCH1EN - Receive channel 1 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH1EN BSP_BIT32(1)
/* field: RXCH0EN - Receive channel 0 unicast enable clear bit. Write 1 to clear the enable, a write of 0 has no effect. */
#define TMS570_EMACM_RXUNICASTCLEAR_RXCH0EN BSP_BIT32(0)
/*-------------------TMS570_EMACM_RXMAXLEN-------------------*/
/* field: RXMAXLEN - Receive maximum frame length. These bits determine the maximum length of a received frame. */
#define TMS570_EMACM_RXMAXLEN_RXMAXLEN(val) BSP_FLD32(val,0, 15)
#define TMS570_EMACM_RXMAXLEN_RXMAXLEN_GET(reg) BSP_FLD32GET(reg,0, 15)
#define TMS570_EMACM_RXMAXLEN_RXMAXLEN_SET(reg,val) BSP_FLD32SET(reg, val,0, 15)
/*----------------TMS570_EMACM_RXBUFFEROFFSET----------------*/
/* field: RXBUFFEROFFSET - Receive buffer offset value. */
#define TMS570_EMACM_RXBUFFEROFFSET_RXBUFFEROFFSET(val) BSP_FLD32(val,0, 15)
#define TMS570_EMACM_RXBUFFEROFFSET_RXBUFFEROFFSET_GET(reg) BSP_FLD32GET(reg,0, 15)
#define TMS570_EMACM_RXBUFFEROFFSET_RXBUFFEROFFSET_SET(reg,val) BSP_FLD32SET(reg, val,0, 15)
/*---------------TMS570_EMACM_RXFILTERLOWTHRESH---------------*/
/* field: RXFILTERTHRESH - Receive filter low threshold. */
#define TMS570_EMACM_RXFILTERLOWTHRESH_RXFILTERTHRESH(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_RXFILTERLOWTHRESH_RXFILTERTHRESH_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_RXFILTERLOWTHRESH_RXFILTERTHRESH_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-----------------TMS570_EMACM_RXFLOWTHRESH-----------------*/
/* field: RXnFLOWTHRESH - Receive flow threshold. */
#define TMS570_EMACM_RXFLOWTHRESH_RXnFLOWTHRESH(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_RXFLOWTHRESH_RXnFLOWTHRESH_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_RXFLOWTHRESH_RXnFLOWTHRESH_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-----------------TMS570_EMACM_RXFREEBUFFER-----------------*/
/* field: RXnFREEBUF - Receive free buffer count. These bits contain the count of free buffers available. */
#define TMS570_EMACM_RXFREEBUFFER_RXnFREEBUF(val) BSP_FLD32(val,0, 15)
#define TMS570_EMACM_RXFREEBUFFER_RXnFREEBUF_GET(reg) BSP_FLD32GET(reg,0, 15)
#define TMS570_EMACM_RXFREEBUFFER_RXnFREEBUF_SET(reg,val) BSP_FLD32SET(reg, val,0, 15)
/*------------------TMS570_EMACM_MACCONTROL------------------*/
/* field: RMIISPEED - RMII interface transmit and receive speed select. */
#define TMS570_EMACM_MACCONTROL_RMIISPEED BSP_BIT32(15)
/* field: RXOFFLENBLOCK - Receive offset / length word write block. */
#define TMS570_EMACM_MACCONTROL_RXOFFLENBLOCK BSP_BIT32(14)
/* field: RXOWNERSHIP - Receive ownership write bit value. */
#define TMS570_EMACM_MACCONTROL_RXOWNERSHIP BSP_BIT32(13)
/* field: CMDIDLE - Command Idle bit */
#define TMS570_EMACM_MACCONTROL_CMDIDLE BSP_BIT32(11)
/* field: TXSHORTGAPEN - Transmit Short Gap Enable */
#define TMS570_EMACM_MACCONTROL_TXSHORTGAPEN BSP_BIT32(10)
/* field: TXPTYPE - Transmit queue priority type */
#define TMS570_EMACM_MACCONTROL_TXPTYPE BSP_BIT32(9)
/* field: TXPACE - Transmit pacing enable bit */
#define TMS570_EMACM_MACCONTROL_TXPACE BSP_BIT32(6)
/* field: GMIIEN - GMII enable bit */
#define TMS570_EMACM_MACCONTROL_GMIIEN BSP_BIT32(5)
/* field: TXFLOWEN - Transmit flow control enable bit. */
#define TMS570_EMACM_MACCONTROL_TXFLOWEN BSP_BIT32(4)
/* field: RXBUFFERFLOWEN - Receive buffer flow control enable bit */
#define TMS570_EMACM_MACCONTROL_RXBUFFERFLOWEN BSP_BIT32(3)
/* field: LOOPBACK - Loopback mode. The loopback mode forces internal full-duplex mode regardless of the FULLDUPLEX bit. */
#define TMS570_EMACM_MACCONTROL_LOOPBACK BSP_BIT32(1)
/* field: FULLDUPLEX - Full duplex mode. */
#define TMS570_EMACM_MACCONTROL_FULLDUPLEX BSP_BIT32(0)
/*-------------------TMS570_EMACM_MACSTATUS-------------------*/
/* field: IDLE - EMAC idle bit. This bit is cleared to 0 at reset; one clock after reset, it goes to 1. */
#define TMS570_EMACM_MACSTATUS_IDLE BSP_BIT32(31)
/* field: TXERRCODE - Transmit host error code. These bits indicate that EMAC detected transmit DMA related host errors. */
#define TMS570_EMACM_MACSTATUS_TXERRCODE(val) BSP_FLD32(val,20, 23)
#define TMS570_EMACM_MACSTATUS_TXERRCODE_GET(reg) BSP_FLD32GET(reg,20, 23)
#define TMS570_EMACM_MACSTATUS_TXERRCODE_SET(reg,val) BSP_FLD32SET(reg, val,20, 23)
/* field: TXERRCH - Transmit host error channel. These bits indicate which transmit channel the host error occurred on. */
#define TMS570_EMACM_MACSTATUS_TXERRCH(val) BSP_FLD32(val,16, 18)
#define TMS570_EMACM_MACSTATUS_TXERRCH_GET(reg) BSP_FLD32GET(reg,16, 18)
#define TMS570_EMACM_MACSTATUS_TXERRCH_SET(reg,val) BSP_FLD32SET(reg, val,16, 18)
/* field: RXERRCODE - Receive host error code. These bits indicate that EMAC detected receive DMA related host errors. */
#define TMS570_EMACM_MACSTATUS_RXERRCODE(val) BSP_FLD32(val,12, 15)
#define TMS570_EMACM_MACSTATUS_RXERRCODE_GET(reg) BSP_FLD32GET(reg,12, 15)
#define TMS570_EMACM_MACSTATUS_RXERRCODE_SET(reg,val) BSP_FLD32SET(reg, val,12, 15)
/* field: RXERRCH - Receive host error channel. These bits indicate which receive channel the host error occurred on. */
#define TMS570_EMACM_MACSTATUS_RXERRCH(val) BSP_FLD32(val,8, 10)
#define TMS570_EMACM_MACSTATUS_RXERRCH_GET(reg) BSP_FLD32GET(reg,8, 10)
#define TMS570_EMACM_MACSTATUS_RXERRCH_SET(reg,val) BSP_FLD32SET(reg, val,8, 10)
/* field: RXQOSACT - Receive Quality of Service (QOS) active bit. */
#define TMS570_EMACM_MACSTATUS_RXQOSACT BSP_BIT32(2)
/* field: RXFLOWACT - Receive flow control active bit. */
#define TMS570_EMACM_MACSTATUS_RXFLOWACT BSP_BIT32(1)
/* field: TXFLOWACT - Transmit flow control active bit. */
#define TMS570_EMACM_MACSTATUS_TXFLOWACT BSP_BIT32(0)
/*-------------------TMS570_EMACM_EMCONTROL-------------------*/
/* field: SOFT - Emulation soft bit. */
#define TMS570_EMACM_EMCONTROL_SOFT BSP_BIT32(1)
/* field: FREE - Emulation free bit. */
#define TMS570_EMACM_EMCONTROL_FREE BSP_BIT32(0)
/*------------------TMS570_EMACM_FIFOCONTROL------------------*/
/* field: TXCELLTHRESH - Transmit FIFO cell threshold. */
#define TMS570_EMACM_FIFOCONTROL_TXCELLTHRESH(val) BSP_FLD32(val,0, 1)
#define TMS570_EMACM_FIFOCONTROL_TXCELLTHRESH_GET(reg) BSP_FLD32GET(reg,0, 1)
#define TMS570_EMACM_FIFOCONTROL_TXCELLTHRESH_SET(reg,val) BSP_FLD32SET(reg, val,0, 1)
/*-------------------TMS570_EMACM_MACCONFIG-------------------*/
/* field: TXCELLDEPTH - Transmit cell depth. These bits indicate the number of cells in the transmit FIFO. */
#define TMS570_EMACM_MACCONFIG_TXCELLDEPTH(val) BSP_FLD32(val,24, 31)
#define TMS570_EMACM_MACCONFIG_TXCELLDEPTH_GET(reg) BSP_FLD32GET(reg,24, 31)
#define TMS570_EMACM_MACCONFIG_TXCELLDEPTH_SET(reg,val) BSP_FLD32SET(reg, val,24, 31)
/* field: RXCELLDEPTH - Receive cell depth. These bits indicate the number of cells in the receive FIFO. */
#define TMS570_EMACM_MACCONFIG_RXCELLDEPTH(val) BSP_FLD32(val,16, 23)
#define TMS570_EMACM_MACCONFIG_RXCELLDEPTH_GET(reg) BSP_FLD32GET(reg,16, 23)
#define TMS570_EMACM_MACCONFIG_RXCELLDEPTH_SET(reg,val) BSP_FLD32SET(reg, val,16, 23)
/* field: ADDRESSTYPE - Address type */
#define TMS570_EMACM_MACCONFIG_ADDRESSTYPE(val) BSP_FLD32(val,8, 15)
#define TMS570_EMACM_MACCONFIG_ADDRESSTYPE_GET(reg) BSP_FLD32GET(reg,8, 15)
#define TMS570_EMACM_MACCONFIG_ADDRESSTYPE_SET(reg,val) BSP_FLD32SET(reg, val,8, 15)
/* field: MACCFIG - MAC configuration value */
#define TMS570_EMACM_MACCONFIG_MACCFIG(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_MACCONFIG_MACCFIG_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_MACCONFIG_MACCFIG_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-------------------TMS570_EMACM_SOFTRESET-------------------*/
/* field: SOFTRESET - Software reset. Writing a 1 to this bit causes the EMAC logic to be reset. */
#define TMS570_EMACM_SOFTRESET_SOFTRESET BSP_BIT32(0)
/*-----------------TMS570_EMACM_MACSRCADDRLO-----------------*/
/* field: MACSRCADDR0 - MAC source address lower 8-0 bits (byte 0) */
#define TMS570_EMACM_MACSRCADDRLO_MACSRCADDR0(val) BSP_FLD32(val,8, 15)
#define TMS570_EMACM_MACSRCADDRLO_MACSRCADDR0_GET(reg) BSP_FLD32GET(reg,8, 15)
#define TMS570_EMACM_MACSRCADDRLO_MACSRCADDR0_SET(reg,val) BSP_FLD32SET(reg, val,8, 15)
/* field: MACSRCADDR1 - MAC source address bits 15-8 (byte 1) */
#define TMS570_EMACM_MACSRCADDRLO_MACSRCADDR1(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_MACSRCADDRLO_MACSRCADDR1_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_MACSRCADDRLO_MACSRCADDR1_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-----------------TMS570_EMACM_MACSRCADDRHI-----------------*/
/* field: MACSRCADDR2 - MAC source address bits 23-16 (byte 2) */
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR2(val) BSP_FLD32(val,24, 31)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR2_GET(reg) BSP_FLD32GET(reg,24, 31)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR2_SET(reg,val) BSP_FLD32SET(reg, val,24, 31)
/* field: MACSRCADDR3 - MAC source address bits 31-24 (byte 3) */
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR3(val) BSP_FLD32(val,16, 23)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR3_GET(reg) BSP_FLD32GET(reg,16, 23)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR3_SET(reg,val) BSP_FLD32SET(reg, val,16, 23)
/* field: MACSRCADDR4 - MAC source address bits 39-32 (byte 4) */
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR4(val) BSP_FLD32(val,8, 15)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR4_GET(reg) BSP_FLD32GET(reg,8, 15)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR4_SET(reg,val) BSP_FLD32SET(reg, val,8, 15)
/* field: MACSRCADDR5 - MAC source address bits 47-40 (byte 5) */
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR5(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR5_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_MACSRCADDRHI_MACSRCADDR5_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-------------------TMS570_EMACM_MACHASH1-------------------*/
/* field: MACHASH1 - Least-significant 32 bits of the hash table corresponding to hash values 0 to 31. */
/* Whole 32 bits */
/*-------------------TMS570_EMACM_MACHASH2-------------------*/
/* field: MACHASH2 - Most-significant 32 bits of the hash table corresponding to hash values 32 to 63. */
/* Whole 32 bits */
/*-------------------TMS570_EMACM_BOFFTEST-------------------*/
/* field: RNDNUM - Backoff random number generator. */
#define TMS570_EMACM_BOFFTEST_RNDNUM(val) BSP_FLD32(val,16, 25)
#define TMS570_EMACM_BOFFTEST_RNDNUM_GET(reg) BSP_FLD32GET(reg,16, 25)
#define TMS570_EMACM_BOFFTEST_RNDNUM_SET(reg,val) BSP_FLD32SET(reg, val,16, 25)
/* field: COLLCOUNT - Collision count. These bits indicate the number of collisions the current frame has experienced. */
#define TMS570_EMACM_BOFFTEST_COLLCOUNT(val) BSP_FLD32(val,12, 15)
#define TMS570_EMACM_BOFFTEST_COLLCOUNT_GET(reg) BSP_FLD32GET(reg,12, 15)
#define TMS570_EMACM_BOFFTEST_COLLCOUNT_SET(reg,val) BSP_FLD32SET(reg, val,12, 15)
/* field: TXBACKOFF - Backoff count. */
#define TMS570_EMACM_BOFFTEST_TXBACKOFF(val) BSP_FLD32(val,0, 9)
#define TMS570_EMACM_BOFFTEST_TXBACKOFF_GET(reg) BSP_FLD32GET(reg,0, 9)
#define TMS570_EMACM_BOFFTEST_TXBACKOFF_SET(reg,val) BSP_FLD32SET(reg, val,0, 9)
/*-------------------TMS570_EMACM_TPACETEST-------------------*/
/* field: PACEVAL - Pacing register current value. A nonzero value in this field indicates that transmit pacing is active. */
#define TMS570_EMACM_TPACETEST_PACEVAL(val) BSP_FLD32(val,0, 4)
#define TMS570_EMACM_TPACETEST_PACEVAL_GET(reg) BSP_FLD32GET(reg,0, 4)
#define TMS570_EMACM_TPACETEST_PACEVAL_SET(reg,val) BSP_FLD32SET(reg, val,0, 4)
/*--------------------TMS570_EMACM_RXPAUSE--------------------*/
/* field: PAUSETIMER - Receive pause timer value. */
#define TMS570_EMACM_RXPAUSE_PAUSETIMER(val) BSP_FLD32(val,0, 15)
#define TMS570_EMACM_RXPAUSE_PAUSETIMER_GET(reg) BSP_FLD32GET(reg,0, 15)
#define TMS570_EMACM_RXPAUSE_PAUSETIMER_SET(reg,val) BSP_FLD32SET(reg, val,0, 15)
/*--------------------TMS570_EMACM_TXPAUSE--------------------*/
/* field: PAUSETIMER - Transmit pause timer value. */
#define TMS570_EMACM_TXPAUSE_PAUSETIMER(val) BSP_FLD32(val,0, 15)
#define TMS570_EMACM_TXPAUSE_PAUSETIMER_GET(reg) BSP_FLD32GET(reg,0, 15)
#define TMS570_EMACM_TXPAUSE_PAUSETIMER_SET(reg,val) BSP_FLD32SET(reg, val,0, 15)
/*-------------------TMS570_EMACM_MACADDRLO-------------------*/
/* field: VALID - Address valid bit. */
#define TMS570_EMACM_MACADDRLO_VALID BSP_BIT32(20)
/* field: MATCHFILT - Match or filter bit */
#define TMS570_EMACM_MACADDRLO_MATCHFILT BSP_BIT32(19)
/* field: CHANNEL - Channel select. Determines which receive channel a valid address match will be transferred to. */
#define TMS570_EMACM_MACADDRLO_CHANNEL(val) BSP_FLD32(val,16, 18)
#define TMS570_EMACM_MACADDRLO_CHANNEL_GET(reg) BSP_FLD32GET(reg,16, 18)
#define TMS570_EMACM_MACADDRLO_CHANNEL_SET(reg,val) BSP_FLD32SET(reg, val,16, 18)
/* field: MACADDR0 - MAC address lower 8-0 bits (byte 0) */
#define TMS570_EMACM_MACADDRLO_MACADDR0(val) BSP_FLD32(val,8, 15)
#define TMS570_EMACM_MACADDRLO_MACADDR0_GET(reg) BSP_FLD32GET(reg,8, 15)
#define TMS570_EMACM_MACADDRLO_MACADDR0_SET(reg,val) BSP_FLD32SET(reg, val,8, 15)
/* field: MACADDR1 - MAC address bits 15-8 (byte 1) */
#define TMS570_EMACM_MACADDRLO_MACADDR1(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_MACADDRLO_MACADDR1_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_MACADDRLO_MACADDR1_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-------------------TMS570_EMACM_MACADDRHI-------------------*/
/* field: MACADDR2 - MAC source address bits 23-16 (byte 2) */
#define TMS570_EMACM_MACADDRHI_MACADDR2(val) BSP_FLD32(val,24, 31)
#define TMS570_EMACM_MACADDRHI_MACADDR2_GET(reg) BSP_FLD32GET(reg,24, 31)
#define TMS570_EMACM_MACADDRHI_MACADDR2_SET(reg,val) BSP_FLD32SET(reg, val,24, 31)
/* field: MACADDR3 - MAC source address bits 31-24 (byte 3) */
#define TMS570_EMACM_MACADDRHI_MACADDR3(val) BSP_FLD32(val,16, 23)
#define TMS570_EMACM_MACADDRHI_MACADDR3_GET(reg) BSP_FLD32GET(reg,16, 23)
#define TMS570_EMACM_MACADDRHI_MACADDR3_SET(reg,val) BSP_FLD32SET(reg, val,16, 23)
/* field: MACADDR4 - MAC source address bits 39-32 (byte 4) */
#define TMS570_EMACM_MACADDRHI_MACADDR4(val) BSP_FLD32(val,8, 15)
#define TMS570_EMACM_MACADDRHI_MACADDR4_GET(reg) BSP_FLD32GET(reg,8, 15)
#define TMS570_EMACM_MACADDRHI_MACADDR4_SET(reg,val) BSP_FLD32SET(reg, val,8, 15)
/* field: MACADDR5 - MAC source address bits 47-40 (byte 5). Bit 40 is the group bit. It is forced to 0 and read as 0. */
#define TMS570_EMACM_MACADDRHI_MACADDR5(val) BSP_FLD32(val,0, 7)
#define TMS570_EMACM_MACADDRHI_MACADDR5_GET(reg) BSP_FLD32GET(reg,0, 7)
#define TMS570_EMACM_MACADDRHI_MACADDR5_SET(reg,val) BSP_FLD32SET(reg, val,0, 7)
/*-------------------TMS570_EMACM_MACINDEX-------------------*/
/* field: MACINDEX - MAC address index. All eight addresses share the upper 40 bits. */
#define TMS570_EMACM_MACINDEX_MACINDEX(val) BSP_FLD32(val,0, 2)
#define TMS570_EMACM_MACINDEX_MACINDEX_GET(reg) BSP_FLD32GET(reg,0, 2)
#define TMS570_EMACM_MACINDEX_MACINDEX_SET(reg,val) BSP_FLD32SET(reg, val,0, 2)
/*---------------------TMS570_EMACM_TXHDP---------------------*/
/* field: TXnHDP - Transmit channel n DMA Head Descriptor pointer. */
/* Whole 32 bits */
/*---------------------TMS570_EMACM_RXHDP---------------------*/
/* field: RXnHDP - Receive channel n DMA Head Descriptor pointer. */
/* Whole 32 bits */
/*---------------------TMS570_EMACM_TXCP---------------------*/
/* field: TXnCP - Transmit channel n completion pointer register is written by the host with the buffer descriptor */
/* Whole 32 bits */
/*---------------------TMS570_EMACM_RXCP---------------------*/
/* field: RXnCP - Receive channel n completion pointer register is written by the host with the buffer descriptor */
/* Whole 32 bits */
#endif /* LIBBSP_ARM_TMS570_EMACM */
|
yangqiao/rtems
|
c/src/lib/libbsp/arm/tms570/include/ti_herc/reg_emacm.h
|
C
|
gpl-2.0
| 45,087
|
/* -*- mode: c; c-basic-offset: 8; indent-tabs-mode: nil; -*-
* vim:expandtab:shiftwidth=8:tabstop=8:
*
* GPL HEADER START
*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This program 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 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 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 program; If not, see
* http://www.sun.com/software/products/lustre/docs/GPLv2.pdf
*
* Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
* CA 95054 USA or visit www.sun.com if you need additional information or
* have any questions.
*
* GPL HEADER END
*/
/*
* Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
* Use is subject to license terms.
*/
/*
* This file is part of Lustre, http://www.lustre.org/
* Lustre is a trademark of Sun Microsystems, Inc.
*
* lustre/obdclass/capa.c
*
* Lustre Capability Hash Management
*
* Author: Lai Siyao<lsy@clusterfs.com>
*/
#ifndef EXPORT_SYMTAB
# define EXPORT_SYMTAB
#endif
#define DEBUG_SUBSYSTEM S_SEC
#ifdef __KERNEL__
#include <linux/version.h>
#include <linux/fs.h>
#include <asm/unistd.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/init.h>
#include <obd_class.h>
#include <lustre_debug.h>
#include <lustre/lustre_idl.h>
#else
#include <liblustre.h>
#endif
#include <libcfs/list.h>
#include <lustre_capa.h>
#define NR_CAPAHASH 32
#define CAPA_HASH_SIZE 3000 /* for MDS & OSS */
cfs_mem_cache_t *capa_cachep = NULL;
#ifdef __KERNEL__
/* lock for capa hash/capa_list/fo_capa_keys */
cfs_spinlock_t capa_lock = CFS_SPIN_LOCK_UNLOCKED;
cfs_list_t capa_list[CAPA_SITE_MAX];
static struct capa_hmac_alg capa_hmac_algs[] = {
DEF_CAPA_HMAC_ALG("sha1", SHA1, 20, 20),
};
#endif
/* capa count */
int capa_count[CAPA_SITE_MAX] = { 0, };
EXPORT_SYMBOL(capa_cachep);
EXPORT_SYMBOL(capa_list);
EXPORT_SYMBOL(capa_lock);
EXPORT_SYMBOL(capa_count);
cfs_hlist_head_t *init_capa_hash(void)
{
cfs_hlist_head_t *hash;
int nr_hash, i;
OBD_ALLOC(hash, CFS_PAGE_SIZE);
if (!hash)
return NULL;
nr_hash = CFS_PAGE_SIZE / sizeof(cfs_hlist_head_t);
LASSERT(nr_hash > NR_CAPAHASH);
for (i = 0; i < NR_CAPAHASH; i++)
CFS_INIT_HLIST_HEAD(hash + i);
return hash;
}
#ifdef __KERNEL__
static inline int capa_on_server(struct obd_capa *ocapa)
{
return ocapa->c_site == CAPA_SITE_SERVER;
}
static inline void capa_delete(struct obd_capa *ocapa)
{
LASSERT(capa_on_server(ocapa));
cfs_hlist_del_init(&ocapa->u.tgt.c_hash);
cfs_list_del_init(&ocapa->c_list);
capa_count[ocapa->c_site]--;
/* release the ref when alloc */
capa_put(ocapa);
}
void cleanup_capa_hash(cfs_hlist_head_t *hash)
{
int i;
cfs_hlist_node_t *pos, *next;
struct obd_capa *oc;
cfs_spin_lock(&capa_lock);
for (i = 0; i < NR_CAPAHASH; i++) {
cfs_hlist_for_each_entry_safe(oc, pos, next, hash + i,
u.tgt.c_hash)
capa_delete(oc);
}
cfs_spin_unlock(&capa_lock);
OBD_FREE(hash, CFS_PAGE_SIZE);
}
static inline int capa_hashfn(struct lu_fid *fid)
{
return (fid_oid(fid) ^ fid_ver(fid)) *
(unsigned long)(fid_seq(fid) + 1) % NR_CAPAHASH;
}
/* capa renewal time check is earlier than that on client, which is to prevent
* client renew right after obtaining it. */
static inline int capa_is_to_expire(struct obd_capa *oc)
{
return cfs_time_before(cfs_time_sub(oc->c_expiry,
cfs_time_seconds(oc->c_capa.lc_timeout)*2/3),
cfs_time_current());
}
static struct obd_capa *find_capa(struct lustre_capa *capa,
cfs_hlist_head_t *head, int alive)
{
cfs_hlist_node_t *pos;
struct obd_capa *ocapa;
int len = alive ? offsetof(struct lustre_capa, lc_keyid):sizeof(*capa);
cfs_hlist_for_each_entry(ocapa, pos, head, u.tgt.c_hash) {
if (memcmp(&ocapa->c_capa, capa, len))
continue;
/* don't return one that will expire soon in this case */
if (alive && capa_is_to_expire(ocapa))
continue;
LASSERT(capa_on_server(ocapa));
DEBUG_CAPA(D_SEC, &ocapa->c_capa, "found");
return ocapa;
}
return NULL;
}
#define LRU_CAPA_DELETE_COUNT 12
static inline void capa_delete_lru(cfs_list_t *head)
{
struct obd_capa *ocapa;
cfs_list_t *node = head->next;
int count = 0;
/* free LRU_CAPA_DELETE_COUNT unused capa from head */
while (count++ < LRU_CAPA_DELETE_COUNT) {
ocapa = cfs_list_entry(node, struct obd_capa, c_list);
node = node->next;
if (cfs_atomic_read(&ocapa->c_refc))
continue;
DEBUG_CAPA(D_SEC, &ocapa->c_capa, "free lru");
capa_delete(ocapa);
}
}
/* add or update */
struct obd_capa *capa_add(cfs_hlist_head_t *hash, struct lustre_capa *capa)
{
cfs_hlist_head_t *head = hash + capa_hashfn(&capa->lc_fid);
struct obd_capa *ocapa, *old = NULL;
cfs_list_t *list = &capa_list[CAPA_SITE_SERVER];
ocapa = alloc_capa(CAPA_SITE_SERVER);
if (IS_ERR(ocapa))
return NULL;
cfs_spin_lock(&capa_lock);
old = find_capa(capa, head, 0);
if (!old) {
ocapa->c_capa = *capa;
set_capa_expiry(ocapa);
cfs_hlist_add_head(&ocapa->u.tgt.c_hash, head);
cfs_list_add_tail(&ocapa->c_list, list);
capa_get(ocapa);
capa_count[CAPA_SITE_SERVER]++;
if (capa_count[CAPA_SITE_SERVER] > CAPA_HASH_SIZE)
capa_delete_lru(list);
cfs_spin_unlock(&capa_lock);
return ocapa;
} else {
capa_get(old);
cfs_spin_unlock(&capa_lock);
capa_put(ocapa);
return old;
}
}
struct obd_capa *capa_lookup(cfs_hlist_head_t *hash, struct lustre_capa *capa,
int alive)
{
struct obd_capa *ocapa;
cfs_spin_lock(&capa_lock);
ocapa = find_capa(capa, hash + capa_hashfn(&capa->lc_fid), alive);
if (ocapa) {
cfs_list_move_tail(&ocapa->c_list,
&capa_list[CAPA_SITE_SERVER]);
capa_get(ocapa);
}
cfs_spin_unlock(&capa_lock);
return ocapa;
}
int capa_hmac(__u8 *hmac, struct lustre_capa *capa, __u8 *key)
{
struct ll_crypto_hash *tfm;
struct capa_hmac_alg *alg;
int keylen;
struct scatterlist sl;
if (capa_alg(capa) != CAPA_HMAC_ALG_SHA1) {
CERROR("unknown capability hmac algorithm!\n");
return -EFAULT;
}
alg = &capa_hmac_algs[capa_alg(capa)];
tfm = ll_crypto_alloc_hash(alg->ha_name, 0, 0);
if (!tfm) {
CERROR("crypto_alloc_tfm failed, check whether your kernel"
"has crypto support!\n");
return -ENOMEM;
}
keylen = alg->ha_keylen;
sg_set_page(&sl, virt_to_page(capa),
offsetof(struct lustre_capa, lc_hmac),
(unsigned long)(capa) % CFS_PAGE_SIZE);
ll_crypto_hmac(tfm, key, &keylen, &sl, sl.length, hmac);
ll_crypto_free_hash(tfm);
return 0;
}
int capa_encrypt_id(__u32 *d, __u32 *s, __u8 *key, int keylen)
{
struct ll_crypto_cipher *tfm;
struct scatterlist sd;
struct scatterlist ss;
struct blkcipher_desc desc;
unsigned int min;
int rc;
char alg[CRYPTO_MAX_ALG_NAME+1] = "aes";
ENTRY;
/* passing "aes" in a variable instead of a constant string keeps gcc
* 4.3.2 happy */
tfm = ll_crypto_alloc_blkcipher(alg, 0, 0 );
if (tfm == NULL) {
CERROR("failed to load transform for aes\n");
RETURN(-EFAULT);
}
min = ll_crypto_tfm_alg_min_keysize(tfm);
if (keylen < min) {
CERROR("keylen at least %d bits for aes\n", min * 8);
GOTO(out, rc = -EINVAL);
}
rc = ll_crypto_blkcipher_setkey(tfm, key, min);
if (rc) {
CERROR("failed to setting key for aes\n");
GOTO(out, rc);
}
sg_set_page(&sd, virt_to_page(d), 16,
(unsigned long)(d) % CFS_PAGE_SIZE);
sg_set_page(&ss, virt_to_page(s), 16,
(unsigned long)(s) % CFS_PAGE_SIZE);
desc.tfm = tfm;
desc.info = NULL;
desc.flags = 0;
rc = ll_crypto_blkcipher_encrypt(&desc, &sd, &ss, 16);
if (rc) {
CERROR("failed to encrypt for aes\n");
GOTO(out, rc);
}
EXIT;
out:
ll_crypto_free_blkcipher(tfm);
return rc;
}
int capa_decrypt_id(__u32 *d, __u32 *s, __u8 *key, int keylen)
{
struct ll_crypto_cipher *tfm;
struct scatterlist sd;
struct scatterlist ss;
struct blkcipher_desc desc;
unsigned int min;
int rc;
char alg[CRYPTO_MAX_ALG_NAME+1] = "aes";
ENTRY;
/* passing "aes" in a variable instead of a constant string keeps gcc
* 4.3.2 happy */
tfm = ll_crypto_alloc_blkcipher(alg, 0, 0 );
if (tfm == NULL) {
CERROR("failed to load transform for aes\n");
RETURN(-EFAULT);
}
min = ll_crypto_tfm_alg_min_keysize(tfm);
if (keylen < min) {
CERROR("keylen at least %d bits for aes\n", min * 8);
GOTO(out, rc = -EINVAL);
}
rc = ll_crypto_blkcipher_setkey(tfm, key, min);
if (rc) {
CERROR("failed to setting key for aes\n");
GOTO(out, rc);
}
sg_set_page(&sd, virt_to_page(d), 16,
(unsigned long)(d) % CFS_PAGE_SIZE);
sg_set_page(&ss, virt_to_page(s), 16,
(unsigned long)(s) % CFS_PAGE_SIZE);
desc.tfm = tfm;
desc.info = NULL;
desc.flags = 0;
rc = ll_crypto_blkcipher_decrypt(&desc, &sd, &ss, 16);
if (rc) {
CERROR("failed to decrypt for aes\n");
GOTO(out, rc);
}
EXIT;
out:
ll_crypto_free_blkcipher(tfm);
return rc;
}
#endif
void capa_cpy(void *capa, struct obd_capa *ocapa)
{
cfs_spin_lock(&ocapa->c_lock);
*(struct lustre_capa *)capa = ocapa->c_capa;
cfs_spin_unlock(&ocapa->c_lock);
}
EXPORT_SYMBOL(init_capa_hash);
EXPORT_SYMBOL(cleanup_capa_hash);
EXPORT_SYMBOL(capa_add);
EXPORT_SYMBOL(capa_lookup);
EXPORT_SYMBOL(capa_hmac);
EXPORT_SYMBOL(capa_encrypt_id);
EXPORT_SYMBOL(capa_decrypt_id);
EXPORT_SYMBOL(capa_cpy);
|
chaos/lustre-kdmu
|
lustre/obdclass/capa.c
|
C
|
gpl-2.0
| 11,672
|
package info.jbcs.minecraft.chisel.client.render;
import info.jbcs.minecraft.utilities.Drawing;
import net.minecraft.block.Block;
import net.minecraft.client.renderer.RenderBlocks;
import net.minecraft.world.IBlockAccess;
import org.lwjgl.opengl.GL11;
import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler;
import cpw.mods.fml.client.registry.RenderingRegistry;
public class BlockNoCTMRenderer implements ISimpleBlockRenderingHandler
{
static int id;
public BlockNoCTMRenderer()
{
id = RenderingRegistry.getNextAvailableRenderId();
}
@Override
public void renderInventoryBlock(Block block, int meta, int modelID, RenderBlocks renderer)
{
GL11.glTranslatef(-0.5F, -0.5F, -0.5F);
Drawing.drawBlock(block, meta, renderer);
}
@Override
public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer)
{
int meta = world.getBlockMetadata(x, y, z);
if(meta != 0) renderer.overrideBlockTexture = block.getIcon(0, meta);
renderer.setRenderBounds(0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 1.0F);
renderer.renderStandardBlock(block, x, y, z);
renderer.overrideBlockTexture = null;
return false;
}
@Override
public boolean shouldRender3DInInventory(int renderId)
{
return true;
}
@Override
public int getRenderId()
{
return id;
}
}
|
EoD/Chisel
|
src/main/java/info/jbcs/minecraft/chisel/client/render/BlockNoCTMRenderer.java
|
Java
|
gpl-2.0
| 1,457
|
/* ----------------------------------------------------------------------------------
RESPONSIVE LAYOUTS
---------------------------------------------------------------------------------- */
/* Desktop / Laptop */
@media only screen and (max-width: 960px) {
}
/* iPad & Tablet */
@media only screen and (max-width: 768px) {
/* Header */
#header {
padding: 10px 10px 20px;
}
#logo {
float: none;
position: static;
text-align: center;
margin: 0 10px 10px;
}
#logo img {
max-height: 40px;
}
#header-links,
#pre-header-search {
display: none;
}
#header-responsive {
display: block;
width: 100%;
}
#header-responsive ul {
margin: 0;
}
#header-responsive li {
list-style: none;
}
#header-responsive .sub-menu li,
#header-responsive .sub-menu li:hover {
padding: 0;
}
#header-responsive li a {
display: block;
padding: 10px 25px;
border-bottom: 1px solid #F0F0F0;
}
#header-responsive li a:hover,
#header-responsive li.current_page_item > a {
color: #F33F3F;
}
#header-responsive-inner {
border-left: 1px solid #F0F0F0;
border-right: 1px solid #F0F0F0;
}
.nav-collapse {
overflow: hidden;
height: 0;
}
.btn-navbar {
display: block;
padding: 10px 10px;
background-color: #333;
border: 1px solid #222;
}
.btn-navbar .icon-bar {
display: block;
width: 20px;
height: 3px;
margin: 0 0 0 auto;
background-color: #FFF;
}
.btn-navbar .icon-bar + .icon-bar {
margin-top: 3px;
}
.nav-collapse.collapse {
-webkit-transition: height 0.35s ease;
-moz-transition: height 0.35s ease;
-ms-transition: height 0.35s ease;
-o-transition: height 0.35s ease;
transition: height 0.35s ease;
position: relative;
overflow: hidden;
height: 0;
}
/* Slider */
#slider {
padding: 0 10px;
}
#slider .rslides-container {
padding: 0;
}
/* Intro / Outro */
.action-text.action-teaser h3,
.attention_text h3 {
margin-top: 0px;
}
/* Footer */
/* Sidebar */
/* Blog */
/* Post */
.commentlist .children .children .children {
margin: 0px;
}
/* Portfolio */
.hover-excerpt {
display: none;
}
.da-thumbs li article h3 {
padding: 0;
}
/* Project */
/* Contact */
/* Widgets */
}
/* Small Tablets & Larger Phones */
@media only screen and (max-width: 685px) {
/* Main */
#pre-header-links-inner,
#breadcrumbs,
#sidebar,
#intro.option3 .page-teaser,
#footer-menu,
.meta-author {
display: none;
}
#main-core,
#intro.option1,
#intro.option2 {
margin-left: 0px;
}
#main {
width: 100%;
}
#main-core,
#intro,
.commentlist .children .children {
margin: 0px;
}
#intro.option1 #intro-core {
display: block;
}
.notification-text {
display: block;
margin-bottom: 5px;
}
/* Featured Slider */
#slider .featured-excerpt {
display: none;
}
/* Portfolio */
/* Single Post Share */
#author-image,
#author-text {
width: 100%;
float: none;
}
#author-text {
margin: 20px 0px 0 0px;
}
#author-text h3,
#author-text p {
margin-left: 30px;
padding-right: 40px;
}
.commentlist .children .children {
margin: 0px;
}
/* Intro / Outro */
.action-text.three_fourth,
.action-button.one_fourth.last {
width:100%;
float:none;
margin-right:0px;
}
.action-button h4 {
padding: 10px 10px;
margin: 0px;
}
.action-text {
padding-bottom: 10px;
}
.action-text > h3 {
margin-top: 0px;
}
.action-text,
.attention_text {
text-align: center;
}
}
/* iPhone (Landscape) */
@media only screen and (max-width: 568px) {
/* Main */
#notification-core .notification-text {
display: block;
margin-bottom: 5px;
}
/* Featured Slider */
#slider .featured-title span {
font-size: 20px;
}
#slider .featured-link a {
padding: 3px 15px;
margin: 0px;
}
/* Portfolio */
.element.column-1 ,
.element.column-2 ,
.element.column-3 ,
.element.column-4 {
width: auto;
}
#filter.portfolio-filter {
margin: 0;
}
#filter.portfolio-filter li {
display: block;
padding-right: 1px;
}
#filter.portfolio-filter li a {
width: 100%;
padding: 5px 20px;
border-bottom: 1px solid #EEE;
}
#filter.portfolio-filter > li:first-child a {
border-top: 1px solid #EEE;
}
#filter.portfolio-filter li:after {
content: "";
}
#filter.portfolio-filter li a:hover,
#filter.portfolio-filter li a.selected {
color: white;
background: #F33F3F;
}
/* Blog */
.blog-style1 .entry-content {
margin-top: 20px;
}
/* Single Post */
#sharemessage {
text-align: center;
margin-bottom: 15px;
padding: 0;
}
#shareicons {
padding: 0;
}
#sharemessage,
#shareicons {
width: 100%;
display: block;
text-align: center;
}
#comments {
margin-right: 0;
}
#nocomments {
margin-left: 0;
}
/* Single Post Share */
#author-image {
display: none;
}
#author-text {
margin: 0px;
}
#author-bio .author-description {
padding-right: 50px;
}
span.post-title {
display:none;
}
p.form-submit {
margin-bottom: 0px;
}
#shareicons a {
float: none;
margin-left: 10px;
margin-right: 10px;
}
.form-allowed-tags {
display: none;
}
/* Intro / Outro */
.action-text h3, .action-text p {
margin-left: 0px;
margin-right: 0px;
}
.action-button p {
margin-left: 0px;
margin-right: 0px;
}
/* Shortcode Content */
.one_half,
.one_third,
.two_third,
.one_fourth,
.three_fourth,
.one_fifth,
.two_fifth,
.three_fifth,
.four_fifth,
.one_sixth,
.five_sixth {
width:100%;
float:none;
margin-right:0px;
}
#footer .widget-area.one_half,
#footer .widget-area.one_third,
#footer .widget-area.two_third,
#footer .widget-area.one_fourth,
#footer .widget-area.three_fourth,
#footer .widget-area.one_fifth,
#footer .widget-area.two_fifth,
#footer .widget-area.three_fifth,
#footer .widget-area.four_fifth,
#footer .widget-area.one_sixth,
#footer .widget-area.five_sixth {
width:100%;
float:none;
margin-right:0px;
}
.border {
margin-left:10px;
margin-right:10px;
}
.pricing-table.style1 span {
text-align: center;
padding-left: 0;
padding-right: 0;
background: none !important
}
.pricing-table.style2 .pricing-package {
float: none;
display: block;
margin: 0 auto 20px;
max-width: 100% !important;
width: 100% !important;
}
.pricing-table.style2 .pricing-package.big {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1);
}
/* Bootstrap Menu */
#logo {
float: none;
text-align: center;
}
.btn-navbar {
float: none;
}
/* Widgets */
.thinkup_widget_categories li span {
float: none;
padding-left: 5px;
}
.thinkup_widget_flickr .flickr-photo {
width: auto !important;
margin-right: 5px !important;
}
}
/* iPhone (Portrait) */
@media only screen and (max-width: 320px) {
/* Single Post Share */
#shareicons a {
margin-left: 5px;
margin-right: 5px;
}
.commentlist .children {
margin: 0 0 0 25px;
}
/* Portfolio */
/* Shortcodes */
}
/* Retina Display */
@media only screen and
(-webkit-min-device-pixel-ratio: 1.5), only screen and
(-o-min-device-pixel-ratio: 3/2), only screen and
(min-device-pixel-ratio: 1.5) {
}
|
dzmitryh/wp-in-mebel.by
|
wp-content/themes/minamaze/styles/style-responsive.css
|
CSS
|
gpl-2.0
| 7,156
|
#include "GUIPlexScreenSaverPhoto.h"
#include "PlexTypes.h"
#include "Application.h"
#include "guilib/GUIMultiImage.h"
#include "guilib/GUIWindowManager.h"
#include "Application.h"
#include "GraphicContext.h"
#include "JobManager.h"
#include "PlexJobs.h"
#include "Client/PlexServerManager.h"
#include "PlexApplication.h"
#include "settings/GUISettings.h"
#include "File.h"
#include "guilib/GUIFontManager.h"
#include "GUIInfoManager.h"
#include "addons/AddonManager.h"
#include "ApplicationMessenger.h"
using namespace XFILE;
///////////////////////////////////////////////////////////////////////////////////////////////////
CGUIPlexScreenSaverPhoto::CGUIPlexScreenSaverPhoto() : CGUIDialog(WINDOW_DIALOG_PLEX_SS_PHOTOS, "")
{
m_needsScaling = false;
m_animations.push_back(CAnimation::CreateFader(0, 100, 0, 700, ANIM_TYPE_WINDOW_OPEN));
m_animations.push_back(CAnimation::CreateFader(100, 0, 0, 700, ANIM_TYPE_WINDOW_CLOSE));
m_loadType = LOAD_EVERY_TIME;
m_renderOrder = INT_MAX;
m_multiImage = NULL;
m_overlayImage = NULL;
m_clockLabel = NULL;
m_imageLabel = NULL;
m_currentPosition = TOP_LEFT;
}
///////////////////////////////////////////////////////////////////////////////////////////////////
bool CGUIPlexScreenSaverPhoto::OnMessage(CGUIMessage &message)
{
switch (message.GetMessage())
{
case GUI_MSG_WINDOW_INIT:
{
if (!m_multiImage)
{
CPlexServerPtr server = g_plexApplication.serverManager->GetBestServer();
if (!server)
return false;
CLabelInfo info;
info.textColor = 0xfff5f5f5;
info.font = g_fontManager.GetFont("Regular-30", true);
if (!info.font)
{
CLog::Log(LOGWARNING, "Cant find font DefaultFont!");
}
info.shadowColor = 0xff000000;
/* we need to get settings */
ADDON::AddonPtr screensaver;
ADDON::CAddonMgr::Get().GetAddon("screensaver.xbmc.builtin.plexphotos", screensaver, ADDON::ADDON_SCREENSAVER);
if (!screensaver)
return false;
if (m_clockLabel)
delete m_clockLabel;
int posX, posY, align;
getXYPosition(posX, posY, align);
if (screensaver->GetSetting("showclock") == "true")
{
m_clockLabel = new CGUILabelControl(GetID(), 1236, posX, posY,
800, 50, info, false, false);
m_clockLabel->SetLabel("00:00");
m_clockLabel->SetAlignment(align);
m_clockLabel->UpdateInfo();
m_clockLabel->SetVisible(true);
posY += 50;
}
if (m_imageLabel)
delete m_imageLabel;
if (screensaver->GetSetting("showinfo") == "true")
{
info.font = g_fontManager.GetFont("Regular-18", true);
m_imageLabel = new CGUILabelControl(GetID(), 1237, posX, posY, 800, 50, info, false, false);
m_imageLabel->SetLabel("No images found...");
m_imageLabel->SetAlignment(align);
m_imageLabel->UpdateInfo();
}
if (screensaver->GetSetting("overlay") == "true" &&
XFILE::CFile::Exists("special://xbmc/media/SlideshowOverlay.png"))
{
if (m_overlayImage)
delete m_overlayImage;
m_overlayImage = new CGUIImage(GetID(), 1235, 0, 0,
g_graphicsContext.GetWidth(),
g_graphicsContext.GetHeight(),
CTextureInfo());
m_overlayImage->SetFileName("special://xbmc/media/SlideshowOverlay.png");
}
if (screensaver->GetSetting("showtype") == "Photos")
m_showType = PHOTOS;
else
m_showType = FANART;
CURL art = server->BuildPlexURL("/library/arts");
art.SetOption("sort", "random");
if (m_showType == PHOTOS)
{
art.SetOption("type", boost::lexical_cast<std::string>(PLEX_MEDIA_FILTER_TYPE_PHOTO));
}
else
{
std::stringstream optval;
optval << PLEX_MEDIA_FILTER_TYPE_MOVIE << "," << PLEX_MEDIA_FILTER_TYPE_SHOW << ","
<< PLEX_MEDIA_FILTER_TYPE_ARTIST;
art.SetOption("type", optval.str());
}
CJobManager::GetInstance().AddJob(new CPlexDirectoryFetchJob(art), this);
m_moveTimer.restart();
}
break;
}
case GUI_MSG_WINDOW_DEINIT:
{
if (m_multiImage)
delete m_multiImage;
m_multiImage = NULL;
if (m_overlayImage)
delete m_overlayImage;
m_overlayImage = NULL;
if (m_clockLabel)
delete m_clockLabel;
m_clockLabel = NULL;
if (m_imageLabel)
delete m_imageLabel;
m_imageLabel = NULL;
break;
}
case GUI_MSG_LABEL_BIND:
{
if (m_multiImage && message.GetControlId() == m_multiImage->GetID())
{
m_multiImage->OnMessage(message);
return true;
}
}
}
return CGUIDialog::OnMessage(message);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CGUIPlexScreenSaverPhoto::getXYPosition(int& x, int& y, int& alignment)
{
switch (m_currentPosition)
{
case TOP_LEFT:
x = 50;
y = 25;
alignment = XBFONT_LEFT;
break;
case BOTTOM_LEFT:
x = 50;
y = g_graphicsContext.GetHeight() - 125;
alignment = XBFONT_LEFT;
break;
case TOP_RIGHT:
x = g_graphicsContext.GetWidth() - 850;
y = 25;
alignment = XBFONT_RIGHT;
break;
case BOTTOM_RIGHT:
x = g_graphicsContext.GetWidth() - 850;
y = g_graphicsContext.GetHeight() - 125;
alignment = XBFONT_RIGHT;
break;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CGUIPlexScreenSaverPhoto::moveLabels()
{
switch (m_currentPosition)
{
case TOP_LEFT:
m_currentPosition = BOTTOM_RIGHT;
break;
case BOTTOM_RIGHT:
m_currentPosition = BOTTOM_LEFT;
break;
case BOTTOM_LEFT:
m_currentPosition = TOP_RIGHT;
break;
case TOP_RIGHT:
m_currentPosition = TOP_LEFT;
break;
}
int x, y, align;
getXYPosition(x, y, align);
if (m_clockLabel)
{
m_clockLabel->SetPosition(x, y);
m_clockLabel->SetAlignment(align);
m_clockLabel->MarkDirtyRegion();
y += 50;
}
if (m_imageLabel)
{
m_imageLabel->SetPosition(x, y);
m_imageLabel->SetAlignment(align);
m_imageLabel->MarkDirtyRegion();
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CGUIPlexScreenSaverPhoto::Process(unsigned int currentTime, CDirtyRegionList &dirtyregions)
{
CGUIDialog::Process(currentTime, dirtyregions);
if (m_moveTimer.elapsedMs() >= 2 * 60 * 1000)
{
moveLabels();
m_moveTimer.restart();
}
if (m_multiImage)
m_multiImage->Process(currentTime, dirtyregions);
if (m_overlayImage)
m_overlayImage->Process(currentTime, dirtyregions);
if (m_clockLabel)
{
m_clockLabel->Process(currentTime, dirtyregions);
m_clockLabel->SetLabel(g_infoManager.GetTime(TIME_FORMAT_GUESS));
m_clockLabel->UpdateInfo();
}
if (m_imageLabel)
{
m_imageLabel->Process(currentTime, dirtyregions);
if (m_multiImage)
{
m_imageLabel->SetLabel(m_multiImage->GetCurrentPlexLabel());
m_imageLabel->UpdateInfo();
}
}
m_renderRegion.SetRect(0, 0, (float)g_graphicsContext.GetWidth(), (float)g_graphicsContext.GetHeight());
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CGUIPlexScreenSaverPhoto::UpdateVisibility()
{
// such a hack
if (g_application.GetDimScreenSaverLevel() == 0.042f)
Show();
else
Close();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CGUIPlexScreenSaverPhoto::Render()
{
CRect rect(0, 0, (float)g_graphicsContext.GetWidth(), (float)g_graphicsContext.GetHeight());
CGUITexture::DrawQuad(rect, 0xff000000);
if (m_active)
{
if (m_multiImage)
m_multiImage->Render();
if (m_overlayImage)
m_overlayImage->Render();
if (m_clockLabel)
m_clockLabel->Render();
if (m_imageLabel)
m_imageLabel->Render();
}
CGUIDialog::Render();
}
///////////////////////////////////////////////////////////////////////////////////////////////////
void CGUIPlexScreenSaverPhoto::OnJobComplete(unsigned int jobID, bool success, CJob *job)
{
if (success)
{
CPlexDirectoryFetchJob *fj = static_cast<CPlexDirectoryFetchJob*>(job);
if (fj)
{
m_images = CFileItemListPtr(new CFileItemList());
m_images->Assign(fj->m_items);
m_multiImage = new CGUIMultiImage(GetID(), 1234, 0, 0,
g_graphicsContext.GetWidth(),
g_graphicsContext.GetHeight(),
CTextureInfo(),
15000, 500, true, true, 0);
m_multiImage->SetVisible(true);
CAspectRatio ar;
if (m_showType == PHOTOS)
ar.ratio = CAspectRatio::AR_KEEP;
else
ar.ratio = CAspectRatio::AR_SCALE;
ar.align = ASPECT_ALIGN_CENTER | ASPECT_ALIGNY_TOP;
m_multiImage->SetAspectRatio(ar);
CGUIMessage msg(GUI_MSG_LABEL_BIND, 0, m_multiImage->GetID(), 0, 0, m_images.get());
CApplicationMessenger::Get().SendGUIMessage(msg, GetID());
}
}
}
|
RasPlex/plex-home-theatre
|
plex/GUI/GUIPlexScreenSaverPhoto.cpp
|
C++
|
gpl-2.0
| 9,592
|
.animated {
-webkit-animation-duration: 1s;
animation-duration: 1s;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
.animated.infinite {
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
.animated.hinge {
-webkit-animation-duration: 2s;
animation-duration: 2s;
}
@-webkit-keyframes bounce {
0%, 20%, 53%, 80%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
-webkit-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
40%, 43% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
-webkit-transform: translate3d(0, -30px, 0);
transform: translate3d(0, -30px, 0);
}
70% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
-webkit-transform: translate3d(0, -15px, 0);
transform: translate3d(0, -15px, 0);
}
90% {
-webkit-transform: translate3d(0,-4px,0);
transform: translate3d(0,-4px,0);
}
}
@keyframes bounce {
0%, 20%, 53%, 80%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
-webkit-transform: translate3d(0,0,0);
-ms-transform: translate3d(0,0,0);
transform: translate3d(0,0,0);
}
40%, 43% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
-webkit-transform: translate3d(0, -30px, 0);
-ms-transform: translate3d(0, -30px, 0);
transform: translate3d(0, -30px, 0);
}
70% {
-webkit-transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
transition-timing-function: cubic-bezier(0.755, 0.050, 0.855, 0.060);
-webkit-transform: translate3d(0, -15px, 0);
-ms-transform: translate3d(0, -15px, 0);
transform: translate3d(0, -15px, 0);
}
90% {
-webkit-transform: translate3d(0,-4px,0);
-ms-transform: translate3d(0,-4px,0);
transform: translate3d(0,-4px,0);
}
}
.bounce {
-webkit-animation-name: bounce;
animation-name: bounce;
-webkit-transform-origin: center bottom;
-ms-transform-origin: center bottom;
transform-origin: center bottom;
}
@-webkit-keyframes flash {
0%, 50%, 100% {
opacity: 1;
}
25%, 75% {
opacity: 0;
}
}
@keyframes flash {
0%, 50%, 100% {
opacity: 1;
}
25%, 75% {
opacity: 0;
}
}
.flash {
-webkit-animation-name: flash;
animation-name: flash;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes pulse {
0% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
50% {
-webkit-transform: scale3d(1.05, 1.05, 1.05);
transform: scale3d(1.05, 1.05, 1.05);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
@keyframes pulse {
0% {
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
50% {
-webkit-transform: scale3d(1.05, 1.05, 1.05);
-ms-transform: scale3d(1.05, 1.05, 1.05);
transform: scale3d(1.05, 1.05, 1.05);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
.pulse {
-webkit-animation-name: pulse;
animation-name: pulse;
}
@-webkit-keyframes rubberBand {
0% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
30% {
-webkit-transform: scale3d(1.25, 0.75, 1);
transform: scale3d(1.25, 0.75, 1);
}
40% {
-webkit-transform: scale3d(0.75, 1.25, 1);
transform: scale3d(0.75, 1.25, 1);
}
50% {
-webkit-transform: scale3d(1.15, 0.85, 1);
transform: scale3d(1.15, 0.85, 1);
}
65% {
-webkit-transform: scale3d(.95, 1.05, 1);
transform: scale3d(.95, 1.05, 1);
}
75% {
-webkit-transform: scale3d(1.05, .95, 1);
transform: scale3d(1.05, .95, 1);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
@keyframes rubberBand {
0% {
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
30% {
-webkit-transform: scale3d(1.25, 0.75, 1);
-ms-transform: scale3d(1.25, 0.75, 1);
transform: scale3d(1.25, 0.75, 1);
}
40% {
-webkit-transform: scale3d(0.75, 1.25, 1);
-ms-transform: scale3d(0.75, 1.25, 1);
transform: scale3d(0.75, 1.25, 1);
}
50% {
-webkit-transform: scale3d(1.15, 0.85, 1);
-ms-transform: scale3d(1.15, 0.85, 1);
transform: scale3d(1.15, 0.85, 1);
}
65% {
-webkit-transform: scale3d(.95, 1.05, 1);
-ms-transform: scale3d(.95, 1.05, 1);
transform: scale3d(.95, 1.05, 1);
}
75% {
-webkit-transform: scale3d(1.05, .95, 1);
-ms-transform: scale3d(1.05, .95, 1);
transform: scale3d(1.05, .95, 1);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
.rubberBand {
-webkit-animation-name: rubberBand;
animation-name: rubberBand;
}
@-webkit-keyframes shake {
0%, 100% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
10%, 30%, 50%, 70%, 90% {
-webkit-transform: translate3d(-10px, 0, 0);
transform: translate3d(-10px, 0, 0);
}
20%, 40%, 60%, 80% {
-webkit-transform: translate3d(10px, 0, 0);
transform: translate3d(10px, 0, 0);
}
}
@keyframes shake {
0%, 100% {
-webkit-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
10%, 30%, 50%, 70%, 90% {
-webkit-transform: translate3d(-10px, 0, 0);
-ms-transform: translate3d(-10px, 0, 0);
transform: translate3d(-10px, 0, 0);
}
20%, 40%, 60%, 80% {
-webkit-transform: translate3d(10px, 0, 0);
-ms-transform: translate3d(10px, 0, 0);
transform: translate3d(10px, 0, 0);
}
}
.shake {
-webkit-animation-name: shake;
animation-name: shake;
}
@-webkit-keyframes swing {
20% {
-webkit-transform: rotate3d(0, 0, 1, 15deg);
transform: rotate3d(0, 0, 1, 15deg);
}
40% {
-webkit-transform: rotate3d(0, 0, 1, -10deg);
transform: rotate3d(0, 0, 1, -10deg);
}
60% {
-webkit-transform: rotate3d(0, 0, 1, 5deg);
transform: rotate3d(0, 0, 1, 5deg);
}
80% {
-webkit-transform: rotate3d(0, 0, 1, -5deg);
transform: rotate3d(0, 0, 1, -5deg);
}
100% {
-webkit-transform: rotate3d(0, 0, 1, 0deg);
transform: rotate3d(0, 0, 1, 0deg);
}
}
@keyframes swing {
20% {
-webkit-transform: rotate3d(0, 0, 1, 15deg);
-ms-transform: rotate3d(0, 0, 1, 15deg);
transform: rotate3d(0, 0, 1, 15deg);
}
40% {
-webkit-transform: rotate3d(0, 0, 1, -10deg);
-ms-transform: rotate3d(0, 0, 1, -10deg);
transform: rotate3d(0, 0, 1, -10deg);
}
60% {
-webkit-transform: rotate3d(0, 0, 1, 5deg);
-ms-transform: rotate3d(0, 0, 1, 5deg);
transform: rotate3d(0, 0, 1, 5deg);
}
80% {
-webkit-transform: rotate3d(0, 0, 1, -5deg);
-ms-transform: rotate3d(0, 0, 1, -5deg);
transform: rotate3d(0, 0, 1, -5deg);
}
100% {
-webkit-transform: rotate3d(0, 0, 1, 0deg);
-ms-transform: rotate3d(0, 0, 1, 0deg);
transform: rotate3d(0, 0, 1, 0deg);
}
}
.swing {
-webkit-transform-origin: top center;
-ms-transform-origin: top center;
transform-origin: top center;
-webkit-animation-name: swing;
animation-name: swing;
}
@-webkit-keyframes tada {
0% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
10%, 20% {
-webkit-transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg);
transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg);
}
30%, 50%, 70%, 90% {
-webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg);
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg);
}
40%, 60%, 80% {
-webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg);
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
@keyframes tada {
0% {
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
10%, 20% {
-webkit-transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg);
-ms-transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg);
transform: scale3d(.9, .9, .9) rotate3d(0, 0, 1, -3deg);
}
30%, 50%, 70%, 90% {
-webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg);
-ms-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg);
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, 3deg);
}
40%, 60%, 80% {
-webkit-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg);
-ms-transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg);
transform: scale3d(1.1, 1.1, 1.1) rotate3d(0, 0, 1, -3deg);
}
100% {
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
.tada {
-webkit-animation-name: tada;
animation-name: tada;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes wobble {
0% {
-webkit-transform: none;
transform: none;
}
15% {
-webkit-transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg);
transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg);
}
30% {
-webkit-transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg);
transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg);
}
45% {
-webkit-transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg);
transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg);
}
60% {
-webkit-transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg);
transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg);
}
75% {
-webkit-transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg);
transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes wobble {
0% {
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
15% {
-webkit-transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg);
-ms-transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg);
transform: translate3d(-25%, 0, 0) rotate3d(0, 0, 1, -5deg);
}
30% {
-webkit-transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg);
-ms-transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg);
transform: translate3d(20%, 0, 0) rotate3d(0, 0, 1, 3deg);
}
45% {
-webkit-transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg);
-ms-transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg);
transform: translate3d(-15%, 0, 0) rotate3d(0, 0, 1, -3deg);
}
60% {
-webkit-transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg);
-ms-transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg);
transform: translate3d(10%, 0, 0) rotate3d(0, 0, 1, 2deg);
}
75% {
-webkit-transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg);
-ms-transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg);
transform: translate3d(-5%, 0, 0) rotate3d(0, 0, 1, -1deg);
}
100% {
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.wobble {
-webkit-animation-name: wobble;
animation-name: wobble;
}
@-webkit-keyframes bounceIn {
0%, 20%, 40%, 60%, 80%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: scale3d(.3, .3, .3);
transform: scale3d(.3, .3, .3);
}
20% {
-webkit-transform: scale3d(1.1, 1.1, 1.1);
transform: scale3d(1.1, 1.1, 1.1);
}
40% {
-webkit-transform: scale3d(.9, .9, .9);
transform: scale3d(.9, .9, .9);
}
60% {
opacity: 1;
-webkit-transform: scale3d(1.03, 1.03, 1.03);
transform: scale3d(1.03, 1.03, 1.03);
}
80% {
-webkit-transform: scale3d(.97, .97, .97);
transform: scale3d(.97, .97, .97);
}
100% {
opacity: 1;
-webkit-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
@keyframes bounceIn {
0%, 20%, 40%, 60%, 80%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: scale3d(.3, .3, .3);
-ms-transform: scale3d(.3, .3, .3);
transform: scale3d(.3, .3, .3);
}
20% {
-webkit-transform: scale3d(1.1, 1.1, 1.1);
-ms-transform: scale3d(1.1, 1.1, 1.1);
transform: scale3d(1.1, 1.1, 1.1);
}
40% {
-webkit-transform: scale3d(.9, .9, .9);
-ms-transform: scale3d(.9, .9, .9);
transform: scale3d(.9, .9, .9);
}
60% {
opacity: 1;
-webkit-transform: scale3d(1.03, 1.03, 1.03);
-ms-transform: scale3d(1.03, 1.03, 1.03);
transform: scale3d(1.03, 1.03, 1.03);
}
80% {
-webkit-transform: scale3d(.97, .97, .97);
-ms-transform: scale3d(.97, .97, .97);
transform: scale3d(.97, .97, .97);
}
100% {
opacity: 1;
-webkit-transform: scale3d(1, 1, 1);
-ms-transform: scale3d(1, 1, 1);
transform: scale3d(1, 1, 1);
}
}
.bounceIn {
-webkit-animation-name: bounceIn;
animation-name: bounceIn;
-webkit-animation-duration: .75s;
animation-duration: .75s;
}
@-webkit-keyframes bounceInDown {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(0, -3000px, 0);
transform: translate3d(0, -3000px, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(0, 25px, 0);
transform: translate3d(0, 25px, 0);
}
75% {
-webkit-transform: translate3d(0, -10px, 0);
transform: translate3d(0, -10px, 0);
}
90% {
-webkit-transform: translate3d(0, 5px, 0);
transform: translate3d(0, 5px, 0);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes bounceInDown {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(0, -3000px, 0);
-ms-transform: translate3d(0, -3000px, 0);
transform: translate3d(0, -3000px, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(0, 25px, 0);
-ms-transform: translate3d(0, 25px, 0);
transform: translate3d(0, 25px, 0);
}
75% {
-webkit-transform: translate3d(0, -10px, 0);
-ms-transform: translate3d(0, -10px, 0);
transform: translate3d(0, -10px, 0);
}
90% {
-webkit-transform: translate3d(0, 5px, 0);
-ms-transform: translate3d(0, 5px, 0);
transform: translate3d(0, 5px, 0);
}
100% {
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.bounceInDown {
-webkit-animation-name: bounceInDown;
animation-name: bounceInDown;
}
@-webkit-keyframes bounceInLeft {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(-3000px, 0, 0);
transform: translate3d(-3000px, 0, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(25px, 0, 0);
transform: translate3d(25px, 0, 0);
}
75% {
-webkit-transform: translate3d(-10px, 0, 0);
transform: translate3d(-10px, 0, 0);
}
90% {
-webkit-transform: translate3d(5px, 0, 0);
transform: translate3d(5px, 0, 0);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes bounceInLeft {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(-3000px, 0, 0);
-ms-transform: translate3d(-3000px, 0, 0);
transform: translate3d(-3000px, 0, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(25px, 0, 0);
-ms-transform: translate3d(25px, 0, 0);
transform: translate3d(25px, 0, 0);
}
75% {
-webkit-transform: translate3d(-10px, 0, 0);
-ms-transform: translate3d(-10px, 0, 0);
transform: translate3d(-10px, 0, 0);
}
90% {
-webkit-transform: translate3d(5px, 0, 0);
-ms-transform: translate3d(5px, 0, 0);
transform: translate3d(5px, 0, 0);
}
100% {
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.bounceInLeft {
-webkit-animation-name: bounceInLeft;
animation-name: bounceInLeft;
}
@-webkit-keyframes bounceInRight {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(3000px, 0, 0);
transform: translate3d(3000px, 0, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(-25px, 0, 0);
transform: translate3d(-25px, 0, 0);
}
75% {
-webkit-transform: translate3d(10px, 0, 0);
transform: translate3d(10px, 0, 0);
}
90% {
-webkit-transform: translate3d(-5px, 0, 0);
transform: translate3d(-5px, 0, 0);
}
100% {
-webkit-transform: none;
transform: none;
}
}
@keyframes bounceInRight {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(3000px, 0, 0);
-ms-transform: translate3d(3000px, 0, 0);
transform: translate3d(3000px, 0, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(-25px, 0, 0);
-ms-transform: translate3d(-25px, 0, 0);
transform: translate3d(-25px, 0, 0);
}
75% {
-webkit-transform: translate3d(10px, 0, 0);
-ms-transform: translate3d(10px, 0, 0);
transform: translate3d(10px, 0, 0);
}
90% {
-webkit-transform: translate3d(-5px, 0, 0);
-ms-transform: translate3d(-5px, 0, 0);
transform: translate3d(-5px, 0, 0);
}
100% {
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.bounceInRight {
-webkit-animation-name: bounceInRight;
animation-name: bounceInRight;
}
@-webkit-keyframes bounceInUp {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(0, 3000px, 0);
transform: translate3d(0, 3000px, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(0, -20px, 0);
transform: translate3d(0, -20px, 0);
}
75% {
-webkit-transform: translate3d(0, 10px, 0);
transform: translate3d(0, 10px, 0);
}
90% {
-webkit-transform: translate3d(0, -5px, 0);
transform: translate3d(0, -5px, 0);
}
100% {
-webkit-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
@keyframes bounceInUp {
0%, 60%, 75%, 90%, 100% {
-webkit-transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
transition-timing-function: cubic-bezier(0.215, 0.610, 0.355, 1.000);
}
0% {
opacity: 0;
-webkit-transform: translate3d(0, 3000px, 0);
-ms-transform: translate3d(0, 3000px, 0);
transform: translate3d(0, 3000px, 0);
}
60% {
opacity: 1;
-webkit-transform: translate3d(0, -20px, 0);
-ms-transform: translate3d(0, -20px, 0);
transform: translate3d(0, -20px, 0);
}
75% {
-webkit-transform: translate3d(0, 10px, 0);
-ms-transform: translate3d(0, 10px, 0);
transform: translate3d(0, 10px, 0);
}
90% {
-webkit-transform: translate3d(0, -5px, 0);
-ms-transform: translate3d(0, -5px, 0);
transform: translate3d(0, -5px, 0);
}
100% {
-webkit-transform: translate3d(0, 0, 0);
-ms-transform: translate3d(0, 0, 0);
transform: translate3d(0, 0, 0);
}
}
.bounceInUp {
-webkit-animation-name: bounceInUp;
animation-name: bounceInUp;
}
@-webkit-keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
.fadeIn {
-webkit-animation-name: fadeIn;
animation-name: fadeIn;
}
@-webkit-keyframes fadeInDown {
0% {
opacity: 0;
-webkit-transform: translate3d(0, -100%, 0);
transform: translate3d(0, -100%, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInDown {
0% {
opacity: 0;
-webkit-transform: translate3d(0, -100%, 0);
-ms-transform: translate3d(0, -100%, 0);
transform: translate3d(0, -100%, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInDown {
-webkit-animation-name: fadeInDown;
animation-name: fadeInDown;
}
@-webkit-keyframes fadeInDownBig {
0% {
opacity: 0;
-webkit-transform: translate3d(0, -2000px, 0);
transform: translate3d(0, -2000px, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInDownBig {
0% {
opacity: 0;
-webkit-transform: translate3d(0, -2000px, 0);
-ms-transform: translate3d(0, -2000px, 0);
transform: translate3d(0, -2000px, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInDownBig {
-webkit-animation-name: fadeInDownBig;
animation-name: fadeInDownBig;
}
@-webkit-keyframes fadeInLeft {
0% {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInLeft {
0% {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0);
-ms-transform: translate3d(-100%, 0, 0);
transform: translate3d(-100%, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInLeft {
-webkit-animation-name: fadeInLeft;
animation-name: fadeInLeft;
}
@-webkit-keyframes fadeInLeftBig {
0% {
opacity: 0;
-webkit-transform: translate3d(-2000px, 0, 0);
transform: translate3d(-2000px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInLeftBig {
0% {
opacity: 0;
-webkit-transform: translate3d(-2000px, 0, 0);
-ms-transform: translate3d(-2000px, 0, 0);
transform: translate3d(-2000px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInLeftBig {
-webkit-animation-name: fadeInLeftBig;
animation-name: fadeInLeftBig;
}
@-webkit-keyframes fadeInRight {
0% {
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInRight {
0% {
opacity: 0;
-webkit-transform: translate3d(100%, 0, 0);
-ms-transform: translate3d(100%, 0, 0);
transform: translate3d(100%, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInRight {
-webkit-animation-name: fadeInRight;
animation-name: fadeInRight;
}
@-webkit-keyframes fadeInRightBig {
0% {
opacity: 0;
-webkit-transform: translate3d(2000px, 0, 0);
transform: translate3d(2000px, 0, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInRightBig {
0% {
opacity: 0;
-webkit-transform: translate3d(2000px, 0, 0);
-ms-transform: translate3d(2000px, 0, 0);
transform: translate3d(2000px, 0, 0);
}
100% {
opacity: 0;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInRightBig {
-webkit-animation-name: fadeInRightBig;
animation-name: fadeInRightBig;
}
@-webkit-keyframes fadeInUp {
0% {
opacity: 0;
-webkit-transform: translate3d(0, 100%, 0);
transform: translate3d(0, 100%, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInUp {
0% {
opacity: 0;
-webkit-transform: translate3d(0, 100%, 0);
-ms-transform: translate3d(0, 100%, 0);
transform: translate3d(0, 100%, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInUp {
-webkit-animation-name: fadeInUp;
animation-name: fadeInUp;
}
@-webkit-keyframes fadeInUpBig {
0% {
opacity: 0;
-webkit-transform: translate3d(0, 2000px, 0);
transform: translate3d(0, 2000px, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes fadeInUpBig {
0% {
opacity: 0;
-webkit-transform: translate3d(0, 2000px, 0);
-ms-transform: translate3d(0, 2000px, 0);
transform: translate3d(0, 2000px, 0);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.fadeInUpBig {
-webkit-animation-name: fadeInUpBig;
animation-name: fadeInUpBig;
}
@-webkit-keyframes flip {
0% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, -360deg);
transform: perspective(400px) rotate3d(0, 1, 0, -360deg);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
40% {
-webkit-transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -190deg);
transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -190deg);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
50% {
-webkit-transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -170deg);
transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -170deg);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
80% {
-webkit-transform: perspective(400px) scale3d(.95, .95, .95);
transform: perspective(400px) scale3d(.95, .95, .95);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
100% {
-webkit-transform: perspective(400px);
transform: perspective(400px);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
}
@keyframes flip {
0% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, -360deg);
-ms-transform: perspective(400px) rotate3d(0, 1, 0, -360deg);
transform: perspective(400px) rotate3d(0, 1, 0, -360deg);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
40% {
-webkit-transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -190deg);
-ms-transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -190deg);
transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -190deg);
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
50% {
-webkit-transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -170deg);
-ms-transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -170deg);
transform: perspective(400px) translate3d(0, 0, 150px) rotate3d(0, 1, 0, -170deg);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
80% {
-webkit-transform: perspective(400px) scale3d(.95, .95, .95);
-ms-transform: perspective(400px) scale3d(.95, .95, .95);
transform: perspective(400px) scale3d(.95, .95, .95);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
100% {
-webkit-transform: perspective(400px);
-ms-transform: perspective(400px);
transform: perspective(400px);
-webkit-animation-timing-function: ease-in;
animation-timing-function: ease-in;
}
}
.animated.flip {
-webkit-backface-visibility: visible;
-ms-backface-visibility: visible;
backface-visibility: visible;
-webkit-animation-name: flip;
animation-name: flip;
}
@-webkit-keyframes flipInX {
0% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
opacity: 0;
}
40% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
}
60% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
opacity: 1;
}
80% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
}
100% {
-webkit-transform: perspective(400px);
transform: perspective(400px);
}
}
@keyframes flipInX {
0% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
-ms-transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
transform: perspective(400px) rotate3d(1, 0, 0, 90deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
opacity: 0;
}
40% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
-ms-transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
transform: perspective(400px) rotate3d(1, 0, 0, -20deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
}
60% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
-ms-transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
transform: perspective(400px) rotate3d(1, 0, 0, 10deg);
opacity: 1;
}
80% {
-webkit-transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
-ms-transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
transform: perspective(400px) rotate3d(1, 0, 0, -5deg);
}
100% {
-webkit-transform: perspective(400px);
-ms-transform: perspective(400px);
transform: perspective(400px);
}
}
.flipInX {
-webkit-backface-visibility: visible !important;
-ms-backface-visibility: visible !important;
backface-visibility: visible !important;
-webkit-animation-name: flipInX;
animation-name: flipInX;
}
@-webkit-keyframes flipInY {
0% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
opacity: 0;
}
40% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, -20deg);
transform: perspective(400px) rotate3d(0, 1, 0, -20deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
}
60% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, 10deg);
transform: perspective(400px) rotate3d(0, 1, 0, 10deg);
opacity: 1;
}
80% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, -5deg);
transform: perspective(400px) rotate3d(0, 1, 0, -5deg);
}
100% {
-webkit-transform: perspective(400px);
transform: perspective(400px);
}
}
@keyframes flipInY {
0% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
-ms-transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
transform: perspective(400px) rotate3d(0, 1, 0, 90deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
opacity: 0;
}
40% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, -20deg);
-ms-transform: perspective(400px) rotate3d(0, 1, 0, -20deg);
transform: perspective(400px) rotate3d(0, 1, 0, -20deg);
-webkit-transition-timing-function: ease-in;
transition-timing-function: ease-in;
}
60% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, 10deg);
-ms-transform: perspective(400px) rotate3d(0, 1, 0, 10deg);
transform: perspective(400px) rotate3d(0, 1, 0, 10deg);
opacity: 1;
}
80% {
-webkit-transform: perspective(400px) rotate3d(0, 1, 0, -5deg);
-ms-transform: perspective(400px) rotate3d(0, 1, 0, -5deg);
transform: perspective(400px) rotate3d(0, 1, 0, -5deg);
}
100% {
-webkit-transform: perspective(400px);
-ms-transform: perspective(400px);
transform: perspective(400px);
}
}
.flipInY {
-webkit-backface-visibility: visible !important;
-ms-backface-visibility: visible !important;
backface-visibility: visible !important;
-webkit-animation-name: flipInY;
animation-name: flipInY;
}
@-webkit-keyframes lightSpeedIn {
0% {
-webkit-transform: translate3d(100%, 0, 0) skewX(-30deg);
transform: translate3d(100%, 0, 0) skewX(-30deg);
opacity: 0;
}
60% {
-webkit-transform: skewX(20deg);
transform: skewX(20deg);
opacity: 1;
}
80% {
-webkit-transform: skewX(-5deg);
transform: skewX(-5deg);
opacity: 1;
}
100% {
-webkit-transform: none;
transform: none;
opacity: 1;
}
}
@keyframes lightSpeedIn {
0% {
-webkit-transform: translate3d(100%, 0, 0) skewX(-30deg);
-ms-transform: translate3d(100%, 0, 0) skewX(-30deg);
transform: translate3d(100%, 0, 0) skewX(-30deg);
opacity: 0;
}
60% {
-webkit-transform: skewX(20deg);
-ms-transform: skewX(20deg);
transform: skewX(20deg);
opacity: 1;
}
80% {
-webkit-transform: skewX(-5deg);
-ms-transform: skewX(-5deg);
transform: skewX(-5deg);
opacity: 1;
}
100% {
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 1;
}
}
.lightSpeedIn {
-webkit-animation-name: lightSpeedIn;
animation-name: lightSpeedIn;
-webkit-animation-timing-function: ease-out;
animation-timing-function: ease-out;
}
@-webkit-keyframes rotateIn {
0% {
-webkit-transform-origin: center;
transform-origin: center;
-webkit-transform: rotate3d(0, 0, 1, -200deg);
transform: rotate3d(0, 0, 1, -200deg);
opacity: 0;
}
100% {
-webkit-transform-origin: center;
transform-origin: center;
-webkit-transform: none;
transform: none;
opacity: 1;
}
}
@keyframes rotateIn {
0% {
-webkit-transform-origin: center;
-ms-transform-origin: center;
transform-origin: center;
-webkit-transform: rotate3d(0, 0, 1, -200deg);
-ms-transform: rotate3d(0, 0, 1, -200deg);
transform: rotate3d(0, 0, 1, -200deg);
opacity: 0;
}
100% {
-webkit-transform-origin: center;
-ms-transform-origin: center;
transform-origin: center;
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 1;
}
}
.rotateIn {
-webkit-animation-name: rotateIn;
animation-name: rotateIn;
}
@-webkit-keyframes rotateInDownLeft {
0% {
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotate3d(0, 0, 1, -45deg);
transform: rotate3d(0, 0, 1, -45deg);
opacity: 0;
}
100% {
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: none;
transform: none;
opacity: 1;
}
}
@keyframes rotateInDownLeft {
0% {
-webkit-transform-origin: left bottom;
-ms-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotate3d(0, 0, 1, -45deg);
-ms-transform: rotate3d(0, 0, 1, -45deg);
transform: rotate3d(0, 0, 1, -45deg);
opacity: 0;
}
100% {
-webkit-transform-origin: left bottom;
-ms-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 1;
}
}
.rotateInDownLeft {
-webkit-animation-name: rotateInDownLeft;
animation-name: rotateInDownLeft;
}
@-webkit-keyframes rotateInDownRight {
0% {
-webkit-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: rotate3d(10, 50, 10, 95deg);
transform: rotate3d(10, 50, 10, 95deg);
opacity: 0;
}
100% {
-webkit-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: none;
transform: none;
opacity: 1;
}
}
@keyframes rotateInDownRight {
0% {
-webkit-transform-origin: right bottom;
-ms-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: rotate3d(0, 0, 1, 95deg);
-ms-transform: rotate3d(0, 0, 1, 95deg);
transform: rotate3d(0, 0, 1, 95deg);
opacity: 0;
}
100% {
-webkit-transform-origin: right bottom;
-ms-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 1;
}
}
.rotateInDownRight {
-webkit-animation-name: rotateInDownRight;
animation-name: rotateInDownRight;
}
@-webkit-keyframes rotateInUpLeft {
0% {
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotate3d(0, 0, 1, 45deg);
transform: rotate3d(0, 0, 1, 45deg);
opacity: 0;
}
100% {
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: none;
transform: none;
opacity: 1;
}
}
@keyframes rotateInUpLeft {
0% {
-webkit-transform-origin: left bottom;
-ms-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotate3d(0, 0, 1, 45deg);
-ms-transform: rotate3d(0, 0, 1, 45deg);
transform: rotate3d(0, 0, 1, 45deg);
opacity: 0;
}
100% {
-webkit-transform-origin: left bottom;
-ms-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 1;
}
}
.rotateInUpLeft {
-webkit-animation-name: rotateInUpLeft;
animation-name: rotateInUpLeft;
}
@-webkit-keyframes rotateInUpRight {
0% {
-webkit-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: rotate3d(0, 0, 1, -90deg);
transform: rotate3d(0, 0, 1, -90deg);
opacity: 0;
}
100% {
-webkit-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: none;
transform: none;
opacity: 1;
}
}
@keyframes rotateInUpRight {
0% {
-webkit-transform-origin: right bottom;
-ms-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: rotate3d(0, 0, 1, -90deg);
-ms-transform: rotate3d(0, 0, 1, -90deg);
transform: rotate3d(0, 0, 1, -90deg);
opacity: 0;
}
100% {
-webkit-transform-origin: right bottom;
-ms-transform-origin: right bottom;
transform-origin: right bottom;
-webkit-transform: none;
-ms-transform: none;
transform: none;
opacity: 1;
}
}
.rotateInUpRight {
-webkit-animation-name: rotateInUpRight;
animation-name: rotateInUpRight;
}
@-webkit-keyframes hinge {
0% {
-webkit-transform-origin: top left;
transform-origin: top left;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
}
20%, 60% {
-webkit-transform: rotate3d(0, 0, 1, 80deg);
transform: rotate3d(0, 0, 1, 80deg);
-webkit-transform-origin: top left;
transform-origin: top left;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
}
40%, 80% {
-webkit-transform: rotate3d(0, 0, 1, 60deg);
transform: rotate3d(0, 0, 1, 60deg);
-webkit-transform-origin: top left;
transform-origin: top left;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
opacity: 1;
}
100% {
-webkit-transform: translate3d(0, 700px, 0);
transform: translate3d(0, 700px, 0);
opacity: 0;
}
}
@keyframes hinge {
0% {
-webkit-transform-origin: top left;
-ms-transform-origin: top left;
transform-origin: top left;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
}
20%, 60% {
-webkit-transform: rotate3d(0, 0, 1, 80deg);
-ms-transform: rotate3d(0, 0, 1, 80deg);
transform: rotate3d(0, 0, 1, 80deg);
-webkit-transform-origin: top left;
-ms-transform-origin: top left;
transform-origin: top left;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
}
40%, 80% {
-webkit-transform: rotate3d(0, 0, 1, 60deg);
-ms-transform: rotate3d(0, 0, 1, 60deg);
transform: rotate3d(0, 0, 1, 60deg);
-webkit-transform-origin: top left;
-ms-transform-origin: top left;
transform-origin: top left;
-webkit-animation-timing-function: ease-in-out;
animation-timing-function: ease-in-out;
opacity: 1;
}
100% {
-webkit-transform: translate3d(0, 700px, 0);
-ms-transform: translate3d(0, 700px, 0);
transform: translate3d(0, 700px, 0);
opacity: 0;
}
}
.hinge {
-webkit-animation-name: hinge;
animation-name: hinge;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes rollIn {
0% {
opacity: 0;
-webkit-transform: translate3d(-50%, 0, 0) rotate3d(10, 10, 10, -200deg);
transform: translate3d(-50%, 0, 0) rotate3d(10, 10, 10, -200deg);
}
100% {
opacity: 1;
-webkit-transform: none;
transform: none;
}
}
@keyframes rollIn {
0% {
opacity: 0;
-webkit-transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg);
-ms-transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg);
transform: translate3d(-100%, 0, 0) rotate3d(0, 0, 1, -120deg);
}
100% {
opacity: 1;
-webkit-transform: none;
-ms-transform: none;
transform: none;
}
}
.rollIn {
-webkit-animation-name: rollIn;
animation-name: rollIn;
}
/* originally authored by Nick Pettit - https://github.com/nickpettit/glide */
@-webkit-keyframes zoomIn {
0% {
opacity: 0;
-webkit-transform: scale3d(.3, .3, .3);
transform: scale3d(.3, .3, .3);
}
50% {
opacity: 1;
}
}
@keyframes zoomIn {
0% {
opacity: 0;
-webkit-transform: scale3d(.3, .3, .3);
-ms-transform: scale3d(.3, .3, .3);
transform: scale3d(.3, .3, .3);
}
50% {
opacity: 1;
}
}
.zoomIn {
-webkit-animation-name: zoomIn;
animation-name: zoomIn;
}
@-webkit-keyframes zoomInDown {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(0, -1000px, 0);
transform: scale3d(.1, .1, .1) translate3d(0, -1000px, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(0, 60px, 0);
transform: scale3d(.475, .475, .475) translate3d(0, 60px, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
@keyframes zoomInDown {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(0, -1000px, 0);
-ms-transform: scale3d(.1, .1, .1) translate3d(0, -1000px, 0);
transform: scale3d(.1, .1, .1) translate3d(0, -1000px, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(0, 60px, 0);
-ms-transform: scale3d(.475, .475, .475) translate3d(0, 60px, 0);
transform: scale3d(.475, .475, .475) translate3d(0, 60px, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
.zoomInDown {
-webkit-animation-name: zoomInDown;
animation-name: zoomInDown;
}
@-webkit-keyframes zoomInLeft {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(-1000px, 0, 0);
transform: scale3d(.1, .1, .1) translate3d(-1000px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(10px, 0, 0);
transform: scale3d(.475, .475, .475) translate3d(10px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
@keyframes zoomInLeft {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(-1000px, 0, 0);
-ms-transform: scale3d(.1, .1, .1) translate3d(-1000px, 0, 0);
transform: scale3d(.1, .1, .1) translate3d(-1000px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(10px, 0, 0);
-ms-transform: scale3d(.475, .475, .475) translate3d(10px, 0, 0);
transform: scale3d(.475, .475, .475) translate3d(10px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
.zoomInLeft {
-webkit-animation-name: zoomInLeft;
animation-name: zoomInLeft;
}
@-webkit-keyframes zoomInRight {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(1000px, 0, 0);
transform: scale3d(.1, .1, .1) translate3d(1000px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(-10px, 0, 0);
transform: scale3d(.475, .475, .475) translate3d(-10px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
@keyframes zoomInRight {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(1000px, 0, 0);
-ms-transform: scale3d(.1, .1, .1) translate3d(1000px, 0, 0);
transform: scale3d(.1, .1, .1) translate3d(1000px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(-10px, 0, 0);
-ms-transform: scale3d(.475, .475, .475) translate3d(-10px, 0, 0);
transform: scale3d(.475, .475, .475) translate3d(-10px, 0, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
.zoomInRight {
-webkit-animation-name: zoomInRight;
animation-name: zoomInRight;
}
@-webkit-keyframes zoomInUp {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(0, 1000px, 0);
transform: scale3d(.1, .1, .1) translate3d(0, 1000px, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(0, -60px, 0);
transform: scale3d(.475, .475, .475) translate3d(0, -60px, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
@keyframes zoomInUp {
0% {
opacity: 0;
-webkit-transform: scale3d(.1, .1, .1) translate3d(0, 1000px, 0);
-ms-transform: scale3d(.1, .1, .1) translate3d(0, 1000px, 0);
transform: scale3d(.1, .1, .1) translate3d(0, 1000px, 0);
-webkit-animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
animation-timing-function: cubic-bezier(0.550, 0.055, 0.675, 0.190);
}
60% {
opacity: 1;
-webkit-transform: scale3d(.475, .475, .475) translate3d(0, -60px, 0);
-ms-transform: scale3d(.475, .475, .475) translate3d(0, -60px, 0);
transform: scale3d(.475, .475, .475) translate3d(0, -60px, 0);
-webkit-animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
animation-timing-function: cubic-bezier(0.175, 0.885, 0.320, 1);
}
}
.zoomInUp {
-webkit-animation-name: zoomInUp;
animation-name: zoomInUp;
}
|
luchego/wordpress-prueba
|
wp-content/plugins/like-box/includes/style/effects.css
|
CSS
|
gpl-2.0
| 49,727
|
#include<osg/Camera>
#include <osgDB/ReadFile>
#include <osg/Geometry>
#include <osg/Geode>
#include <osg/Texture2D>
#include <osg/TextureCubeMap>
#include "OsgDebugHUD.h"
SDDebugHUD::SDDebugHUD(){
osg::Geometry* geom;
osg::ref_ptr<osg::Vec3Array> texcoords;
osg::ref_ptr<osg::Geode> quad = new osg::Geode;
float zoom = 0.5f;
//neg Z
geom = osg::createTexturedQuadGeometry(
osg::Vec3(-1.0f,-1.0f,0.0f), osg::Vec3(0.5f,0.0f,0.0f), osg::Vec3(0.0f,0.7f,0.0f));
texcoords = new osg::Vec3Array;
texcoords->push_back( osg::Vec3(1.0f, -1.0f,-zoom) );
texcoords->push_back( osg::Vec3(1.0f, 1.0f,-zoom) );
texcoords->push_back( osg::Vec3(-1.0f, 1.0f,-zoom) );
texcoords->push_back( osg::Vec3(-1.0f,-1.0f,-zoom) );
geom->setTexCoordArray(0,texcoords);
quad->addDrawable( geom );
//negX
geom = osg::createTexturedQuadGeometry(
osg::Vec3(-0.3f,-1.0f,0.0f), osg::Vec3(0.5f,0.0f,0.0f), osg::Vec3(0.0f,0.7f,0.0f));
texcoords = new osg::Vec3Array;
texcoords->push_back( osg::Vec3(-1.0f,-1.0f,zoom) );
texcoords->push_back( osg::Vec3(-1.0f, 1.0f,zoom) );
texcoords->push_back( osg::Vec3(1.0f, 1.0f,zoom) );
texcoords->push_back( osg::Vec3(1.0f, -1.0f,zoom) );
geom->setTexCoordArray(0,texcoords);
quad->addDrawable( geom );
HUD_camera = new osg::Camera;
HUD_camera->setClearMask( GL_DEPTH_BUFFER_BIT );
HUD_camera->setRenderOrder( osg::Camera::POST_RENDER );
HUD_camera->setProjectionMatrix(osg::Matrix::ortho2D(-1, 1, -1, 1));
HUD_camera->setReferenceFrame( osg::Camera::ABSOLUTE_RF );
HUD_camera->addChild( quad );
HUD_camera->setNodeMask(0);
}
void SDDebugHUD::setTexture(osg::ref_ptr<osg::Texture> map){
osg::StateSet* stateset = HUD_camera->getOrCreateStateSet();
stateset->setTextureAttributeAndModes( 0,map);
}
void SDDebugHUD::toggleHUD(){
HUD_camera->setNodeMask(1-HUD_camera->getNodeMask());
}
SDDebugHUD::~SDDebugHUD(){
}
|
kumar003vinod/SpeedDreams
|
src/modules/graphic/osggraph/OsgView/OsgDebugHUD.cpp
|
C++
|
gpl-2.0
| 1,967
|
<?php
/**
* Class for managing email-based authentication.
*
* PHP version 7
*
* Copyright (C) The National Library of Finland 2019.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*
* @category VuFind
* @package Authentication
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:authentication_handlers Wiki
*/
namespace VuFind\Auth;
use Laminas\Http\PhpEnvironment\RemoteAddress;
use Laminas\Http\PhpEnvironment\Request;
use VuFind\DB\Table\AuthHash as AuthHashTable;
use VuFind\Exception\Auth as AuthException;
/**
* Class for managing email-based authentication.
*
* This class provides functionality for authentication based on a known-valid email
* address.
*
* @category VuFind
* @package Authentication
* @author Ere Maijala <ere.maijala@helsinki.fi>
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License
* @link https://vufind.org/wiki/development:plugins:authentication_handlers Wiki
*/
class EmailAuthenticator implements \VuFind\I18n\Translator\TranslatorAwareInterface
{
use \VuFind\I18n\Translator\TranslatorAwareTrait;
/**
* Session Manager
*
* @var \Laminas\Session\SessionManager
*/
protected $sessionManager = null;
/**
* CSRF Validator
*
* @var \VuFind\Validator\Csrf $csrf CSRF validator
*/
protected $csrf = null;
/**
* Mailer
*
* @var \VuFind\Mailer\Mailer
*/
protected $mailer = null;
/**
* View Renderer
*
* @var \Laminas\View\Renderer\RendererInterface
*/
protected $viewRenderer = null;
/**
* Remote address
*
* @var RemoteAddress
*/
protected $remoteAddress;
/**
* Configuration
*
* @var \Laminas\Config\Config
*/
protected $config;
/**
* How long a login request is considered to be valid (seconds)
*
* @var int
*/
protected $loginRequestValidTime = 600;
/**
* Database table for authentication hashes
*
* @var AuthHashTable
*/
protected $authHashTable;
/**
* Constructor
*
* @param \Laminas\Session\SessionManager $session Session Manager
* @param \VuFind\Validator\Csrf $csrf CSRF Validator
* @param \VuFind\Mailer\Mailer $mailer Mailer
* @param \Laminas\View\Renderer\RendererInterface $viewRenderer View Renderer
* @param RemoteAddress $remoteAddr Remote address
* @param \Laminas\Config\Config $config Configuration
* @param AuthHashTable $authHash AuthHash Table
*/
public function __construct(\Laminas\Session\SessionManager $session,
\VuFind\Validator\Csrf $csrf, \VuFind\Mailer\Mailer $mailer,
\Laminas\View\Renderer\RendererInterface $viewRenderer,
RemoteAddress $remoteAddr,
\Laminas\Config\Config $config, AuthHashTable $authHash
) {
$this->sessionManager = $session;
$this->csrf = $csrf;
$this->mailer = $mailer;
$this->viewRenderer = $viewRenderer;
$this->remoteAddress = $remoteAddr;
$this->config = $config;
$this->authHashTable = $authHash;
}
/**
* Send an email authentication link to the specified email address.
*
* Stores the required information in the session.
*
* @param string $email Email address to send the link to
* @param array $data Information from the authentication request (such as
* user details)
* @param array $urlParams Default parameters for the generated URL
* @param string $linkRoute The route to use as the base url for the login link
* @param string $subject Email subject
* @param string $template Email message template
*
* @return void
*/
public function sendAuthenticationLink($email, $data,
$urlParams, $linkRoute = 'myresearch-home',
$subject = 'email_login_subject',
$template = 'Email/login-link.phtml'
) {
// Make sure we've waited long enough
$recoveryInterval = isset($this->config->Authentication->recover_interval)
? $this->config->Authentication->recover_interval
: 60;
$sessionId = $this->sessionManager->getId();
if (($row = $this->authHashTable->getLatestBySessionId($sessionId))
&& time() - strtotime($row['created']) < $recoveryInterval
) {
throw new AuthException('authentication_error_in_progress');
}
$this->csrf->trimTokenList(5);
$linkData = [
'timestamp' => time(),
'data' => $data,
'email' => $email,
'ip' => $this->remoteAddress->getIpAddress()
];
$hash = $this->csrf->getHash(true);
$row = $this->authHashTable
->getByHashAndType($hash, AuthHashTable::TYPE_EMAIL);
$row['session_id'] = $sessionId;
$row['data'] = json_encode($linkData);
$row->save();
$serverHelper = $this->viewRenderer->plugin('serverurl');
$urlHelper = $this->viewRenderer->plugin('url');
$urlParams['hash'] = $hash;
$viewParams = $linkData;
$viewParams['url'] = $serverHelper(
$urlHelper($linkRoute, [], ['query' => $urlParams])
);
$viewParams['title'] = $this->config->Site->title;
$message = $this->viewRenderer->render($template, $viewParams);
$from = !empty($this->config->Mail->user_email_in_from)
? $email
: ($this->config->Mail->default_from ?? $this->config->Site->email);
$subject = $this->translator->translate($subject);
$subject = str_replace('%%title%%', $viewParams['title'], $subject);
$this->mailer->send($email, $from, $subject, $message);
}
/**
* Authenticate using a hash
*
* @param string $hash Hash
*
* @return array
* @throws AuthException
*/
public function authenticate($hash)
{
$row = $this->authHashTable
->getByHashAndType($hash, AuthHashTable::TYPE_EMAIL, false);
if (!$row) {
// Assume the hash has already been used or has expired
throw new AuthException('authentication_error_expired');
}
$linkData = json_decode($row['data'], true);
// Require same session id or IP address:
$sessionId = $this->sessionManager->getId();
if ($row['session_id'] !== $sessionId
&& $linkData['ip'] !== $this->remoteAddress->getIpAddress()
) {
throw new AuthException('authentication_error_session_ip_mismatch');
}
// Only delete the token now that we know the requester is correct. Otherwise
// it may end up deleted due to e.g. safe link check by the email server.
$row->delete();
if (time() - strtotime($row['created']) > $this->loginRequestValidTime) {
throw new AuthException('authentication_error_expired');
}
return $linkData['data'];
}
/**
* Check if the given request is a valid login request
*
* @param Request $request Request object.
*
* @return bool
*/
public function isValidLoginRequest(Request $request)
{
$hash = $request->getPost()->get(
'hash',
$request->getQuery()->get('hash', '')
);
if ($hash) {
$row = $this->authHashTable
->getByHashAndType($hash, AuthHashTable::TYPE_EMAIL, false);
return !empty($row);
}
return false;
}
}
|
swissbib/vufind
|
module/VuFind/src/VuFind/Auth/EmailAuthenticator.php
|
PHP
|
gpl-2.0
| 8,458
|
namespace Server.Items
{
public class ArmsOfArmstrong : LeatherArms
{
public override bool IsArtifact => true;
[Constructable]
public ArmsOfArmstrong()
{
LootType = LootType.Blessed;
Attributes.BonusStr = 3;
Attributes.RegenHits = 1;
}
public ArmsOfArmstrong(Serial serial)
: base(serial)
{
}
public override int LabelNumber => 1077675;// Arms of Armstrong
public override int BasePhysicalResistance => 6;
public override int BaseFireResistance => 6;
public override int BaseColdResistance => 5;
public override int BasePoisonResistance => 5;
public override int BaseEnergyResistance => 5;
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();
}
}
}
|
Argalep/ServUO
|
Scripts/Items/Artifacts/Equipment/Armor/ArmsOfArmstrong.cs
|
C#
|
gpl-2.0
| 1,109
|
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<!-- Copyright (C) 1988-2015 Free Software Foundation, Inc.
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU Free Documentation License, Version 1.3 or
any later version published by the Free Software Foundation; with the
Invariant Sections being "Funding Free Software", the Front-Cover
Texts being (a) (see below), and with the Back-Cover Texts being (b)
(see below). A copy of the license is included in the section entitled
"GNU Free Documentation License".
(a) The FSF's Front-Cover Text is:
A GNU Manual
(b) The FSF's Back-Cover Text is:
You have freedom to copy and modify this GNU Manual, like GNU
software. Copies published by the Free Software Foundation raise
funds for GNU development. -->
<!-- Created by GNU Texinfo 5.2, http://www.gnu.org/software/texinfo/ -->
<head>
<title>Using the GNU Compiler Collection (GCC): Gcov Intro</title>
<meta name="description" content="Using the GNU Compiler Collection (GCC): Gcov Intro">
<meta name="keywords" content="Using the GNU Compiler Collection (GCC): Gcov Intro">
<meta name="resource-type" content="document">
<meta name="distribution" content="global">
<meta name="Generator" content="makeinfo">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<link href="index.html#Top" rel="start" title="Top">
<link href="Option-Index.html#Option-Index" rel="index" title="Option Index">
<link href="index.html#SEC_Contents" rel="contents" title="Table of Contents">
<link href="Gcov.html#Gcov" rel="up" title="Gcov">
<link href="Invoking-Gcov.html#Invoking-Gcov" rel="next" title="Invoking Gcov">
<link href="Gcov.html#Gcov" rel="prev" title="Gcov">
<style type="text/css">
<!--
a.summary-letter {text-decoration: none}
blockquote.smallquotation {font-size: smaller}
div.display {margin-left: 3.2em}
div.example {margin-left: 3.2em}
div.indentedblock {margin-left: 3.2em}
div.lisp {margin-left: 3.2em}
div.smalldisplay {margin-left: 3.2em}
div.smallexample {margin-left: 3.2em}
div.smallindentedblock {margin-left: 3.2em; font-size: smaller}
div.smalllisp {margin-left: 3.2em}
kbd {font-style:oblique}
pre.display {font-family: inherit}
pre.format {font-family: inherit}
pre.menu-comment {font-family: serif}
pre.menu-preformatted {font-family: serif}
pre.smalldisplay {font-family: inherit; font-size: smaller}
pre.smallexample {font-size: smaller}
pre.smallformat {font-family: inherit; font-size: smaller}
pre.smalllisp {font-size: smaller}
span.nocodebreak {white-space:nowrap}
span.nolinebreak {white-space:nowrap}
span.roman {font-family:serif; font-weight:normal}
span.sansserif {font-family:sans-serif; font-weight:normal}
ul.no-bullet {list-style: none}
-->
</style>
</head>
<body lang="en" bgcolor="#FFFFFF" text="#000000" link="#0000FF" vlink="#800080" alink="#FF0000">
<a name="Gcov-Intro"></a>
<div class="header">
<p>
Next: <a href="Invoking-Gcov.html#Invoking-Gcov" accesskey="n" rel="next">Invoking Gcov</a>, Up: <a href="Gcov.html#Gcov" accesskey="u" rel="up">Gcov</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Option-Index.html#Option-Index" title="Index" rel="index">Index</a>]</p>
</div>
<hr>
<a name="Introduction-to-gcov"></a>
<h3 class="section">10.1 Introduction to <code>gcov</code></h3>
<p><code>gcov</code> is a test coverage program. Use it in concert with GCC
to analyze your programs to help create more efficient, faster running
code and to discover untested parts of your program. You can use
<code>gcov</code> as a profiling tool to help discover where your
optimization efforts will best affect your code. You can also use
<code>gcov</code> along with the other profiling tool, <code>gprof</code>, to
assess which parts of your code use the greatest amount of computing
time.
</p>
<p>Profiling tools help you analyze your code’s performance. Using a
profiler such as <code>gcov</code> or <code>gprof</code>, you can find out some
basic performance statistics, such as:
</p>
<ul>
<li> how often each line of code executes
</li><li> what lines of code are actually executed
</li><li> how much computing time each section of code uses
</li></ul>
<p>Once you know these things about how your code works when compiled, you
can look at each module to see which modules should be optimized.
<code>gcov</code> helps you determine where to work on optimization.
</p>
<p>Software developers also use coverage testing in concert with
testsuites, to make sure software is actually good enough for a release.
Testsuites can verify that a program works as expected; a coverage
program tests to see how much of the program is exercised by the
testsuite. Developers can then determine what kinds of test cases need
to be added to the testsuites to create both better testing and a better
final product.
</p>
<p>You should compile your code without optimization if you plan to use
<code>gcov</code> because the optimization, by combining some lines of code
into one function, may not give you as much information as you need to
look for ‘hot spots’ where the code is using a great deal of computer
time. Likewise, because <code>gcov</code> accumulates statistics by line (at
the lowest resolution), it works best with a programming style that
places only one statement on each line. If you use complicated macros
that expand to loops or to other control structures, the statistics are
less helpful—they only report on the line where the macro call
appears. If your complex macros behave like functions, you can replace
them with inline functions to solve this problem.
</p>
<p><code>gcov</code> creates a logfile called <samp><var>sourcefile</var>.gcov</samp> which
indicates how many times each line of a source file <samp><var>sourcefile</var>.c</samp>
has executed. You can use these logfiles along with <code>gprof</code> to aid
in fine-tuning the performance of your programs. <code>gprof</code> gives
timing information you can use along with the information you get from
<code>gcov</code>.
</p>
<p><code>gcov</code> works only on code compiled with GCC. It is not
compatible with any other profiling or test coverage mechanism.
</p>
<hr>
<div class="header">
<p>
Next: <a href="Invoking-Gcov.html#Invoking-Gcov" accesskey="n" rel="next">Invoking Gcov</a>, Up: <a href="Gcov.html#Gcov" accesskey="u" rel="up">Gcov</a> [<a href="index.html#SEC_Contents" title="Table of contents" rel="contents">Contents</a>][<a href="Option-Index.html#Option-Index" title="Index" rel="index">Index</a>]</p>
</div>
</body>
</html>
|
thanhphat11/android_kernel_xiaomi_msm8996
|
toolchains/share/doc/gcc/Gcov-Intro.html
|
HTML
|
gpl-2.0
| 6,698
|
#include "btfiles.h"
#ifdef WINDOWS
#include <io.h>
#include <memory.h>
#include <direct.h>
#else
#include <unistd.h>
#include <dirent.h>
#include <sys/param.h>
#endif
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>
#include <ctype.h> // isprint
#include "bencode.h"
#include "btcontent.h"
#include "bitfield.h"
#include "console.h"
#include "bttime.h"
#ifndef HAVE_SNPRINTF
#include "compat.h"
#endif
#define MAX_OPEN_FILES 20
btFiles::btFiles()
{
m_btfhead = (BTFILE*) 0;
m_nfiles = 0;
m_file = (BTFILE **)0;
m_total_files_length = 0;
m_total_opened = 0;
m_flag_automanage = 1;
m_directory = (char*)0;
}
btFiles::~btFiles()
{
_btf_destroy();
if( m_directory ) delete []m_directory;
}
BTFILE* btFiles::_new_bfnode()
{
BTFILE *pnew = new BTFILE;
#ifndef WINDOWS
if( !pnew ) return (BTFILE*) 0;
#endif
pnew->bf_flag_opened = 0;
pnew->bf_flag_readonly = 0;
pnew->bf_filename = (char*) 0;
pnew->bf_fp = (FILE*) 0;
pnew->bf_length = 0;
pnew->bf_buffer = (char *) 0;
pnew->bf_last_timestamp = (time_t) 0;
pnew->bf_next = (BTFILE*) 0;
return pnew;
}
void btFiles::CloseFile(size_t nfile)
{
if( nfile && nfile <= m_nfiles )
_btf_close(m_file[nfile-1]);
}
int btFiles::_btf_close_oldest()
{
BTFILE *pbf_n,*pbf_close;
pbf_close = (BTFILE *) 0;
for(pbf_n = m_btfhead; pbf_n; pbf_n = pbf_n->bf_next){
if(!pbf_n->bf_flag_opened) continue; // file not been opened.
if(!pbf_close || pbf_n->bf_last_timestamp < pbf_close->bf_last_timestamp)
pbf_close = pbf_n;
}
if(!pbf_close) return -1;
return _btf_close(pbf_close);
}
int btFiles::_btf_close(BTFILE *pbf)
{
if( !pbf->bf_flag_opened ) return 0;
if( fclose(pbf->bf_fp) == EOF )
CONSOLE.Warning(2, "warn, error closing file \"%s\": %s",
pbf->bf_filename, strerror(errno));
pbf->bf_flag_opened = 0;
pbf->bf_fp = (FILE *)0;
if( pbf->bf_buffer ){
delete []pbf->bf_buffer;
pbf->bf_buffer = (char *)0;
}
m_total_opened--;
return 0;
}
int btFiles::_btf_open(BTFILE *pbf, const int iotype)
{
char fn[MAXPATHLEN];
if( pbf->bf_flag_opened ){
if( pbf->bf_flag_readonly && iotype ) _btf_close(pbf);
else return 0; // already open in a usable mode
}
if(m_flag_automanage && (m_total_opened >= MAX_OPEN_FILES)){ // close a file
if( _btf_close_oldest() < 0 ) return -1;
}
if( m_directory ){
if( MAXPATHLEN <= snprintf(fn, MAXPATHLEN, "%s%c%s", m_directory, PATH_SP,
pbf->bf_filename) ){
errno = ENAMETOOLONG;
return -1;
}
}else{
strcpy(fn, pbf->bf_filename);
}
pbf->bf_last_timestamp = now + 1;
if( !(pbf->bf_fp = fopen(fn, iotype ? "r+b" : "rb")) ){
if( EMFILE == errno || ENFILE == errno ){
if( _btf_close_oldest() < 0 ||
!(pbf->bf_fp = fopen(fn, iotype ? "r+b" : "rb")) )
return -1; // caller prints error
}else return -1; // caller prints error
}
pbf->bf_buffer = new char[DEFAULT_SLICE_SIZE];
if(pbf->bf_buffer)
setvbuf(pbf->bf_fp, pbf->bf_buffer, _IOFBF, DEFAULT_SLICE_SIZE);
pbf->bf_flag_opened = 1;
pbf->bf_flag_readonly = iotype ? 0 : 1;
m_total_opened++;
return 0;
}
ssize_t btFiles::IO(char *buf, uint64_t off, size_t len, const int iotype)
{
uint64_t n = 0;
off_t pos,nio;
BTFILE *pbf = m_btfhead;
if( (off + (uint64_t)len) > m_total_files_length ){
CONSOLE.Warning(1, "error, data offset %llu length %lu out of range",
(unsigned long long)off, (unsigned long)len);
return -1;
}
for(; pbf; pbf = pbf->bf_next){
n += (uint64_t) pbf->bf_length;
if(n > off) break;
}
if( !pbf ){
CONSOLE.Warning(1, "error, failed to find file for offset %llu",
(unsigned long long)off);
return -1;
}
pos = off - (n - pbf->bf_length);
for(; len ;){
if( (!pbf->bf_flag_opened || (iotype && pbf->bf_flag_readonly)) &&
_btf_open(pbf, iotype) < 0 ){
CONSOLE.Warning(1, "error, failed to open file \"%s\": %s",
pbf->bf_filename, strerror(errno));
return -1;
}
pbf->bf_last_timestamp = now;
#ifdef HAVE_FSEEKO
if( fseeko(pbf->bf_fp,pos,SEEK_SET) < 0 ){
#else
if( fseek(pbf->bf_fp,(long) pos,SEEK_SET) < 0 ){
#endif
CONSOLE.Warning(1, "error, failed to seek to %llu on file \"%s\": %s",
(unsigned long long)pos, pbf->bf_filename, strerror(errno));
return -1;
}
// }
nio = (len < pbf->bf_length - pos) ? len : (pbf->bf_length - pos);
if(0 == iotype){
errno = 0;
if( 1 != fread(buf,nio,1,pbf->bf_fp) && ferror(pbf->bf_fp) ){
CONSOLE.Warning(1, "error, read failed at %llu on file \"%s\": %s",
(unsigned long long)pos, pbf->bf_filename, strerror(errno));
return -1;
}
}else{
errno = 0;
if( 1 != fwrite(buf,nio,1,pbf->bf_fp) ){
CONSOLE.Warning(1, "error, write failed at %llu on file \"%s\": %s",
(unsigned long long)pos, pbf->bf_filename, strerror(errno));
return -1;
}
if( fflush(pbf->bf_fp) == EOF ){
CONSOLE.Warning(1, "error, flush failed at %llu on file \"%s\": %s",
(unsigned long long)pos, pbf->bf_filename, strerror(errno));
return -1;
}
}
len -= nio;
buf += nio;
if( len ){
do{
pbf = pbf->bf_next;
if( !pbf ){
CONSOLE.Warning(1,
"error, data left over with no more files to write");
return -1;
}
}while( 0==pbf->bf_length );
pos = 0;
}
} // end for
return 0;
}
int btFiles::_btf_destroy()
{
BTFILE *pbf,*pbf_next;
for(pbf = m_btfhead; pbf;){
pbf_next = pbf->bf_next;
if( pbf->bf_fp && pbf->bf_flag_opened ) fclose( pbf->bf_fp );
if( pbf->bf_filename ) delete []pbf->bf_filename;
if( pbf->bf_buffer ) delete []pbf->bf_buffer;
delete pbf;
pbf = pbf_next;
}
m_btfhead = (BTFILE*) 0;
m_total_files_length = (uint64_t) 0;
m_total_opened = 0;
return 0;
}
int btFiles::_btf_ftruncate(int fd,int64_t length)
{
if( arg_allocate ){
char *c = new char[256*1024];
if( !c ){ errno = ENOMEM; return -1; }
memset(c, 0, 256*1024);
int r, wlen;
int64_t len = 0;
for( int i=0; len < length; i++ ){
if( len + 256*1024 > length ) wlen = (int)(length - len);
else wlen = 256*1024;
if( 0 == i % 100 ) CONSOLE.Interact_n(".");
if( (r = write(fd, c, wlen)) < 0 ) return r;
len += wlen;
}
delete []c;
return r;
}
#ifdef WINDOWS
char c = (char)0;
if( lseek(fd,length - 1, SEEK_SET) < 0 ) return -1;
return write(fd, &c, 1);
#else
// ftruncate() not allowed on [v]fat under linux
int retval = ftruncate(fd,length);
if( retval < 0 ) {
char c = (char)0;
if( lseek(fd,length - 1, SEEK_SET) < 0 ) return -1;
return write(fd, &c, 1);
}
else return retval;
#endif
}
int btFiles::_btf_recurses_directory(const char *cur_path, BTFILE* *plastnode)
{
char full_cur[MAXPATHLEN];
char fn[MAXPATHLEN];
struct stat sb;
struct dirent *dirp;
DIR *dp;
BTFILE *pbf;
if( !getcwd(full_cur,MAXPATHLEN) ) return -1;
if( cur_path ){
strcpy(fn, full_cur);
if( MAXPATHLEN <= snprintf(full_cur, MAXPATHLEN, "%s%c%s", fn, PATH_SP,
cur_path) ){
errno = ENAMETOOLONG;
return -1;
}
}
if( (DIR*) 0 == (dp = opendir(full_cur)) ){
CONSOLE.Warning(1, "error, open directory \"%s\" failed: %s",
cur_path, strerror(errno));
return -1;
}
while( (struct dirent*) 0 != (dirp = readdir(dp)) ){
if( 0 == strcmp(dirp->d_name, ".") ||
0 == strcmp(dirp->d_name, "..") ) continue;
if( cur_path ){
if(MAXPATHLEN < snprintf(fn, MAXPATHLEN, "%s%c%s", cur_path, PATH_SP,
dirp->d_name)){
CONSOLE.Warning(1, "error, pathname too long");
errno = ENAMETOOLONG;
return -1;
}
}else{
strcpy(fn, dirp->d_name);
}
if( stat(fn, &sb) < 0 ){
CONSOLE.Warning(1, "error, stat \"%s\" failed: %s",fn,strerror(errno));
return -1;
}
if( S_IFREG & sb.st_mode ){
pbf = _new_bfnode();
#ifndef WINDOWS
if( !pbf ){ errno = ENOMEM; return -1; }
#endif
pbf->bf_filename = new char[strlen(fn) + 1];
#ifndef WINDOWS
if( !pbf->bf_filename ){ closedir(dp); errno = ENOMEM; return -1; }
#endif
strcpy(pbf->bf_filename, fn);
pbf->bf_length = sb.st_size;
m_total_files_length += sb.st_size;
if( *plastnode ) (*plastnode)->bf_next = pbf; else m_btfhead = pbf;
*plastnode = pbf;
}else if( S_IFDIR & sb.st_mode ){
if(_btf_recurses_directory(fn, plastnode) < 0){closedir(dp); return -1;}
}else{
CONSOLE.Warning(1, "error, \"%s\" is not a directory or regular file.",
fn);
closedir(dp);
return -1;
}
} // end while
closedir(dp);
return 0;
}
int btFiles::_btf_creat_by_path(const char *pathname, int64_t file_length)
{
struct stat sb;
int fd;
char *p,*pnext,last = 0;
char sp[MAXPATHLEN];
strcpy(sp,pathname);
pnext = sp;
if(PATH_SP == *pnext) pnext++;
for(; !last; ){
for(p = pnext; *p && PATH_SP != *p; p++) ;
if( !*p ) last = 1;
if(last && PATH_SP == *p){ last = 0; break;}
*p = '\0';
if(stat(sp,&sb) < 0){
if( ENOENT == errno ){
if( !last ){
#ifdef WINDOWS
if(mkdir(sp) < 0) break;
#else
if(mkdir(sp,0755) < 0) break;
#endif
}else{
if((fd = creat(sp,0644)) < 0){ last = 0; break; }
if(file_length && _btf_ftruncate(fd, file_length) < 0){
close(fd); last = 0; break;
}
close(fd);
}
}else{last = 0; break;}
}
if( !last ){ *p = PATH_SP; pnext = p + 1; }
}
return last;
}
int btFiles::BuildFromFS(const char *pathname)
{
struct stat sb;
BTFILE *pbf = (BTFILE*) 0;
BTFILE *lastnode = (BTFILE*) 0;
if( stat(pathname, &sb) < 0 ){
CONSOLE.Warning(1, "error, stat file \"%s\" failed: %s",
pathname, strerror(errno));
return -1;
}
if( S_IFREG & sb.st_mode ){
pbf = _new_bfnode();
#ifndef WINDOWS
if( !pbf ) return -1;
#endif
pbf->bf_length = m_total_files_length = sb.st_size;
pbf->bf_filename = new char[strlen(pathname) + 1];
#ifndef WINDOWS
if( !pbf->bf_filename ) return -1;
#endif
strcpy(pbf->bf_filename, pathname);
m_btfhead = pbf;
}else if( S_IFDIR & sb.st_mode ){
char wd[MAXPATHLEN];
if( !getcwd(wd,MAXPATHLEN) ) return -1;
m_directory = new char[strlen(pathname) + 1];
#ifndef WINDOWS
if( !m_directory ) return -1;
#endif
strcpy(m_directory, pathname);
if(chdir(m_directory) < 0){
CONSOLE.Warning(1, "error, change work directory to \"%s\" failed: %s",
m_directory, strerror(errno));
return -1;
}
if(_btf_recurses_directory((const char*)0, &lastnode) < 0) return -1;
if( chdir(wd) < 0) return -1;
}else{
CONSOLE.Warning(1, "error, \"%s\" is not a directory or regular file.",
pathname);
return -1;
}
return 0;
}
int btFiles::BuildFromMI(const char *metabuf, const size_t metabuf_len, const char *saveas)
{
char path[MAXPATHLEN];
const char *s, *p;
size_t r,q,n;
int64_t t;
int f_warned = 0;
if( !decode_query(metabuf, metabuf_len, "info|name", &s, &q, (int64_t*)0,
QUERY_STR) || MAXPATHLEN <= q )
return -1;
memcpy(path, s, q);
path[q] = '\0';
r = decode_query(metabuf, metabuf_len, "info|files", (const char**)0, &q,
(int64_t*)0, QUERY_POS);
if( r ){
BTFILE *pbf_last = (BTFILE*) 0;
BTFILE *pbf = (BTFILE*) 0;
size_t dl;
if( decode_query(metabuf,metabuf_len,"info|length",
(const char**) 0,(size_t*) 0,(int64_t*) 0,QUERY_LONG) )
return -1;
if( saveas ){
m_directory = new char[strlen(saveas) + 1];
#ifndef WINDOWS
if(!m_directory) return -1;
#endif
strcpy(m_directory,saveas);
}else{
int f_conv;
char *tmpfn = new char[strlen(path)*2+5];
#ifndef WINDOWS
if( !tmpfn ) return -1;
#endif
if( f_conv = ConvertFilename(tmpfn, path, strlen(path)*2+5) ){
if( arg_flg_convert_filenames ){
m_directory = new char[strlen(tmpfn) + 1];
#ifndef WINDOWS
if( !m_directory ){
delete []tmpfn;
return -1;
}
#endif
strcpy(m_directory,tmpfn);
}else{
CONSOLE.Warning(3,
"Dir name contains non-printable characters; use -T to convert.");
f_warned = 1;
}
}
delete []tmpfn;
if( !f_conv || !arg_flg_convert_filenames ){
m_directory = new char[strlen(path) + 1];
#ifndef WINDOWS
if( !m_directory ) return -1;
#endif
strcpy(m_directory,path);
}
}
/* now r saved the pos of files list. q saved list length */
p = metabuf + r + 1;
q--;
for(; q && 'e' != *p; p += dl, q -= dl){
if(!(dl = decode_dict(p, q, (const char*) 0)) ) return -1;
if( !decode_query(p, dl, "length", (const char**) 0,
(size_t*) 0,&t,QUERY_LONG) ) return -1;
pbf = _new_bfnode();
#ifndef WINDOWS
if( !pbf ) return -1;
#endif
pbf->bf_length = t;
m_total_files_length += t;
r = decode_query(p, dl, "path", (const char **)0, &n, (int64_t*)0,
QUERY_POS);
if( !r ) return -1;
if(!decode_list2path(p + r, n, path)) return -1;
int f_conv;
char *tmpfn = new char[strlen(path)*2+5];
#ifndef WINDOWS
if( !tmpfn ) return -1;
#endif
if( f_conv = ConvertFilename(tmpfn, path, strlen(path)*2+5) ){
if( arg_flg_convert_filenames ){
pbf->bf_filename = new char[strlen(tmpfn) + 1];
#ifndef WINDOWS
if( !pbf->bf_filename ){
delete []tmpfn;
return -1;
}
#endif
strcpy(pbf->bf_filename, tmpfn);
}else if(!f_warned){
CONSOLE.Warning(3,
"Filename contains non-printable characters; use -T to convert.");
f_warned = 1;
}
}
delete []tmpfn;
if( !f_conv || !arg_flg_convert_filenames ){
pbf->bf_filename = new char[strlen(path) + 1];
#ifndef WINDOWS
if( !pbf->bf_filename ) return -1;
#endif
strcpy(pbf->bf_filename, path);
}
if(pbf_last) pbf_last->bf_next = pbf; else m_btfhead = pbf;
pbf_last = pbf;
}
}else{
if( !decode_query(metabuf,metabuf_len,"info|length",
(const char**) 0,(size_t*) 0,&t,QUERY_LONG) )
return -1;
m_btfhead = _new_bfnode();
#ifndef WINDOWS
if( !m_btfhead) return -1;
#endif
m_btfhead->bf_length = m_total_files_length = t;
if( saveas ){
m_btfhead->bf_filename = new char[strlen(saveas) + 1];
#ifndef WINDOWS
if(!m_btfhead->bf_filename ) return -1;
#endif
strcpy(m_btfhead->bf_filename, saveas);
}else if( arg_flg_convert_filenames ){
char *tmpfn = new char[strlen(path)*2+5];
#ifndef WINDOWS
if( !tmpfn ) return -1;
#endif
ConvertFilename(tmpfn, path, strlen(path)*2+5);
m_btfhead->bf_filename = new char[strlen(tmpfn) + 1];
#ifndef WINDOWS
if( !m_btfhead->bf_filename ){
delete []tmpfn;
return -1;
}
#endif
strcpy(m_btfhead->bf_filename, tmpfn);
delete []tmpfn;
}else{
m_btfhead->bf_filename = new char[strlen(path) + 1];
#ifndef WINDOWS
if(!m_btfhead->bf_filename ) return -1;
#endif
strcpy(m_btfhead->bf_filename, path);
}
}
return 0;
}
int btFiles::CreateFiles()
{
int check_exist = 0;
char fn[MAXPATHLEN];
BTFILE *pbt = m_btfhead;
struct stat sb;
int i = 0;
for(; pbt; pbt = pbt->bf_next){
m_nfiles++;
if( m_directory ){
if( MAXPATHLEN <= snprintf(fn, MAXPATHLEN, "%s%c%s",
m_directory, PATH_SP, pbt->bf_filename) ){
errno = ENAMETOOLONG;
return -1;
}
}else{
strcpy(fn, pbt->bf_filename);
}
if(stat(fn, &sb) < 0){
if(ENOENT == errno){
CONSOLE.Interact_n("");
CONSOLE.Interact_n("Creating file \"%s\"", fn);
if( !_btf_creat_by_path(fn,pbt->bf_length)){
CONSOLE.Warning(1, "error, create file \"%s\" failed: %s", fn,
strerror(errno));
return -1;
}
}else{
CONSOLE.Warning(1, "error, couldn't create file \"%s\": %s", fn,
strerror(errno));
return -1;
}
}else{
if( !check_exist) check_exist = 1;
if( !(S_IFREG & sb.st_mode) ){
CONSOLE.Warning(1, "error, file \"%s\" is not a regular file.", fn);
return -1;
}
if(sb.st_size != pbt->bf_length){
CONSOLE.Warning(1,"error, file \"%s\" size doesn't match; must be %llu",
fn, (unsigned long long)(pbt->bf_length));
return -1;
}
}
} //end for
m_file = new BTFILE *[m_nfiles];
if( !m_file ){
CONSOLE.Warning(1, "error, failed to allocate memory for files list");
return -1;
}
for( pbt = m_btfhead; pbt; pbt = pbt->bf_next ){
m_file[i++] = pbt;
}
return check_exist;
}
void btFiles::PrintOut()
{
BTFILE *p = m_btfhead;
size_t id = 0;
CONSOLE.Print("");
CONSOLE.Print("FILES INFO");
BitField tmpBitField, tmpFilter;
if(m_directory) CONSOLE.Print("Directory: %s", m_directory);
for( ; p ; p = p->bf_next ){
++id;
CONSOLE.Print_n("");
CONSOLE.Print_n("<%d> %s%s [%llu]", (int)id, m_directory ? " " : "",
p->bf_filename, (unsigned long long)(p->bf_length));
if( !arg_flg_exam_only ){
BTCONTENT.SetTmpFilter(id, &tmpFilter);
tmpBitField = *BTCONTENT.pBF;
tmpBitField.Except(tmpFilter);
CONSOLE.Print_n(" %d/%d (%d%%)",
(int)(tmpBitField.Count()), (int)(GetFilePieces(id)),
GetFilePieces(id) ?
(100 * tmpBitField.Count() / GetFilePieces(id)) : 100);
}
}
CONSOLE.Print("Total: %lu MB",
(unsigned long)(m_total_files_length/1024/1024));
}
size_t btFiles::FillMetaInfo(FILE* fp)
{
BTFILE *p;
if( m_directory ){
// multi files
if( bencode_str("files", fp) != 1 ) return 0;
if( bencode_begin_list(fp) != 1) return 0;
for( p = m_btfhead; p; p = p->bf_next){
if( bencode_begin_dict(fp) != 1) return 0;
if( bencode_str("length", fp) != 1 ) return 0;
if( bencode_int(p->bf_length, fp) != 1) return 0;
if( bencode_str("path", fp) != 1) return 0;
if( bencode_path2list(p->bf_filename, fp) != 1 ) return 0;
if( bencode_end_dict_list(fp) != 1) return 0;
}
if(bencode_end_dict_list(fp) != 1 ) return 0;
if(bencode_str("name", fp) != 1) return 0;
return bencode_str(m_directory, fp);
}else{
if( bencode_str("length", fp) != 1 ) return 0;
if( bencode_int(m_btfhead->bf_length, fp) != 1) return 0;
if( bencode_str("name", fp) != 1 ) return 0;
return bencode_str(m_btfhead->bf_filename, fp);
}
return 1;
}
void btFiles::SetFilter(int nfile, BitField *pFilter, size_t pieceLength)
{
BTFILE *p = m_btfhead;
size_t id = 0;
uint64_t sizeBuffer=0;
size_t index;
if( nfile==0 || nfile>m_nfiles ){
pFilter->Clear();
return;
}
pFilter->SetAll();
for( ; p ; p = p->bf_next ){
if(++id == nfile){
if( 0 == p->bf_length ){
p->bf_npieces = 0;
return;
}
size_t start, stop;
start = sizeBuffer / pieceLength;
stop = (sizeBuffer + p->bf_length) / pieceLength;
// calculation is off if file ends on a piece boundary
if(stop > start && 0 == (sizeBuffer + p->bf_length) % pieceLength)
--stop;
p->bf_npieces = stop - start + 1;
for(index = start; index <= stop; index++) {
pFilter->UnSet(index);
}
break;
}
sizeBuffer += p->bf_length;
}
}
char *btFiles::GetFileName(size_t nfile) const
{
if( nfile && nfile <= m_nfiles )
return m_file[nfile-1]->bf_filename;
return (char *)0;
}
uint64_t btFiles::GetFileSize(size_t nfile) const
{
if( nfile && nfile <= m_nfiles )
return m_file[nfile-1]->bf_length;
return 0;
}
size_t btFiles::GetFilePieces(size_t nfile) const
{
//returns the number of pieces in the file
if( nfile && nfile <= m_nfiles )
return m_file[nfile-1]->bf_npieces;
return 0;
}
int btFiles::ConvertFilename(char *dst, const char *src, int size)
{
int retval=0, i, j, f_print=0, f_punct=0;
for(i=j=0; src[i] != '\0' && j < size-2; i++){
if( isprint(src[i]) ){
if( ispunct(src[i]) ) f_punct = 1;
else f_punct = 0;
if(j && !f_print && !f_punct){ sprintf(dst+j, "_"); j++; }
dst[j++] = src[i];
f_print = 1;
}else{
if(f_print && !f_punct){ sprintf(dst+j, "_"); j++; }
snprintf(dst+j, 3, "%.2X", (unsigned char)(src[i]));
j += 2;
f_print = f_punct = 0;
if( !retval ) retval = 1;
}
}
dst[j] = '\0';
return retval;
}
char *btFiles::GetDataName() const
{
return m_directory ? m_directory : m_btfhead->bf_filename;
}
|
akosciak/ctorrent_plus
|
btfiles.cpp
|
C++
|
gpl-2.0
| 21,071
|
/* global mejs, _wpmejsSettings */
(function( window, $ ) {
window.wp = window.wp || {};
// add mime-type aliases to MediaElement plugin support
mejs.plugins.silverlight[0].types.push('video/x-ms-wmv');
mejs.plugins.silverlight[0].types.push('audio/x-ms-wma');
function wpMediaElement() {
var settings = {};
/**
* Initialize media elements.
*
* Ensures media elements that have already been initialized won't be
* processed again.
*
* @since 4.4.0
*/
function initialize() {
if ( typeof _wpmejsSettings !== 'undefined' ) {
settings = $.extend( true, {}, _wpmejsSettings );
}
settings.success = settings.success || function (mejs) {
var autoplay, loop;
if ( 'flash' === mejs.pluginType ) {
autoplay = mejs.attributes.autoplay && 'false' !== mejs.attributes.autoplay;
loop = mejs.attributes.loop && 'false' !== mejs.attributes.loop;
autoplay && mejs.addEventListener( 'canplay', function () {
mejs.play();
}, false );
loop && mejs.addEventListener( 'ended', function () {
mejs.play();
}, false );
}
};
// Only initialize new media elements.
$( '.wp-audio-shortcode, .wp-video-shortcode' )
.not( '.mejs-container' )
.filter(function () {
return ! $( this ).parent().hasClass( '.mejs-mediaelement' );
})
.mediaelementplayer( settings );
}
return {
initialize: initialize
};
}
window.wp.mediaelement = new wpMediaElement();
$( window.wp.mediaelement.initialize );
})( window, jQuery );
|
Gollos/watercase.tk
|
wp-includes/js/mediaelement/wp-mediaelement.js
|
JavaScript
|
gpl-2.0
| 1,596
|
/*
***************************************************************************
* Ralink Tech Inc.
* 4F, No. 2 Technology 5th Rd.
* Science-based Industrial Park
* Hsin-chu, Taiwan, R.O.C.
*
* (c) Copyright 2002, Ralink Technology, Inc.
*
* All rights reserved. Ralink's source code is an unpublished work and the
* use of a copyright notice does not imply otherwise. This source code
* contains confidential trade secret material of Ralink Tech. Any attemp
* or participation in deciphering, decoding, reverse engineering or in any
* way altering the source code is stricitly prohibited, unless the prior
* written consent of Ralink Technology, Inc. is obtained.
***************************************************************************
Module Name:
client_wds.h
Abstract:
*/
#ifndef __CLIENT_WDS_H__
#define __CLIENT_WDS_H__
#include "client_wds_cmm.h"
VOID CliWds_ProxyTabInit(
IN PRTMP_ADAPTER pAd);
VOID CliWds_ProxyTabDestory(
IN PRTMP_ADAPTER pAd);
PCLIWDS_PROXY_ENTRY CliWdsEntyAlloc(
IN PRTMP_ADAPTER pAd);
VOID CliWdsEntyFree(
IN PRTMP_ADAPTER pAd,
IN PCLIWDS_PROXY_ENTRY pCliWdsEntry);
PUCHAR CliWds_ProxyLookup(
IN PRTMP_ADAPTER pAd,
IN PUCHAR pMac);
VOID CliWds_ProxyTabUpdate(
IN PRTMP_ADAPTER pAd,
IN SHORT Aid,
IN PUCHAR pMac);
VOID CliWds_ProxyTabMaintain(
IN PRTMP_ADAPTER pAd);
#endif // __CLIENT_WDS_H__ //
|
StanislavPodolsky/RT5350
|
linux-3.8.7/drivers/net/wireless/ralink/rt3883/rt2860v2/include/client_wds.h
|
C
|
gpl-2.0
| 1,374
|
<?php
/**
* NoNumber Framework Helper File: Assignments: FlexiContent
*
* @package NoNumber Framework
* @version 15.11.2151
*
* @author Peter van Westen <peter@nonumber.nl>
* @link http://www.nonumber.nl
* @copyright Copyright © 2015 NoNumber All Rights Reserved
* @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
*/
defined('_JEXEC') or die;
require_once JPATH_PLUGINS . '/system/nnframework/helpers/assignment.php';
class NNFrameworkAssignmentsFlexiContent extends NNFrameworkAssignment
{
function passPageTypes()
{
return $this->passByPageTypes('com_flexicontent', $this->selection, $this->assignment);
}
function passTags()
{
if ($this->request->option != 'com_flexicontent')
{
return $this->pass(false);
}
$pass = (
($this->params->inc_tags && $this->request->view == 'tags')
|| ($this->params->inc_items && in_array($this->request->view, array('item', 'items')))
);
if (!$pass)
{
return $this->pass(false);
}
if ($this->params->inc_tags && $this->request->view == 'tags')
{
$query = $this->db->getQuery(true)
->select('t.name')
->from('#__flexicontent_tags AS t')
->where('t.id = ' . (int) trim(JFactory::getApplication()->input->getInt('id', 0)))
->where('t.published = 1');
$this->db->setQuery($query);
$tag = $this->db->loadResult();
$tags = array($tag);
}
else
{
$query = $this->db->getQuery(true)
->select('t.name')
->from('#__flexicontent_tags_item_relations AS x')
->join('LEFT', '#__flexicontent_tags AS t ON t.id = x.tid')
->where('x.itemid = ' . (int) $this->request->id)
->where('t.published = 1');
$this->db->setQuery($query);
$tags = $this->db->loadColumn();
}
return $this->passSimple($tags, true);
}
function passTypes()
{
if ($this->request->option != 'com_flexicontent')
{
return $this->pass(false);
}
$pass = in_array($this->request->view, array('item', 'items'));
if (!$pass)
{
return $this->pass(false);
}
$query = $this->db->getQuery(true)
->select('x.type_id')
->from('#__flexicontent_items_ext AS x')
->where('x.item_id = ' . (int) $this->request->id);
$this->db->setQuery($query);
$type = $this->db->loadResult();
$types = $this->makeArray($type, 1);
return $this->passSimple($types);
}
function getCatParentIds($id = 0)
{
return $this->getParentIds($id, 'categories', 'parent_id');
}
}
|
christopherstock/WinklerUndSchorn
|
joomla/plugins/system/nnframework/helpers/assignments/flexicontent.php
|
PHP
|
gpl-2.0
| 2,457
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- /home/espenr/tmp/qt-3.3.8-espenr-2499/qt-x11-free-3.3.8/include/qgrid.h:1 -->
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>qgrid.h Include File</title>
<style type="text/css"><!--
fn { margin-left: 1cm; text-indent: -1cm; }
a:link { color: #004faf; text-decoration: none }
a:visited { color: #672967; text-decoration: none }
body { background: #ffffff; color: black; }
--></style>
</head>
<body>
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr bgcolor="#E5E5E5">
<td valign=center>
<a href="index.html">
<font color="#004faf">Home</font></a>
| <a href="classes.html">
<font color="#004faf">All Classes</font></a>
| <a href="mainclasses.html">
<font color="#004faf">Main Classes</font></a>
| <a href="annotated.html">
<font color="#004faf">Annotated</font></a>
| <a href="groups.html">
<font color="#004faf">Grouped Classes</font></a>
| <a href="functions.html">
<font color="#004faf">Functions</font></a>
</td>
<td align="right" valign="center"><img src="logo32.png" align="right" width="64" height="32" border="0"></td></tr></table><h1 align=center>qgrid.h</h1>
<p>This is the verbatim text of the qgrid.h include file. It is provided only for illustration; the copyright remains with Trolltech.
<hr>
<pre>
/****************************************************************************
** $Id: qt/qgrid.h 3.3.8 edited Jan 11 14:38 $
**
** Copyright (C) 1992-2007 Trolltech ASA. All rights reserved.
**
** This file is part of the widgets module of the Qt GUI Toolkit.
**
** This file may be used under the terms of the GNU General Public
** License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Alternatively you may (at your option) use any
** later version of the GNU General Public License if such license has
** been publicly approved by Trolltech ASA (or its successors, if any)
** and the KDE Free Qt Foundation.
**
** Please review the following information to ensure GNU General
** Public Licensing requirements will be met:
** http://trolltech.com/products/qt/licenses/licensing/opensource/.
** If you are unsure which license is appropriate for your use, please
** review the following information:
** http://trolltech.com/products/qt/licenses/licensing/licensingoverview
** or contact the sales department at sales@trolltech.com.
**
** This file may be used under the terms of the Q Public License as
** defined by Trolltech ASA and appearing in the file LICENSE.QPL
** included in the packaging of this file. Licensees holding valid Qt
** Commercial licenses may use this file in accordance with the Qt
** Commercial License Agreement provided with the Software.
**
** This file is provided "AS IS" with NO WARRANTY OF ANY KIND,
** INCLUDING THE WARRANTIES OF DESIGN, MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE. Trolltech reserves all rights not granted
** herein.
**
**********************************************************************/
#ifndef QGRID_H
#define QGRID_H
#ifndef QT_H
#include "qframe.h"
#endif // QT_H
#ifndef QT_NO_GRID
class QGridLayout;
class Q_EXPORT QGrid : public QFrame
{
Q_OBJECT
public:
QGrid( int n, QWidget* parent=0, const char* name=0, WFlags f = 0 );
QGrid( int n, Orientation orient, QWidget* parent=0, const char* name=0,
WFlags f = 0 );
void setSpacing( int );
QSize sizeHint() const;
#ifndef QT_NO_COMPAT
typedef Orientation Direction;
#endif
protected:
void frameChanged();
private:
QGridLayout *lay;
private: // Disabled copy constructor and operator=
#if defined(Q_DISABLE_COPY)
QGrid( const QGrid & );
QGrid& operator=( const QGrid & );
#endif
};
#endif // QT_NO_GRID
#endif // QGRID_H
</pre>
<!-- eof -->
<p><address><hr><div align=center>
<table width=100% cellspacing=0 border=0><tr>
<td>Copyright © 2007
<a href="troll.html">Trolltech</a><td align=center><a href="trademarks.html">Trademarks</a>
<td align=right><div align=right>Qt 3.3.8</div>
</table></div></address></body>
</html>
|
gnu-andrew/qt3
|
doc/html/qgrid-h.html
|
HTML
|
gpl-2.0
| 4,194
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.