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
|
|---|---|---|---|---|---|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_strsplit_blanks.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: jdaufin <jdaufin@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2017/06/27 19:38:16 by jdaufin #+# #+# */
/* Updated: 2020/12/10 17:03:41 by jdaufin ### ########lyon.fr */
/* */
/* ************************************************************************** */
#include "libft.h"
static size_t ft_wordcount_blanks(char *s)
{
ssize_t i;
size_t ret;
_Bool inword;
if (!s)
return (0);
i = -1;
ret = 0;
inword = 0;
while (s[++i])
{
if (ft_isspace(s[i]))
inword = 0;
else if (!inword)
{
inword = 1;
ret++;
}
}
return (ret);
}
static unsigned int nextwd(char *s, unsigned int start)
{
unsigned int ret;
_Bool inword;
ret = start;
if (!s || (start >= ft_strlen(s)) || (!ret && !ft_isspace(s[ret])))
return (0);
inword = ft_isspace(s[ret]) ? 0 : 1;
while (s[ret])
{
if (inword)
while (s[ret] && !ft_isspace(s[ret]))
ret++;
while (ft_isspace(s[ret]))
ret++;
if (s[ret])
return (ret);
else
return (0);
}
return (0);
}
static size_t ft_wdlen(char *cur)
{
size_t ret;
if (!cur || ft_isspace(*cur))
return (0);
ret = 0;
while (*cur && !ft_isspace(*cur))
{
ret++;
cur++;
}
return (ret);
}
char **ft_strsplit_blanks(char *s)
{
char **ret;
size_t retsize;
size_t i;
unsigned int pos;
retsize = ft_wordcount_blanks(s);
if (!s || !(ret = (char **)ft_memalloc((retsize + 1) * sizeof(char *))))
return (NULL);
i = 0;
pos = 0;
while (i < retsize)
{
pos = i ? nextwd(s, (unsigned int)ft_wdlen(&s[pos]) + pos) \
: nextwd(s, 0);
if (i && !pos)
return (NULL);
else
ret[i++] = ft_strsub(s, pos, ft_wdlen(&s[pos]));
}
ret[i] = NULL;
return (ret);
}
|
anucii/libft
|
srcs/ft_strsplit_blanks.c
|
C
|
gpl-3.0
| 2,283
|
/* $XFree86: xc/programs/Xserver/hw/xfree86/os-support/sysv/sysv_io.c,v 3.11 2003/02/17 15:12:00 dawes Exp $ */
/*
* Copyright 1990,91 by Thomas Roell, Dinkelscherben, Germany
* Copyright 1993 by David Dawes <dawes@xfree86.org>
*
* Permission to use, copy, modify, distribute, and sell this software and its
* documentation for any purpose is hereby granted without fee, provided that
* the above copyright notice appear in all copies and that both that
* copyright notice and this permission notice appear in supporting
* documentation, and that the names of Thomas Roell and David Dawes
* not be used in advertising or publicity pertaining to distribution of
* the software without specific, written prior permission. Thomas Roell and
* David Dawes makes no representations about the suitability of this
* software for any purpose. It is provided "as is" without express or
* implied warranty.
*
* THOMAS ROELL AND DAVID DAWES DISCLAIMS ALL WARRANTIES WITH REGARD TO
* THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS, IN NO EVENT SHALL THOMAS ROELL OR DAVID DAWES BE LIABLE FOR
* ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
* RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF
* CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*
*/
/* $XConsortium: sysv_io.c /main/8 1996/10/19 18:08:06 kaleb $ */
#include "X.h"
#include "compiler.h"
#include "xf86.h"
#include "xf86Priv.h"
#include "xf86_OSlib.h"
void
xf86SoundKbdBell(int loudness, int pitch, int duration)
{
if (loudness && pitch)
{
#ifdef KDMKTONE
/*
* If we have KDMKTONE use it to avoid putting the server
* to sleep
*/
ioctl(xf86Info.consoleFd, KDMKTONE,
((1193190 / pitch) & 0xffff) |
(((unsigned long)duration *
loudness / 50) << 16));
#else
ioctl(xf86Info.consoleFd, KIOCSOUND, 1193180 / pitch);
usleep(xf86Info.bell_duration * loudness * 20);
ioctl(xf86Info.consoleFd, KIOCSOUND, 0);
#endif
}
}
void
xf86SetKbdLeds(int leds)
{
#ifdef KBIO_SETMODE
ioctl(xf86Info.consoleFd, KBIO_SETMODE, KBM_AT);
ioctl(xf86Info.consoleFd, KDSETLED, leds);
ioctl(xf86Info.consoleFd, KBIO_SETMODE, KBM_XT);
#endif
}
#include "xf86OSKbd.h"
Bool
xf86OSKbdPreInit(InputInfoPtr pInfo)
{
return FALSE;
}
|
chriskmanx/qmole
|
QMOLEDEV/vnc-4_1_3-unixsrc/unix/xc/programs/Xserver/hw/xfree86/os-support/sysv/sysv_io.c
|
C
|
gpl-3.0
| 2,393
|
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <dlfcn.h>
enum {EXIT, GENERATE_PRIME, TEST_PRIME};
enum { NOT_PRIME, PRIME };
void menu();
void call_functions(int option);
void test_prime_call();
int main()
{
int option = 0;
void* handle = dlopen("libprimo.so", RTLD_LAZY);
int (*generate_prime)() = dlsym(handle, "generate_prime");
int (*test_prime)() = dlsym(handle, "test_prime");
do {
menu();
scanf("%d", &option);
call_functions(option);
} while(option != EXIT);
dlclose(handle);
return 0;
}
void menu()
{
printf("Escolha uma opção.\n");
printf("1) Gerar um número primo.\n");
printf("2) Testar a primalidade de um primo.\n");
printf("0) Sair do programa.\n");
}
void call_functions(int option)
{
int prime;
switch(option) {
case GENERATE_PRIME:
prime = generate_prime();
printf("Numero primo gerado: %d\n", prime);
break;
case TEST_PRIME:
test_prime_call();
break;
case EXIT:
printf("Bye!\n");
break;
default:
printf("Opção inválida! Digite uma das opções apresentadas no menu...\n");
break;
}
}
void test_prime_call()
{
int number;
int result;
printf("Digite o número que você deseja testar: \n");
scanf("%d", &number);
result = test_prime(number);
if(result == PRIME) {
printf("O numero %d é primo!\n", number);
}
else {
printf("O numero %d não é primo!\n", number);
}
}
|
CodigosFSO/trabalho03
|
q01c/src/q01c.c
|
C
|
gpl-3.0
| 1,392
|
// ----------------------------------------------------------------------------
// Copyright (C) 2015 Strategic Facilities Technology Council
//
// This file is part of the Engineering Autonomous Space Software (EASS) Library.
//
// The EASS Library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 3 of the License, or (at your option) any later version.
//
// The EASS 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 EASS Library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
// To contact the authors:
// http://www.csc.liv.ac.uk/~lad
//
//----------------------------------------------------------------------------
package eass.mas.ev3;
import ail.syntax.Literal;
import ail.syntax.NumberTermImpl;
import java.io.PrintStream;
import java.rmi.RemoteException;
import lejos.remote.ev3.RemoteRequestEV3;
import lejos.remote.ev3.RemoteRequestSampleProvider;
/**
* Encapsulation of an Ultrasonic Sensor to be used with an EASS environment.
* @author louiseadennis
*
*/
public class EASSUltrasonicSensor implements EASSSensor {
PrintStream out;
RemoteRequestSampleProvider sensor;
public EASSUltrasonicSensor(RemoteRequestEV3 brick, String portName) throws RemoteException {
sensor = (RemoteRequestSampleProvider) brick.createSampleProvider(portName, "lejos.hardware.sensor.EV3UltrasonicSensor", "Distance");
}
/*
* (non-Javadoc)
* @see eass.mas.ev3.EASSSensor#addPercept(eass.mas.ev3.EASSEV3Environment)
*/
@Override
public void addPercept(EASSEV3Environment env) {
try {
float[] sample = new float[1];
sensor.fetchSample(sample, 0);
float distancevalue = sample[0];
if (out != null) {
out.println("distance is " + distancevalue);
}
Literal distance = new Literal("distance");
distance.addTerm(new NumberTermImpl(distancevalue));
env.addUniquePercept("distance", distance);
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
/*
* (non-Javadoc)
* @see eass.mas.ev3.EASSSensor#setPrintStream(java.io.PrintStream)
*/
@Override
public void setPrintStream(PrintStream s) {
out = s;
}
/*
* (non-Javadoc)
* @see eass.mas.ev3.EASSSensor#close()
*/
@Override
public void close() {
try {
sensor.close();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
|
VerifiableAutonomy/mcapl
|
src/classes/eass/mas/ev3/EASSUltrasonicSensor.java
|
Java
|
gpl-3.0
| 2,779
|
#!/usr/bin/env python
# _*_ coding:utf-8 _*-_
############################
# File Name: demo.py
# Author: lza
# Created Time: 2016-08-30 16:29:35
############################
import dns.resolver
domain = raw_input ('Please input an domain: ') #输入域名地址
MX = dns.resolver.query(domain , "MX") #指定查询类型为A记录
for i in MX: # 遍历回应结果,输出MX记录的preference及exchanger信息
print 'MX preference =', i.preference, 'mail exchanger =', i.exchange
if __name__ == "__main__":
pass
|
zhengjue/mytornado
|
study/1/dnspython/demo1.py
|
Python
|
gpl-3.0
| 537
|
/*
* The MIT License
* Copyright (c) 2012 Matias Meno <m@tias.me>
*/
@-webkit-keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px); }
30%, 70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px); }
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px); } }
@-moz-keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px); }
30%, 70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px); }
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px); } }
@keyframes passing-through {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px); }
30%, 70% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px); }
100% {
opacity: 0;
-webkit-transform: translateY(-40px);
-moz-transform: translateY(-40px);
-ms-transform: translateY(-40px);
-o-transform: translateY(-40px);
transform: translateY(-40px); } }
@-webkit-keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px); }
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px); } }
@-moz-keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px); }
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px); } }
@keyframes slide-in {
0% {
opacity: 0;
-webkit-transform: translateY(40px);
-moz-transform: translateY(40px);
-ms-transform: translateY(40px);
-o-transform: translateY(40px);
transform: translateY(40px); }
30% {
opacity: 1;
-webkit-transform: translateY(0px);
-moz-transform: translateY(0px);
-ms-transform: translateY(0px);
-o-transform: translateY(0px);
transform: translateY(0px); } }
@-webkit-keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1); }
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1); }
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1); } }
@-moz-keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1); }
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1); }
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1); } }
@keyframes pulse {
0% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1); }
10% {
-webkit-transform: scale(1.1);
-moz-transform: scale(1.1);
-ms-transform: scale(1.1);
-o-transform: scale(1.1);
transform: scale(1.1); }
20% {
-webkit-transform: scale(1);
-moz-transform: scale(1);
-ms-transform: scale(1);
-o-transform: scale(1);
transform: scale(1); } }
.dropzone, .dropzone * {
box-sizing: border-box; }
.dropzone {
min-height: 150px;
border: 2px solid rgba(0, 0, 0, 0.3);
background: white;
padding: 20px 20px; }
.dropzone.dz-clickable {
cursor: pointer; }
.dropzone.dz-clickable * {
cursor: default; }
.dropzone.dz-clickable .dz-message, .dropzone.dz-clickable .dz-message * {
cursor: pointer; }
.dropzone.dz-started .dz-message {
display: none; }
.dropzone.dz-drag-hover {
border-style: solid; }
.dropzone.dz-drag-hover .dz-message {
opacity: 0.5; }
.dropzone .dz-message {
text-align: center;
margin: 3em 0; }
.dropzone .dz-preview {
position: relative;
display: inline-block;
vertical-align: top;
margin: 16px;
min-height: 100px; }
.dropzone .dz-preview:hover {
z-index: 1000; }
.dropzone .dz-preview:hover .dz-details {
opacity: 1; }
.dropzone .dz-preview.dz-file-preview .dz-image {
border-radius: 20px;
background: #999;
background: linear-gradient(to bottom, #eee, #ddd); }
.dropzone .dz-preview.dz-file-preview .dz-details {
opacity: 1; }
.dropzone .dz-preview.dz-image-preview {
background: white; }
.dropzone .dz-preview.dz-image-preview .dz-details {
-webkit-transition: opacity 0.2s linear;
-moz-transition: opacity 0.2s linear;
-ms-transition: opacity 0.2s linear;
-o-transition: opacity 0.2s linear;
transition: opacity 0.2s linear; }
.dropzone .dz-preview .dz-remove {
font-size: 14px;
text-align: center;
display: block;
cursor: pointer;
border: none; }
.dropzone .dz-preview .dz-remove:hover {
text-decoration: underline; }
.dropzone .dz-preview:hover .dz-details {
opacity: 1; }
.dropzone .dz-preview .dz-details {
z-index: 20;
position: absolute;
top: 0;
left: 0;
opacity: 0;
font-size: 13px;
min-width: 100%;
max-width: 100%;
padding: 2em 1em;
text-align: center;
color: rgba(0, 0, 0, 0.9);
line-height: 150%; }
.dropzone .dz-preview .dz-details .dz-size {
margin-bottom: 1em;
font-size: 16px; }
.dropzone .dz-preview .dz-details .dz-filename {
white-space: nowrap; }
.dropzone .dz-preview .dz-details .dz-filename:hover span {
border: 1px solid rgba(200, 200, 200, 0.8);
background-color: rgba(255, 255, 255, 0.8); }
.dropzone .dz-preview .dz-details .dz-filename:not(:hover) {
overflow: hidden;
text-overflow: ellipsis; }
.dropzone .dz-preview .dz-details .dz-filename:not(:hover) span {
border: 1px solid transparent; }
.dropzone .dz-preview .dz-details .dz-filename span, .dropzone .dz-preview .dz-details .dz-size span {
background-color: rgba(255, 255, 255, 0.4);
padding: 0 0.4em;
border-radius: 3px; }
.dropzone .dz-preview:hover .dz-image img {
-webkit-transform: scale(1.05, 1.05);
-moz-transform: scale(1.05, 1.05);
-ms-transform: scale(1.05, 1.05);
-o-transform: scale(1.05, 1.05);
transform: scale(1.05, 1.05);
-webkit-filter: blur(8px);
filter: blur(8px); }
.dropzone .dz-preview .dz-image {
border-radius: 20px;
overflow: hidden;
width: 120px;
height: 120px;
position: relative;
display: block;
z-index: 10; }
.dropzone .dz-preview .dz-image img {
display: block; }
.dropzone .dz-preview.dz-success .dz-success-mark {
-webkit-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-moz-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-ms-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
-o-animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1);
animation: passing-through 3s cubic-bezier(0.77, 0, 0.175, 1); }
.dropzone .dz-preview.dz-error .dz-error-mark {
opacity: 1;
-webkit-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-moz-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-ms-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
-o-animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1);
animation: slide-in 3s cubic-bezier(0.77, 0, 0.175, 1); }
.dropzone .dz-preview .dz-success-mark, .dropzone .dz-preview .dz-error-mark {
pointer-events: none;
opacity: 0;
z-index: 500;
position: absolute;
display: block;
top: 50%;
left: 50%;
margin-left: -27px;
margin-top: -27px; }
.dropzone .dz-preview .dz-success-mark svg, .dropzone .dz-preview .dz-error-mark svg {
display: block;
width: 54px;
height: 54px; }
.dropzone .dz-preview.dz-processing .dz-progress {
opacity: 1;
-webkit-transition: all 0.2s linear;
-moz-transition: all 0.2s linear;
-ms-transition: all 0.2s linear;
-o-transition: all 0.2s linear;
transition: all 0.2s linear; }
.dropzone .dz-preview.dz-complete .dz-progress {
opacity: 0;
-webkit-transition: opacity 0.4s ease-in;
-moz-transition: opacity 0.4s ease-in;
-ms-transition: opacity 0.4s ease-in;
-o-transition: opacity 0.4s ease-in;
transition: opacity 0.4s ease-in; }
.dropzone .dz-preview:not(.dz-processing) .dz-progress {
-webkit-animation: pulse 6s ease infinite;
-moz-animation: pulse 6s ease infinite;
-ms-animation: pulse 6s ease infinite;
-o-animation: pulse 6s ease infinite;
animation: pulse 6s ease infinite; }
.dropzone .dz-preview .dz-progress {
opacity: 1;
z-index: 1000;
pointer-events: none;
position: absolute;
height: 16px;
left: 50%;
top: 50%;
margin-top: -8px;
width: 80px;
margin-left: -40px;
background: rgba(255, 255, 255, 0.9);
-webkit-transform: scale(1);
border-radius: 8px;
overflow: hidden; }
.dropzone .dz-preview .dz-progress .dz-upload {
background: #333;
background: linear-gradient(to bottom, #666, #444);
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 0;
-webkit-transition: width 300ms ease-in-out;
-moz-transition: width 300ms ease-in-out;
-ms-transition: width 300ms ease-in-out;
-o-transition: width 300ms ease-in-out;
transition: width 300ms ease-in-out; }
.dropzone .dz-preview.dz-error .dz-error-message {
display: block; }
.dropzone .dz-preview.dz-error:hover .dz-error-message {
opacity: 1;
pointer-events: auto; }
.dropzone .dz-preview .dz-error-message {
pointer-events: none;
z-index: 1000;
position: absolute;
display: block;
display: none;
opacity: 0;
-webkit-transition: opacity 0.3s ease;
-moz-transition: opacity 0.3s ease;
-ms-transition: opacity 0.3s ease;
-o-transition: opacity 0.3s ease;
transition: opacity 0.3s ease;
border-radius: 8px;
font-size: 13px;
top: 130px;
left: -10px;
width: 140px;
background: #be2626;
background: linear-gradient(to bottom, #be2626, #a92222);
padding: 0.5em 1.2em;
color: white; }
.dropzone .dz-preview .dz-error-message:after {
content: '';
position: absolute;
top: -6px;
left: 64px;
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid #be2626; }
.dropzone {
background-color: #f3f4ee;
margin: 20px 10px;
-webkit-border-radius: 20px;
-moz-border-radius: 20px;
border-radius: 20px;
box-shadow: inset 5px 5px 10px 2px #e1e2dc, 5px 5px 10px 2px #e1e2dc;
-webkit-box-shadow: inset 5px 5px 10px 2px #e1e2dc, 5px 5px 10px 2px #e1e2dc;
-moz-box-shadow: inset 5px 5px 10px 2px #e1e2dc, 5px 5px 10px 2px #e1e2dc;
-o-box-shadow: 5px 5px 10px 2px #e1e2dc, 5px 5px 10px 2px #e1e2dc;
}
.dropzone span {
color: #bbb;
font-size: 26px;
text-transform: uppercase;
font-weight: bold;
}
.dropzone .dz-preview span {
font-size: 12px;
}
.dropzone .dz-filename {
padding-top: 20px;
}
|
UH-StudentServices/coursepages
|
modules/uhc_course_material_dnd/css/dropzone.css
|
CSS
|
gpl-3.0
| 13,231
|
<?php
/**
* @file
* Definition of EntityDailyReportMigration.
*/
class EntityDailyReportMigration extends Migration {
public function __construct($arguments) {
parent::__construct($arguments);
$options = array();
$options['header_rows'] = 1;
$options['delimiter'] = ",";
$columns = array(
0 => array('cha', 'Total chemo appointment added yesterday'),
1 => array('date', 'The date chemo apps were processed'),
2 => array('chp', 'Total chemo appointment processed yesterday'),
3 => array('date2', 'The date chemo apps were completed'),
4 => array('chc', 'Total chemo appointment completed yesterday'),
5 => array('date3', 'The date chemo apps were added'),
6 => array('moa', 'Total medonc appointment added yesterday'),
7 => array('date4', 'The date medonc apps were processed'),
8 => array('mop', 'Total medonc appointment processed yesterday'),
9 => array('date5', 'The date medonc apps were completed'),
10 => array('moc', 'Total medonc appointment completed yesterday'),
11 => array('date6', 'The date radonc apps were added'),
12 => array('roa', 'Total radonc appointment added yesterday'),
13 => array('date7', 'The date radonc apps were processed'),
14 => array('rop', 'Total radonc appointment processed yesterday'),
15 => array('date8', 'The date radonc apps were completed'),
16 => array('roc', 'Total radonc appointment completed yesterday'),
17 => array('date9', 'The date medicare apps were added'),
18 => array('mdca', 'Total medicare appointment added yesterday'),
29 => array('date10', 'The medicare date apps were processed'),
20 => array('mdcp', 'Total medicare appointment processed yesterday'),
21 => array('date11', 'The date medicare apps were completed'),
22 => array('mdcc', 'Total medicare appointment completed yesterday'),
23 => array('date1', 'The date medicare apps were completed'),
24 => array('pk', 'A random primary key needed for migration')
);
$csv_file = DRUPAL_ROOT . '/' . 'sites/default/files/export_import/agg.csv';
$this->source = new MigrateSourceCSV($csv_file, $columns, $options);
$this->body = t('CSV Chemo Processed Total Appointments on Date');
$this->destination = new MigrateDestinationEntityAPI('daily_report','daily_report');
// Tell Migrate the unique IDs for this migration live - watch for multiple appts.
$source_key_schema = array('cha' => array(
'type' => 'pk',
'unsigned' => TRUE,
'not null' => TRUE,
),
);
$this->map = new MigrateSQLMap($this->machineName,
$source_key_schema,
$this->destination->getKeySchema('daily_report')
);
$this->addFieldMapping('field_date','date'); // may need to work on
$this->addFieldMapping('field_chemo_added', 'cha');
$this->addFieldMapping('field_chemo_processed', 'chp');
$this->addFieldMapping('field_chemo_completed', 'chc');
$this->addFieldMapping('field_medonc_added', 'moa');
$this->addFieldMapping('field_medonc_processed', 'mop');
$this->addFieldMapping('field_medonc_completed', 'moc');
$this->addFieldMapping('field_radonc_added', 'roa');
$this->addFieldMapping('field_radonc_processed', 'rop');
$this->addFieldMapping('field_radonc_completed', 'roc');
$this->addFieldMapping('field_medicare_added', 'mdca');
$this->addFieldMapping('field_medicare_processed', 'mdcp');
$this->addFieldMapping('field_medicare_completed', 'mdcc');
$this->addUnmigratedSources(array(
'date1',
'date2',
'date3',
'date4',
'date5',
'date6',
'date7',
'date8',
'date9',
'date10',
'date11',
));
$this->addUnmigratedDestinations(array(
'path',
'field_date:timezone',// Timezone
'field_date:rrule', // Recurring event rule
'field_date:to', // End date date
));
}
/**
* Prepare a proper unique key.
*/
public function prepareKey($key, $row) {
$key = array();
$row->pk = rand(1,$row->cha);
$key['orc_id_drug'] = $row->pk;
return $key;
}
public function prepareRow($row) {
parent::prepareRow($row);
//date
if(preg_match('/\d+\/\d+\/\d+/',$row->date, $matches)){
$row->date = $row->date . ' 12:00:00 PM';
}else{
$row->date = date("Y-m-d"); // set to today's date, as no records were added today.
}
}
}
|
UNMCCC/prior-auths-drupal7
|
modules/daily_report_migration/migration/EntityDailyReportMigration.php
|
PHP
|
gpl-3.0
| 4,941
|
#
# Cookbook:: build_cookbook
# Recipe:: lint
#
# Copyright:: 2017, Luca Capanna
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
include_recipe 'delivery-truck::lint'
|
CPTBarbaciccia/chef-knockd
|
.delivery/build_cookbook/recipes/lint.rb
|
Ruby
|
gpl-3.0
| 757
|
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The Tudors</title>
<meta http-equiv="refresh" content="0;URL='/icingaweb2/'" />
</head>
<body>
<p>This page has moved to a <a href="/icingaweb2/">
icingaweb2</a>.</p>
</body>
</html>
|
joshuacox/docker-icinga2
|
www/index.html
|
HTML
|
gpl-3.0
| 301
|
/**
* @file ColorUtility.h
*
* @note This file is part of the "Synesthesia3D" graphics engine
*
* @copyright Copyright (C) Iftode Bogdan-Marius <iftode.bogdan@gmail.com>
*
* @copyright
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* @copyright
* 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.
* @copyright
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef COLORUTILITY_H
#define COLORUTILITY_H
#include "ResourceData.h"
#include "HalfFloat.h"
namespace Synesthesia3D
{
/**
* @brief Utility class for converting between various color formats.
*/
class ColorUtility
{
public:
/**
* @brief Encode provided red, green and blue values into a single R8G8B8X8 value.
* @note Default alpha value is 255.
*
* @param[in] red Red channel value.
* @param[in] green Green channel value.
* @param[in] blue Blue channel value.
*
* @return A single R8G8B8X8 value.
*/
static SYNESTHESIA3D_DLL s3dDword MakeR8G8B8(
const s3dByte red,
const s3dByte green,
const s3dByte blue);
/**
* @brief Encode provided red, green, blue and alpha values into a single R8G8B8A8 value.
*
* @param[in] red Red channel value.
* @param[in] green Green channel value.
* @param[in] blue Blue channel value.
* @param[in] alpha Alpha channel value.
*
* @return A single R8G8B8A8 value.
*/
static SYNESTHESIA3D_DLL s3dDword MakeR8G8B8A8(
const s3dByte red,
const s3dByte green,
const s3dByte blue,
const s3dByte alpha);
/**
* @brief Decode provided R8G8B8X8 value into red, green and blue values.
*
* @param[in] rgb R8G8B8X8 value.
* @param[out] red Red channel value.
* @param[out] green Green channel value.
* @param[out] blue Blue channel value.
*/
static SYNESTHESIA3D_DLL void ExtractR8G8B8(
const s3dDword rgb,
s3dByte& red,
s3dByte& green,
s3dByte& blue);
/**
* @brief Decode provided R8G8B8A8 value into red, green, blue and alpha values.
*
* @param[in] rgba R8G8B8A8 value.
* @param[out] red Red channel value.
* @param[out] green Green channel value.
* @param[out] blue Blue channel value.
* @param[out] alpha Alpha channel value.
*/
static SYNESTHESIA3D_DLL void ExtractR8G8B8A8(
const s3dDword rgba,
s3dByte& red,
s3dByte& green,
s3dByte& blue,
s3dByte& alpha);
/**
* @brief Encode provided red, green and blue values into a single B8G8R8X8 value.
* @note Default alpha value is 255.
*
* @param[in] red Red channel value.
* @param[in] green Green channel value.
* @param[in] blue Blue channel value.
*
* @return A single B8G8R8X8 value.
*/
static SYNESTHESIA3D_DLL s3dDword MakeB8G8R8(
const s3dByte red,
const s3dByte green,
const s3dByte blue);
/**
* @brief Encode provided red, green, blue and alpha values into a single B8G8R8A8 value.
*
* @param[in] red Red channel value.
* @param[in] green Green channel value.
* @param[in] blue Blue channel value.
* @param[in] alpha Alpha channel value.
*
* @return A single B8G8R8A8 value.
*/
static SYNESTHESIA3D_DLL s3dDword MakeB8G8R8A8(
const s3dByte red,
const s3dByte green,
const s3dByte blue,
const s3dByte alpha);
/**
* @brief Decode provided B8G8R8X8 value into red, green and blue values.
*
* @param[in] bgr B8G8R8X8 value.
* @param[out] red Red channel value.
* @param[out] green Green channel value.
* @param[out] blue Blue channel value.
*/
static SYNESTHESIA3D_DLL void ExtractB8G8R8(
const s3dDword bgr,
s3dByte& red,
s3dByte& green,
s3dByte& blue);
/**
* @brief Decode provided B8G8R8A8 value into red, green, blue and alpha values.
*
* @param[in] bgra B8G8R8A8 value.
* @param[out] red Red channel value.
* @param[out] green Green channel value.
* @param[out] blue Blue channel value.
* @param[out] alpha Alpha channel value.
*/
static SYNESTHESIA3D_DLL void ExtractB8G8R8A8(
const s3dDword bgra,
s3dByte& red,
s3dByte& green,
s3dByte& blue,
s3dByte& alpha);
/**
* @brief Encode provided red, green and blue values into a single R5G6B5 value.
*
* @param[in] red Red channel value.
* @param[in] green Green channel value.
* @param[in] blue Blue channel value.
*
* @return A single R5G6B5 value.
*/
static SYNESTHESIA3D_DLL s3dWord MakeR5G6B5(
const s3dByte red,
const s3dByte green,
const s3dByte blue);
/**
* @brief Decode provided R5G6B5 value into red, green and blue values.
*
* @param[in] rgb R5G6B5 value.
* @param[out] red Red channel value.
* @param[out] green Green channel value.
* @param[out] blue Blue channel value.
*/
static SYNESTHESIA3D_DLL void ExtractR5G6B5(
const s3dWord rgb,
s3dByte& red,
s3dByte& green,
s3dByte& blue);
/**
* @brief Decodes a R5G6B5 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of R5G6B5 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromR5G6B5(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A1R5G5B5 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A1R5G5B5 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA1R5G5B5(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A4R4G4B4 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A4R4G4B4 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA4R4G4B4(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a L8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of L8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromL8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A8L8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A8L8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA8L8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a R8G8B8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of R8G8B8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromR8G8B8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a X8R8G8B8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of X8R8G8B8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromX8R8G8B8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A8R8G8B8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A8R8G8B8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA8R8G8B8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A8B8G8R8 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A8B8G8R8 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA8B8G8R8(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a L16 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of L16 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromL16(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a G16R16 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of G16R16 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromG16R16(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A16B16G16R16 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of A16B16G16R16 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA16B16G16R16(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a R16F texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
*
* @param[in] inData An array of R16F values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromR16F(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a G16R16F texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
*
* @param[in] inData An array of G16R16F values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromG16R16F(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A16B16G16R16F texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
*
* @param[in] inData An array of A16B16G16R16F values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA16B16G16R16F(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a R32F texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
*
* @param[in] inData An array of R32F values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromR32F(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a G32R32F texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
*
* @param[in] inData An array of G32R32F values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromG32R32F(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a A32B32G32R32F texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
*
* @param[in] inData An array of A32B32G32R32F values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromA32B32G32R32F(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a DXT1 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of DXT1 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromDXT1(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a DXT3 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of DXT3 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromDXT3(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Decodes a DXT5 texture buffer to an array of floating-point red, green, blue and alpha values (in this order).
* @note Output color channels are normalized.
*
* @param[in] inData An array of DXT5 values (texture data).
* @param[out] outRGBA Array of decoded floating-point red, green, blue and alpha values (in this order).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertFromDXT5(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a R5G6B5 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of R5G6B5 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToR5G6B5(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A1R5G5B5 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A1R5G5B5 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA1R5G5B5(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A4R4G4B4 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A4R4G4B4 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA4R4G4B4(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a L8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of L8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToL8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A8L8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A8L8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA8L8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a R8G8B8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of R8G8B8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToR8G8B8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a X8R8G8B8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of X8R8G8B8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToX8R8G8B8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A8R8G8B8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A8R8G8B8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA8R8G8B8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A8B8G8R8 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A8B8G8R8 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA8B8G8R8(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a L16 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of L16 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToL16(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a G16R16 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of G16R16 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToG16R16(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A16B16G16R16 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A16B16G16R16 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA16B16G16R16(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a R16F texture buffer.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of R16F values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToR16F(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a G16R16F texture buffer.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of G16R16F values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToG16R16F(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A16B16G16R16F texture buffer.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A16B16G16R16F values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA16B16G16R16F(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a R32F texture buffer.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of R32F values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToR32F(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a G32R32F texture buffer.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of G32R32F values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToG32R32F(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a A32B32G32R32F texture buffer.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of A32B32G32R32F values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToA32B32G32R32F(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a DXT1 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of DXT1 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToDXT1(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a DXT3 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of DXT3 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToDXT3(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Encodes an array of floating-point red, green, blue and alpha values (in this order) into a DXT5 texture buffer.
* @note Input color channels must be normalized.
*
* @param[in] inRGBA Array of floating-point red, green, blue and alpha values (in this order).
* @param[out] outData Array of DXT5 values (texture data).
* @param[in] width Texture width.
* @param[in] height Texture height.
* @param[in] depth Texture depth.
*/
static SYNESTHESIA3D_DLL void ConvertToDXT5(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth = 1);
/**
* @brief Allows convenient usage of "convert from" functions.
*/
typedef void(*ConvertFromFunc)(const s3dByte* const inData, Vec4f* const outRGBA, const unsigned int width, const unsigned int height, const unsigned int depth);
static SYNESTHESIA3D_DLL ConvertFromFunc ConvertFrom[PF_MAX]; /**< @brief "Convert from" function look up table, for convenience. */
/**
* @brief Allows convenient usage of "convert to" functions.
*/
typedef void(*ConvertToFunc)(const Vec4f* const inRGBA, s3dByte* const outData, const unsigned int width, const unsigned int height, const unsigned int depth);
static SYNESTHESIA3D_DLL ConvertToFunc ConvertTo[PF_MAX]; /**< @brief "Convert to" function look up table, for convenience. */
};
}
#endif // COLORUTILITY_H
|
iftodebogdan/GITechDemo
|
GITechDemo/Code/External/Synesthesia3D/Utility/ColorUtility.h
|
C
|
gpl-3.0
| 40,428
|
<!DOCTYPE html>
<html xml:lang="en-GB" lang="en-GB" xmlns="http://www.w3.org/1999/xhtml">
<head lang="en-GB">
<title>Ross Gammon’s Family Tree - Places</title>
<meta charset="UTF-8" />
<meta name ="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=1" />
<meta name ="apple-mobile-web-app-capable" content="yes" />
<meta name="generator" content="Gramps 4.2.8 http://gramps-project.org/" />
<meta name="author" content="" />
<link href="../../../images/favicon2.ico" rel="shortcut icon" type="image/x-icon" />
<link href="../../../css/narrative-screen.css" media="screen" rel="stylesheet" type="text/css" />
<link href="../../../css/narrative-print.css" media="print" rel="stylesheet" type="text/css" />
</head>
<body onload = "initialize();" >
<div id="header">
<h1 id="SiteTitle">Ross Gammon’s Family Tree</h1>
</div>
<div class="wrapper" id="nav" role="navigation">
<div class="container">
<ul class="menu" id="dropmenu">
<li><a href="../../../individuals.html" title="Individuals">Individuals</a></li>
<li><a href="../../../index.html" title="Surnames">Surnames</a></li>
<li><a href="../../../families.html" title="Families">Families</a></li>
<li><a href="../../../events.html" title="Events">Events</a></li>
<li class = "CurrentSection"><a href="../../../places.html" title="Places">Places</a></li>
<li><a href="../../../sources.html" title="Sources">Sources</a></li>
<li><a href="../../../repositories.html" title="Repositories">Repositories</a></li>
<li><a href="../../../media.html" title="Media">Media</a></li>
<li><a href="../../../thumbnails.html" title="Thumbnails">Thumbnails</a></li>
</ul>
</div>
</div>
<div class="content" id="PlaceDetail">
<h3></h3>
<div id="summaryarea">
<table class="infolist place">
<tbody>
<tr>
<td class="ColumnAttribute">Gramps ID</td>
<td class="ColumnValue">P1010</td>
</tr>
</tbody>
</table>
</div>
<div class="subsection" id="references">
<h4>References</h4>
<ol class="Col1" role="Volume-n-Page"type = 1>
<li>
<a href="../../../ppl/b/5/d15f5fe8ee226a795d8a6d5fc5b.html">
ANDERSON, Mary Robina
<span class="grampsid"> [I3936]</span>
</a>
</li>
<li>
<a href="../../../fam/a/6/d15f5fe9a1d2a09419ad85a4e6a.html">
Family of JACKAWAY, Frederick Harold and HODGETTS, Hilda Myrtle
<span class="grampsid"> [F1289]</span>
</a>
</li>
<li>
<a href="../../../fam/5/5/d15f5fe971ecf0303ba7825455.html">
Family of MILLARD, Frederick Vincent and HODGETTS, Florence May
<span class="grampsid"> [F1281]</span>
</a>
</li>
<li>
<a href="../../../ppl/2/3/d15f5fe904050b6fcad861c5132.html">
HODGETTS, Alice Maud
<span class="grampsid"> [I3941]</span>
</a>
</li>
<li>
<a href="../../../ppl/0/a/d15f5fe8e74589cf2b6588cd1a0.html">
HODGETTS, Arthur Thomas
<span class="grampsid"> [I3935]</span>
</a>
</li>
<li>
<a href="../../../ppl/3/d/d15f5fe96ec3f557085ebaee5d3.html">
HODGETTS, Florence May
<span class="grampsid"> [I3964]</span>
</a>
</li>
<li>
<a href="../../../ppl/7/5/d15f5fe99f97affa058a3f89a57.html">
HODGETTS, Hilda Myrtle
<span class="grampsid"> [I3991]</span>
</a>
</li>
<li>
<a href="../../../ppl/c/f/d15f5fe8f337b12ade78bb9ddfc.html">
HODGETTS, Nellie F
<span class="grampsid"> [I3937]</span>
</a>
</li>
<li>
<a href="../../../ppl/6/7/d15f5fe8fb1438bd457216ef876.html">
HODGETTS, Sadie May
<span class="grampsid"> [I3939]</span>
</a>
</li>
<li>
<a href="../../../ppl/e/a/d15f5fe9a296301e1095e4101ae.html">
JACKAWAY, Frederick Harold
<span class="grampsid"> [I3992]</span>
</a>
</li>
<li>
<a href="../../../ppl/2/2/d15f5fe972b2eb0f3bd0268a822.html">
MILLARD, Frederick Vincent
<span class="grampsid"> [I3965]</span>
</a>
</li>
<li>
<a href="../../../ppl/b/c/d15f5fe8f87571a408d510300cb.html">
VORWERK, Albert Alexander
<span class="grampsid"> [I3938]</span>
</a>
</li>
<li>
<a href="../../../ppl/3/7/d15f5fee246263588765ef3b973.html">
VORWERK, Albert Alexander
<span class="grampsid"> [I4358]</span>
</a>
</li>
</ol>
</div>
</div>
<div class="fullclear"></div>
<div id="footer">
<p id="createdate">
Generated by <a href="http://gramps-project.org/">Gramps</a> 4.2.8<br />Last change was the 2015-08-05 19:55:47<br />Created for <a href="../../../ppl/9/e/d15f5fb48902c4fc1b421d249e9.html">GAMMON, Francis</a>
</p>
<p id="copyright">
</p>
</div>
</body>
</html>
|
RossGammon/the-gammons.net
|
RossFamilyTree/plc/2/7/d15f5fe8e9c101a5f1d515b0772.html
|
HTML
|
gpl-3.0
| 4,754
|
// Copyright (C) 2011 - Will Glozer. All rights reserved.
package com.lambdaworks.redis;
import org.junit.Test;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static org.junit.Assert.*;
public class ServerCommandTest extends AbstractCommandTest {
@Test
public void bgrewriteaof() throws Exception {
String msg = "Background append only file rewriting started";
assertEquals(msg, redis.bgrewriteaof());
}
@Test
public void bgsave() throws Exception {
while (redis.info().contains("bgrewriteaof_in_progress:1")) {
Thread.sleep(100);
}
String msg = "Background saving started";
assertEquals(msg, redis.bgsave());
}
@Test
public void clientKill() throws Exception {
Pattern p = Pattern.compile("addr=(\\S+)");
Matcher m = p.matcher(redis.clientList());
assertTrue(m.lookingAt());
assertEquals("OK", redis.clientKill(m.group(1)));
}
@Test
public void clientList() throws Exception {
assertTrue(redis.clientList().contains("addr="));
}
@Test
public void configGet() throws Exception {
assertEquals(list("maxmemory", "0"), redis.configGet("maxmemory"));
}
@Test
public void configResetstat() throws Exception {
redis.get(key);
redis.get(key);
assertEquals("OK", redis.configResetstat());
assertTrue(redis.info().contains("keyspace_misses:0"));
}
@Test
public void configSet() throws Exception {
String maxmemory = redis.configGet("maxmemory").get(1);
assertEquals("OK", redis.configSet("maxmemory", "1024"));
assertEquals("1024", redis.configGet("maxmemory").get(1));
redis.configSet("maxmemory", maxmemory);
}
@Test
public void dbsize() throws Exception {
assertEquals(0, (long) redis.dbsize());
redis.set(key, value);
assertEquals(1, (long) redis.dbsize());
}
@Test
public void debugObject() throws Exception {
redis.set(key, value);
redis.debugObject(key);
}
@Test
public void flushall() throws Exception {
redis.set(key, value);
assertEquals("OK", redis.flushall());
assertNull(redis.get(key));
}
@Test
public void flushdb() throws Exception {
redis.set(key, value);
redis.select(1);
redis.set(key, value + "X");
assertEquals("OK", redis.flushdb());
assertNull(redis.get(key));
redis.select(0);
assertEquals(value, redis.get(key));
}
@Test
public void info() throws Exception {
assertTrue(redis.info().contains("redis_version"));
}
@Test
public void lastsave() throws Exception {
Date start = new Date(System.currentTimeMillis() / 1000);
assertTrue(start.compareTo(redis.lastsave()) <= 0);
}
@Test
public void save() throws Exception {
assertEquals("OK", redis.save());
}
@Test
public void slaveof() throws Exception {
assertEquals("OK", redis.slaveof("localhost", 0));
redis.slaveofNoOne();
}
@Test
public void slaveofNoOne() throws Exception {
assertEquals("OK", redis.slaveofNoOne());
}
@Test
@SuppressWarnings("unchecked")
public void slowlog() throws Exception {
long start = System.currentTimeMillis() / 1000;
assertEquals("OK", redis.configSet("slowlog-log-slower-than", "1"));
assertEquals("OK", redis.slowlogReset());
redis.set(key, value);
List<Object> log = redis.slowlogGet();
assertEquals(2, log.size());
List<Object> entry = (List<Object>) log.get(0);
assertEquals(4, entry.size());
assertTrue(entry.get(0) instanceof Long);
assertTrue((Long) entry.get(1) >= start);
assertTrue(entry.get(2) instanceof Long);
assertEquals(list("SET", key, value), entry.get(3));
entry = (List<Object>) log.get(1);
assertEquals(4, entry.size());
assertTrue(entry.get(0) instanceof Long);
assertTrue((Long) entry.get(1) >= start);
assertTrue(entry.get(2) instanceof Long);
assertEquals(list("SLOWLOG", "RESET"), entry.get(3));
assertEquals(1, redis.slowlogGet(1).size());
assertEquals(4, (long) redis.slowlogLen());
redis.configSet("slowlog-log-slower-than", "0");
}
@Test
public void sync() throws Exception {
assertTrue(redis.sync().startsWith("REDIS"));
}
}
|
nicatronTg/ShankShock-Core
|
wg-lettuce/src/test/java/com/lambdaworks/redis/ServerCommandTest.java
|
Java
|
gpl-3.0
| 4,596
|
#!/bin/bash
#where am i? move to where I am. This ensures source is properly sourced
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR
source ../../config/scripts/drush-create-site/config.cfg
#provide messaging colors for output to console
txtbld=$(tput bold) # Bold
bldgrn=${txtbld}$(tput setaf 2) # green
bldred=${txtbld}$(tput setaf 1) # red
txtreset=$(tput sgr0)
elmslnecho(){
echo "${bldgrn}$1${txtreset}"
}
elmslnwarn(){
echo "${bldred}$1${txtreset}"
}
# Define seconds timestamp
timestamp(){
date +"%s"
}
#test for empty vars. if empty required var -- exit
if [ -z $elmsln ]; then
elmslnwarn "please update your config.cfg file"
exit 1
fi
# to decrease risk of a WSOD when there are significant shifts
# under the hood, we should run RRs prior to the rest of the routine
elmslnecho "Rebuilding registies and caches for all systems"
drush @elmsln rr --y
# run the safe upgrade of projects by taking the site offline then back on
elmslnecho "Running update hooks"
drush @elmsln cook dr_run_updates --y
# run global upgrades from drup recipes
drush @elmsln drup d7_elmsln_global ${elmsln}/scripts/upgrade/drush_recipes/d7/global --y
# load the stacks in question
cd /var/www/elmsln/core/dslmcode/stacks
stacklist=( $(find . -maxdepth 1 -type d | sed 's/\///' | sed 's/\.//') )
for stack in "${stacklist[@]}"
do
elmslnecho "Applying specific upgrades against $stack"
# run stack specific upgrades if they exist
drush @${stack}-all drup d7_elmsln_${stack} ${elmsln}/scripts/upgrade/drush_recipes/d7/${stack} --y
done
# trigger crons to run now that these sites are all back and happy
elmslnecho "Run crons as clean up"
drush @elmsln cron --y
# now loop through and prime the caches on everything
elmslnecho "Seeding caches of all entities"
drush @elmsln ecl --y
|
bigwhirled/elmsln
|
scripts/upgrade/elmsln-upgrade-sites.sh
|
Shell
|
gpl-3.0
| 1,814
|
# -*- coding: utf-8 -*-
# Copyright 2014-2016 Akretion (http://www.akretion.com)
# @author Alexis de Lattre <alexis.delattre@akretion.com>
# Copyright 2016 Sodexis (http://sodexis.com)
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
from openerp import models, fields, api, _
from openerp.exceptions import ValidationError
class ProductProduct(models.Model):
_inherit = 'product.product'
# Link rental service -> rented HW product
rented_product_id = fields.Many2one(
'product.product', string='Related Rented Product',
domain=[('type', 'in', ('product', 'consu'))])
# Link rented HW product -> rental service
rental_service_ids = fields.One2many(
'product.product', 'rented_product_id',
string='Related Rental Services')
@api.one
@api.constrains('rented_product_id', 'must_have_dates', 'type', 'uom_id')
def _check_rental(self):
if self.rented_product_id and self.type != 'service':
raise ValidationError(_(
"The rental product '%s' must be of type 'Service'.")
% self.name)
if self.rented_product_id and not self.must_have_dates:
raise ValidationError(_(
"The rental product '%s' must have the option "
"'Must Have Start and End Dates' checked.")
% self.name)
# In the future, we would like to support all time UoMs
# but it is more complex and requires additionnal developments
day_uom = self.env.ref('product.product_uom_day')
if self.rented_product_id and self.uom_id != day_uom:
raise ValidationError(_(
"The unit of measure of the rental product '%s' must "
"be 'Day'.") % self.name)
@api.multi
def _need_procurement(self):
# Missing self.ensure_one() in the native code !
res = super(ProductProduct, self)._need_procurement()
if not res:
for product in self:
if product.type == 'service' and product.rented_product_id:
return True
# TODO find a replacement for soline.rental_type == 'new_rental')
return res
|
stellaf/sales_rental
|
sale_rental/models/product.py
|
Python
|
gpl-3.0
| 2,194
|
/*
*
* * This file is part of the Hesperides distribution.
* * (https://github.com/voyages-sncf-technologies/hesperides)
* * Copyright (c) 2016 VSCT.
* *
* * Hesperides 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 3.
* *
* * Hesperides is distributed in the hope that it will be useful, but
* * WITHOUT ANY WARRANTY; without even the implied warranty of
* * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* * General Public License for more details.
* *
* * You should have received a copy of the GNU General Public License
* * along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
*/
package com.vsct.dt.hesperides.resources;
/**
* Created by emeric_martineau on 27/10/2015.
*/
@FunctionalInterface
public interface ResponseConverter<E, T> {
T convert(E obj);
}
|
JordanKergoat/hesperides
|
src/main/java/com/vsct/dt/hesperides/resources/ResponseConverter.java
|
Java
|
gpl-3.0
| 968
|
/*
* uget-chrome-wrapper is an extension to integrate uGet Download manager
* with Google Chrome, Chromium, Vivaldi and Opera in Linux and Windows.
*
* Copyright (C) 2016 Gobinath
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var current_browser;
try {
current_browser = browser;
current_browser.runtime.getBrowserInfo().then(
function(info) {
if (info.name === 'Firefox') {
// Do nothing
}
}
);
} catch (ex) {
// Not Firefox
current_browser = chrome;
}
function saveChanges() {
var keywordsToExclude = document.getElementById("keywordsToExclude").value.trim();
var keywordsToInclude = document.getElementById("keywordsToInclude").value.trim();
var interrupt = document.getElementById('chk-interrupt').checked;
var minFileSize = parseInt(document.getElementById("fileSize").value) * 1024;
if (isNaN(minFileSize)) {
minFileSize = 300 * 1024;
} else if(minFileSize < 0) {
minFileSize = -1024; // Which is -1 KB
}
current_browser.runtime.getBackgroundPage(function(backgroundPage) {
backgroundPage.updateKeywords(keywordsToInclude, keywordsToExclude);
backgroundPage.setInterruptDownload(interrupt, true);
backgroundPage.updateMinFileSize(minFileSize);
});
window.close();
}
// When the popup HTML has loaded
window.addEventListener('load', function(evt) {
// Show the system status
current_browser.runtime.getBackgroundPage(function(backgroundPage) {
var state = backgroundPage.getState();
if (state == 0) {
// document.getElementById('info').innerHTML = "Info: Found uGet and uget-chrome-wrapper";
document.getElementById('info').style.display = 'block';
document.getElementById('warn').style.display = 'none';
document.getElementById('error').style.display = 'none';
var element = document.getElementById("element-id");
element.parentNode.removeChild(element);
} else if (state == 1) {
// document.getElementById('warn').innerHTML = "Warning: Please update the uget-chrome-wrapper to the latest version";
document.getElementById('info').style.display = 'none';
document.getElementById('warn').style.display = 'block';
document.getElementById('error').style.display = 'none';
} else {
// document.getElementById('error').innerHTML = "Error: Unable to connect to the uget-chrome-wrapper";
document.getElementById('info').style.display = 'none';
document.getElementById('warn').style.display = 'none';
document.getElementById('error').style.display = 'block';
}
});
let interrupt = (current_browser.storage.sync["uget-interrupt"] == "true");
document.getElementById('save').addEventListener('click', saveChanges);
current_browser.storage.sync.get(function(items) {
document.getElementById('keywordsToExclude').value = items["uget-keywords-exclude"];
document.getElementById('keywordsToInclude').value = items["uget-keywords-include"];
document.getElementById('fileSize').value = parseInt(items["uget-min-file-size"]) / 1024;
document.getElementById('chk-interrupt').checked = items["uget-interrupt"] == "true";
});
});
|
slgobinath/uget-chrome-wrapper
|
extension/popup.js
|
JavaScript
|
gpl-3.0
| 3,640
|
class TranslatePage
include PageObject
page_url 'Special:Translate?<%=params[:extra]%>'
div(:workflow_state, class: 'tux-workflow-status')
ul(:workflow_state_selector, class: 'tux-workflow-status-selector')
end
|
Facerafter/starcitizen-tools
|
extensions/Translate/tests/browser/features/support/pages/translate_page.rb
|
Ruby
|
gpl-3.0
| 221
|
<h1 id="cheat-detection">Cheat Detection</h1>
<p>The Campus Judge uses <strong><a href="http://theory.stanford.edu/~aiken/moss">Moss</a></strong> to detect similar codes. Moss (for a Measure Of Software Similarity) is an automatic system for determining the similarity of programs. To date, the main application of Moss has been in detecting plagiarism in programming classes.</p>
<p>You can send <strong>Final</strong> submitted codes (those selected by students as "Final Submission") to Moss server with one click.</p>
<p>Before using Moss, you must get a <strong>Moss user id</strong> and set your Moss user id in The Campus Judge. Read <a href="http://theory.stanford.edu/~aiken/moss">this page</a> and register for Moss. You will receive a mail containing a perl script. Your user id is in that script.</p>
<p>This is a part of this perl script containing user id:</p>
<div class="sourceCode"><pre class="sourceCode perl"><code class="sourceCode perl">
...
<span class="dt">$server</span> = <span class="kw">'</span><span class="st">moss.stanford.edu</span><span class="kw">'</span>;
<span class="dt">$port</span> = <span class="kw">'</span><span class="st">7690</span><span class="kw">'</span>;
<span class="dt">$noreq</span> = <span class="kw">"</span><span class="st">Request not sent.</span><span class="kw">"</span>;
<span class="dt">$usage</span> = <span class="kw">"</span><span class="st">usage: moss [-x] [-l language] [-d] [-b basefile1] ... [-b basefilen] [-m #] [-c \"string\"] file1 file2 file3 ...</span><span class="kw">"</span>;
<span class="co">#</span>
<span class="co"># The userid is used to authenticate your queries to the server; don't change it!</span>
<span class="co">#</span>
<span class="dt">$userid</span>=YOUR_MOSS_USER_ID;
<span class="co">#</span>
<span class="co"># Process the command line options. This is done in a non-standard</span>
<span class="co"># way to allow multiple -b's.</span>
<span class="co">#</span>
<span class="dt">$opt_l</span> = <span class="kw">"</span><span class="st">c</span><span class="kw">"</span>; <span class="co"># default language is c</span>
<span class="dt">$opt_m</span> = <span class="dv">10</span>;
<span class="dt">$opt_d</span> = <span class="dv">0</span>;
...</code></pre></div>
<p>Find your user id and use it in The Campus Judge for cheat detection. You don't need to put your user id in any file. Just save your user id in The Campus Judge's Moss page and The Campus Judge will use your user id in Moss perl script.</p>
<p>Your server must have <code>perl</code> installed to use Moss.</p>
<p>It is recommended to detect similar codes after assignment finishes. Because The Campus Judge just sends <strong>Final</strong> submissions to Moss and students can change their <strong>Final</strong> submissions before assignment finishes.</p>
|
shubham1559/The-Campus-Judge
|
docs/html/moss.html
|
HTML
|
gpl-3.0
| 2,902
|
# coding=utf-8
Version = "0.2.0"
Description = "LOTRO/DDO Launcher"
Author = "Alan Jackson"
Email = "ajackson@bcs.org.uk"
WebSite = "http://www.lotrolinux.com"
LongDescription = "Lord of the Rings Online and Dungeons & Dragons Online\nLauncher for Linux & Mac OS X"
Copyright=" (C) 2009-2010 AJackson"
CLIReference = "Based on CLI launcher for LOTRO\n(C) 2007-2010 SNy"
LotROLinuxReference = "Based on LotROLinux\n(C) 2007-2009 AJackson"
|
Lynx3d/pylotro
|
PyLotROLauncher/Information.py
|
Python
|
gpl-3.0
| 441
|
{- To ensure GHC evalutes attributes the right number of times we disable the CSE optimisation -}
{-# OPTIONS_GHC -fno-cse #-}
{-# LANGUAGE DeriveDataTypeable #-}
module Data.Config.Args
( Args(..)
, defArgs
, etcConfig
) where
import System.Console.CmdArgs
newtype Args = Args { configPath :: Maybe String
} deriving (Show, Data, Typeable)
defArgs :: Args
defArgs = Args { configPath = def }
etcConfig :: String
etcConfig = "/etc/security-log/config.yaml"
|
retep007/security-log
|
src/Data/Config/Args.hs
|
Haskell
|
gpl-3.0
| 483
|
package com.fr.design.mainframe.widget.editors;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.ArrayList;
import java.util.List;
import javax.swing.*;
import com.fr.design.data.DesignTableDataManager;
import com.fr.data.TableDataSource;
import com.fr.design.data.datapane.TableDataComboBox;
import com.fr.design.gui.icombobox.UIComboBoxRenderer;
import com.fr.design.gui.icombobox.LazyComboBox;
import com.fr.design.layout.FRGUIPaneFactory;
import com.fr.design.editor.editor.Editor;
import com.fr.form.data.DataBinding;
import com.fr.general.Inter;
/**
* DataBindingEditor
*
* @editor zhou
* @since 2012-3-29下午5:26:28
*/
public class DataBindingEditor extends Editor<DataBinding> {
private final static int HORI_GAP = 1;
private final static int VER_GAP = 7;
private TableDataComboBox tableDataComboBox;
private LazyComboBox columnNameComboBox;
private ItemListener tableDataComboBoxListener = new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
boolean isInit = columnNameComboBox.getSelectedIndex() == -1;
columnNameComboBox.loadList();
if (columnNameComboBox.getItemCount() > 0) {
columnNameComboBox.setSelectedIndex(0);
}
if (!isInit && !stopEvent) {
DataBindingEditor.this.fireStateChanged();
}
}
};
private ItemListener columnNameComboboxListener = new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if (DataBindingEditor.this.getValue() != DataBinding.empty && e.getStateChange() == ItemEvent.SELECTED) {
DataBindingEditor.this.fireStateChanged();
}
}
};
private boolean stopEvent = false;
public DataBindingEditor() {
this.initCompontents();
this.setName(Inter.getLocText("FR-Designer_Widget_Field"));
}
private void initCompontents() {
this.setLayout(new BorderLayout(HORI_GAP, VER_GAP));
tableDataComboBox = new TableDataComboBox(getTableDataSource());
tableDataComboBox.setPreferredSize(new Dimension(55, 20));
tableDataComboBox.addItemListener(tableDataComboBoxListener);
columnNameComboBox = new LazyComboBox() {
@Override
public Object[] load() {
List<String> l = calculateColumnNameList();
return l.toArray(new String[l.size()]);
}
};
columnNameComboBox.setRenderer(new UIComboBoxRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected,
boolean cellHasFocus) {
JLabel label = (JLabel) super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
label.setToolTipText(value == null ? null : value.toString());
return label;
}
});
columnNameComboBox.setEditable(true);
this.add(tableDataComboBox, BorderLayout.NORTH);
this.add(columnNameComboBox, BorderLayout.CENTER);
columnNameComboBox.addItemListener(columnNameComboboxListener);
}
protected TableDataSource getTableDataSource() {
return DesignTableDataManager.getEditingTableDataSource();
}
private List<String> calculateColumnNameList() {
if (this.tableDataComboBox.getSelectedItem() != null) {
List<String> list = this.tableDataComboBox.getSelectedItem().calculateColumnNameList();
if (list != null) {
return list;
}
}
return new ArrayList<String>();
}
@Override
/**
* get value
*/
public DataBinding getValue() {
if (this.tableDataComboBox.getSelectedItem() == null || this.columnNameComboBox.getSelectedItem() == null) {
return DataBinding.empty;
}
return new DataBinding(this.tableDataComboBox.getSelectedItem().getTableDataName(), (String) this.columnNameComboBox.getSelectedItem());
}
@Override
/**
* set value
*/
public void setValue(DataBinding value) {
if (value == null) {
return;
}
stopEvent = true;
tableDataComboBox.removeItemListener(tableDataComboBoxListener);
columnNameComboBox.removeItemListener(columnNameComboboxListener);
tableDataComboBox.setSelectedTableDataByName(value.getDataSourceName());
columnNameComboBox.setSelectedItem(value.getDataBindingKey());
tableDataComboBox.addItemListener(tableDataComboBoxListener);
columnNameComboBox.addItemListener(columnNameComboboxListener);
stopEvent = false;
}
/**
* 是否是支持的类型
* @param object 需要被判断的object
* @return 如果是,返回true
*/
public boolean accept(Object object) {
return object instanceof DataBinding;
}
public String getIconName() {
return "bind_ds_column";
}
}
|
fanruan/finereport-design
|
designer_base/src/com/fr/design/mainframe/widget/editors/DataBindingEditor.java
|
Java
|
gpl-3.0
| 5,366
|
/*
* 02/06/2011
*
* ActiveLineRangeListener.java - Listens for "active line range" changes
* in an RSyntaxTextArea.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package com.fr.design.gui.syntax.ui.rsyntaxtextarea;
import java.util.EventListener;
/**
* Listens for "active line range" events from an <code>RSyntaxTextArea</code>.
* If a text area contains some semantic knowledge of the programming language
* being edited, it may broadcast {@link ActiveLineRangeEvent}s whenever the
* caret moves into a new "block" of code. Listeners can listen for these
* events and respond accordingly.<p>
*
* See the <code>RSTALanguageSupport</code> project at
* <a href="http://fifesoft.com">http://fifesoft.com</a> for some
* <code>LanguageSupport</code> implementations that may broadcast these
* events. Note that if an RSTA/LanguageSupport does not support broadcasting
* these events, the listener will simply never receive any notifications.
*
* @author Robert Futrell
* @version 1.0
*/
public interface ActiveLineRangeListener extends EventListener {
/**
* Called whenever the "active line range" changes.
*
* @param e Information about the line range change. If there is no longer
* an "active line range," the "minimum" and "maximum" line values
* should both be <code>-1</code>.
*/
public void activeLineRangeChanged(ActiveLineRangeEvent e);
}
|
fanruan/finereport-design
|
designer_base/src/com/fr/design/gui/syntax/ui/rsyntaxtextarea/ActiveLineRangeListener.java
|
Java
|
gpl-3.0
| 1,491
|
<?php
/**
* @package Mautic
* @copyright 2014 Mautic Contributors. All rights reserved.
* @author Mautic
* @link http://mautic.org
* @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html
*/
$view->extend('MauticCoreBundle:Default:content.html.php');
$view['slots']->set('mauticContent', 'client');
$id = $form->vars['data']->getId();
if (!empty($id)) {
$name = $form->vars['data']->getName();
$header = $view['translator']->trans('mautic.api.client.header.edit', array("%name%" => $name));
} else {
$header = $view['translator']->trans('mautic.api.client.header.new');
}
$view['slots']->set("headerTitle", $header);
?>
<div class="box-layout">
<div class="col-md-9 bg-auto height-auto bdr-r">
<div class="pa-md">
<?php echo $view['form']->form($form); ?>
</div>
</div>
</div>
|
MAT978/mautic
|
app/bundles/ApiBundle/Views/Client/form.html.php
|
PHP
|
gpl-3.0
| 860
|
/* mconf.h
*
* Common include file for math routines
*
*
*
* SYNOPSIS:
*
* #include "mconf.h"
*
*
*
* DESCRIPTION:
*
* This file contains definitions for error codes that are
* passed to the common error handling routine mtherr()
* (which see).
*
* The file also includes a conditional assembly definition
* for the type of computer arithmetic (IEEE, DEC, Motorola
* IEEE, or UNKnown).
*
* For Digital Equipment PDP-11 and VAX computers, certain
* IBM systems, and others that use numbers with a 56-bit
* significand, the symbol DEC should be defined. In this
* mode, most floating point constants are given as arrays
* of octal integers to eliminate decimal to binary conversion
* errors that might be introduced by the compiler.
*
* For little-endian computers, such as IBM PC, that follow the
* IEEE Standard for Binary Floating Point Arithmetic (ANSI/IEEE
* Std 754-1985), the symbol IBMPC should be defined. These
* numbers have 53-bit significands. In this mode, constants
* are provided as arrays of hexadecimal 16 bit integers.
*
* Big-endian IEEE format is denoted MIEEE. On some RISC
* systems such as Sun SPARC, double precision constants
* must be stored on 8-byte address boundaries. Since integer
* arrays may be aligned differently, the MIEEE configuration
* may fail on such machines.
*
* To accommodate other types of computer arithmetic, all
* constants are also provided in a normal decimal radix
* which one can hope are correctly converted to a suitable
* format by the available C language compiler. To invoke
* this mode, define the symbol UNK.
*
* An important difference among these modes is a predefined
* set of machine arithmetic constants for each. The numbers
* MACHEP (the machine roundoff error), MAXNUM (largest number
* represented), and several other parameters are preset by
* the configuration symbol. Check the file const.c to
* ensure that these values are correct for your computer.
*
* Configurations NANS, INFINITIES, MINUSZERO, and DENORMAL
* may fail on many systems. Verify that they are supposed
* to work on your computer.
*/
/*
Cephes Math Library Release 2.3: June, 1995
Copyright 1984, 1987, 1989, 1995 by Stephen L. Moshier
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 <ORGANIZATION> nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
/* Define if the `long double' type works. */
//#define HAVE_LONG_DOUBLE 0
/* Define as the return type of signal handlers (int or void). */
#define RETSIGTYPE void
/* Define if you have the ANSI C header files. */
#define STDC_HEADERS 1
/* Define if your processor stores words with the most significant
byte first (like Motorola and SPARC, unlike Intel and VAX). */
/* #undef WORDS_BIGENDIAN */
/* Define if floating point words are bigendian. */
/* #undef FLOAT_WORDS_BIGENDIAN */
/* The number of bytes in a int. */
#define SIZEOF_INT 4
/* Define if you have the <string.h> header file. */
#define HAVE_STRING_H 1
/* Name of package */
#define PACKAGE "cephes"
/* Version number of package */
#define VERSION "2.7"
/* Constant definitions for math error conditions
*/
#define DOMAIN 1 /* argument domain error */
#define SING 2 /* argument singularity */
#define OVERFLOW 3 /* overflow range error */
#define UNDERFLOW 4 /* underflow range error */
#define TLOSS 5 /* total loss of precision */
#define PLOSS 6 /* partial loss of precision */
#define EDOM 33
#define ERANGE 34
/* Complex numeral. */
typedef struct
{
double r;
double i;
} cmplx;
#ifdef HAVE_LONG_DOUBLE
/* Long double complex numeral. */
typedef struct
{
long double r;
long double i;
} cmplxl;
#endif
/* Type of computer arithmetic */
/* PDP-11, Pro350, VAX:
*/
/* #define DEC 1 */
/* Intel IEEE, low order words come first:
*/
//#define IBMPC 1
/* Motorola IEEE, high order words come first
* (Sun 680x0 workstation):
*/
/* #define MIEEE 1 */
/* UNKnown arithmetic, invokes coefficients given in
* normal decimal format. Beware of range boundary
* problems (MACHEP, MAXLOG, etc. in const.c) and
* roundoff problems in pow.c:
* (Sun SPARCstation)
*/
#define UNK 1
/* If you define UNK, then be sure to set BIGENDIAN properly. */
#ifdef FLOAT_WORDS_BIGENDIAN
#define BIGENDIAN 1
#else
#define BIGENDIAN 0
#endif
/* Define this `volatile' if your compiler thinks
* that floating point arithmetic obeys the associative
* and distributive laws. It will defeat some optimizations
* (but probably not enough of them).
*
* #define VOLATILE volatile
*/
#define VOLATILE
/* For 12-byte long doubles on an i386, pad a 16-bit short 0
* to the end of real constants initialized by integer arrays.
*
* #define XPD 0,
*
* Otherwise, the type is 10 bytes long and XPD should be
* defined blank (e.g., Microsoft C).
*
* #define XPD
*/
#define XPD 0,
/* Define to support tiny denormal numbers, else undefine. */
#define DENORMAL 1
/* Define to ask for infinity support, else undefine. */
#define INFINITIES 1
/* Define to ask for support of numbers that are Not-a-Number,
else undefine. This may automatically define INFINITIES in some files. */
#define NANS 1
/* Define to distinguish between -0.0 and +0.0. */
#define MINUSZERO 1
/* Define 1 for ANSI C atan2() function
See atan.c and clog.c. */
#define ANSIC 1
/* Get ANSI function prototypes, if you want them. */
#if 1
/* #ifdef __STDC__ */
#define ANSIPROT 1
int mtherr ( char *, int );
#else
int mtherr();
#endif
/* Variable for error reporting. See mtherr.c. */
extern int merror;
|
Xane123/MaryMagicalAdventure
|
src/utility/math/mconf.h
|
C
|
gpl-3.0
| 6,879
|
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<style>
table.head, table.foot { width: 100%; }
td.head-rtitle, td.foot-os { text-align: right; }
td.head-vol { text-align: center; }
table.foot td { width: 50%; }
table.head td { width: 33%; }
div.spacer { margin: 1em 0; }
</style>
<title>
SOCKATMARK(3P)</title>
</head>
<body>
<div class="mandoc">
<table class="head">
<tbody>
<tr>
<td class="head-ltitle">
SOCKATMARK(3P)</td>
<td class="head-vol">
POSIX Programmer's Manual</td>
<td class="head-rtitle">
SOCKATMARK(3P)</td>
</tr>
</tbody>
</table>
<div class="section">
<h1>PROLOG</h1> This manual page is part of the POSIX Programmer's Manual. The Linux implementation of this interface may differ (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not be implemented on Linux.<div style="height: 1.00em;">
 </div>
</div>
<div class="section">
<h1>NAME</h1> sockatmark — determine whether a socket is at the out-of-band mark</div>
<div class="section">
<h1>SYNOPSIS</h1><br/>
#include <sys/socket.h><div class="spacer">
</div>
int sockatmark(int <i>s</i>);<br/>
</div>
<div class="section">
<h1>DESCRIPTION</h1> The <i>sockatmark</i>() function shall determine whether the socket specified by the descriptor <i>s</i> is at the out-of-band data mark (see <i>Section 2.10.12</i>, <i>Socket Out-of-Band Data State</i>). If the protocol for the socket supports out-of-band data by marking the stream with an out-of-band data mark, the <i>sockatmark</i>() function shall return 1 when all data preceding the mark has been read and the out-of-band data mark is the first element in the receive queue. The <i>sockatmark</i>() function shall not remove the mark from the stream.</div>
<div class="section">
<h1>RETURN VALUE</h1> Upon successful completion, the <i>sockatmark</i>() function shall return a value indicating whether the socket is at an out-of-band data mark. If the protocol has marked the data stream and all data preceding the mark has been read, the return value shall be 1; if there is no mark, or if data precedes the mark in the receive queue, the <i>sockatmark</i>() function shall return 0. Otherwise, it shall return a value of −1 and set <i>errno</i> to indicate the error.</div>
<div class="section">
<h1>ERRORS</h1> The <i>sockatmark</i>() function shall fail if:<dl>
<dt>
<b>EBADF</b></dt>
<dd>
The <i>s</i> argument is not a valid file descriptor.</dd>
</dl>
<dl>
<dt>
<b>ENOTTY</b></dt>
<dd>
The file associated with the <i>s</i> argument is not a socket.</dd>
</dl>
<div class="spacer">
</div>
<i>The following sections are informative.</i></div>
<div class="section">
<h1>EXAMPLES</h1> None.</div>
<div class="section">
<h1>APPLICATION USAGE</h1> The use of this function between receive operations allows an application to determine which received data precedes the out-of-band data and which follows the out-of-band data.<div class="spacer">
</div>
There is an inherent race condition in the use of this function. On an empty receive queue, the current read of the location might well be at the ``mark'', but the system has no way of knowing that the next data segment that will arrive from the network will carry the mark, and <i>sockatmark</i>() will return false, and the next read operation will silently consume the mark.<div class="spacer">
</div>
Hence, this function can only be used reliably when the application already knows that the out-of-band data has been seen by the system or that it is known that there is data waiting to be read at the socket (via SIGURG or <i>select</i>()). See <i>Section 2.10.11</i>, <i>Socket Receive Queue</i>, <i>Section 2.10.12</i>, <i>Socket Out-of-Band Data State</i>, <i>Section 2.10.14</i>, <i>Signals</i>, and <i>pselect</i>() for details.</div>
<div class="section">
<h1>RATIONALE</h1> The <i>sockatmark</i>() function replaces the historical SIOCATMARK command to <i>ioctl</i>() which implemented the same functionality on many implementations. Using a wrapper function follows the adopted conventions to avoid specifying commands to the <i>ioctl</i>() function, other than those now included to support XSI STREAMS. The <i>sockatmark</i>() function could be implemented as follows:<div style="height: 1.00em;">
 </div>
<div style="margin-left: 4.00ex;">
<br/>
<b></b><br/>
<b>#include <sys/ioctl.h></b><div class="spacer">
</div>
int sockatmark(int s)<br/>
{<br/>
int val;<br/>
if (ioctl(s,SIOCATMARK,&val)==−1)<br/>
return(−1);<br/>
return(val);<br/>
}<br/>
</div>
<div class="spacer">
</div>
The use of <b>[ENOTTY]</b> to indicate an incorrect descriptor type matches the historical behavior of SIOCATMARK.</div>
<div class="section">
<h1>FUTURE DIRECTIONS</h1> None.</div>
<div class="section">
<h1>SEE ALSO</h1> <i>Section 2.10.12</i>, <i>Socket Out-of-Band Data State</i>, <i><i>pselect</i>()</i>, <i><i>recv</i>()</i>, <i><i>recvmsg</i>()</i><div class="spacer">
</div>
The Base Definitions volume of POSIX.1‐2008, <i><b><sys_socket.h></b></i></div>
<div class="section">
<h1>COPYRIGHT</h1> Portions of this text are reprinted and reproduced in electronic form from IEEE Std 1003.1, 2013 Edition, Standard for Information Technology -- Portable Operating System Interface (POSIX), The Open Group Base Specifications Issue 7, Copyright (C) 2013 by the Institute of Electrical and Electronics Engineers, Inc and The Open Group. (This is POSIX.1-2008 with the 2013 Technical Corrigendum 1 applied.) In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at http://www.unix.org/online.html .<div style="height: 1.00em;">
 </div>
Any typographical or formatting errors that appear in this page are most likely to have been introduced during the conversion of the source files to man page format. To report such errors, see https://www.kernel.org/doc/man-pages/reporting_bugs.html .</div>
<table class="foot">
<tr>
<td class="foot-date">
2013</td>
<td class="foot-os">
IEEE/The Open Group</td>
</tr>
</table>
</div>
</body>
</html>
|
fusion809/fusion809.github.io-old
|
man/sockatmark.3p.html
|
HTML
|
gpl-3.0
| 6,229
|
using CNCMaps.FileFormats;
namespace CNCMaps.Engine.Types {
public class SuperWeaponType : AbstractType {
// rules
public WeaponType WeaponType;
public Action Action;
public bool IsPowered;
public bool DisableableFromShell;
public int SidebarFlashTabFrames;
public bool AIDefendAgainst;
public bool PreClick;
public bool PostClick;
public bool ShowTimer;
public Sound SpecialSound;
public Sound StartSound;
public float Range;
public int LineMultiplier;
public AbstractType Type;
public WeaponType PreDependent;
public BuildingType AuxBuilding;
public bool UseChargeDrain;
public bool ManualControl;
public float RechargeTime;
public string SidebarImage;
public SuperWeaponType(string ID) : base(ID) { }
public override void LoadRules(IniFile.IniSection rules) {
base.LoadRules(rules);
WeaponType = rules.ReadEnum<WeaponType>("WeaponType", null);
Action = rules.ReadEnum<Action>("Action", Action.MultiMissile);
IsPowered = rules.ReadBool("IsPowered", true);
DisableableFromShell = rules.ReadBool("DisableableFromShell");
SidebarFlashTabFrames = rules.ReadInt("SidebarFlashTabFrames", -1);
AIDefendAgainst = rules.ReadBool("AIDefendAgainst");
PreClick = rules.ReadBool("PreClick");
PostClick = rules.ReadBool("PostClick");
ShowTimer = rules.ReadBool("ShowTimer");
SpecialSound = Get<Sound>(rules.ReadString("SpecialSound"));
StartSound = Get<Sound>(rules.ReadString("StartSound"));
Range = rules.ReadFloat("Range", 0);
LineMultiplier = rules.ReadInt("LineMultiplier", 0);
Type = rules.ReadEnum<AbstractType>("Type", null);
PreDependent = rules.ReadEnum<WeaponType>("PreDependent", null);
AuxBuilding = Get<BuildingType>(rules.ReadString("AuxBuilding"));
UseChargeDrain = rules.ReadBool("UseChargeDrain");
ManualControl = rules.ReadBool("ManualControl");
RechargeTime = rules.ReadFloat("RechargeTime", 5.0f);
SidebarImage = rules.ReadString("SidebarImage", "");
}
}
}
|
zzattack/ccmaps-net
|
CNCMaps.Engine/Types/SuperWeaponType.cs
|
C#
|
gpl-3.0
| 2,048
|
<?php
/*
* Copyright 2014 REI Systems, Inc.
*
* This file is part of GovDashboard.
*
* GovDashboard is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* GovDashboard 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 GovDashboard. If not, see <http://www.gnu.org/licenses/>.
*/
namespace GD\Security\Authorization\Role;
class DrupalRole extends AbstractRole {}
|
REI-Systems/GovDashboard-Community
|
webapp/sites/all/modules/custom/security/lib/GD/Security/Authorization/Role/DrupalRole.php
|
PHP
|
gpl-3.0
| 827
|
n=int(input('Enter any number: '))
if n%2!=0:
n=n+1
for i in range(n):
for j in range(n):
if (i==int(n/2)) or j==int(n/2) or ((i==0)and (j>=int(n/2))) or ((j==0)and (i<=int(n/2))) or ((j==n-1)and (i>=int(n/2))) or ((i==n-1)and (j<=int(n/2))):
print('*',end='')
else:
print(' ',end='')
print()
|
rohitjogson/pythonwork
|
assign27.09.py
|
Python
|
gpl-3.0
| 355
|
#!/bin/sh
# Temperature.sh
# Promus
# Copyright © 2013 by Johannes Frotscher.
# tempus=`ioreg -l | grep "IOHWSensors" | grep "current-value" | head -n 1 | awk -F ",\"current-value" '{print $2}' | awk -F ",\"sensor-flags" '{print $1}' | tr -d "\"=" | awk '{print((($1/65536)-32)*5/9)}'`
# printable=`printf "%.1f\n" "$tempus"`
echo 'Temp: ' $printable C
|
Promus/Promus
|
Promus.app/Contents/Resources/Temperature.sh
|
Shell
|
gpl-3.0
| 379
|
namespace OmniXaml.Parsers
{
using System;
public class XamlParseException : Exception
{
public XamlParseException(string message) : base(message)
{
}
}
}
|
danwalmsley/OmniXaml
|
OmniXaml/OmniXaml/Parsers/XamlParseException.cs
|
C#
|
gpl-3.0
| 195
|
/*
* gpio-watch, a tool for running scripts in response to gpio events
* Copyright (C) 2014 Lars Kellogg-Stedman <lars@oddbit.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _GPIO_H
#define _GPIO_H
#define EDGE_NONE 0
#define EDGE_RISING 1
#define EDGE_FALLING 2
#define EDGE_BOTH 3
#define EDGE_SWITCH 4
#define EDGESTRLEN 8
#define DIRECTION_IN 0
#define DIRECTION_OUT 1
#define EDGESTRLEN 8
#define DIRSTRLEN 4
#define GPIODIRLEN 8
#ifndef GPIO_BASE
#define GPIO_BASE "/sys/class/gpio"
#endif
struct pin {
int pin;
int edge;
};
int parse_direction(const char *direction);
int parse_edge(const char *edge);
void pin_export(int pin);
int pin_set_edge(int pin, int edge);
int pin_set_direction(int pin, int direction);
#endif // _GPIO_H
|
larsks/gpio-watch
|
gpio.h
|
C
|
gpl-3.0
| 1,368
|
Ext.define('Omni.view.bin_skus.Inspector', {
extend:'Buildit.ux.inspector.Panel',
alias:'widget.omni-bin_skus-Inspector',
initComponent:function () {
var me = this;
// LABELS (Start) ======================================================================
// LABELS (End)
// INSPECTOR INIT (Start) ==============================================================
Ext.applyIf(this, {
associativeFilter: {
property: 'bin_sku_id',
value: me.record.get('bin_sku_id')
}
});
// INSPECTOR INIT (End)
// CARDS (Start) =======================================================================
Ext.apply(this, {
cards: [
{
title: 'Profile',
xtype: 'omni-bin_skus-Form'
}
]
});
// CARDS (End)
// TITLES (Start) ======================================================================
Ext.apply(this, {
title: 'Bin Sku',
subtitle: this.record.get('display')
});
// TITLES (End)
this.callParent();
}
});
|
tunacasserole/omni
|
app/assets/javascripts/omni/view/bin_skus/Inspector.js
|
JavaScript
|
gpl-3.0
| 1,081
|
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.18444
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace TrovoSiteSearch.SP2010QueryServiceProxy {
using System.Data;
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(Namespace="http://microsoft.com/webservices/OfficeServer/QueryService", ConfigurationName="SP2010QueryServiceProxy.QueryServiceSoap")]
public interface QueryServiceSoap {
// CODEGEN: Generating message contract since the wrapper namespace (urn:Microsoft.Search) of message QueryRequest does not match the default value (http://microsoft.com/webservices/OfficeServer/QueryService)
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/Query", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
TrovoSiteSearch.SP2010QueryServiceProxy.QueryResponse Query(TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest request);
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/Query", ReplyAction="*")]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.QueryResponse> QueryAsync(TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/QueryEx", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
System.Data.DataSet QueryEx(string queryXml);
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/QueryEx", ReplyAction="*")]
System.Threading.Tasks.Task<System.Data.DataSet> QueryExAsync(string queryXml);
// CODEGEN: Generating message contract since the wrapper namespace (urn:Microsoft.Search) of message RegistrationRequest does not match the default value (http://microsoft.com/webservices/OfficeServer/QueryService)
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/Registration", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationResponse Registration(TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest request);
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/Registration", ReplyAction="*")]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationResponse> RegistrationAsync(TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest request);
// CODEGEN: Generating message contract since the wrapper namespace (urn:Microsoft.Search) of message StatusRequest does not match the default value (http://microsoft.com/webservices/OfficeServer/QueryService)
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/Status", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
TrovoSiteSearch.SP2010QueryServiceProxy.StatusResponse Status(TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest request);
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/Status", ReplyAction="*")]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.StatusResponse> StatusAsync(TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/GetPortalSearchInfo", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
string GetPortalSearchInfo();
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/GetPortalSearchInfo", ReplyAction="*")]
System.Threading.Tasks.Task<string> GetPortalSearchInfoAsync();
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/GetSearchMetadata", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
System.Data.DataSet GetSearchMetadata();
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/GetSearchMetadata", ReplyAction="*")]
System.Threading.Tasks.Task<System.Data.DataSet> GetSearchMetadataAsync();
// CODEGEN: Generating message contract since the wrapper namespace (urn:Microsoft.Search) of message RecordClickRequest does not match the default value (http://microsoft.com/webservices/OfficeServer/QueryService)
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/RecordClick", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickResponse RecordClick(TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest request);
[System.ServiceModel.OperationContractAttribute(Action="urn:Microsoft.Search/RecordClick", ReplyAction="*")]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickResponse> RecordClickAsync(TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest request);
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/GetQuerySuggestions", ReplyAction="*")]
[System.ServiceModel.XmlSerializerFormatAttribute(SupportFaults=true)]
string[] GetQuerySuggestions(string queryXml);
[System.ServiceModel.OperationContractAttribute(Action="http://microsoft.com/webservices/OfficeServer/QueryService/GetQuerySuggestions", ReplyAction="*")]
System.Threading.Tasks.Task<string[]> GetQuerySuggestionsAsync(string queryXml);
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="Query", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class QueryRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:Microsoft.Search", Order=0)]
public string queryXml;
public QueryRequest() {
}
public QueryRequest(string queryXml) {
this.queryXml = queryXml;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="QueryResponse", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class QueryResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:Microsoft.Search", Order=0)]
public string QueryResult;
public QueryResponse() {
}
public QueryResponse(string QueryResult) {
this.QueryResult = QueryResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="Registration", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class RegistrationRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:Microsoft.Search", Order=0)]
public string registrationXml;
public RegistrationRequest() {
}
public RegistrationRequest(string registrationXml) {
this.registrationXml = registrationXml;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="RegistrationResponse", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class RegistrationResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:Microsoft.Search", Order=0)]
public string RegistrationResult;
public RegistrationResponse() {
}
public RegistrationResponse(string RegistrationResult) {
this.RegistrationResult = RegistrationResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="Status", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class StatusRequest {
public StatusRequest() {
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="StatusResponse", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class StatusResponse {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:Microsoft.Search", Order=0)]
public string StatusResult;
public StatusResponse() {
}
public StatusResponse(string StatusResult) {
this.StatusResult = StatusResult;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="RecordClick", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class RecordClickRequest {
[System.ServiceModel.MessageBodyMemberAttribute(Namespace="urn:Microsoft.Search", Order=0)]
public string clickInfoXml;
public RecordClickRequest() {
}
public RecordClickRequest(string clickInfoXml) {
this.clickInfoXml = clickInfoXml;
}
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
[System.ServiceModel.MessageContractAttribute(WrapperName="RecordClickResponse", WrapperNamespace="urn:Microsoft.Search", IsWrapped=true)]
public partial class RecordClickResponse {
public RecordClickResponse() {
}
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface QueryServiceSoapChannel : TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class QueryServiceSoapClient : System.ServiceModel.ClientBase<TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap>, TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap {
public QueryServiceSoapClient() {
}
public QueryServiceSoapClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public QueryServiceSoapClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public QueryServiceSoapClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public QueryServiceSoapClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
TrovoSiteSearch.SP2010QueryServiceProxy.QueryResponse TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.Query(TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest request) {
return base.Channel.Query(request);
}
public string Query(string queryXml) {
TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest();
inValue.queryXml = queryXml;
TrovoSiteSearch.SP2010QueryServiceProxy.QueryResponse retVal = ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).Query(inValue);
return retVal.QueryResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.QueryResponse> TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.QueryAsync(TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest request) {
return base.Channel.QueryAsync(request);
}
public System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.QueryResponse> QueryAsync(string queryXml) {
TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.QueryRequest();
inValue.queryXml = queryXml;
return ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).QueryAsync(inValue);
}
public System.Data.DataSet QueryEx(string queryXml) {
return base.Channel.QueryEx(queryXml);
}
public System.Threading.Tasks.Task<System.Data.DataSet> QueryExAsync(string queryXml) {
return base.Channel.QueryExAsync(queryXml);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationResponse TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.Registration(TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest request) {
return base.Channel.Registration(request);
}
public string Registration(string registrationXml) {
TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest();
inValue.registrationXml = registrationXml;
TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationResponse retVal = ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).Registration(inValue);
return retVal.RegistrationResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationResponse> TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.RegistrationAsync(TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest request) {
return base.Channel.RegistrationAsync(request);
}
public System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationResponse> RegistrationAsync(string registrationXml) {
TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.RegistrationRequest();
inValue.registrationXml = registrationXml;
return ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).RegistrationAsync(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
TrovoSiteSearch.SP2010QueryServiceProxy.StatusResponse TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.Status(TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest request) {
return base.Channel.Status(request);
}
public string Status() {
TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest();
TrovoSiteSearch.SP2010QueryServiceProxy.StatusResponse retVal = ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).Status(inValue);
return retVal.StatusResult;
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.StatusResponse> TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.StatusAsync(TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest request) {
return base.Channel.StatusAsync(request);
}
public System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.StatusResponse> StatusAsync() {
TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.StatusRequest();
return ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).StatusAsync(inValue);
}
public string GetPortalSearchInfo() {
return base.Channel.GetPortalSearchInfo();
}
public System.Threading.Tasks.Task<string> GetPortalSearchInfoAsync() {
return base.Channel.GetPortalSearchInfoAsync();
}
public System.Data.DataSet GetSearchMetadata() {
return base.Channel.GetSearchMetadata();
}
public System.Threading.Tasks.Task<System.Data.DataSet> GetSearchMetadataAsync() {
return base.Channel.GetSearchMetadataAsync();
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickResponse TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.RecordClick(TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest request) {
return base.Channel.RecordClick(request);
}
public void RecordClick(string clickInfoXml) {
TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest();
inValue.clickInfoXml = clickInfoXml;
TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickResponse retVal = ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).RecordClick(inValue);
}
[System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)]
System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickResponse> TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap.RecordClickAsync(TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest request) {
return base.Channel.RecordClickAsync(request);
}
public System.Threading.Tasks.Task<TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickResponse> RecordClickAsync(string clickInfoXml) {
TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest inValue = new TrovoSiteSearch.SP2010QueryServiceProxy.RecordClickRequest();
inValue.clickInfoXml = clickInfoXml;
return ((TrovoSiteSearch.SP2010QueryServiceProxy.QueryServiceSoap)(this)).RecordClickAsync(inValue);
}
public string[] GetQuerySuggestions(string queryXml) {
return base.Channel.GetQuerySuggestions(queryXml);
}
public System.Threading.Tasks.Task<string[]> GetQuerySuggestionsAsync(string queryXml) {
return base.Channel.GetQuerySuggestionsAsync(queryXml);
}
}
}
|
TrovoLtd/TESSDotNet
|
src/TESSDotNet/TrovoSiteSearch/Service References/SP2010QueryServiceProxy/Reference.cs
|
C#
|
gpl-3.0
| 21,355
|
#include "soc_common.h"
#include <errno.h>
#include <fcntl.h>
#include <stdarg.h>
#include <sys/ioctl.h>
int ioctl(int sockfd, int request, ...)
{
int ret;
int flags;
int *value;
va_list ap;
sockfd = soc_get_fd(sockfd);
if(sockfd < 0) {
errno = -sockfd;
return -1;
}
switch(request) {
case FIONBIO:
va_start(ap, request);
value = va_arg(ap, int*);
va_end(ap);
if(value == NULL) {
errno = EFAULT;
return -1;
}
flags = fcntl(sockfd, F_GETFL, 0);
if(flags == -1)
return -1;
if(*value)
ret = fcntl(sockfd, F_SETFL, flags | O_NONBLOCK);
else
ret = fcntl(sockfd, F_SETFL, flags & ~O_NONBLOCK);
break;
default:
errno = ENOTTY;
ret = -1;
break;
}
return ret;
}
|
keanutah/lpp-3ds
|
libctru/source/services/soc/soc_ioctl.c
|
C
|
gpl-3.0
| 720
|
### Hierarchical State Machine
### Description
> Portable cross-platform hierarchical state machine that uses a trick to
> implement inheritance in C.
### Build tool requirements
Required:
Under GNU/Linux environment( Makefile is not tested on Windows or Mac OS )
1. GNU make
2. gcc
3. g++
4. perl
5. tput
6. git
7. doxygen
8. graphviz
9. cppcheck
10. cppUtest
```sh
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install make
sudo apt-get install build-essential
sudo apt-get install perl
sudo apt-get install libncurses5-dev libncursesw5-dev
sudo apt-get install git
sudo apt-get install doxygen
sudo apt-get install graphviz
sudo apt-get install cppcheck
#sudo apt-get install cpputest( build from Github )
```
Optional:
1. Eclipse (Neon 3) with CDT
2. Segger JLink drivers
3. Saleae logic analyser
4. picocom
5. STM32CubeMx
6. Segger Ozone
```sh
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install picocom
```
### How to build
To see available targets and help information:
```sh
make help
```
Build with ARM as target:
```sh
make all
```
Build with GNU/Linux as target:
```sh
make TARGET_SELECT=host all
```
Eclipse:
1. Open Eclipse with **proj/eclipse_workspace** as the workspace.
2. Import existing project in the solution.
3. Start developing...
### Maintainer
[Kanelis Ilias](mailto:hkanelhs@yahoo.gr)
### License
[GNU3](LICENSE) © Kanelis Ilias
|
TediCreations/HSM
|
README.md
|
Markdown
|
gpl-3.0
| 1,397
|
module("About Scope (topics/about_scope.js)");
thisIsAGlobalVariable = 77;
test("global variables", function() {
equal(77, thisIsAGlobalVariable, 'is thisIsAGlobalVariable defined in this scope?');
});
test("variables declared inside of a function", function() {
var outerVariable = "outer";
// this is a self-invoking function. Notice that it calls itself at the end ().
(function() {
var innerVariable = "inner";
equal('outer', outerVariable, 'is outerVariable defined in this scope?');
equal('inner', innerVariable, 'is innerVariable defined in this scope?');
})();
equal('outer', outerVariable, 'is outerVariable defined in this scope?');
equal('undefined', typeof(innerVariable), 'is innerVariable defined in this scope?');
});
|
MTEySS/taller-web
|
07_js_basico/soluciones/01_koans/topics/about_scope.js
|
JavaScript
|
gpl-3.0
| 764
|
# ng-d2c (Angular directive to component)
Converts AngularJS directives to components. Tries to avoid converting directives that can not be converted safety.
Directives are overwritten in-place. The purpose of this tool is to perform a one-time migration to the new component syntax.
### Before
```
angular.module("foo").directive("simple", function () {
return {
scope: {},
bindToController: true,
restrict: "E"
};
});
```
### After
```
angular.module("foo").component("simple", {
bindings: {}
});
```
## Usage
### 1. Analyze
```
# Find and analyze directives in .js files in the current directory and subdirectories
$ ng-d2c
OK: advancedDirective.js
OK: multiDirective.js
OK: simpleDirective.js
FAIL: invalidDirective.js
Directive does not return an object
OK: 3 (Can be converted)
FAIL: 1 (Can not be converted until errors are fixed)
```
### 2. Convert
WARNING: Always use version control software and review the changes made by this tool before committing your new components!
```
# Convert all directives which can be converted safely in the current directory and subdirectories
$ ng-d2c convert
Converting: advancedDirective.js
Converting: multiDirective.js
Converting: simpleDirective.js
```
|
thesam/ng-d2c
|
README.md
|
Markdown
|
gpl-3.0
| 1,248
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_11) on Mon Jun 16 17:36:03 PDT 2014 -->
<title>Uses of Class java.io.ByteArrayInputStream (Java Platform SE 8 )</title>
<meta name="date" content="2014-06-16">
<link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class java.io.ByteArrayInputStream (Java Platform SE 8 )";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../java/io/ByteArrayInputStream.html" title="class in java.io">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?java/io/class-use/ByteArrayInputStream.html" target="_top">Frames</a></li>
<li><a href="ByteArrayInputStream.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class java.io.ByteArrayInputStream" class="title">Uses of Class<br>java.io.ByteArrayInputStream</h2>
</div>
<div class="classUseContainer">No usage of java.io.ByteArrayInputStream</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../java/io/ByteArrayInputStream.html" title="class in java.io">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
<div class="aboutLanguage"><strong>Java™ Platform<br>Standard Ed. 8</strong></div>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?java/io/class-use/ByteArrayInputStream.html" target="_top">Frames</a></li>
<li><a href="ByteArrayInputStream.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small><font size="-1"> <a href="http://bugreport.sun.com/bugreport/">Submit a bug or feature</a> <br>For further API reference and developer documentation, see <a href="http://download.oracle.com/javase/8/docs/index.html" target="_blank">Java SE Documentation</a>. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.<br> Copyright © 1993, 2014, Oracle and/or its affiliates. All rights reserved. </font></small></p>
</body>
</html>
|
DeanAaron/jdk8
|
jdk8en_us/docs/api/java/io/class-use/ByteArrayInputStream.html
|
HTML
|
gpl-3.0
| 5,003
|
import numpy, cairo, math
from scipy import ndimage
from .object3d import Object3d
from .point3d import Point3d
from .polygon3d import Polygon3d
from .draw_utils import *
from .colors import hsv_to_rgb, rgb_to_hsv
def surface2array(surface):
data = surface.get_data()
if not data:
return None
rgb_array = 0+numpy.frombuffer(surface.get_data(), numpy.uint8)
rgb_array.shape = (surface.get_height(), surface.get_width(), 4)
#rgb_array = rgb_array[:,:,[2,1,0,3]]
#rgb_array = rgb_array[:,:, :3]
return rgb_array
class Camera3d(Object3d):
def __init__(self, viewer=(0,0,0)):
super(Camera3d, self).__init__()
self.viewer = Point3d.create_if_needed(viewer)
self.sorted_items = []
self.mat_params = None
self.hit_alpha = 0
self.convolve_kernel = 0
self.hsv_coef = None
def project_point_values(self, point_values):
point_values = self.forward_transform_point_values(point_values)
return self.viewer_point_values(point_values)
def viewer_point_values(self, point_values):
if self.viewer.get_z() != 0:
ratio = self.viewer.get_z()/point_values[:, 2]
x_values = (ratio*point_values[:,0]) - self.viewer.get_x()
y_values = (ratio*point_values[:,1]) - self.viewer.get_y()
return numpy.stack((x_values, y_values), axis=1)
else:
return point_values[:, [0,1]]
def reverse_project_point_value(self, point_value, z_depth):
real_point_value = Point3d(x=point_value[0], y=point_value[1], z=z_depth)
if self.viewer.get_z() != 0:
ratio = z_depth/self.viewer.get_z()
real_point_value.values[0] = (point_value[0] + self.viewer.get_x())/ratio
real_point_value.values[1] = (point_value[1] + self.viewer.get_y())/ratio
real_point_value.values = self.reverse_transform_point_values(real_point_value.values)
return real_point_value.values
def sort_items(self, items=None):
polygons = []
if items is None:
polygons.extend(Polygon3d.Items)
else:
for item in items:
if not hasattr(item, "polygons"):
continue
polygons.extend(item.polygons)
self.sorted_items = sorted(polygons, key=self.z_depth_sort_key)
self.poly_face_params = None
for item in self.sorted_items:
params = numpy.array([item.plane_params_normalized[self]])
if self.poly_face_params is None:
self.poly_face_params = params
else:
self.poly_face_params = numpy.concatenate(
(self.poly_face_params, params), axis=0)
def z_depth_sort_key(self, ob):
return ob.z_depths[self]
def get_image_canvas(self, left, top, width, height, border_color=None, border_width=None, scale=.5):
left = math.floor(left)
top = math.floor(top)
width = int(width)
height = int(height)
if border_width>0:
border_width = max(border_width*scale, 1)
min_depth = -100000
canvas_width = int(width*scale)
canvas_height = int(height*scale)
pixel_count = canvas_width*canvas_height
canvas_surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, canvas_width, canvas_height)
canvas_surf_array = surface2array(canvas_surf)
canvas_z_depths =numpy.repeat(min_depth, pixel_count)
canvas_z_depths = canvas_z_depths.astype("f").reshape(canvas_height, canvas_width)
obj_pad = max(border_width*4, 0)
for object_3d in self.sorted_items:
if object_3d.border_width:
pad = max(obj_pad, object_3d.border_width*2)
else:
pad = obj_pad
brect = object_3d.bounding_rect[self]
bleft, btop = int(math.ceil(brect[0][0])), int(math.ceil(brect[0][1]))
bright, bbottom = int(math.ceil(brect[1][0])), int(math.ceil(brect[1][1]))
if bleft>left+width or bright<left or \
btop>top+height or bbottom<top:
continue
bleft -= pad
bright += pad
btop -= pad
bbottom += pad
sleft = max(left, bleft)
stop = max(top, btop)
sright = min(left+width, bright)
sbottom = min(top+height, bbottom)
#if sleft>=sright or stop>=sbottom:
# continue
sw = int(math.ceil(sright-sleft))
sh = int(math.ceil(sbottom-stop))
if sw<=0 or sh<=0:
continue
poly_canvas_width = int(sw*scale)
poly_canvas_height = int(sh*scale)
cleft = int((sleft-left)*scale)
cright = min(int((sright-left)*scale), canvas_width)
ctop = int((stop-top)*scale)
cbottom = int((sbottom-top)*scale)
if (ctop-cbottom!=poly_canvas_height):
cbottom=poly_canvas_height+ctop
if cbottom>canvas_height:
cbottom = canvas_height
ctop = cbottom-poly_canvas_height
if (cright-cleft!=poly_canvas_width):
cright=poly_canvas_width+cleft
if cright>canvas_width:
cright = canvas_width
cleft = cright-poly_canvas_width
#print "poly_canvas_height", poly_canvas_height, "poly_canvas_width", poly_canvas_width
#print "cbottom-ctop", cbottom-ctop, "cright-cleft", cright-cleft
#print "canvas_width, canvas_height", canvas_width, canvas_height
#print "cbottom, ctop", cbottom, ctop, "cright, cleft", cright, cleft
poly_surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, poly_canvas_width, poly_canvas_height)
poly_ctx = cairo.Context(poly_surf)
poly_ctx.scale(scale, scale)
set_default_line_style(poly_ctx)
poly_ctx.rectangle(0, 0, sw, sh)
poly_ctx.set_source_rgba(1, 0, 0, 0)
poly_ctx.fill()
poly_ctx.translate(-bleft, -btop)
poly_ctx.translate(-(sleft-bleft), -(stop-btop))
object_3d.draw(poly_ctx, self, border_color=border_color, border_width=border_width)
surfacearray = surface2array(poly_surf)
if surfacearray is None:
continue
area_cond = (surfacearray[:, :, 3]<=self.hit_alpha)
xs = numpy.linspace(sleft, sright, poly_canvas_width)
xcount = len(xs)
ys = numpy.linspace(stop, sbottom, poly_canvas_height)
ycount = len(ys)
xs, ys = numpy.meshgrid(xs, ys)
coords = numpy.vstack((xs.flatten(), ys.flatten()))
coords = coords.T#.reshape((ycount, xcount, 2))
coords.shape = (xcount*ycount, 2)
vz = self.viewer.get_z()
if vz == 0:
coords_depths = numpy.matmul(object_3d.plane_params_normalized[self],
numpy.concatenate((coords.T, [numpy.ones(coords.shape[0])]), axis=0))
else:
vx = self.viewer.get_x()
vy = self.viewer.get_y()
pp = object_3d.plane_params_normalized[self]
coords_depths = pp[2]*vz/(-pp[0]*(coords[:, 0]+vx)-pp[1]*(coords[:, 1]+vy)+vz)
coords_depths.shape = (ycount, xcount)
coords_depths.shape = (ycount, xcount)
blank_depths = numpy.repeat(min_depth+1, ycount*xcount)
blank_depths.shape = coords_depths.shape
coords_depths = numpy.where(area_cond, blank_depths, coords_depths)
pre_depths = canvas_z_depths[ctop:cbottom, cleft:cright]
pre_depths.shape = (cbottom-ctop, cright-cleft)
depths_cond = pre_depths<coords_depths#highier depths come at top
new_depths = numpy.where(depths_cond, coords_depths, pre_depths)
canvas_z_depths[ctop:cbottom, cleft:cright] = new_depths
pre_colors = canvas_surf_array[ctop:cbottom, cleft:cright, :]
pre_colors.shape = (cbottom-ctop, cright-cleft, 4)
depths_cond_multi = numpy.repeat(depths_cond, 4)
depths_cond_multi.shape = (depths_cond.shape[0], depths_cond.shape[1], 4)
new_colors = numpy.where(depths_cond_multi, surfacearray, pre_colors)
canvas_surf_array[ctop:cbottom, cleft:cright, :] = new_colors
"""
cond = (canvas_surf_array[:, :, 3]!=255)
cond_multi = numpy.repeat(cond, 4)
cond_multi.shape = (cond.shape[0], cond.shape[1], 4)
filled_values = numpy.repeat([[255, 0, 0, 255]], height*width, axis=0 ).astype(numpy.uint8)
filled_values.shape= (cond.shape[0], cond.shape[1], 4)
canvas_surf_array = numpy.where(cond_multi, filled_values, canvas_surf_array)
"""
canvas = cairo.ImageSurface.create_for_data(
canvas_surf_array, cairo.FORMAT_ARGB32, canvas_width, canvas_height)
if scale != 1:
enlarged_canvas = cairo.ImageSurface(cairo.FORMAT_ARGB32, width, height)
ctx = cairo.Context(enlarged_canvas)
ctx.rectangle(0, 0, width, height)
ctx.scale(1./scale, 1./scale)
ctx.set_source_surface(canvas)
ctx.paint()
canvas = enlarged_canvas
return canvas
def draw(self, ctx, border_color, border_width):
for object_3d in self.sorted_items:
object_3d.draw(ctx, self, border_color=border_color, border_width=border_width)
def get_image_canvas_high_quality(self,
container,
canvas_width, canvas_height, premat,
left, top, width, height,
border_color=None, border_width=None):
min_depth = -100000
canvas_width = int(canvas_width)
canvas_height = int(canvas_height)
canvas_surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, canvas_width, canvas_height)
ctx = cairo.Context(canvas_surf)
ctx.rectangle(0, 0, canvas_width, canvas_height)
draw_fill(ctx, "00000000")
canvas_surf_array = surface2array(canvas_surf)
canvas_z_depths = numpy.zeros(canvas_surf_array.shape[:2], dtype="f")
canvas_z_depths.fill(min_depth)
canvas_normals = numpy.zeros(
(canvas_surf_array.shape[0],
canvas_surf_array.shape[1],
3), dtype="f")
canvas_normals.fill(0)
canvas_points = numpy.zeros(
(canvas_surf_array.shape[0],
canvas_surf_array.shape[1],
3), dtype="f")
canvas_points.fill(0)
invert = cairo.Matrix().multiply(premat)
invert.invert()
xx, yx, xy, yy, x0, y0 = invert
numpy_pre_invert_mat = numpy.array([[xx, xy, x0], [yx, yy, y0]])
span_y = max(-top, top+height)
lights = container.get_lights()
lights = sorted(lights, self.z_depth_sort_key)
for object_3d in self.sorted_items:
brect = object_3d.bounding_rect[self]
bleft, btop = brect[0][0], brect[0][1]
bright, bbottom = brect[1][0], brect[1][1]
if bleft>left+width or bright<left or \
btop>span_y or bbottom<-span_y:
continue
sleft = max(left, bleft)
stop = btop#max(top, btop)
sright = min(left+width, bright+1)
sbottom = bbottom#min(top+height, bbottom+1)
sw = sright-sleft
sh = sbottom-stop
if sw<=0 or sh<=0:
continue
poly_surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, canvas_width, canvas_height)
poly_ctx = cairo.Context(poly_surf)
set_default_line_style(poly_ctx)
poly_ctx.rectangle(0, 0, canvas_width, canvas_height)
poly_ctx.set_source_rgba(1, 0, 0, 0)
poly_ctx.fill()
poly_ctx.set_matrix(premat)
object_3d.draw(poly_ctx, self, border_color=border_color, border_width=border_width)
del poly_ctx
surfacearray = surface2array(poly_surf)
xs = numpy.arange(0, canvas_width, step=1)
xcount = len(xs)
ys = numpy.arange(0, canvas_height, step=1)
ycount = len(ys)
xs, ys = numpy.meshgrid(xs, ys)
surface_grid = numpy.vstack((xs.flatten(), ys.flatten(), numpy.ones(xcount*ycount)))
surface_grid.shape = (3, ycount*xcount)
del xs, ys
hit_area_cond = (surfacearray[:, :, 3]>self.hit_alpha)
hit_area_cond.shape = (ycount*xcount,)
canvas_poly_coords = surface_grid[:, hit_area_cond]
canvas_poly_coords.shape = (3, -1)
del hit_area_cond
poly_coor_x = canvas_poly_coords[0, :].astype(numpy.uint32)
poly_coor_y = canvas_poly_coords[1, :].astype(numpy.uint32)
coords = numpy.matmul(numpy_pre_invert_mat, canvas_poly_coords)
coords.shape = (2, -1)
del canvas_poly_coords
coords_depths = numpy.matmul(object_3d.plane_params_normalized[self],
numpy.concatenate((coords, [numpy.ones(coords.shape[1])]), axis=0))
surface_points = numpy.concatenate((coords, [coords_depths]), axis=0).T
del coords
canvas_points[poly_coor_y, poly_coor_x, :] = surface_points
canvas_normals[poly_coor_y, poly_coor_x, :] = object_3d.plane_normals[self].copy()
pre_depths = canvas_z_depths[poly_coor_y, poly_coor_x]
depths_cond = pre_depths<coords_depths
new_depths = numpy.where(depths_cond, coords_depths, pre_depths)
canvas_z_depths[poly_coor_y, poly_coor_x] = new_depths
del pre_depths, new_depths
pre_colors = canvas_surf_array[poly_coor_y, poly_coor_x, :]
pre_colors.shape = (-1, 4)
depths_cond_multi = numpy.repeat(depths_cond, 4)
depths_cond_multi.shape = (depths_cond.shape[0], 4)
picked_surface = surfacearray[poly_coor_y, poly_coor_x]
picked_surface.shape = (-1, 4)
for light in lights:
light_depths_cond = ((coords_depths<light.z_depths[self]) & (coords_depths>min_depth))
light_vectors = light.rel_location_values[self][0][:3]-surface_points[light_depths_cond, :]
if len(light_vectors)==0:
continue
surface_normals = object_3d.plane_normals[self]
norm = numpy.linalg.norm(light_vectors, axis=1)
norm = numpy.repeat(norm, 3)
norm.shape = (-1,3)
light_vectors = light_vectors/norm
cosines = numpy.sum(light_vectors*surface_normals, axis=1)
cosines = numpy.abs(cosines)
cosines_multi = numpy.repeat(cosines, 4)
cosines_multi.shape = (cosines.shape[0],4)
if hasattr(light, "normal"):
cosines = numpy.sum(-light_vectors*light.normal.values[:3], axis=1)
cosines = numpy.abs(cosines)
damp = numpy.exp(-light.decay*(numpy.abs(cosines-light.cone_cosine)))
colors = numpy.repeat([light.color.to_255()], len(light_vectors), axis=0)
colors.shape = (-1, 4)
colors[:,3] = colors[:,3]*cosines
else:
colors = numpy.repeat([light.color.to_255()], len(light_vectors), axis=0)
pre_surf_colors = picked_surface[light_depths_cond, :].copy()
picked_surface[light_depths_cond, :] = (pre_surf_colors*(1-cosines_multi) + \
colors*cosines_multi).astype(numpy.uint8)
new_colors = numpy.where(depths_cond_multi, picked_surface, pre_colors)
new_colors.shape = (-1, 4)
del depths_cond_multi, pre_colors, picked_surface
canvas_surf_array[poly_coor_y, poly_coor_x, :] = new_colors
del poly_coor_x, poly_coor_y
if self.convolve_kernel:
n=self.convolve_kernel
kernel = numpy.ones(n*n).reshape(n,n)*1./(n*n)
for i in xrange(4):
canvas_surf_array[:,:,i] = ndimage.convolve(
canvas_surf_array[:,:,i], kernel, mode="constant")
if self.hsv_coef:
hsv = rgb_to_hsv(canvas_surf_array[:,:,:3].copy())
hsv[:, :, 0] = (hsv[:, :,0]*self.hsv_coef[0])
hsv[:, :, 1] = (hsv[:, :,1]*self.hsv_coef[1])
hsv[:, :, 2] = (hsv[:, :,2]*self.hsv_coef[2])
canvas_surf_array[:, :, :3] = hsv_to_rgb(hsv)
"""
for light in lights:
depths_cond = ((canvas_z_depths<light.z_depths[self]) & (canvas_z_depths>min_depth))
light_vectors = light.rel_location_values[self][0][:3]-canvas_points[depths_cond, :]
if len(light_vectors)==0:
continue
surface_normals = canvas_normals[depths_cond, :]
norm = numpy.linalg.norm(light_vectors, axis=1)
norm = numpy.repeat(norm, 3)
norm.shape = (-1,3)
light_vectors = light_vectors/norm
cosines = numpy.sum(light_vectors*surface_normals, axis=1)
cosines = numpy.abs(cosines)
cosines_multi = numpy.repeat(cosines, 4)
cosines_multi.shape = (cosines.shape[0],4)
if hasattr(light, "normal"):
cosines = numpy.sum(-light_vectors*light.normal.values[:3], axis=1)
cosines = numpy.abs(cosines)
damp = numpy.exp(-light.decay*(numpy.abs(cosines-light.cone_cosine)))
cosines = numpy.where(cosines<light.cone_cosine, damp, 1)
colors = numpy.repeat([light.color.to_255()], len(light_vectors), axis=0)
colors.shape = (-1, 4)
colors[:,3] = colors[:,3]*cosines
else:
colors = numpy.repeat([light.color.to_255()], len(light_vectors), axis=0)
pre_colors = canvas_surf_array[depths_cond, :].copy()
canvas_surf_array[depths_cond, :] = (pre_colors*(1-cosines_multi) + \
colors*cosines_multi).astype(numpy.uint8)
"""
canvas = cairo.ImageSurface.create_for_data(
numpy.getbuffer(canvas_surf_array), cairo.FORMAT_ARGB32, canvas_width, canvas_height)
return canvas
def draw_objects(self, ctx, left, top, width, height):
image_canvas = self.get_image_canvas(left, top, width, height)
ctx.set_source_surface(image_canvas, left, top)
ctx.get_source().set_filter(cairo.FILTER_FAST)
ctx.paint()
"""
for object_3d in self.get_sorted_items():
object_3d.draw_bounding_rect(self, ctx)
"""
|
sujoykroy/motion-picture
|
editor/MotionPicture/commons/camera3d.py
|
Python
|
gpl-3.0
| 18,923
|
/**
* This file is part of RagEmu.
* http://ragemu.org - https://github.com/RagEmu/PreRenewal
*
* Copyright (C) 2016 RagEmu Dev Team
* Copyright (C) 2012-2016 Hercules Dev Team
* Copyright (C) Athena Dev Teams
*
* RagEmu is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#define RAGEMU_CORE
#include "config/core.h" // CELL_NOSTACK, CIRCULAR_AREA, CONSOLE_INPUT, HMAP_ZONE_DAMAGE_CAP_TYPE, OFFICIAL_WALKPATH, SCRIPT_CALLFUNC_CHECK, SECURE_NPCTIMEOUT, STATS_OPT_OUT
#include "battle.h"
#include "map/battleground.h"
#include "map/chrif.h"
#include "map/clif.h"
#include "map/elemental.h"
#include "map/guild.h"
#include "map/homunculus.h"
#include "map/itemdb.h"
#include "map/map.h"
#include "map/mercenary.h"
#include "map/mob.h"
#include "map/party.h"
#include "map/path.h"
#include "map/pc.h"
#include "map/pet.h"
#include "map/skill.h"
#include "map/status.h"
#include "common/HPM.h"
#include "common/cbasetypes.h"
#include "common/ers.h"
#include "common/memmgr.h"
#include "common/nullpo.h"
#include "common/random.h"
#include "common/showmsg.h"
#include "common/socket.h"
#include "common/strlib.h"
#include "common/sysinfo.h"
#include "common/timer.h"
#include "common/utils.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Battle_Config battle_config;
struct battle_interface battle_s;
struct battle_interface *battle;
/**
* Returns the current/last skill in use by this bl.
*
* @param bl The bl to check.
* @return The current/last skill ID.
*/
int battle_getcurrentskill(struct block_list *bl)
{
const struct unit_data *ud;
nullpo_ret(bl);
if (bl->type == BL_SKILL) {
const struct skill_unit *su = BL_UCCAST(BL_SKILL, bl);
if (su->group == NULL)
return 0;
return su->group->skill_id;
}
ud = unit->bl2ud(bl);
if (ud == NULL)
return 0;
return ud->skill_id;
}
/*==========================================
* Get random targeting enemy
*------------------------------------------*/
int battle_gettargeted_sub(struct block_list *bl, va_list ap) {
struct block_list **bl_list;
struct unit_data *ud;
int target_id;
int *c;
nullpo_ret(bl);
bl_list = va_arg(ap, struct block_list **);
c = va_arg(ap, int *);
target_id = va_arg(ap, int);
if (bl->id == target_id)
return 0;
if (*c >= 24)
return 0;
if (!(ud = unit->bl2ud(bl)))
return 0;
if (ud->target == target_id || ud->skilltarget == target_id) {
bl_list[(*c)++] = bl;
return 1;
}
return 0;
}
struct block_list* battle_gettargeted(struct block_list *target) {
struct block_list *bl_list[24];
int c = 0;
nullpo_retr(NULL, target);
memset(bl_list, 0, sizeof(bl_list));
map->foreachinrange(battle->get_targeted_sub, target, AREA_SIZE, BL_CHAR, bl_list, &c, target->id);
if ( c == 0 )
return NULL;
if( c > 24 )
c = 24;
return bl_list[rnd()%c];
}
//Returns the id of the current targeted character of the passed bl. [Skotlex]
int battle_gettarget(struct block_list* bl) {
nullpo_ret(bl);
switch (bl->type) {
case BL_PC: return BL_UCCAST(BL_PC, bl)->ud.target;
case BL_MOB: return BL_UCCAST(BL_MOB, bl)->target_id;
case BL_PET: return BL_UCCAST(BL_PET, bl)->target_id;
case BL_HOM: return BL_UCCAST(BL_HOM, bl)->ud.target;
case BL_MER: return BL_UCCAST(BL_MER, bl)->ud.target;
case BL_ELEM: return BL_UCCAST(BL_ELEM, bl)->ud.target;
}
return 0;
}
int battle_getenemy_sub(struct block_list *bl, va_list ap) {
struct block_list **bl_list;
struct block_list *target;
int *c;
nullpo_ret(bl);
bl_list = va_arg(ap, struct block_list **);
c = va_arg(ap, int *);
target = va_arg(ap, struct block_list *);
if (bl->id == target->id)
return 0;
if (*c >= 24)
return 0;
if (status->isdead(bl))
return 0;
if (battle->check_target(target, bl, BCT_ENEMY) > 0) {
bl_list[(*c)++] = bl;
return 1;
}
return 0;
}
// Picks a random enemy of the given type (BL_PC, BL_CHAR, etc) within the range given. [Skotlex]
struct block_list* battle_getenemy(struct block_list *target, int type, int range) {
struct block_list *bl_list[24];
int c = 0;
nullpo_retr(NULL, target);
memset(bl_list, 0, sizeof(bl_list));
map->foreachinrange(battle->get_enemy_sub, target, range, type, bl_list, &c, target);
if ( c == 0 )
return NULL;
if( c > 24 )
c = 24;
return bl_list[rnd()%c];
}
int battle_getenemyarea_sub(struct block_list *bl, va_list ap) {
struct block_list **bl_list, *src;
int *c, ignore_id;
nullpo_ret(bl);
bl_list = va_arg(ap, struct block_list **);
nullpo_ret(bl_list);
c = va_arg(ap, int *);
nullpo_ret(c);
src = va_arg(ap, struct block_list *);
ignore_id = va_arg(ap, int);
if( bl->id == src->id || bl->id == ignore_id )
return 0; // Ignores Caster and a possible pre-target
if( *c >= 23 )
return 0;
if( status->isdead(bl) )
return 0;
if( battle->check_target(src, bl, BCT_ENEMY) > 0 ) {// Is Enemy!...
bl_list[(*c)++] = bl;
return 1;
}
return 0;
}
// Pick a random enemy
struct block_list* battle_getenemyarea(struct block_list *src, int x, int y, int range, int type, int ignore_id) {
struct block_list *bl_list[24];
int c = 0;
nullpo_retr(NULL, src);
memset(bl_list, 0, sizeof(bl_list));
map->foreachinarea(battle->get_enemy_area_sub, src->m, x - range, y - range, x + range, y + range, type, bl_list, &c, src, ignore_id);
if( c == 0 )
return NULL;
if( c >= 24 )
c = 23;
return bl_list[rnd()%c];
}
int battle_delay_damage_sub(int tid, int64 tick, int id, intptr_t data) {
struct delay_damage *dat = (struct delay_damage *)data;
if ( dat ) {
struct block_list *src = map->id2bl(dat->src_id);
struct map_session_data *sd = BL_CAST(BL_PC, src);
struct block_list *target = map->id2bl(dat->target_id);
if (target != NULL && !status->isdead(target)) {
//Check to see if you haven't teleported. [Skotlex]
if (src != NULL && (
battle_config.fix_warp_hit_delay_abuse ?
(dat->skill_id == MO_EXTREMITYFIST || target->m != src->m || check_distance_bl(src, target, dat->distance))
:
((target->type != BL_PC || BL_UCAST(BL_PC, target)->invincible_timer == INVALID_TIMER)
&& (dat->skill_id == MO_EXTREMITYFIST || (target->m == src->m && check_distance_bl(src, target, dat->distance))))
)) {
map->freeblock_lock();
status_fix_damage(src, target, dat->damage, dat->delay);
if (dat->attack_type && !status->isdead(target) && dat->additional_effects)
skill->additional_effect(src,target,dat->skill_id,dat->skill_lv,dat->attack_type,dat->dmg_lv,tick);
if (dat->dmg_lv > ATK_BLOCK && dat->attack_type)
skill->counter_additional_effect(src,target,dat->skill_id,dat->skill_lv,dat->attack_type,tick);
map->freeblock_unlock();
} else if (src == NULL && dat->skill_id == CR_REFLECTSHIELD) {
// it was monster reflected damage, and the monster died, we pass the damage to the character as expected
map->freeblock_lock();
status_fix_damage(target, target, dat->damage, dat->delay);
map->freeblock_unlock();
}
}
if (sd != NULL && --sd->delayed_damage == 0 && sd->state.hold_recalc) {
sd->state.hold_recalc = 0;
status_calc_pc(sd, SCO_FORCE);
}
}
ers_free(battle->delay_damage_ers, dat);
return 0;
}
int battle_delay_damage(int64 tick, int amotion, struct block_list *src, struct block_list *target, int attack_type, uint16 skill_id, uint16 skill_lv, int64 damage, enum damage_lv dmg_lv, int ddelay, bool additional_effects) {
struct delay_damage *dat;
struct status_change *sc;
struct block_list *d_tbl = NULL;
nullpo_ret(src);
nullpo_ret(target);
sc = status->get_sc(target);
if (sc && sc->data[SC_DEVOTION] && sc->data[SC_DEVOTION]->val1)
d_tbl = map->id2bl(sc->data[SC_DEVOTION]->val1);
if (d_tbl && sc && check_distance_bl(target, d_tbl, sc->data[SC_DEVOTION]->val3) && damage > 0 && skill_id != PA_PRESSURE && skill_id != CR_REFLECTSHIELD)
damage = 0;
if ( !battle_config.delay_battle_damage || amotion <= 1 ) {
map->freeblock_lock();
status_fix_damage(src, target, damage, ddelay); // We have to separate here between reflect damage and others [icescope]
if( attack_type && !status->isdead(target) && additional_effects )
skill->additional_effect(src, target, skill_id, skill_lv, attack_type, dmg_lv, timer->gettick());
if( dmg_lv > ATK_BLOCK && attack_type )
skill->counter_additional_effect(src, target, skill_id, skill_lv, attack_type, timer->gettick());
map->freeblock_unlock();
return 0;
}
dat = ers_alloc(battle->delay_damage_ers, struct delay_damage);
dat->src_id = src->id;
dat->target_id = target->id;
dat->skill_id = skill_id;
dat->skill_lv = skill_lv;
dat->attack_type = attack_type;
dat->damage = damage;
dat->dmg_lv = dmg_lv;
dat->delay = ddelay;
dat->distance = distance_bl(src, target) + (battle_config.snap_dodge ? 10 : battle_config.area_size);
dat->additional_effects = additional_effects;
dat->src_type = src->type;
if (src->type != BL_PC && amotion > 1000)
amotion = 1000; //Aegis places a damage-delay cap of 1 sec to non player attacks. [Skotlex]
if (src->type == BL_PC) {
BL_UCAST(BL_PC, src)->delayed_damage++;
}
timer->add(tick+amotion, battle->delay_damage_sub, 0, (intptr_t)dat);
return 0;
}
int battle_attr_ratio(int atk_elem,int def_type, int def_lv)
{
if (atk_elem < ELE_NEUTRAL || atk_elem >= ELE_MAX)
return 100;
if (def_type < ELE_NEUTRAL || def_type >= ELE_MAX || def_lv < 1 || def_lv > 4)
return 100;
return battle->attr_fix_table[def_lv-1][atk_elem][def_type];
}
/*==========================================
* Does attribute fix modifiers.
* Added passing of the chars so that the status changes can affect it. [Skotlex]
* Note: Passing src/target == NULL is perfectly valid, it skips SC_ checks.
*------------------------------------------*/
int64 battle_attr_fix(struct block_list *src, struct block_list *target, int64 damage,int atk_elem,int def_type, int def_lv)
{
struct status_change *sc=NULL, *tsc=NULL;
int ratio;
if (src) sc = status->get_sc(src);
if (target) tsc = status->get_sc(target);
if (atk_elem < ELE_NEUTRAL || atk_elem >= ELE_MAX)
atk_elem = rnd()%ELE_MAX;
if (def_type < ELE_NEUTRAL || def_type >= ELE_MAX ||
def_lv < 1 || def_lv > 4) {
ShowError("battle_attr_fix: unknown attr type: atk=%d def_type=%d def_lv=%d\n",atk_elem,def_type,def_lv);
return damage;
}
ratio = battle->attr_fix_table[def_lv-1][atk_elem][def_type];
if (sc && sc->count) {
if(sc->data[SC_VOLCANO] && atk_elem == ELE_FIRE)
ratio += skill->enchant_eff[sc->data[SC_VOLCANO]->val1-1];
if(sc->data[SC_VIOLENTGALE] && atk_elem == ELE_WIND)
ratio += skill->enchant_eff[sc->data[SC_VIOLENTGALE]->val1-1];
if(sc->data[SC_DELUGE] && atk_elem == ELE_WATER)
ratio += skill->enchant_eff[sc->data[SC_DELUGE]->val1-1];
if(sc->data[SC_FIRE_CLOAK_OPTION] && atk_elem == ELE_FIRE)
damage += damage * sc->data[SC_FIRE_CLOAK_OPTION]->val2 / 100;
}
if( target && target->type == BL_SKILL ) {
if( atk_elem == ELE_FIRE && battle->get_current_skill(target) == GN_WALLOFTHORN ) {
struct skill_unit *su = BL_UCAST(BL_SKILL, target);
struct skill_unit_group *sg;
struct block_list *sgsrc;
if(!su->alive
|| (sg = su->group) == NULL || sg->val3 == -1
|| (sgsrc = map->id2bl(sg->src_id)) == NULL || status->isdead(sgsrc)
)
return 0;
if( sg->unit_id != UNT_FIREWALL ) {
int x,y;
x = sg->val3 >> 16;
y = sg->val3 & 0xffff;
skill->unitsetting(sgsrc,su->group->skill_id,su->group->skill_lv,x,y,1);
sg->val3 = -1;
sg->limit = DIFF_TICK32(timer->gettick(),sg->tick)+300;
}
}
}
if( tsc && tsc->count ) { //since an atk can only have one type let's optimize this a bit
switch(atk_elem){
case ELE_FIRE:
if( tsc->data[SC_SPIDERWEB]) {
tsc->data[SC_SPIDERWEB]->val1 = 0; // free to move now
if( tsc->data[SC_SPIDERWEB]->val2-- > 0 )
damage <<= 1; // double damage
if( tsc->data[SC_SPIDERWEB]->val2 == 0 )
status_change_end(target, SC_SPIDERWEB, INVALID_TIMER);
}
if( tsc->data[SC_THORNS_TRAP])
status_change_end(target, SC_THORNS_TRAP, INVALID_TIMER);
if( tsc->data[SC_COLD] && target->type != BL_MOB)
status_change_end(target, SC_COLD, INVALID_TIMER);
if( tsc->data[SC_EARTH_INSIGNIA]) damage += damage/2;
if( tsc->data[SC_FIRE_CLOAK_OPTION])
damage -= damage * tsc->data[SC_FIRE_CLOAK_OPTION]->val2 / 100;
if( tsc->data[SC_VOLCANIC_ASH]) damage += damage/2; //150%
break;
case ELE_HOLY:
if( tsc->data[SC_ORATIO]) ratio += tsc->data[SC_ORATIO]->val1 * 2;
break;
case ELE_POISON:
if( tsc->data[SC_VENOMIMPRESS] && atk_elem == ELE_POISON ) ratio += tsc->data[SC_VENOMIMPRESS]->val2;
break;
case ELE_WIND:
if( tsc->data[SC_COLD] && target->type != BL_MOB) damage += damage/2;
if( tsc->data[SC_WATER_INSIGNIA]) damage += damage/2;
break;
case ELE_WATER:
if( tsc->data[SC_FIRE_INSIGNIA]) damage += damage/2;
break;
case ELE_EARTH:
if( tsc->data[SC_WIND_INSIGNIA]) damage += damage/2;
break;
}
} //end tsc check
if( ratio < 100 )
return damage - (damage * (100 - ratio) / 100);
else
return damage + (damage * (ratio - 100) / 100);
}
//FIXME: Missing documentation for flag, flag2
int64 battle_calc_weapon_damage(struct block_list *src, struct block_list *bl, uint16 skill_id, uint16 skill_lv, struct weapon_atk *watk, int nk, bool n_ele, short s_ele, short s_ele_, int size, int type, int flag, int flag2){ // [malufett]
return 0;
}
/*==========================================
* Calculates the standard damage of a normal attack assuming it hits,
* it calculates nothing extra fancy, is needed for magnum breaks WATK_ELEMENT bonus. [Skotlex]
*------------------------------------------
* Pass damage2 as NULL to not calc it.
* Flag values: // TODO: Check whether these values are correct (the flag parameter seems to be passed through to other functions), and replace them with an enum.
* &1: Critical hit
* &2: Arrow attack
* &4: Skill is Magic Crasher
* &8: Skip target size adjustment (Extremity Fist?)
*&16: Arrow attack but BOW, REVOLVER, RIFLE, SHOTGUN, GATLING or GRENADE type weapon not equipped (i.e. shuriken, kunai and venom knives not affected by DEX)
*/
/* 'battle_calc_base_damage' is used on renewal, 'battle_calc_base_damage2' otherwise. */
// FIXME: Missing documentation for flag2
int64 battle_calc_base_damage(struct block_list *src, struct block_list *bl, uint16 skill_id, uint16 skill_lv, int nk, bool n_ele, short s_ele, short s_ele_, int type, int flag, int flag2) {
int64 damage;
struct status_data *st = status->get_status_data(src);
struct status_change *sc = status->get_sc(src);
const struct map_session_data *sd = NULL;
nullpo_retr(0, src);
sd = BL_CCAST(BL_PC, src);
if ( !skill_id ) {
s_ele = st->rhw.ele;
s_ele_ = st->lhw.ele;
if (sd != NULL) {
if (sd->charm_type != CHARM_TYPE_NONE && sd->charm_count >= MAX_SPIRITCHARM) {
s_ele = s_ele_ = sd->charm_type;
}
if (flag&2 && sd->bonus.arrow_ele != 0)
s_ele = sd->bonus.arrow_ele;
}
}
if (src->type == BL_PC) {
int64 batk;
// Property from mild wind bypasses it
if (sc && sc->data[SC_TK_SEVENWIND])
batk = battle->calc_elefix(src, bl, skill_id, skill_lv, status->calc_batk(bl, sc, st->batk, false), nk, n_ele, s_ele, s_ele_, false, flag);
else
batk = battle->calc_elefix(src, bl, skill_id, skill_lv, status->calc_batk(bl, sc, st->batk, false), nk, n_ele, ELE_NEUTRAL, ELE_NEUTRAL, false, flag);
if (type == EQI_HAND_L)
damage = batk + 3 * battle->calc_weapon_damage(src, bl, skill_id, skill_lv, &st->lhw, nk, n_ele, s_ele, s_ele_, status_get_size(bl), type, flag, flag2) / 4;
else
damage = (batk << 1) + battle->calc_weapon_damage(src, bl, skill_id, skill_lv, &st->rhw, nk, n_ele, s_ele, s_ele_, status_get_size(bl), type, flag, flag2);
} else {
damage = st->batk + battle->calc_weapon_damage(src, bl, skill_id, skill_lv, &st->rhw, nk, n_ele, s_ele, s_ele_, status_get_size(bl), type, flag, flag2);
}
return damage;
}
int64 battle_calc_base_damage2(struct status_data *st, struct weapon_atk *wa, struct status_change *sc, unsigned short t_size, struct map_session_data *sd, int flag) {
unsigned int atkmin=0, atkmax=0;
short type = 0;
int64 damage = 0;
nullpo_retr(damage, st);
nullpo_retr(damage, wa);
if (!sd) { //Mobs/Pets
if(flag&4) {
atkmin = st->matk_min;
atkmax = st->matk_max;
} else {
atkmin = wa->atk;
atkmax = wa->atk2;
}
if (atkmin > atkmax)
atkmin = atkmax;
} else { //PCs
atkmax = wa->atk;
type = (wa == &st->lhw)?EQI_HAND_L:EQI_HAND_R;
if (!(flag&1) || (flag&2)) { //Normal attacks
atkmin = st->dex;
if (sd->equip_index[type] >= 0 && sd->inventory_data[sd->equip_index[type]])
atkmin = atkmin*(80 + sd->inventory_data[sd->equip_index[type]]->wlv*20)/100;
if (atkmin > atkmax)
atkmin = atkmax;
if(flag&2 && !(flag&16)) { //Bows
atkmin = atkmin*atkmax/100;
if (atkmin > atkmax)
atkmax = atkmin;
}
}
}
if (sc && sc->data[SC_MAXIMIZEPOWER])
atkmin = atkmax;
//Weapon Damage calculation
if (!(flag&1))
damage = (atkmax>atkmin? rnd()%(atkmax-atkmin):0)+atkmin;
else
damage = atkmax;
if (sd) {
//rodatazone says the range is 0~arrow_atk-1 for non crit
if (flag&2 && sd->bonus.arrow_atk)
damage += ( (flag&1) ? sd->bonus.arrow_atk : rnd()%sd->bonus.arrow_atk );
//SizeFix only for players
if (!(sd->special_state.no_sizefix || (flag&8)))
damage = damage * ( type == EQI_HAND_L ? sd->left_weapon.atkmods[t_size] : sd->right_weapon.atkmods[t_size] ) / 100;
}
//Finally, add baseatk
if(flag&4)
damage += st->matk_min;
else
damage += st->batk;
//rodatazone says that Overrefined bonuses are part of baseatk
//Here we also apply the weapon_atk_rate bonus so it is correctly applied on left/right hands.
if(sd) {
if (type == EQI_HAND_L) {
if(sd->left_weapon.overrefine)
damage += rnd()%sd->left_weapon.overrefine+1;
if (sd->weapon_atk_rate[sd->weapontype2])
damage += damage * sd->weapon_atk_rate[sd->weapontype2] / 100;
} else { //Right hand
if(sd->right_weapon.overrefine)
damage += rnd()%sd->right_weapon.overrefine+1;
if (sd->weapon_atk_rate[sd->weapontype1])
damage += damage * sd->weapon_atk_rate[sd->weapontype1] / 100;
}
}
return damage;
}
int64 battle_calc_sizefix(struct map_session_data *sd, int64 damage, int type, int size, bool ignore){
//SizeFix only for players
nullpo_retr(damage, sd);
if (!(sd->special_state.no_sizefix || (ignore)))
damage = damage * ( type == EQI_HAND_L ? sd->left_weapon.atkmods[size] : sd->right_weapon.atkmods[size] ) / 100;
return damage;
}
/*==========================================
* Passive skill damages increases
*------------------------------------------*/
// FIXME: type is undocumented
int64 battle_addmastery(struct map_session_data *sd,struct block_list *target,int64 dmg,int type) {
int64 damage;
struct status_data *st = status->get_status_data(target);
int weapon, skill_lv;
damage = dmg;
nullpo_retr(damage, sd);
nullpo_retr(damage, target);
if((skill_lv = pc->checkskill(sd,AL_DEMONBANE)) > 0 &&
target->type == BL_MOB && //This bonus doesn't work against players.
(battle->check_undead(st->race,st->def_ele) || st->race==RC_DEMON) )
damage += (int)(skill_lv*(3+sd->status.base_level/20.0));
//damage += (skill_lv * 3);
if( (skill_lv = pc->checkskill(sd, RA_RANGERMAIN)) > 0 && (st->race == RC_BRUTE || st->race == RC_PLANT || st->race == RC_FISH) )
damage += (skill_lv * 5);
if( (skill_lv = pc->checkskill(sd,NC_RESEARCHFE)) > 0 && (st->def_ele == ELE_FIRE || st->def_ele == ELE_EARTH) )
damage += (skill_lv * 10);
if((skill_lv = pc->checkskill(sd,HT_BEASTBANE)) > 0 && (st->race==RC_BRUTE || st->race==RC_INSECT) ) {
damage += (skill_lv * 4);
if (sd->sc.data[SC_SOULLINK] && sd->sc.data[SC_SOULLINK]->val2 == SL_HUNTER)
damage += sd->status.str;
}
if(type == 0)
weapon = sd->weapontype1;
else
weapon = sd->weapontype2;
switch(weapon) {
case W_1HSWORD:
case W_DAGGER:
if((skill_lv = pc->checkskill(sd,SM_SWORD)) > 0)
damage += (skill_lv * 4);
if((skill_lv = pc->checkskill(sd,GN_TRAINING_SWORD)) > 0)
damage += skill_lv * 10;
break;
case W_2HSWORD:
if((skill_lv = pc->checkskill(sd,SM_TWOHAND)) > 0)
damage += (skill_lv * 4);
break;
case W_1HSPEAR:
case W_2HSPEAR:
if ((skill_lv = pc->checkskill(sd, KN_SPEARMASTERY)) > 0) {
if (pc_hasmount(sd))
damage += (skill_lv * 5);
else
damage += (skill_lv * 4);
}
break;
case W_1HAXE:
case W_2HAXE:
if((skill_lv = pc->checkskill(sd,AM_AXEMASTERY)) > 0)
damage += (skill_lv * 3);
if((skill_lv = pc->checkskill(sd,NC_TRAININGAXE)) > 0)
damage += (skill_lv * 5);
break;
case W_MACE:
case W_2HMACE:
if((skill_lv = pc->checkskill(sd,PR_MACEMASTERY)) > 0)
damage += (skill_lv * 3);
if((skill_lv = pc->checkskill(sd,NC_TRAININGAXE)) > 0)
damage += (skill_lv * 5);
break;
case W_FIST:
if((skill_lv = pc->checkskill(sd,TK_RUN)) > 0)
damage += (skill_lv * 10);
// No break, fall through to Knuckles
case W_KNUCKLE:
if((skill_lv = pc->checkskill(sd,MO_IRONHAND)) > 0)
damage += (skill_lv * 3);
break;
case W_MUSICAL:
if((skill_lv = pc->checkskill(sd,BA_MUSICALLESSON)) > 0)
damage += (skill_lv * 3);
break;
case W_WHIP:
if((skill_lv = pc->checkskill(sd,DC_DANCINGLESSON)) > 0)
damage += (skill_lv * 3);
break;
case W_BOOK:
if((skill_lv = pc->checkskill(sd,SA_ADVANCEDBOOK)) > 0)
damage += (skill_lv * 3);
break;
case W_KATAR:
if((skill_lv = pc->checkskill(sd,AS_KATAR)) > 0)
damage += (skill_lv * 3);
break;
}
return damage;
}
/*==========================================
* Calculates ATK masteries.
*------------------------------------------*/
int64 battle_calc_masteryfix(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int64 damage, int div, bool left, bool weapon) {
int skill2_lv, i;
struct status_change *sc;
struct map_session_data *sd;
struct status_data *tstatus;
nullpo_ret(src);
nullpo_ret(target);
sc = status->get_sc(src);
sd = BL_CAST(BL_PC, src);
tstatus = status->get_status_data(target);
if ( !sd )
return damage;
damage = battle->add_mastery(sd, target, damage, left);
switch( skill_id ){ // specific skill masteries
case MO_INVESTIGATE:
case MO_EXTREMITYFIST:
case CR_GRANDCROSS:
case NJ_ISSEN:
case CR_ACIDDEMONSTRATION:
return damage;
case NJ_SYURIKEN:
if ((skill2_lv = pc->checkskill(sd,NJ_TOBIDOUGU)) > 0 && weapon)
damage += 3 * skill2_lv;
break;
case NJ_KUNAI:
if( weapon )
damage += 60;
break;
case RA_WUGDASH://(Caster Current Weight x 10 / 8)
if( sd->weight )
damage += sd->weight / 8;
/* Fall through */
case RA_WUGSTRIKE:
case RA_WUGBITE:
damage += 30*pc->checkskill(sd, RA_TOOTHOFWUG);
break;
case HT_FREEZINGTRAP:
damage += 40 * pc->checkskill(sd, RA_RESEARCHTRAP);
break;
default:
battle->calc_masteryfix_unknown(src, target, &skill_id, &skill_lv, &damage, &div, &left, &weapon);
break;
}
if( sc ){ // sc considered as masteries
if(sc->data[SC_GN_CARTBOOST])
damage += 10 * sc->data[SC_GN_CARTBOOST]->val1;
if(sc->data[SC_CAMOUFLAGE])
damage += 30 * ( 10 - sc->data[SC_CAMOUFLAGE]->val4 );
}
// general skill masteries
if( skill_id != ASC_BREAKER && weapon ) // Adv Katar Mastery is does not applies to ASC_BREAKER, but other masteries DO apply >_>
if( sd->status.weapon == W_KATAR && (skill2_lv=pc->checkskill(sd,ASC_KATAR)) > 0 )
damage += damage * (10 + 2 * skill2_lv) / 100;
// percentage factor masteries
if ( sc && sc->data[SC_MIRACLE] )
i = 2; //Star anger
else
ARR_FIND(0, MAX_PC_FEELHATE, i, status->get_class(target) == sd->hate_mob[i]);
if (i < MAX_PC_FEELHATE && (skill2_lv=pc->checkskill(sd,pc->sg_info[i].anger_id)) > 0 && weapon) {
int ratio = sd->status.base_level + status_get_dex(src) + status_get_luk(src);
if ( i == 2 ) ratio += status_get_str(src); //Star Anger
if (skill2_lv < 4 )
ratio /= (12 - 3 * skill2_lv);
damage += damage * ratio / 100;
}
if( sd->status.class_ == JOB_ARCH_BISHOP_T || sd->status.class_ == JOB_ARCH_BISHOP ){
if((skill2_lv = pc->checkskill(sd,AB_EUCHARISTICA)) > 0 &&
(tstatus->race == RC_DEMON || tstatus->def_ele == ELE_DARK) )
damage += damage * skill2_lv / 100;
}
return damage;
}
void battle_calc_masteryfix_unknown(struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int64 *damage, int *div, bool *left, bool *weapon) {
}
/*==========================================
* Elemental attribute fix.
*------------------------------------------*/
// FIXME: flag is undocumented
int64 battle_calc_elefix(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int64 damage, int nk, int n_ele, int s_ele, int s_ele_, bool left, int flag)
{
struct status_data *tstatus;
nullpo_ret(src);
nullpo_ret(target);
tstatus = status->get_status_data(target);
if ((nk&NK_NO_ELEFIX) || n_ele)
return damage;
if (damage > 0) {
if(left)
damage = battle->attr_fix(src, target, damage, s_ele_, tstatus->def_ele, tstatus->ele_lv);
else
{
damage = battle->attr_fix(src, target, damage, s_ele, tstatus->def_ele, tstatus->ele_lv);
if (skill_id == MC_CARTREVOLUTION) // Cart Revolution applies the element fix once more with neutral element
damage = battle->attr_fix(src, target, damage, ELE_NEUTRAL, tstatus->def_ele, tstatus->ele_lv);
if (skill_id == NC_ARMSCANNON)
damage = battle->attr_fix(src, target, damage, ELE_NEUTRAL, tstatus->def_ele, tstatus->ele_lv);
if (skill_id == GS_GROUNDDRIFT) // Additional 50*lv Neutral damage.
damage += battle->attr_fix(src, target, 50 * skill_lv, ELE_NEUTRAL, tstatus->def_ele, tstatus->ele_lv);
}
}
{
struct status_data *sstatus;
struct status_change *sc;
sstatus = status->get_status_data(src);
sc = status->get_sc(src);
if (sc && sc->data[SC_SUB_WEAPONPROPERTY]) { // Descriptions indicate this means adding a percent of a normal attack in another element. [Skotlex]
int64 temp = battle->calc_base_damage2(sstatus, &sstatus->rhw, sc, tstatus->size, BL_CAST(BL_PC, src), (flag?2:0)) * sc->data[SC_SUB_WEAPONPROPERTY]->val2 / 100;
damage += battle->attr_fix(src, target, temp, sc->data[SC_SUB_WEAPONPROPERTY]->val1, tstatus->def_ele, tstatus->ele_lv);
if (left) {
temp = battle->calc_base_damage2(sstatus, &sstatus->lhw, sc, tstatus->size, BL_CAST(BL_PC, src), (flag?2:0)) * sc->data[SC_SUB_WEAPONPROPERTY]->val2 / 100;
damage += battle->attr_fix(src, target, temp, sc->data[SC_SUB_WEAPONPROPERTY]->val1, tstatus->def_ele, tstatus->ele_lv);
}
}
}
return damage;
}
int64 battle_calc_cardfix2(struct block_list *src, struct block_list *bl, int64 damage, int s_ele, int nk, int flag)
{
return damage;
}
/*==========================================
* Calculates card bonuses damage adjustments.
* cflag(cardfix flag):
* &1 - calc for left hand.
* &2 - atker side cardfix(BF_WEAPON) otherwise target side(BF_WEAPON).
*------------------------------------------*/
// FIXME: wflag is undocumented
int64 battle_calc_cardfix(int attack_type, struct block_list *src, struct block_list *target, int nk, int s_ele, int s_ele_, int64 damage, int cflag, int wflag){
struct map_session_data *sd, *tsd;
short cardfix = 1000;
short t_class, s_class, s_race2, t_race2;
struct status_data *sstatus, *tstatus;
int i;
if( !damage )
return 0;
nullpo_ret(src);
nullpo_ret(target);
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
t_class = status->get_class(target);
s_class = status->get_class(src);
sstatus = status->get_status_data(src);
tstatus = status->get_status_data(target);
s_race2 = status->get_race2(src);
switch(attack_type){
case BF_MAGIC:
if ( sd && !(nk&NK_NO_CARDFIX_ATK) ) {
cardfix = cardfix * (100 + sd->magic_addrace[tstatus->race]) / 100;
if (!(nk&NK_NO_ELEFIX))
cardfix = cardfix*(100+sd->magic_addele[tstatus->def_ele]) / 100;
cardfix = cardfix * (100 + sd->magic_addsize[tstatus->size]) / 100;
cardfix = cardfix * (100 + sd->magic_addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100;
cardfix = cardfix * (100 + sd->magic_atk_ele[s_ele])/100;
for(i=0; i< ARRAYLENGTH(sd->add_mdmg) && sd->add_mdmg[i].rate; i++) {
if(sd->add_mdmg[i].class_ == t_class) {
cardfix = cardfix * (100 + sd->add_mdmg[i].rate) / 100;
break;
}
}
}
if( tsd && !(nk&NK_NO_CARDFIX_DEF) )
{ // Target cards.
if (!(nk&NK_NO_ELEFIX))
{
int ele_fix = tsd->subele[s_ele];
for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
{
if(tsd->subele2[i].ele != s_ele) continue;
if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK &&
tsd->subele2[i].flag&wflag&BF_RANGEMASK &&
tsd->subele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += tsd->subele2[i].rate;
}
cardfix = cardfix * (100 - ele_fix) / 100;
}
cardfix = cardfix * (100 - tsd->subsize[sstatus->size]) / 100;
cardfix = cardfix * (100 - tsd->subrace2[s_race2]) / 100;
cardfix = cardfix * (100 - tsd->subrace[sstatus->race]) / 100;
cardfix = cardfix * (100 - tsd->subrace[is_boss(src)?RC_BOSS:RC_NONBOSS]) / 100;
for(i=0; i < ARRAYLENGTH(tsd->add_mdef) && tsd->add_mdef[i].rate;i++) {
if(tsd->add_mdef[i].class_ == s_class) {
cardfix = cardfix * (100-tsd->add_mdef[i].rate) / 100;
break;
}
}
//It was discovered that ranged defense also counts vs magic! [Skotlex]
if ( wflag&BF_SHORT )
cardfix = cardfix * ( 100 - tsd->bonus.near_attack_def_rate ) / 100;
else
cardfix = cardfix * ( 100 - tsd->bonus.long_attack_def_rate ) / 100;
cardfix = cardfix * ( 100 - tsd->bonus.magic_def_rate ) / 100;
if( tsd->sc.data[SC_PROTECT_MDEF] )
cardfix = cardfix * ( 100 - tsd->sc.data[SC_PROTECT_MDEF]->val1 ) / 100;
}
if ( cardfix != 1000 )
damage = damage * cardfix / 1000;
break;
case BF_WEAPON:
t_race2 = status->get_race2(target);
if( cflag&2 ){
if( sd && !(nk&NK_NO_CARDFIX_ATK) ){
short cardfix_ = 1000;
if( sd->state.arrow_atk ){
cardfix = cardfix * (100 + sd->right_weapon.addrace[tstatus->race] + sd->arrow_addrace[tstatus->race]) / 100;
if( !(nk&NK_NO_ELEFIX) ){
int ele_fix = sd->right_weapon.addele[tstatus->def_ele] + sd->arrow_addele[tstatus->def_ele];
for(i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++){
if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue;
if(!(sd->right_weapon.addele2[i].flag&wflag&BF_WEAPONMASK &&
sd->right_weapon.addele2[i].flag&wflag&BF_RANGEMASK &&
sd->right_weapon.addele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += sd->right_weapon.addele2[i].rate;
}
cardfix = cardfix * (100 + ele_fix) / 100;
}
cardfix = cardfix * (100 + sd->right_weapon.addsize[tstatus->size]+sd->arrow_addsize[tstatus->size]) / 100;
cardfix = cardfix * (100 + sd->right_weapon.addrace2[t_race2]) / 100;
cardfix = cardfix * (100 + sd->right_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS] + sd->arrow_addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100;
}else{ // Melee attack
if( !battle_config.left_cardfix_to_right ){
cardfix=cardfix*(100+sd->right_weapon.addrace[tstatus->race])/100;
if( !(nk&NK_NO_ELEFIX) ){
int ele_fix = sd->right_weapon.addele[tstatus->def_ele];
for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++) {
if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue;
if(!(sd->right_weapon.addele2[i].flag&wflag&BF_WEAPONMASK &&
sd->right_weapon.addele2[i].flag&wflag&BF_RANGEMASK &&
sd->right_weapon.addele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += sd->right_weapon.addele2[i].rate;
}
cardfix = cardfix * (100+ele_fix) / 100;
}
cardfix = cardfix * (100+sd->right_weapon.addsize[tstatus->size]) / 100;
cardfix = cardfix * (100+sd->right_weapon.addrace2[t_race2]) / 100;
cardfix = cardfix * (100+sd->right_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100;
if( cflag&1 ){
cardfix_ = cardfix_*(100+sd->left_weapon.addrace[tstatus->race])/100;
if (!(nk&NK_NO_ELEFIX)){
int ele_fix_lh = sd->left_weapon.addele[tstatus->def_ele];
for (i = 0; ARRAYLENGTH(sd->left_weapon.addele2) > i && sd->left_weapon.addele2[i].rate != 0; i++) {
if (sd->left_weapon.addele2[i].ele != tstatus->def_ele) continue;
if(!(sd->left_weapon.addele2[i].flag&wflag&BF_WEAPONMASK &&
sd->left_weapon.addele2[i].flag&wflag&BF_RANGEMASK &&
sd->left_weapon.addele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix_lh += sd->left_weapon.addele2[i].rate;
}
cardfix = cardfix * (100+ele_fix_lh) / 100;
}
cardfix_ = cardfix_ * (100+sd->left_weapon.addsize[tstatus->size]) / 100;
cardfix_ = cardfix_ * (100+sd->left_weapon.addrace2[t_race2]) / 100;
cardfix_ = cardfix_ * (100+sd->left_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100;
}
}else{
int ele_fix = sd->right_weapon.addele[tstatus->def_ele] + sd->left_weapon.addele[tstatus->def_ele];
for (i = 0; ARRAYLENGTH(sd->right_weapon.addele2) > i && sd->right_weapon.addele2[i].rate != 0; i++){
if (sd->right_weapon.addele2[i].ele != tstatus->def_ele) continue;
if(!(sd->right_weapon.addele2[i].flag&wflag&BF_WEAPONMASK &&
sd->right_weapon.addele2[i].flag&wflag&BF_RANGEMASK &&
sd->right_weapon.addele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += sd->right_weapon.addele2[i].rate;
}
for (i = 0; ARRAYLENGTH(sd->left_weapon.addele2) > i && sd->left_weapon.addele2[i].rate != 0; i++){
if (sd->left_weapon.addele2[i].ele != tstatus->def_ele) continue;
if(!(sd->left_weapon.addele2[i].flag&wflag&BF_WEAPONMASK &&
sd->left_weapon.addele2[i].flag&wflag&BF_RANGEMASK &&
sd->left_weapon.addele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += sd->left_weapon.addele2[i].rate;
}
cardfix = cardfix * (100 + sd->right_weapon.addrace[tstatus->race] + sd->left_weapon.addrace[tstatus->race]) / 100;
cardfix = cardfix * (100 + ele_fix) / 100;
cardfix = cardfix * (100 + sd->right_weapon.addsize[tstatus->size] + sd->left_weapon.addsize[tstatus->size])/100;
cardfix = cardfix * (100 + sd->right_weapon.addrace2[t_race2] + sd->left_weapon.addrace2[t_race2])/100;
cardfix = cardfix * (100 + sd->right_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS] + sd->left_weapon.addrace[is_boss(target)?RC_BOSS:RC_NONBOSS]) / 100;
}
}
for( i = 0; i < ARRAYLENGTH(sd->right_weapon.add_dmg) && sd->right_weapon.add_dmg[i].rate; i++ ){
if( sd->right_weapon.add_dmg[i].class_ == t_class ){
cardfix = cardfix * (100 + sd->right_weapon.add_dmg[i].rate) / 100;
break;
}
}
if( cflag&1 ){
for( i = 0; i < ARRAYLENGTH(sd->left_weapon.add_dmg) && sd->left_weapon.add_dmg[i].rate; i++ ){
if( sd->left_weapon.add_dmg[i].class_ == t_class ){
cardfix_ = cardfix_ * (100 + sd->left_weapon.add_dmg[i].rate) / 100;
break;
}
}
}
if( wflag&BF_LONG )
cardfix = cardfix * (100 + sd->bonus.long_attack_atk_rate) / 100;
if( (cflag&1) && cardfix_ != 1000 )
damage = damage * cardfix_ / 1000;
else if( cardfix != 1000 )
damage = damage * cardfix / 1000;
}
}else{
// Target side
if( tsd && !(nk&NK_NO_CARDFIX_DEF) ){
if( !(nk&NK_NO_ELEFIX) ){
int ele_fix = tsd->subele[s_ele];
for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
{
if(tsd->subele2[i].ele != s_ele) continue;
if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK &&
tsd->subele2[i].flag&wflag&BF_RANGEMASK &&
tsd->subele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += tsd->subele2[i].rate;
}
cardfix = cardfix * (100-ele_fix) / 100;
if( cflag&1 && s_ele_ != s_ele ){
int ele_fix_lh = tsd->subele[s_ele_];
for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++){
if(tsd->subele2[i].ele != s_ele_) continue;
if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK &&
tsd->subele2[i].flag&wflag&BF_RANGEMASK &&
tsd->subele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix_lh += tsd->subele2[i].rate;
}
cardfix = cardfix * (100 - ele_fix_lh) / 100;
}
}
cardfix = cardfix * (100-tsd->subsize[sstatus->size]) / 100;
cardfix = cardfix * (100-tsd->subrace2[s_race2]) / 100;
cardfix = cardfix * (100-tsd->subrace[sstatus->race]) / 100;
cardfix = cardfix * (100-tsd->subrace[is_boss(src)?RC_BOSS:RC_NONBOSS]) / 100;
for( i = 0; i < ARRAYLENGTH(tsd->add_def) && tsd->add_def[i].rate;i++ ){
if( tsd->add_def[i].class_ == s_class )
{
cardfix = cardfix * (100 - tsd->add_def[i].rate) / 100;
break;
}
}
if( wflag&BF_SHORT )
cardfix = cardfix * (100 - tsd->bonus.near_attack_def_rate) / 100;
else // BF_LONG (there's no other choice)
cardfix = cardfix * (100 - tsd->bonus.long_attack_def_rate) / 100;
if( tsd->sc.data[SC_PROTECT_DEF] )
cardfix = cardfix * (100 - tsd->sc.data[SC_PROTECT_DEF]->val1) / 100;
if( cardfix != 1000 )
damage = damage * cardfix / 1000;
}
}
break;
case BF_MISC:
if ( tsd && !(nk&NK_NO_CARDFIX_DEF) ) {
// misc damage reduction from equipment
if ( !(nk&NK_NO_ELEFIX) )
{
int ele_fix = tsd->subele[s_ele];
for (i = 0; ARRAYLENGTH(tsd->subele2) > i && tsd->subele2[i].rate != 0; i++)
{
if(tsd->subele2[i].ele != s_ele) continue;
if(!(tsd->subele2[i].flag&wflag&BF_WEAPONMASK &&
tsd->subele2[i].flag&wflag&BF_RANGEMASK &&
tsd->subele2[i].flag&wflag&BF_SKILLMASK))
continue;
ele_fix += tsd->subele2[i].rate;
}
cardfix = cardfix * (100 - ele_fix) / 100;
}
cardfix = cardfix*(100-tsd->subrace[sstatus->race]) / 100;
cardfix = cardfix*(100-tsd->subrace[is_boss(src)?RC_BOSS:RC_NONBOSS]) / 100;
if( wflag&BF_SHORT )
cardfix = cardfix * ( 100 - tsd->bonus.near_attack_def_rate ) / 100;
else // BF_LONG (there's no other choice)
cardfix = cardfix * ( 100 - tsd->bonus.long_attack_def_rate ) / 100;
cardfix = cardfix*(100 - tsd->subsize[sstatus->size]) / 100;
cardfix = cardfix*(100 - tsd->subrace2[s_race2]) / 100;
cardfix = cardfix * (100 - tsd->bonus.misc_def_rate) / 100;
if ( cardfix != 1000 )
damage = damage * cardfix / 1000;
}
break;
}
return damage;
}
/*==========================================
* Calculates defense reduction. [malufett]
* flag:
* &1 - idef/imdef(Ignore defense)
* &2 - pdef(Pierce defense)
* &4 - tdef(Total defense reduction)
*------------------------------------------*/
// TODO: Add an enum for flag
int64 battle_calc_defense(int attack_type, struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int64 damage, int flag, int pdef){
struct status_data *sstatus, *tstatus;
struct map_session_data *sd, *tsd;
struct status_change *sc, *tsc;
int i;
if( !damage )
return 0;
nullpo_ret(src);
nullpo_ret(target);
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
sstatus = status->get_status_data(src);
tstatus = status->get_status_data(target);
sc = status->get_sc(src);
tsc = status->get_sc(target);
switch(attack_type){
case BF_WEAPON:
{
/* Take note in RE
* def1 = equip def
* def2 = status def
*/
defType def1 = status->get_def(target); //Don't use tstatus->def1 due to skill timer reductions.
short def2 = tstatus->def2, vit_def;
def1 = status->calc_def(target, tsc, def1, false); // equip def(RE)
def2 = status->calc_def2(target, tsc, def2, false); // status def(RE)
if ( sd ) {
if ( sd->charm_type == CHARM_TYPE_LAND && sd->charm_count > 0 ) // hidden from status window
def1 += 10 * def1 * sd->charm_count / 100;
i = sd->ignore_def[is_boss(target) ? RC_BOSS : RC_NONBOSS];
i += sd->ignore_def[tstatus->race];
if ( i ) {
if ( i > 100 ) i = 100;
def1 -= def1 * i / 100;
def2 -= def2 * i / 100;
}
}
if( sc && sc->data[SC_EXPIATIO] ){
i = 5 * sc->data[SC_EXPIATIO]->val1; // 5% per level
def1 -= def1 * i / 100;
def2 -= def2 * i / 100;
}
if( battle_config.vit_penalty_type && battle_config.vit_penalty_target&target->type ) {
unsigned char target_count; //256 max targets should be a sane max
target_count = unit->counttargeted(target);
if(target_count >= battle_config.vit_penalty_count) {
if(battle_config.vit_penalty_type == 1) {
if( !tsc || !tsc->data[SC_STEELBODY] )
def1 = (def1 * (100 - (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num))/100;
def2 = (def2 * (100 - (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num))/100;
} else { //Assume type 2
if( !tsc || !tsc->data[SC_STEELBODY] )
def1 -= (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num;
def2 -= (target_count - (battle_config.vit_penalty_count - 1))*battle_config.vit_penalty_num;
}
}
if(skill_id == AM_ACIDTERROR) def1 = 0; //Acid Terror ignores only armor defense. [Skotlex]
if(def2 < 1) def2 = 1;
}
//Vitality reduction from rodatazone: http://rodatazone.simgaming.net/mechanics/substats.php#def
if (tsd) {
//Sd vit-eq
//[VIT*0.5] + rnd([VIT*0.3], max([VIT*0.3],[VIT^2/150]-1))
vit_def = def2*(def2-15)/150;
vit_def = def2/2 + (vit_def>0?rnd()%vit_def:0);
if((battle->check_undead(sstatus->race,sstatus->def_ele) || sstatus->race==RC_DEMON) && //This bonus already doesn't work vs players
src->type == BL_MOB && (i=pc->checkskill(tsd,AL_DP)) > 0)
vit_def += i*(int)(3 +(tsd->status.base_level+1)*0.04); // [orn]
if( src->type == BL_MOB && (i=pc->checkskill(tsd,RA_RANGERMAIN))>0 &&
(sstatus->race == RC_BRUTE || sstatus->race == RC_FISH || sstatus->race == RC_PLANT) )
vit_def += i*5;
}
else { //Mob-Pet vit-eq
//VIT + rnd(0,[VIT/20]^2-1)
vit_def = (def2/20)*(def2/20);
vit_def = def2 + (vit_def>0?rnd()%vit_def:0);
}
if (battle_config.weapon_defense_type) {
vit_def += def1*battle_config.weapon_defense_type;
def1 = 0;
}
if( def1 > 100 ) def1 = 100;
if( !(flag&1) ){
if( flag&2 )
damage = damage * pdef * (def1+vit_def) / 100;
else
damage = damage * (100-def1) / 100;
}
if( !(flag&1 || flag&2) )
damage -= vit_def;
}
break;
case BF_MAGIC:
{
defType mdef = tstatus->mdef;
short mdef2= tstatus->mdef2;
mdef2 = status->calc_mdef2(target, tsc, mdef2, false); // status mdef(RE)
mdef = status->calc_mdef(target, tsc, mdef, false); // equip mde(RE)
if( flag&1 )
mdef = 0;
if(sd) {
i = sd->ignore_mdef[is_boss(target)?RC_BOSS:RC_NONBOSS];
i += sd->ignore_mdef[tstatus->race];
if (i)
{
if (i > 100) i = 100;
mdef -= mdef * i/100;
//mdef2-= mdef2* i/100;
}
}
if(battle_config.magic_defense_type)
damage = damage - mdef*battle_config.magic_defense_type - mdef2;
else
damage = damage * (100-mdef)/100 - mdef2;
}
break;
}
return damage;
}
// Minstrel/Wanderer number check for chorus skills.
int battle_calc_chorusbonus(struct map_session_data *sd) {
int members = 0;
if (!sd || !sd->status.party_id)
return 0;
members = party->foreachsamemap(party->sub_count_chorus, sd, 0);
if (members < 3)
return 0; // Bonus remains 0 unless 3 or more Minstrel's/Wanderer's are in the party.
if (members > 7)
return 5; // Maximum effect possible from 7 or more Minstrel's/Wanderer's
return members - 2; // Effect bonus from additional Minstrel's/Wanderer's if not above the max possible
}
// FIXME: flag is undocumented
int battle_calc_skillratio(int attack_type, struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv, int skillratio, int flag){
int i;
struct status_change *sc, *tsc;
struct map_session_data *sd, *tsd;
struct status_data *st, *tst, *bst;
nullpo_ret(src);
nullpo_ret(target);
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
sc = status->get_sc(src);
tsc = status->get_sc(target);
st = status->get_status_data(src);
bst = status->get_base_status(src);
tst = status->get_status_data(target);
switch(attack_type){
case BF_MAGIC:
switch(skill_id){
case MG_NAPALMBEAT:
skillratio += skill_lv * 10 - 30;
break;
case MG_FIREBALL:
skillratio += skill_lv * 10 - 30;
break;
case MG_SOULSTRIKE:
if (battle->check_undead(tst->race,tst->def_ele))
skillratio += 5*skill_lv;
break;
case MG_FIREWALL:
skillratio -= 50;
break;
case MG_THUNDERSTORM:
skillratio -= 20;
break;
case MG_FROSTDIVER:
skillratio += 10 * skill_lv;
break;
case AL_HOLYLIGHT:
skillratio += 25;
if (sc && sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_PRIEST)
skillratio *= 5; //Does 5x damage include bonuses from other skills?
break;
case AL_RUWACH:
skillratio += 45;
break;
case WZ_FROSTNOVA:
skillratio += (100+skill_lv*10) * 2 / 3 - 100;
break;
case WZ_FIREPILLAR:
if (skill_lv > 10)
skillratio += 2300; //200% MATK each hit
else
skillratio += -60 + 20*skill_lv; //20% MATK each hit
break;
case WZ_SIGHTRASHER:
skillratio += 20 * skill_lv;
break;
case WZ_WATERBALL:
skillratio += 30 * skill_lv;
break;
case WZ_STORMGUST:
skillratio += 40 * skill_lv;
break;
case HW_NAPALMVULCAN:
skillratio += 10 * skill_lv - 30;
break;
case SL_STIN:
skillratio += (tst->size!=SZ_SMALL?-99:10*skill_lv); //target size must be small (0) for full damage.
break;
case SL_STUN:
skillratio += (tst->size!=SZ_BIG?5*skill_lv:-99); //Full damage is dealt on small/medium targets
break;
case SL_SMA:
skillratio += -60 + status->get_lv(src); //Base damage is 40% + lv%
break;
case NJ_KOUENKA:
skillratio -= 10;
if (sd && sd->charm_type == CHARM_TYPE_FIRE && sd->charm_count > 0)
skillratio += 20 * sd->charm_count;
break;
case NJ_KAENSIN:
skillratio -= 50;
if (sd && sd->charm_type == CHARM_TYPE_FIRE && sd->charm_count > 0)
skillratio += 10 * sd->charm_count;
break;
case NJ_BAKUENRYU:
skillratio += 50 * (skill_lv - 1);
if (sd && sd->charm_type == CHARM_TYPE_FIRE && sd->charm_count > 0)
skillratio += 15 * sd->charm_count;
break;
case NJ_HYOUSYOURAKU:
skillratio += 50 * skill_lv;
if (sd && sd->charm_type == CHARM_TYPE_WATER && sd->charm_count > 0)
skillratio += 25 * sd->charm_count;
break;
case NJ_RAIGEKISAI:
skillratio += 60 + 40 * skill_lv;
if (sd && sd->charm_type == CHARM_TYPE_WIND && sd->charm_count > 0)
skillratio += 15 * sd->charm_count;
break;
case NJ_KAMAITACHI:
if (sd && sd->charm_type == CHARM_TYPE_WIND && sd->charm_count > 0)
skillratio += 10 * sd->charm_count;
/* Fall through */
case NPC_ENERGYDRAIN:
skillratio += 100 * skill_lv;
break;
case WZ_VERMILION:
skillratio += 20*skill_lv-20;
break;
/**
* Arch Bishop
**/
case AB_JUDEX:
skillratio = 300 + 20 * skill_lv;
break;
case AB_ADORAMUS:
skillratio = 500 + 100 * skill_lv;
break;
case AB_DUPLELIGHT_MAGIC:
skillratio = 200 + 20 * skill_lv;
break;
/**
* Warlock
**/
case WL_SOULEXPANSION: // MATK [{( Skill Level + 4 ) x 100 ) + ( Caster's INT )} x ( Caster's Base Level / 100 )] %
skillratio = 100 * (skill_lv + 4) + st->int_;
break;
case WL_FROSTMISTY: // MATK [{( Skill Level x 100 ) + 200 } x ( Caster's Base Level / 100 )] %
skillratio += 100 + 100 * skill_lv;
break;
case WL_JACKFROST:
if( tsc && tsc->data[SC_FROSTMISTY] ){
skillratio += 900 + 300 * skill_lv;
}else{
skillratio += 400 + 100 * skill_lv;
}
break;
case WL_DRAINLIFE:
skillratio = 200 * skill_lv + status_get_int(src);
break;
case WL_CRIMSONROCK:
skillratio = 300 * skill_lv;
skillratio += 1300;
break;
case WL_HELLINFERNO:
skillratio = 300 * skill_lv;
// Shadow: MATK [{( Skill Level x 300 ) x ( Caster Base Level / 100 ) x 4/5 }] %
// Fire : MATK [{( Skill Level x 300 ) x ( Caster Base Level / 100 ) /5 }] %
if( flag&ELE_DARK )
skillratio *= 4;
skillratio /= 5;
break;
case WL_COMET:
i = ( sc ? distance_xy(target->x, target->y, sc->comet_x, sc->comet_y) : 8 );
if( i <= 3 ) skillratio += 2400 + 500 * skill_lv; // 7 x 7 cell
else
if( i <= 5 ) skillratio += 1900 + 500 * skill_lv; // 11 x 11 cell
else
if( i <= 7 ) skillratio += 1400 + 500 * skill_lv; // 15 x 15 cell
else
skillratio += 900 + 500 * skill_lv; // 19 x 19 cell
if( sd && sd->status.party_id ){
struct map_session_data* psd;
int p_sd[5] = {0, 0, 0, 0, 0}, c; // just limit it to 5
c = 0;
memset (p_sd, 0, sizeof(p_sd));
party->foreachsamemap(skill->check_condition_char_sub, sd, 3, &sd->bl, &c, &p_sd, skill_id);
c = ( c > 1 ? rnd()%c : 0 );
if( (psd = map->id2sd(p_sd[c])) && pc->checkskill(psd,WL_COMET) > 0 ){
skillratio = skill_lv * 400; //MATK [{( Skill Level x 400 ) x ( Caster's Base Level / 120 )} + 2500 ] %
skillratio += 2500;
status_zap(&psd->bl, 0, skill->get_sp(skill_id, skill_lv) / 2);
}
}
break;
case WL_CHAINLIGHTNING_ATK:
skillratio += 400 + 100 * skill_lv;
if(flag > 0)
skillratio += 100 * flag;
break;
case WL_EARTHSTRAIN:
skillratio = 2000 + 100 * skill_lv;
break;
case WL_TETRAVORTEX_FIRE:
case WL_TETRAVORTEX_WATER:
case WL_TETRAVORTEX_WIND:
case WL_TETRAVORTEX_GROUND:
skillratio += 400 + 500 * skill_lv;
break;
case WL_SUMMON_ATK_FIRE:
case WL_SUMMON_ATK_WATER:
case WL_SUMMON_ATK_WIND:
case WL_SUMMON_ATK_GROUND:
skillratio = (1 + skill_lv) / 2 * (status->get_lv(src) + (sd ? sd->status.job_level : 50));
break;
case LG_RAYOFGENESIS:
{
uint16 lv = skill_lv;
int bandingBonus = 0;
if( sc && sc->data[SC_BANDING] )
bandingBonus = 200 * (sd ? skill->check_pc_partner(sd,skill_id,&lv,skill->get_splash(skill_id,skill_lv),0) : 1);
skillratio = ((300 * skill_lv) + bandingBonus) * (sd ? sd->status.job_level : 1) / 25;
}
break;
case LG_SHIELDSPELL:
if ( sd && skill_lv == 2 ) // [(Casters Base Level x 4) + (Shield MDEF x 100) + (Casters INT x 2)] %
skillratio = 4 * status->get_lv(src) + 100 * sd->bonus.shieldmdef + 2 * st->int_;
else
skillratio = 0;
break;
case WM_METALICSOUND:
skillratio = 120 * skill_lv + 60 * ( sd? pc->checkskill(sd, WM_LESSON) : 10 );
break;
case WM_REVERBERATION_MAGIC:
skillratio = 100 * skill_lv + 100;
break;
case SO_FIREWALK:
skillratio = 60 * skill_lv;
if( sc && sc->data[SC_HEATER_OPTION] )
skillratio += sc->data[SC_HEATER_OPTION]->val3 / 2;
break;
case SO_ELECTRICWALK:
skillratio = 60 * skill_lv;
if( sc && sc->data[SC_BLAST_OPTION] )
skillratio += sc->data[SC_BLAST_OPTION]->val2 / 2;
break;
case SO_EARTHGRAVE:
skillratio = st->int_ * skill_lv + 200 * (sd ? pc->checkskill(sd,SA_SEISMICWEAPON) : 1);
if( sc && sc->data[SC_CURSED_SOIL_OPTION] )
skillratio += sc->data[SC_CURSED_SOIL_OPTION]->val3 * 5;
break;
case SO_DIAMONDDUST:
skillratio = (st->int_ * skill_lv + 200 * (sd ? pc->checkskill(sd, SA_FROSTWEAPON) : 1)) * status->get_lv(src) / 100;
if( sc && sc->data[SC_COOLER_OPTION] )
skillratio += sc->data[SC_COOLER_OPTION]->val3 * 5;
break;
case SO_POISON_BUSTER:
skillratio += 900 + 300 * skill_lv;
if( sc && sc->data[SC_CURSED_SOIL_OPTION] )
skillratio += sc->data[SC_CURSED_SOIL_OPTION]->val3 * 5;
break;
case SO_PSYCHIC_WAVE:
skillratio = 70 * skill_lv + 3 * st->int_;
if( sc && ( sc->data[SC_HEATER_OPTION] || sc->data[SC_COOLER_OPTION]
|| sc->data[SC_BLAST_OPTION] || sc->data[SC_CURSED_SOIL_OPTION] ) )
skillratio += skillratio * 20 / 100;
break;
case SO_VARETYR_SPEAR:
skillratio = status_get_int(src) * skill_lv + ( sd ? pc->checkskill(sd, SA_LIGHTNINGLOADER) * 50 : 0 );
if( sc && sc->data[SC_BLAST_OPTION] )
skillratio += sc->data[SC_BLAST_OPTION]->val2 * 5;
break;
case SO_CLOUD_KILL:
skillratio = 40 * skill_lv;
if( sc && sc->data[SC_CURSED_SOIL_OPTION] )
skillratio += sc->data[SC_CURSED_SOIL_OPTION]->val3;
break;
case GN_DEMONIC_FIRE: {
int fire_expansion_lv = skill_lv / 100;
skill_lv = skill_lv % 100;
skillratio = 110 + 20 * skill_lv;
if ( fire_expansion_lv == 1 )
skillratio += status_get_int(src) + (sd?sd->status.job_level:50);
else if ( fire_expansion_lv == 2 )
skillratio += status_get_int(src) * 10;
}
break;
// Magical Elemental Spirits Attack Skills
case EL_FIRE_MANTLE:
case EL_WATER_SCREW:
skillratio += 900;
break;
case EL_FIRE_ARROW:
case EL_ROCK_CRUSHER_ATK:
skillratio += 200;
break;
case EL_FIRE_BOMB:
case EL_ICE_NEEDLE:
case EL_HURRICANE_ATK:
skillratio += 400;
break;
case EL_FIRE_WAVE:
case EL_TYPOON_MIS_ATK:
skillratio += 1100;
break;
case MH_ERASER_CUTTER:
skillratio += 400 + 100 * skill_lv + (skill_lv%2 > 0 ? 0 : 300);
break;
case MH_XENO_SLASHER:
if(skill_lv%2) skillratio += 350 + 50 * skill_lv; //500:600:700
else skillratio += 400 + 100 * skill_lv; //700:900
break;
case MH_HEILIGE_STANGE:
skillratio += 400 + 250 * skill_lv;
break;
case MH_POISON_MIST:
skillratio += 100 * skill_lv;
break;
case KO_KAIHOU:
if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count > 0) {
skillratio += -100 + 200 * sd->charm_count;
pc->del_charm(sd, sd->charm_count, sd->charm_type);
}
break;
default:
battle->calc_skillratio_magic_unknown(&attack_type, src, target, &skill_id, &skill_lv, &skillratio, &flag);
break;
}
break;
case BF_WEAPON:
switch( skill_id )
{
case SM_BASH:
case MS_BASH:
skillratio += 30 * skill_lv;
break;
case SM_MAGNUM:
case MS_MAGNUM:
skillratio += 20 * skill_lv;
break;
case MC_MAMMONITE:
skillratio += 50 * skill_lv;
break;
case HT_POWER:
skillratio += -50 + 8 * status_get_str(src);
break;
case AC_DOUBLE:
case MA_DOUBLE:
skillratio += 10 * (skill_lv-1);
break;
case AC_SHOWER:
case MA_SHOWER:
skillratio += -25 + 5 * skill_lv;
break;
case AC_CHARGEARROW:
case MA_CHARGEARROW:
skillratio += 50;
break;
case HT_FREEZINGTRAP:
case MA_FREEZINGTRAP:
skillratio += -50 + 10 * skill_lv;
break;
case KN_PIERCE:
case ML_PIERCE:
skillratio += 10 * skill_lv;
break;
case MER_CRASH:
skillratio += 10 * skill_lv;
break;
case KN_SPEARSTAB:
skillratio += 20 * skill_lv;
break;
case KN_SPEARBOOMERANG:
skillratio += 50*skill_lv;
break;
case KN_BRANDISHSPEAR:
case ML_BRANDISH:
{
int ratio = 100 + 20 * skill_lv;
skillratio += ratio - 100;
if(skill_lv>3 && flag==1) skillratio += ratio / 2;
if(skill_lv>6 && flag==1) skillratio += ratio / 4;
if(skill_lv>9 && flag==1) skillratio += ratio / 8;
if(skill_lv>6 && flag==2) skillratio += ratio / 2;
if(skill_lv>9 && flag==2) skillratio += ratio / 4;
if(skill_lv>9 && flag==3) skillratio += ratio / 2;
break;
}
case KN_BOWLINGBASH:
case MS_BOWLINGBASH:
skillratio+= 40 * skill_lv;
break;
case AS_GRIMTOOTH:
skillratio += 20 * skill_lv;
break;
case AS_POISONREACT:
skillratio += 30 * skill_lv;
break;
case AS_SONICBLOW:
skillratio += 300 + 40 * skill_lv;
break;
case TF_SPRINKLESAND:
skillratio += 30;
break;
case MC_CARTREVOLUTION:
skillratio += 50;
if( sd && sd->cart_weight )
skillratio += 100 * sd->cart_weight / sd->cart_weight_max; // +1% every 1% weight
else if (!sd)
skillratio += 100; //Max damage for non players.
break;
case NPC_RANDOMATTACK:
skillratio += 100 * skill_lv;
break;
case NPC_WATERATTACK:
case NPC_GROUNDATTACK:
case NPC_FIREATTACK:
case NPC_WINDATTACK:
case NPC_POISONATTACK:
case NPC_HOLYATTACK:
case NPC_DARKNESSATTACK:
case NPC_UNDEADATTACK:
case NPC_TELEKINESISATTACK:
case NPC_BLOODDRAIN:
case NPC_ACIDBREATH:
case NPC_DARKNESSBREATH:
case NPC_FIREBREATH:
case NPC_ICEBREATH:
case NPC_THUNDERBREATH:
case NPC_HELLJUDGEMENT:
case NPC_PULSESTRIKE:
skillratio += 100 * (skill_lv-1);
break;
case NPC_EARTHQUAKE:
skillratio += 100 + 100 * skill_lv + 100 * (skill_lv / 2);
break;
case RG_BACKSTAP:
if( sd && sd->status.weapon == W_BOW && battle_config.backstab_bow_penalty )
skillratio += (200 + 40 * skill_lv) / 2;
else
skillratio += 200 + 40 * skill_lv;
break;
case RG_RAID:
skillratio += 40 * skill_lv;
break;
case RG_INTIMIDATE:
skillratio += 30 * skill_lv;
break;
case CR_SHIELDCHARGE:
skillratio += 20 * skill_lv;
break;
case CR_SHIELDBOOMERANG:
skillratio += 30 * skill_lv;
break;
case NPC_DARKCROSS:
case CR_HOLYCROSS:
{
int ratio = 35 * skill_lv;
skillratio += ratio;
break;
}
case AM_DEMONSTRATION:
skillratio += 20 * skill_lv;
break;
case AM_ACIDTERROR:
skillratio += 40 * skill_lv;
break;
case MO_FINGEROFFENSIVE:
skillratio+= 50 * skill_lv;
break;
case MO_INVESTIGATE:
skillratio += 75 * skill_lv;
break;
case MO_EXTREMITYFIST:
{
//Overflow check. [Skotlex]
unsigned int ratio = skillratio + 100*(8 + st->sp/10);
//You'd need something like 6K SP to reach this max, so should be fine for most purposes.
if (ratio > 60000) ratio = 60000; //We leave some room here in case skillratio gets further increased.
skillratio = (unsigned short)ratio;
}
break;
case MO_TRIPLEATTACK:
skillratio += 20 * skill_lv;
break;
case MO_CHAINCOMBO:
skillratio += 50 + 50 * skill_lv;
break;
case MO_COMBOFINISH:
skillratio += 140 + 60 * skill_lv;
break;
case BA_MUSICALSTRIKE:
case DC_THROWARROW:
skillratio += 25 + 25 * skill_lv;
break;
case CH_TIGERFIST:
skillratio += 100 * skill_lv - 60;
break;
case CH_CHAINCRUSH:
skillratio += 300 + 100 * skill_lv;
break;
case CH_PALMSTRIKE:
skillratio += 100 + 100 * skill_lv;
break;
case LK_HEADCRUSH:
skillratio += 40 * skill_lv;
break;
case LK_JOINTBEAT:
i = 10 * skill_lv - 50;
// Although not clear, it's being assumed that the 2x damage is only for the break neck ailment.
if (flag&BREAK_NECK) i*=2;
skillratio += i;
break;
case ASC_METEORASSAULT:
skillratio += 40 * skill_lv - 60;
break;
case SN_SHARPSHOOTING:
case MA_SHARPSHOOTING:
skillratio += 100 + 50 * skill_lv;
break;
case CG_ARROWVULCAN:
skillratio += 100 + 100 * skill_lv;
break;
case AS_SPLASHER:
skillratio += 400 + 50 * skill_lv;
if(sd)
skillratio += 20 * pc->checkskill(sd,AS_POISONREACT);
break;
case ASC_BREAKER:
skillratio += 100*skill_lv-100;
break;
case PA_SACRIFICE:
skillratio += 10 * skill_lv - 10;
break;
case PA_SHIELDCHAIN:
skillratio += 30 * skill_lv;
break;
case WS_CARTTERMINATION:
i = 10 * (16 - skill_lv);
if (i < 1) i = 1;
//Preserve damage ratio when max cart weight is changed.
if(sd && sd->cart_weight)
skillratio += sd->cart_weight/i * 80000/battle_config.max_cart_weight - 100;
else if (!sd)
skillratio += 80000 / i - 100;
break;
case TK_DOWNKICK:
skillratio += 60 + 20 * skill_lv;
break;
case TK_STORMKICK:
skillratio += 60 + 20 * skill_lv;
break;
case TK_TURNKICK:
skillratio += 90 + 30 * skill_lv;
break;
case TK_COUNTER:
skillratio += 90 + 30 * skill_lv;
break;
case TK_JUMPKICK:
skillratio += -70 + 10*skill_lv;
if (sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == skill_id)
skillratio += 10 * status->get_lv(src) / 3; //Tumble bonus
if (flag) {
skillratio += 10 * status->get_lv(src) / 3; //Running bonus (TODO: What is the real bonus?)
if( sc && sc->data[SC_STRUP] ) // Spurt bonus
skillratio *= 2;
}
break;
case GS_TRIPLEACTION:
skillratio += 50 * skill_lv;
break;
case GS_BULLSEYE:
//Only works well against brute/demi-humans non bosses.
if((tst->race == RC_BRUTE || tst->race == RC_DEMIHUMAN)
&& !(tst->mode&MD_BOSS))
skillratio += 400;
break;
case GS_TRACKING:
skillratio += 100 * (skill_lv+1);
break;
case GS_PIERCINGSHOT:
skillratio += 20 * skill_lv;
break;
case GS_RAPIDSHOWER:
skillratio += 10 * skill_lv;
break;
case GS_DESPERADO:
skillratio += 50 * (skill_lv-1);
break;
case GS_DUST:
skillratio += 50 * skill_lv;
break;
case GS_FULLBUSTER:
skillratio += 100 * (skill_lv+2);
break;
case GS_SPREADATTACK:
skillratio += 20 * (skill_lv-1);
break;
case NJ_HUUMA:
skillratio += 50 + 150 * skill_lv;
break;
case NJ_TATAMIGAESHI:
skillratio += 10 * skill_lv;
break;
case NJ_KASUMIKIRI:
skillratio += 10 * skill_lv;
break;
case NJ_KIRIKAGE:
skillratio += 100 * (skill_lv-1);
break;
case KN_CHARGEATK:
{
int k = (flag-1)/3; //+100% every 3 cells of distance
if( k > 2 ) k = 2; // ...but hard-limited to 300%.
skillratio += 100 * k;
}
break;
case HT_PHANTASMIC:
skillratio += 50;
break;
case MO_BALKYOUNG:
skillratio += 200;
break;
case HFLI_MOON: //[orn]
skillratio += 10 + 110 * skill_lv;
break;
case HFLI_SBR44: //[orn]
skillratio += 100 * (skill_lv-1);
break;
case NPC_VAMPIRE_GIFT:
skillratio += ((skill_lv-1)%5+1) * 100;
break;
case RK_SONICWAVE:
skillratio = (skill_lv + 5) * 100;
skillratio = skillratio * (100 + (status->get_lv(src)-100) / 2) / 100;
break;
case RK_HUNDREDSPEAR:
skillratio += 500 + (80 * skill_lv);
if( sd ){
short index = sd->equip_index[EQI_HAND_R];
if( index >= 0 && sd->inventory_data[index]
&& sd->inventory_data[index]->type == IT_WEAPON )
skillratio += (10000 - min(10000, sd->inventory_data[index]->weight)) / 10;
skillratio = skillratio * (100 + (status->get_lv(src)-100) / 2) / 100 + 50 * pc->checkskill(sd,LK_SPIRALPIERCE);
}
break;
case RK_WINDCUTTER:
skillratio = (skill_lv + 2) * 50;
break;
case RK_IGNITIONBREAK:
i = distance_bl(src,target);
if( i < 2 )
skillratio = 300 * skill_lv;
else if( i < 4 )
skillratio = 250 * skill_lv;
else
skillratio = 200 * skill_lv;
skillratio = skillratio * status->get_lv(src) / 100;
if( st->rhw.ele == ELE_FIRE )
skillratio += 100 * skill_lv;
break;
case RK_STORMBLAST:
skillratio = ((sd ? pc->checkskill(sd,RK_RUNEMASTERY) : 1) + status_get_int(src) / 8) * 100;
break;
case RK_PHANTOMTHRUST:
skillratio = 50 * skill_lv + 10 * (sd ? pc->checkskill(sd,KN_SPEARMASTERY) : 10);
break;
/**
* GC Guillotine Cross
**/
case GC_CROSSIMPACT:
skillratio += 900 + 100 * skill_lv;
break;
case GC_PHANTOMMENACE:
skillratio += 200;
break;
case GC_COUNTERSLASH:
//ATK [{(Skill Level x 100) + 300} x Caster's Base Level / 120]% + ATK [(AGI x 2) + (Caster's Job Level x 4)]%
skillratio += 200 + (100 * skill_lv);
break;
case GC_ROLLINGCUTTER:
skillratio = 50 + 50 * skill_lv;
break;
case GC_CROSSRIPPERSLASHER:
skillratio += 300 + 80 * skill_lv;
if( sc && sc->data[SC_ROLLINGCUTTER] )
skillratio += sc->data[SC_ROLLINGCUTTER]->val1 * status_get_agi(src);
break;
case GC_DARKCROW:
skillratio += 100 * (skill_lv - 1);
break;
/**
* Arch Bishop
**/
case AB_DUPLELIGHT_MELEE:
skillratio += 10 * skill_lv;
break;
/**
* Ranger
**/
case RA_ARROWSTORM:
skillratio += 900 + 80 * skill_lv;
break;
case RA_AIMEDBOLT:
skillratio += 400 + 50 * skill_lv;
break;
case RA_CLUSTERBOMB:
skillratio += 100 + 100 * skill_lv;
break;
case RA_WUGDASH:// ATK 300%
skillratio = 300;
if( sc && sc->data[SC_DANCE_WITH_WUG] )
skillratio += 10 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd));
break;
case RA_WUGSTRIKE:
skillratio = 200 * skill_lv;
if( sc && sc->data[SC_DANCE_WITH_WUG] )
skillratio += 10 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd));
break;
case RA_WUGBITE:
skillratio += 300 + 200 * skill_lv;
if ( skill_lv == 5 ) skillratio += 100;
break;
case RA_SENSITIVEKEEN:
skillratio = 150 * skill_lv;
break;
/**
* Mechanic
**/
case NC_BOOSTKNUCKLE:
skillratio = skill_lv * 100 + 200 + st->dex;
break;
case NC_PILEBUNKER:
skillratio = skill_lv*100 + 300 + status_get_str(src);
break;
case NC_VULCANARM:
skillratio = 70 * skill_lv + status_get_dex(src);
break;
case NC_FLAMELAUNCHER:
case NC_COLDSLOWER:
skillratio += 200 + 300 * skill_lv;
break;
case NC_ARMSCANNON:
switch( tst->size ) {
case SZ_SMALL: skillratio = 300 + 350 * skill_lv; break; // Medium
case SZ_MEDIUM: skillratio = 300 + 400 * skill_lv; break; // Small
case SZ_BIG: skillratio = 300 + 300 * skill_lv; break; // Large
}
break;
case NC_AXEBOOMERANG:
skillratio = 250 + 50 * skill_lv;
if( sd ) {
short index = sd->equip_index[EQI_HAND_R];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON )
skillratio += sd->inventory_data[index]->weight / 10;
}
break;
case NC_POWERSWING:
skillratio = 300 + 100*skill_lv + ( status_get_str(src)+status_get_dex(src) ) * status->get_lv(src) / 100;
break;
case NC_AXETORNADO:
skillratio = 200 + 100 * skill_lv + st->vit;
if( st->rhw.ele == ELE_WIND )
skillratio = skillratio * 125 / 100;
if ( distance_bl(src, target) > 2 ) // Will deal 75% damage outside of 5x5 area.
skillratio = skillratio * 75 / 100;
break;
case SC_FATALMENACE:
skillratio = 100 * (skill_lv+1);
break;
case SC_TRIANGLESHOT:
skillratio = ( 300 + (skill_lv-1) * status_get_agi(src)/2 );
break;
case SC_FEINTBOMB:
skillratio = (skill_lv+1) * (st->dex/2) * (sd?sd->status.job_level:50)/10;
break;
case LG_CANNONSPEAR:
skillratio = (50 + st->str) * skill_lv;
break;
case LG_BANISHINGPOINT:
skillratio = 50 * skill_lv + 30 * (sd ? pc->checkskill(sd,SM_BASH) : 10);
break;
case LG_SHIELDPRESS:
skillratio = 150 * skill_lv + st->str;
if( sd ) {
short index = sd->equip_index[EQI_HAND_L];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR )
skillratio += sd->inventory_data[index]->weight / 10;
}
break;
case LG_PINPOINTATTACK:
skillratio = 100 * skill_lv + 5 * st->agi;
break;
case LG_RAGEBURST:
if( sc ){
skillratio += -100 + (status_get_max_hp(src) - status_get_hp(src)) / 100 + sc->fv_counter * 200;
clif->millenniumshield(src, (sc->fv_counter = 0));
}
break;
case LG_SHIELDSPELL:
if ( sd && skill_lv == 1 ) {
struct item_data *shield_data = sd->inventory_data[sd->equip_index[EQI_HAND_L]];
if( shield_data )
skillratio = 4 * status->get_lv(src) + 10 * shield_data->def + 2 * st->vit;
}
else
skillratio = 0; // Prevents ATK damage from being done on LV 2 usage since LV 2 us MATK. [Rytech]
break;
case LG_MOONSLASHER:
skillratio = 120 * skill_lv + 80 * (sd ? pc->checkskill(sd,LG_OVERBRAND) : 5);
break;
case LG_OVERBRAND:
skillratio += -100 + 400 * skill_lv + 50 * ((sd) ? pc->checkskill(sd,CR_SPEARQUICKEN) : 1);
break;
case LG_OVERBRAND_BRANDISH:
skillratio += -100 + 300 * skill_lv + status_get_str(src) + status_get_dex(src);
break;
case LG_OVERBRAND_PLUSATK:
skillratio = 200 * skill_lv + rnd_value( 10, 100);
break;
case LG_RAYOFGENESIS:
skillratio = 300 + 300 * skill_lv;
break;
case LG_EARTHDRIVE:
if( sd ) {
short index = sd->equip_index[EQI_HAND_L];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR )
skillratio = (1 + skill_lv) * sd->inventory_data[index]->weight / 10;
}
break;
case LG_HESPERUSLIT:
skillratio = 120 * skill_lv;
if( sc && sc->data[SC_BANDING] )
skillratio += 200 * sc->data[SC_BANDING]->val2;
if( sc && sc->data[SC_BANDING] && sc->data[SC_BANDING]->val2 > 5 )
skillratio = skillratio * 150 / 100;
if( sc && sc->data[SC_INSPIRATION] )
skillratio += 600;
break;
case SR_DRAGONCOMBO:
skillratio += 40 * skill_lv;
break;
case SR_SKYNETBLOW:
if( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_DRAGONCOMBO )//ATK [{(Skill Level x 100) + (Caster AGI) + 150} x Caster Base Level / 100] %
skillratio += 100 * skill_lv + status_get_agi(src) + 50;
else //ATK [{(Skill Level x 80) + (Caster AGI)} x Caster Base Level / 100] %
skillratio += -100 + 80 * skill_lv + status_get_agi(src);
break;
case SR_EARTHSHAKER:
if( tsc && (tsc->data[SC_HIDING] || tsc->data[SC_CLOAKING] || // [(Skill Level x 150) x (Caster Base Level / 100) + (Caster INT x 3)] %
tsc->data[SC_CHASEWALK] || tsc->data[SC_CLOAKINGEXCEED] || tsc->data[SC__INVISIBILITY]) ){
skillratio += -100 + 150 * skill_lv;
skillratio += status_get_int(src) * 3;
}else{ //[(Skill Level x 50) x (Caster Base Level / 100) + (Caster INT x 2)] %
skillratio += 50 * (skill_lv-2);
skillratio += status_get_int(src) * 2;
}
break;
case SR_FALLENEMPIRE:// ATK [(Skill Level x 150 + 100) x Caster Base Level / 150] %
skillratio += 150 *skill_lv;
break;
case SR_TIGERCANNON:// ATK [((Caster consumed HP + SP) / 4) x Caster Base Level / 100] %
{
int hp = status_get_max_hp(src) * (10 + 2 * skill_lv) / 100,
sp = status_get_max_sp(src) * (6 + skill_lv) / 100;
if( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE ) // ATK [((Caster consumed HP + SP) / 2) x Caster Base Level / 100] %
skillratio += -100 + (hp+sp) / 2;
else
skillratio += -100 + (hp+sp) / 4;
}
break;
case SR_RAMPAGEBLASTER:
skillratio += 20 * skill_lv * (sd?sd->spiritball_old:5) - 100;
if( sc && sc->data[SC_EXPLOSIONSPIRITS] ) {
skillratio += sc->data[SC_EXPLOSIONSPIRITS]->val1 * 20;
} else {
}
break;
case SR_KNUCKLEARROW:
if ( flag&4 || map->list[src->m].flag.gvg_castle || tst->mode&MD_BOSS ) {
// ATK [(Skill Level x 150) + (1000 x Target current weight / Maximum weight) + (Target Base Level x 5) x (Caster Base Level / 150)] %
skillratio = 150 * skill_lv + status->get_lv(target) * 5 * (status->get_lv(src) / 100) ;
if( tsd && tsd->weight )
skillratio += 100 * (tsd->weight / tsd->max_weight);
}else // ATK [(Skill Level x 100 + 500) x Caster Base Level / 100] %
skillratio += 400 + (100 * skill_lv);
break;
case SR_WINDMILL: // ATK [(Caster Base Level + Caster DEX) x Caster Base Level / 100] %
skillratio = status->get_lv(src) + status_get_dex(src);
break;
case SR_GATEOFHELL:
if( sc && sc->data[SC_COMBOATTACK]
&& sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE )
skillratio += 800 * skill_lv -100;
else
skillratio += 500 * skill_lv -100;
break;
case SR_GENTLETOUCH_QUIET:
skillratio += 100 * skill_lv - 100 + status_get_dex(src);
break;
case SR_HOWLINGOFLION:
skillratio += 300 * skill_lv - 100;
break;
case SR_RIDEINLIGHTNING: // ATK [{(Skill Level x 200) + Additional Damage} x Caster Base Level / 100] %
if( (st->rhw.ele) == ELE_WIND || (st->lhw.ele) == ELE_WIND )
skillratio += skill_lv * 50;
skillratio += -100 + 200 * skill_lv;
break;
case WM_REVERBERATION_MELEE:
skillratio += 200 + 100 * skill_lv;
break;
case WM_SEVERE_RAINSTORM_MELEE:
skillratio = (st->agi + st->dex) * skill_lv / 5;
break;
case WM_GREAT_ECHO:
{
int chorusbonus = battle->calc_chorusbonus(sd);
skillratio += 300 + 200 * skill_lv;
//Chorus bonus don't count the first 2 Minstrel's/Wanderer's and only increases when their's 3 or more. [Rytech]
if (chorusbonus >= 1 && chorusbonus <= 5)
skillratio += 100<<(chorusbonus-1); // 1->100; 2->200; 3->400; 4->800; 5->1600
}
break;
case GN_CART_TORNADO:
{
int strbonus = bst->str;
skillratio = 50 * skill_lv + (sd ? sd->cart_weight : battle_config.max_cart_weight) / 10 / max(150 - strbonus, 1) + 50 * (sd ? pc->checkskill(sd, GN_REMODELING_CART) : 5);
}
break;
case GN_CARTCANNON:
skillratio += -100 + (int)(50.0f * (sd ? pc->checkskill(sd, GN_REMODELING_CART) : 5) * (st->int_ / 40.0f) + 60.0f * skill_lv);
break;
case GN_SPORE_EXPLOSION:
skillratio = 100 * skill_lv + (200 + st->int_) * status->get_lv(src) / 100;
/* Fall through */
case GN_CRAZYWEED_ATK:
skillratio += 400 + 100 * skill_lv;
break;
case GN_SLINGITEM_RANGEMELEEATK:
if( sd ) {
switch( sd->itemid ) {
case ITEMID_APPLE_BOMB:
skillratio = st->str + st->dex + 300;
break;
case ITEMID_MELON_BOMB:
skillratio = st->str + st->dex + 500;
break;
case ITEMID_COCONUT_BOMB:
case ITEMID_PINEAPPLE_BOMB:
case ITEMID_BANANA_BOMB:
skillratio = st->str + st->dex + 800;
break;
case ITEMID_BLACK_LUMP:
skillratio = (st->str + st->agi + st->dex) / 3; // Black Lump
break;
case ITEMID_BLACK_HARD_LUMP:
skillratio = (st->str + st->agi + st->dex) / 2; // Hard Black Lump
break;
case ITEMID_VERY_HARD_LUMP:
skillratio = st->str + st->agi + st->dex; // Extremely Hard Black Lump
break;
}
}
break;
case SO_VARETYR_SPEAR://ATK [{( Striking Level x 50 ) + ( Varetyr Spear Skill Level x 50 )} x Caster Base Level / 100 ] %
skillratio += -100 + 50 * skill_lv + ( sd ? pc->checkskill(sd, SO_STRIKING) * 50 : 0 );
if( sc && sc->data[SC_BLAST_OPTION] )
skillratio += (sd ? sd->status.job_level * 5 : 0);
break;
// Physical Elemental Spirits Attack Skills
case EL_CIRCLE_OF_FIRE:
case EL_FIRE_BOMB_ATK:
case EL_STONE_RAIN:
skillratio += 200;
break;
case EL_FIRE_WAVE_ATK:
skillratio += 500;
break;
case EL_TIDAL_WEAPON:
skillratio += 1400;
break;
case EL_WIND_SLASH:
skillratio += 100;
break;
case EL_HURRICANE:
skillratio += 600;
break;
case EL_TYPOON_MIS:
case EL_WATER_SCREW_ATK:
skillratio += 900;
break;
case EL_STONE_HAMMER:
skillratio += 400;
break;
case EL_ROCK_CRUSHER:
skillratio += 700;
break;
case KO_JYUMONJIKIRI:
skillratio += -100 + 150 * skill_lv;
if( tsc && tsc->data[SC_KO_JYUMONJIKIRI] )
skillratio += status->get_lv(src) * skill_lv;
break;
case KO_HUUMARANKA:
skillratio += -100 + 150 * skill_lv + status_get_agi(src) + status_get_dex(src) + 100 * (sd ? pc->checkskill(sd, NJ_HUUMA) : 0);
break;
case KO_SETSUDAN:
skillratio += -100 + 100 * skill_lv;
break;
case MH_NEEDLE_OF_PARALYZE:
skillratio += 600 + 100 * skill_lv;
break;
case MH_STAHL_HORN:
skillratio += 400 + 100 * skill_lv;
break;
case MH_LAVA_SLIDE:
skillratio += -100 + 70 * skill_lv;
break;
case MH_TINDER_BREAKER:
case MH_MAGMA_FLOW:
skillratio += -100 + 100 * skill_lv;
break;
default:
battle->calc_skillratio_weapon_unknown(&attack_type, src, target, &skill_id, &skill_lv, &skillratio, &flag);
break;
}
//Skill damage modifiers that stack linearly
if(sc && skill_id != PA_SACRIFICE){
if(sc->data[SC_OVERTHRUST])
skillratio += sc->data[SC_OVERTHRUST]->val3;
if(sc->data[SC_OVERTHRUSTMAX])
skillratio += sc->data[SC_OVERTHRUSTMAX]->val2;
if(sc->data[SC_BERSERK])
skillratio += 100;
if( (!skill_id || skill_id == KN_AUTOCOUNTER) && sc->data[SC_CRUSHSTRIKE] ){
if( sd )
{//ATK [{Weapon Level * (Weapon Upgrade Level + 6) * 100} + (Weapon ATK) + (Weapon Weight)]%
short index = sd->equip_index[EQI_HAND_R];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_WEAPON )
skillratio += -100 + sd->inventory_data[index]->weight/10 + st->rhw.atk +
100 * sd->inventory_data[index]->wlv * (sd->status.inventory[index].refine + 6);
}
status_change_end(src, SC_CRUSHSTRIKE, INVALID_TIMER);
skill->break_equip(src,EQP_WEAPON,2000,BCT_SELF); // 20% chance to destroy the weapon.
}
}
}
if( skillratio < 1 )
return 0;
return skillratio;
}
void battle_calc_skillratio_magic_unknown(int *attack_type, struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int *skillratio, int *flag) {
}
void battle_calc_skillratio_weapon_unknown(int *attack_type, struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int *skillratio, int *flag) {
}
/*==========================================
* Check damage trough status.
* ATK may be MISS, BLOCKED FAIL, reduce, increase, end status...
* After this we apply bg/gvg reduction
*------------------------------------------*/
int64 battle_calc_damage(struct block_list *src,struct block_list *bl,struct Damage *d,int64 damage,uint16 skill_id,uint16 skill_lv) {
struct map_session_data *s_sd, *t_sd;
struct status_change *s_sc, *sc;
struct status_change_entry *sce;
int div_, flag;
nullpo_ret(bl);
nullpo_ret(d);
s_sd = BL_CAST(BL_PC, src);
t_sd = BL_CAST(BL_PC, bl);
div_ = d->div_;
flag = d->flag;
// need check src for null pointer?
if( !damage )
return 0;
if( battle_config.ksprotection && mob->ksprotected(src, bl) )
return 0;
if (t_sd != NULL) {
//Special no damage states
if(flag&BF_WEAPON && t_sd->special_state.no_weapon_damage)
damage -= damage * t_sd->special_state.no_weapon_damage / 100;
if(flag&BF_MAGIC && t_sd->special_state.no_magic_damage)
damage -= damage * t_sd->special_state.no_magic_damage / 100;
if(flag&BF_MISC && t_sd->special_state.no_misc_damage)
damage -= damage * t_sd->special_state.no_misc_damage / 100;
if(!damage) return 0;
}
s_sc = status->get_sc(src);
sc = status->get_sc(bl);
if( sc && sc->data[SC_INVINCIBLE] && !sc->data[SC_INVINCIBLEOFF] )
return 1;
if (skill_id == PA_PRESSURE)
return damage; //This skill bypass everything else.
if( sc && sc->count )
{
//First, sc_*'s that reduce damage to 0.
if( sc->data[SC_BASILICA] && !(status_get_mode(src)&MD_BOSS) )
{
d->dmg_lv = ATK_BLOCK;
return 0;
}
if( sc->data[SC_WHITEIMPRISON] && skill_id != HW_GRAVITATION ) { // Gravitation and Pressure do damage without removing the effect
if( skill_id == MG_NAPALMBEAT ||
skill_id == MG_SOULSTRIKE ||
skill_id == WL_SOULEXPANSION ||
(skill_id && skill->get_ele(skill_id, skill_lv) == ELE_GHOST) ||
(!skill_id && (status->get_status_data(src))->rhw.ele == ELE_GHOST)
){
if( skill_id == WL_SOULEXPANSION )
damage <<= 1; // If used against a player in White Imprison, the skill deals double damage.
status_change_end(bl,SC_WHITEIMPRISON,INVALID_TIMER); // Those skills do damage and removes effect
}else{
d->dmg_lv = ATK_BLOCK;
return 0;
}
}
if( sc->data[SC_ZEPHYR] && ((flag&BF_LONG) || rnd()%100 < 10) ) {
d->dmg_lv = ATK_BLOCK;
return 0;
}
if( sc->data[SC_SAFETYWALL] && (flag&(BF_SHORT|BF_MAGIC))==BF_SHORT )
{
struct skill_unit_group* group = skill->id2group(sc->data[SC_SAFETYWALL]->val3);
uint16 src_skill_id = sc->data[SC_SAFETYWALL]->val2;
if (group) {
d->dmg_lv = ATK_BLOCK;
if(src_skill_id == MH_STEINWAND){
if (--group->val2<=0)
skill->del_unitgroup(group,ALC_MARK);
if( (group->val3 - damage) > 0 )
group->val3 -= (int)cap_value(damage, INT_MIN, INT_MAX);
else
skill->del_unitgroup(group,ALC_MARK);
return 0;
}
if( skill_id == SO_ELEMENTAL_SHIELD ) {
if ( ( group->val2 - damage) > 0 ) {
group->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX);
} else
skill->del_unitgroup(group,ALC_MARK);
return 0;
}
if (--group->val2<=0)
skill->del_unitgroup(group,ALC_MARK);
return 0;
}
status_change_end(bl, SC_SAFETYWALL, INVALID_TIMER);
}
if( ( sc->data[SC_PNEUMA] && (flag&(BF_MAGIC|BF_LONG)) == BF_LONG ) || sc->data[SC__MANHOLE] ) {
d->dmg_lv = ATK_BLOCK;
return 0;
}
if( sc->data[SC_NEUTRALBARRIER] && (flag&(BF_MAGIC|BF_LONG)) == BF_LONG && skill_id != CR_ACIDDEMONSTRATION ) {
d->dmg_lv = ATK_BLOCK;
return 0;
}
if( sc->data[SC__MAELSTROM] && (flag&BF_MAGIC) && skill_id && (skill->get_inf(skill_id)&INF_GROUND_SKILL) ) {
// {(Maelstrom Skill LevelxAbsorbed Skill Level)+(Caster's Job/5)}/2
int sp = (sc->data[SC__MAELSTROM]->val1 * skill_lv + (t_sd ? t_sd->status.job_level / 5 : 0)) / 2;
status->heal(bl, 0, sp, 3);
d->dmg_lv = ATK_BLOCK;
return 0;
}
if( sc->data[SC_WEAPONBLOCKING] && flag&(BF_SHORT|BF_WEAPON) && rnd()%100 < sc->data[SC_WEAPONBLOCKING]->val2 )
{
clif->skill_nodamage(bl,src,GC_WEAPONBLOCKING,1,1);
d->dmg_lv = ATK_BLOCK;
sc_start2(src,bl,SC_COMBOATTACK,100,GC_WEAPONBLOCKING,src->id,2000);
return 0;
}
if ((sce=sc->data[SC_AUTOGUARD]) && flag&BF_WEAPON && !(skill->get_nk(skill_id)&NK_NO_CARDFIX_ATK) && rnd()%100 < sce->val2) {
int delay;
struct status_change_entry *sce_d = sc->data[SC_DEVOTION];
// different delay depending on skill level [celest]
if (sce->val1 <= 5)
delay = 300;
else if (sce->val1 > 5 && sce->val1 <= 9)
delay = 200;
else
delay = 100;
if (sce_d) {
// If the target is too far away from the devotion caster, autoguard has no effect
// Autoguard will be disabled later on
struct block_list *d_bl = map->id2bl(sce_d->val1);
struct mercenary_data *d_md = BL_CAST(BL_MER, d_bl);
struct map_session_data *d_sd = BL_CAST(BL_PC, d_bl);
if (d_bl != NULL && check_distance_bl(bl, d_bl, sce_d->val3)
&& ((d_bl->type == BL_MER && d_md->master != NULL && d_md->master->bl.id == bl->id)
|| (d_bl->type == BL_PC && d_sd->devotion[sce_d->val2] == bl->id))
) {
// if player is target of devotion, show guard effect on the devotion caster rather than the target
clif->skill_nodamage(d_bl, d_bl, CR_AUTOGUARD, sce->val1, 1);
unit->set_walkdelay(d_bl, timer->gettick(), delay, 1);
d->dmg_lv = ATK_MISS;
return 0;
}
} else {
clif->skill_nodamage(bl, bl, CR_AUTOGUARD, sce->val1, 1);
unit->set_walkdelay(bl, timer->gettick(), delay, 1);
if(sc->data[SC_CR_SHRINK] && rnd()%100<5*sce->val1)
skill->blown(bl,src,skill->get_blewcount(CR_SHRINK,1),-1,0);
d->dmg_lv = ATK_MISS;
return 0;
}
}
if( (sce = sc->data[SC_MILLENNIUMSHIELD]) && sce->val2 > 0 && damage > 0 ) {
clif->skill_nodamage(bl, bl, RK_MILLENNIUMSHIELD, 1, 1);
sce->val3 -= (int)cap_value(damage,INT_MIN,INT_MAX); // absorb damage
d->dmg_lv = ATK_BLOCK;
sc_start(src,bl,SC_STUN,15,0,skill->get_time2(RK_MILLENNIUMSHIELD,sce->val1)); // There is a chance to be stunned when one shield is broken.
if( sce->val3 <= 0 ) { // Shield Down
sce->val2--;
if( sce->val2 > 0 ) {
clif->millenniumshield(bl,sce->val2);
sce->val3 = 1000; // Next Shield
} else
status_change_end(bl,SC_MILLENNIUMSHIELD,INVALID_TIMER); // All shields down
}
return 0;
}
if( (sce=sc->data[SC_PARRYING]) && flag&BF_WEAPON && skill_id != WS_CARTTERMINATION && rnd()%100 < sce->val2 )
{ // attack blocked by Parrying
clif->skill_nodamage(bl, bl, LK_PARRYING, sce->val1,1);
return 0;
}
if(sc->data[SC_DODGE_READY] && ( !sc->opt1 || sc->opt1 == OPT1_BURNING ) &&
(flag&BF_LONG || sc->data[SC_STRUP])
&& rnd()%100 < 20) {
if (t_sd && pc_issit(t_sd)) pc->setstand(t_sd); //Stand it to dodge.
clif->skill_nodamage(bl,bl,TK_DODGE,1,1);
if (!sc->data[SC_COMBOATTACK])
sc_start4(src, bl, SC_COMBOATTACK, 100, TK_JUMPKICK, src->id, 1, 0, 2000);
return 0;
}
if((sc->data[SC_HERMODE]) && flag&BF_MAGIC)
return 0;
if(sc->data[SC_NJ_TATAMIGAESHI] && (flag&(BF_MAGIC|BF_LONG)) == BF_LONG)
return 0;
if ((sce=sc->data[SC_KAUPE]) && rnd()%100 < sce->val2) {
//Kaupe blocks damage (skill or otherwise) from players, mobs, homuns, mercenaries.
clif->specialeffect(bl, 462, AREA);
//Shouldn't end until Breaker's non-weapon part connects.
if (skill_id != ASC_BREAKER || !(flag&BF_WEAPON))
if (--(sce->val3) <= 0) //We make it work like Safety Wall, even though it only blocks 1 time.
status_change_end(bl, SC_KAUPE, INVALID_TIMER);
return 0;
}
if (flag&BF_MAGIC && (sce=sc->data[SC_PRESTIGE]) != NULL && rnd()%100 < sce->val2) {
clif->specialeffect(bl, 462, AREA); // Still need confirm it.
return 0;
}
if (((sce=sc->data[SC_NJ_UTSUSEMI]) || sc->data[SC_NJ_BUNSINJYUTSU])
&& flag&BF_WEAPON && !(skill->get_nk(skill_id)&NK_NO_CARDFIX_ATK)) {
skill->additional_effect (src, bl, skill_id, skill_lv, flag, ATK_BLOCK, timer->gettick() );
if( !status->isdead(src) )
skill->counter_additional_effect( src, bl, skill_id, skill_lv, flag, timer->gettick() );
if (sce) {
clif->specialeffect(bl, 462, AREA);
skill->blown(src,bl,sce->val3,-1,0);
}
//Both need to be consumed if they are active.
if (sce && --(sce->val2) <= 0)
status_change_end(bl, SC_NJ_UTSUSEMI, INVALID_TIMER);
if ((sce=sc->data[SC_NJ_BUNSINJYUTSU]) && --(sce->val2) <= 0)
status_change_end(bl, SC_NJ_BUNSINJYUTSU, INVALID_TIMER);
return 0;
}
//Now damage increasing effects
if( sc->data[SC_LEXAETERNA] && skill_id != PF_SOULBURN)
{
if( src->type != BL_MER || skill_id == 0 )
damage <<= 1; // Lex Aeterna only doubles damage of regular attacks from mercenaries
if( skill_id != ASC_BREAKER || !(flag&BF_WEAPON) )
status_change_end(bl, SC_LEXAETERNA, INVALID_TIMER); //Shouldn't end until Breaker's non-weapon part connects.
}
if( damage ) {
if( sc->data[SC_DEEP_SLEEP] ) {
damage += damage / 2; // 1.5 times more damage while in Deep Sleep.
status_change_end(bl,SC_DEEP_SLEEP,INVALID_TIMER);
}
if( s_sd && t_sd && sc->data[SC_COLD] && flag&BF_WEAPON ){
switch(s_sd->status.weapon){
case W_MACE:
case W_2HMACE:
case W_1HAXE:
case W_2HAXE:
damage = damage * 150/100;
break;
case W_MUSICAL:
case W_WHIP:
if(!t_sd->state.arrow_atk)
break;
case W_BOW:
case W_REVOLVER:
case W_RIFLE:
case W_GATLING:
case W_SHOTGUN:
case W_GRENADE:
case W_DAGGER:
case W_1HSWORD:
case W_2HSWORD:
damage = damage * 50/100;
break;
}
}
if( sc->data[SC_SIREN] )
status_change_end(bl,SC_SIREN,INVALID_TIMER);
}
//Finally damage reductions....
// Assumptio doubles the def & mdef on RE mode, otherwise gives a reduction on the final damage. [Igniz]
if( sc->data[SC_ASSUMPTIO] ) {
if( map_flag_vs(bl->m) )
damage = damage*2/3; //Receive 66% damage
else
damage >>= 1; //Receive 50% damage
}
if(sc->data[SC_DEFENDER] &&
(flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) // In pre-re Defender doesn't reduce damage from Acid Demonstration
damage = damage * ( 100 - sc->data[SC_DEFENDER]->val2 ) / 100;
if(sc->data[SC_GS_ADJUSTMENT] &&
(flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON))
damage -= damage * 20 / 100;
if(sc->data[SC_FOGWALL]) {
if(flag&BF_SKILL) { //25% reduction
if ( !(skill->get_inf(skill_id)&INF_GROUND_SKILL) && !(skill->get_nk(skill_id)&NK_SPLASH) )
damage -= 25*damage/100;
} else if ((flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON)) {
damage >>= 2; //75% reduction
}
}
if ( sc->data[SC_WATER_BARRIER] )
damage = damage * ( 100 - 20 ) / 100;
if( sc->data[SC_FIRE_EXPANSION_SMOKE_POWDER] ) {
if( (flag&(BF_SHORT|BF_WEAPON)) == (BF_SHORT|BF_WEAPON) )
damage -= 15 * damage / 100;//15% reduction to physical melee attacks
else if( (flag&(BF_LONG|BF_WEAPON)) == (BF_LONG|BF_WEAPON) )
damage -= 50 * damage / 100;//50% reduction to physical ranged attacks
}
// Compressed code, fixed by map.h [Epoque]
if (src->type == BL_MOB) {
const struct mob_data *md = BL_UCCAST(BL_MOB, src);
int i;
if (sc->data[SC_MANU_DEF] != NULL) {
for (i = 0; i < ARRAYLENGTH(mob->manuk); i++) {
if (mob->manuk[i] == md->class_) {
damage -= damage * sc->data[SC_MANU_DEF]->val1 / 100;
break;
}
}
}
if (sc->data[SC_SPL_DEF] != NULL) {
for (i = 0; i < ARRAYLENGTH(mob->splendide); i++) {
if (mob->splendide[i] == md->class_) {
damage -= damage * sc->data[SC_SPL_DEF]->val1 / 100;
break;
}
}
}
if (sc->data[SC_MORA_BUFF] != NULL) {
for (i = 0; i < ARRAYLENGTH(mob->mora); i++) {
if (mob->mora[i] == md->class_) {
damage -= damage * sc->data[SC_MORA_BUFF]->val1 / 100;
break;
}
}
}
}
if((sce=sc->data[SC_ARMOR]) && //NPC_DEFENDER
sce->val3&flag && sce->val4&flag)
damage -= damage * sc->data[SC_ARMOR]->val2 / 100;
if( sc->data[SC_ENERGYCOAT] && (skill_id == GN_HELLS_PLANT_ATK ||
(flag&BF_WEAPON && skill_id != WS_CARTTERMINATION)) )
{
struct status_data *sstatus = status->get_status_data(bl);
int per = 100*sstatus->sp / sstatus->max_sp -1; //100% should be counted as the 80~99% interval
per /=20; //Uses 20% SP intervals.
//SP Cost: 1% + 0.5% per every 20% SP
if (!status->charge(bl, 0, (10+5*per)*sstatus->max_sp/1000))
status_change_end(bl, SC_ENERGYCOAT, INVALID_TIMER);
//Reduction: 6% + 6% every 20%
damage -= damage * (6 * (1+per)) / 100;
}
if(sc->data[SC_GRANITIC_ARMOR]){
damage -= damage * sc->data[SC_GRANITIC_ARMOR]->val2 / 100;
}
if(sc->data[SC_PAIN_KILLER]){
damage -= damage * sc->data[SC_PAIN_KILLER]->val3 / 100;
}
if((sce=sc->data[SC_MAGMA_FLOW]) && (rnd()%100 <= sce->val2) ){
skill->castend_damage_id(bl,src,MH_MAGMA_FLOW,sce->val1,timer->gettick(),0);
}
if( sc->data[SC_DARKCROW] && (flag&(BF_SHORT|BF_MAGIC)) == BF_SHORT )
damage += damage * sc->data[SC_DARKCROW]->val2 / 100;
if( (sce = sc->data[SC_STONEHARDSKIN]) && flag&(BF_SHORT|BF_WEAPON) && damage > 0 ) {
sce->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX);
if( src->type == BL_PC ) {
if (s_sd && s_sd->status.weapon != W_BOW)
skill->break_equip(src, EQP_WEAPON, 3000, BCT_SELF);
} else
skill->break_equip(src, EQP_WEAPON, 3000, BCT_SELF);
// 30% chance to reduce monster's ATK by 25% for 10 seconds.
if( src->type == BL_MOB )
sc_start(bl,src, SC_NOEQUIPWEAPON, 30, 0, skill->get_time2(RK_STONEHARDSKIN, sce->val1));
if( sce->val2 <= 0 )
status_change_end(bl, SC_STONEHARDSKIN, INVALID_TIMER);
}
//Finally added to remove the status of immobile when aimedbolt is used. [Jobbie]
if( skill_id == RA_AIMEDBOLT && (sc->data[SC_WUGBITE] || sc->data[SC_ANKLESNARE] || sc->data[SC_ELECTRICSHOCKER]) )
{
status_change_end(bl, SC_WUGBITE, INVALID_TIMER);
status_change_end(bl, SC_ANKLESNARE, INVALID_TIMER);
status_change_end(bl, SC_ELECTRICSHOCKER, INVALID_TIMER);
}
//Finally Kyrie because it may, or not, reduce damage to 0.
if((sce = sc->data[SC_KYRIE]) && damage > 0){
sce->val2 -= (int)cap_value(damage,INT_MIN,INT_MAX);
if(flag&BF_WEAPON || skill_id == TF_THROWSTONE){
if(sce->val2>=0)
damage=0;
else
damage=-sce->val2;
}
if((--sce->val3)<=0 || (sce->val2<=0) || skill_id == AL_HOLYLIGHT)
status_change_end(bl, SC_KYRIE, INVALID_TIMER);
}
if( sc->data[SC_MEIKYOUSISUI] && rnd()%100 < 40 ) // custom value
damage = 0;
if (!damage) return 0;
if( (sce = sc->data[SC_LIGHTNINGWALK]) && flag&BF_LONG && rnd()%100 < sce->val1 ) {
int dx[8]={0,-1,-1,-1,0,1,1,1};
int dy[8]={1,1,0,-1,-1,-1,0,1};
uint8 dir = map->calc_dir(bl, src->x, src->y);
if( unit->movepos(bl, src->x-dx[dir], src->y-dy[dir], 1, 1) ) {
clif->slide(bl,src->x-dx[dir],src->y-dy[dir]);
unit->setdir(bl, dir);
}
d->dmg_lv = ATK_DEF;
status_change_end(bl, SC_LIGHTNINGWALK, INVALID_TIMER);
return 0;
}
//Probably not the most correct place, but it'll do here
//(since battle_drain is strictly for players currently)
if ((sce=sc->data[SC_HAMI_BLOODLUST]) && flag&BF_WEAPON && damage > 0 &&
rnd()%100 < sce->val3)
status->heal(src, damage*sce->val4/100, 0, 3);
if( (sce = sc->data[SC_FORCEOFVANGUARD]) && flag&BF_WEAPON
&& rnd()%100 < sce->val2 && sc->fv_counter <= sce->val3 )
clif->millenniumshield(bl, sc->fv_counter++);
if (sc->data[SC_STYLE_CHANGE] && rnd()%2) {
struct homun_data *hd = BL_CAST(BL_HOM,bl);
if (hd) homun->addspiritball(hd, 10); //add a sphere
}
if( sc->data[SC__DEADLYINFECT] && flag&BF_SHORT && damage > 0 && rnd()%100 < 30 + 10 * sc->data[SC__DEADLYINFECT]->val1 && !is_boss(src) )
status->change_spread(bl, src); // Deadly infect attacked side
if (t_sd && damage > 0 && (sce = sc->data[SC_GENTLETOUCH_ENERGYGAIN]) != NULL) {
if ( rnd() % 100 < sce->val2 )
pc->addspiritball(t_sd, skill->get_time(MO_CALLSPIRITS, 1), pc->getmaxspiritball(t_sd, 0));
}
}
//SC effects from caster side.
if (s_sc && s_sc->count) {
if( s_sc->data[SC_INVINCIBLE] && !s_sc->data[SC_INVINCIBLEOFF] )
damage += damage * 75 / 100;
// [Epoque]
if (bl->type == BL_MOB) {
const struct mob_data *md = BL_UCCAST(BL_MOB, bl);
int i;
if (((sce=s_sc->data[SC_MANU_ATK]) != NULL && (flag&BF_WEAPON))
|| ((sce=s_sc->data[SC_MANU_MATK]) != NULL && (flag&BF_MAGIC))) {
for (i = 0; i < ARRAYLENGTH(mob->manuk); i++)
if (md->class_ == mob->manuk[i]) {
damage += damage * sce->val1 / 100;
break;
}
}
if (((sce=s_sc->data[SC_SPL_ATK]) != NULL && (flag&BF_WEAPON))
|| ((sce=s_sc->data[SC_SPL_MATK]) != NULL && (flag&BF_MAGIC))) {
for (i = 0; i < ARRAYLENGTH(mob->splendide); i++)
if (md->class_ == mob->splendide[i]) {
damage += damage * sce->val1 / 100;
break;
}
}
}
if( s_sc->data[SC_POISONINGWEAPON] ) {
struct status_data *tstatus = status->get_status_data(bl);
if ( !(flag&BF_SKILL) && (flag&BF_WEAPON) && damage > 0 && rnd()%100 < s_sc->data[SC_POISONINGWEAPON]->val3 ) {
short rate = 100;
if ( s_sc->data[SC_POISONINGWEAPON]->val1 == 9 ) // Oblivion Curse gives a 2nd success chance after the 1st one passes which is reducible. [Rytech]
rate = 100 - tstatus->int_ * 4 / 5;
sc_start(src,bl,s_sc->data[SC_POISONINGWEAPON]->val2,rate,s_sc->data[SC_POISONINGWEAPON]->val1,skill->get_time2(GC_POISONINGWEAPON,1) - (tstatus->vit + tstatus->luk) / 2 * 1000);
}
}
if( s_sc->data[SC__DEADLYINFECT] && flag&BF_SHORT && damage > 0 && rnd()%100 < 30 + 10 * s_sc->data[SC__DEADLYINFECT]->val1 && !is_boss(src) )
status->change_spread(src, bl);
if (s_sc->data[SC_SHIELDSPELL_REF] && s_sc->data[SC_SHIELDSPELL_REF]->val1 == 1 && damage > 0)
skill->break_equip(bl,EQP_ARMOR,10000,BCT_ENEMY );
if (s_sc->data[SC_STYLE_CHANGE] && rnd()%2) {
struct homun_data *hd = BL_CAST(BL_HOM,bl);
if (hd) homun->addspiritball(hd, 10);
}
if (src->type == BL_PC && damage > 0 && (sce = s_sc->data[SC_GENTLETOUCH_ENERGYGAIN]) != NULL) {
if (s_sd != NULL && rnd() % 100 < sce->val2)
pc->addspiritball(s_sd, skill->get_time(MO_CALLSPIRITS, 1), pc->getmaxspiritball(s_sd, 0));
}
}
/* no data claims these settings affect anything other than players */
if( damage && t_sd && bl->type == BL_PC ) {
switch( skill_id ) {
//case PA_PRESSURE: /* pressure also belongs to this list but it doesn't reach this area -- so don't worry about it */
case HW_GRAVITATION:
case NJ_ZENYNAGE:
case KO_MUCHANAGE:
break;
default:
if (flag & BF_SKILL) { //Skills get a different reduction than non-skills. [Skotlex]
if (flag&BF_WEAPON)
damage = damage * map->list[bl->m].weapon_damage_rate / 100;
if (flag&BF_MAGIC)
damage = damage * map->list[bl->m].magic_damage_rate / 100;
if (flag&BF_MISC)
damage = damage * map->list[bl->m].misc_damage_rate / 100;
} else { //Normal attacks get reductions based on range.
if (flag & BF_SHORT)
damage = damage * map->list[bl->m].short_damage_rate / 100;
if (flag & BF_LONG)
damage = damage * map->list[bl->m].long_damage_rate / 100;
}
if(!damage) damage = 1;
break;
}
}
if(battle_config.skill_min_damage && damage > 0 && damage < div_)
{
if ((flag&BF_WEAPON && battle_config.skill_min_damage&1)
|| (flag&BF_MAGIC && battle_config.skill_min_damage&2)
|| (flag&BF_MISC && battle_config.skill_min_damage&4)
)
damage = div_;
}
if( bl->type == BL_MOB && !status->isdead(bl) && src != bl) {
struct mob_data *md = BL_UCAST(BL_MOB, bl);
if (damage > 0)
mob->skill_event(md, src, timer->gettick(), flag);
if (skill_id)
mob->skill_event(md, src, timer->gettick(), MSC_SKILLUSED|(skill_id<<16));
}
if (t_sd && rnd()%100 < 50) {
int element = -1;
if (!skill_id || (element = skill->get_ele(skill_id, skill_lv)) == -1) {
// Take weapon's element
struct status_data *sstatus = NULL;
if (s_sd != NULL && s_sd->bonus.arrow_ele != 0) {
element = s_sd->bonus.arrow_ele;
} else if ((sstatus = status->get_status_data(src)) != NULL) {
element = sstatus->rhw.ele;
}
} else if (element == -2) {
// Use enchantment's element
element = status_get_attack_sc_element(src,status->get_sc(src));
} else if (element == -3) {
// Use random element
element = rnd()%ELE_MAX;
}
if (element == ELE_FIRE)
pc->overheat(t_sd, 1);
else if (element == ELE_WATER)
pc->overheat(t_sd, -1);
}
return damage;
}
/*==========================================
* Calculates BG related damage adjustments.
*------------------------------------------*/
// FIXME: flag is undocumented
int64 battle_calc_bg_damage(struct block_list *src, struct block_list *bl, int64 damage, int div_, uint16 skill_id, uint16 skill_lv, int flag) {
if (!damage)
return 0;
nullpo_retr(damage, bl);
if (bl->type == BL_MOB) {
struct mob_data* md = BL_CAST(BL_MOB, bl);
if (flag&BF_SKILL && (md->class_ == MOBID_OBJ_A2 || md->class_ == MOBID_OBJ_B2))
return 0; // Crystal cannot receive skill damage on battlegrounds
}
return damage;
}
/*==========================================
* Calculates GVG related damage adjustments.
*------------------------------------------*/
// FIXME: flag is undocumented
int64 battle_calc_gvg_damage(struct block_list *src,struct block_list *bl,int64 damage,int div_,uint16 skill_id,uint16 skill_lv,int flag) {
struct mob_data* md = BL_CAST(BL_MOB, bl);
int class_ = status->get_class(bl);
if (!damage) //No reductions to make.
return 0;
nullpo_retr(damage, src);
nullpo_retr(damage, bl);
if(md && md->guardian_data) {
if (class_ == MOBID_EMPELIUM && flag&BF_SKILL) {
//Skill immunity.
switch (skill_id) {
case MO_TRIPLEATTACK:
case HW_GRAVITATION:
case TF_DOUBLE:
break;
default:
return 0;
}
}
if(src->type != BL_MOB) {
struct guild *g = NULL;
if (src->type == BL_PC) {
struct map_session_data *sd = BL_UCAST(BL_PC, src);
g = sd->guild;
} else {
g = guild->search(status->get_guild_id(src));
}
if (class_ == MOBID_EMPELIUM && (!g || guild->checkskill(g,GD_APPROVAL) <= 0))
return 0;
if (g && battle_config.guild_max_castles && guild->checkcastles(g)>=battle_config.guild_max_castles)
return 0; // [MouseJstr]
}
}
switch (skill_id) {
case PA_PRESSURE:
case HW_GRAVITATION:
case NJ_ZENYNAGE:
case KO_MUCHANAGE:
case NC_SELFDESTRUCTION:
break;
default:
/* Uncomment if you want god-mode Emperiums at 100 defense. [Kisuka]
if (md && md->guardian_data) {
damage -= damage * (md->guardian_data->castle->defense/100) * battle_config.castle_defense_rate/100;
}
*/
break;
}
return damage;
}
/*==========================================
* HP/SP drain calculation
*------------------------------------------*/
int battle_calc_drain(int64 damage, int rate, int per) {
int64 diff = 0;
if (per && rnd()%1000 < rate) {
diff = (damage * per) / 100;
if (diff == 0) {
if (per > 0)
diff = 1;
else
diff = -1;
}
}
return (int)cap_value(diff,INT_MIN,INT_MAX);
}
/*==========================================
* Consumes ammo for the given skill.
*------------------------------------------*/
void battle_consume_ammo(struct map_session_data *sd, int skill_id, int lv)
{
int qty=1;
nullpo_retv(sd);
if (!battle_config.arrow_decrement)
return;
if (skill_id && lv) {
qty = skill->get_ammo_qty(skill_id, lv);
if (!qty) qty = 1;
}
if(sd->equip_index[EQI_AMMO]>=0) //Qty check should have been done in skill_check_condition
pc->delitem(sd, sd->equip_index[EQI_AMMO], qty, 0, DELITEM_SKILLUSE, LOG_TYPE_CONSUME);
sd->state.arrow_atk = 0;
}
//Skill Range Criteria
int battle_range_type(struct block_list *src, struct block_list *target, uint16 skill_id, uint16 skill_lv) {
nullpo_retr(BF_SHORT, src);
nullpo_retr(BF_SHORT, target);
if (battle_config.skillrange_by_distance &&
(src->type&battle_config.skillrange_by_distance)
) { //based on distance between src/target [Skotlex]
if (check_distance_bl(src, target, 5))
return BF_SHORT;
return BF_LONG;
}
if (skill_id == SR_GATEOFHELL) {
if (skill_lv < 5)
return BF_SHORT;
else
return BF_LONG;
}
//based on used skill's range
if (skill->get_range2(src, skill_id, skill_lv) < 5)
return BF_SHORT;
return BF_LONG;
}
int battle_adjust_skill_damage(int m, unsigned short skill_id) {
if( map->list[m].skill_count ) {
int i;
ARR_FIND(0, map->list[m].skill_count, i, map->list[m].skills[i]->skill_id == skill_id );
if( i < map->list[m].skill_count ) {
return map->list[m].skills[i]->modifier;
}
}
return 0;
}
int battle_blewcount_bonus(struct map_session_data *sd, uint16 skill_id) {
int i;
nullpo_ret(sd);
if (!sd->skillblown[0].id)
return 0;
//Apply the bonus blow count. [Skotlex]
for (i = 0; i < ARRAYLENGTH(sd->skillblown) && sd->skillblown[i].id; i++) {
if (sd->skillblown[i].id == skill_id)
return sd->skillblown[i].val;
}
return 0;
}
//For quick div adjustment.
#define damage_div_fix(dmg, div) do { if ((div) > 1) (dmg)*=(div); else if ((div) < 0) (div)*=-1; } while(0)
/*==========================================
* battle_calc_magic_attack [DracoRPG]
*------------------------------------------*/
// FIXME: mflag is undocumented
struct Damage battle_calc_magic_attack(struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv,int mflag) {
int nk;
short s_ele = 0;
struct map_session_data *sd = NULL;
struct status_change *sc;
struct Damage ad;
struct status_data *sstatus = status->get_status_data(src);
struct status_data *tstatus = status->get_status_data(target);
struct {
unsigned imdef : 2;
unsigned infdef : 1;
} flag;
memset(&ad,0,sizeof(ad));
memset(&flag,0,sizeof(flag));
nullpo_retr(ad, src);
nullpo_retr(ad, target);
//Initial Values
ad.damage = 1;
ad.div_=skill->get_num(skill_id,skill_lv);
ad.amotion = (skill->get_inf(skill_id)&INF_GROUND_SKILL) ? 0 : sstatus->amotion; //Amotion should be 0 for ground skills.
ad.dmotion=tstatus->dmotion;
ad.blewcount = skill->get_blewcount(skill_id,skill_lv);
ad.flag=BF_MAGIC|BF_SKILL;
ad.dmg_lv=ATK_DEF;
nk = skill->get_nk(skill_id);
flag.imdef = (nk&NK_IGNORE_DEF)? 1 : 0;
sd = BL_CAST(BL_PC, src);
sc = status->get_sc(src);
//Initialize variables that will be used afterwards
s_ele = skill->get_ele(skill_id, skill_lv);
if (s_ele == -1){ // pl=-1 : the skill takes the weapon's element
s_ele = sstatus->rhw.ele;
if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count >= MAX_SPIRITCHARM) {
//Summoning 10 spiritcharm will endow your weapon
s_ele = sd->charm_type;
}
}else if (s_ele == -2) //Use status element
s_ele = status_get_attack_sc_element(src,status->get_sc(src));
else if( s_ele == -3 ) //Use random element
s_ele = rnd()%ELE_MAX;
if( skill_id == SO_PSYCHIC_WAVE ) {
if( sc && sc->count ) {
if( sc->data[SC_HEATER_OPTION] ) s_ele = sc->data[SC_HEATER_OPTION]->val4;
else if( sc->data[SC_COOLER_OPTION] ) s_ele = sc->data[SC_COOLER_OPTION]->val4;
else if( sc->data[SC_BLAST_OPTION] ) s_ele = sc->data[SC_BLAST_OPTION]->val3;
else if( sc->data[SC_CURSED_SOIL_OPTION] ) s_ele = sc->data[SC_CURSED_SOIL_OPTION]->val4;
}
}
//Set miscellaneous data that needs be filled
if(sd) {
sd->state.arrow_atk = 0;
ad.blewcount += battle->blewcount_bonus(sd, skill_id);
}
//Skill Range Criteria
ad.flag |= battle->range_type(src, target, skill_id, skill_lv);
flag.infdef = (tstatus->mode&MD_PLANT) ? 1 : 0;
if (!flag.infdef && target->type == BL_SKILL) {
const struct skill_unit *su = BL_UCCAST(BL_SKILL, target);
if (su->group->unit_id == UNT_REVERBERATION)
flag.infdef = 1; // Reverberation takes 1 damage
}
switch(skill_id) {
case MG_FIREWALL:
if ( tstatus->def_ele == ELE_FIRE || battle->check_undead(tstatus->race, tstatus->def_ele) )
ad.blewcount = 0; //No knockback
break;
case NJ_KAENSIN:
case PR_SANCTUARY:
ad.dmotion = 0; //No flinch animation.
break;
case WL_HELLINFERNO:
if( mflag&ELE_DARK )
s_ele = ELE_DARK;
break;
case KO_KAIHOU:
if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count > 0) {
s_ele = sd->charm_type;
}
break;
}
if (!flag.infdef) //No need to do the math for plants
{
int i;
//MATK_RATE scales the damage. 100 = no change. 50 is halved, 200 is doubled, etc
#define MATK_RATE( a ) ( ad.damage= ad.damage*(a)/100 )
//Adds dmg%. 100 = +100% (double) damage. 10 = +10% damage
#define MATK_ADDRATE( a ) ( ad.damage+= ad.damage*(a)/100 )
//Adds an absolute value to damage. 100 = +100 damage
#define MATK_ADD( a ) ( ad.damage+= (a) )
switch (skill_id) {
//Calc base damage according to skill
case AL_HEAL:
case PR_BENEDICTIO:
case PR_SANCTUARY:
ad.damage = skill->calc_heal(src, target, skill_id, skill_lv, false);
break;
/**
* Arch Bishop
**/
case AB_HIGHNESSHEAL:
ad.damage = skill->calc_heal(src, target, AL_HEAL, 10, false) * ( 17 + 3 * skill_lv ) / 10;
break;
case PR_ASPERSIO:
ad.damage = 40;
break;
case ALL_RESURRECTION:
case PR_TURNUNDEAD:
//Undead check is on skill_castend_damageid code.
i = 20*skill_lv + sstatus->luk + sstatus->int_ + status->get_lv(src)
+ 200 - 200*tstatus->hp/tstatus->max_hp;
if(i > 700) i = 700;
if(rnd()%1000 < i && !(tstatus->mode&MD_BOSS))
ad.damage = tstatus->hp;
else {
ad.damage = status->get_lv(src) + sstatus->int_ + skill_lv * 10;
}
break;
case PF_SOULBURN:
ad.damage = tstatus->sp * 2;
break;
/**
* Arch Bishop
**/
case AB_RENOVATIO:
//Damage calculation from iRO wiki. [Jobbie]
ad.damage = status->get_lv(src) * 10 + sstatus->int_;
break;
default: {
unsigned int skillratio = 100; //Skill dmg modifiers.
MATK_ADD( status->get_matk(src, 2) );
if (nk&NK_SPLASHSPLIT) { // Divide MATK in case of multiple targets skill
if(mflag>0)
ad.damage/= mflag;
else
ShowError("0 enemies targeted by %d:%s, divide per 0 avoided!\n", skill_id, skill->get_name(skill_id));
}
if (sc){
if( sc->data[SC_TELEKINESIS_INTENSE] && s_ele == ELE_GHOST )
ad.damage += sc->data[SC_TELEKINESIS_INTENSE]->val3;
}
switch(skill_id){
case MG_FIREBOLT:
case MG_COLDBOLT:
case MG_LIGHTNINGBOLT:
if ( sc && sc->data[SC_SPELLFIST] && mflag&BF_SHORT ) {
skillratio = sc->data[SC_SPELLFIST]->val2 * 50 + sc->data[SC_SPELLFIST]->val4 * 100;// val4 = used bolt level, val2 = used spellfist level. [Rytech]
ad.div_ = 1;// ad mods, to make it work similar to regular hits [Xazax]
ad.flag = BF_WEAPON|BF_SHORT;
ad.type = BDT_NORMAL;
}
/* Fall through */
default:
MATK_RATE(battle->calc_skillratio(BF_MAGIC, src, target, skill_id, skill_lv, skillratio, mflag));
}
//Constant/misc additions from skills
if (skill_id == WZ_FIREPILLAR)
MATK_ADD(100+50*skill_lv);
if( sd && ( sd->status.class_ == JOB_ARCH_BISHOP_T || sd->status.class_ == JOB_ARCH_BISHOP ) &&
(i=pc->checkskill(sd,AB_EUCHARISTICA)) > 0 &&
(tstatus->race == RC_DEMON || tstatus->def_ele == ELE_DARK) )
MATK_ADDRATE(i);
}
}
#ifndef HMAP_ZONE_DAMAGE_CAP_TYPE
if (skill_id) {
for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) {
if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) {
if (target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE) {
const struct mob_data *md = BL_UCCAST(BL_MOB, target);
if ((md->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS))
continue;
if (md->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE))
continue;
}
if( ad.damage > map->list[target->m].zone->capped_skills[i]->cap )
ad.damage = map->list[target->m].zone->capped_skills[i]->cap;
if( ad.damage2 > map->list[target->m].zone->capped_skills[i]->cap )
ad.damage2 = map->list[target->m].zone->capped_skills[i]->cap;
break;
}
}
}
#endif
if(sd) {
uint16 rskill;/* redirect skill */
//Damage bonuses
if ((i = pc->skillatk_bonus(sd, skill_id)))
ad.damage += ad.damage*i/100;
switch(skill_id){
case WL_CHAINLIGHTNING_ATK:
rskill = WL_CHAINLIGHTNING;
break;
case AB_DUPLELIGHT_MAGIC:
rskill = AB_DUPLELIGHT;
break;
case WL_TETRAVORTEX_FIRE:
case WL_TETRAVORTEX_WATER:
case WL_TETRAVORTEX_WIND:
case WL_TETRAVORTEX_GROUND:
rskill = WL_TETRAVORTEX;
break;
case WL_SUMMON_ATK_FIRE:
case WL_SUMMON_ATK_WIND:
case WL_SUMMON_ATK_WATER:
case WL_SUMMON_ATK_GROUND:
rskill = WL_RELEASE;
break;
case WM_REVERBERATION_MAGIC:
rskill = WM_REVERBERATION;
break;
default:
rskill = skill_id;
}
if( (i = battle->adjust_skill_damage(src->m,rskill)) )
MATK_RATE(i);
//Ignore Defense?
if (!flag.imdef && (
sd->bonus.ignore_mdef_ele & ( 1 << tstatus->def_ele ) ||
sd->bonus.ignore_mdef_race & map->race_id2mask(tstatus->race) ||
sd->bonus.ignore_mdef_race & map->race_id2mask(is_boss(target) ? RC_BOSS : RC_NONBOSS)
))
flag.imdef = 1;
}
ad.damage = battle->calc_defense(BF_MAGIC, src, target, skill_id, skill_lv, ad.damage, flag.imdef, 0);
if(ad.damage<1)
ad.damage=1;
else if(sc){//only applies when hit
// TODO: there is another factor that contribute with the damage and need to be formulated. [malufett]
switch(skill_id){
case MG_LIGHTNINGBOLT:
case MG_THUNDERSTORM:
case MG_FIREBOLT:
case MG_FIREWALL:
case MG_COLDBOLT:
case MG_FROSTDIVER:
case WZ_EARTHSPIKE:
case WZ_HEAVENDRIVE:
if(sc->data[SC_GUST_OPTION] || sc->data[SC_PETROLOGY_OPTION]
|| sc->data[SC_PYROTECHNIC_OPTION] || sc->data[SC_AQUAPLAY_OPTION])
ad.damage += (6 + sstatus->int_/4) + max(sstatus->dex-10,0)/30;
break;
}
}
if (!(nk&NK_NO_ELEFIX))
ad.damage=battle->attr_fix(src, target, ad.damage, s_ele, tstatus->def_ele, tstatus->ele_lv);
if( skill_id == CR_GRANDCROSS || skill_id == NPC_GRANDDARKNESS )
{ //Apply the physical part of the skill's damage. [Skotlex]
struct Damage wd = battle->calc_weapon_attack(src,target,skill_id,skill_lv,mflag);
ad.damage = battle->attr_fix(src, target, wd.damage + ad.damage, s_ele, tstatus->def_ele, tstatus->ele_lv) * (100 + 40*skill_lv)/100;
if( src == target )
{
if( src->type == BL_PC )
ad.damage = ad.damage/2;
else
ad.damage = 0;
}
}
ad.damage = battle->calc_cardfix(BF_MAGIC, src, target, nk, s_ele, 0, ad.damage, 0, ad.flag);
}
damage_div_fix(ad.damage, ad.div_);
if (flag.infdef && ad.damage)
ad.damage = ad.damage>0?1:-1;
if (skill_id != ASC_BREAKER)
ad.damage = battle->calc_damage(src, target, &ad, ad.damage, skill_id, skill_lv);
if( map_flag_gvg2(target->m) )
ad.damage=battle->calc_gvg_damage(src,target,ad.damage,ad.div_,skill_id,skill_lv,ad.flag);
else if( map->list[target->m].flag.battleground )
ad.damage=battle->calc_bg_damage(src,target,ad.damage,ad.div_,skill_id,skill_lv,ad.flag);
switch( skill_id ) { /* post-calc modifiers */
case SO_VARETYR_SPEAR: { // Physical damage.
struct Damage wd = battle->calc_weapon_attack(src,target,skill_id,skill_lv,mflag);
if(!flag.infdef && ad.damage > 1)
ad.damage += wd.damage;
break;
}
//case HM_ERASER_CUTTER:
}
return ad;
#undef MATK_RATE
#undef MATK_ADDRATE
#undef MATK_ADD
}
/*==========================================
* Calculate Misc damage for skill_id
*------------------------------------------*/
// FIXME: mflag is undocumented
struct Damage battle_calc_misc_attack(struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv,int mflag) {
int temp;
short i, nk;
short s_ele;
struct map_session_data *sd, *tsd;
struct Damage md; //DO NOT CONFUSE with md of mob_data!
struct status_data *sstatus = status->get_status_data(src);
struct status_data *tstatus = status->get_status_data(target);
struct status_change *tsc = status->get_sc(target);
memset(&md,0,sizeof(md));
nullpo_retr(md, src);
nullpo_retr(md, target);
//Some initial values
md.amotion = (skill->get_inf(skill_id)&INF_GROUND_SKILL) ? 0 : sstatus->amotion;
md.dmotion=tstatus->dmotion;
md.div_=skill->get_num( skill_id,skill_lv );
md.blewcount=skill->get_blewcount(skill_id,skill_lv);
md.dmg_lv=ATK_DEF;
md.flag=BF_MISC|BF_SKILL;
nk = skill->get_nk(skill_id);
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
if(sd) {
sd->state.arrow_atk = 0;
md.blewcount += battle->blewcount_bonus(sd, skill_id);
}
s_ele = skill->get_ele(skill_id, skill_lv);
if (s_ele < 0 && s_ele != -3) //Attack that takes weapon's element for misc attacks? Make it neutral [Skotlex]
s_ele = ELE_NEUTRAL;
else if (s_ele == -3) //Use random element
s_ele = rnd()%ELE_MAX;
//Skill Range Criteria
md.flag |= battle->range_type(src, target, skill_id, skill_lv);
switch( skill_id )
{
case HT_LANDMINE:
case MA_LANDMINE:
md.damage=skill_lv*(sstatus->dex+75)*(100+sstatus->int_)/100;
break;
case HT_BLASTMINE:
md.damage=skill_lv*(sstatus->dex/2+50)*(100+sstatus->int_)/100;
break;
case HT_CLAYMORETRAP:
md.damage=skill_lv*(sstatus->dex/2+75)*(100+sstatus->int_)/100;
break;
case HT_BLITZBEAT:
case SN_FALCONASSAULT:
//Blitz-beat Damage.
if(!sd || (temp = pc->checkskill(sd,HT_STEELCROW)) <= 0)
temp=0;
md.damage=(sstatus->dex/10+sstatus->int_/2+temp*3+40)*2;
if(mflag > 1) //Autocasted Blitz.
nk|=NK_SPLASHSPLIT;
if (skill_id == SN_FALCONASSAULT) {
//Div fix of Blitzbeat
temp = skill->get_num(HT_BLITZBEAT, 5);
damage_div_fix(md.damage, temp);
//Falcon Assault Modifier
md.damage=md.damage*(150+70*skill_lv)/100;
}
break;
case TF_THROWSTONE:
md.damage=50;
break;
case BA_DISSONANCE:
md.damage=30+skill_lv*10;
if (sd)
md.damage+= 3*pc->checkskill(sd,BA_MUSICALLESSON);
break;
case NPC_SELFDESTRUCTION:
md.damage = sstatus->hp;
break;
case NPC_SMOKING:
md.damage=3;
break;
case NPC_DARKBREATH:
md.damage = 500 + (skill_lv-1)*1000 + rnd()%1000;
if(md.damage > 9999) md.damage = 9999;
break;
case PA_PRESSURE:
md.damage=500+300*skill_lv;
break;
case PA_GOSPEL:
md.damage = 1+rnd()%9999;
break;
case CR_ACIDDEMONSTRATION:
// updated the formula based on a Japanese formula found to be exact [Reddozen]
if(tstatus->vit+sstatus->int_) //crash fix
md.damage = (int)(7*tstatus->vit*sstatus->int_*sstatus->int_ / (10*(tstatus->vit+sstatus->int_)));
else
md.damage = 0;
if (tsd) md.damage>>=1;
// Some monsters have totaldef higher than md.damage in some cases, leading to md.damage < 0
if( md.damage < 0 )
md.damage = 0;
if( md.damage > INT_MAX>>1 )
//Overflow prevention, will anyone whine if I cap it to a few billion?
//Not capped to INT_MAX to give some room for further damage increase.
md.damage = INT_MAX>>1;
break;
case KO_MUCHANAGE:
md.damage = skill->get_zeny(skill_id ,skill_lv);
md.damage = md.damage * (50 + rnd()%50) / 100;
if ( is_boss(target) || (sd && !pc->checkskill(sd,NJ_TOBIDOUGU)) )
md.damage >>= 1;
break;
case NJ_ZENYNAGE:
md.damage = skill->get_zeny(skill_id ,skill_lv);
if (!md.damage) md.damage = 2;
md.damage = rnd()%md.damage + md.damage;
if (is_boss(target))
md.damage=md.damage / 3;
else if (tsd)
md.damage=md.damage / 2;
break;
case GS_FLING:
md.damage = sd?sd->status.job_level:status->get_lv(src);
break;
case HVAN_EXPLOSION: //[orn]
md.damage = sstatus->max_hp * (50 + 50 * skill_lv) / 100;
break ;
case ASC_BREAKER:
{
md.damage = 500+rnd()%500 + 5*skill_lv * sstatus->int_;
nk|=NK_IGNORE_FLEE|NK_NO_ELEFIX; //These two are not properties of the weapon based part.
}
break;
case HW_GRAVITATION:
md.damage = 200+200*skill_lv;
md.dmotion = 0; //No flinch animation.
break;
case NPC_EVILLAND:
md.damage = skill->calc_heal(src,target,skill_id,skill_lv,false);
break;
case RK_DRAGONBREATH:
case RK_DRAGONBREATH_WATER:
md.damage = ((status_get_hp(src) / 50) + (status_get_max_sp(src) / 4)) * skill_lv;
if (sd) md.damage = md.damage * (95 + 5 * pc->checkskill(sd,RK_DRAGONTRAINING)) / 100;
md.flag |= BF_LONG|BF_WEAPON;
break;
/**
* Ranger
**/
case RA_CLUSTERBOMB:
case RA_FIRINGTRAP:
case RA_ICEBOUNDTRAP:
md.damage = (int64)skill_lv * sstatus->dex + sstatus->int_ * 5 ;
if(sd)
{
int researchskill_lv = pc->checkskill(sd,RA_RESEARCHTRAP);
if(researchskill_lv)
md.damage = md.damage * 20 * researchskill_lv / (skill_id == RA_CLUSTERBOMB?50:100);
else
md.damage = 0;
}else
md.damage = md.damage * 200 / (skill_id == RA_CLUSTERBOMB?50:100);
break;
case WM_SOUND_OF_DESTRUCTION:
md.damage = 1000 * (int64)skill_lv + sstatus->int_ * (sd ? pc->checkskill(sd,WM_LESSON) : 10);
md.damage += md.damage * 10 * battle->calc_chorusbonus(sd) / 100;
break;
/**
* Mechanic
**/
case NC_SELFDESTRUCTION:
{
short totaldef = tstatus->def2 + (short)status->get_def(target);
md.damage = ( (sd?pc->checkskill(sd,NC_MAINFRAME):10) + 8 ) * ( skill_lv + 1 ) * ( status_get_sp(src) + sstatus->vit );
md.damage += status_get_hp(src) - totaldef;
}
break;
case NC_MAGMA_ERUPTION:
md.damage = 1200 + 400 * skill_lv;
break;
case GN_THORNS_TRAP:
md.damage = 100 + 200 * skill_lv + sstatus->int_;
break;
case GN_HELLS_PLANT_ATK:
md.damage = skill_lv * status->get_lv(target) * 10 + sstatus->int_ * 7 / 2 * (18 + (sd ? sd->status.job_level : 0) / 4) * (5 / (10 - (sd ? pc->checkskill(sd, AM_CANNIBALIZE) : 0)));
md.damage = md.damage*(1000 + tstatus->mdef) / (1000 + tstatus->mdef * 10) - tstatus->mdef2;
break;
case KO_HAPPOKUNAI:
{
struct Damage wd = battle->calc_weapon_attack(src, target, 0, 1, mflag);
short totaldef = tstatus->def2 + (short)status->get_def(target);
if (sd != NULL)
wd.damage += sd->bonus.arrow_atk;
md.damage = (int)(3 * (1 + wd.damage) * (5 + skill_lv) / 5.0f);
md.damage -= totaldef;
}
break;
default:
battle->calc_misc_attack_unknown(src, target, &skill_id, &skill_lv, &mflag, &md);
break;
}
if (nk&NK_SPLASHSPLIT){ // Divide ATK among targets
if(mflag>0)
md.damage/= mflag;
else
ShowError("0 enemies targeted by %d:%s, divide per 0 avoided!\n", skill_id, skill->get_name(skill_id));
}
damage_div_fix(md.damage, md.div_);
if (!(nk&NK_IGNORE_FLEE))
{
i = 0; //Temp for "hit or no hit"
if(tsc && tsc->opt1 && tsc->opt1 != OPT1_STONEWAIT && tsc->opt1 != OPT1_BURNING)
i = 1;
else {
short
flee = tstatus->flee,
hitrate = 80; //Default hitrate
if(battle_config.agi_penalty_type && battle_config.agi_penalty_target&target->type) {
unsigned char attacker_count; //256 max targets should be a sane max
attacker_count = unit->counttargeted(target);
if(attacker_count >= battle_config.agi_penalty_count)
{
if (battle_config.agi_penalty_type == 1)
flee = (flee * (100 - (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num))/100;
else // assume type 2: absolute reduction
flee -= (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num;
if(flee < 1) flee = 1;
}
}
hitrate+= sstatus->hit - flee;
if( skill_id == KO_MUCHANAGE )
hitrate = (int)((10 - ((float)1 / (status_get_dex(src) + status_get_luk(src))) * 500) * ((float)skill_lv / 2 + 5));
hitrate = cap_value(hitrate, battle_config.min_hitrate, battle_config.max_hitrate);
if(rnd()%100 < hitrate)
i = 1;
}
if (!i) {
md.damage = 0;
md.dmg_lv=ATK_FLEE;
}
}
#ifndef HMAP_ZONE_DAMAGE_CAP_TYPE
if (skill_id) {
for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) {
if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) {
if (target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE) {
const struct mob_data *t_md = BL_UCCAST(BL_MOB, target);
if ((t_md->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS))
continue;
if (t_md->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE))
continue;
}
if( md.damage > map->list[target->m].zone->capped_skills[i]->cap )
md.damage = map->list[target->m].zone->capped_skills[i]->cap;
if( md.damage2 > map->list[target->m].zone->capped_skills[i]->cap )
md.damage2 = map->list[target->m].zone->capped_skills[i]->cap;
break;
}
}
}
#endif
md.damage = battle->calc_cardfix(BF_MISC, src, target, nk, s_ele, 0, md.damage, 0, md.flag);
md.damage = battle->calc_cardfix2(src, target, md.damage, s_ele, nk, md.flag);
if(skill_id){
uint16 rskill;/* redirect skill id */
switch(skill_id){
case GN_HELLS_PLANT_ATK:
rskill = GN_HELLS_PLANT;
break;
default:
rskill = skill_id;
}
if (sd && (i = pc->skillatk_bonus(sd, rskill)) != 0)
md.damage += md.damage*i/100;
}
if( (i = battle->adjust_skill_damage(src->m,skill_id)) )
md.damage = md.damage * i / 100;
if(md.damage < 0)
md.damage = 0;
else if(md.damage && tstatus->mode&MD_PLANT){
switch(skill_id){
case HT_LANDMINE:
case MA_LANDMINE:
case HT_BLASTMINE:
case HT_CLAYMORETRAP:
case RA_CLUSTERBOMB:
default:
md.damage = 1;
}
}
if(!(nk&NK_NO_ELEFIX))
md.damage=battle->attr_fix(src, target, md.damage, s_ele, tstatus->def_ele, tstatus->ele_lv);
md.damage=battle->calc_damage(src,target,&md,md.damage,skill_id,skill_lv);
if( map_flag_gvg2(target->m) )
md.damage=battle->calc_gvg_damage(src,target,md.damage,md.div_,skill_id,skill_lv,md.flag);
else if( map->list[target->m].flag.battleground )
md.damage=battle->calc_bg_damage(src,target,md.damage,md.div_,skill_id,skill_lv,md.flag);
switch( skill_id ) {
case RA_FIRINGTRAP:
case RA_ICEBOUNDTRAP:
if( md.damage == 1 ) break;
case RA_CLUSTERBOMB:
{
struct Damage wd;
wd = battle->calc_weapon_attack(src,target,skill_id,skill_lv,mflag);
md.damage += wd.damage;
}
break;
case NJ_ZENYNAGE:
if( sd ) {
if ( md.damage > sd->status.zeny )
md.damage = sd->status.zeny;
pc->payzeny(sd, (int)cap_value(md.damage,INT_MIN,INT_MAX),LOG_TYPE_STEAL,NULL);
}
break;
}
return md;
}
void battle_calc_misc_attack_unknown(struct block_list *src, struct block_list *target, uint16 *skill_id, uint16 *skill_lv, int *mflag, struct Damage *md) {
}
/*==========================================
* battle_calc_weapon_attack (by Skotlex)
*------------------------------------------*/
// FIXME: wflag is undocumented
struct Damage battle_calc_weapon_attack(struct block_list *src,struct block_list *target,uint16 skill_id,uint16 skill_lv,int wflag)
{
short temp=0;
short s_ele, s_ele_;
int i, nk;
bool n_ele = false; // non-elemental
struct map_session_data *sd, *tsd;
struct Damage wd;
struct status_change *sc = status->get_sc(src);
struct status_change *tsc = status->get_sc(target);
struct status_data *sstatus = status->get_status_data(src);
struct status_data *tstatus = status->get_status_data(target);
struct {
unsigned hit : 1; ///< the attack Hit? (not a miss)
unsigned cri : 1; ///< Critical hit
unsigned idef : 1; ///< Ignore defense
unsigned idef2 : 1; ///< Ignore defense (left weapon)
unsigned pdef : 2; ///< Pierces defense (Investigate/Ice Pick)
unsigned pdef2 : 2; ///< 1: Use def+def2/100, 2: Use def+def2/50
unsigned infdef : 1; ///< Infinite defense (plants)
unsigned arrow : 1; ///< Attack is arrow-based
unsigned rh : 1; ///< Attack considers right hand (wd.damage)
unsigned lh : 1; ///< Attack considers left hand (wd.damage2)
unsigned weapon : 1; ///< It's a weapon attack (consider VVS, and all that)
} flag;
memset(&wd,0,sizeof(wd));
memset(&flag,0,sizeof(flag));
nullpo_retr(wd, src);
nullpo_retr(wd, target);
//Initial flag
flag.rh=1;
flag.weapon=1;
flag.infdef = (tstatus->mode&MD_PLANT && skill_id != RA_CLUSTERBOMB?1:0);
if (!flag.infdef && target->type == BL_SKILL) {
const struct skill_unit *su = BL_UCCAST(BL_SKILL, target);
if (su->group->unit_id == UNT_REVERBERATION)
flag.infdef = 1; // Reverberation takes 1 damage
}
//Initial Values
wd.type = BDT_NORMAL;
wd.div_ = skill_id ? skill->get_num(skill_id,skill_lv) : 1;
wd.amotion=(skill_id && skill->get_inf(skill_id)&INF_GROUND_SKILL)?0:sstatus->amotion; //Amotion should be 0 for ground skills.
if(skill_id == KN_AUTOCOUNTER)
wd.amotion >>= 1;
wd.dmotion=tstatus->dmotion;
wd.blewcount = skill_id ? skill->get_blewcount(skill_id,skill_lv) : 0;
wd.flag = BF_WEAPON; //Initial Flag
wd.flag |= (skill_id||wflag)?BF_SKILL:BF_NORMAL; // Baphomet card's splash damage is counted as a skill. [Inkfish]
wd.dmg_lv=ATK_DEF; //This assumption simplifies the assignation later
nk = skill->get_nk(skill_id);
if( !skill_id && wflag ) //If flag, this is splash damage from Baphomet Card and it always hits.
nk |= NK_NO_CARDFIX_ATK|NK_IGNORE_FLEE;
flag.hit = (nk&NK_IGNORE_FLEE) ? 1 : 0;
flag.idef = flag.idef2 = (nk&NK_IGNORE_DEF) ? 1 : 0;
if (sc && !sc->count)
sc = NULL; //Skip checking as there are no status changes active.
if (tsc && !tsc->count)
tsc = NULL; //Skip checking as there are no status changes active.
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
if(sd)
wd.blewcount += battle->blewcount_bonus(sd, skill_id);
//Set miscellaneous data that needs be filled regardless of hit/miss
if(
(sd && sd->state.arrow_atk) ||
(!sd && ((skill_id && skill->get_ammotype(skill_id)) || sstatus->rhw.range>3))
)
flag.arrow = 1;
if(skill_id) {
wd.flag |= battle->range_type(src, target, skill_id, skill_lv);
switch(skill_id) {
case MO_FINGEROFFENSIVE:
if(sd) {
if (battle_config.finger_offensive_type)
wd.div_ = 1;
else
wd.div_ = sd->spiritball_old;
}
break;
case HT_PHANTASMIC:
//Since these do not consume ammo, they need to be explicitly set as arrow attacks.
flag.arrow = 1;
break;
case PA_SHIELDCHAIN:
case CR_SHIELDBOOMERANG:
case LG_SHIELDPRESS:
case LG_EARTHDRIVE:
flag.weapon = 0;
break;
case KN_PIERCE:
case ML_PIERCE:
wd.div_= (wd.div_>0?tstatus->size+1:-(tstatus->size+1));
break;
case TF_DOUBLE: //For NPC used skill.
case GS_CHAINACTION:
wd.type = BDT_MULTIHIT;
break;
case GS_GROUNDDRIFT:
case KN_SPEARSTAB:
case KN_BOWLINGBASH:
case MS_BOWLINGBASH:
case MO_BALKYOUNG:
case TK_TURNKICK:
wd.blewcount=0;
break;
case KN_AUTOCOUNTER:
wd.flag=(wd.flag&~BF_SKILLMASK)|BF_NORMAL;
break;
case NPC_CRITICALSLASH:
case LG_PINPOINTATTACK:
flag.cri = 1; //Always critical skill.
break;
case LK_SPIRALPIERCE:
if (!sd) wd.flag=(wd.flag&~(BF_RANGEMASK|BF_WEAPONMASK))|BF_LONG|BF_MISC;
break;
//When in banding, the number of hits is equal to the number of Royal Guards in banding.
case LG_HESPERUSLIT:
if( sc && sc->data[SC_BANDING] && sc->data[SC_BANDING]->val2 > 3 )
wd.div_ = sc->data[SC_BANDING]->val2;
break;
case MO_INVESTIGATE:
flag.pdef = flag.pdef2 = 2;
break;
case RA_AIMEDBOLT:
if( tsc && (tsc->data[SC_WUGBITE] || tsc->data[SC_ANKLESNARE] || tsc->data[SC_ELECTRICSHOCKER]) )
wd.div_ = tstatus->size + 2 + ( (rnd()%100 < 50-tstatus->size*10) ? 1 : 0 );
break;
case NPC_EARTHQUAKE:
wd.flag = (wd.flag&~(BF_WEAPON)) | BF_MAGIC;
break;
}
} else //Range for normal attacks.
wd.flag |= flag.arrow?BF_LONG:BF_SHORT;
if ((!skill_id || skill_id == PA_SACRIFICE) && tstatus->flee2 && rnd()%1000 < tstatus->flee2) {
//Check for Lucky Dodge
wd.type = BDT_PDODGE;
wd.dmg_lv=ATK_LUCKY;
if (wd.div_ < 0) wd.div_*=-1;
return wd;
}
s_ele = s_ele_ = skill_id ? skill->get_ele(skill_id, skill_lv) : -1;
if (s_ele == -1) {
//Take weapon's element
s_ele = sstatus->rhw.ele;
s_ele_ = sstatus->lhw.ele;
if (sd && sd->charm_type != CHARM_TYPE_NONE && sd->charm_count >= MAX_SPIRITCHARM) {
//Summoning 10 spiritcharm will endow your weapon.
s_ele = s_ele_ = sd->charm_type;
}
if( flag.arrow && sd && sd->bonus.arrow_ele )
s_ele = sd->bonus.arrow_ele;
if( battle_config.attack_attr_none&src->type )
n_ele = true; //Weapon's element is "not elemental"
} else if (s_ele == -2) {
//Use enchantment's element
s_ele = s_ele_ = status_get_attack_sc_element(src,sc);
} else if (s_ele == -3) {
//Use random element
s_ele = s_ele_ = rnd()%ELE_MAX;
}
switch (skill_id) {
case GS_GROUNDDRIFT:
s_ele = s_ele_ = wflag; //element comes in flag.
break;
case LK_SPIRALPIERCE:
if (!sd) n_ele = false; //forced neutral for monsters
break;
case LG_HESPERUSLIT:
if ( sc && sc->data[SC_BANDING] && sc->data[SC_BANDING]->val2 == 5 )
s_ele = ELE_HOLY; // Banding with 5 RGs: change atk element to Holy.
break;
}
if (!(nk & NK_NO_ELEFIX) && !n_ele)
if (src->type == BL_HOM)
n_ele = true; //skill is "not elemental"
if (sc && sc->data[SC_GOLDENE_FERSE] && ((!skill_id && (rnd() % 100 < sc->data[SC_GOLDENE_FERSE]->val4)) || skill_id == MH_STAHL_HORN)) {
s_ele = s_ele_ = ELE_HOLY;
n_ele = false;
}
if(!skill_id) {
//Skills ALWAYS use ONLY your right-hand weapon (tested on Aegis 10.2)
if (sd && sd->weapontype1 == 0 && sd->weapontype2 > 0)
{
flag.rh=0;
flag.lh=1;
}
if (sstatus->lhw.atk)
flag.lh=1;
}
if (sd && !skill_id) {
//Check for double attack.
if (( (skill_lv=pc->checkskill(sd,TF_DOUBLE)) > 0 && sd->weapontype1 == W_DAGGER )
|| ( sd->bonus.double_rate > 0 && sd->weapontype1 != W_FIST ) //Will fail bare-handed
|| ( sc && sc->data[SC_KAGEMUSYA] && sd->weapontype1 != W_FIST ) // Need confirmation
) {
//Success chance is not added, the higher one is used [Skotlex]
if( rnd()%100 < ( 5*skill_lv > sd->bonus.double_rate ? 5*skill_lv : sc && sc->data[SC_KAGEMUSYA]?sc->data[SC_KAGEMUSYA]->val1*3:sd->bonus.double_rate ) )
{
wd.div_ = skill->get_num(TF_DOUBLE,skill_lv?skill_lv:1);
wd.type = BDT_MULTIHIT;
}
}
else if( sd->weapontype1 == W_REVOLVER && (skill_lv = pc->checkskill(sd,GS_CHAINACTION)) > 0 && rnd()%100 < 5*skill_lv )
{
wd.div_ = skill->get_num(GS_CHAINACTION,skill_lv);
wd.type = BDT_MULTIHIT;
}
else if(sc && sc->data[SC_FEARBREEZE] && sd->weapontype1==W_BOW
&& (i = sd->equip_index[EQI_AMMO]) >= 0 && sd->inventory_data[i] && sd->status.inventory[i].amount > 1){
int chance = rnd()%100;
switch(sc->data[SC_FEARBREEZE]->val1){
case 5:
if( chance < 3){// 3 % chance to attack 5 times.
wd.div_ = 5;
break;
}
case 4:
if( chance < 7){// 6 % chance to attack 4 times.
wd.div_ = 4;
break;
}
case 3:
if( chance < 10){// 9 % chance to attack 3 times.
wd.div_ = 3;
break;
}
case 2:
case 1:
if( chance < 13){// 12 % chance to attack 2 times.
wd.div_ = 2;
break;
}
}
if ( wd.div_ > 1 ) {
wd.div_ = min(wd.div_, sd->status.inventory[i].amount);
sc->data[SC_FEARBREEZE]->val4 = wd.div_ - 1;
wd.type = BDT_MULTIHIT;
}
}
}
//Check for critical
if( !flag.cri && wd.type != BDT_MULTIHIT && sstatus->cri &&
(!skill_id ||
skill_id == KN_AUTOCOUNTER ||
skill_id == SN_SHARPSHOOTING || skill_id == MA_SHARPSHOOTING ||
skill_id == NJ_KIRIKAGE))
{
short cri = sstatus->cri;
if (sd != NULL) {
// if show_katar_crit_bonus is enabled, it already done the calculation in status.c
if (!battle_config.show_katar_crit_bonus && sd->status.weapon == W_KATAR) {
cri <<= 1;
}
cri+= sd->critaddrace[tstatus->race];
if (flag.arrow) {
cri += sd->bonus.arrow_cri;
}
}
if (sc && sc->data[SC_CAMOUFLAGE])
cri += 10 * (10-sc->data[SC_CAMOUFLAGE]->val4);
//The official equation is *2, but that only applies when sd's do critical.
//Therefore, we use the old value 3 on cases when an sd gets attacked by a mob
cri -= tstatus->luk*(!sd&&tsd?3:2);
if( tsc && tsc->data[SC_SLEEP] ) {
cri <<= 1;
}
switch (skill_id) {
case 0:
if(!(sc && sc->data[SC_AUTOCOUNTER]))
break;
status_change_end(src, SC_AUTOCOUNTER, INVALID_TIMER);
case KN_AUTOCOUNTER:
if(battle_config.auto_counter_type &&
(battle_config.auto_counter_type&src->type))
flag.cri = 1;
else
cri <<= 1;
break;
case SN_SHARPSHOOTING:
case MA_SHARPSHOOTING:
cri += 200;
break;
case NJ_KIRIKAGE:
cri += 250 + 50*skill_lv;
break;
}
if(tsd && tsd->bonus.critical_def)
cri = cri * ( 100 - tsd->bonus.critical_def ) / 100;
if (rnd()%1000 < cri)
flag.cri = 1;
}
if (flag.cri) {
wd.type = BDT_CRIT;
flag.idef = flag.idef2 =
flag.hit = 1;
} else {
//Check for Perfect Hit
if(sd && sd->bonus.perfect_hit > 0 && rnd()%100 < sd->bonus.perfect_hit)
flag.hit = 1;
if (sc && sc->data[SC_FUSION]) {
flag.hit = 1; //SG_FUSION always hit [Komurka]
flag.idef = flag.idef2 = 1; //def ignore [Komurka]
}
if( !flag.hit )
switch(skill_id)
{
case AS_SPLASHER:
if( !wflag ) // Always hits the one exploding.
flag.hit = 1;
break;
case CR_SHIELDBOOMERANG:
if( sc && sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_CRUSADER )
flag.hit = 1;
break;
}
if (tsc && !flag.hit && tsc->opt1 && tsc->opt1 != OPT1_STONEWAIT && tsc->opt1 != OPT1_BURNING)
flag.hit = 1;
}
if (!flag.hit) {
//Hit/Flee calculation
short flee = tstatus->flee;
short hitrate = 80; //Default hitrate
if(battle_config.agi_penalty_type && battle_config.agi_penalty_target&target->type) {
unsigned char attacker_count; //256 max targets should be a sane max
attacker_count = unit->counttargeted(target);
if(attacker_count >= battle_config.agi_penalty_count) {
if (battle_config.agi_penalty_type == 1)
flee = (flee * (100 - (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num))/100;
else //asume type 2: absolute reduction
flee -= (attacker_count - (battle_config.agi_penalty_count - 1))*battle_config.agi_penalty_num;
if(flee < 1) flee = 1;
}
}
hitrate+= sstatus->hit - flee;
if(wd.flag&BF_LONG && !skill_id && //Fogwall's hit penalty is only for normal ranged attacks.
tsc && tsc->data[SC_FOGWALL])
hitrate -= 50;
if(sd && flag.arrow)
hitrate += sd->bonus.arrow_hit;
switch(skill_id) {
//Hit skill modifiers
//It is proven that bonus is applied on final hitrate, not hit.
case SM_BASH:
case MS_BASH:
hitrate += hitrate * 5 * skill_lv / 100;
break;
case MS_MAGNUM:
case SM_MAGNUM:
hitrate += hitrate * 10 * skill_lv / 100;
break;
case KN_AUTOCOUNTER:
case PA_SHIELDCHAIN:
case NPC_WATERATTACK:
case NPC_GROUNDATTACK:
case NPC_FIREATTACK:
case NPC_WINDATTACK:
case NPC_POISONATTACK:
case NPC_HOLYATTACK:
case NPC_DARKNESSATTACK:
case NPC_UNDEADATTACK:
case NPC_TELEKINESISATTACK:
case NPC_BLEEDING:
case NPC_EARTHQUAKE:
case NPC_FIREBREATH:
case NPC_ICEBREATH:
case NPC_THUNDERBREATH:
case NPC_ACIDBREATH:
case NPC_DARKNESSBREATH:
hitrate += hitrate * 20 / 100;
break;
case KN_PIERCE:
case ML_PIERCE:
hitrate += hitrate * 5 * skill_lv / 100;
break;
case AS_SONICBLOW:
if(sd && pc->checkskill(sd,AS_SONICACCEL)>0)
hitrate += hitrate * 50 / 100;
break;
case MC_CARTREVOLUTION:
case GN_CART_TORNADO:
case GN_CARTCANNON:
if( sd && pc->checkskill(sd, GN_REMODELING_CART) )
hitrate += pc->checkskill(sd, GN_REMODELING_CART) * 4;
break;
case GC_VENOMPRESSURE:
hitrate += 10 + 4 * skill_lv;
break;
case SC_FATALMENACE:
hitrate -= 35 - 5 * skill_lv;
break;
case LG_BANISHINGPOINT:
hitrate += 3 * skill_lv;
break;
}
if( sd ) {
// Weaponry Research hidden bonus
if ((temp = pc->checkskill(sd,BS_WEAPONRESEARCH)) > 0)
hitrate += hitrate * ( 2 * temp ) / 100;
if( (sd->status.weapon == W_1HSWORD || sd->status.weapon == W_DAGGER) &&
(temp = pc->checkskill(sd, GN_TRAINING_SWORD))>0 )
hitrate += 3 * temp;
}
hitrate = cap_value(hitrate, battle_config.min_hitrate, battle_config.max_hitrate);
if(rnd()%100 >= hitrate){
wd.dmg_lv = ATK_FLEE;
if (skill_id == SR_GATEOFHELL)
flag.hit = 1;/* will hit with the special */
}
else
flag.hit = 1;
} //End hit/miss calculation
if (flag.hit && !flag.infdef) { //No need to do the math for plants
unsigned int skillratio = 100; //Skill dmg modifiers.
//Hitting attack
//Assuming that 99% of the cases we will not need to check for the flag.rh... we don't.
//ATK_RATE scales the damage. 100 = no change. 50 is halved, 200 is doubled, etc
#define ATK_RATE( a ) do { int64 temp__ = (a); wd.damage= wd.damage*temp__/100 ; if(flag.lh) wd.damage2= wd.damage2*temp__/100; } while(0)
#define ATK_RATER(a) ( wd.damage = wd.damage*(a)/100 )
#define ATK_RATEL(a) ( wd.damage2 = wd.damage2*(a)/100 )
//Adds dmg%. 100 = +100% (double) damage. 10 = +10% damage
#define ATK_ADDRATE( a ) do { int64 temp__ = (a); wd.damage+= wd.damage*temp__/100; if(flag.lh) wd.damage2+= wd.damage2*temp__/100; } while(0)
//Adds an absolute value to damage. 100 = +100 damage
#define ATK_ADD( a ) do { int64 temp__ = (a); wd.damage += temp__; if (flag.lh) wd.damage2 += temp__; } while(0)
#define ATK_ADD2( a , b ) do { wd.damage += (a); if (flag.lh) wd.damage2 += (b); } while(0)
switch (skill_id) {
//Calc base damage according to skill
case PA_SACRIFICE:
wd.damage = sstatus->max_hp* 9/100;
wd.damage2 = 0;
break;
case NJ_ISSEN: // [malufett]
wd.damage = 40*sstatus->str +skill_lv*(sstatus->hp/10 + 35);
wd.damage2 = 0;
break;
case LK_SPIRALPIERCE:
case ML_SPIRALPIERCE:
if (sd) {
short index = sd->equip_index[EQI_HAND_R];
if (index >= 0 &&
sd->inventory_data[index] &&
sd->inventory_data[index]->type == IT_WEAPON)
wd.damage = sd->inventory_data[index]->weight*8/100; //80% of weight
ATK_ADDRATE(50*skill_lv); //Skill modifier applies to weight only.
} else {
wd.damage = battle->calc_base_damage2(sstatus, &sstatus->rhw, sc, tstatus->size, sd, 0); //Monsters have no weight and use ATK instead
}
i = sstatus->str/10;
i*=i;
ATK_ADD(i); //Add str bonus.
switch (tstatus->size) { //Size-fix. Is this modified by weapon perfection?
case SZ_SMALL: //Small: 125%
ATK_RATE(125);
break;
//case SZ_MEDIUM: //Medium: 100%
case SZ_BIG: //Large: 75%
ATK_RATE(75);
break;
}
break;
case PA_SHIELDCHAIN:
case CR_SHIELDBOOMERANG:
wd.damage = sstatus->batk;
if (sd) {
int damagevalue = 0;
short index = sd->equip_index[EQI_HAND_L];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR )
damagevalue = sd->inventory_data[index]->weight/10;
ATK_ADD(damagevalue);
} else
ATK_ADD(sstatus->rhw.atk2); //Else use Atk2
break;
case HFLI_SBR44: //[orn]
if (src->type == BL_HOM) {
const struct homun_data *hd = BL_UCCAST(BL_HOM, src);
wd.damage = hd->homunculus.intimacy;
break;
}
break;
default:
{
i = (flag.cri
?1:0)|
(flag.arrow?2:0)|
(skill_id == HW_MAGICCRASHER?4:0)|
(skill_id == MO_EXTREMITYFIST?8:0)|
(!skill_id && sc && sc->data[SC_HLIF_CHANGE]?4:0)|
(sc && sc->data[SC_WEAPONPERFECT]?8:0);
if (flag.arrow && sd)
switch(sd->status.weapon) {
case W_BOW:
case W_REVOLVER:
case W_GATLING:
case W_SHOTGUN:
case W_GRENADE:
break;
default:
i |= 16; // for ex. shuriken must not be influenced by DEX
}
wd.damage = battle->calc_base_damage2(sstatus, &sstatus->rhw, sc, tstatus->size, sd, i);
if (flag.lh)
wd.damage2 = battle->calc_base_damage2(sstatus, &sstatus->lhw, sc, tstatus->size, sd, i);
if (nk&NK_SPLASHSPLIT){ // Divide ATK among targets
if(wflag>0)
wd.damage/= wflag;
else
ShowError("0 enemies targeted by %d:%s, divide per 0 avoided!\n", skill_id, skill->get_name(skill_id));
}
//Add any bonuses that modify the base baseatk+watk (pre-skills)
if(sd) {
if (sd->bonus.atk_rate)
ATK_ADDRATE(sd->bonus.atk_rate);
if(flag.cri && sd->bonus.crit_atk_rate)
ATK_ADDRATE(sd->bonus.crit_atk_rate);
if(flag.cri && sc && sc->data[SC_MTF_CRIDAMAGE])
ATK_ADDRATE(sc->data[SC_MTF_CRIDAMAGE]->val1);// temporary it should be 'bonus.crit_atk_rate'
if(sd->status.party_id && (temp=pc->checkskill(sd,TK_POWER)) > 0){
if( (i = party->foreachsamemap(party->sub_count, sd, 0)) > 1 ) // exclude the player himself [Inkfish]
ATK_ADDRATE(2*temp*i);
}
}
break;
} //End default case
} //End switch(skill_id)
if( sc && skill_id != PA_SACRIFICE && sc->data[SC_UNLIMIT] && (wd.flag&(BF_LONG|BF_MAGIC)) == BF_LONG) {
switch(skill_id) {
case RA_WUGDASH:
case RA_WUGSTRIKE:
case RA_WUGBITE:
break;
default:
ATK_ADDRATE( 50 * sc->data[SC_UNLIMIT]->val1 );
}
}
if ( sc && !skill_id && sc->data[SC_EXEEDBREAK] ) {
ATK_ADDRATE(sc->data[SC_EXEEDBREAK]->val1);
status_change_end(src, SC_EXEEDBREAK, INVALID_TIMER);
}
switch(skill_id){
case SR_GATEOFHELL:
if (wd.dmg_lv != ATK_FLEE)
ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag));
else
wd.dmg_lv = ATK_DEF;
break;
case KO_BAKURETSU:
{
skillratio = skill_lv * (50 + status_get_dex(src) / 4);
skillratio = (int)(skillratio * (sd ? pc->checkskill(sd, NJ_TOBIDOUGU) : 10) * 40.f / 100.0f * status->get_lv(src) / 120);
ATK_RATE(skillratio + 10 * (sd ? sd->status.job_level : 0));
}
break;
default:
ATK_RATE(battle->calc_skillratio(BF_WEAPON, src, target, skill_id, skill_lv, skillratio, wflag));
}
//Constant/misc additions from skills
switch (skill_id) {
case MO_EXTREMITYFIST:
ATK_ADD(250 + 150*skill_lv);
break;
case TK_DOWNKICK:
case TK_STORMKICK:
case TK_TURNKICK:
case TK_COUNTER:
case TK_JUMPKICK:
//TK_RUN kick damage bonus.
if(sd && sd->weapontype1 == W_FIST && sd->weapontype2 == W_FIST)
ATK_ADD(10*pc->checkskill(sd, TK_RUN));
break;
case GS_MAGICALBULLET:
ATK_ADD( status->get_matk(src, 2) );
break;
case NJ_SYURIKEN:
ATK_ADD(4*skill_lv);
break;
case GC_COUNTERSLASH:
ATK_ADD( status_get_agi(src) * 2 + (sd?sd->status.job_level:0) * 4 );
break;
case RA_WUGDASH:
if( sc && sc->data[SC_DANCE_WITH_WUG] )
ATK_ADD(2 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd)));
break;
case SR_TIGERCANNON:
ATK_ADD( skill_lv * 240 + status->get_lv(target) * 40 );
if( sc && sc->data[SC_COMBOATTACK]
&& sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE )
ATK_ADD( skill_lv * 500 + status->get_lv(target) * 40 );
break;
case RA_WUGSTRIKE:
case RA_WUGBITE:
if(sd)
ATK_ADD(30*pc->checkskill(sd, RA_TOOTHOFWUG));
if( sc && sc->data[SC_DANCE_WITH_WUG] )
ATK_ADD(2 * sc->data[SC_DANCE_WITH_WUG]->val1 * (2 + battle->calc_chorusbonus(sd)));
break;
case LG_SHIELDPRESS:
if( sd ) {
int damagevalue = 0;
short index = sd->equip_index[EQI_HAND_L];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR )
damagevalue = sstatus->vit * sd->status.inventory[index].refine;
ATK_ADD(damagevalue);
}
break;
case SR_GATEOFHELL:
ATK_ADD(sstatus->max_hp - status_get_hp(src));
if ( sc && sc->data[SC_COMBOATTACK] && sc->data[SC_COMBOATTACK]->val1 == SR_FALLENEMPIRE ) {
ATK_ADD((sstatus->max_sp * (1 + skill_lv * 2 / 10)) + 40 * status->get_lv(src));
} else {
ATK_ADD((sstatus->sp * (1 + skill_lv * 2 / 10)) + 10 * status->get_lv(src));
}
break;
case SR_FALLENEMPIRE:// [(Target Size value + Skill Level - 1) x Caster STR] + [(Target current weight x Caster DEX / 120)]
ATK_ADD( ((tstatus->size+1)*2 + (int64)skill_lv - 1) * sstatus->str);
if( tsd && tsd->weight ){
ATK_ADD( (tsd->weight/10) * sstatus->dex / 120 );
}else{
ATK_ADD( status->get_lv(target) * 50 ); //mobs
}
break;
case KO_SETSUDAN:
if( tsc && tsc->data[SC_SOULLINK] ){
ATK_ADDRATE(200*tsc->data[SC_SOULLINK]->val1);
status_change_end(target,SC_SOULLINK,INVALID_TIMER);
}
break;
case KO_MAKIBISHI:
wd.damage = 20 * skill_lv;
break;
}
//Div fix.
damage_div_fix(wd.damage, wd.div_);
//The following are applied on top of current damage and are stackable.
if ( sc ) {
if( sc->data[SC_TRUESIGHT] )
ATK_ADDRATE(2*sc->data[SC_TRUESIGHT]->val1);
if( sc->data[SC_EDP] ){
switch(skill_id){
case AS_SPLASHER: // Needs more info
case ASC_BREAKER:
case ASC_METEORASSAULT: break;
default:
ATK_ADDRATE(sc->data[SC_EDP]->val3);
}
}
if(sc->data[SC_STYLE_CHANGE]){
struct homun_data *hd = BL_CAST(BL_HOM, src);
if (hd != NULL)
ATK_ADD(hd->homunculus.spiritball * 3);
}
}
switch (skill_id) {
case AS_SONICBLOW:
if (sc && sc->data[SC_SOULLINK] &&
sc->data[SC_SOULLINK]->val2 == SL_ASSASIN)
ATK_ADDRATE(map_flag_gvg(src->m)?25:100); //+25% dmg on woe/+100% dmg on nonwoe
if(sd && pc->checkskill(sd,AS_SONICACCEL)>0)
ATK_ADDRATE(10);
break;
case CR_SHIELDBOOMERANG:
if(sc && sc->data[SC_SOULLINK] &&
sc->data[SC_SOULLINK]->val2 == SL_CRUSADER)
ATK_ADDRATE(100);
break;
}
if( skill_id ){
uint16 rskill;/* redirect skill id */
switch(skill_id){
case AB_DUPLELIGHT_MELEE:
rskill = AB_DUPLELIGHT;
break;
case LG_OVERBRAND_BRANDISH:
case LG_OVERBRAND_PLUSATK:
rskill = LG_OVERBRAND;
break;
case WM_SEVERE_RAINSTORM_MELEE:
rskill = WM_SEVERE_RAINSTORM;
break;
case WM_REVERBERATION_MELEE:
rskill = WM_REVERBERATION;
break;
case GN_CRAZYWEED_ATK:
rskill = GN_CRAZYWEED;
break;
case GN_SLINGITEM_RANGEMELEEATK:
rskill = GN_SLINGITEM;
break;
case RL_R_TRIP_PLUSATK:
rskill = RL_R_TRIP;
break;
case RL_B_FLICKER_ATK:
rskill = RL_FLICKER;
break;
case RL_GLITTERING_GREED_ATK:
rskill = RL_GLITTERING_GREED;
break;
default:
rskill = skill_id;
}
if( (i = battle->adjust_skill_damage(src->m,rskill)) )
ATK_RATE(i);
}
if( sd ) {
if (skill_id && (i = pc->skillatk_bonus(sd, skill_id)))
ATK_ADDRATE(i);
if( (i=pc->checkskill(sd,AB_EUCHARISTICA)) > 0 &&
(tstatus->race == RC_DEMON || tstatus->def_ele == ELE_DARK) )
ATK_ADDRATE(-i);
if (skill_id != PA_SACRIFICE && skill_id != MO_INVESTIGATE && skill_id != CR_GRANDCROSS && skill_id != NPC_GRANDDARKNESS && skill_id != PA_SHIELDCHAIN && !flag.cri) {
//Elemental/Racial adjustments
if (sd->right_weapon.def_ratio_atk_ele & (1<<tstatus->def_ele)
|| sd->right_weapon.def_ratio_atk_race & map->race_id2mask(tstatus->race)
|| sd->right_weapon.def_ratio_atk_race & map->race_id2mask(is_boss(target) ? RC_BOSS : RC_NONBOSS)
)
flag.pdef = 1;
if (sd->left_weapon.def_ratio_atk_ele & (1<<tstatus->def_ele)
|| sd->left_weapon.def_ratio_atk_race & map->race_id2mask(tstatus->race)
|| sd->left_weapon.def_ratio_atk_race & map->race_id2mask(is_boss(target) ? RC_BOSS : RC_NONBOSS)
) {
//Pass effect onto right hand if configured so. [Skotlex]
if (battle_config.left_cardfix_to_right && flag.rh)
flag.pdef = 1;
else
flag.pdef2 = 1;
}
}
if (skill_id != CR_GRANDCROSS && skill_id != NPC_GRANDDARKNESS) {
//Ignore Defense?
if (!flag.idef && (
sd->right_weapon.ignore_def_ele & (1<<tstatus->def_ele) ||
sd->right_weapon.ignore_def_race & map->race_id2mask(tstatus->race) ||
sd->right_weapon.ignore_def_race & map->race_id2mask(is_boss(target) ? RC_BOSS : RC_NONBOSS)
))
flag.idef = 1;
if (!flag.idef2 && (
sd->left_weapon.ignore_def_ele & (1<<tstatus->def_ele) ||
sd->left_weapon.ignore_def_race & map->race_id2mask(tstatus->race) ||
sd->left_weapon.ignore_def_race & map->race_id2mask(is_boss(target) ? RC_BOSS : RC_NONBOSS)
)) {
if(battle_config.left_cardfix_to_right && flag.rh) //Move effect to right hand. [Skotlex]
flag.idef = 1;
else
flag.idef2 = 1;
}
}
}
if((!flag.idef || !flag.idef2)) { //Defense reduction
wd.damage = battle->calc_defense(BF_WEAPON, src, target, skill_id, skill_lv, wd.damage,
(flag.idef?1:0)|(flag.pdef?2:0)
, flag.pdef);
if( wd.damage2 )
wd.damage2 = battle->calc_defense(BF_WEAPON, src, target, skill_id, skill_lv, wd.damage2,
(flag.idef2?1:0)|(flag.pdef2?2:0)
, flag.pdef2);
}
//Post skill/vit reduction damage increases
if (sc) {
//SC skill damages
if(sc->data[SC_AURABLADE]
&& skill_id != LK_SPIRALPIERCE && skill_id != ML_SPIRALPIERCE
){
int lv = sc->data[SC_AURABLADE]->val1;
ATK_ADD(20*lv);
}
if( !skill_id ) {
if( sc->data[SC_ENCHANTBLADE] ) {
//[( ( Skill Lv x 20 ) + 100 ) x ( casterBaseLevel / 150 )] + casterInt
i = ( sc->data[SC_ENCHANTBLADE]->val1 * 20 + 100 ) * status->get_lv(src) / 150 + status_get_int(src);
i = i - status->get_total_mdef(target) + status->get_matk(src, 2);
if( i )
ATK_ADD(i);
}
if( sc->data[SC_GIANTGROWTH] && rnd()%100 < 15 )
ATK_ADDRATE(200); // Triple Damage
}
}
//Refine bonus
if( sd && flag.weapon && skill_id != MO_INVESTIGATE && skill_id != MO_EXTREMITYFIST )
{ // Counts refine bonus multiple times
if( skill_id == MO_FINGEROFFENSIVE )
{
ATK_ADD2(wd.div_*sstatus->rhw.atk2, wd.div_*sstatus->lhw.atk2);
} else {
ATK_ADD2(sstatus->rhw.atk2, sstatus->lhw.atk2);
}
}
//Set to min of 1
if (flag.rh && wd.damage < 1) wd.damage = 1;
if (flag.lh && wd.damage2 < 1) wd.damage2 = 1;
wd.damage = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage, wd.div_, 0, flag.weapon);
if( flag.lh )
wd.damage2 = battle->calc_masteryfix(src, target, skill_id, skill_lv, wd.damage2, wd.div_, 1, flag.weapon);
} //Here ends flag.hit section, the rest of the function applies to both hitting and missing attacks
else if(wd.div_ < 0) //Since the attack missed...
wd.div_ *= -1;
if(sd && (temp=pc->checkskill(sd,BS_WEAPONRESEARCH)) > 0)
ATK_ADD(temp*2);
wd.damage = battle->calc_elefix(src, target, skill_id, skill_lv, wd.damage, nk, n_ele, s_ele, s_ele_, false, flag.arrow);
if( flag.lh )
wd.damage2 = battle->calc_elefix(src, target, skill_id, skill_lv, wd.damage2, nk, n_ele, s_ele, s_ele_, true, flag.arrow);
if(skill_id == CR_GRANDCROSS || skill_id == NPC_GRANDDARKNESS)
return wd; //Enough, rest is not needed.
#ifndef HMAP_ZONE_DAMAGE_CAP_TYPE
if (skill_id) {
for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) {
if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) {
if (target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE) {
const struct mob_data *md = BL_UCCAST(BL_MOB, target);
if ((md->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS))
continue;
if (md->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE))
continue;
}
if( wd.damage > map->list[target->m].zone->capped_skills[i]->cap )
wd.damage = map->list[target->m].zone->capped_skills[i]->cap;
if( wd.damage2 > map->list[target->m].zone->capped_skills[i]->cap )
wd.damage2 = map->list[target->m].zone->capped_skills[i]->cap;
break;
}
}
}
#endif
if (sd) {
if (skill_id != CR_SHIELDBOOMERANG) //Only Shield boomerang doesn't takes the Star Crumbs bonus.
ATK_ADD2(wd.div_*sd->right_weapon.star, wd.div_*sd->left_weapon.star);
if (skill_id==MO_FINGEROFFENSIVE) { //The finger offensive spheres on moment of attack do count. [Skotlex]
ATK_ADD(wd.div_*sd->spiritball_old*3);
} else {
ATK_ADD(wd.div_*sd->spiritball*3);
}
//Card Fix, sd side
wd.damage = battle->calc_cardfix(BF_WEAPON, src, target, nk, s_ele, s_ele_, wd.damage, 2, wd.flag);
if( flag.lh )
wd.damage2 = battle->calc_cardfix(BF_WEAPON, src, target, nk, s_ele, s_ele_, wd.damage2, 3, wd.flag);
if( skill_id == CR_SHIELDBOOMERANG || skill_id == PA_SHIELDCHAIN )
{ //Refine bonus applies after cards and elements.
short index= sd->equip_index[EQI_HAND_L];
if( index >= 0 && sd->inventory_data[index] && sd->inventory_data[index]->type == IT_ARMOR )
ATK_ADD(10*sd->status.inventory[index].refine);
}
}
//Card Fix, tsd side
if ( tsd ) { //if player on player then it was already measured above
wd.damage = battle->calc_cardfix(BF_WEAPON, src, target, nk, s_ele, s_ele_, wd.damage, (flag.lh ? 1 : 0), wd.flag);
}
if( flag.infdef ) { //Plants receive 1 damage when hit
short class_ = status->get_class(target);
if( flag.hit || wd.damage > 0 )
wd.damage = wd.div_; // In some cases, right hand no need to have a weapon to increase damage
if( flag.lh && (flag.hit || wd.damage2 > 0) )
wd.damage2 = wd.div_;
if (flag.hit && class_ == MOBID_EMPELIUM) {
if(wd.damage2 > 0) {
wd.damage2 = battle->attr_fix(src,target,wd.damage2,s_ele_,tstatus->def_ele, tstatus->ele_lv);
wd.damage2 = battle->calc_gvg_damage(src,target,wd.damage2,wd.div_,skill_id,skill_lv,wd.flag);
}
else if(wd.damage > 0) {
wd.damage = battle->attr_fix(src,target,wd.damage,s_ele_,tstatus->def_ele, tstatus->ele_lv);
wd.damage = battle->calc_gvg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag);
}
return wd;
}
if( !(battle_config.skill_min_damage&1) )
//Do not return if you are supposed to deal greater damage to plants than 1. [Skotlex]
return wd;
}
if (sd) {
if (!flag.rh && flag.lh) {
//Move lh damage to the rh
wd.damage = wd.damage2;
wd.damage2 = 0;
flag.rh=1;
flag.lh=0;
} else if(flag.rh && flag.lh) {
//Dual-wield
if (wd.damage) {
temp = pc->checkskill(sd,AS_RIGHT) * 10;
if( (sd->class_&MAPID_UPPERMASK) == MAPID_KAGEROUOBORO )
temp = pc->checkskill(sd,KO_RIGHT) * 10 + 20;
ATK_RATER( 50 + temp );
}
if (wd.damage2) {
temp = pc->checkskill(sd,AS_LEFT) * 10;
if( (sd->class_&MAPID_UPPERMASK) == MAPID_KAGEROUOBORO )
temp = pc->checkskill(sd,KO_LEFT) * 10 + 20;
ATK_RATEL( 30 + temp );
}
if(wd.damage < 1) wd.damage = 1;
if(wd.damage2 < 1) wd.damage2 = 1;
} else if(sd->status.weapon == W_KATAR && !skill_id) { //Katars (offhand damage only applies to normal attacks, tested on Aegis 10.2)
temp = pc->checkskill(sd,TF_DOUBLE);
wd.damage2 = wd.damage * (1 + (temp * 2))/100;
if(wd.damage && !wd.damage2) {
wd.damage2 = 1;
}
flag.lh = 1;
}
}
if(!flag.rh && wd.damage)
wd.damage=0;
if(!flag.lh && wd.damage2)
wd.damage2=0;
if( sc && sc->data[SC_GLOOMYDAY] ) {
switch( skill_id ) {
case KN_BRANDISHSPEAR:
case LK_SPIRALPIERCE:
case CR_SHIELDCHARGE:
case CR_SHIELDBOOMERANG:
case PA_SHIELDCHAIN:
case RK_HUNDREDSPEAR:
case LG_SHIELDPRESS:
wd.damage += wd.damage * sc->data[SC_GLOOMYDAY]->val2 / 100;
}
}
if( sc ) {
//SG_FUSION hp penalty [Komurka]
if (sc->data[SC_FUSION]) {
int hp= sstatus->max_hp;
if (sd && tsd) {
hp = 8*hp/100;
if ((sstatus->hp * 100) <= (sstatus->max_hp * 20))
hp = sstatus->hp;
} else
hp = 2*hp/100; //2% hp loss per hit
status_zap(src, hp, 0);
}
status_change_end(src,SC_CAMOUFLAGE, INVALID_TIMER);
}
switch(skill_id){
case LG_RAYOFGENESIS:
{
struct Damage md = battle->calc_magic_attack(src, target, skill_id, skill_lv, wflag);
wd.damage += md.damage;
break;
}
}
if( wd.damage + wd.damage2 ) { //There is a total damage value
int64 damage = wd.damage + wd.damage2;
if (!wd.damage2) {
wd.damage = battle->calc_damage(src, target, &wd, wd.damage, skill_id, skill_lv);
if( map_flag_gvg2(target->m) )
wd.damage=battle->calc_gvg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag);
else if( map->list[target->m].flag.battleground )
wd.damage=battle->calc_bg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag);
}
else if (!wd.damage) {
wd.damage2 = battle->calc_damage(src, target, &wd, wd.damage2, skill_id, skill_lv);
if (map_flag_gvg2(target->m))
wd.damage2 = battle->calc_gvg_damage(src, target, wd.damage2, wd.div_, skill_id, skill_lv, wd.flag);
else if (map->list[target->m].flag.battleground)
wd.damage = battle->calc_bg_damage(src, target, wd.damage2, wd.div_, skill_id, skill_lv, wd.flag);
} else {
int64 d1 = wd.damage + wd.damage2,d2 = wd.damage2;
wd.damage = battle->calc_damage(src,target,&wd,d1,skill_id,skill_lv);
if( map_flag_gvg2(target->m) )
wd.damage = battle->calc_gvg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag);
else if( map->list[target->m].flag.battleground )
wd.damage = battle->calc_bg_damage(src,target,wd.damage,wd.div_,skill_id,skill_lv,wd.flag);
wd.damage2 = d2*100/d1 * wd.damage/100;
if(wd.damage > 1 && wd.damage2 < 1) wd.damage2 = 1;
wd.damage-=wd.damage2;
}
if( src != target ) { // Don't reflect your own damage (Grand Cross)
if( wd.dmg_lv == ATK_MISS || wd.dmg_lv == ATK_BLOCK ) {
int64 prev1 = wd.damage, prev2 = wd.damage2;
wd.damage = damage;
wd.damage2 = 0;
battle->reflect_damage(target, src, &wd, skill_id);
wd.damage = prev1;
wd.damage2 = prev2;
} else
battle->reflect_damage(target, src, &wd, skill_id);
}
}
//Reject Sword bugreport:4493 by Daegaladh
if (wd.damage != 0 && tsc != NULL && tsc->data[SC_SWORDREJECT] != NULL
&& (sd == NULL || sd->weapontype1 == W_DAGGER || sd->weapontype1 == W_1HSWORD || sd->status.weapon == W_2HSWORD)
&& rnd()%100 < tsc->data[SC_SWORDREJECT]->val2
) {
ATK_RATER(50);
status_fix_damage(target,src,wd.damage,clif->damage(target,src,0,0,wd.damage,0,BDT_NORMAL,0));
clif->skill_nodamage(target,target,ST_REJECTSWORD,tsc->data[SC_SWORDREJECT]->val1,1);
if( --(tsc->data[SC_SWORDREJECT]->val3) <= 0 )
status_change_end(target, SC_SWORDREJECT, INVALID_TIMER);
}
if(skill_id == ASC_BREAKER) {
//Breaker's int-based damage (a misc attack?)
struct Damage md = battle->calc_misc_attack(src, target, skill_id, skill_lv, wflag);
wd.damage += md.damage;
}
return wd;
}
/*==========================================
* Battle main entry, from skill->attack
*------------------------------------------*/
struct Damage battle_calc_attack(int attack_type,struct block_list *bl,struct block_list *target,uint16 skill_id,uint16 skill_lv,int count)
{
struct Damage d;
struct map_session_data *sd=BL_CAST(BL_PC,bl);
switch(attack_type) {
case BF_WEAPON: d = battle->calc_weapon_attack(bl,target,skill_id,skill_lv,count); break;
case BF_MAGIC: d = battle->calc_magic_attack(bl,target,skill_id,skill_lv,count); break;
case BF_MISC: d = battle->calc_misc_attack(bl,target,skill_id,skill_lv,count); break;
default:
ShowError("battle_calc_attack: unknown attack type! %d\n",attack_type);
memset(&d,0,sizeof(d));
break;
}
nullpo_retr(d, target);
#ifdef HMAP_ZONE_DAMAGE_CAP_TYPE
if( target && skill_id ) {
int i;
for(i = 0; i < map->list[target->m].zone->capped_skills_count; i++) {
if( skill_id == map->list[target->m].zone->capped_skills[i]->nameid && (map->list[target->m].zone->capped_skills[i]->type & target->type) ) {
if (target->type == BL_MOB && map->list[target->m].zone->capped_skills[i]->subtype != MZS_NONE) {
const struct mob_data *md = BL_UCCAST(BL_MOB, target);
if ((md->status.mode&MD_BOSS) && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_BOSS))
continue;
if (md->special_state.clone && !(map->list[target->m].zone->disabled_skills[i]->subtype&MZS_CLONE))
continue;
}
if( d.damage > map->list[target->m].zone->capped_skills[i]->cap )
d.damage = map->list[target->m].zone->capped_skills[i]->cap;
if( d.damage2 > map->list[target->m].zone->capped_skills[i]->cap )
d.damage2 = map->list[target->m].zone->capped_skills[i]->cap;
break;
}
}
}
#endif
if( d.damage + d.damage2 < 1 ) { //Miss/Absorbed
//Weapon attacks should go through to cause additional effects.
if (d.dmg_lv == ATK_DEF /*&& attack_type&(BF_MAGIC|BF_MISC)*/) // Isn't it that additional effects don't apply if miss?
d.dmg_lv = ATK_MISS;
d.dmotion = 0;
} else // Some skills like Weaponry Research will cause damage even if attack is dodged
d.dmg_lv = ATK_DEF;
if (sd && d.damage + d.damage2 > 1) {
// HPVanishRate
if (sd->bonus.hp_vanish_rate && sd->bonus.hp_vanish_trigger && rnd() % 1000 < sd->bonus.hp_vanish_rate &&
((d.flag&sd->bonus.hp_vanish_trigger&BF_WEAPONMASK) || (d.flag&sd->bonus.hp_vanish_trigger&BF_RANGEMASK)
|| (d.flag&sd->bonus.hp_vanish_trigger&BF_SKILLMASK)))
status_percent_damage(&sd->bl, target, -sd->bonus.hp_vanish_per, 0, false);
// SPVanishRate
if (sd->bonus.sp_vanish_rate && sd->bonus.sp_vanish_trigger && rnd() % 1000 < sd->bonus.sp_vanish_rate &&
((d.flag&sd->bonus.sp_vanish_trigger&BF_WEAPONMASK) || (d.flag&sd->bonus.sp_vanish_trigger&BF_RANGEMASK)
|| (d.flag&sd->bonus.sp_vanish_trigger&BF_SKILLMASK)))
status_percent_damage(&sd->bl, target, 0, -sd->bonus.sp_vanish_per, false);
}
return d;
}
//Performs reflect damage (magic (maya) is performed over skill.c).
void battle_reflect_damage(struct block_list *target, struct block_list *src, struct Damage *wd,uint16 skill_id) {
int64 damage, rdamage = 0, trdamage = 0;
struct map_session_data *sd, *tsd;
struct status_change *sc;
int64 tick = timer->gettick();
int delay = 50, rdelay = 0;
damage = wd->damage + wd->damage2;
nullpo_retv(wd);
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
sc = status->get_sc(target);
#define NORMALIZE_RDAMAGE(d) ( trdamage += rdamage = max(1, (d)) )
if( sc && !sc->count )
sc = NULL;
if( sc ) {
if (wd->flag & BF_SHORT && !(skill->get_inf(skill_id) & (INF_GROUND_SKILL | INF_SELF_SKILL))) {
if( sc->data[SC_CRESCENTELBOW] && !is_boss(src) && rnd()%100 < sc->data[SC_CRESCENTELBOW]->val2 ){
//ATK [{(Target HP / 100) x Skill Level} x Caster Base Level / 125] % + [Received damage x {1 + (Skill Level x 0.2)}]
int ratio = (status_get_hp(src) / 100) * sc->data[SC_CRESCENTELBOW]->val1 * status->get_lv(target) / 125;
if (ratio > 5000) ratio = 5000; // Maximum of 5000% ATK
rdamage = ratio + (damage)* (10 + sc->data[SC_CRESCENTELBOW]->val1 * 20 / 10) / 10;
skill->blown(target, src, skill->get_blewcount(SR_CRESCENTELBOW_AUTOSPELL, sc->data[SC_CRESCENTELBOW]->val1), unit->getdir(src), 0);
clif->skill_damage(target, src, tick, status_get_amotion(src), 0, rdamage,
1, SR_CRESCENTELBOW_AUTOSPELL, sc->data[SC_CRESCENTELBOW]->val1, BDT_SKILL); // This is how official does
clif->delay_damage(tick + delay, src, target,status_get_amotion(src)+1000,0, rdamage/10, 1, BDT_NORMAL);
status->damage(src, target, status->damage(target, src, rdamage, 0, 0, 1)/10, 0, 0, 1);
status_change_end(target, SC_CRESCENTELBOW, INVALID_TIMER);
/* shouldn't this trigger skill->additional_effect? */
return; // Just put here to minimize redundancy
}
}
if( wd->flag & BF_SHORT ) {
if( !is_boss(src) ) {
if( sc->data[SC_DEATHBOUND] && skill_id != WS_CARTTERMINATION ) {
uint8 dir = map->calc_dir(target,src->x,src->y),
t_dir = unit->getdir(target);
if( !map->check_dir(dir,t_dir) ) {
int64 rd1 = damage * sc->data[SC_DEATHBOUND]->val2 / 100; // Amplify damage.
trdamage += rdamage = rd1 - (damage = rd1 * 30 / 100); // not normalized as intended.
rdelay = clif->skill_damage(src, target, tick, status_get_amotion(src), status_get_dmotion(src), -3000, 1, RK_DEATHBOUND, sc->data[SC_DEATHBOUND]->val1, BDT_SKILL);
skill->blown(target, src, skill->get_blewcount(RK_DEATHBOUND, sc->data[SC_DEATHBOUND]->val1), unit->getdir(src), 0);
if( tsd ) /* is this right? rdamage as both left and right? */
battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0);
battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true);
delay += 100;/* gradual increase so the numbers don't clip in the client */
}
wd->damage = wd->damage + wd->damage2;
wd->damage2 = 0;
status_change_end(target,SC_DEATHBOUND,INVALID_TIMER);
}
}
}
if( sc->data[SC_KYOMU] ){
// Nullify reflecting ability of the conditions onwards
return;
}
}
if( wd->flag & BF_SHORT ) {
if ( tsd && tsd->bonus.short_weapon_damage_return ) {
NORMALIZE_RDAMAGE(damage * tsd->bonus.short_weapon_damage_return / 100);
rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE);
/* is this right? rdamage as both left and right? */
battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0);
battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true);
delay += 100;/* gradual increase so the numbers don't clip in the client */
}
if( wd->dmg_lv >= ATK_BLOCK ) {/* yes block still applies, somehow gravity thinks it makes sense. */
struct status_change *ssc;
if( sc ) {
struct status_change_entry *sce_d = sc->data[SC_DEVOTION];
struct block_list *d_bl = NULL;
if (sce_d && sce_d->val1)
d_bl = map->id2bl(sce_d->val1);
if( sc->data[SC_REFLECTSHIELD] && skill_id != WS_CARTTERMINATION && skill_id != GS_DESPERADO
&& !(d_bl && !(wd->flag&BF_SKILL)) // It should not be a basic attack if the target is under devotion
&& !(d_bl && sce_d && !check_distance_bl(target, d_bl, sce_d->val3)) // It should not be out of range if the target is under devotion
) {
NORMALIZE_RDAMAGE(damage * sc->data[SC_REFLECTSHIELD]->val2 / 100);
rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE);
/* is this right? rdamage as both left and right? */
if( tsd )
battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0);
battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true);
delay += 100;/* gradual increase so the numbers don't clip in the client */
}
if( sc->data[SC_LG_REFLECTDAMAGE] && rnd()%100 < (30 + 10*sc->data[SC_LG_REFLECTDAMAGE]->val1) ) {
bool change = false;
NORMALIZE_RDAMAGE(damage * sc->data[SC_LG_REFLECTDAMAGE]->val2 / 100);
trdamage -= rdamage;/* wont count towards total */
if( sd && !sd->state.autocast ) {
change = true;
sd->state.autocast = 1;
}
map->foreachinshootrange(battle->damage_area,target,skill->get_splash(LG_REFLECTDAMAGE,1),BL_CHAR,tick,target,delay,wd->dmotion,rdamage,status_get_race(target));
if( change )
sd->state.autocast = 0;
delay += 150;/* gradual increase so the numbers don't clip in the client */
if( (--sc->data[SC_LG_REFLECTDAMAGE]->val3) <= 0 )
status_change_end(target, SC_LG_REFLECTDAMAGE, INVALID_TIMER);
}
if( sc->data[SC_SHIELDSPELL_DEF] && sc->data[SC_SHIELDSPELL_DEF]->val1 == 2 ){
NORMALIZE_RDAMAGE(damage * sc->data[SC_SHIELDSPELL_DEF]->val2 / 100);
rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE);
/* is this right? rdamage as both left and right? */
if( tsd )
battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0);
battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true);
delay += 100;/* gradual increase so the numbers don't clip in the client */
}
if (sc->data[SC_MVPCARD_ORCLORD]) {
NORMALIZE_RDAMAGE(damage * sc->data[SC_MVPCARD_ORCLORD]->val1 / 100);
rdelay = clif->delay_damage(tick + delay, src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE);
if (tsd)
battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0);
battle->delay_damage(tick, wd->amotion, target, src, 0, CR_REFLECTSHIELD, 0, rdamage, ATK_DEF, rdelay, true);
delay += 100;
}
}
if( ( ssc = status->get_sc(src) ) ) {
if( ssc->data[SC_INSPIRATION] ) {
NORMALIZE_RDAMAGE(damage / 100);
rdelay = clif->delay_damage(tick+delay,target, target, status_get_amotion(target), status_get_dmotion(target), rdamage, 1, BDT_ENDURE);
/* is this right? rdamage as both left and right? */
if( sd )
battle->drain(sd, target, rdamage, rdamage, status_get_race(target), 0);
battle->delay_damage(tick, wd->amotion,src,target,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true);
delay += 100;/* gradual increase so the numbers don't clip in the client */
}
}
}
} else {/* long */
if ( tsd && tsd->bonus.long_weapon_damage_return ) {
NORMALIZE_RDAMAGE(damage * tsd->bonus.long_weapon_damage_return / 100);
rdelay = clif->delay_damage(tick+delay,src, src, status_get_amotion(src), status_get_dmotion(src), rdamage, 1, BDT_ENDURE);
/* is this right? rdamage as both left and right? */
battle->drain(tsd, src, rdamage, rdamage, status_get_race(src), 0);
battle->delay_damage(tick, wd->amotion,target,src,0,CR_REFLECTSHIELD,0,rdamage,ATK_DEF,rdelay,true);
delay += 100;/* gradual increase so the numbers don't clip in the client */
}
}
// Tell analyzers/compilers that we want to += it even the value is currently unused (it'd be used if we added new checks)
(void)delay;
/* something caused reflect */
if( trdamage ) {
skill->additional_effect(target, src, CR_REFLECTSHIELD, 1, BF_WEAPON|BF_SHORT|BF_NORMAL,ATK_DEF,tick);
}
return;
#undef NORMALIZE_RDAMAGE
}
void battle_drain(struct map_session_data *sd, struct block_list *tbl, int64 rdamage, int64 ldamage, int race, int boss)
{
struct weapon_data *wd;
int type, thp = 0, tsp = 0, rhp = 0, rsp = 0, hp, sp, i;
int64 *damage;
nullpo_retv(sd);
for (i = 0; i < 4; i++) {
//First two iterations: Right hand
if (i < 2) { wd = &sd->right_weapon; damage = &rdamage; }
else { wd = &sd->left_weapon; damage = &ldamage; }
if (*damage <= 0) continue;
//First and Third iterations: race, other two boss/nonboss state
if (i == 0 || i == 2)
type = race;
else
type = boss ? RC_BOSS : RC_NONBOSS;
hp = wd->hp_drain[type].value;
if (wd->hp_drain[type].rate)
hp += battle->calc_drain(*damage, wd->hp_drain[type].rate, wd->hp_drain[type].per);
sp = wd->sp_drain[type].value;
if (wd->sp_drain[type].rate)
sp += battle->calc_drain(*damage, wd->sp_drain[type].rate, wd->sp_drain[type].per);
// HPVanishRate
if (sd->bonus.hp_vanish_rate && rnd() % 1000 < sd->bonus.hp_vanish_rate && !sd->bonus.hp_vanish_trigger)
status_percent_damage(&sd->bl, tbl, (unsigned char)sd->bonus.hp_vanish_per, 0, false);
// SPVanishRate
if (sd->bonus.sp_vanish_rate && rnd() % 1000 < sd->bonus.sp_vanish_rate && !sd->bonus.sp_vanish_trigger)
status_percent_damage(&sd->bl, tbl, 0, (unsigned char)sd->bonus.sp_vanish_per, false);
if (hp) {
if (wd->hp_drain[type].type)
rhp += hp;
thp += hp;
}
if (sp) {
if (wd->sp_drain[type].type)
rsp += sp;
tsp += sp;
}
}
if (sd->sp_gain_race_attack[race])
tsp += sd->sp_gain_race_attack[race];
if (sd->hp_gain_race_attack[race])
thp += sd->hp_gain_race_attack[race];
if (!thp && !tsp) return;
status->heal(&sd->bl, thp, tsp, battle_config.show_hp_sp_drain ? 3 : 1);
if (rhp || rsp)
status_zap(tbl, rhp, rsp);
}
// Deals the same damage to targets in area. [pakpil]
int battle_damage_area(struct block_list *bl, va_list ap) {
int64 tick;
int amotion, dmotion, damage;
struct block_list *src;
nullpo_ret(bl);
tick = va_arg(ap, int64);
src=va_arg(ap,struct block_list *);
amotion=va_arg(ap,int);
dmotion=va_arg(ap,int);
damage=va_arg(ap,int);
if (bl->type == BL_MOB && BL_UCCAST(BL_MOB, bl)->class_ == MOBID_EMPELIUM)
return 0;
if( bl != src && battle->check_target(src,bl,BCT_ENEMY) > 0 ) {
struct map_session_data *sd = NULL;
nullpo_ret(src);
map->freeblock_lock();
sd = BL_CAST(BL_PC, src);
if (src->type == BL_PC)
battle->drain(sd, bl, damage, damage, status_get_race(bl), is_boss(bl));
if( amotion )
battle->delay_damage(tick, amotion,src,bl,0,CR_REFLECTSHIELD,0,damage,ATK_DEF,0,true);
else
status_fix_damage(src,bl,damage,0);
clif->damage(bl,bl,amotion,dmotion,damage,1,BDT_ENDURE,0);
if (src->type != BL_PC || !sd->state.autocast)
skill->additional_effect(src, bl, CR_REFLECTSHIELD, 1, BF_WEAPON|BF_SHORT|BF_NORMAL,ATK_DEF,tick);
map->freeblock_unlock();
}
return 0;
}
bool battle_check_arrows(struct map_session_data *sd)
{
int index = sd->equip_index[EQI_AMMO];
if (index < 0) {
if (sd->weapontype1 > W_KATAR && sd->weapontype1 < W_HUUMA)
clif->skill_fail(sd, 0, USESKILL_FAIL_NEED_MORE_BULLET, 0);
else
clif->arrow_fail(sd, 0);
return false;
}
//Ammo check by Ishizu-chan
if (sd->inventory_data[index]) {
switch (sd->status.weapon) {
case W_BOW:
if (sd->inventory_data[index]->look != A_ARROW) {
clif->arrow_fail(sd, 0);
return false;
}
break;
case W_REVOLVER:
case W_RIFLE:
case W_GATLING:
case W_SHOTGUN:
if (sd->inventory_data[index]->look != A_BULLET) {
clif->skill_fail(sd, 0, USESKILL_FAIL_NEED_MORE_BULLET, 0);
return false;
}
break;
case W_GRENADE:
if (sd->inventory_data[index]->look != A_GRENADE) {
clif->skill_fail(sd, 0, USESKILL_FAIL_NEED_MORE_BULLET, 0);
return false;
}
break;
}
}
return true;
}
/*==========================================
* Do a basic physical attack (call trough unit_attack_timer)
*------------------------------------------*/
// FIXME: flag is undocumented
enum damage_lv battle_weapon_attack(struct block_list* src, struct block_list* target, int64 tick, int flag) {
struct map_session_data *sd = NULL, *tsd = NULL;
struct status_data *sstatus, *tstatus;
struct status_change *sc, *tsc;
int64 damage;
int skillv;
struct Damage wd;
nullpo_retr(ATK_NONE, src);
nullpo_retr(ATK_NONE, target);
if (src->prev == NULL || target->prev == NULL)
return ATK_NONE;
sd = BL_CAST(BL_PC, src);
tsd = BL_CAST(BL_PC, target);
sstatus = status->get_status_data(src);
tstatus = status->get_status_data(target);
sc = status->get_sc(src);
tsc = status->get_sc(target);
if (sc && !sc->count) //Avoid sc checks when there's none to check for. [Skotlex]
sc = NULL;
if (tsc && !tsc->count)
tsc = NULL;
if (sd)
{
sd->state.arrow_atk = (sd->status.weapon == W_BOW || (sd->status.weapon >= W_REVOLVER && sd->status.weapon <= W_GRENADE));
if (sd->state.arrow_atk)
{
if (battle->check_arrows(sd) == false)
return ATK_NONE;
}
}
if (sc && sc->count) {
if (sc->data[SC_CLOAKING] && !(sc->data[SC_CLOAKING]->val4 & 2))
status_change_end(src, SC_CLOAKING, INVALID_TIMER);
else if (sc->data[SC_CLOAKINGEXCEED] && !(sc->data[SC_CLOAKINGEXCEED]->val4 & 2))
status_change_end(src, SC_CLOAKINGEXCEED, INVALID_TIMER);
}
if( tsc && tsc->data[SC_AUTOCOUNTER] && status->check_skilluse(target, src, KN_AUTOCOUNTER, 1) ) {
uint8 dir = map->calc_dir(target,src->x,src->y);
int t_dir = unit->getdir(target);
int dist = distance_bl(src, target);
if(dist <= 0 || (!map->check_dir(dir,t_dir) && dist <= tstatus->rhw.range+1)) {
uint16 skill_lv = tsc->data[SC_AUTOCOUNTER]->val1;
clif->skillcastcancel(target); //Remove the casting bar. [Skotlex]
clif->damage(src, target, sstatus->amotion, 1, 0, 1, BDT_NORMAL, 0); //Display MISS.
status_change_end(target, SC_AUTOCOUNTER, INVALID_TIMER);
skill->attack(BF_WEAPON,target,target,src,KN_AUTOCOUNTER,skill_lv,tick,0);
return ATK_BLOCK;
}
}
if( tsc && tsc->data[SC_BLADESTOP_WAIT] && !is_boss(src) && (src->type == BL_PC || tsd == NULL || distance_bl(src, target) <= (tsd->status.weapon == W_FIST ? 1 : 2)) )
{
uint16 skill_lv = tsc->data[SC_BLADESTOP_WAIT]->val1;
int duration = skill->get_time2(MO_BLADESTOP,skill_lv);
status_change_end(target, SC_BLADESTOP_WAIT, INVALID_TIMER);
if(sc_start4(target, src, SC_BLADESTOP, 100, sd?pc->checkskill(sd, MO_BLADESTOP):5, 0, 0, target->id, duration)) {
//Target locked.
clif->damage(src, target, sstatus->amotion, 1, 0, 1, BDT_NORMAL, 0); //Display MISS.
clif->bladestop(target, src->id, 1);
sc_start4(target, target, SC_BLADESTOP, 100, skill_lv, 0, 0, src->id, duration);
return ATK_BLOCK;
}
}
if(sd && (skillv = pc->checkskill(sd,MO_TRIPLEATTACK)) > 0) {
int triple_rate= 30 - skillv; //Base Rate
if (sc && sc->data[SC_SKILLRATE_UP] && sc->data[SC_SKILLRATE_UP]->val1 == MO_TRIPLEATTACK) {
triple_rate+= triple_rate*(sc->data[SC_SKILLRATE_UP]->val2)/100;
status_change_end(src, SC_SKILLRATE_UP, INVALID_TIMER);
}
if (rnd()%100 < triple_rate) {
if( skill->attack(BF_WEAPON,src,src,target,MO_TRIPLEATTACK,skillv,tick,0) )
return ATK_DEF;
return ATK_MISS;
}
}
if (sc) {
if (sc->data[SC_SACRIFICE]) {
uint16 skill_lv = sc->data[SC_SACRIFICE]->val1;
damage_lv ret_val;
if( --sc->data[SC_SACRIFICE]->val2 <= 0 )
status_change_end(src, SC_SACRIFICE, INVALID_TIMER);
/**
* We need to calculate the DMG before the hp reduction, because it can kill the source.
* For further information: bugreport:4950
**/
ret_val = (damage_lv)skill->attack(BF_WEAPON,src,src,target,PA_SACRIFICE,skill_lv,tick,0);
status_zap(src, sstatus->max_hp*9/100, 0);//Damage to self is always 9%
if( ret_val == ATK_NONE )
return ATK_MISS;
return ret_val;
}
if (sc->data[SC_MAGICALATTACK]) {
if( skill->attack(BF_MAGIC,src,src,target,NPC_MAGICALATTACK,sc->data[SC_MAGICALATTACK]->val1,tick,0) )
return ATK_DEF;
return ATK_MISS;
}
if( tsc && tsc->data[SC_MTF_MLEATKED] && rnd()%100 < 20 )
clif->skill_nodamage(target, target, SM_ENDURE, 5,
sc_start(target,target, SC_ENDURE, 100, 5, skill->get_time(SM_ENDURE, 5)));
}
if(tsc && tsc->data[SC_KAAHI] && tsc->data[SC_KAAHI]->val4 == INVALID_TIMER && tstatus->hp < tstatus->max_hp)
tsc->data[SC_KAAHI]->val4 = timer->add(tick + skill->get_time2(SL_KAAHI,tsc->data[SC_KAAHI]->val1), status->kaahi_heal_timer, target->id, SC_KAAHI); //Activate heal.
wd = battle->calc_attack(BF_WEAPON, src, target, 0, 0, flag);
if( sc && sc->count ) {
if( sc->data[SC_SPELLFIST] ) {
if( --(sc->data[SC_SPELLFIST]->val1) >= 0 ){
struct Damage ad = battle->calc_attack(BF_MAGIC,src,target,sc->data[SC_SPELLFIST]->val3,sc->data[SC_SPELLFIST]->val4,flag|BF_SHORT);
wd.damage = ad.damage;
damage_div_fix(wd.damage, wd.div_);
}else
status_change_end(src,SC_SPELLFIST,INVALID_TIMER);
}
if( sd && sc->data[SC_FEARBREEZE] && sc->data[SC_FEARBREEZE]->val4 > 0 && sd->status.inventory[sd->equip_index[EQI_AMMO]].amount >= sc->data[SC_FEARBREEZE]->val4 && battle_config.arrow_decrement){
pc->delitem(sd, sd->equip_index[EQI_AMMO], sc->data[SC_FEARBREEZE]->val4, 0, DELITEM_SKILLUSE, LOG_TYPE_CONSUME);
sc->data[SC_FEARBREEZE]->val4 = 0;
}
}
if (sd && sd->state.arrow_atk) //Consume arrow.
battle->consume_ammo(sd, 0, 0);
damage = wd.damage + wd.damage2;
if( damage > 0 && src != target ) {
if( sc && sc->data[SC_DUPLELIGHT] && (wd.flag&BF_SHORT) && rnd()%100 <= 10+2*sc->data[SC_DUPLELIGHT]->val1 ){
// Activates it only from melee damage
uint16 skill_id;
if( rnd()%2 == 1 )
skill_id = AB_DUPLELIGHT_MELEE;
else
skill_id = AB_DUPLELIGHT_MAGIC;
skill->attack(skill->get_type(skill_id), src, src, target, skill_id, sc->data[SC_DUPLELIGHT]->val1, tick, SD_LEVEL);
}
}
wd.dmotion = clif->damage(src, target, wd.amotion, wd.dmotion, wd.damage, wd.div_ , wd.type, wd.damage2);
if (sd && sd->bonus.splash_range > 0 && damage > 0)
skill->castend_damage_id(src, target, 0, 1, tick, 0);
if (target->type == BL_SKILL && damage > 0) {
struct skill_unit *su = BL_UCAST(BL_SKILL, target);
if (su->group && su->group->skill_id == HT_BLASTMINE)
skill->blown(src, target, 3, -1, 0);
}
map->freeblock_lock();
if( skill->check_shadowform(target, damage, wd.div_) ){
if( !status->isdead(target) )
skill->additional_effect(src, target, 0, 0, wd.flag, wd.dmg_lv, tick);
if( wd.dmg_lv > ATK_BLOCK)
skill->counter_additional_effect(src, target, 0, 0, wd.flag,tick);
}else
battle->delay_damage(tick, wd.amotion, src, target, wd.flag, 0, 0, damage, wd.dmg_lv, wd.dmotion, true);
if( tsc ) {
if( tsc->data[SC_DEVOTION] ) {
struct status_change_entry *sce = tsc->data[SC_DEVOTION];
struct block_list *d_bl = map->id2bl(sce->val1);
struct mercenary_data *d_md = BL_CAST(BL_MER, d_bl);
struct map_session_data *d_sd = BL_CAST(BL_PC, d_bl);
if (d_bl != NULL
&& ((d_bl->type == BL_MER && d_md->master != NULL && d_md->master->bl.id == target->id)
|| (d_bl->type == BL_PC && d_sd->devotion[sce->val2] == target->id)
)
&& check_distance_bl(target, d_bl, sce->val3)
) {
clif->damage(d_bl, d_bl, 0, 0, damage, 0, BDT_NORMAL, 0);
status_fix_damage(NULL, d_bl, damage, 0);
} else {
status_change_end(target, SC_DEVOTION, INVALID_TIMER);
}
} else if( tsc->data[SC_CIRCLE_OF_FIRE_OPTION] && (wd.flag&BF_SHORT) && target->type == BL_PC ) {
struct elemental_data *ed = BL_UCAST(BL_PC, target)->ed;
if (ed != NULL) {
clif->skill_damage(&ed->bl, target, tick, status_get_amotion(src), 0, -30000, 1, EL_CIRCLE_OF_FIRE, tsc->data[SC_CIRCLE_OF_FIRE_OPTION]->val1, BDT_SKILL);
skill->attack(BF_MAGIC,&ed->bl,&ed->bl,src,EL_CIRCLE_OF_FIRE,tsc->data[SC_CIRCLE_OF_FIRE_OPTION]->val1,tick,wd.flag);
}
} else if( tsc->data[SC_WATER_SCREEN_OPTION] && tsc->data[SC_WATER_SCREEN_OPTION]->val1 ) {
struct block_list *e_bl = map->id2bl(tsc->data[SC_WATER_SCREEN_OPTION]->val1);
if( e_bl && !status->isdead(e_bl) ) {
clif->damage(e_bl,e_bl,wd.amotion,wd.dmotion,damage,wd.div_,wd.type,wd.damage2);
status->damage(target,e_bl,damage,0,0,0);
// Just show damage in target.
clif->damage(src, target, wd.amotion, wd.dmotion, damage, wd.div_, wd.type, wd.damage2 );
map->freeblock_unlock();
return ATK_NONE;
}
}
}
if (sc && sc->data[SC_AUTOSPELL] && rnd()%100 < sc->data[SC_AUTOSPELL]->val4) {
int sp = 0;
uint16 skill_id = sc->data[SC_AUTOSPELL]->val2;
uint16 skill_lv = sc->data[SC_AUTOSPELL]->val3;
int i = rnd()%100;
if (sc->data[SC_SOULLINK] && sc->data[SC_SOULLINK]->val2 == SL_SAGE)
i = 0; //Max chance, no skill_lv reduction. [Skotlex]
if (i >= 50) skill_lv -= 2;
else if (i >= 15) skill_lv--;
if (skill_lv < 1) skill_lv = 1;
sp = skill->get_sp(skill_id,skill_lv) * 2 / 3;
if (status->charge(src, 0, sp)) {
switch (skill->get_casttype(skill_id)) {
case CAST_GROUND:
skill->castend_pos2(src, target->x, target->y, skill_id, skill_lv, tick, flag);
break;
case CAST_NODAMAGE:
skill->castend_nodamage_id(src, target, skill_id, skill_lv, tick, flag);
break;
case CAST_DAMAGE:
skill->castend_damage_id(src, target, skill_id, skill_lv, tick, flag);
break;
}
}
}
if (sd) {
if( wd.flag&BF_SHORT && sc
&& sc->data[SC__AUTOSHADOWSPELL] && rnd()%100 < sc->data[SC__AUTOSHADOWSPELL]->val3
&& sd->status.skill[skill->get_index(sc->data[SC__AUTOSHADOWSPELL]->val1)].id != 0
&& sd->status.skill[skill->get_index(sc->data[SC__AUTOSHADOWSPELL]->val1)].flag == SKILL_FLAG_PLAGIARIZED
) {
int r_skill = sd->status.skill[skill->get_index(sc->data[SC__AUTOSHADOWSPELL]->val1)].id;
int r_lv = sc->data[SC__AUTOSHADOWSPELL]->val2;
if (r_skill != AL_HOLYLIGHT && r_skill != PR_MAGNUS) {
int type;
if( (type = skill->get_casttype(r_skill)) == CAST_GROUND ) {
int maxcount = 0;
if( !(BL_PC&battle_config.skill_reiteration)
&& skill->get_unit_flag(r_skill)&UF_NOREITERATION )
type = -1;
if( BL_PC&battle_config.skill_nofootset
&& skill->get_unit_flag(r_skill)&UF_NOFOOTSET )
type = -1;
if( BL_PC&battle_config.land_skill_limit
&& (maxcount = skill->get_maxcount(r_skill, r_lv)) > 0
) {
int v;
for(v=0;v<MAX_SKILLUNITGROUP && sd->ud.skillunit[v] && maxcount;v++) {
if(sd->ud.skillunit[v]->skill_id == r_skill)
maxcount--;
}
if( maxcount == 0 )
type = -1;
}
if( type != CAST_GROUND ) {
clif->skill_fail(sd,r_skill,USESKILL_FAIL_LEVEL,0);
map->freeblock_unlock();
return wd.dmg_lv;
}
}
sd->state.autocast = 1;
skill->consume_requirement(sd,r_skill,r_lv,3);
switch( type ) {
case CAST_GROUND:
skill->castend_pos2(src, target->x, target->y, r_skill, r_lv, tick, flag);
break;
case CAST_NODAMAGE:
skill->castend_nodamage_id(src, target, r_skill, r_lv, tick, flag);
break;
case CAST_DAMAGE:
skill->castend_damage_id(src, target, r_skill, r_lv, tick, flag);
break;
}
sd->state.autocast = 0;
sd->ud.canact_tick = tick + skill->delay_fix(src, r_skill, r_lv);
clif->status_change(src, SI_POSTDELAY, 1, skill->delay_fix(src, r_skill, r_lv), 0, 0, 1);
}
}
if (wd.flag & BF_WEAPON && src != target && damage > 0) {
if (battle_config.left_cardfix_to_right)
battle->drain(sd, target, wd.damage, wd.damage, tstatus->race, is_boss(target));
else
battle->drain(sd, target, wd.damage, wd.damage2, tstatus->race, is_boss(target));
}
}
if (tsc) {
if (tsc->data[SC_POISONREACT]
&& ( rnd()%100 < tsc->data[SC_POISONREACT]->val3
|| sstatus->def_ele == ELE_POISON
)
/* && check_distance_bl(src, target, tstatus->rhw.range+1) Doesn't check range! o.O; */
&& status->check_skilluse(target, src, TF_POISON, 0)
) {
//Poison React
struct status_change_entry *sce = tsc->data[SC_POISONREACT];
if (sstatus->def_ele == ELE_POISON) {
sce->val2 = 0;
skill->attack(BF_WEAPON,target,target,src,AS_POISONREACT,sce->val1,tick,0);
} else {
skill->attack(BF_WEAPON,target,target,src,TF_POISON, 5, tick, 0);
--sce->val2;
}
if (sce->val2 <= 0)
status_change_end(target, SC_POISONREACT, INVALID_TIMER);
}
}
map->freeblock_unlock();
return wd.dmg_lv;
}
#undef ATK_RATE
#undef ATK_RATER
#undef ATK_RATEL
#undef ATK_ADDRATE
#undef ATK_ADD
#undef ATK_ADD2
#undef GET_NORMAL_ATTACK
#undef GET_NORMAL_ATTACK2
bool battle_check_undead(int race,int element)
{
if(battle_config.undead_detect_type == 0) {
if(element == ELE_UNDEAD)
return true;
}
else if(battle_config.undead_detect_type == 1) {
if(race == RC_UNDEAD)
return true;
}
else {
if(element == ELE_UNDEAD || race == RC_UNDEAD)
return true;
}
return false;
}
//Returns the upmost level master starting with the given object
struct block_list *battle_get_master(struct block_list *src)
{
struct block_list *prev = NULL; //Used for infinite loop check (master of yourself?)
nullpo_retr(NULL, src);
do {
prev = src;
switch (src->type) {
case BL_PET:
{
struct pet_data *pd = BL_UCAST(BL_PET, src);
if (pd->msd != NULL)
src = &pd->msd->bl;
}
break;
case BL_MOB:
{
struct mob_data *md = BL_UCAST(BL_MOB, src);
if (md->master_id != 0)
src = map->id2bl(md->master_id);
}
break;
case BL_HOM:
{
struct homun_data *hd = BL_UCAST(BL_HOM, src);
if (hd->master != NULL)
src = &hd->master->bl;
}
break;
case BL_MER:
{
struct mercenary_data *md = BL_UCAST(BL_MER, src);
if (md->master != NULL)
src = &md->master->bl;
}
break;
case BL_ELEM:
{
struct elemental_data *ed = BL_UCAST(BL_ELEM, src);
if (ed->master != NULL)
src = &ed->master->bl;
}
break;
case BL_SKILL:
{
struct skill_unit *su = BL_UCAST(BL_SKILL, src);
if (su->group != NULL && su->group->src_id != 0)
src = map->id2bl(su->group->src_id);
}
break;
}
} while (src && src != prev);
return prev;
}
/*==========================================
* Checks the state between two targets (rewritten by Skotlex)
* (enemy, friend, party, guild, etc)
* See battle.h for possible values/combinations
* to be used here (BCT_* constants)
* Return value is:
* 1: flag holds true (is enemy, party, etc)
* -1: flag fails
* 0: Invalid target (non-targetable ever)
*------------------------------------------*/
int battle_check_target( struct block_list *src, struct block_list *target,int flag)
{
int16 m; //map
int state = 0; //Initial state none
int strip_enemy = 1; //Flag which marks whether to remove the BCT_ENEMY status if it's also friend/ally.
struct block_list *s_bl = src, *t_bl = target;
nullpo_ret(src);
nullpo_ret(target);
m = target->m;
if (flag & BCT_ENEMY && (map->getcell(m, src, src->x, src->y, CELL_CHKBASILICA) || map->getcell(m, src, target->x, target->y, CELL_CHKBASILICA))) {
return -1;
}
//t_bl/s_bl hold the 'master' of the attack, while src/target are the actual
//objects involved.
if( (t_bl = battle->get_master(target)) == NULL )
t_bl = target;
if( (s_bl = battle->get_master(src)) == NULL )
s_bl = src;
if (s_bl->type == BL_PC) {
const struct map_session_data *s_sd = BL_UCCAST(BL_PC, s_bl);
switch (t_bl->type) {
case BL_MOB: // Source => PC, Target => MOB
if (pc_has_permission(s_sd, PC_PERM_DISABLE_PVM))
return 0;
break;
case BL_PC:
if (pc_has_permission(s_sd, PC_PERM_DISABLE_PVP))
return 0;
break;
default:/* anything else goes */
break;
}
}
switch( target->type ) { // Checks on actual target
case BL_PC:
{
const struct status_change *sc = status->get_sc(src);
const struct map_session_data *t_sd = BL_UCCAST(BL_PC, target);
if (t_sd->invincible_timer != INVALID_TIMER) {
switch( battle->get_current_skill(src) ) {
/* TODO a proper distinction should be established bugreport:8397 */
case PR_SANCTUARY:
case PR_MAGNIFICAT:
break;
default:
return -1;
}
}
if (pc_isinvisible(t_sd))
return -1; //Cannot be targeted yet.
if (sc && sc->count) {
if (sc->data[SC_SIREN] && sc->data[SC_SIREN]->val2 == target->id)
return -1;
}
}
break;
case BL_MOB:
{
const struct mob_data *md = BL_UCCAST(BL_MOB, target);
if((
(md->special_state.ai == AI_SPHERE || (md->special_state.ai == AI_FLORA && battle_config.summon_flora&1))
&& s_bl->type == BL_PC && src->type != BL_MOB
)
|| (md->special_state.ai == AI_ZANZOU && t_bl->id != s_bl->id)
) {
//Targetable by players
state |= BCT_ENEMY;
strip_enemy = 0;
}
break;
}
case BL_SKILL:
{
const struct skill_unit *su = BL_UCCAST(BL_SKILL, target);
if( !su->group )
return 0;
if( skill->get_inf2(su->group->skill_id)&INF2_TRAP &&
su->group->unit_id != UNT_USED_TRAPS &&
su->group->unit_id != UNT_NETHERWORLD ) { //Only a few skills can target traps...
switch( battle->get_current_skill(src) ) {
case RK_DRAGONBREATH:// it can only hit traps in pvp/gvg maps
case RK_DRAGONBREATH_WATER:
if( !map->list[m].flag.pvp && !map->list[m].flag.gvg )
break;
case 0://you can hit them without skills
case MA_REMOVETRAP:
case HT_REMOVETRAP:
case AC_SHOWER:
case MA_SHOWER:
case WZ_SIGHTRASHER:
case WZ_SIGHTBLASTER:
case SM_MAGNUM:
case MS_MAGNUM:
case RA_DETONATOR:
case RA_SENSITIVEKEEN:
case RK_STORMBLAST:
case SR_RAMPAGEBLASTER:
case NC_COLDSLOWER:
state |= BCT_ENEMY;
strip_enemy = 0;
break;
default:
return 0;
}
} else if (su->group->skill_id==WZ_ICEWALL ||
su->group->skill_id == GN_WALLOFTHORN) {
state |= BCT_ENEMY;
strip_enemy = 0;
} else {
//Excepting traps and icewall, you should not be able to target skills.
return 0;
}
}
break;
//Valid targets with no special checks here.
case BL_MER:
case BL_HOM:
case BL_ELEM:
break;
//All else not specified is an invalid target.
default:
return 0;
} //end switch actual target
switch( t_bl->type ) { //Checks on target master
case BL_PC:
{
const struct map_session_data *sd = BL_UCCAST(BL_PC, t_bl);
if (t_bl == s_bl)
break;
if( sd->state.monster_ignore && flag&BCT_ENEMY )
return 0; // Global immunity only to Attacks
if (sd->status.karma && s_bl->type == BL_PC && BL_UCCAST(BL_PC, s_bl)->status.karma)
state |= BCT_ENEMY; // Characters with bad karma may fight amongst them
if( sd->state.killable ) {
state |= BCT_ENEMY; // Everything can kill it
strip_enemy = 0;
}
break;
}
case BL_MOB:
{
const struct mob_data *md = BL_UCCAST(BL_MOB, t_bl);
if( !((map->agit_flag || map->agit2_flag) && map->list[m].flag.gvg_castle)
&& md->guardian_data && (md->guardian_data->g || md->guardian_data->castle->guild_id) )
return 0; // Disable guardians/emperiums owned by Guilds on non-woe times.
break;
}
default: break; //other type doesn't have slave yet
} //end switch master target
switch( src->type ) { //Checks on actual src type
case BL_PET:
if (t_bl->type != BL_MOB && flag&BCT_ENEMY)
return 0; //Pet may not attack non-mobs.
if (t_bl->type == BL_MOB && BL_UCCAST(BL_MOB, t_bl)->guardian_data && flag&BCT_ENEMY)
return 0; //pet may not attack Guardians/Emperium
break;
case BL_SKILL:
{
const struct skill_unit *su = BL_UCCAST(BL_SKILL, src);
const struct status_change *sc = status->get_sc(target);
if (su->group == NULL)
return 0;
if (su->group->src_id == target->id) {
int inf2 = skill->get_inf2(su->group->skill_id);
if (inf2&INF2_NO_TARGET_SELF)
return -1;
if (inf2&INF2_TARGET_SELF)
return 1;
}
//Status changes that prevent traps from triggering
if (sc != NULL && sc->count != 0 && skill->get_inf2(su->group->skill_id)&INF2_TRAP) {
if (sc->data[SC_WZ_SIGHTBLASTER] != NULL && sc->data[SC_WZ_SIGHTBLASTER]->val2 > 0 && sc->data[SC_WZ_SIGHTBLASTER]->val4%2 == 0)
return -1;
}
}
break;
case BL_MER:
if (t_bl->type == BL_MOB && BL_UCCAST(BL_MOB, t_bl)->class_ == MOBID_EMPELIUM && flag&BCT_ENEMY)
return 0; //mercenary may not attack Emperium
break;
} //end switch actual src
switch( s_bl->type ) { //Checks on source master
case BL_PC:
{
const struct map_session_data *sd = BL_UCCAST(BL_PC, s_bl);
if( s_bl != t_bl ) {
if( sd->state.killer ) {
state |= BCT_ENEMY; // Can kill anything
strip_enemy = 0;
} else if( sd->duel_group
&& !((!battle_config.duel_allow_pvp && map->list[m].flag.pvp) || (!battle_config.duel_allow_gvg && map_flag_gvg(m)))
) {
if (t_bl->type == BL_PC && sd->duel_group == BL_UCCAST(BL_PC, t_bl)->duel_group)
return (BCT_ENEMY&flag)?1:-1; // Duel targets can ONLY be your enemy, nothing else.
else if (src->type != BL_SKILL || (flag&BCT_ALL) != BCT_ALL)
return 0;
}
}
if (map_flag_gvg(m) && !sd->status.guild_id && t_bl->type == BL_MOB && BL_UCCAST(BL_MOB, t_bl)->class_ == MOBID_EMPELIUM)
return 0; //If you don't belong to a guild, can't target emperium.
if( t_bl->type != BL_PC )
state |= BCT_ENEMY; //Natural enemy.
break;
}
case BL_MOB:
{
const struct mob_data *md = BL_UCCAST(BL_MOB, s_bl);
if( !((map->agit_flag || map->agit2_flag) && map->list[m].flag.gvg_castle)
&& md->guardian_data && (md->guardian_data->g || md->guardian_data->castle->guild_id) )
return 0; // Disable guardians/emperium owned by Guilds on non-woe times.
if (md->special_state.ai == AI_NONE) {
//Normal mobs
const struct mob_data *target_md = BL_CCAST(BL_MOB, target);
if ((target_md != NULL && t_bl->type == BL_PC && target_md->special_state.ai != AI_ZANZOU && target_md->special_state.ai != AI_ATTACK)
|| (t_bl->type == BL_MOB && BL_UCCAST(BL_MOB, t_bl)->special_state.ai == AI_NONE))
state |= BCT_PARTY; //Normal mobs with no ai are friends.
else
state |= BCT_ENEMY; //However, all else are enemies.
} else {
if (t_bl->type == BL_MOB && BL_UCCAST(BL_MOB, t_bl)->special_state.ai == AI_NONE)
state |= BCT_ENEMY; //Natural enemy for AI mobs are normal mobs.
}
break;
}
default:
//Need some sort of default behavior for unhandled types.
if (t_bl->type != s_bl->type)
state |= BCT_ENEMY;
break;
} //end switch on src master
if( (flag&BCT_ALL) == BCT_ALL )
{ //All actually stands for all attackable chars
if( target->type&BL_CHAR )
return 1;
else
return -1;
}
if( flag == BCT_NOONE ) //Why would someone use this? no clue.
return -1;
if( t_bl == s_bl )
{ //No need for further testing.
state |= BCT_SELF|BCT_PARTY|BCT_GUILD;
if( state&BCT_ENEMY && strip_enemy )
state&=~BCT_ENEMY;
return (flag&state)?1:-1;
}
if( map_flag_vs(m) ) {
//Check rivalry settings.
int sbg_id = 0, tbg_id = 0;
if( map->list[m].flag.battleground ) {
sbg_id = bg->team_get_id(s_bl);
tbg_id = bg->team_get_id(t_bl);
}
if( flag&(BCT_PARTY|BCT_ENEMY) ) {
int s_party = status->get_party_id(s_bl);
int s_guild = status->get_guild_id(s_bl);
if( s_party && s_party == status->get_party_id(t_bl)
&& !(map->list[m].flag.pvp && map->list[m].flag.pvp_noparty)
&& !(map_flag_gvg(m) && map->list[m].flag.gvg_noparty && !( s_guild && s_guild == status->get_guild_id(t_bl) ))
&& (!map->list[m].flag.battleground || sbg_id == tbg_id) )
state |= BCT_PARTY;
else
state |= BCT_ENEMY;
}
if( flag&(BCT_GUILD|BCT_ENEMY) ) {
int s_guild = status->get_guild_id(s_bl);
int t_guild = status->get_guild_id(t_bl);
if( !(map->list[m].flag.pvp && map->list[m].flag.pvp_noguild)
&& s_guild && t_guild
&& (s_guild == t_guild || (!(flag&BCT_SAMEGUILD) && guild->isallied(s_guild, t_guild)))
&& (!map->list[m].flag.battleground || sbg_id == tbg_id) )
state |= BCT_GUILD;
else
state |= BCT_ENEMY;
}
if( state&BCT_ENEMY && map->list[m].flag.battleground && sbg_id && sbg_id == tbg_id )
state &= ~BCT_ENEMY;
if (state&BCT_ENEMY && battle_config.pk_mode && !map_flag_gvg(m) && s_bl->type == BL_PC && t_bl->type == BL_PC) {
// Prevent novice engagement on pk_mode (feature by Valaris)
const struct map_session_data *s_sd = BL_UCCAST(BL_PC, s_bl);
const struct map_session_data *t_sd = BL_UCCAST(BL_PC, t_bl);
if (
(s_sd->class_&MAPID_UPPERMASK) == MAPID_NOVICE ||
(t_sd->class_&MAPID_UPPERMASK) == MAPID_NOVICE ||
(int)s_sd->status.base_level < battle_config.pk_min_level ||
(int)t_sd->status.base_level < battle_config.pk_min_level ||
(battle_config.pk_level_range && abs((int)s_sd->status.base_level - (int)t_sd->status.base_level) > battle_config.pk_level_range)
)
state &= ~BCT_ENEMY;
}
}//end map_flag_vs chk rivality
else
{ //Non pvp/gvg, check party/guild settings.
if( flag&BCT_PARTY || state&BCT_ENEMY ) {
int s_party = status->get_party_id(s_bl);
if(s_party && s_party == status->get_party_id(t_bl))
state |= BCT_PARTY;
}
if( flag&BCT_GUILD || state&BCT_ENEMY ) {
int s_guild = status->get_guild_id(s_bl);
int t_guild = status->get_guild_id(t_bl);
if(s_guild && t_guild && (s_guild == t_guild || (!(flag&BCT_SAMEGUILD) && guild->isallied(s_guild, t_guild))))
state |= BCT_GUILD;
}
} //end non pvp/gvg chk rivality
if( !state ) //If not an enemy, nor a guild, nor party, nor yourself, it's neutral.
state = BCT_NEUTRAL;
//Alliance state takes precedence over enemy one.
else if( state&BCT_ENEMY && strip_enemy && state&(BCT_SELF|BCT_PARTY|BCT_GUILD) )
state&=~BCT_ENEMY;
return (flag&state)?1:-1;
}
/*==========================================
* Check if can attack from this range
* Basic check then calling path->search for obstacle etc..
*------------------------------------------*/
bool battle_check_range(struct block_list *src, struct block_list *bl, int range)
{
int d;
nullpo_retr(false, src);
nullpo_retr(false, bl);
if( src->m != bl->m )
return false;
#ifndef CIRCULAR_AREA
if( src->type == BL_PC ) { // Range for players' attacks and skills should always have a circular check. [Angezerus]
if ( !check_distance_client_bl(src, bl, range) )
return false;
} else
#endif
if( !check_distance_bl(src, bl, range) )
return false;
if( (d = distance_bl(src, bl)) < 2 )
return true; // No need for path checking.
if( d > AREA_SIZE )
return false; // Avoid targeting objects beyond your range of sight.
return path->search_long(NULL,src,src->m,src->x,src->y,bl->x,bl->y,CELL_CHKWALL);
}
static const struct battle_data {
const char* str;
int* val;
int defval;
int min;
int max;
} battle_data[] = {
{ "warp_point_debug", &battle_config.warp_point_debug, 0, 0, 1, },
{ "enable_critical", &battle_config.enable_critical, BL_PC, BL_NUL, BL_ALL, },
{ "mob_critical_rate", &battle_config.mob_critical_rate, 100, 0, INT_MAX, },
{ "critical_rate", &battle_config.critical_rate, 100, 0, INT_MAX, },
{ "enable_baseatk", &battle_config.enable_baseatk, BL_PC|BL_HOM, BL_NUL, BL_ALL, },
{ "enable_perfect_flee", &battle_config.enable_perfect_flee, BL_PC|BL_PET, BL_NUL, BL_ALL, },
{ "casting_rate", &battle_config.cast_rate, 100, 0, INT_MAX, },
{ "delay_rate", &battle_config.delay_rate, 100, 0, INT_MAX, },
{ "delay_dependon_dex", &battle_config.delay_dependon_dex, 0, 0, 1, },
{ "delay_dependon_agi", &battle_config.delay_dependon_agi, 0, 0, 1, },
{ "skill_delay_attack_enable", &battle_config.sdelay_attack_enable, 0, 0, 1, },
{ "left_cardfix_to_right", &battle_config.left_cardfix_to_right, 0, 0, 1, },
{ "skill_add_range", &battle_config.skill_add_range, 0, 0, INT_MAX, },
{ "skill_out_range_consume", &battle_config.skill_out_range_consume, 1, 0, 1, },
{ "skillrange_by_distance", &battle_config.skillrange_by_distance, ~BL_PC, BL_NUL, BL_ALL, },
{ "skillrange_from_weapon", &battle_config.use_weapon_skill_range, BL_NUL, BL_NUL, BL_ALL, },
{ "player_damage_delay_rate", &battle_config.pc_damage_delay_rate, 100, 0, INT_MAX, },
{ "defunit_not_enemy", &battle_config.defnotenemy, 0, 0, 1, },
{ "gvg_traps_target_all", &battle_config.vs_traps_bctall, BL_PC, BL_NUL, BL_ALL, },
{ "traps_setting", &battle_config.traps_setting, 0, 0, 1, },
{ "summon_flora_setting", &battle_config.summon_flora, 1|2, 0, 1|2, },
{ "clear_skills_on_death", &battle_config.clear_unit_ondeath, BL_NUL, BL_NUL, BL_ALL, },
{ "clear_skills_on_warp", &battle_config.clear_unit_onwarp, BL_ALL, BL_NUL, BL_ALL, },
{ "random_monster_checklv", &battle_config.random_monster_checklv, 0, 0, 1, },
{ "attribute_recover", &battle_config.attr_recover, 1, 0, 1, },
{ "flooritem_lifetime", &battle_config.flooritem_lifetime, 60000, 1000, INT_MAX, },
{ "item_auto_get", &battle_config.item_auto_get, 0, 0, 1, },
{ "item_first_get_time", &battle_config.item_first_get_time, 3000, 0, INT_MAX, },
{ "item_second_get_time", &battle_config.item_second_get_time, 1000, 0, INT_MAX, },
{ "item_third_get_time", &battle_config.item_third_get_time, 1000, 0, INT_MAX, },
{ "mvp_item_first_get_time", &battle_config.mvp_item_first_get_time, 10000, 0, INT_MAX, },
{ "mvp_item_second_get_time", &battle_config.mvp_item_second_get_time, 10000, 0, INT_MAX, },
{ "mvp_item_third_get_time", &battle_config.mvp_item_third_get_time, 2000, 0, INT_MAX, },
{ "drop_rate0item", &battle_config.drop_rate0item, 0, 0, 1, },
{ "base_exp_rate", &battle_config.base_exp_rate, 100, 0, INT_MAX, },
{ "job_exp_rate", &battle_config.job_exp_rate, 100, 0, INT_MAX, },
{ "pvp_exp", &battle_config.pvp_exp, 1, 0, 1, },
{ "death_penalty_type", &battle_config.death_penalty_type, 0, 0, 2, },
{ "death_penalty_base", &battle_config.death_penalty_base, 0, 0, INT_MAX, },
{ "death_penalty_job", &battle_config.death_penalty_job, 0, 0, INT_MAX, },
{ "zeny_penalty", &battle_config.zeny_penalty, 0, 0, INT_MAX, },
{ "hp_rate", &battle_config.hp_rate, 100, 1, INT_MAX, },
{ "sp_rate", &battle_config.sp_rate, 100, 1, INT_MAX, },
{ "restart_hp_rate", &battle_config.restart_hp_rate, 0, 0, 100, },
{ "restart_sp_rate", &battle_config.restart_sp_rate, 0, 0, 100, },
{ "guild_aura", &battle_config.guild_aura, 31, 0, 31, },
{ "mvp_hp_rate", &battle_config.mvp_hp_rate, 100, 1, INT_MAX, },
{ "mvp_exp_rate", &battle_config.mvp_exp_rate, 100, 0, INT_MAX, },
{ "monster_hp_rate", &battle_config.monster_hp_rate, 100, 1, INT_MAX, },
{ "monster_max_aspd", &battle_config.monster_max_aspd, 199, 100, 199, },
{ "view_range_rate", &battle_config.view_range_rate, 100, 0, INT_MAX, },
{ "chase_range_rate", &battle_config.chase_range_rate, 100, 0, INT_MAX, },
{ "gtb_sc_immunity", &battle_config.gtb_sc_immunity, 50, 0, INT_MAX, },
{ "guild_max_castles", &battle_config.guild_max_castles, 0, 0, INT_MAX, },
{ "guild_skill_relog_delay", &battle_config.guild_skill_relog_delay, 0, 0, 1, },
{ "emergency_call", &battle_config.emergency_call, 11, 0, 31, },
{ "atcommand_spawn_quantity_limit", &battle_config.atc_spawn_quantity_limit, 100, 0, INT_MAX, },
{ "atcommand_slave_clone_limit", &battle_config.atc_slave_clone_limit, 25, 0, INT_MAX, },
{ "partial_name_scan", &battle_config.partial_name_scan, 0, 0, 1, },
{ "player_skillfree", &battle_config.skillfree, 0, 0, 1, },
{ "player_skillup_limit", &battle_config.skillup_limit, 1, 0, 1, },
{ "weapon_produce_rate", &battle_config.wp_rate, 100, 0, INT_MAX, },
{ "potion_produce_rate", &battle_config.pp_rate, 100, 0, INT_MAX, },
{ "monster_active_enable", &battle_config.monster_active_enable, 1, 0, 1, },
{ "monster_damage_delay_rate", &battle_config.monster_damage_delay_rate, 100, 0, INT_MAX, },
{ "monster_loot_type", &battle_config.monster_loot_type, 0, 0, 1, },
//{ "mob_skill_use", &battle_config.mob_skill_use, 1, 0, 1, }, //Deprecated
{ "mob_skill_rate", &battle_config.mob_skill_rate, 100, 0, INT_MAX, },
{ "mob_skill_delay", &battle_config.mob_skill_delay, 100, 0, INT_MAX, },
{ "mob_count_rate", &battle_config.mob_count_rate, 100, 0, INT_MAX, },
{ "mob_spawn_delay", &battle_config.mob_spawn_delay, 100, 0, INT_MAX, },
{ "plant_spawn_delay", &battle_config.plant_spawn_delay, 100, 0, INT_MAX, },
{ "boss_spawn_delay", &battle_config.boss_spawn_delay, 100, 0, INT_MAX, },
{ "no_spawn_on_player", &battle_config.no_spawn_on_player, 0, 0, 100, },
{ "force_random_spawn", &battle_config.force_random_spawn, 0, 0, 1, },
{ "slaves_inherit_mode", &battle_config.slaves_inherit_mode, 2, 0, 3, },
{ "slaves_inherit_speed", &battle_config.slaves_inherit_speed, 3, 0, 3, },
{ "summons_trigger_autospells", &battle_config.summons_trigger_autospells, 1, 0, 1, },
{ "pc_damage_walk_delay_rate", &battle_config.pc_walk_delay_rate, 20, 0, INT_MAX, },
{ "damage_walk_delay_rate", &battle_config.walk_delay_rate, 100, 0, INT_MAX, },
{ "multihit_delay", &battle_config.multihit_delay, 80, 0, INT_MAX, },
{ "quest_skill_learn", &battle_config.quest_skill_learn, 0, 0, 1, },
{ "quest_skill_reset", &battle_config.quest_skill_reset, 0, 0, 1, },
{ "basic_skill_check", &battle_config.basic_skill_check, 1, 0, 1, },
{ "guild_emperium_check", &battle_config.guild_emperium_check, 1, 0, 1, },
{ "guild_exp_limit", &battle_config.guild_exp_limit, 50, 0, 99, },
{ "player_invincible_time", &battle_config.pc_invincible_time, 5000, 0, INT_MAX, },
{ "pet_catch_rate", &battle_config.pet_catch_rate, 100, 0, INT_MAX, },
{ "pet_rename", &battle_config.pet_rename, 0, 0, 1, },
{ "pet_friendly_rate", &battle_config.pet_friendly_rate, 100, 0, INT_MAX, },
{ "pet_hungry_delay_rate", &battle_config.pet_hungry_delay_rate, 100, 10, INT_MAX, },
{ "pet_hungry_friendly_decrease", &battle_config.pet_hungry_friendly_decrease, 5, 0, INT_MAX, },
{ "pet_status_support", &battle_config.pet_status_support, 0, 0, 1, },
{ "pet_attack_support", &battle_config.pet_attack_support, 0, 0, 1, },
{ "pet_damage_support", &battle_config.pet_damage_support, 0, 0, 1, },
{ "pet_support_min_friendly", &battle_config.pet_support_min_friendly, 900, 0, 950, },
{ "pet_equip_min_friendly", &battle_config.pet_equip_min_friendly, 900, 0, 950, },
{ "pet_support_rate", &battle_config.pet_support_rate, 100, 0, INT_MAX, },
{ "pet_attack_exp_to_master", &battle_config.pet_attack_exp_to_master, 0, 0, 1, },
{ "pet_attack_exp_rate", &battle_config.pet_attack_exp_rate, 100, 0, INT_MAX, },
{ "pet_lv_rate", &battle_config.pet_lv_rate, 0, 0, INT_MAX, },
{ "pet_max_stats", &battle_config.pet_max_stats, 99, 0, INT_MAX, },
{ "pet_max_atk1", &battle_config.pet_max_atk1, 750, 0, INT_MAX, },
{ "pet_max_atk2", &battle_config.pet_max_atk2, 1000, 0, INT_MAX, },
{ "pet_disable_in_gvg", &battle_config.pet_no_gvg, 0, 0, 1, },
{ "skill_min_damage", &battle_config.skill_min_damage, 2|4, 0, 1|2|4, },
{ "finger_offensive_type", &battle_config.finger_offensive_type, 0, 0, 1, },
{ "heal_exp", &battle_config.heal_exp, 0, 0, INT_MAX, },
{ "resurrection_exp", &battle_config.resurrection_exp, 0, 0, INT_MAX, },
{ "shop_exp", &battle_config.shop_exp, 0, 0, INT_MAX, },
{ "max_heal_lv", &battle_config.max_heal_lv, 11, 1, INT_MAX, },
{ "max_heal", &battle_config.max_heal, 9999, 0, INT_MAX, },
{ "combo_delay_rate", &battle_config.combo_delay_rate, 100, 0, INT_MAX, },
{ "item_check", &battle_config.item_check, 0, 0, 1, },
{ "item_use_interval", &battle_config.item_use_interval, 100, 0, INT_MAX, },
{ "cashfood_use_interval", &battle_config.cashfood_use_interval, 60000, 0, INT_MAX, },
{ "wedding_modifydisplay", &battle_config.wedding_modifydisplay, 0, 0, 1, },
{ "wedding_ignorepalette", &battle_config.wedding_ignorepalette, 0, 0, 1, },
{ "xmas_ignorepalette", &battle_config.xmas_ignorepalette, 0, 0, 1, },
{ "summer_ignorepalette", &battle_config.summer_ignorepalette, 0, 0, 1, },
{ "hanbok_ignorepalette", &battle_config.hanbok_ignorepalette, 0, 0, 1, },
{ "natural_healhp_interval", &battle_config.natural_healhp_interval, 6000, NATURAL_HEAL_INTERVAL, INT_MAX, },
{ "natural_healsp_interval", &battle_config.natural_healsp_interval, 8000, NATURAL_HEAL_INTERVAL, INT_MAX, },
{ "natural_heal_skill_interval", &battle_config.natural_heal_skill_interval, 10000, NATURAL_HEAL_INTERVAL, INT_MAX, },
{ "natural_heal_weight_rate", &battle_config.natural_heal_weight_rate, 50, 50, 101 },
{ "arrow_decrement", &battle_config.arrow_decrement, 1, 0, 2, },
{ "max_aspd", &battle_config.max_aspd, 190, 100, 199, },
{ "max_walk_speed", &battle_config.max_walk_speed, 300, 100, 100*DEFAULT_WALK_SPEED, },
{ "max_lv", &battle_config.max_lv, 99, 0, MAX_LEVEL, },
{ "aura_lv", &battle_config.aura_lv, 99, 0, INT_MAX, },
{ "max_hp", &battle_config.max_hp, 1000000, 100, 21474836, },
{ "max_sp", &battle_config.max_sp, 1000000, 100, 21474836, },
{ "max_cart_weight", &battle_config.max_cart_weight, 8000, 100, 1000000, },
{ "max_parameter", &battle_config.max_parameter, 99, 10, 10000, },
{ "max_baby_parameter", &battle_config.max_baby_parameter, 80, 10, 10000, },
{ "max_def", &battle_config.max_def, 99, 0, INT_MAX, },
{ "over_def_bonus", &battle_config.over_def_bonus, 0, 0, 1000, },
{ "skill_log", &battle_config.skill_log, BL_NUL, BL_NUL, BL_ALL, },
{ "battle_log", &battle_config.battle_log, 0, 0, 1, },
{ "etc_log", &battle_config.etc_log, 1, 0, 1, },
{ "save_clothcolor", &battle_config.save_clothcolor, 1, 0, 1, },
{ "undead_detect_type", &battle_config.undead_detect_type, 0, 0, 2, },
{ "auto_counter_type", &battle_config.auto_counter_type, BL_ALL, BL_NUL, BL_ALL, },
{ "min_hitrate", &battle_config.min_hitrate, 5, 0, 100, },
{ "max_hitrate", &battle_config.max_hitrate, 100, 0, 100, },
{ "agi_penalty_target", &battle_config.agi_penalty_target, BL_PC, BL_NUL, BL_ALL, },
{ "agi_penalty_type", &battle_config.agi_penalty_type, 1, 0, 2, },
{ "agi_penalty_count", &battle_config.agi_penalty_count, 3, 2, INT_MAX, },
{ "agi_penalty_num", &battle_config.agi_penalty_num, 10, 0, INT_MAX, },
{ "vit_penalty_target", &battle_config.vit_penalty_target, BL_PC, BL_NUL, BL_ALL, },
{ "vit_penalty_type", &battle_config.vit_penalty_type, 1, 0, 2, },
{ "vit_penalty_count", &battle_config.vit_penalty_count, 3, 2, INT_MAX, },
{ "vit_penalty_num", &battle_config.vit_penalty_num, 5, 0, INT_MAX, },
{ "weapon_defense_type", &battle_config.weapon_defense_type, 0, 0, INT_MAX, },
{ "magic_defense_type", &battle_config.magic_defense_type, 0, 0, INT_MAX, },
{ "skill_reiteration", &battle_config.skill_reiteration, BL_NUL, BL_NUL, BL_ALL, },
{ "skill_nofootset", &battle_config.skill_nofootset, BL_PC, BL_NUL, BL_ALL, },
{ "player_cloak_check_type", &battle_config.pc_cloak_check_type, 1, 0, 1|2|4, },
{ "monster_cloak_check_type", &battle_config.monster_cloak_check_type, 4, 0, 1|2|4, },
{ "sense_type", &battle_config.estimation_type, 1|2, 0, 1|2, },
{ "gvg_flee_penalty", &battle_config.gvg_flee_penalty, 20, 0, INT_MAX, },
{ "mob_changetarget_byskill", &battle_config.mob_changetarget_byskill, 0, 0, 1, },
{ "attack_direction_change", &battle_config.attack_direction_change, BL_ALL, BL_NUL, BL_ALL, },
{ "land_skill_limit", &battle_config.land_skill_limit, BL_ALL, BL_NUL, BL_ALL, },
{ "monster_class_change_full_recover", &battle_config.monster_class_change_recover, 1, 0, 1, },
{ "produce_item_name_input", &battle_config.produce_item_name_input, 0x1|0x2, 0, 0x9F, },
{ "display_skill_fail", &battle_config.display_skill_fail, 2, 0, 1|2|4|8, },
{ "chat_warpportal", &battle_config.chat_warpportal, 0, 0, 1, },
{ "mob_warp", &battle_config.mob_warp, 0, 0, 1|2|4, },
{ "dead_branch_active", &battle_config.dead_branch_active, 1, 0, 1, },
{ "vending_max_value", &battle_config.vending_max_value, 10000000, 1, MAX_ZENY, },
{ "vending_over_max", &battle_config.vending_over_max, 1, 0, 1, },
{ "show_steal_in_same_party", &battle_config.show_steal_in_same_party, 0, 0, 1, },
{ "party_hp_mode", &battle_config.party_hp_mode, 0, 0, 1, },
{ "show_party_share_picker", &battle_config.party_show_share_picker, 1, 0, 1, },
{ "show_picker.item_type", &battle_config.show_picker_item_type, 112, 0, INT_MAX, },
{ "party_update_interval", &battle_config.party_update_interval, 1000, 100, INT_MAX, },
{ "party_item_share_type", &battle_config.party_share_type, 0, 0, 1|2|3, },
{ "attack_attr_none", &battle_config.attack_attr_none, ~BL_PC, BL_NUL, BL_ALL, },
{ "gx_allhit", &battle_config.gx_allhit, 0, 0, 1, },
{ "gx_disptype", &battle_config.gx_disptype, 1, 0, 1, },
{ "devotion_level_difference", &battle_config.devotion_level_difference, 10, 0, INT_MAX, },
{ "player_skill_partner_check", &battle_config.player_skill_partner_check, 1, 0, 1, },
{ "invite_request_check", &battle_config.invite_request_check, 1, 0, 1, },
{ "skill_removetrap_type", &battle_config.skill_removetrap_type, 0, 0, 1, },
{ "disp_experience", &battle_config.disp_experience, 0, 0, 1, },
{ "disp_zeny", &battle_config.disp_zeny, 0, 0, 1, },
{ "castle_defense_rate", &battle_config.castle_defense_rate, 100, 0, 100, },
{ "bone_drop", &battle_config.bone_drop, 0, 0, 2, },
{ "buyer_name", &battle_config.buyer_name, 1, 0, 1, },
{ "skill_wall_check", &battle_config.skill_wall_check, 1, 0, 1, },
{ "official_cell_stack_limit", &battle_config.official_cell_stack_limit, 1, 0, 255, },
{ "custom_cell_stack_limit", &battle_config.custom_cell_stack_limit, 1, 1, 255, },
{ "dancing_weaponswitch_fix", &battle_config.dancing_weaponswitch_fix, 1, 0, 1, },
{ "check_occupied_cells", &battle_config.check_occupied_cells, 1, 0, 1, },
// eAthena additions
{ "item_logarithmic_drops", &battle_config.logarithmic_drops, 0, 0, 1, },
{ "item_drop_common_min", &battle_config.item_drop_common_min, 1, 1, 10000, },
{ "item_drop_common_max", &battle_config.item_drop_common_max, 10000, 1, 10000, },
{ "item_drop_equip_min", &battle_config.item_drop_equip_min, 1, 1, 10000, },
{ "item_drop_equip_max", &battle_config.item_drop_equip_max, 10000, 1, 10000, },
{ "item_drop_card_min", &battle_config.item_drop_card_min, 1, 1, 10000, },
{ "item_drop_card_max", &battle_config.item_drop_card_max, 10000, 1, 10000, },
{ "item_drop_mvp_min", &battle_config.item_drop_mvp_min, 1, 1, 10000, },
{ "item_drop_mvp_max", &battle_config.item_drop_mvp_max, 10000, 1, 10000, },
{ "item_drop_heal_min", &battle_config.item_drop_heal_min, 1, 1, 10000, },
{ "item_drop_heal_max", &battle_config.item_drop_heal_max, 10000, 1, 10000, },
{ "item_drop_use_min", &battle_config.item_drop_use_min, 1, 1, 10000, },
{ "item_drop_use_max", &battle_config.item_drop_use_max, 10000, 1, 10000, },
{ "item_drop_add_min", &battle_config.item_drop_adddrop_min, 1, 1, 10000, },
{ "item_drop_add_max", &battle_config.item_drop_adddrop_max, 10000, 1, 10000, },
{ "item_drop_treasure_min", &battle_config.item_drop_treasure_min, 1, 1, 10000, },
{ "item_drop_treasure_max", &battle_config.item_drop_treasure_max, 10000, 1, 10000, },
{ "item_rate_mvp", &battle_config.item_rate_mvp, 100, 0, 1000000, },
{ "item_rate_common", &battle_config.item_rate_common, 100, 0, 1000000, },
{ "item_rate_common_boss", &battle_config.item_rate_common_boss, 100, 0, 1000000, },
{ "item_rate_equip", &battle_config.item_rate_equip, 100, 0, 1000000, },
{ "item_rate_equip_boss", &battle_config.item_rate_equip_boss, 100, 0, 1000000, },
{ "item_rate_card", &battle_config.item_rate_card, 100, 0, 1000000, },
{ "item_rate_card_boss", &battle_config.item_rate_card_boss, 100, 0, 1000000, },
{ "item_rate_heal", &battle_config.item_rate_heal, 100, 0, 1000000, },
{ "item_rate_heal_boss", &battle_config.item_rate_heal_boss, 100, 0, 1000000, },
{ "item_rate_use", &battle_config.item_rate_use, 100, 0, 1000000, },
{ "item_rate_use_boss", &battle_config.item_rate_use_boss, 100, 0, 1000000, },
{ "item_rate_adddrop", &battle_config.item_rate_adddrop, 100, 0, 1000000, },
{ "item_rate_treasure", &battle_config.item_rate_treasure, 100, 0, 1000000, },
{ "prevent_logout", &battle_config.prevent_logout, 10000, 0, 60000, },
{ "alchemist_summon_reward", &battle_config.alchemist_summon_reward, 1, 0, 2, },
{ "drops_by_luk", &battle_config.drops_by_luk, 0, 0, INT_MAX, },
{ "drops_by_luk2", &battle_config.drops_by_luk2, 0, 0, INT_MAX, },
{ "equip_natural_break_rate", &battle_config.equip_natural_break_rate, 0, 0, INT_MAX, },
{ "equip_self_break_rate", &battle_config.equip_self_break_rate, 100, 0, INT_MAX, },
{ "equip_skill_break_rate", &battle_config.equip_skill_break_rate, 100, 0, INT_MAX, },
{ "pk_mode", &battle_config.pk_mode, 0, 0, 2, },
{ "pk_level_range", &battle_config.pk_level_range, 0, 0, INT_MAX, },
{ "manner_system", &battle_config.manner_system, 0xFFF, 0, 0xFFF, },
{ "pet_equip_required", &battle_config.pet_equip_required, 0, 0, 1, },
{ "multi_level_up", &battle_config.multi_level_up, 0, 0, 1, },
{ "max_exp_gain_rate", &battle_config.max_exp_gain_rate, 0, 0, INT_MAX, },
{ "backstab_bow_penalty", &battle_config.backstab_bow_penalty, 0, 0, 1, },
{ "night_at_start", &battle_config.night_at_start, 0, 0, 1, },
{ "show_mob_info", &battle_config.show_mob_info, 0, 0, 1|2|4, },
{ "ban_hack_trade", &battle_config.ban_hack_trade, 0, 0, INT_MAX, },
{ "min_hair_style", &battle_config.min_hair_style, 0, 0, INT_MAX, },
{ "max_hair_style", &battle_config.max_hair_style, 23, 0, INT_MAX, },
{ "min_hair_color", &battle_config.min_hair_color, 0, 0, INT_MAX, },
{ "max_hair_color", &battle_config.max_hair_color, 9, 0, INT_MAX, },
{ "min_cloth_color", &battle_config.min_cloth_color, 0, 0, INT_MAX, },
{ "max_cloth_color", &battle_config.max_cloth_color, 4, 0, INT_MAX, },
{ "pet_hair_style", &battle_config.pet_hair_style, 100, 0, INT_MAX, },
{ "castrate_dex_scale", &battle_config.castrate_dex_scale, 150, 1, INT_MAX, },
{ "vcast_stat_scale", &battle_config.vcast_stat_scale, 530, 1, INT_MAX, },
{ "area_size", &battle_config.area_size, 14, 0, INT_MAX, },
{ "zeny_from_mobs", &battle_config.zeny_from_mobs, 0, 0, 1, },
{ "mobs_level_up", &battle_config.mobs_level_up, 0, 0, 1, },
{ "mobs_level_up_exp_rate", &battle_config.mobs_level_up_exp_rate, 1, 1, INT_MAX, },
{ "pk_min_level", &battle_config.pk_min_level, 55, 1, INT_MAX, },
{ "skill_steal_max_tries", &battle_config.skill_steal_max_tries, 0, 0, UCHAR_MAX, },
{ "exp_calc_type", &battle_config.exp_calc_type, 0, 0, 1, },
{ "exp_bonus_attacker", &battle_config.exp_bonus_attacker, 25, 0, INT_MAX, },
{ "exp_bonus_max_attacker", &battle_config.exp_bonus_max_attacker, 12, 2, INT_MAX, },
{ "min_skill_delay_limit", &battle_config.min_skill_delay_limit, 100, 10, INT_MAX, },
{ "default_walk_delay", &battle_config.default_walk_delay, 300, 0, INT_MAX, },
{ "no_skill_delay", &battle_config.no_skill_delay, BL_MOB, BL_NUL, BL_ALL, },
{ "attack_walk_delay", &battle_config.attack_walk_delay, BL_ALL, BL_NUL, BL_ALL, },
{ "require_glory_guild", &battle_config.require_glory_guild, 0, 0, 1, },
{ "idle_no_share", &battle_config.idle_no_share, 0, 0, INT_MAX, },
{ "party_even_share_bonus", &battle_config.party_even_share_bonus, 0, 0, INT_MAX, },
{ "delay_battle_damage", &battle_config.delay_battle_damage, 1, 0, 1, },
{ "hide_woe_damage", &battle_config.hide_woe_damage, 0, 0, 1, },
{ "display_version", &battle_config.display_version, 1, 0, 1, },
{ "display_hallucination", &battle_config.display_hallucination, 1, 0, 1, },
{ "use_statpoint_table", &battle_config.use_statpoint_table, 1, 0, 1, },
{ "ignore_items_gender", &battle_config.ignore_items_gender, 1, 0, 1, },
{ "copyskill_restrict", &battle_config.copyskill_restrict, 2, 0, 2, },
{ "berserk_cancels_buffs", &battle_config.berserk_cancels_buffs, 0, 0, 1, },
{ "monster_ai", &battle_config.mob_ai, 0x000, 0x000, 0x77F, },
{ "hom_setting", &battle_config.hom_setting, 0xFFFF, 0x0000, 0xFFFF, },
{ "dynamic_mobs", &battle_config.dynamic_mobs, 1, 0, 1, },
{ "mob_remove_damaged", &battle_config.mob_remove_damaged, 1, 0, 1, },
{ "show_hp_sp_drain", &battle_config.show_hp_sp_drain, 0, 0, 1, },
{ "show_hp_sp_gain", &battle_config.show_hp_sp_gain, 1, 0, 1, },
{ "show_katar_crit_bonus", &battle_config.show_katar_crit_bonus, 0, 0, 1, },
{ "mob_npc_event_type", &battle_config.mob_npc_event_type, 1, 0, 1, },
{ "character_size", &battle_config.character_size, 1|2, 0, 1|2, },
{ "retaliate_to_master", &battle_config.retaliate_to_master, 1, 0, 1, },
{ "rare_drop_announce", &battle_config.rare_drop_announce, 0, 0, 10000, },
{ "duel_allow_pvp", &battle_config.duel_allow_pvp, 0, 0, 1, },
{ "duel_allow_gvg", &battle_config.duel_allow_gvg, 0, 0, 1, },
{ "duel_allow_teleport", &battle_config.duel_allow_teleport, 0, 0, 1, },
{ "duel_autoleave_when_die", &battle_config.duel_autoleave_when_die, 1, 0, 1, },
{ "duel_time_interval", &battle_config.duel_time_interval, 60, 0, INT_MAX, },
{ "duel_only_on_same_map", &battle_config.duel_only_on_same_map, 0, 0, 1, },
{ "skip_teleport_lv1_menu", &battle_config.skip_teleport_lv1_menu, 0, 0, 1, },
{ "mob_max_skilllvl", &battle_config.mob_max_skilllvl, 100, 1, INT_MAX, },
{ "allow_skill_without_day", &battle_config.allow_skill_without_day, 0, 0, 1, },
{ "allow_es_magic_player", &battle_config.allow_es_magic_pc, 0, 0, 1, },
{ "skill_caster_check", &battle_config.skill_caster_check, 1, 0, 1, },
{ "status_cast_cancel", &battle_config.sc_castcancel, BL_NUL, BL_NUL, BL_ALL, },
{ "pc_status_def_rate", &battle_config.pc_sc_def_rate, 100, 0, INT_MAX, },
{ "mob_status_def_rate", &battle_config.mob_sc_def_rate, 100, 0, INT_MAX, },
{ "pc_max_status_def", &battle_config.pc_max_sc_def, 100, 0, INT_MAX, },
{ "mob_max_status_def", &battle_config.mob_max_sc_def, 100, 0, INT_MAX, },
{ "sg_miracle_skill_ratio", &battle_config.sg_miracle_skill_ratio, 1, 0, 10000, },
{ "sg_angel_skill_ratio", &battle_config.sg_angel_skill_ratio, 10, 0, 10000, },
{ "autospell_stacking", &battle_config.autospell_stacking, 0, 0, 1, },
{ "override_mob_names", &battle_config.override_mob_names, 0, 0, 2, },
{ "min_chat_delay", &battle_config.min_chat_delay, 0, 0, INT_MAX, },
{ "friend_auto_add", &battle_config.friend_auto_add, 1, 0, 1, },
{ "hom_rename", &battle_config.hom_rename, 0, 0, 1, },
{ "homunculus_show_growth", &battle_config.homunculus_show_growth, 0, 0, 1, },
{ "homunculus_friendly_rate", &battle_config.homunculus_friendly_rate, 100, 0, INT_MAX, },
{ "vending_tax", &battle_config.vending_tax, 0, 0, 10000, },
{ "day_duration", &battle_config.day_duration, 0, 0, INT_MAX, },
{ "night_duration", &battle_config.night_duration, 0, 0, INT_MAX, },
{ "mob_remove_delay", &battle_config.mob_remove_delay, 60000, 1000, INT_MAX, },
{ "mob_active_time", &battle_config.mob_active_time, 0, 0, INT_MAX, },
{ "boss_active_time", &battle_config.boss_active_time, 0, 0, INT_MAX, },
{ "sg_miracle_skill_duration", &battle_config.sg_miracle_skill_duration, 3600000, 0, INT_MAX, },
{ "hvan_explosion_intimate", &battle_config.hvan_explosion_intimate, 45000, 0, 100000, },
{ "quest_exp_rate", &battle_config.quest_exp_rate, 100, 0, INT_MAX, },
{ "at_mapflag", &battle_config.autotrade_mapflag, 0, 0, 1, },
{ "at_timeout", &battle_config.at_timeout, 0, 0, INT_MAX, },
{ "homunculus_autoloot", &battle_config.homunculus_autoloot, 0, 0, 1, },
{ "idle_no_autoloot", &battle_config.idle_no_autoloot, 0, 0, INT_MAX, },
{ "max_guild_alliance", &battle_config.max_guild_alliance, 3, 0, 3, },
{ "ksprotection", &battle_config.ksprotection, 5000, 0, INT_MAX, },
{ "auction_feeperhour", &battle_config.auction_feeperhour, 12000, 0, INT_MAX, },
{ "auction_maximumprice", &battle_config.auction_maximumprice, 500000000, 0, MAX_ZENY, },
{ "homunculus_auto_vapor", &battle_config.homunculus_auto_vapor, 1, 0, 1, },
{ "display_status_timers", &battle_config.display_status_timers, 1, 0, 1, },
{ "skill_add_heal_rate", &battle_config.skill_add_heal_rate, 7, 0, INT_MAX, },
{ "eq_single_target_reflectable", &battle_config.eq_single_target_reflectable, 1, 0, 1, },
{ "invincible.nodamage", &battle_config.invincible_nodamage, 0, 0, 1, },
{ "mob_slave_keep_target", &battle_config.mob_slave_keep_target, 0, 0, 1, },
{ "autospell_check_range", &battle_config.autospell_check_range, 0, 0, 1, },
{ "knockback_left", &battle_config.knockback_left, 1, 0, 1, },
{ "client_reshuffle_dice", &battle_config.client_reshuffle_dice, 0, 0, 1, },
{ "client_sort_storage", &battle_config.client_sort_storage, 0, 0, 1, },
{ "feature.buying_store", &battle_config.feature_buying_store, 1, 0, 1, },
{ "feature.search_stores", &battle_config.feature_search_stores, 1, 0, 1, },
{ "searchstore_querydelay", &battle_config.searchstore_querydelay, 10, 0, INT_MAX, },
{ "searchstore_maxresults", &battle_config.searchstore_maxresults, 30, 1, INT_MAX, },
{ "display_party_name", &battle_config.display_party_name, 0, 0, 1, },
{ "cashshop_show_points", &battle_config.cashshop_show_points, 0, 0, 1, },
{ "mail_show_status", &battle_config.mail_show_status, 0, 0, 2, },
{ "client_limit_unit_lv", &battle_config.client_limit_unit_lv, 0, 0, BL_ALL, },
{ "client_emblem_max_blank_percent", &battle_config.client_emblem_max_blank_percent, 100, 0, 100, },
// BattleGround Settings
{ "bg_update_interval", &battle_config.bg_update_interval, 1000, 100, INT_MAX, },
{ "bg_flee_penalty", &battle_config.bg_flee_penalty, 20, 0, INT_MAX, },
/**
* rAthena
**/
{ "atcommand_max_stat_bypass", &battle_config.atcommand_max_stat_bypass, 0, 0, 100, },
{ "skill_amotion_leniency", &battle_config.skill_amotion_leniency, 90, 0, 300 },
{ "mvp_tomb_enabled", &battle_config.mvp_tomb_enabled, 1, 0, 1 },
{ "feature.atcommand_suggestions", &battle_config.atcommand_suggestions_enabled, 0, 0, 1 },
{ "min_npc_vendchat_distance", &battle_config.min_npc_vendchat_distance, 3, 0, 100 },
{ "vendchat_near_hiddennpc", &battle_config.vendchat_near_hiddennpc, 0, 0, 1 },
{ "atcommand_mobinfo_type", &battle_config.atcommand_mobinfo_type, 0, 0, 1 },
{ "homunculus_max_level", &battle_config.hom_max_level, 99, 0, MAX_LEVEL, },
{ "mob_size_influence", &battle_config.mob_size_influence, 0, 0, 1, },
{ "bowling_bash_area", &battle_config.bowling_bash_area, 0, 0, 20, },
/**
* Hercules
**/
{ "skill_trap_type", &battle_config.skill_trap_type, 0, 0, 1, },
{ "item_restricted_consumption_type", &battle_config.item_restricted_consumption_type,1, 0, 1, },
{ "unequip_restricted_equipment", &battle_config.unequip_restricted_equipment, 0, 0, 3, },
{ "max_walk_path", &battle_config.max_walk_path, 17, 1, MAX_WALKPATH, },
{ "item_enabled_npc", &battle_config.item_enabled_npc, 1, 0, 1, },
{ "gm_ignore_warpable_area", &battle_config.gm_ignore_warpable_area, 0, 2, 100, },
{ "packet_obfuscation", &battle_config.packet_obfuscation, 1, 0, 3, },
{ "client_accept_chatdori", &battle_config.client_accept_chatdori, 0, 0, INT_MAX, },
{ "snovice_call_type", &battle_config.snovice_call_type, 0, 0, 1, },
{ "guild_notice_changemap", &battle_config.guild_notice_changemap, 2, 0, 2, },
{ "feature.banking", &battle_config.feature_banking, 1, 0, 1, },
{ "feature.auction", &battle_config.feature_auction, 0, 0, 2, },
{ "idletime_criteria", &battle_config.idletime_criteria, 0x25, 1, INT_MAX, },
{ "mon_trans_disable_in_gvg", &battle_config.mon_trans_disable_in_gvg, 0, 0, 1, },
{ "case_sensitive_aegisnames", &battle_config.case_sensitive_aegisnames, 1, 0, 1, },
{ "guild_castle_invite", &battle_config.guild_castle_invite, 0, 0, 1, },
{ "guild_castle_expulsion", &battle_config.guild_castle_expulsion, 0, 0, 1, },
{ "song_timer_reset", &battle_config.song_timer_reset, 0, 0, 1, },
{ "snap_dodge", &battle_config.snap_dodge, 0, 0, 1, },
{ "stormgust_knockback", &battle_config.stormgust_knockback, 1, 0, 1, },
{ "monster_chase_refresh", &battle_config.mob_chase_refresh, 1, 0, 30, },
{ "mob_icewall_walk_block", &battle_config.mob_icewall_walk_block, 75, 0, 255, },
{ "boss_icewall_walk_block", &battle_config.boss_icewall_walk_block, 0, 0, 255, },
{ "feature.roulette", &battle_config.feature_roulette, 1, 0, 1, },
{ "show_monster_hp_bar", &battle_config.show_monster_hp_bar, 1, 0, 1, },
{ "fix_warp_hit_delay_abuse", &battle_config.fix_warp_hit_delay_abuse, 0, 0, 1, },
{ "costume_refine_def", &battle_config.costume_refine_def, 1, 0, 1, },
{ "shadow_refine_def", &battle_config.shadow_refine_def, 1, 0, 1, },
{ "shadow_refine_atk", &battle_config.shadow_refine_atk, 1, 0, 1, },
{ "min_body_style", &battle_config.min_body_style, 0, 0, SHRT_MAX, },
{ "max_body_style", &battle_config.max_body_style, 4, 0, SHRT_MAX, },
{ "save_body_style", &battle_config.save_body_style, 0, 0, 1, },
};
#ifndef STATS_OPT_OUT
/**
* Hercules anonymous statistic usage report -- packet is built here, and sent to char server to report.
**/
void Hercules_report(char* date, char *time_c) {
int i, bd_size = ARRAYLENGTH(battle_data);
unsigned int config = 0;
char timestring[25];
time_t curtime;
char* buf;
enum config_table {
C_CIRCULAR_AREA = 0x0001,
C_CELLNOSTACK = 0x0002,
C_CONSOLE_INPUT = 0x0004,
C_SCRIPT_CALLFUNC_CHECK = 0x0008,
C_OFFICIAL_WALKPATH = 0x0010,
C_SECURE_NPCTIMEOUT = 0x1000,
//C_SQL_DB_ITEM = 0x2000,
C_SQL_LOGS = 0x4000,
C_MEMWATCH = 0x8000,
C_DMALLOC = 0x10000,
C_GCOLLECT = 0x20000,
C_SEND_SHORTLIST = 0x40000,
//C_SQL_DB_MOB = 0x80000,
//C_SQL_DB_MOBSKILL = 0x100000,
C_PACKETVER_RE = 0x200000,
};
/* we get the current time */
time(&curtime);
strftime(timestring, 24, "%Y-%m-%d %H:%M:%S", localtime(&curtime));
#ifdef CIRCULAR_AREA
config |= C_CIRCULAR_AREA;
#endif
#ifdef CELL_NOSTACK
config |= C_CELLNOSTACK;
#endif
#ifdef CONSOLE_INPUT
config |= C_CONSOLE_INPUT;
#endif
#ifdef SCRIPT_CALLFUNC_CHECK
config |= C_SCRIPT_CALLFUNC_CHECK;
#endif
#ifdef OFFICIAL_WALKPATH
config |= C_OFFICIAL_WALKPATH;
#endif
#ifdef SECURE_NPCTIMEOUT
config |= C_SECURE_NPCTIMEOUT;
#endif
#ifdef PACKETVER_RE
config |= C_PACKETVER_RE;
#endif
/* non-define part */
if( logs->config.sql_logs )
config |= C_SQL_LOGS;
#ifdef MEMWATCH
config |= C_MEMWATCH;
#endif
#ifdef DMALLOC
config |= C_DMALLOC;
#endif
#ifdef GCOLLECT
config |= C_GCOLLECT;
#endif
#ifdef SEND_SHORTLIST
config |= C_SEND_SHORTLIST;
#endif
#define BFLAG_LENGTH 35
CREATE(buf, char, 262 + ( bd_size * ( BFLAG_LENGTH + 4 ) ) + 1 );
/* build packet */
WBUFW(buf,0) = 0x3000;
WBUFW(buf,2) = 262 + ( bd_size * ( BFLAG_LENGTH + 4 ) );
WBUFW(buf,4) = 0x9f;
safestrncpy(WBUFP(buf,6), date, 12);
safestrncpy(WBUFP(buf,18), time_c, 9);
safestrncpy(WBUFP(buf,27), timestring, 24);
safestrncpy(WBUFP(buf,51), sysinfo->platform(), 16);
safestrncpy(WBUFP(buf,67), sysinfo->osversion(), 50);
safestrncpy(WBUFP(buf,117), sysinfo->cpu(), 32);
WBUFL(buf,149) = sysinfo->cpucores();
safestrncpy(WBUFP(buf,153), sysinfo->arch(), 8);
WBUFB(buf,161) = sysinfo->vcstypeid();
WBUFB(buf,162) = sysinfo->is64bit();
safestrncpy(WBUFP(buf,163), sysinfo->vcsrevision_src(), 41);
safestrncpy(WBUFP(buf,204), sysinfo->vcsrevision_scripts(), 41);
WBUFB(buf,245) = (sysinfo->is_superuser()? 1 : 0);
WBUFL(buf,246) = map->getusers();
WBUFL(buf,250) = config;
WBUFL(buf,254) = PACKETVER;
WBUFL(buf,258) = bd_size;
for( i = 0; i < bd_size; i++ ) {
safestrncpy(WBUFP(buf,262 + ( i * ( BFLAG_LENGTH + 4 ) ) ), battle_data[i].str, BFLAG_LENGTH);
WBUFL(buf,262 + BFLAG_LENGTH + ( i * ( BFLAG_LENGTH + 4 ) ) ) = *battle_data[i].val;
}
chrif->send_report(buf, 262 + ( bd_size * ( BFLAG_LENGTH + 4 ) ) );
aFree(buf);
#undef BFLAG_LENGTH
}
static int Hercules_report_timer(int tid, int64 tick, int id, intptr_t data) {
if( chrif->isconnected() ) {/* char server relays it, so it must be online. */
Hercules_report(__DATE__,__TIME__);
}
return 0;
}
#endif
int battle_set_value(const char* w1, const char* w2)
{
int val = config_switch(w2);
int i;
nullpo_retr(1, w1);
nullpo_retr(1, w2);
ARR_FIND(0, ARRAYLENGTH(battle_data), i, strcmpi(w1, battle_data[i].str) == 0);
if (i == ARRAYLENGTH(battle_data)) {
if( HPM->parseConf(w1,w2,HPCT_BATTLE) ) /* if plugin-owned, succeed */
return 1;
return 0; // not found
}
if (val < battle_data[i].min || val > battle_data[i].max)
{
ShowWarning("Value for setting '%s': %s is invalid (min:%i max:%i)! Defaulting to %i...\n", w1, w2, battle_data[i].min, battle_data[i].max, battle_data[i].defval);
val = battle_data[i].defval;
}
*battle_data[i].val = val;
return 1;
}
bool battle_get_value(const char *w1, int *value)
{
int i;
nullpo_retr(false, w1);
nullpo_retr(false, value);
ARR_FIND(0, ARRAYLENGTH(battle_data), i, strcmpi(w1, battle_data[i].str) == 0);
if (i == ARRAYLENGTH(battle_data)) {
if (HPM->getBattleConf(w1,value))
return true;
} else {
*value = *battle_data[i].val;
return true;
}
return false;
}
void battle_set_defaults(void) {
int i;
for (i = 0; i < ARRAYLENGTH(battle_data); i++)
*battle_data[i].val = battle_data[i].defval;
}
void battle_adjust_conf(void)
{
battle_config.monster_max_aspd = 2000 - battle_config.monster_max_aspd * 10;
battle_config.max_aspd = 2000 - battle_config.max_aspd * 10;
battle_config.max_walk_speed = 100 * DEFAULT_WALK_SPEED / battle_config.max_walk_speed;
battle_config.max_cart_weight *= 10;
if (battle_config.max_def > 100 && !battle_config.weapon_defense_type) // added by [Skotlex]
battle_config.max_def = 100;
if (battle_config.min_hitrate > battle_config.max_hitrate)
battle_config.min_hitrate = battle_config.max_hitrate;
if (battle_config.pet_max_atk1 > battle_config.pet_max_atk2) // Skotlex
battle_config.pet_max_atk1 = battle_config.pet_max_atk2;
if (battle_config.day_duration && battle_config.day_duration < 60000) // added by [Yor]
battle_config.day_duration = 60000;
if (battle_config.night_duration && battle_config.night_duration < 60000) // added by [Yor]
battle_config.night_duration = 60000;
#if PACKETVER < 20100427
if (battle_config.feature_buying_store) {
ShowWarning("conf/battle/feature.conf buying_store is enabled but it requires PACKETVER 2010-04-27 or newer, disabling...\n");
battle_config.feature_buying_store = 0;
}
#endif
#if PACKETVER < 20100803
if (battle_config.feature_search_stores) {
ShowWarning("conf/battle/feature.conf search_stores is enabled but it requires PACKETVER 2010-08-03 or newer, disabling...\n");
battle_config.feature_search_stores = 0;
}
#endif
#if PACKETVER < 20130724
if (battle_config.feature_banking) {
ShowWarning("conf/battle/feature.conf banking is enabled but it requires PACKETVER 2013-07-24 or newer, disabling...\n");
battle_config.feature_banking = 0;
}
#endif
#if PACKETVER < 20141022
if (battle_config.feature_roulette) {
ShowWarning("conf/battle/feature.conf roulette is enabled but it requires PACKETVER 2014-10-22 or newer, disabling...\n");
battle_config.feature_roulette = 0;
}
#endif
#if PACKETVER > 20120000 && PACKETVER < 20130515 /* exact date (when it started) not known */
if (battle_config.feature_auction == 1) {
ShowWarning("conf/battle/feature.conf:feature.auction is enabled but it is not stable on PACKETVER "EXPAND_AND_QUOTE(PACKETVER)", disabling...\n");
ShowWarning("conf/battle/feature.conf:feature.auction change value to '2' to silence this warning and maintain it enabled\n");
battle_config.feature_auction = 0;
}
#endif
#ifndef CELL_NOSTACK
if (battle_config.custom_cell_stack_limit != 1)
ShowWarning("Battle setting 'custom_cell_stack_limit' takes no effect as this server was compiled without Cell Stack Limit support.\n");
#endif
}
int battle_config_read(const char* cfgName)
{
FILE* fp;
static int count = 0;
nullpo_ret(cfgName);
if (count == 0)
battle->config_set_defaults();
count++;
fp = fopen(cfgName,"r");
if (fp == NULL)
ShowError("File not found: %s\n", cfgName);
else
{
char line[1024], w1[1024], w2[1024];
while(fgets(line, sizeof(line), fp))
{
if (line[0] == '/' && line[1] == '/')
continue;
if (sscanf(line, "%1023[^:]:%1023s", w1, w2) != 2)
continue;
if (strcmpi(w1, "import") == 0)
battle->config_read(w2);
else
if (battle->config_set_value(w1, w2) == 0)
ShowWarning("Unknown setting '%s' in file %s\n", w1, cfgName);
}
fclose(fp);
}
count--;
if (count == 0) {
battle->config_adjust();
clif->bc_ready();
}
return 0;
}
void do_init_battle(bool minimal) {
if (minimal)
return;
battle->delay_damage_ers = ers_new(sizeof(struct delay_damage),"battle.c::delay_damage_ers",ERS_OPT_CLEAR);
timer->add_func_list(battle->delay_damage_sub, "battle_delay_damage_sub");
#ifndef STATS_OPT_OUT
timer->add_func_list(Hercules_report_timer, "Hercules_report_timer");
timer->add_interval(timer->gettick()+30000, Hercules_report_timer, 0, 0, 60000 * 30);
#endif
}
void do_final_battle(void) {
ers_destroy(battle->delay_damage_ers);
}
/* initialize the interface */
void battle_defaults(void) {
battle = &battle_s;
battle->bc = &battle_config;
memset(battle->attr_fix_table, 0, sizeof(battle->attr_fix_table));
battle->delay_damage_ers = NULL;
battle->init = do_init_battle;
battle->final = do_final_battle;
battle->calc_attack = battle_calc_attack;
battle->calc_damage = battle_calc_damage;
battle->calc_gvg_damage = battle_calc_gvg_damage;
battle->calc_bg_damage = battle_calc_bg_damage;
battle->weapon_attack = battle_weapon_attack;
battle->check_arrows = battle_check_arrows;
battle->calc_weapon_attack = battle_calc_weapon_attack;
battle->delay_damage = battle_delay_damage;
battle->drain = battle_drain;
battle->reflect_damage = battle_reflect_damage;
battle->attr_ratio = battle_attr_ratio;
battle->attr_fix = battle_attr_fix;
battle->calc_cardfix = battle_calc_cardfix;
battle->calc_cardfix2 = battle_calc_cardfix2;
battle->calc_elefix = battle_calc_elefix;
battle->calc_masteryfix = battle_calc_masteryfix;
battle->calc_chorusbonus = battle_calc_chorusbonus;
battle->calc_skillratio = battle_calc_skillratio;
battle->calc_sizefix = battle_calc_sizefix;
battle->calc_weapon_damage = battle_calc_weapon_damage;
battle->calc_defense = battle_calc_defense;
battle->get_master = battle_get_master;
battle->get_targeted = battle_gettargeted;
battle->get_enemy = battle_getenemy;
battle->get_target = battle_gettarget;
battle->get_current_skill = battle_getcurrentskill;
battle->check_undead = battle_check_undead;
battle->check_target = battle_check_target;
battle->check_range = battle_check_range;
battle->consume_ammo = battle_consume_ammo;
battle->get_targeted_sub = battle_gettargeted_sub;
battle->get_enemy_sub = battle_getenemy_sub;
battle->get_enemy_area_sub = battle_getenemyarea_sub;
battle->delay_damage_sub = battle_delay_damage_sub;
battle->blewcount_bonus = battle_blewcount_bonus;
battle->range_type = battle_range_type;
battle->calc_base_damage = battle_calc_base_damage;
battle->calc_base_damage2 = battle_calc_base_damage2;
battle->calc_misc_attack = battle_calc_misc_attack;
battle->calc_magic_attack = battle_calc_magic_attack;
battle->adjust_skill_damage = battle_adjust_skill_damage;
battle->add_mastery = battle_addmastery;
battle->calc_drain = battle_calc_drain;
battle->config_read = battle_config_read;
battle->config_set_defaults = battle_set_defaults;
battle->config_set_value = battle_set_value;
battle->config_get_value = battle_get_value;
battle->config_adjust = battle_adjust_conf;
battle->get_enemy_area = battle_getenemyarea;
battle->damage_area = battle_damage_area;
battle->calc_masteryfix_unknown = battle_calc_masteryfix_unknown;
battle->calc_skillratio_magic_unknown = battle_calc_skillratio_magic_unknown;
battle->calc_skillratio_weapon_unknown = battle_calc_skillratio_weapon_unknown;
battle->calc_misc_attack_unknown = battle_calc_misc_attack_unknown;
}
|
RagEmu/PreRenewal
|
src/map/battle.c
|
C
|
gpl-3.0
| 264,887
|
/*
* Copyright (c) 2016 Lee A. Stripp <leestripp@gmail.com>
*
* This file is part of qBot
*
* qBot is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* qBot 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 qBot. If not, see <http://www.gnu.org/licenses/>
*/
// datablocks
#include "../datablocks/lslinkedlist.h"
#include "../datablocks/lslistitem_pollentry.h"
#include "bangpoll.h"
bangPoll::bangPoll(QObject *parent) : qBotCmd(parent)
{
poll_entries = new lsLinkedList();
if(! poll_entries )
{
// ERROR
cout << "ERROR: Could not create poll_entries instance." << endl;
}
// defaults
poll_length = 5; // minutes
// Timer
poll_timer.stop();
connect( &poll_timer, SIGNAL(timeout()), this, SLOT(pollTimeout()) );
}
bangPoll::~bangPoll()
{
if( poll_entries ) delete poll_entries;
// debug
cout << "Delete bangPoll command..." << endl;
}
QString bangPoll::command() const
{
return "!poll";
}
void bangPoll::Get(const QString &data)
{
// Stats
setCalls( getCalls() + 1 );
lsListItem_PollEntry *entry;
QString res;
QString convert;
// No options, display list
if( data.isEmpty() )
{
// check if a poll is running
if( poll_timer.isActive() )
{
int i = 0;
res = "PRIVMSG " + getChannel() + " :";
res += poll_title + " > ";
// Calc remaining time
qint64 duration = poll_timer.remainingTime() / 1000; // in seconds
int seconds = (int) (duration % 60);
duration /= 60;
int minutes = (int) (duration % 60);
duration /= 60;
int hours = (int) (duration % 24);
if( hours > 0 )
res += convert.sprintf( "%d hour(s) ", hours );
if( minutes > 0 )
res += convert.sprintf( "%d minutes ", minutes );
if( seconds > 0 )
res += convert.sprintf( "%d seconds ", seconds );
res += "left.";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
res = "";
entry = (lsListItem_PollEntry*)poll_entries->getItem_list();
while( entry )
{
i++;
res += "PRIVMSG " + getChannel() + " :";
res += QString::number(i) + ": ";
res += entry->title() + " -- Score :";
res += QString::number(entry->score());
if( entry->getNext_item() ) res += "\r\n";
entry = (lsListItem_PollEntry*)entry->getNext_item();
}
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
// Check i
if( i == 0 )
{
res = "PRIVMSG " + getChannel() + " :";
res += "No entries - use s to add one.";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
return;
} else
{
// No poll running
res += "PRIVMSG " + getChannel() + " :";
res += "No poll running.";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
return;
}
return;
}
// Split the data
QStringList list = data.split( ' ', QString::SkipEmptyParts );
// n # : New Poll
if( list[0] == "n" )
{
// check if a poll is running
if( poll_timer.isActive() )
{
// Admin can overtide poll
if( getUser() == getAdmin() )
{
// Clear old poll
poll_entries->Clear();
// Set the poll length
if( list.size() > 1 )
{
bool OK;
poll_length = list[1].toInt( &OK );
if( OK )
{
if( poll_length > 60 ) poll_length = 60;
if( poll_length <= 0 ) poll_length = 1;
} else
{
// output one event
poll_length = 5;
}
}
// Title
if( list.size() > 2 )
{
poll_title = data.mid( data.indexOf( list[2] ) );
} else
{
poll_title = "No title set.";
}
// Start new Poll, convert to milisecs
poll_timer.start( poll_length * 60 * 1000 );
res = "PRIVMSG " + getChannel() + " :";
res += "Starting Poll for " + QString::number(poll_length) + " minutes -- Title :" + poll_title;
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
return;
} else
{
// A poll is running
res += "PRIVMSG " + getChannel() + " :";
res += "A poll is running.";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
return;
}
} else
{
// Clear old poll
poll_entries->Clear();
// Set the poll length
if( list.size() > 1 )
{
bool OK;
poll_length = list[1].toInt( &OK );
if( OK )
{
if( poll_length > 60 ) poll_length = 60;
if( poll_length <= 0 ) poll_length = 1;
} else
{
// output one event
poll_length = 5;
}
}
// title
if( list.size() > 2 )
{
poll_title = data.mid( data.indexOf( list[2] ) );
} else
{
poll_title = "No title set.";
}
// Start new Poll, convert to milisecs
poll_timer.start( poll_length * 60 * 1000 );
res = "PRIVMSG " + getChannel() + " :";
res += "Starting Poll for " + QString::number(poll_length) + " minutes -- Title :" + poll_title;
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
return;
}// if( list[0] == "n" )
// s : Suggest
if( data.left(1) == "s" )
{
// check if a poll is running
if( poll_timer.isActive() )
{
// Check empty string
if( data.mid(2).isEmpty() )
{
return;
}
// Check for duplicates
lsListItem_PollEntry *entry;
entry = (lsListItem_PollEntry*)poll_entries->getItem_list();
while( entry )
{
if( entry->title() == data.mid(2) )
{
break;
}
entry = (lsListItem_PollEntry*)entry->getNext_item();
}
// found double
if( entry )
{
res = "PRIVMSG " + getChannel() + " :";
res += "Suggestion already exsists. Try again.";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
return;
}
// Add new item at end
lsListItem_PollEntry *item;
item = new lsListItem_PollEntry();
if( item )
{
item->setTitle( data.mid(2) );
item->setScore( 1 );
poll_entries->Add_itematEnd( item );
// Give user feedback
res = "PRIVMSG " + getChannel() + " :";
res += "Suggestion " + item->title() + " added!";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
}
return;
}
// +# : Score
if( data.left(1) == "+" )
{
// check if a poll is running
if( poll_timer.isActive() )
{
// Add one point to selected entry
bool OK;
int h = 0;
int i = data.mid(1).toInt( &OK );
if( OK )
{
// Find entry
lsListItem_PollEntry *entry;
entry = (lsListItem_PollEntry*)poll_entries->getItem_list();
while( entry )
{
h++;
if( h == i )
{
// Add 1 to score
entry->setScore( entry->score() + 1 );
res = "PRIVMSG " + getChannel() + " :";
res += "1 point added to " + entry->title();
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
break;
}
entry = (lsListItem_PollEntry*)entry->getNext_item();
}
} else
{
res = "PRIVMSG " + getChannel() + " :";
res += "Invalid number";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
}// if( poll_timer.isActive() )
return;
}// if( data.left(1) == "+" )
}
void bangPoll::help()
{
QString res;
res = "PRIVMSG " + getChannel() + " :!poll [option] [data] [title] : ";
res += "Poll the audience";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
void bangPoll::help_options()
{
QString res;
res = "PRIVMSG " + getChannel() + " :!poll [option] [data] [title]";
res += "\r\n";
res += "PRIVMSG " + getChannel() + " : ";
res += "No options = List the current poll entries\r\n";
res += "PRIVMSG " + getChannel() + " : ";
res += "n 30 Title = Start a New poll for 30 minutes called Title\r\n";
res += "PRIVMSG " + getChannel() + " : ";
res += "s example = Suggest a poll entry of example\r\n";
res += "PRIVMSG " + getChannel() + " : ";
res += "+3 = Add 1 point to the entry numbered 3";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
void bangPoll::stats()
{
QString res;
res = "PRIVMSG " + getAdmin() + " :Stats >> " + command() + " ";
res += "calls:" + QString::number( getCalls() ) + " ";
res += "posts:" + QString::number( getPosts() );
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
void bangPoll::pollTimeout()
{
// End the Poll
poll_timer.stop();
// Doisplay results
QString res;
lsListItem_PollEntry *entry;
res = "PRIVMSG " + getChannel() + " :";
res += poll_title + " > Poll finished...";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
res = "";
entry = (lsListItem_PollEntry*)poll_entries->getItem_list();
if( entry )
{
while( entry )
{
res += "PRIVMSG " + getChannel() + " :";
res += "Score " + QString::number( entry->score() ) + " : ";
res += entry->title();
if( entry->getNext_item() ) res += "\r\n";
entry = (lsListItem_PollEntry*)entry->getNext_item();
}
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
} else
{
// No entries
res = "PRIVMSG " + getChannel() + " :";
res += "Poll had no entries.";
// Stats
setPosts( getPosts() + 1 );
emit( dataReady( res ) );
}
}
|
leestripp/qBot
|
src/commands/bangpoll.cpp
|
C++
|
gpl-3.0
| 12,318
|
#!/usr/bin/env python
# Copyright (C) 2014 Equinor ASA, Norway.
#
# The file 'test_grid.py' is part of ERT - Ensemble based Reservoir Tool.
#
# ERT is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ERT 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 at <http://www.gnu.org/licenses/gpl.html>
# for more details.
import os.path
import six
from unittest import skipIf, skip
import time
import itertools
from numpy import linspace
from ecl.util.util import IntVector
from ecl import EclDataType, EclUnitTypeEnum
from ecl.eclfile import EclKW, EclFile
from ecl.grid import EclGrid
from ecl.grid import EclGridGenerator as GridGen
from ecl.grid.faults import Layer , FaultCollection
from ecl.util.test import TestAreaContext
from numpy.testing import assert_allclose
from tests import EclTest
# This dict is used to verify that corners are mapped to the correct
# cell with respect to containment.
CORNER_HOME = {
(0, 0, 0) : 0, (0, 0, 1) : 9, (0, 0, 2) : 18, (0, 0, 3) : 18,
(0, 1, 0) : 3, (0, 1, 1) : 12, (0, 1, 2) : 21, (0, 1, 3) : 21,
(0, 2, 0) : 6, (0, 2, 1) : 15, (0, 2, 2) : 24, (0, 2, 3) : 24,
(0, 3, 0) : 6, (0, 3, 1) : 15, (0, 3, 2) : 24, (0, 3, 3) : 24,
(1, 0, 0) : 1, (1, 0, 1) : 10, (1, 0, 2) : 19, (1, 0, 3) : 19,
(1, 1, 0) : 4, (1, 1, 1) : 13, (1, 1, 2) : 22, (1, 1, 3) : 22,
(1, 2, 0) : 7, (1, 2, 1) : 16, (1, 2, 2) : 25, (1, 2, 3) : 25,
(1, 3, 0) : 7, (1, 3, 1) : 16, (1, 3, 2) : 25, (1, 3, 3) : 25,
(2, 0, 0) : 2, (2, 0, 1) : 11, (2, 0, 2) : 20, (2, 0, 3) : 20,
(2, 1, 0) : 5, (2, 1, 1) : 14, (2, 1, 2) : 23, (2, 1, 3) : 23,
(2, 2, 0) : 8, (2, 2, 1) : 17, (2, 2, 2) : 26, (2, 2, 3) : 26,
(2, 3, 0) : 8, (2, 3, 1) : 17, (2, 3, 2) : 26, (2, 3, 3) : 26,
(3, 0, 0) : 2, (3, 0, 1) : 11, (3, 0, 2) : 20, (3, 0, 3) : 20,
(3, 1, 0) : 5, (3, 1, 1) : 14, (3, 1, 2) : 23, (3, 1, 3) : 23,
(3, 2, 0) : 8, (3, 2, 1) : 17, (3, 2, 2) : 26, (3, 2, 3) : 26,
(3, 3, 0) : 8, (3, 3, 1) : 17, (3, 3, 2) : 26, (3, 3, 3) : 26
}
def createVolumeTestGridBase(dim, dV, offset=1):
return [
GridGen.create_grid(dim, dV, offset=0),
GridGen.create_grid(dim, dV, offset=offset),
GridGen.create_grid(dim, dV, offset=offset, irregular_offset=True),
GridGen.create_grid(dim, dV, offset=offset, concave=True),
GridGen.create_grid(dim, dV, offset=offset, irregular=True),
GridGen.create_grid(dim, dV, offset=offset, concave=True, irregular=True),
GridGen.create_grid(dim, dV, offset=offset, irregular_offset=True, concave=True),
GridGen.create_grid(dim, dV, offset=0, faults=True),
GridGen.create_grid(dim, dV, offset=offset, faults=True),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), scale=2),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), scale=0.5),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), translation=(50,50,0)),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), rotate=True),
GridGen.create_grid(dim, dV, escape_origo_shift=(100, 100, 0), misalign=True),
GridGen.create_grid(dim, dV, offset=offset, escape_origo_shift=(100, 100, 0),
irregular_offset=True, concave=True, irregular=True,
scale=1.5, translation=(5,5,0), rotate=True,
misalign=True)
]
def createContainmentTestBase():
return [
(3, GridGen.create_grid((6,6,6), (1,1,1), offset=1)),
(10, GridGen.create_grid((3,3,3), (1,1,1), offset=1, concave=True)),
(4, GridGen.create_grid((10,10,1), (1,1,1), offset=0., misalign=True)),
(3,
GridGen.create_grid((6,6,6), (1,1,1), offset=0.,
escape_origo_shift=(100, 100, 0),
irregular_offset=True, concave=True, irregular=True,
scale=1.5, translation=(5,5,0),
misalign=True
)
)
]
def getMinMaxValue(grid):
corners = [
grid.getCellCorner(i, cell)
for i in range(8)
for cell in range(grid.getGlobalSize())
]
return [(min(values), max(values)) for values in zip(*corners)]
def createWrapperGrid(grid):
"""
Creates a grid that occupies the same space as the given grid,
but that consists of a single cell.
"""
x, y, z = grid.getNX()-1, grid.getNY()-1, grid.getNZ()-1
corner_pos = [
(0, 0, 0), (x, 0, 0), (0, y, 0), (x, y, 0),
(0, 0, z), (x, 0, z), (0, y, z), (x, y, z)
]
corners = [
grid.getCellCorner(i, ijk=pos)
for i, pos in enumerate(corner_pos)
]
return GridGen.create_single_cell_grid(corners)
def average(points):
p = six.functools.reduce(
lambda a, b: (a[0] + b[0], a[1] + b[1], a[2] + b[2]), points)
return [elem/float(len(points)) for elem in p]
# This test class should only have test cases which do not require
# external test data. Tests involving Equinor test data are in the
# test_grid_equinor module.
class GridTest(EclTest):
def test_oom_grid(self):
nx = 2000
ny = 2000
nz = 2000
with self.assertRaises(MemoryError):
grid = GridGen.createRectangular( (nx,ny,nz), (1,1,1))
def test_posXYEdge(self):
nx = 10
ny = 11
grid = GridGen.createRectangular( (nx,ny,1) , (1,1,1) )
self.assertEqual( grid.findCellCornerXY(0,0,0) , 0 )
self.assertEqual( grid.findCellCornerXY(nx,0,0) , nx)
self.assertEqual( grid.findCellCornerXY(0 , ny , 0) , (nx + 1 ) * ny )
self.assertEqual( grid.findCellCornerXY(nx,ny,0) , (nx + 1 ) * (ny + 1) - 1)
self.assertEqual( grid.findCellCornerXY(0.25,0,0) , 0 )
self.assertEqual( grid.findCellCornerXY(0,0.25,0) , 0 )
self.assertEqual( grid.findCellCornerXY(nx - 0.25,0,0) , nx )
self.assertEqual( grid.findCellCornerXY(nx , 0.25,0) , nx )
self.assertEqual( grid.findCellCornerXY(0 , ny - 0.25, 0) , (nx + 1 ) * ny )
self.assertEqual( grid.findCellCornerXY(0.25 , ny , 0) , (nx + 1 ) * ny )
self.assertEqual( grid.findCellCornerXY(nx -0.25 ,ny,0) , (nx + 1 ) * (ny + 1) - 1)
self.assertEqual( grid.findCellCornerXY(nx , ny - 0.25,0) , (nx + 1 ) * (ny + 1) - 1)
def test_dims(self):
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) )
self.assertEqual( grid.getNX() , 10 )
self.assertEqual( grid.getNY() , 20 )
self.assertEqual( grid.getNZ() , 30 )
self.assertEqual( grid.getGlobalSize() , 30*10*20 )
self.assertEqual( grid.getDims() , (10,20,30,6000) )
def test_create(self):
with self.assertRaises(ValueError):
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) , actnum = [0,1,1,2])
with self.assertRaises(ValueError):
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) , actnum = IntVector(initial_size = 10))
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) ) # actnum=None -> all active
self.assertEqual( grid.getNumActive( ) , 30*20*10)
actnum = IntVector(default_value = 1 , initial_size = 6000)
actnum[0] = 0
actnum[1] = 0
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) , actnum = actnum)
self.assertEqual( grid.getNumActive( ) , 30*20*10 - 2)
def test_all_iters(self):
fk = self.createTestPath('local/ECLIPSE/faarikaal/faarikaal1.EGRID')
grid = EclGrid(fk)
cell = grid[3455]
self.assertEqual(3455, cell.global_index)
cell = grid[(4,1,82)]
self.assertEqual(3455, cell.global_index)
self.assertEqual(grid.cell(global_index=3455),
grid.cell(active_index=2000))
self.assertEqual(grid.cell(global_index=3455),
grid.cell(i=4, j=1, k=82))
na = grid.get_num_active()
self.assertEqual(na, 4160)
cnt = 0
for c in grid.cells(active=True):
cnt += 1
self.assertTrue(c.active)
self.assertEqual(cnt, 4160)
cnt = len([c for c in grid.cells()])
self.assertEqual(cnt, len(grid))
def test_repr_and_name(self):
grid = GridGen.createRectangular((2,2,2), (10,10,10), actnum=[0,0,0,0,1,1,1,1])
pfx = 'EclGrid('
rep = repr(grid)
self.assertEqual(pfx, rep[:len(pfx)])
self.assertEqual(type(rep), type(''))
self.assertEqual(type(grid.getName()), type(''))
with TestAreaContext("python/ecl_grid/repr"):
grid.save_EGRID("CASE.EGRID")
g2 = EclGrid("CASE.EGRID")
r2 = repr(g2)
self.assertEqual(pfx, r2[:len(pfx)])
self.assertEqual(type(r2), type(''))
self.assertEqual(type(g2.getName()), type(''))
def test_node_pos(self):
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) )
with self.assertRaises(IndexError):
grid.getNodePos(-1,0,0)
with self.assertRaises(IndexError):
grid.getNodePos(11,0,0)
p0 = grid.getNodePos(0,0,0)
self.assertEqual( p0 , (0,0,0))
p7 = grid.getNodePos(10,20,30)
self.assertEqual( p7 , (10,20,30))
# The broken file was previously handled by the ecl_file_open() call internally
# in the ecl_grid implementation. That will now not fail for a broken file, and then
# the grid class needs to do more/better checking itself.
@skip("Needs better error checking inside in the ecl_grid")
def test_truncated_file(self):
grid = GridGen.createRectangular( (10,20,30) , (1,1,1) )
with TestAreaContext("python/ecl_grid/truncated"):
grid.save_EGRID( "TEST.EGRID")
size = os.path.getsize( "TEST.EGRID")
with open("TEST.EGRID" , "r+") as f:
f.truncate( size / 2 )
with self.assertRaises(IOError):
EclGrid("TEST.EGRID")
def test_posXY1(self):
nx = 4
ny = 1
nz = 1
grid = GridGen.createRectangular( (nx,ny,nz) , (1,1,1) )
(i,j) = grid.findCellXY( 0.5 , 0.5, 0 )
self.assertEqual(i , 0)
self.assertEqual(j , 0)
(i,j) = grid.findCellXY( 3.5 , 0.5, 0 )
self.assertEqual(i , 3)
self.assertEqual(j , 0)
def test_init_ACTNUM(self):
nx = 10
ny = 23
nz = 7
grid = GridGen.createRectangular( (nx,ny,nz) , (1,1,1) )
actnum = grid.exportACTNUM()
self.assertEqual( len(actnum) , nx*ny*nz )
self.assertEqual( actnum[0] , 1 )
self.assertEqual( actnum[nx*ny*nz - 1] , 1 )
actnum_kw = grid.exportACTNUMKw( )
self.assertEqual(len(actnum_kw) , len(actnum))
for a1,a2 in zip(actnum, actnum_kw):
self.assertEqual(a1, a2)
def test_posXY(self):
nx = 10
ny = 23
nz = 7
grid = GridGen.createRectangular( (nx,ny,nz) , (1,1,1) )
with self.assertRaises(IndexError):
grid.findCellXY( 1 , 1, -1 )
with self.assertRaises(IndexError):
grid.findCellXY( 1 , 1, nz + 1 )
with self.assertRaises(ValueError):
grid.findCellXY(15 , 78 , 2)
i,j = grid.findCellXY( 1.5 , 1.5 , 2 )
self.assertEqual(i , 1)
self.assertEqual(j , 1)
for i in range(nx):
for j in range(ny):
p = grid.findCellXY(i + 0.5 , j+ 0.5 , 0)
self.assertEqual( p[0] , i )
self.assertEqual( p[1] , j )
c = grid.findCellCornerXY( 0.10 , 0.10 , 0 )
self.assertEqual(c , 0)
c = grid.findCellCornerXY( 0.90 , 0.90 , 0 )
self.assertEqual( c , (nx + 1) + 1 )
c = grid.findCellCornerXY( 0.10 , 0.90 , 0 )
self.assertEqual( c , (nx + 1) )
c = grid.findCellCornerXY( 0.90 , 0.90 , 0 )
self.assertEqual( c , (nx + 1) + 1 )
c = grid.findCellCornerXY( 0.90 , 0.10 , 0 )
self.assertEqual( c , 1 )
def test_compressed_copy(self):
nx = 10
ny = 10
nz = 10
grid = GridGen.createRectangular( (nx,ny,nz) , (1,1,1) )
kw1 = EclKW("KW" , 1001 , EclDataType.ECL_INT )
with self.assertRaises(ValueError):
cp = grid.compressedKWCopy( kw1 )
def test_dxdydz(self):
nx = 10
ny = 10
nz = 10
grid = GridGen.createRectangular( (nx,ny,nz) , (2,3,4) )
(dx,dy,dz) = grid.getCellDims( active_index = 0 )
self.assertEqual( dx , 2 )
self.assertEqual( dy , 3 )
self.assertEqual( dz , 4 )
def test_create_3d_is_create_kw_inverse(self):
nx = 10
ny = 7
nz = 5
grid = GridGen.create_rectangular((nx, ny, nz), (1, 1, 1))
kw1 = EclKW("SWAT", nx * ny * nz, EclDataType.ECL_FLOAT)
for k, j, i in itertools.product(range(nz), range(ny), range(nx)):
kw1[i + j * nx + nx * ny * k] = i * j * k
numpy_3d = grid.create3D(kw1)
kw2 = grid.create_kw(numpy_3d, "SWAT", False)
self.assertEqual(kw2.name, "SWAT")
assert_allclose(grid.create3D(kw2), numpy_3d)
def test_create_3d_agrees_with_get_value(self):
nx = 5
ny = 3
nz = 2
grid = GridGen.createRectangular((nx, ny, nz), (1, 1, 1))
kw = EclKW("SWAT", nx * ny * nz, EclDataType.ECL_FLOAT)
for k, j, i in itertools.product(range(nz), range(ny), range(nx)):
kw[i + j * nx + nx * ny * k] = i * j * k
numpy_3d = grid.create3D(kw)
for k, j, i in itertools.product(range(nz), range(ny), range(nx)):
self.assertAlmostEqual(numpy_3d[i, j, k], grid.grid_value(kw, i, j, k))
def test_len(self):
nx = 10
ny = 11
nz = 12
actnum = EclKW( "ACTNUM" , nx*ny*nz , EclDataType.ECL_INT )
actnum[0] = 1
actnum[1] = 1
actnum[2] = 1
actnum[3] = 1
grid = GridGen.createRectangular( (nx,ny,nz) , (1,1,1), actnum = actnum)
self.assertEqual( len(grid) , nx*ny*nz )
self.assertEqual( grid.getNumActive( ) , 4 )
def test_export(self):
dims = (3, 3, 3)
coord = GridGen.create_coord(dims, (1,1,1))
zcorn = GridGen.create_zcorn(dims, (1,1,1), offset=0)
grid = EclGrid.create(dims, zcorn, coord, None)
self.assertEqual(zcorn, grid.export_zcorn())
self.assertEqual(coord, grid.export_coord())
def test_output_units(self):
n = 10
a = 1
grid = GridGen.createRectangular( (n,n,n), (a,a,a))
with TestAreaContext("python/ecl_grid/units"):
grid.save_EGRID( "CASE.EGRID" , output_unit = EclUnitTypeEnum.ECL_FIELD_UNITS )
f = EclFile("CASE.EGRID")
g = f["GRIDUNIT"][0]
self.assertEqual( g[0].strip( ) , "FEET" )
g2 = EclGrid("CASE.EGRID")
self.assertFloatEqual( g2.cell_volume( global_index = 0 ) , 3.28084*3.28084*3.28084)
grid.save_EGRID( "CASE.EGRID" )
f = EclFile("CASE.EGRID")
g = f["GRIDUNIT"][0]
self.assertEqual( g[0].strip( ) , "METRES" )
grid.save_EGRID( "CASE.EGRID" , output_unit = EclUnitTypeEnum.ECL_LAB_UNITS)
f = EclFile("CASE.EGRID")
g = f["GRIDUNIT"][0]
self.assertEqual( g[0].strip() , "CM" )
g2 = EclGrid("CASE.EGRID")
self.assertFloatEqual( g2.cell_volume( global_index = 0 ) , 100*100*100 )
def test_volume(self):
dim = (10,10,10)
dV = (2,2,2)
grids = createVolumeTestGridBase(dim, dV)
for grid in grids:
tot_vol = createWrapperGrid(grid).cell_volume(0)
cell_volumes = [grid.cell_volume(i) for i in range(grid.getGlobalSize())]
self.assertTrue(min(cell_volumes) >= 0)
self.assertFloatEqual(sum(cell_volumes), tot_vol)
def test_unique_containment(self):
test_base = createContainmentTestBase()
for steps_per_unit, grid in test_base:
wgrid = createWrapperGrid(grid)
(xmin, xmax), (ymin, ymax), (zmin, zmax) = getMinMaxValue(wgrid)
x_space = linspace(
xmin - 1, xmax + 1, int(xmax - xmin + 2) * steps_per_unit + 1
)
y_space = linspace(
ymin - 1, ymax + 1, int(ymax - ymin + 2) * steps_per_unit + 1
)
z_space = linspace(
zmin - 1, zmax + 1, int(zmax - zmin + 2) * steps_per_unit + 1
)
# limit amount of points tested by
# only testing every 3rd point
x_space = x_space[0:-1:3]
y_space = y_space[0:-1:3]
z_space = z_space[0:-1:3]
for x, y, z in itertools.product(x_space, y_space, z_space):
hits = [
grid.cell_contains(x, y, z, i)
for i in range(grid.getGlobalSize())
].count(True)
self.assertIn(hits, [0, 1])
expected = 1 if wgrid.cell_contains(x, y, z, 0) else 0
self.assertEqual(
expected,
hits,
'Expected %d for (%g,%g,%g), got %d' % (expected, x, y, z, hits)
)
def test_cell_corner_containment(self):
n = 4
d = 10
grid = GridGen.createRectangular( (n, n, n), (d, d, d))
for x, y, z in itertools.product(range(0, n*d+1, d), repeat=3):
self.assertEqual(
1,
[grid.cell_contains(x, y, z, i) for i in range(n**3)].count(True)
)
def test_cell_corner_containment_compatability(self):
grid = GridGen.createRectangular( (3,3,3), (1,1,1) )
for x, y, z in itertools.product(range(4), repeat=3):
for i in range(27):
if grid.cell_contains(x, y, z, i):
self.assertEqual(
CORNER_HOME[(x,y,z)],
i
)
def test_cell_face_containment(self):
n = 4
d = 10
grid = GridGen.createRectangular( (n, n, n), (d, d, d))
for x, y, z in itertools.product(range(d//2, n*d, d), repeat=3):
for axis, direction in itertools.product(range(3), [-1, 1]):
p = [x, y, z]
p[axis] = p[axis] + direction*d/2
self.assertEqual(
1,
[grid.cell_contains(p[0], p[1], p[2], i) for i in range(n**3)].count(True)
)
# This test generates a cell that is concave on ALL 6 sides
def test_concave_cell_containment(self):
points = [
(5, 5, 5),
(20, 10, 10),
(10, 20, 10),
(25, 25, 5),
(10, 10, 20),
(25, 5, 25),
(5, 25, 25),
(20, 20, 20)
]
grid = GridGen.create_single_cell_grid(points)
assertPoint = lambda p : self.assertTrue(
grid.cell_contains(p[0], p[1], p[2], 0)
)
assertNotPoint = lambda p : self.assertFalse(
grid.cell_contains(p[0], p[1], p[2], 0)
)
# Cell center
assertPoint(average(points));
# "Side" center
assertNotPoint(average(points[0:4:]))
assertNotPoint(average(points[4:8:]))
assertNotPoint(average(points[1:8:2]))
assertNotPoint(average(points[0:8:2]))
assertNotPoint(average(points[0:8:4] + points[1:8:4]))
assertNotPoint(average(points[2:8:4] + points[3:8:4]))
# Corners
for p in points:
assertPoint(p)
# Edges
edges = ([(i, i+1) for i in range(0, 8, 2)] +
[(i, i+2) for i in [0, 1, 4, 5]] +
[(i, i+4) for i in range(4)] +
[(1,2), (2,7), (1,7), (4,7), (2,4), (4,1)])
for a,b in edges:
assertPoint(average([points[a], points[b]]))
# Epsilon inside from corners
middle_point = average(points)
for p in points:
assertPoint(average(20*[p] + [middle_point]))
# Espilon outside
middle_point[2] = 0
for p in points[0:4:]:
assertNotPoint(average(20*[p] + [middle_point]))
middle_point[2] = 30
for p in points[4:8:]:
assertNotPoint(average(20*[p] + [middle_point]))
# This test generates a cell that is strictly convex on ALL 6 sides
def test_concvex_cell_containment(self):
points = [
(10, 10, 10),
(25, 5, 5),
(5, 25, 5),
(20, 20, 10),
(5, 5, 25),
(20, 10, 20),
(10, 20, 20),
(25, 25, 25)
]
grid = GridGen.create_single_cell_grid(points)
assertPoint = lambda p : self.assertTrue(
grid.cell_contains(p[0], p[1], p[2], 0)
)
assertNotPoint = lambda p : self.assertFalse(
grid.cell_contains(p[0], p[1], p[2], 0)
)
# Cell center
assertPoint(average(points));
# "Side" center
assertPoint(average(points[0:4:]))
assertPoint(average(points[4:8:]))
assertPoint(average(points[1:8:2]))
assertPoint(average(points[0:8:2]))
assertPoint(average(points[0:8:4] + points[1:8:4]))
assertPoint(average(points[2:8:4] + points[3:8:4]))
# Corners
for p in points:
assertPoint(p)
# Edges
edges = ([(i, i+1) for i in range(0, 8, 2)] +
[(i, i+2) for i in [0, 1, 4, 5]] +
[(i, i+4) for i in range(4)] +
[(1,2), (2,7), (1,7), (4,7), (2,4), (4,1)])
for a,b in edges:
assertPoint(average([points[a], points[b]]))
# Epsilon inside from corners
middle_point = average(points)
for p in points:
assertPoint(average(20*[p] + [middle_point]))
# Espilon outside
middle_point[2] = 0
for p in points[0:4:]:
assertNotPoint(average(20*[p] + [middle_point]))
middle_point[2] = 30
for p in points[4:8:]:
assertNotPoint(average(20*[p] + [middle_point]))
|
Statoil/libecl
|
python/tests/ecl_tests/test_grid.py
|
Python
|
gpl-3.0
| 23,060
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.3 on 2017-08-15 09:46
from __future__ import unicode_literals
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('scoping', '0128_auto_20170808_0954'),
]
operations = [
migrations.CreateModel(
name='ProjectRoles',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('role', models.CharField(choices=[('OW', 'Owner'), ('AD', 'Admin'), ('RE', 'Reviewer'), ('VE', 'Viewer')], max_length=2)),
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
migrations.RemoveField(
model_name='project',
name='owner',
),
migrations.AddField(
model_name='projectroles',
name='project',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='scoping.Project'),
),
migrations.AddField(
model_name='project',
name='users',
field=models.ManyToManyField(through='scoping.ProjectRoles', to=settings.AUTH_USER_MODEL),
),
]
|
mcallaghan/tmv
|
BasicBrowser/scoping/migrations/0129_auto_20170815_0946.py
|
Python
|
gpl-3.0
| 1,435
|
// The OpenSplice DDS Community Edition project.
//
// Copyright (C) 2006 to 2011 PrismTech Limited and its licensees.
// Copyright (C) 2009 L-3 Communications / IS
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License Version 3 dated 29 June 2007, 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
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with OpenSplice DDS Community Edition; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
using System;
using System.Runtime.InteropServices;
namespace DDS.OpenSplice.Gapi
{
static internal class GenericAllocRelease
{
/* Generic allocation/release functions */
[DllImport("ddskernel", EntryPoint = "gapi_free")]
public static extern void Free(IntPtr buffer);
// it is actually a uint not an int...but all are
// lengths are ints, so this saves a cast.
[DllImport("ddskernel", EntryPoint = "gapi_alloc")]
public static extern IntPtr Alloc(int length);
[DllImport("ddskernel", EntryPoint = "gapi_sequence_malloc")]
public static extern IntPtr sequence_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_string_alloc")]
public static extern IntPtr string_alloc(int length);
[DllImport("ddskernel", EntryPoint = "gapi_string_dup")]
public static extern IntPtr string_dup(string stringPtr);
// QOS alloc's
[DllImport("ddskernel", EntryPoint = "gapi_domainParticipantFactoryQos__alloc")]
public static extern IntPtr domainParticipantFactoryQos_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_domainParticipantQos__alloc")]
public static extern IntPtr domainParticipantQos_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_topicQos__alloc")]
public static extern IntPtr topicQos_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_dataWriterQos__alloc")]
public static extern IntPtr dataWriterQos_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_publisherQos__alloc")]
public static extern IntPtr publisherQos_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_dataReaderQos__alloc")]
public static extern IntPtr dataReaderQos_alloc();
[DllImport("ddskernel", EntryPoint = "gapi_subscriberQos__alloc")]
public static extern IntPtr subscriberQos_alloc();
//// sequence alloc's
//[DllImport("ddskernel", EntryPoint = "gapi_stringSeq__alloc")]
//public static extern IntPtr stringSeq_alloc();
// TODO: More seqs
// sequence buffer alloc's
//[DllImport("ddskernel", EntryPoint = "gapi_instanceHandleSeq_allocbuf")]
//public static extern IntPtr instanceHandleSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_stringSeq_allocbuf")]
//public static extern IntPtr stringSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_qosPolicyCountSeq_allocbuf")]
//public static extern IntPtr qosPolicyCountSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_topicSeq_allocbuf")]
//public static extern IntPtr topicSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_dataReaderSeq_allocbuf")]
//public static extern IntPtr dataReaderSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_dataReaderViewSeq_allocbuf")]
//public static extern IntPtr dataReaderViewSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_conditionSeq_allocbuf")]
//public static extern IntPtr conditionSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_sampleStateSeq_allocbuf")]
//public static extern IntPtr sampleStateSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_viewStateSeq_allocbuf")]
//public static extern IntPtr viewStateSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_instanceStateSeq_allocbuf")]
//public static extern IntPtr instanceStateSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_octetSeq_allocbuf")]
//public static extern IntPtr octetSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_participantBuiltinTopicDataSeq_allocbuf")]
//public static extern IntPtr participantBuiltinTopicDataSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_topicBuiltinTopicDataSeq_allocbuf")]
//public static extern IntPtr topicBuiltinTopicDataSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_publicationBuiltinTopicDataSeq_allocbuf")]
//public static extern IntPtr publicationBuiltinTopicDataSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_subscriptionBuiltinTopicDataSeq_allocbuf")]
//public static extern IntPtr subscriptionBuiltinTopicDataSeq_allocbuf(uint length);
//[DllImport("ddskernel", EntryPoint = "gapi_sampleInfoSeq_allocbuf")]
//public static extern IntPtr sampleInfoSeq_allocbuf(uint length);
}
/*
* // ----------------------------------------------------------------------
* // gapi Constants & Macro's
* // ----------------------------------------------------------------------
*/
internal static class NativeConstants
{
public static IntPtr GapiParticipantQosDefault
{
get
{
return IntPtr.Zero;
}
}
public static IntPtr GapiPublisherQosDefault
{
get
{
return IntPtr.Zero;
}
}
public static IntPtr GapiSubscriberQosDefault
{
get
{
return IntPtr.Zero;
}
}
public static IntPtr GapiTopicQosDefault
{
get
{
return IntPtr.Zero;
}
}
public static IntPtr GapiDataWriterQosDefault
{
get
{
return IntPtr.Zero;
}
}
}
/*
* // ----------------------------------------------------------------------
* // Listeners
* // ----------------------------------------------------------------------
* interface Listener;
* interface Entity;
* interface TopicDescription;
* interface Topic;
* interface ContentFilteredTopic;
* interface MultiTopic;
* interface DataWriter;
* interface DataReader;
* interface Subscriber;
* interface Publisher;
* interface TypeSupport;
*/
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listenerThreadAction(System.IntPtr listener_data);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_deleteEntityAction(IntPtr entityData, IntPtr userData);
// topic listener
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_InconsistentTopicListener(IntPtr entityData, IntPtr topicPtr, InconsistentTopicStatus status);
internal struct gapi_topicListener
{
public IntPtr listener_data;
public gapi_listener_InconsistentTopicListener on_inconsistent_topic;
}
// datawriter listener
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_OfferedDeadlineMissedListener(IntPtr entityData, IntPtr writerPtr, OfferedDeadlineMissedStatus status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_LivelinessLostListener(IntPtr entityData, IntPtr writerPtr, LivelinessLostStatus status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_OfferedIncompatibleQosListener(IntPtr entityData, IntPtr writerPtr, IntPtr gapi_status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_PublicationMatchedListener(IntPtr entityData, IntPtr writerPtr, PublicationMatchedStatus status);
internal struct gapi_publisherDataWriterListener
{
public IntPtr listener_data;
public gapi_listener_OfferedDeadlineMissedListener on_offered_deadline_missed;
public gapi_listener_OfferedIncompatibleQosListener on_offered_incompatible_qos;
public gapi_listener_LivelinessLostListener on_liveliness_lost;
public gapi_listener_PublicationMatchedListener on_publication_match;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_RequestedDeadlineMissedListener(IntPtr entityData, IntPtr readerPtr, RequestedDeadlineMissedStatus status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_LivelinessChangedListener(IntPtr entityData, IntPtr readerPtr, LivelinessChangedStatus status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_RequestedIncompatibleQosListener(IntPtr entityData, IntPtr readerPtr, IntPtr gapi_status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_SampleRejectedListener(IntPtr entityData, IntPtr readerPtr, SampleRejectedStatus status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_DataAvailableListener(IntPtr entityData, IntPtr readerPtr);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_SubscriptionMatchedListener(IntPtr entityData, IntPtr readerPtr, SubscriptionMatchedStatus status);
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_SampleLostListener(IntPtr entityData, IntPtr readerPtr, SampleLostStatus status);
internal struct gapi_dataReaderListener
{
public IntPtr listener_data;
public gapi_listener_RequestedDeadlineMissedListener on_requested_deadline_missed;
public gapi_listener_RequestedIncompatibleQosListener on_requested_incompatible_qos;
public gapi_listener_SampleRejectedListener on_sample_rejected;
public gapi_listener_LivelinessChangedListener on_liveliness_changed;
public gapi_listener_DataAvailableListener on_data_available;
public gapi_listener_SubscriptionMatchedListener on_subscription_match;
public gapi_listener_SampleLostListener on_sample_lost;
}
[UnmanagedFunctionPointer(CallingConvention.Cdecl)]
internal delegate void gapi_listener_DataOnReadersListener(IntPtr entityData, IntPtr subscriberPtr);
internal struct gapi_subscriberListener
{
public gapi_dataReaderListener dataReader;
public gapi_listener_DataOnReadersListener on_data_on_readers;
}
internal struct gapi_domainParticipantListener
{
public IntPtr listener_data;
public gapi_listener_InconsistentTopicListener on_inconsistent_topic;
public gapi_listener_OfferedDeadlineMissedListener on_offered_deadline_missed;
public gapi_listener_OfferedIncompatibleQosListener on_offered_incompatible_qos;
public gapi_listener_LivelinessLostListener on_liveliness_lost;
public gapi_listener_PublicationMatchedListener on_publication_match;
public gapi_listener_RequestedDeadlineMissedListener on_requested_deadline_missed;
public gapi_listener_RequestedIncompatibleQosListener on_requested_incompatible_qos;
public gapi_listener_SampleRejectedListener on_sample_rejected;
public gapi_listener_LivelinessChangedListener on_liveliness_changed;
public gapi_listener_DataAvailableListener on_data_available;
public gapi_listener_SubscriptionMatchedListener on_subscription_match;
public gapi_listener_SampleLostListener on_sample_lost;
public gapi_listener_DataOnReadersListener on_data_on_readers;
}
/*
* struct QosPolicyCount {
* QosPolicyId_t policy_id;
* long count;
* };
*/
//typedef C_STRUCT(gapi_qosPolicyCount) {
// gapi_qosPolicyId_t policy_id;
// gapi_long count;
//} gapi_qosPolicyCount;
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct gapi_qosPolicyCount
{
public int policy_id;
public int count;
}
// NOTE: Both gapi_requestedIncompatibleQosStatus and gapi_offeredIncompatibleQosStatus
// use the same basic type, so we create gapi_offeredRequestedIncompatibleQosStatus
//typedef C_STRUCT(gapi_requestedIncompatibleQosStatus) {
// gapi_long total_count;
// gapi_long total_count_change;
// gapi_qosPolicyId_t last_policy_id;
// gapi_qosPolicyCountSeq policies;
//} gapi_requestedIncompatibleQosStatus;
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct gapi_offeredRequestedIncompatibleQosStatus
{
public int total_count;
public int total_count_change;
public int last_policy_id;
// gapi_qosPolicyCountSeq
public gapi_Seq policies;
}
/*
* // ----------------------------------------------------------------------
* // Qos
* // ----------------------------------------------------------------------
*/
#pragma warning disable 169
[StructLayoutAttribute(LayoutKind.Sequential)]
public class gapi_Seq
{
public uint _maximum;
public uint _length;
public IntPtr _buffer;
[MarshalAs(UnmanagedType.U1)]
public bool _release;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_userDataQosPolicy
{
// octetSeq
gapi_Seq value;
}
/* struct EntityFactoryQosPolicy {
* boolean autoenable_created_entities;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_entityFactoryQosPolicy
{
[MarshalAs(UnmanagedType.U1)]
bool autoenable_created_entities;
}
/* struct ShareQosPolicy {
* String name;
* Boolean enable;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_shareQosPolicy
{
IntPtr name;
[MarshalAs(UnmanagedType.U1)]
bool enable;
}
/* struct SchedulingClassQosPolicy {
* SchedulingClassQosPolicyKind kind;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_schedulingClassQosPolicy
{
SchedulingClassQosPolicyKind kind;
}
/* struct SchedulingPriorityQosPolicy {
* SchedulingPriorityQosPolicyKind kind;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_schedulingPriorityQosPolicy
{
SchedulingPriorityQosPolicyKind kind;
}
/* struct SchedulingQosPolicy {
* SchedulingClassQosPolicy scheduling_class;
* SchedulingPriorityQosPolicy scheduling_priority_kind;
* long scheduling_priority;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_schedulingQosPolicy
{
gapi_schedulingClassQosPolicy scheduling_class;
gapi_schedulingPriorityQosPolicy scheduling_priority_kind;
int scheduling_priority;
}
/*
* struct DomainParticipantFactoryQos {
* UserDataQosPolicy user_data;
* EntityFactoryQosPolicy entity_factory;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_domainParticipantFactoryQos
{
gapi_entityFactoryQosPolicy entity_factory;
}
/*
* struct DomainParticipantQos {
* UserDataQosPolicy user_data;
* EntityFactoryQosPolicy entity_factory;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_domainParticipantQos
{
gapi_userDataQosPolicy user_data;
gapi_entityFactoryQosPolicy entity_factory;
gapi_schedulingQosPolicy watchdog_scheduling;
gapi_schedulingQosPolicy listener_scheduling;
}
/* struct PresentationQosPolicy {
* PresentationQosPolicyAccessScopeKind access_scope;
* boolean coherent_access;
* boolean ordered_access;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_presentationQosPolicy
{
int access_scope;
[MarshalAs(UnmanagedType.U1)]
bool coherent_access;
[MarshalAs(UnmanagedType.U1)]
bool ordered_access;
}
/* struct GroupDataQosPolicy {
* sequence<octet> value;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_groupDataQosPolicy
{
// octetSeq
gapi_Seq value;
}
/* struct PartitionQosPolicy {
* StringSeq name;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_partitionQosPolicy
{
// stringSeq
gapi_Seq name;
}
/*
* struct PublisherQos {
* PresentationQosPolicy presentation;
* PartitionQosPolicy partition;
* GroupDataQosPolicy group_data;
* EntityFactoryQosPolicy entity_factory;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_publisherQos
{
gapi_presentationQosPolicy presentation;
gapi_partitionQosPolicy partition;
gapi_groupDataQosPolicy group_data;
gapi_entityFactoryQosPolicy entity_factory;
}
/*
* struct SubscriberQos {
* PresentationQosPolicy presentation;
* PartitionQosPolicy partition;
* GroupDataQosPolicy group_data;
* EntityFactoryQosPolicy entity_factory;
* ShareQosPolicy share;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_subscriberQos
{
gapi_presentationQosPolicy presentation;
gapi_partitionQosPolicy partition;
gapi_groupDataQosPolicy group_data;
gapi_entityFactoryQosPolicy entity_factory;
gapi_shareQosPolicy share;
}
/*
* struct TopicDataQosPolicy {
* sequence<octet> value;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_topicDataQosPolicy
{
// octetSeq
gapi_Seq value;
}
/* struct DurabilityQosPolicy {
* DurabilityQosPolicyKind kind;
* Duration_t service_cleanup_delay;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_durabilityQosPolicy
{
DurabilityQosPolicyKind kind;
}
/* struct DurabilityServiceQosPolicy {
* HistoryQosPolicyKind history_kind;
* long history_depth;
* long max_samples;
* long max_instances;
* long max_samples_per_instance;
* Duration_t service_cleanup_delay;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_durabilityServiceQosPolicy
{
Duration service_cleanup_delay;
HistoryQosPolicyKind history_kind;
int history_depth;
int max_samples;
int max_instances;
int max_samples_per_instance;
}
/* struct DeadlineQosPolicy {
* Duration_t period;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_deadlineQosPolicy
{
Duration period;
}
/* struct LatencyBudgetQosPolicy {
* Duration_t duration;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_latencyBudgetQosPolicy
{
Duration duration;
}
/* struct LivelinessQosPolicy {
* LivelinessQosPolicyKind kind;
* Duration_t lease_duration;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_livelinessQosPolicy
{
LivelinessQosPolicyKind kind;
Duration lease_duration;
}
/* struct ReliabilityQosPolicy {
* ReliabilityQosPolicyKind kind;
* Duration_t max_blocking_time;
* boolean synchronous;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_reliabilityQosPolicy
{
ReliabilityQosPolicyKind kind;
Duration max_blocking_time;
[MarshalAs(UnmanagedType.U1)]
bool synchronous;
}
/* struct DestinationOrderQosPolicy {
* DestinationOrderQosPolicyKind kind;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_destinationOrderQosPolicy
{
DestinationOrderQosPolicyKind kind;
}
/* struct HistoryQosPolicy {
* HistoryQosPolicyKind kind;
* long depth;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_historyQosPolicy
{
HistoryQosPolicyKind kind;
int depth;
}
/* struct ResourceLimitsQosPolicy {
* long max_samples;
* long max_instances;
* long max_samples_per_instance;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_resourceLimitsQosPolicy
{
int max_samples;
int max_instances;
int max_samples_per_instance;
}
/* struct TransportPriorityQosPolicy {
* long value;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_transportPriorityQosPolicy
{
int value;
}
/* struct LifespanQosPolicy {
* Duration_t duration;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_lifespanQosPolicy
{
Duration duration;
}
/* struct OwnershipQosPolicy {
* OwnershipQosPolicyKind kind;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_ownershipQosPolicy
{
OwnershipQosPolicyKind kind;
}
/*
* struct TopicQos {
* TopicDataQosPolicy topic_data;
* DurabilityQosPolicy durability;
* DeadlineQosPolicy deadline;
* LatencyBudgetQosPolicy latency_budget;
* LivelinessQosPolicy liveliness;
* ReliabilityQosPolicy reliability;
* DestinationOrderQosPolicy destination_order;
* HistoryQosPolicy history;
* ResourceLimitsQosPolicy resource_limits;
* TransportPriorityQosPolicy transport_priority;
* LifespanQosPolicy lifespan;
* OwnershipQosPolicy ownership;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_topicQos
{
gapi_topicDataQosPolicy topic_data;
gapi_durabilityQosPolicy durability;
gapi_durabilityServiceQosPolicy durability_service;
gapi_deadlineQosPolicy deadline;
gapi_latencyBudgetQosPolicy latency_budget;
gapi_livelinessQosPolicy liveliness;
gapi_reliabilityQosPolicy reliability;
gapi_destinationOrderQosPolicy destination_order;
gapi_historyQosPolicy history;
gapi_resourceLimitsQosPolicy resource_limits;
gapi_transportPriorityQosPolicy transport_priority;
gapi_lifespanQosPolicy lifespan;
gapi_ownershipQosPolicy ownership;
}
/* struct TimeBasedFilterQosPolicy {
* Duration_t minimum_separation;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_timeBasedFilterQosPolicy
{
Duration minimum_separation;
}
/*
enum InvalidSampleVisibilityQosPolicyKind {
NO_INVALID_SAMPLES,
MINIMUM_INVALID_SAMPLES,
ALL_INVALID_SAMPLES
};
*/
/* struct InvalidSampleVisibilityQosPolicy {
* InvalidSampleVisibilityQosPolicyKind kind;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_invalidSampleVisibilityQosPolicy
{
InvalidSampleVisibilityQosPolicyKind kind;
}
/* struct ReaderDataLifecycleQosPolicy {
* Duration_t autopurge_nowriter_samples_delay;
* Duration_t autopurge_disposed_samples_delay;
* boolean enable_invalid_samples;
* InvalidSampleVisibilityQosPolicy invalid_sample_visibility;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_readerDataLifecycleQosPolicy
{
Duration autopurge_nowriter_samples_delay;
Duration autopurge_disposed_samples_delay;
[MarshalAs(UnmanagedType.U1)]
bool enable_invalid_samples;
gapi_invalidSampleVisibilityQosPolicy invalid_sample_visibility;
}
/* struct SubscriptionKeyQosPolicy {
* Boolean use_key_list;
* StringSeq key_list;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_subscriptionKeyQosPolicy
{
[MarshalAs(UnmanagedType.U1)]
bool use_key_list;
// string seq
gapi_Seq key_list;
}
/* struct ReaderLifespanQosPolicy {
* Boolean use_lifespan;
* Duration_t duration;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_readerLifespanQosPolicy
{
[MarshalAs(UnmanagedType.U1)]
bool use_lifespan;
Duration duration;
}
/*
* struct DataReaderQos {
* DurabilityQosPolicy durability;
* DeadlineQosPolicy deadline;
* LatencyBudgetQosPolicy latency_budget;
* LivelinessQosPolicy liveliness;
* ReliabilityQosPolicy reliability;
* DestinationOrderQosPolicy destination_order;
* HistoryQosPolicy history;
* ResourceLimitsQosPolicy resource_limits;
* UserDataQosPolicy user_data;
* OwnershipQosPolicy ownership;
* TimeBasedFilterQosPolicy time_based_filter;
* ReaderDataLifecycleQosPolicy reader_data_lifecycle;
* SubscriptionKeyQosPolicy subscription_keys;
* ReaderLifespanQosPolicy reader_lifespan;
* ShareQosPolicy share;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_dataReaderQos
{
gapi_durabilityQosPolicy durability;
gapi_deadlineQosPolicy deadline;
gapi_latencyBudgetQosPolicy latency_budget;
gapi_livelinessQosPolicy liveliness;
gapi_reliabilityQosPolicy reliability;
gapi_destinationOrderQosPolicy destination_order;
gapi_historyQosPolicy history;
gapi_resourceLimitsQosPolicy resource_limits;
gapi_userDataQosPolicy user_data;
gapi_ownershipQosPolicy ownership;
gapi_timeBasedFilterQosPolicy time_based_filter;
gapi_readerDataLifecycleQosPolicy reader_data_lifecycle;
gapi_subscriptionKeyQosPolicy subscription_keys;
gapi_readerLifespanQosPolicy reader_lifespan;
gapi_shareQosPolicy share;
} ;
/* struct OwnershipStrengthQosPolicy {
* long value;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_ownershipStrengthQosPolicy
{
int value;
}
/* struct WriterDataLifecycleQosPolicy {
* boolean autodispose_unregistered_instances;
* Duration_t autopurge_suspended_samples_delay;
* Duration_t autounregister_instance_delay;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_writerDataLifecycleQosPolicy
{
[MarshalAs(UnmanagedType.U1)]
bool autodispose_unregistered_instances;
Duration autopurge_suspended_samples_delay;
Duration autounregister_instance_delay;
}
/*
* struct DataWriterQos {
* DurabilityQosPolicy durability;
* DeadlineQosPolicy deadline;
* LatencyBudgetQosPolicy latency_budget;
* LivelinessQosPolicy liveliness;
* ReliabilityQosPolicy reliability;
* DestinationOrderQosPolicy destination_order;
* HistoryQosPolicy history;
* ResourceLimitsQosPolicy resource_limits;
* TransportPriorityQosPolicy transport_priority;
* LifespanQosPolicy lifespan;
* UserDataQosPolicy user_data;
* OwnershipQosPolicy ownership;
* OwnershipStrengthQosPolicy ownership_strength;
* WriterDataLifecycleQosPolicy writer_data_lifecycle;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_dataWriterQos
{
gapi_durabilityQosPolicy durability;
gapi_deadlineQosPolicy deadline;
gapi_latencyBudgetQosPolicy latency_budget;
gapi_livelinessQosPolicy liveliness;
gapi_reliabilityQosPolicy reliability;
gapi_destinationOrderQosPolicy destination_order;
gapi_historyQosPolicy history;
gapi_resourceLimitsQosPolicy resource_limits;
gapi_transportPriorityQosPolicy transport_priority;
gapi_lifespanQosPolicy lifespan;
gapi_userDataQosPolicy user_data;
gapi_ownershipQosPolicy ownership;
gapi_ownershipStrengthQosPolicy ownership_strength;
gapi_writerDataLifecycleQosPolicy writer_data_lifecycle;
}
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct BuiltinTopicKey
{
public uint SystemId;
public uint LocalId;
public uint Serial;
}
/*
* struct TopicBuiltinTopicData {
* BuiltinTopicKey_t key;
* string name;
* string type_name;
* DurabilityQosPolicy durability;
* DeadlineQosPolicy deadline;
* LatencyBudgetQosPolicy latency_budget;
* LivelinessQosPolicy liveliness;
* ReliabilityQosPolicy reliability;
* TransportPriorityQosPolicy transport_priority;
* LifespanQosPolicy lifespan;
* DestinationOrderQosPolicy destination_order;
* HistoryQosPolicy history;
* ResourceLimitsQosPolicy resource_limits;
* OwnershipQosPolicy ownership;
* TopicDataQosPolicy topic_data;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_topicBuiltinTopicData
{
BuiltinTopicKey key;
IntPtr name;
IntPtr type_name;
gapi_durabilityQosPolicy durability;
gapi_durabilityServiceQosPolicy durability_service;
gapi_deadlineQosPolicy deadline;
gapi_latencyBudgetQosPolicy latency_budget;
gapi_livelinessQosPolicy liveliness;
gapi_reliabilityQosPolicy reliability;
gapi_transportPriorityQosPolicy transport_priority;
gapi_lifespanQosPolicy lifespan;
gapi_destinationOrderQosPolicy destination_order;
gapi_historyQosPolicy history;
gapi_resourceLimitsQosPolicy resource_limits;
gapi_ownershipQosPolicy ownership;
gapi_topicDataQosPolicy topic_data;
IntPtr meta_data;
IntPtr key_list;
}
/*
* struct PublicationBuiltinTopicData {
* BuiltinTopicKey_t key;
* BuiltinTopicKey_t participant_key;
* string topic_name;
* string type_name;
* DurabilityQosPolicy durability;
* DeadlineQosPolicy deadline;
* LatencyBudgetQosPolicy latency_budget;
* LivelinessQosPolicy liveliness;
* ReliabilityQosPolicy reliability;
* LifespanQosPolicy lifespan;
* UserDataQosPolicy user_data;
* OwnershipQosPolicy ownership;
* OwnershipStrengthQosPolicy ownership_strength;
* PresentationQosPolicy presentation;
* PartitionQosPolicy partition;
* TopicDataQosPolicy topic_data;
* GroupDataQosPolicy group_data;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_publicationBuiltinTopicData
{
BuiltinTopicKey key;
BuiltinTopicKey participant_key;
IntPtr topic_name;
IntPtr type_name;
gapi_durabilityQosPolicy durability;
gapi_deadlineQosPolicy deadline;
gapi_latencyBudgetQosPolicy latency_budget;
gapi_livelinessQosPolicy liveliness;
gapi_reliabilityQosPolicy reliability;
gapi_lifespanQosPolicy lifespan;
gapi_destinationOrderQosPolicy destination_order;
gapi_userDataQosPolicy user_data;
gapi_ownershipQosPolicy ownership;
gapi_ownershipStrengthQosPolicy ownership_strength;
gapi_presentationQosPolicy presentation;
gapi_partitionQosPolicy partition;
gapi_topicDataQosPolicy topic_data;
gapi_groupDataQosPolicy group_data;
}
/*
* struct SubscriptionBuiltinTopicData {
* BuiltinTopicKey_t key;
* BuiltinTopicKey_t participant_key;
* string topic_name;
* string type_name;
* DurabilityQosPolicy durability;
* DeadlineQosPolicy deadline;
* LatencyBudgetQosPolicy latency_budget;
* LivelinessQosPolicy liveliness;
* ReliabilityQosPolicy reliability;
* DestinationOrderQosPolicy destination_order;
* UserDataQosPolicy user_data;
* OwnershipQosPolicy ownership;
* TimeBasedFilterQosPolicy time_based_filter;
* PresentationQosPolicy presentation;
* PartitionQosPolicy partition;
* TopicDataQosPolicy topic_data;
* GroupDataQosPolicy group_data;
* };
*/
[StructLayoutAttribute(LayoutKind.Sequential)]
internal struct gapi_subscriptionBuiltinTopicData
{
BuiltinTopicKey key;
BuiltinTopicKey participant_key;
IntPtr topic_name;
IntPtr type_name;
gapi_durabilityQosPolicy durability;
gapi_deadlineQosPolicy deadline;
gapi_latencyBudgetQosPolicy latency_budget;
gapi_livelinessQosPolicy liveliness;
gapi_reliabilityQosPolicy reliability;
gapi_ownershipQosPolicy ownership;
gapi_destinationOrderQosPolicy destination_order;
gapi_userDataQosPolicy user_data;
gapi_timeBasedFilterQosPolicy time_based_filter;
gapi_presentationQosPolicy presentation;
gapi_partitionQosPolicy partition;
gapi_topicDataQosPolicy topic_data;
gapi_groupDataQosPolicy group_data;
}
//typedef struct gapi_readerInfo_s {
// gapi_unsigned_long max_samples;
// gapi_unsigned_long num_samples;
// gapi_copyOut copy_out;
// gapi_copyCache copy_cache;
// gapi_unsigned_long alloc_size;
// gapi_topicAllocBuffer alloc_buffer;
// void *data_buffer;
// void *info_buffer;
// void **loan_registry;
//} gapi_readerInfo;
[StructLayoutAttribute(LayoutKind.Sequential)]
public class gapi_readerInfo
{
public int max_samples;
public int num_samples;
public IntPtr copy_out;
IntPtr copy_cache;
uint alloc_size;
IntPtr alloc_buffer;
public IntPtr data_buffer;
public IntPtr info_buffer;
IntPtr loan_registry;
}
// typedef C_STRUCT(gapi_dataSample) {
// void *data;
// gapi_sampleInfo info;
//} gapi_dataSample;
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct gapi_dataSample
{
public IntPtr data;
public gapi_sampleInfo sampleInfo;
// _NOL_
private IntPtr message;
}
//typedef C_STRUCT(gapi_sampleInfo) {
// gapi_sampleStateKind sample_state;
// gapi_viewStateKind view_state;
// gapi_instanceStateKind instance_state;
// gapi_boolean valid_data;
// gapi_time_t source_timestamp;
// gapi_instanceHandle_t instance_handle;
// gapi_instanceHandle_t publication_handle;
// gapi_long disposed_generation_count;
// gapi_long no_writers_generation_count;
// gapi_long sample_rank;
// gapi_long generation_rank;
// gapi_long absolute_generation_rank;
// gapi_time_t arrival_timestamp;
//} gapi_sampleInfo;
//We have one defined that matches exacly
// in the DdsDcpsStruct.cs
[StructLayoutAttribute(LayoutKind.Sequential)]
public struct gapi_sampleInfo
{
public SampleStateKind sample_state;
public ViewStateKind view_state;
public InstanceStateKind instance_state;
[MarshalAs(UnmanagedType.U1)]
public bool valid_data;
public Time source_timestamp;
public InstanceHandle instance_handle;
public InstanceHandle publication_handle;
public int disposed_generation_count;
public int no_writers_generation_count;
public int sample_rank;
public int generation_rank;
public int absolute_generation_rank;
public Time arrival_timestamp;
}
}
#pragma warning restore 169
|
SanderMertens/opensplice
|
src/api/dcps/sacs/code/DDS/OpenSplice/Gapi/DcpsGapi.cs
|
C#
|
gpl-3.0
| 37,571
|
#include "stdafx.h"
bool t_list_view::is_search_box_open() {return m_search_editbox != NULL;}
void t_list_view::focus_search_box() {if (m_search_editbox) SetFocus(m_search_editbox);}
void t_list_view::show_search_box(const char * label, bool b_focus)
{
if (!m_search_editbox)
{
m_search_editbox = CreateWindowEx(WS_EX_CLIENTEDGE, WC_EDIT, L"" /*pfc::stringcvt::string_os_from_utf8("").get_ptr()*/, WS_CHILD|WS_CLIPSIBLINGS|ES_LEFT|
WS_VISIBLE|WS_CLIPCHILDREN|ES_AUTOHSCROLL|WS_TABSTOP, 0,
0, 0, 0, get_wnd(), HMENU(668), core_api::get_my_instance(), 0);
m_search_label = label;
SetWindowLongPtr(m_search_editbox,GWL_USERDATA,(LPARAM)(this));
m_proc_search_edit = (WNDPROC)SetWindowLongPtr(m_search_editbox,GWL_WNDPROC,(LPARAM)(g_on_search_edit_message));
//SetWindowPos(m_wnd_inline_edit,HWND_TOP,0,0,0,0,SWP_NOMOVE|SWP_NOSIZE);
SendMessage(m_search_editbox, WM_SETFONT, (WPARAM)m_font.get(), MAKELONG(TRUE,0));
SetWindowTheme(m_search_editbox, L"SearchBoxEdit", NULL);
//m_search_box_theme = OpenThemeData(m_search_editbox, L"Edit");
/* COLORREF cr = NULL;
GetThemeColor(m_theme, NULL, NULL, TMT_EDGEHIGHLIGHTCOLOR, &cr);
m_search_box_hot_brush = CreateSolidBrush(cr);
BYTE b = LOBYTE(HIWORD(cr)), g = HIBYTE(LOWORD(cr)), r = LOBYTE(LOWORD(cr));
r-=r/20;
g-=g/20;
b-=b/20;
//r = pfc::rint32(r*0.9);
//g = pfc::rint32(g*0.9);
//b = pfc::rint32(b*0.9);
cr = RGB(r, g, b);
m_search_box_nofocus_brush = CreateSolidBrush(cr);*/
//SendMessage(m_search_editbox, EM_SETMARGINS, EC_LEFTMARGIN, 0);
Edit_SetCueBannerText(m_search_editbox, uT(label));
if (b_focus)
SetFocus(m_search_editbox);
on_size();
#if 0
HTHEME thm = OpenThemeData(m_search_editbox, L"Edit");
t_size i;
for (i=TMT_RESERVEDLOW; i<TMT_RESERVEDHIGH; i++)
{
COLORREF cr = 0;
if (SUCCEEDED(GetThemeColor(thm, EP_BACKGROUND, EBS_NORMAL, i, &cr)) && cr)
console::formatter() << i << " " << (unsigned)GetRValue(cr) << " " << (unsigned)GetGValue(cr) << " " << (unsigned)GetBValue(cr);
cr = 0;
if (SUCCEEDED(GetThemeColor(thm, EP_BACKGROUND, EBS_HOT, i, &cr)) && cr)
console::formatter() << i << " " << (unsigned)GetRValue(cr) << " " << (unsigned)GetGValue(cr) << " " << (unsigned)GetBValue(cr);
cr = 0;
if (SUCCEEDED(GetThemeColor(thm, EP_BACKGROUND, EBS_FOCUSED, i, &cr)) && cr)
console::formatter() << i << " " << (unsigned)GetRValue(cr) << " " << (unsigned)GetGValue(cr) << " " << (unsigned)GetBValue(cr);
}
CloseThemeData(thm);
#endif
}
}
void t_list_view::close_search_box(bool b_notify)
{
if (m_search_editbox)
{
DestroyWindow(m_search_editbox);
m_search_editbox = NULL;
}
/*if (m_search_box_theme)
{
CloseThemeData(m_search_box_theme);
m_search_box_theme = NULL;
}*/
m_search_label.reset();
on_size();
if (b_notify)
notify_on_search_box_close();
}
void t_list_view::get_search_box_rect(LPRECT rc)
{
if (m_search_editbox)
{
GetRelativeRect(m_search_editbox, get_wnd(), rc);
//rc->top -= 2;
//rc->bottom += 2;
}
else
{
GetClientRect(get_wnd(), rc);
rc->top = rc->bottom;
}
}
unsigned t_list_view::get_search_box_height()
{
unsigned ret = 0;
if (m_search_editbox)
{
RECT rc;
get_search_box_rect(&rc);
ret = RECT_CY(rc);
}
return ret;
}
LRESULT WINAPI t_list_view::g_on_search_edit_message(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)
{
t_list_view * p_this;
LRESULT rv;
p_this = reinterpret_cast<t_list_view*>(GetWindowLongPtr(wnd,GWL_USERDATA));
rv = p_this ? p_this->on_search_edit_message(wnd,msg,wp,lp) : DefWindowProc(wnd, msg, wp, lp);;
return rv;
}
LRESULT t_list_view::on_search_edit_message(HWND wnd,UINT msg,WPARAM wp,LPARAM lp)
{
switch(msg)
{
case WM_KILLFOCUS:
break;
case WM_SETFOCUS:
break;
case WM_GETDLGCODE:
//return CallWindowProc(m_proc_search_edit,wnd,msg,wp,lp)|DLGC_WANTALLKEYS;
break;
case WM_KEYDOWN:
switch (wp)
{
case VK_TAB:
{
uie::window::g_on_tab(wnd);
}
//return 0;
break;
case VK_ESCAPE:
close_search_box();
//notify_on_search_box_close();
return 0;
case VK_RETURN:
return 0;
}
break;
case WM_MOUSEMOVE:
{
POINT pt = {GET_X_LPARAM(lp), GET_Y_LPARAM(lp)};
__search_box_update_hot_status(pt);
}
break;
#if 0
case WM_PAINT:
{
PAINTSTRUCT ps;
HDC dc = BeginPaint(wnd, &ps);
RECT rc;
GetClientRect(m_search_editbox, &rc);
HTHEME thm = OpenThemeData(m_search_editbox, L"SearchBox");//SearchBox
t_size step = rc.right/10;
t_size i;
for (i=0; i<10; i++)
{
rc.left = i*step;
rc.right = (i+1)*step;
FillRect(dc, &rc, GetSysColorBrush(COLOR_3DLIGHT));
DrawThemeBackground(thm, (HDC)dc, 1, i, &rc, NULL);
}
CloseThemeData(thm);
EndPaint(wnd, &ps);
}
return 0;
#endif
}
return CallWindowProc(m_proc_search_edit,wnd,msg,wp,lp);
}
void t_list_view::__search_box_update_hot_status(const POINT & pt)
{
POINT pts = pt;
MapWindowPoints(get_wnd(), HWND_DESKTOP, &pts, 1);
bool b_in_wnd = WindowFromPoint(pts) == m_search_editbox;
bool b_focused = GetFocus() == m_search_editbox;
bool b_new_hot = b_in_wnd && !b_focused;
if (m_search_box_hot != b_new_hot)
{
m_search_box_hot = b_new_hot;
if (m_search_box_hot)
SetCapture(m_search_editbox);
else if (GetCapture() == m_search_editbox)
ReleaseCapture();
RedrawWindow(m_search_editbox, NULL, NULL, RDW_INVALIDATE|RDW_ERASE|RDW_UPDATENOW|RDW_ERASENOW);
}
}
|
samithaj/columns_ui
|
foobar2000/ui_helpers/List View/list_view_search.cpp
|
C++
|
gpl-3.0
| 5,388
|
package moe.ahao.spring.boot.dependency;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import java.util.concurrent.CountDownLatch;
@Service
public class TestService {
private static final Logger logger = LoggerFactory.getLogger(TestService.class);
@Async
public void async(CountDownLatch latch) {
logger.trace("async trace");
logger.debug("async debug");
logger.info("async info");
logger.warn("async warn");
logger.error("async error");
latch.countDown();
}
}
|
Ahaochan/invoice
|
ahao-spring-boot-log-trace/src/test/java/moe/ahao/spring/boot/dependency/TestService.java
|
Java
|
gpl-3.0
| 643
|
'''
Created on Mar 20, 2011
@author: frederikns
'''
from model.flyweight import Flyweight
from collections import namedtuple
from model.static.database import database
from model.dynamic.inventory.item import Item
class SchematicTypeMap(Flyweight):
def __init__(self,schematic_id):
#prevents reinitializing
if "_inited" in self.__dict__:
return
self._inited = None
#prevents reinitializing
self.schematic_id = schematic_id
cursor = database.get_cursor(
"select * from planetSchematicTypeMap where schematicID={};".format(self.schematic_id))
types = list()
schematic_type = namedtuple("schematic_type", "item, is_input")
for row in cursor:
types.append(schematic_type(
item=Item(row["typeID"], row["quantity"]),
is_input=(row["isInput"])))
cursor.close()
|
Iconik/eve-suite
|
src/model/static/planet/schematic_type_map.py
|
Python
|
gpl-3.0
| 914
|
/*
* Copyright (c) 2018 Amir Czwink (amir130@hotmail.de)
*
* This file is part of Std++.
*
* Std++ is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Std++ 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 Std++. If not, see <http://www.gnu.org/licenses/>.
*/
//Global
extern "C"
{
#include <libavcodec/avcodec.h>
}
//Local
#include <Std++/Multimedia/Parser.hpp>
#include "../../../src/Multimedia/CodingFormatIdMap.hpp"
namespace _stdxx_
{
class libavcodec_Parser : public StdXX::Multimedia::Parser
{
public:
//Constructor
inline libavcodec_Parser(const CodingFormatIdMap<AVCodecID> &libavCodecIdMap, StdXX::Multimedia::CodingFormatId codingFormatId, AVCodecID libavCodecId) :
codingFormatId(codingFormatId), libavCodecId(libavCodecId), libavCodecIdMap(libavCodecIdMap)
{
AVCodecParserContext *parserContext = av_parser_init(libavCodecId);
this->parser = parserContext->parser;
av_parser_close(parserContext);
}
//Methods
StdXX::Multimedia::ParserContext * CreateContext(StdXX::Multimedia::Stream& stream) const override;
StdXX::FixedArray<StdXX::Multimedia::CodingFormatId> GetCodingFormatIds() const override;
private:
//Members
StdXX::Multimedia::CodingFormatId codingFormatId;
AVCodecID libavCodecId;
const CodingFormatIdMap<AVCodecID> &libavCodecIdMap;
AVCodecParser *parser;
};
}
|
aczwink/ACStdLib
|
src_backends/ffmpeg/codec/libavcodec_Parser.hpp
|
C++
|
gpl-3.0
| 1,776
|
/*
* File: Physical.h
* Author: jsmtux
*
* Created on December 18, 2012, 2:16 PM
*/
#ifndef PHYSICAL_H
#define PHYSICAL_H
#include "../../ProjectManagement/MXML.h"
#include "Math/Vector3.h"
#include "Resources/Resource.h"
#include <map>
class Timer;
enum tShape{S_BOX,S_SPHERE,S_CAPSULE,S_UNIMPLEMENTED};
class Physical{
public:
Physical();
Physical(MXML::Tag &code);
Physical(string dir);
btRigidBody* toRigidBody();
void fromXML(MXML::Tag &code);
MXML::Tag toXML();
void setMass(float m){mass=m;}
void setRestitution(float r){restitution=r;}
void setFriction(float f){friction=f;}
void setAngularFriction(float a){angularFriction=a;}
float getMass(){return mass;}
float getRestitution(){return restitution;}
float getFriction(){return friction;}
float getAngularFriction(){return angularFriction;}
void addShape(Vector3 size, Vector3 offset, tShape category);
void setContactResponse(bool responds);
bool getContactResponse();
private:
float mass;
float restitution;
float friction;
float angularFriction;
bool contactResponse=true;
struct ShapeDefinition{
ShapeDefinition(){};
ShapeDefinition(Vector3 size, Vector3 offset, tShape shape):size(size), offset(offset), shapeCategory(shape){};
Vector3 size;
Vector3 offset;
tShape shapeCategory;
btCollisionShape* toShape(){
switch(shapeCategory){
case S_SPHERE:
return new btSphereShape(size.x);
break;
case S_BOX:
return new btBoxShape(size);
break;
case S_CAPSULE:
return new btCapsuleShape(size.x,size.y);
}
}
};
vector<ShapeDefinition> shape;
};
#endif /* PHYSICAL_H */
|
jsmtux/Op3nD
|
src/Engine/ObjectTypes/Physical.h
|
C
|
gpl-3.0
| 1,716
|
package pattern;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class Engine implements Component {
private static Engine instance = new Engine();
private List<Entity> entities = new ArrayList<>();
private List<Entity> entitiesToAdd = new ArrayList<>();
private List<Entity> entitiesToRemove = new ArrayList<>();
private Map<Class<? extends Component>, List<Component>> components = new HashMap<>();
private ArrayDeque<Event> eventsToProcess = new ArrayDeque<>();
private List<Event> eventsToProcessNextTurn = new ArrayList<>();
public static boolean DEBUG = false;
private Engine() {
}
public <E extends Entity> void addEntity(E entity) {
entitiesToAdd.add(entity);
}
public <E extends Entity> void addEntities(List<E> entityList) {
entitiesToAdd.addAll(entityList);
}
public void updateEntity(Entity entity) {
for(Component component : entity) {
if(components.containsKey(component.getClass())) {
if(!components.get(component.getClass()).contains(component)) {
components.get(component.getClass()).add(component);
}
}
else {
ArrayList<Component> listComponents = new ArrayList<>();
listComponents.add(component);
components.put(component.getClass(), listComponents);
}
}
}
public void addHeadEvent(Event event) {
eventsToProcess.addFirst(event);
}
public void addTailEvent(Event event) {
eventsToProcess.addLast(event);
}
public void addNextTurnEvent(Event event) {
eventsToProcessNextTurn.add(event);
}
public void removeEntity(Entity entity) {
entitiesToRemove.add(entity);
}
public void removeEntitiesByComponentClass(Class<? extends Component> component) {
List<Entity> entitiesOfComponentClass = new ArrayList<>();
for(Entity entity : entities) {
for(Component c : entity) {
if(component.isAssignableFrom(c.getClass())) {
entitiesOfComponentClass.add(entity);
}
}
}
entitiesToRemove.addAll(entitiesOfComponentClass);
}
public Entity getEntityByComponent(Component component) {
for(Entity entity : entities) {
for(Component c : entity) {
if(c == component) {
return entity;
}
}
}
return null;
}
public Entity getEntityByComponentClass(Class<? extends Component> component) {
for(Entity entity : entities) {
for(Component c : entity) {
if(component.isAssignableFrom(c.getClass())) {
return entity;
}
}
}
return null;
}
public List<Entity> getEntitiesByComponentClass(Class<? extends Component> component) {
List<Entity> entitiesOfComponentClass = new ArrayList<>();
for(Entity entity : entities) {
for(Component c : entity) {
if(component.isAssignableFrom(c.getClass())) {
entitiesOfComponentClass.add(entity);
}
}
}
return entitiesOfComponentClass;
}
@Override
public void process(Event event, double deltaTime) {
if(DEBUG) {
System.out.println("---");
}
updateListsEngine();
for(Event e : eventsToProcessNextTurn) {
eventsToProcess.addFirst(e);
}
eventsToProcessNextTurn.clear();
while(!eventsToProcess.isEmpty()) {
Event nextEvent = eventsToProcess.pollFirst();
if(DEBUG) {
System.out.println(nextEvent.getClass().getName());
}
if(nextEvent instanceof EntityComponentEvent) {
EntityComponentEvent nextEntityComponentEvent = (EntityComponentEvent)nextEvent;
for(Component c : nextEntityComponentEvent.getEntity()) {
if(nextEntityComponentEvent.getComponent().isInstance(c)) {
c.process(nextEntityComponentEvent, deltaTime);
}
}
}
else if(nextEvent instanceof ComponentEvent) {
ComponentEvent nextComponentEvent = (ComponentEvent)nextEvent;
for(Entry<Class<? extends Component>, List<Component>> entry : components.entrySet()) {
if(nextComponentEvent.getComponent().isAssignableFrom(entry.getKey())) {
for(Component c : entry.getValue()) {
c.process(nextComponentEvent, deltaTime);
}
}
}
}
}
updateListsEngine();
}
private void updateListsEngine() {
for(Entity entity : entitiesToRemove) {
for(Component component : entity) {
if(components.containsKey(component.getClass())) {
components.get(component.getClass()).remove(component);
}
}
}
entities.removeAll(entitiesToRemove);
entitiesToRemove.clear();
for(Entity entity : entitiesToAdd) {
for(Component component : entity) {
if(components.containsKey(component.getClass())) {
components.get(component.getClass()).add(component);
}
else {
ArrayList<Component> listComponents = new ArrayList<>();
listComponents.add(component);
components.put(component.getClass(), listComponents);
}
}
}
entities.addAll(entitiesToAdd);
entitiesToAdd.clear();
}
public static Engine getInstance() {
return instance;
}
}
|
julianmaster/TinyRL
|
src/pattern/Engine.java
|
Java
|
gpl-3.0
| 4,930
|
---
layout: politician2
title: barkuwar gagrai
profile:
party: BJP
constituency: Singhbhum
state: Jharkhand
education:
level: Graduate
details: ranchi university
photo:
sex:
caste:
religion:
current-office-title:
crime-accusation-instances: 1
date-of-birth: 1969
profession:
networth:
assets: 6,91,735
liabilities: 1,17,349
pan:
twitter:
website:
youtube-interview:
wikipedia:
candidature:
- election: Lok Sabha 2009
myneta-link: http://myneta.info/ls2009/candidate.php?candidate_id=4316
affidavit-link: http://myneta.info/candidate.php?candidate_id=4316&scan=original
expenses-link:
constituency: Singhbhum
party: BJP
criminal-cases: 1
assets: 6,91,735
liabilities: 1,17,349
result:
crime-record:
- crime: accussed
ipc:
details: "138 N.I. ACT"
date: 2014-01-28
version: 0.0.5
tags:
---
##Summary
##Education
{% include "education.html" %}
##Political Career
{% include "political-career.html" %}
##Criminal Record
{% include "criminal-record.html" %}
##Personal Wealth
{% include "personal-wealth.html" %}
##Public Office Track Record
{% include "track-record.html" %}
##References
{% include "references.html" %}
|
vaibhavb/wisevoter
|
site/politicians/_posts/2013-12-18-barkuwar-gagrai.md
|
Markdown
|
gpl-3.0
| 1,254
|
/////////////////////////////////////////////////////////////////////////////
//
// Project ProjectForge Community Edition
// www.projectforge.org
//
// Copyright (C) 2001-2014 Kai Reinhard (k.reinhard@micromata.de)
//
// ProjectForge is dual-licensed.
//
// This community edition 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 3 of the License.
//
// This community edition is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
// Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program; if not, see http://www.gnu.org/licenses/.
//
/////////////////////////////////////////////////////////////////////////////
package org.projectforge.web;
import static org.testng.AssertJUnit.assertEquals;
import static org.testng.AssertJUnit.assertNull;
import org.projectforge.business.utils.HtmlHelper;
import org.testng.annotations.Test;
public class HtmlHelperTest
{
@Test
public void testAttribute()
{
assertEquals(" hallo=\"test\"", HtmlHelper.attribute("hallo", "test"));
}
@Test
public void testAppendAncorOnClickSubmitEventStartTag()
{
StringBuffer buf = new StringBuffer();
HtmlHelper.appendAncorOnClickSubmitEventStartTag(buf, "submitEvent", "select.task");
assertEquals("<a href=\"#\" onclick=\"javascript:submitEvent('select.task')\">", buf.toString());
buf = new StringBuffer();
HtmlHelper.appendAncorOnClickSubmitEventStartTag(buf, "submitSelectedEvent", "selectTask", "4");
assertEquals("<a href=\"#\" onclick=\"javascript:submitSelectedEvent('selectTask', '4')\">", buf.toString());
}
@Test
public void testFormatText()
{
assertEquals("", HtmlHelper.formatText(null, true));
assertEquals("", HtmlHelper.formatText("", true));
assertEquals("<br/>", HtmlHelper.formatText("\n", true));
assertEquals(" ", HtmlHelper.formatText("\t ", true));
assertEquals(
"Name: Reinhard<br/>Vorname: Kai<br/>Test ",
HtmlHelper.formatText("Name:\tReinhard\r\nVorname:\tKai\nTest ", true));
}
@Test
public void escapeHtml()
{
assertNull(HtmlHelper.escapeHtml(null, true));
assertNull(HtmlHelper.escapeHtml(null, false));
assertEquals("", HtmlHelper.escapeHtml("", true));
assertEquals("", HtmlHelper.escapeHtml("", false));
assertEquals("Stéphanie<<br/>\n", HtmlHelper.escapeHtml("Stéphanie<\n", true));
assertEquals("Stéphanie<\n", HtmlHelper.escapeHtml("Stéphanie<\n", false));
assertEquals("Stéphanie<<br/>\nGermany", HtmlHelper.escapeHtml("Stéphanie<\nGermany", true));
assertEquals("Stéphanie<\nGermany", HtmlHelper.escapeHtml("Stéphanie<\nGermany", false));
assertEquals("Stéphanie<<br/>\r\n", HtmlHelper.escapeHtml("Stéphanie<\r\n", true));
assertEquals("Stéphanie<\r\n", HtmlHelper.escapeHtml("Stéphanie<\r\n", false));
assertEquals("Test\nStéphanie<<br/>\r\nGermany",
HtmlHelper.escapeHtml("Test\nStéphanie<\r\nGermany", true));
assertEquals("Stéphanie<\r\nGermany", HtmlHelper.escapeHtml("Stéphanie<\r\nGermany", false));
}
}
|
FlowsenAusMonotown/projectforge
|
projectforge-business/src/test/java/org/projectforge/web/HtmlHelperTest.java
|
Java
|
gpl-3.0
| 3,553
|
<!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.6.0_18) on Fri Apr 06 23:09:18 CEST 2012 -->
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<TITLE>
com.googlecode.fspotcloud.shared.main.actions Class Hierarchy (F-Spot Cloud Java Edition 0.12-beta Test API)
</TITLE>
<META NAME="date" CONTENT="2012-04-06">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="com.googlecode.fspotcloud.shared.main.actions Class Hierarchy (F-Spot Cloud Java Edition 0.12-beta Test API)";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= 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="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../com/googlecode/fspotcloud/shared/admin/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../../com/googlecode/fspotcloud/shared/peer/rpc/actions/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/googlecode/fspotcloud/shared/main/actions/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.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>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<HR>
<CENTER>
<H2>
Hierarchy For Package com.googlecode.fspotcloud.shared.main.actions
</H2>
</CENTER>
<DL>
<DT><B>Package Hierarchies:</B><DD><A HREF="../../../../../../overview-tree.html">All Packages</A></DL>
<HR>
<H2>
Class Hierarchy
</H2>
<UL>
<LI TYPE="circle">java.lang.<A HREF="http://download.oracle.com/javase/6/docs/api/java/lang/Object.html?is-external=true" title="class or interface in java.lang"><B>Object</B></A><UL>
<LI TYPE="circle">junit.framework.Assert<UL>
<LI TYPE="circle">junit.framework.TestCase (implements junit.framework.Test)
<UL>
<LI TYPE="circle">com.googlecode.fspotcloud.shared.main.actions.<A HREF="../../../../../../com/googlecode/fspotcloud/shared/main/actions/UserInfoTest.html" title="class in com.googlecode.fspotcloud.shared.main.actions"><B>UserInfoTest</B></A></UL>
</UL>
</UL>
</UL>
<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="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT> </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>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../com/googlecode/fspotcloud/shared/admin/package-tree.html"><B>PREV</B></A>
<A HREF="../../../../../../com/googlecode/fspotcloud/shared/peer/rpc/actions/package-tree.html"><B>NEXT</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../../index.html?com/googlecode/fspotcloud/shared/main/actions/package-tree.html" target="_top"><B>FRAMES</B></A>
<A HREF="package-tree.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>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<HR>
Copyright © 2012. All Rights Reserved.
</BODY>
</HTML>
|
slspeek/FSpotCloudSite
|
testapidocs/com/googlecode/fspotcloud/shared/main/actions/package-tree.html
|
HTML
|
gpl-3.0
| 6,937
|
var loggedInUserInfo;
function setupMenu() {
jQuery.ajaxSetup({async:false});
$.get('/adoration/getLoggedInUserInfo', function(data) {
loggedInUserInfo = data.loggedInUserInfo;
if (loggedInUserInfo.isLoggedIn) {
$("#loggedInUserLegend").text("Belépve: " + loggedInUserInfo.loggedInUserName);
$("#nav-information").show();
$("#nav-exit").show();
} else {
$("#loggedInUserLegend").text("");
$("#nav-login").show();
}
if (loggedInUserInfo.isRegisteredAdorator) {
$("#nav-ador-list").show();
} else {
$("#nav-ador-registration").show();
}
if (loggedInUserInfo.isAdoratorAdmin) {
$("#nav-application-log").show();
}
});
jQuery.ajaxSetup({async:true});
}
function getReadableLanguageCode(code) {
var z;
switch (code) {
case "hu": z = 'magyar'; break;
case "en": z = 'angol'; break;
case "it": z = 'olasz'; break;
case "es": z = 'spanyol'; break;
case "fr": z = 'francia'; break;
case "ge": z = 'német'; break;
default: z = '???';
}
return z;
}
function validateEmail(email) {
var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; //NOSONAR
return re.test(String(email).toLowerCase());
}
function findGetParameter(parameterName) {
var result = null,
tmp = [];
var items = location.search.substr(1).split("&");
for (var index = 0; index < items.length; index++) {
tmp = items[index].split("=");
if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
}
return result;
}
function getDayNameLocalized(hourId, dayNames) {
var x = getDay(hourId);
return dayNames[x];
}
function getDayName(hourId) {
var dayNames = ['vasárnap', 'hétfő', 'kedd', 'szerda', 'csütörtök', 'péntek', 'szombat']
var x = getDay(hourId);
return dayNames[x];
}
/**
* Get Day ID (0..6) from hourID.
*/
function getDay(hourId) {
var x = Math.floor(hourId / 24);
return x;
}
function getHourName(hourId) {
return hourId % 24;
}
function getPerson(list, personId) {
for (var i = 0; i < list.length; i++) {
if (list[i].id == personId) {
return list[i];
}
}
return null;
}
function getCoordinator(list, hourInDayId) {
for (var i = 0; i < list.length; i++) {
if (parseInt(list[i].coordinatorType) == hourInDayId) {
return list[i];
}
}
return null;
}
//replacing alert
var alertModal;
var alertSpan;
var alertAfterCloseFunction;
function showAlert(title, message, afterCloseFunction) {
$("#commonAlertTitle").text(title);
$("#commonAlertBody").text(message);
alertModal = document.getElementById("commonAlertModal");
alertSpan = document.getElementsByClassName("commonAlertClose")[0];
alertAfterCloseFunction = afterCloseFunction;
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == alertModal) {
hideAlert();
}
}
alertModal.style.display="block";
}
function hideAlert() {
alertModal.style.display="none";
if (typeof alertAfterCloseFunction != "undefined") {
alertAfterCloseFunction();
}
}
//replacing confirm
var confirmModal;
var confirmSpan;
var confirmAfterCloseFunctionOk;
var confirmAfterCloseFunctionCancel;
function showConfirm(title, message, afterCloseFunctionOk, afterCloseFunctionCancel) {
$("#commonConfirmTitle").text(title);
$("#commonConfirmBody").text(message);
confirmModal = document.getElementById("commonConfirmModal");
confirmSpan = document.getElementsByClassName("commonConfirmClose")[0];
confirmAfterCloseFunctionOk = afterCloseFunctionOk;
confirmAfterCloseFunctionCancel = afterCloseFunctionCancel;
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == confirmModal) {
hideConfirmCancel();
}
}
confirmModal.style.display="block";
}
function hideConfirmCancel() {
confirmModal.style.display="none";
if (typeof confirmAfterCloseFunctionCancel != "undefined") {
confirmAfterCloseFunctionCancel();
}
}
function hideConfirmOk() {
confirmModal.style.display="none";
if (typeof confirmAfterCloseFunctionOk != "undefined") {
confirmAfterCloseFunctionOk();
}
}
function reloadLocation() {
location.reload();
}
|
tkohegyi/adoration
|
adoration-application/modules/adoration-webapp/src/main/resources/webapp/resources/js/common.js
|
JavaScript
|
gpl-3.0
| 4,661
|
<?php
/*************************
Coppermine Photo Gallery
************************
Copyright (c) 2003-2016 Coppermine Dev Team
v1.0 originally written by Gregory Demar
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 3
as published by the Free Software Foundation.
********************************************
Coppermine version: 1.6.03
$HeadURL$
**********************************************/
$base = array(
0x00 => 'Yan ', 'Yan ', 'Ding ', 'Fu ', 'Qiu ', 'Qiu ', 'Jiao ', 'Hong ', 'Ji ', 'Fan ', 'Xun ', 'Diao ', 'Hong ', 'Cha ', 'Tao ', 'Xu ',
0x10 => 'Jie ', 'Yi ', 'Ren ', 'Xun ', 'Yin ', 'Shan ', 'Qi ', 'Tuo ', 'Ji ', 'Xun ', 'Yin ', 'E ', 'Fen ', 'Ya ', 'Yao ', 'Song ',
0x20 => 'Shen ', 'Yin ', 'Xin ', 'Jue ', 'Xiao ', 'Ne ', 'Chen ', 'You ', 'Zhi ', 'Xiong ', 'Fang ', 'Xin ', 'Chao ', 'She ', 'Xian ', 'Sha ',
0x30 => 'Tun ', 'Xu ', 'Yi ', 'Yi ', 'Su ', 'Chi ', 'He ', 'Shen ', 'He ', 'Xu ', 'Zhen ', 'Zhu ', 'Zheng ', 'Gou ', 'Zi ', 'Zi ',
0x40 => 'Zhan ', 'Gu ', 'Fu ', 'Quan ', 'Die ', 'Ling ', 'Di ', 'Yang ', 'Li ', 'Nao ', 'Pan ', 'Zhou ', 'Gan ', 'Yi ', 'Ju ', 'Ao ',
0x50 => 'Zha ', 'Tuo ', 'Yi ', 'Qu ', 'Zhao ', 'Ping ', 'Bi ', 'Xiong ', 'Qu ', 'Ba ', 'Da ', 'Zu ', 'Tao ', 'Zhu ', 'Ci ', 'Zhe ',
0x60 => 'Yong ', 'Xu ', 'Xun ', 'Yi ', 'Huang ', 'He ', 'Shi ', 'Cha ', 'Jiao ', 'Shi ', 'Hen ', 'Cha ', 'Gou ', 'Gui ', 'Quan ', 'Hui ',
0x70 => 'Jie ', 'Hua ', 'Gai ', 'Xiang ', 'Wei ', 'Shen ', 'Chou ', 'Tong ', 'Mi ', 'Zhan ', 'Ming ', 'E ', 'Hui ', 'Yan ', 'Xiong ', 'Gua ',
0x80 => 'Er ', 'Beng ', 'Tiao ', 'Chi ', 'Lei ', 'Zhu ', 'Kuang ', 'Kua ', 'Wu ', 'Yu ', 'Teng ', 'Ji ', 'Zhi ', 'Ren ', 'Su ', 'Lang ',
0x90 => 'E ', 'Kuang ', 'E ', 'Shi ', 'Ting ', 'Dan ', 'Bo ', 'Chan ', 'You ', 'Heng ', 'Qiao ', 'Qin ', 'Shua ', 'An ', 'Yu ', 'Xiao ',
0xA0 => 'Cheng ', 'Jie ', 'Xian ', 'Wu ', 'Wu ', 'Gao ', 'Song ', 'Pu ', 'Hui ', 'Jing ', 'Shuo ', 'Zhen ', 'Shuo ', 'Du ', 'Yasashi ', 'Chang ',
0xB0 => 'Shui ', 'Jie ', 'Ke ', 'Qu ', 'Cong ', 'Xiao ', 'Sui ', 'Wang ', 'Xuan ', 'Fei ', 'Chi ', 'Ta ', 'Yi ', 'Na ', 'Yin ', 'Diao ',
0xC0 => 'Pi ', 'Chuo ', 'Chan ', 'Chen ', 'Zhun ', 'Ji ', 'Qi ', 'Tan ', 'Zhui ', 'Wei ', 'Ju ', 'Qing ', 'Jian ', 'Zheng ', 'Ze ', 'Zou ',
0xD0 => 'Qian ', 'Zhuo ', 'Liang ', 'Jian ', 'Zhu ', 'Hao ', 'Lun ', 'Shen ', 'Biao ', 'Huai ', 'Pian ', 'Yu ', 'Die ', 'Xu ', 'Pian ', 'Shi ',
0xE0 => 'Xuan ', 'Shi ', 'Hun ', 'Hua ', 'E ', 'Zhong ', 'Di ', 'Xie ', 'Fu ', 'Pu ', 'Ting ', 'Jian ', 'Qi ', 'Yu ', 'Zi ', 'Chuan ',
0xF0 => 'Xi ', 'Hui ', 'Yin ', 'An ', 'Xian ', 'Nan ', 'Chen ', 'Feng ', 'Zhu ', 'Yang ', 'Yan ', 'Heng ', 'Xuan ', 'Ge ', 'Nuo ', 'Qi ',
);
|
coppermine-gallery/cpg1.6.x
|
include/transliteration/x8a.php
|
PHP
|
gpl-3.0
| 2,753
|
package com.alonsoruibal.chess;
import com.alonsoruibal.chess.bitboard.BitboardUtils;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class BitBoardUtilsTest {
@Test
public void testHorizontalLine() {
assertEquals((1L << 7) | (1L << 6) | (1L << 5), BitboardUtils.getHorizontalLine((1L << 7), (1L << 5)));
assertEquals((1L << 63) | (1L << 62) | (1L << 61) | (1L << 60), BitboardUtils.getHorizontalLine((1L << 63), (1L << 60)));
}
@Test
public void testLsb() {
assertEquals((1L), BitboardUtils.lsb(1L));
assertEquals((1L << 63), BitboardUtils.lsb(1L << 63));
assertEquals((1L << 32), BitboardUtils.lsb((1L << 63) | 1L << 32));
assertEquals(1L, BitboardUtils.lsb((1L << 32) | 1L));
assertEquals(0, BitboardUtils.lsb(0));
}
@Test
public void testMsb() {
assertEquals((1L), BitboardUtils.msb(1L));
assertEquals((1L << 63), BitboardUtils.msb(1L << 63));
assertEquals((1L << 63), BitboardUtils.msb((1L << 63) | 1L << 32));
assertEquals((1L << 32), BitboardUtils.msb((1L << 32) | 1L));
assertEquals(0, BitboardUtils.msb(0));
}
}
|
albertoruibal/carballo
|
jse/src/test/java/com/alonsoruibal/chess/BitBoardUtilsTest.java
|
Java
|
gpl-3.0
| 1,088
|
/*--
SSH.java - Created in July 2009
Copyright (c) 2009-2011 Flavio Miguel ABREU ARAUJO.
Université catholique de Louvain, Louvain-la-Neuve, Belgium
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 disclaimer that follows
these conditions in the documentation and/or other materials
provided with the distribution.
3. The names of the author may not be used to endorse or promote
products derived from this software without specific prior written
permission.
In addition, we request (but do not require) that you include in the
end-user documentation provided with the redistribution and/or in the
software itself an acknowledgement equivalent to the following:
"This product includes software developed by the
Abinit Project (http://www.abinit.org/)."
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 JDOM AUTHORS OR THE PROJECT
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.
For more information on the Abinit Project, please see
<http://www.abinit.org/>.
*/
package abinitgui;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Vector;
import javax.swing.JTextArea;
//@SuppressWarnings({"deprecation","unchecked"})
public class SSH {
private InputStream in;
private OutputStream out;
public Channel channel;
public Session session;
private String userAndHost = null;
private String password = null;
private JTextArea outputTA;
private OutputHandler sshOH;
private Vector cmds = new Vector();
private String retMSG = "";
private SSHExecOutput sshEO;
boolean console = false;
private int sshPort = 22;
private static boolean DEBUG = false;
private DisplayerJDialog dialog;
private boolean graphical = false;
public void setDialog(DisplayerJDialog dialog) {
graphical = true;
this.dialog = dialog;
}
void printOUT(String str) {
if (graphical) {
if (str.endsWith("\n")) {
dialog.appendOUT(str);
} else {
dialog.appendOUT(str + "\n");
}
} else {
if (str.endsWith("\n")) {
System.out.print(str);
} else {
System.out.println(str);
}
}
}
void printERR(String str) {
if (graphical) {
if (str.endsWith("\n")) {
dialog.appendERR(str);
} else {
dialog.appendERR(str + "\n");
}
} else {
if (str.endsWith("\n")) {
System.err.print(str);
} else {
System.err.println(str);
}
}
}
void printDEB(String str) {
if (graphical) {
if (str.endsWith("\n")) {
dialog.appendDEB(str);
} else {
dialog.appendDEB(str + "\n");
}
} else {
if (str.endsWith("\n")) {
System.out.print(str);
} else {
System.out.println(str);
}
}
}
public SSH(JTextArea outputTA) {
this(outputTA, false);
}
public SSH(JTextArea outputTA, boolean console) {
this.outputTA = outputTA;
this.console = console;
}
public void setUserAndHost(String userAndHost) {
this.userAndHost = userAndHost;
}
public void setPassword(String password) {
this.password = password;
}
public void setPort(int port) {
this.sshPort = port;
}
/*synchronized*/ public void sendCommand(String cmd) {
if (console) {
try {
cmd += '\n';
out.write(cmd.getBytes(), 0, cmd.length());
out.flush();
} catch (Exception e) {
printERR(e.getMessage());
}
} else {
if (cmd.startsWith("ls")) {
cmd += " --color=never";
}
if (cmd.startsWith("exec") || cmd.startsWith("EXEC")) {
// cette commande n'est pas gérée
outputTA.append("Command [" + cmd + "] not supported by ABINIT GUI !\n");
return;
}
if (cmd.equals("vi") || cmd.equals("VI")) {
// cette commande n'est pas gérée
outputTA.append("Command [" + cmd + "] not supported by ABINIT GUI !\n");
return;
}
if (cmd.equals("vim") || cmd.equals("VIM")) {
// cette commande n'est pas gérée
outputTA.append("Command [" + cmd + "] not supported by ABINIT GUI !\n");
return;
}
if (cmds.add(cmd)) {
//printOUT("Command [" + cmd + "] successfuly registred.");
} else {
printERR("Could not register the command: " + cmd);
}
}
}
public boolean start() {
try {
if (DEBUG) {
JSch.setLogger(new MyLogger());
}
JSch jsch = new JSch();
String user = userAndHost.substring(0, userAndHost.indexOf('@'));
String host = userAndHost.substring(userAndHost.indexOf('@') + 1);
session = jsch.getSession(user, host, sshPort);
// username and password will be given via UserInfo interface.
UserInfo ui = new MyUserInfo();
((MyUserInfo) ui).setPassword(password);
session.setUserInfo(ui);
session.connect();
channel = session.openChannel("shell");
//((ChannelShell) channel).setXForwarding(true); // XForwarding
out = channel.getOutputStream();
in = channel.getInputStream();
if (console) {
sshEO = new SSHExecOutput(in);
} else {
sshOH = new OutputHandler();
sshOH.start();
}
channel.connect();
if (session.isConnected() && channel.isConnected()) {
return true;
} else {
return false;
}
} catch (com.jcraft.jsch.JSchException e) {
String msg = e.getMessage();
if (e.getCause() != null) {
String msg2 = msg.substring(0, msg.indexOf(':'));
String msg3 = e.getCause().getMessage();
if (msg2.equals("java.net.UnknownHostException")) {
printERR("Unknown hostname: " + msg3);
} else {
printERR("Exception: " + msg2);
}
} else {
if (msg.equals("Auth fail")) {
printERR("Username or password is wrong !!");
} else {
printERR("JSchException => MSG: " + msg);
}
}
return false;
} catch (Exception e) {
printERR(e.getMessage());
return false;
}
}
public void stop() {
if (console) {
if(channel != null && session != null) sendCommand("exit");
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
if (sshEO != null) {
sshEO.stop();
}
} else {
new ClosureWatcher().start();
}
}
public boolean isConnected() {
if(channel.isConnected()) {
return session.isConnected();
} else {
return false;
}
}
public class OutputHandler extends Thread {
//private String lastCMD = "";
@Override
public void run() {
String msg = null;
byte[] buf = new byte[1024];
int i = 0;
try {
while (true) {
msg = "";
do {
int b = in.read();
//outputTA.append("[" + b + "-" + (char) b + "]\n");
if (b == -1) {
//OutputTA.append("code de retour [" + b + "]\n");
} else if (b == 0) {
outputTA.append("[" + b + "] SUCCES\n");
} else if (b == 1) {
outputTA.append("[" + b + "] ERROR\n");
} else if (b == 2) {
outputTA.append("[" + b + "] FATAL ERROR\n");
}
i = in.read(buf, 0, 1024);
if (i <= 0) {
break;
} else {
byte[] tmp = new byte[i];
for (int k = 0; k < i; k++) {
tmp[k] = buf[k];
}
msg = (char) b + new String(tmp);
outputTA.append(msg);
outputTA.setCaretPosition(outputTA.getDocument().getLength());
if (msg.contains("@") && ((msg.endsWith("> ") || msg.endsWith(">") ||
msg.endsWith("# ") || msg.endsWith("#") ||
msg.endsWith("$ ") || msg.endsWith("$")))) {
// THE PROMPT IS READY !!
//printOUT(msg + '\n');
String cmd = execNextCMD();
if (cmd.startsWith("exit") || cmd.startsWith("EXIT")) {
//Ceci provoque l'arrêt contrôlé du thread OutputHandler
throw new Exception("OutputHandler thread is shuting down !!");
}
} else {
if (msg.contains("Password:") || msg.contains("password:")) {
printOUT("msg.contains(\"Password:\") || msg.contains(\"password:\")");
execNextCMD();
} else if (msg.endsWith("ETA")) {
// scp command
outputTA.append("\n");
outputTA.setCaretPosition(outputTA.getDocument().getLength());
} else {
// Continuer à lire
break;
}
}
}
} while (in.available() > 0);
}
} catch (Exception e) {
printERR(e.getMessage());
}
}
private String execNextCMD() {
String cmd = null;
do {
if (!cmds.isEmpty()) {
cmd = (String) cmds.firstElement();
break;
}
try {
Thread.sleep(10);
} catch (Exception e) {
}
} while (true);
cmds.remove(cmd);
try {
cmd += '\n';
out.write(cmd.getBytes(), 0, cmd.length());
out.flush();
} catch (Exception e) {
printERR(e.getMessage());
}
return cmd;
}
}
public class ClosureWatcher extends Thread {
@Override
public void run() {
sendCommand("exit");
try {
sshOH.join();
} catch (Exception e) {
printERR("SSH stop(): " + e);
}
if (channel != null) {
channel.disconnect();
}
if (session != null) {
session.disconnect();
}
if (sshOH != null) {
sshOH.stop();
}
}
}
public class SSHExecOutput extends Thread {
private InputStream input;
public SSHExecOutput(InputStream input) {
this.input = input;
this.start();
}
@Override
public void run() {
byte[] buf = new byte[1024];
int i = 0;
try {
while (true) {
i = input.read(buf, 0, 1024);
if (i <= 0) {
break;
} else {
byte[] tmp = new byte[i];
for (int k = 0; k < i; k++) {
tmp[k] = buf[k];
}
String str = new String(tmp);
outputTA.append(str.replace("[0;0m", "")
.replace("[1;39m", "")
.replace("[00m", "")
.replace("[01;31m", "")
.replace("[01;32m", "")
.replace("[01;33m", "")
.replace("[01;34m", "")
.replace("[m", "")
.replace("[0m", "")
.replace("[K", ""));
outputTA.setCaretPosition(outputTA.getDocument().getLength());
}
}
} catch (Exception e) {
printERR(e.getMessage());
}
}
}
}
|
qsnake/abinit
|
gui/src/abinitgui/SSH.java
|
Java
|
gpl-3.0
| 14,699
|
/*! normalize.css v3.0.2 | MIT License | git.io/normalize */
/**
* 1. Set default font family to sans-serif.
* 2. Prevent iOS text size adjust after orientation change, without disabling
* user zoom.
*/
html {
font-family: sans-serif;
/* 1 */
-ms-text-size-adjust: 100%;
/* 2 */
-webkit-text-size-adjust: 100%;
/* 2 */
}
/**
* Remove default margin.
*/
body {
margin: 0;
}
/* HTML5 display definitions
========================================================================== */
/**
* Correct `block` display not defined for any HTML5 element in IE 8/9.
* Correct `block` display not defined for `details` or `summary` in IE 10/11
* and Firefox.
* Correct `block` display not defined for `main` in IE 11.
*/
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
menu,
nav,
section,
summary {
display: block;
}
/**
* 1. Correct `inline-block` display not defined in IE 8/9.
* 2. Normalize vertical alignment of `progress` in Chrome, Firefox, and Opera.
*/
audio,
canvas,
progress,
video {
display: inline-block;
/* 1 */
vertical-align: baseline;
/* 2 */
}
/**
* Prevent modern browsers from displaying `audio` without controls.
* Remove excess height in iOS 5 devices.
*/
audio:not([controls]) {
display: none;
height: 0;
}
/**
* Address `[hidden]` styling not present in IE 8/9/10.
* Hide the `template` element in IE 8/9/11, Safari, and Firefox < 22.
*/
[hidden],
template {
display: none;
}
/* Links
========================================================================== */
/**
* Remove the gray background color from active links in IE 10.
*/
a {
background-color: transparent;
}
/**
* Improve readability when focused and also mouse hovered in all browsers.
*/
a:active,
a:hover {
outline: 0;
}
/* Text-level semantics
========================================================================== */
/**
* Address styling not present in IE 8/9/10/11, Safari, and Chrome.
*/
abbr[title] {
border-bottom: 1px dotted;
}
/**
* Address style set to `bolder` in Firefox 4+, Safari, and Chrome.
*/
b,
strong {
font-weight: bold;
}
/**
* Address styling not present in Safari and Chrome.
*/
dfn {
font-style: italic;
}
/**
* Address variable `h1` font-size and margin within `section` and `article`
* contexts in Firefox 4+, Safari, and Chrome.
*/
h1 {
font-size: 2em;
margin: 0.67em 0;
}
/**
* Address styling not present in IE 8/9.
*/
mark {
background: #ff0;
color: #000;
}
/**
* Address inconsistent and variable font size in all browsers.
*/
small {
font-size: 80%;
}
/**
* Prevent `sub` and `sup` affecting `line-height` in all browsers.
*/
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
/* Embedded content
========================================================================== */
/**
* Remove border when inside `a` element in IE 8/9/10.
*/
img {
border: 0;
}
/**
* Correct overflow not hidden in IE 9/10/11.
*/
svg:not(:root) {
overflow: hidden;
}
/* Grouping content
========================================================================== */
/**
* Address margin not present in IE 8/9 and Safari.
*/
figure {
margin: 1em 40px;
}
/**
* Address differences between Firefox and other browsers.
*/
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
/**
* Contain overflow in all browsers.
*/
pre {
overflow: auto;
}
/**
* Address odd `em`-unit font size rendering in all browsers.
*/
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
/* Forms
========================================================================== */
/**
* Known limitation: by default, Chrome and Safari on OS X allow very limited
* styling of `select`, unless a `border` property is set.
*/
/**
* 1. Correct color not being inherited.
* Known issue: affects color of disabled elements.
* 2. Correct font properties not being inherited.
* 3. Address margins set differently in Firefox 4+, Safari, and Chrome.
*/
button,
input,
optgroup,
select,
textarea {
color: inherit;
/* 1 */
font: inherit;
/* 2 */
margin: 0;
/* 3 */
}
/**
* Address `overflow` set to `hidden` in IE 8/9/10/11.
*/
button {
overflow: visible;
}
/**
* Address inconsistent `text-transform` inheritance for `button` and `select`.
* All other form control elements do not inherit `text-transform` values.
* Correct `button` style inheritance in Firefox, IE 8/9/10/11, and Opera.
* Correct `select` style inheritance in Firefox.
*/
button,
select {
text-transform: none;
}
/**
* 1. Avoid the WebKit bug in Android 4.0.* where (2) destroys native `audio`
* and `video` controls.
* 2. Correct inability to style clickable `input` types in iOS.
* 3. Improve usability and consistency of cursor style between image-type
* `input` and others.
*/
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
/* 2 */
cursor: pointer;
/* 3 */
}
/**
* Re-set default cursor for disabled elements.
*/
button[disabled],
html input[disabled] {
cursor: default;
}
/**
* Remove inner padding and border in Firefox 4+.
*/
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
/**
* Address Firefox 4+ setting `line-height` on `input` using `!important` in
* the UA stylesheet.
*/
input {
line-height: normal;
}
/**
* It's recommended that you don't attempt to style these elements.
* Firefox's implementation doesn't respect box-sizing, padding, or width.
*
* 1. Address box sizing set to `content-box` in IE 8/9/10.
* 2. Remove excess padding in IE 8/9/10.
*/
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Fix the cursor style for Chrome's increment/decrement buttons. For certain
* `font-size` values of the `input`, it causes the cursor style of the
* decrement button to change from `default` to `text`.
*/
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
/**
* 1. Address `appearance` set to `searchfield` in Safari and Chrome.
* 2. Address `box-sizing` set to `border-box` in Safari and Chrome
* (include `-moz` to future-proof).
*/
input[type="search"] {
-webkit-appearance: textfield;
/* 1 */
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
/* 2 */
box-sizing: content-box;
}
/**
* Remove inner padding and search cancel button in Safari and Chrome on OS X.
* Safari (but not Chrome) clips the cancel button when the search input has
* padding (and `textfield` appearance).
*/
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
/**
* Define consistent border, margin, and padding.
*/
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
/**
* 1. Correct `color` not being inherited in IE 8/9/10/11.
* 2. Remove padding so people aren't caught out if they zero out fieldsets.
*/
legend {
border: 0;
/* 1 */
padding: 0;
/* 2 */
}
/**
* Remove default vertical scrollbar in IE 8/9/10/11.
*/
textarea {
overflow: auto;
}
/**
* Don't inherit the `font-weight` (applied by a rule above).
* NOTE: the default cannot safely be changed in Chrome and Safari on OS X.
*/
optgroup {
font-weight: bold;
}
/* Tables
========================================================================== */
/**
* Remove most spacing between table cells.
*/
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
/* @group ----- Generic ----- */
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
body {
font: 12px Helvetica, Arial, sans-serif;
line-height: 18px;
color: #333;
background: #fff;
}
form, fieldset {
border: 0;
margin: 0;
padding: 0;
}
input[type=text], input[type=password], textarea {
border: 1px solid #ccc;
display: block;
}
/* -- Headings -- */
h1, h2, h3, h4, h5, h6 {
margin-bottom: 18px;
}
h1, h2, h3 {
font-weight: normal;
font-family: "Cinzel", Georgia, 'Gill Sans MT', 'Gill Sans', sans-serif;
color: #333;
}
h1 {
font-size: 30px;
line-height: 36px;
text-transform: uppercase;
letter-spacing: .1em;
word-break: break-word;
}
h2 {
font-size: 24px;
line-height: 36px;
}
h3 {
font-size: 18px;
line-height: 18px;
color: #015581;
}
h4, h5 {
font-size: 15px;
line-height: 18px;
font-family: "Amiri";
}
h4 {
font-weight: bold;
}
h5 {
font-style: italic;
}
h6 {
color: #666;
}
h1 a, h2 a, h3 a {
text-decoration: none;
}
/* -- Misc Block elements -- */
p, ul, ol, dl {
margin: 1.5em 0;
}
ul ul, ul ol, ol ol, ol ul {
margin-bottom: 0;
}
/* -- Misc Inline elements -- */
em, i {
font-style: italic;
}
strong, b {
font-weight: bold;
}
abbr, acronym {
border: none;
font-style: normal;
}
blockquote {
margin: 0 3em;
font-style: italic;
}
dt {
font-weight: bold;
}
dd {
margin-left: 1.5em;
}
/* -- Tables -- */
table {
width: 100%;
}
th, td {
border-bottom: 1px solid #ccc;
margin: 0;
padding: 0.75em 0;
}
th {
border-width: 3px;
text-align: left;
}
/* -- Links -- */
a:link, a:visited {
color: #369;
}
a:hover, a:active {
color: #ff8000;
}
img a {
border: none;
}
/* @end */
/* @group ----- Header ----- */
header {
position: relative;
margin: 0 auto;
padding: 0;
width: 960px;
padding: 3em 0;
position: relative;
}
header:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
header {
width: 768px;
}
}
@media only screen and (max-width: 767px) {
header {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
header {
width: 420px;
}
}
#header-image {
position: relative;
margin: 0 auto;
padding: 0;
width:960px;
}
#header-image:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#header-image {
width: 768px;
}
}
@media only screen and (max-width: 767px) {
#header-image {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
#header-image {
width: 420px;
}
}
#header-image img {
width: 100%;
height: auto;
vertical-align: bottom;
border: solid #ccc;
border-width: 1px 1px 0 1px;
}
#site-title {
float: left;
width: 50%;
font-weight: normal;
font-family: "Cinzel Decorative", 'Gill Sans MT', 'Gill Sans', sans-serif;
color: #333;
font-size: 36px;
line-height: 36px;
/*text-transform: uppercase;*/
letter-spacing: .2em;
position: relative;
}
#site-title img {
max-width: 100%;
height: auto;
}
#site-title a {
text-decoration: none;
}
#search-container {
float: right;
width: 45%;
position: relative;
font-size: 1.16667em;
line-height: 1.28571em;
}
#search-container h2 {
display: none;
}
#search-container input[type=text], #search-container button {
border: 1px solid #ccc;
background: #fafafa;
-moz-appearance: none;
-webkit-appearance: none;
border-radius: 0;
height: 30px;
}
#search-container input[type=text] {
padding: 3px;
width: 100%;
behavior: url("../javascripts/boxsizing.htc");
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
#search-container button {
background: #333;
color: white;
position: absolute;
border: 0;
right: 0;
top: 0;
width: 30px;
text-indent: -9999px;
}
#search-container button:after {
font-family: "FontAwesome";
content: "\f002";
text-indent: 0;
position: absolute;
top: 0;
left: 0;
height: 30px;
line-height: 30px;
text-align: center;
width: 30px;
}
.show-advanced.button {
width: 30px;
right: 0;
top: 0;
bottom: 0;
border-left: 1px solid #005177;
position: absolute;
text-decoration: none;
text-indent: -9999px;
behavior: url("../javascripts/boxsizing.htc");
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
.show-advanced.button:after {
content: "\2026";
display: block;
text-indent: 0;
text-align: center;
position: absolute;
width: 100%;
color: #fff;
background: #333;
top: 0;
bottom: 0;
font-size: 14px;
line-height: 30px;
}
#advanced-form {
display: none;
background-color: #fff;
overflow: auto;
z-index: 1001;
position: absolute;
top: 30px;
left: 0;
border: 1px solid #e7e7e7;
width: 100%;
padding: 1.5em 1em;
*behavior: url("../javascripts/boxsizing.htc");
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
#advanced-form fieldset p {
margin: 0;
}
#advanced-form > *:last-child {
margin-bottom: 0em;
}
#advanced-form.open {
display: block;
}
#advanced-form input[type="radio"] {
margin-right: 5px;
}
#search-form fieldset fieldset {
margin-bottom: 18px;
}
#search-container.with-advanced .button {
right: 30px;
}
#skipnav {
border: 0;
clip: rect(0, 0, 0, 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
width: 1px;
}
#skipnav:focus {
top: 0;
z-index: 9999;
clip: initial;
height: auto;
width: auto;
padding: .5em;
border: 1px blue dashed;
color: #ff8000;
}
/* @end */
/* @group ----- Navigation ----- */
.navigation {
list-style: none;
margin: 0;
padding-left: 0;
}
.navigation a {
text-decoration: none;
}
.navigation li {
float: left;
}
#admin-bar ul {
display: inline-block;
}
#primary-nav {
clear: both;
position: relative;
margin: 0 auto;
padding: 0;
width: 960px;
z-index: 50;
/* mega menu list */
/* a top level navigation item in the mega menu */
/* first descendant link within a top level navigation item */
/* focus/open states of first descendant link within a top level
navigation item */
/* open state of first descendant link within a top level
navigation item */
/* sub-navigation panel */
/* sub-navigation panel open state */
/* list of items within sub-navigation panel */
/* list item within sub-navigation panel */
}
#primary-nav:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#primary-nav {
width: 768px;
}
}
@media only screen and (max-width: 767px) {
#primary-nav {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
#primary-nav {
width: 420px;
}
}
#primary-nav .nav-menu {
display: block;
position: relative;
list-style: none;
margin: 0 0 0 -1px;
padding: 0 0 0 1px;
z-index: 15;
}
#primary-nav li {
list-style-type: none;
margin: 0 0 -1px 0;
position: relative;
}
#primary-nav .navigation {
position: relative;
z-index: 100;
overflow: visible;
}
#primary-nav .nav-item {
list-style: none;
display: block;
padding: 0;
margin: 0;
float: left;
position: relative;
overflow: visible;
}
#primary-nav .nav-item:first-child > a {
border-left: 1px solid #ccc;
}
#primary-nav .nav-item > a {
position: relative;
display: inline-block;
margin: 0 0 -1px 0;
border: 1px solid #ccc;
}
#primary-nav .nav-item:not(:first-child) > a {
margin-left: -1px;
}
#primary-nav .nav-item > a:focus,
#primary-nav .nav-item > a.open {
border: 1px solid #333;
}
#primary-nav .nav-item > a.open {
background-color: #fafafa;
z-index: 1;
}
#primary-nav .sub-nav {
position: absolute;
display: none;
top: 3em;
margin-top: 1px;
padding: 0;
border: 1px solid #333;
background-color: #333;
}
#primary-nav .sub-nav.open {
display: block;
width: 160px;
}
#primary-nav .sub-nav.open li {
width: 100%;
}
#primary-nav .subnav a:hover + ul,
#primary-nav .subnav a:focus + ul {
display: block;
position: absolute;
top: 3em;
margin-top: 1px;
z-index: 1000;
-moz-box-shadow: #ccc 0 3px 5px;
-webkit-box-shadow: #ccc 0 3px 5px;
box-shadow: #ccc 0 3px 5px;
}
#primary-nav .sub-nav ul {
vertical-align: top;
margin: 0;
padding: 0;
}
#primary-nav .sub-nav ul a {
margin-top: -0.75em;
padding-left: 2.25em;
}
#primary-nav .sub-nav li {
display: block;
list-style-type: none;
margin: 0;
padding: 0;
}
#primary-nav .sub-nav > li {
border-color: #ccc;
border-bottom-width: 0.08333em;
border-bottom-style: solid;
padding-bottom: -0.08333em;
}
#primary-nav .sub-nav a {
width: 100%;
}
#primary-nav a {
behavior: url("../javascripts/boxsizing.htc");
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
text-decoration: none;
display: block;
padding: 0.75em 18px;
background: #333;
color: #fff;
}
#primary-nav a:hover,
#primary-nav a:focus,
#primary-nav li.active a {
color: #fff;
position: relative;
z-index: 1;
}
#primary-nav [aria-haspopup="true"]:after {
font-family: "FontAwesome";
content: "\f0da";
margin: -1px 0 0 .5em;
display: inline-block;
}
#primary-nav [aria-haspopup="true"].open:after {
content: "\f0d7";
}
#secondary-nav, .secondary-nav {
margin-bottom: 1.5em;
overflow: auto;
border-bottom: 1px solid #ccc;
clear: both;
}
#secondary-nav li, .secondary-nav li {
padding: 1.5em 0;
margin-right: 20px;
}
#secondary-nav a, .secondary-nav a {
color: #666;
}
#secondary-nav .active a, .secondary-nav .active a {
background: #333;
color: #333;
font-weight: bold;
}
#secondary-nav .tags .nav-browse-all a, .secondary-nav .tags .nav-browse-all a {
font-weight: normal;
border: none;
border-bottom: 1px solid #fff;
background: none;
}
#mobile-nav {
display: none;
}
/* Pagination Classes */
.pagination {
float: left;
padding-left: 0;
margin: 0 0 1.5em 0;
}
.pagination ul {
margin-left: 0;
}
.pagination li {
height: 3em;
border: solid #e7e7e7;
border-width: 1px 0 1px 1px;
float: left;
list-style-type: none;
}
.pagination li:last-of-type {
border-right: 1px solid #e7e7e7;
}
.pagination a, .pagination form {
text-decoration: none;
padding: 0 10px;
line-height: 36px;
display: inline-block;
}
.page-input input[type=text] {
border: 1px solid #ccc;
text-align: right;
width: 50px;
margin-right: 5px;
display: inline-block;
}
/* @end */
/* @group ----- Global selectors ----- */
#content {
overflow: hidden;
border: 1px solid #ccc;
background: #fff;
position: relative;
margin: 0 auto;
padding: 0;
width: 960px;
padding: 1.5em 10px;
z-index: 0;
}
#content:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#content {
width: 768px;
}
}
@media only screen and (max-width: 767px) {
#content {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
#content {
width: 420px;
}
}
.hidden {
display: none;
}
.image {
float: left;
margin: 0 1.5em 1.5em 0;
}
.image img {
border: 1px solid #ccc;
float: left;
padding: 2px;
width: auto;
vertical-align: top;
height: 100%;
}
.item-file img {
max-width: 100%;
}
.record {
clear: both;
overflow: auto;
}
#sort-links + .item,
#sort-links + .collection,
nav + .exhibit {
border-top: 1px solid #eee;
}
.item + .pagination-nav ul,
.collection + .pagination-nav ul,
.exhibit + .pagination-nav ul {
margin-top: 1.5em;
}
/* @end */
/* @group ----- Home Page ----- */
#home #primary {
float: left;
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 460px;
margin-left: 0;
margin-right: 0;
padding-right: 10px;
}
@media only screen and (max-width: 767px) {
#home #primary {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#home #primary {
width: 364px;
}
}
@media only screen and (max-width: 767px) {
#home #primary {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
#home #primary {
width: 420px;
}
}
#home #secondary {
float: right;
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 460px;
margin-right: 0;
padding-left: 10px;
}
@media only screen and (max-width: 767px) {
#home #secondary {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#home #secondary {
width: 364px;
}
}
@media only screen and (max-width: 767px) {
#home #secondary {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
#home #secondary {
width: 420px;
}
}
#home #content h2 {
text-transform: uppercase;
letter-spacing: .1em;
}
.featured,
#featured-exhibit {
overflow: hidden;
background: #eee;
padding: 1.5em 20px;
margin-bottom: 1.5em;
}
.featured h2,
#featured-exhibit h2 {
margin: 0;
}
.featured h3,
#featured-exhibit h3 {
margin: 0 0 1em;
}
.featured img,
#featured-exhibit img {
float: left;
border: 1px solid #ccc;
padding: 2px;
height: 10.5em;
width: auto;
background-color: #fff;
}
#recent-items .item {
overflow: hidden;
border-bottom: 1px solid #ccc;
margin-bottom: 1.5em;
}
#recent-items .item .image {
height: 6em;
}
#recent-items .item h3 {
margin-top: 0;
}
.view-items-link {
margin-bottom: 0em;
}
/* @end */
/* @group ----- Items ----- */
.items #content {
position: relative;
margin: 0 auto;
padding: 0;
width: 960px;
padding: 1.5em 10px;
}
.items #content:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.items #content {
width: 768px;
}
}
@media only screen and (max-width: 767px) {
.items #content {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.items #content {
width: 420px;
}
}
#next-item {
float: right;
}
.item-description a.show {
padding-left: 5px;
display: inline;
}
.sort-label {
display: inline-block;
}
#sort-links-list {
display: inline-block;
margin: 0.75em 0 0.75em 10px;
}
.desc a:after, .asc a:after {
font-family: "FontAwesome";
display: inline-block;
height: 0;
width: 0;
text-decoration: underline;
margin-right: 10px;
}
.desc a:after {
content: "\00a0\f0d8";
}
.asc a:after {
content: "\00a0\f0d7";
}
ul.title-list {
margin: 0;
}
.title-list li {
font-size: 1.2em;
line-height: 1.5em;
font-style: italic;
}
#item-images {
overflow: hidden;
margin-bottom: 18px;
margin-right: -10px;
}
.fullsize {
margin-right: 10px;
}
#item-image img {
width: 100%;
}
.items.show h3 {
margin-bottom: 0.75em;
}
/* Items Classes*/
.element {
overflow: hidden;
clear: both;
margin-bottom: 1.5em;
}
.browse .item {
clear: both;
border-bottom: 1px solid #eee;
padding: 3em 0;
float: left;
width: 100%;
}
.item-pagination {
clear: both;
overflow: hidden;
border-top: 1px solid #eee;
padding-top: 18px;
}
.item-pagination a {
text-decoration: none;
font-weight: bold;
float: left;
}
.item-pagination .next a {
float: right;
text-align: right;
}
.item .tags {
clear: left;
margin-left: 216px;
}
.item .item-file a {
display: block;
height: 9em;
}
.item .item-file a img {
height: 100%;
width: auto;
}
.item h2 {
margin-top: 0;
}
/* Tags Classes */
.tags li {
display: inline;
}
/* Tag Clouds */
.hTagcloud ul {
list-style: none;
margin-left: 0;
padding-left: 0;
}
.hTagcloud li {
display: inline;
margin-right: 3px;
}
.popular a {
font-size: 120%;
}
.v-popular a {
font-size: 140%;
}
.vv-popular a {
font-size: 180%;
}
.vvv-popular a {
font-size: 220%;
}
.vvvv-popular a {
font-size: 260%;
}
.vvvvv-popular a {
font-size: 300%;
}
.vvvvvv-popular a {
font-size: 320%;
}
.vvvvvvv-popular a {
font-size: 340%;
}
.vvvvvvvv-popular a {
font-size: 360%;
}
/* @end */
/* @group ----- Items/Browse ----- */
.browse .item h2,
.browse .item-meta .item-img {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 220px;
}
@media only screen and (max-width: 767px) {
.browse .item h2,
.browse .item-meta .item-img {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.browse .item h2,
.browse .item-meta .item-img {
width: 172px;
}
}
@media only screen and (max-width: 767px) {
.browse .item h2,
.browse .item-meta .item-img {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.browse .item h2,
.browse .item-meta .item-img {
width: 420px;
}
}
.browse .item h2 {
margin-left: 0;
margin-bottom: 0;
max-width: 100%;
}
.browse .item-meta .item-img {
margin-right: 0;
float: right;
text-align: right;
}
.browse .item-img img {
height: 10.5em;
}
.browse .item-meta {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 700px;
margin: 0;
max-width: 100%;
}
@media only screen and (max-width: 767px) {
.browse .item-meta {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.browse .item-meta {
width: 556px;
}
}
@media only screen and (max-width: 767px) {
.browse .item-meta {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.browse .item-meta {
width: 420px;
}
}
.browse .item-meta p:first-of-type {
margin-top: 0;
}
.browse .item-meta > div {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 460px;
margin: 0;
max-width: 100%;
}
@media only screen and (max-width: 767px) {
.browse .item-meta > div {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.browse .item-meta > div {
width: 364px;
}
}
@media only screen and (max-width: 767px) {
.browse .item-meta > div {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.browse .item-meta > div {
width: 420px;
}
}
.browse .item-meta .item-description {
margin-bottom: 1.5em;
}
.browse .item-meta .item-description:only-of-type {
margin-bottom: 0;
}
#sort-links {
float: right;
list-style-type: none;
padding: 0;
display: block;
}
#sort-links ul {
padding-left: 0;
}
#sort-links ul li {
padding-left: 10px;
display: inline-block;
}
#outputs {
clear: both;
}
.item-img a {
display: block;
}
/* @end */
/* @group ----- Items/Search ----- */
.field {
margin-bottom: 1.5em;
}
.search-entry select {
margin-bottom: 0.75em;
}
.search-entry input[type=text] {
display: inline-block;
}
.remove_search {
text-indent: -9999px;
width: 18px;
position: relative;
height: 18px;
color: #666;
}
.remove_search:after {
content: "\f00d";
font-family: "FontAwesome";
text-indent: 0;
text-align: center;
width: 100%;
top: 0;
left: 0;
position: absolute;
line-height: 18px;
}
/* @end */
/* @group ----- Collections/Browse ----- */
.browse .collection,
.browse .exhibit {
clear: both;
border-bottom: 1px solid #eee;
float: left;
width: 100%;
padding-top: 1.5em;
}
.browse .collection .view-items-link,
.browse .exhibit .view-items-link {
margin-bottom: 2.25em;
}
.browse .collection h3,
.browse .exhibit h3 {
margin: 0;
}
.collection .element-text p:only-child {
margin-bottom: 0;
}
.collection .image,
.exhibit .image {
display: block;
-moz-box-shadow: -5px -5px 0 -1px #f2f2f2, -5px -5px 0 #ccc, -8px -8px 0 -1px #ddd, -8px -8px 0 #CCC;
-webkit-box-shadow: -5px -5px 0 -1px #f2f2f2, -5px -5px 0 #ccc, -8px -8px 0 -1px #ddd, -8px -8px 0 #CCC;
box-shadow: -5px -5px 0 -1px #f2f2f2, -5px -5px 0 #ccc, -8px -8px 0 -1px #ddd, -8px -8px 0 #CCC;
margin: 0 1.5em 1.5em 9px;
}
.collection .image img,
.exhibit .image img {
height: 10.5em;
}
.browse .collection h2,
.browse .exhibit h2 {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 220px;
margin-left: 0;
margin: 0;
max-width: 100%;
}
@media only screen and (max-width: 767px) {
.browse .collection h2,
.browse .exhibit h2 {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.browse .collection h2,
.browse .exhibit h2 {
width: 172px;
}
}
@media only screen and (max-width: 767px) {
.browse .collection h2,
.browse .exhibit h2 {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.browse .collection h2,
.browse .exhibit h2 {
width: 420px;
}
}
.browse .collection .image,
.browse .exhibit .image {
margin-right: 0;
float: right;
text-align: right;
height: 10.5em;
}
.browse .collection .image img,
.browse .exhibit .image img {
height: 100%;
width: auto;
}
.collection-meta {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 520px;
}
@media only screen and (max-width: 767px) {
.collection-meta {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.collection-meta {
width: 412px;
}
}
@media only screen and (max-width: 767px) {
.collection-meta {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.collection-meta {
width: 420px;
}
}
.collection-description p:first-of-type,
.view-items-link:only-child {
margin-top: 0.75em;
}
.browse .collection .element {
clear: none;
}
/* @end */
/* @group ----- Collections/Show ----- */
.collections .item-img {
float: left;
margin: 0 1.5em 0 0;
}
.collections .item-img a {
display: block;
height: 6em;
border: 1px solid #ccc;
padding: 2px;
}
.collections .item-img img {
height: 100%;
width: auto;
}
.collections .item {
overflow: hidden;
border-color: #ccc;
border-top-width: 0.08333em;
border-top-style: solid;
padding-top: -0.08333em;
margin-top: 1.5em;
}
/* @end */
/* @group ----- Search Results ----- */
#search-results + .pagination {
margin-top: 2.25em;
}
#search-results td {
vertical-align: top;
}
#search-results .image {
float: left;
height: 6em;
margin: 0 1.5em 0 0;
}
#search-results .image img {
height: 100%;
width: auto;
}
#item-filters ul, #search-filters ul {
padding-left: 0;
list-style-type: none;
}
#item-filters ul > li, #search-filters ul > li {
display: inline-block;
}
#item-filters ul > li:after, #search-filters ul > li:after {
content: " \00B7";
margin: 0 10px 0 5px;
}
#item-filters ul > li:last-child:after, #search-filters ul > li:last-child:after {
content: "\00A0";
}
#item-filters ul li ul, #search-filters ul li ul {
display: inline;
}
#item-filters ul li ul li, #search-filters ul li ul li {
display: inline-block;
}
#item-filters ul li ul li:after, #search-filters ul li ul li:after {
content: ", ";
margin: 0;
}
#item-filters ul li ul li:last-child:after, #search-filters ul li ul li:last-child:after {
content: "";
}
/* @end */
/* @group ----- Footer ----- */
footer {
clear: both;
position: relative;
margin: 0 auto;
padding: 0;
background: #333;
width: 960px;
overflow: hidden;
margin-top: 1.5em;
}
footer:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
footer {
width: 768px;
}
}
@media only screen and (max-width: 767px) {
footer {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
footer {
width: 420px;
}
}
footer a {
text-decoration: none;
}
footer .navigation {
font-weight: bold;
}
footer .navigation li {
display: inline;
}
footer .navigation li:after {
content: " \00B7";
margin: 0 10px 0 5px;
color: #fff;
}
footer .navigation li:last-child {
margin: 0;
}
footer .navigation li:last-child:after {
content: "\00A0";
display: none;
}
footer .navigation a {
white-space: nowrap;
color: #fff;
}
footer nav + p {
text-align: right;
color: #fff;
}
#footer-text {
float: left;
width: 48%;
}
/* @end */
/* @group ----- Exhibit Builder ----- */
.pagination + .exhibit {
border-top: 1px solid #eee;
}
#exhibit-pages {
width: 220px;
display: inline-block;
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
#exhibit-pages {
width: 172px;
}
}
#exhibit-pages h4 {
font-family: 'Gill Sans MT', 'Gill Sans', sans-serif;
font-weight: normal;
text-transform: uppercase;
}
#exhibit-pages a {
text-decoration: none;
}
#exhibit-pages > ul {
margin-left: 0;
border-top-width: 0.08333em;
border-top-style: solid;
padding-top: 1.41667em;
border-color: #eee;
padding-left: 0;
list-style-type: none;
}
#exhibit-pages > ul > li {
border-bottom-width: 0.08333em;
border-bottom-style: solid;
padding-bottom: 1.41667em;
border-color: #eee;
margin-bottom: 1.5em;
}
#exhibit-pages ul li > ul {
padding-left: 1.5em;
margin-left: 0;
}
#exhibit-pages ul li > ul li {
text-indent: -1.5em;
}
#exhibit-pages ul li > ul li:before {
content: "\2014";
}
#exhibit-pages li {
list-style-type: none;
margin-left: 0;
}
#exhibit-pages .current {
font-weight: bold;
}
#exhibit-pages .current > *:not(a) {
font-weight: normal;
}
#exhibit-pages > ul > li:not(.parent) ul {
display: none;
}
#exhibit-pages > ul > li.current ul {
display: block;
}
#exhibit-pages ul ul {
margin: 0;
}
.exhibits #content > h1:first-of-type,
#exhibit-blocks,
#exhibit-page-navigation,
.exhibits.summary #primary {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 700px;
margin-left: 0;
padding-right: 20px;
margin-left: 0;
}
@media only screen and (max-width: 767px) {
.exhibits #content > h1:first-of-type,
#exhibit-blocks,
#exhibit-page-navigation,
.exhibits.summary #primary {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.exhibits #content > h1:first-of-type,
#exhibit-blocks,
#exhibit-page-navigation,
.exhibits.summary #primary {
width: 556px;
}
}
@media only screen and (max-width: 767px) {
.exhibits #content > h1:first-of-type,
#exhibit-blocks,
#exhibit-page-navigation,
.exhibits.summary #primary {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.exhibits #content > h1:first-of-type,
#exhibit-blocks,
#exhibit-page-navigation,
.exhibits.summary #primary {
width: 420px;
}
}
.exhibit-page-nav a:hover,
.exhibit-page-nav a:active,
.exhibit-page-nav .current a {
background: #ff8000;
}
.exhibit-pagination .next a {
float: right;
text-align: right;
}
#exhibit-page-navigation {
clear: none;
margin: 3em 0 1.5em;
}
.exhibit .description,
.exhibit .description ~ * {
float: left;
display: inline;
margin-left: 10px;
margin-right: 10px;
width: 520px;
}
@media only screen and (max-width: 767px) {
.exhibit .description,
.exhibit .description ~ * {
margin: 0;
}
}
@media only screen and (min-width: 768px) and (max-width: 959px) {
.exhibit .description,
.exhibit .description ~ * {
width: 412px;
}
}
@media only screen and (max-width: 767px) {
.exhibit .description,
.exhibit .description ~ * {
width: 300px;
}
}
@media only screen and (min-width: 480px) and (max-width: 767px) {
.exhibit .description,
.exhibit .description ~ * {
width: 420px;
}
}
.exhibit .description p:first-of-type,
.exhibit .description ~ * p:first-of-type {
margin-top: 0.75em;
}
.exhibit .description ~ * {
display: block;
margin: 1.5em auto;
padding: 0 40px 0 80px;
float: none;
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
.exhibit-items .download-file:last-child {
margin-bottom: 1.5em;
}
/* @end */
/* @group ----- Other plugin styles ----- */
#collection-tree {
margin-left: auto;
margin-right: auto;
}
#recaptcha_area input {
display: inline;
}
/* @end */
@media screen and (max-width: 768px) {
/* @group ----- Generic HTML elements ----- */
input[type=text], input[type=password], textarea {
width: 100%;
display: block;
}
/* @end */
/* @group ----- Global selectors ----- */
#search-container {
clear: both;
width: 100%;
margin-top: 1.5em;
margin-bottom: 0em;
}
/* @end */
/* @group ----- Header ----- */
#site-title {
width: 100%;
}
/* @end */
/* @group ----- Navigation ----- */
#primary-nav {
display: none;
}
#mobile-nav {
display: block;
clear: both;
position: relative;
margin: 0 auto;
padding: 0;
width: 960px;
zoom: 1;
}
#mobile-nav:after {
content: "\0020";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
}
@media only screen and (max-width: 768px) and (min-width: 768px) and (max-width: 959px) {
#mobile-nav {
width: 768px;
}
}
@media only screen and (max-width: 768px) and (max-width: 767px) {
#mobile-nav {
width: 300px;
}
}
@media only screen and (max-width: 768px) and (min-width: 480px) and (max-width: 767px) {
#mobile-nav {
width: 420px;
}
}
@media screen and (max-width: 768px) {
#mobile-nav ul {
position: absolute;
z-index: 199;
background: #fafafa;
border-bottom: 1px solid #ccc;
width: 100%;
padding-left: 0;
margin: 0;
}
#mobile-nav li {
text-align: left;
display: block;
overflow: hidden;
width: 100%;
}
#mobile-nav a {
text-decoration: none;
display: block;
padding: 10px;
border: 1px solid #ccc;
border-width: 1px 1px 0 1px;
}
#mobile-nav a:hover {
background: #fff;
}
#mobile-nav > a:first-child {
background: #fafafa;
cursor: pointer;
}
#mobile-nav li.current a {
background: #fff;
color: #ff8000;
}
#mobile-nav li ul {
position: relative;
}
#mobile-nav li ul a:before {
content: "-- ";
}
#mobile-nav li ul ul a:before {
content: "---- ";
}
/* @end */
/* @group ----- Footer ----- */
footer .navigation {
float: none;
width: 100%;
text-align: left;
margin-bottom: 1.5em;
}
/* @end */
/* @group ----- Home ----- */
#home #primary, #home #secondary {
padding: 0;
max-width: 100%;
}
#home #primary > div:last-of-type {
border-bottom: 1px solid #ccc;
}
/* @end */
/* @group ----- Items/Browse ----- */
.browse .item img {
margin-bottom: 1.5em;
margin-top: 1.5em;
}
.browse .item.record h2 {
margin-bottom: 0.75em;
}
.browse .item-meta .item-img {
width: auto;
float: left;
margin: 0 1.5em 0 0;
}
.browse .item-meta .item-img img {
margin-top: 0em;
}
.browse .item {
padding: 1.5em 0;
}
.browse .item-meta > div {
float: none;
}
#sort-links {
float: left;
}
/* @end */
/* @group ----- Exhibits/Show ----- */
.exhibit {
clear: both;
}
.exhibit .description {
float: none;
}
.exhibit .description ~ * {
padding: 0;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
/* @end */
/* @group ----- Exhibits/Show ----- */
#exhibit-pages {
width: 100%;
}
/* @end */
}
|
HCDigitalScholarship/friends-asylum
|
themes/berlin/css/style.css
|
CSS
|
gpl-3.0
| 39,429
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_102) on Tue Feb 21 18:03:21 GMT 2017 -->
<title>gate.crowdsource Class Hierarchy (${plugin.name} JavaDoc)</title>
<meta name="date" content="2017-02-21">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
<script type="text/javascript" src="../../script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="gate.crowdsource Class Hierarchy (${plugin.name} JavaDoc)";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li><a href="../../gate/crowdsource/classification/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?gate/crowdsource/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h1 class="title">Hierarchy For Package gate.crowdsource</h1>
<span class="packageHierarchyLabel">Package Hierarchies:</span>
<ul class="horizontal">
<li><a href="../../overview-tree.html">All Packages</a></li>
</ul>
</div>
<div class="contentContainer">
<h2 title="Interface Hierarchy">Interface Hierarchy</h2>
<ul>
<li type="circle">gate.crowdsource.<a href="../../gate/crowdsource/CrowdFlowerConstants.html" title="interface in gate.crowdsource"><span class="typeNameLink">CrowdFlowerConstants</span></a></li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li>Class</li>
<li class="navBarCell1Rev">Tree</li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-all.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li><a href="../../gate/crowdsource/classification/package-tree.html">Next</a></li>
</ul>
<ul class="navList">
<li><a href="../../index.html?gate/crowdsource/package-tree.html" target="_top">Frames</a></li>
<li><a href="package-tree.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
masterucm1617/botzzaroni
|
BotzzaroniDev/GATE_Developer_8.4/plugins/Crowd_Sourcing/doc/javadoc/gate/crowdsource/package-tree.html
|
HTML
|
gpl-3.0
| 4,322
|
<?php
/**
* @copyright Copyright (c) 2010-2015 Mediaparts Interactive. All rights reserved.
* @license GNU/GPL http://www.gnu.org/licenses/gpl.html
*/
defined('_JEXEC') or die('Restricted access'); // No direct access
jimport('joomla.utilities.date');
class GlobalFlashGalleriesViewGalleries extends JViewLegacy
{
function display( $tpl = null )
{
//$document = JFactory::getDocument();
//$document->addStyleSheet( globalflash_adminURL.'/css/icons.css', 'text/css', null, array() );
$title = JText::_('Manage Galleries');
JToolBarHelper::title( JText::_('Flash Galleries').": <small>[ {$title} ]</small>", 'gallery.png' );
$items = $this->get('Data');
if ( count($items) )
{
JToolBarHelper::publishList();
JToolBarHelper::unpublishList();
JToolBarHelper::deleteList();
if (method_exists('JToolBarHelper', 'editListX'))
JToolBarHelper::editListX();
else
JToolBarHelper::editList();
}
if (method_exists('JToolBarHelper', 'addNewX'))
JToolBarHelper::addNewX();
else
JToolBarHelper::addNew();
JToolBarHelper::help('../galleries.html', true);
$this->assignRef('items', $items);
parent::display($tpl);
}
}
|
olegshs/com_globalflashgalleries
|
admin/views/galleries/view.html.php
|
PHP
|
gpl-3.0
| 1,176
|
#!/usr/bin/env python
# vim: set expandtab shiftwidth=4:
# http://www.voip-info.org/wiki/view/asterisk+manager+events
import sys,time
import simplejson as json
from stompy.simple import Client
import ConfigParser
config = ConfigParser.ConfigParser()
devel_config = ConfigParser.ConfigParser()
config.read('/opt/ucall/etc/config.ini')
devel_config.read('/opt/ucall/etc/devel_config.ini')
stomp_host = config.get('STOMP', 'host')
stomp_username = config.get('STOMP', 'username')
stomp_password = config.get('STOMP', 'password')
stomp_queue = "/queue/messages/" + devel_config.get('GENERAL', 'agent')
print '='*80
print 'Stomp host:', stomp_host
print 'Stomp username:', stomp_username
print 'Stomp password:', stomp_password
print 'Stomp queue:', stomp_queue
print '='*80
stomp = Client(stomp_host)
stomp.connect(stomp_username, stomp_password)
stomp.subscribe("jms.queue.msg.ctrl")
while True:
message = stomp.get()
print message.body
stomp.disconnect()
|
gryzz/uCall
|
utils/asterisk-connector/ami2stomp-get.py
|
Python
|
gpl-3.0
| 972
|
/*---------------------------------------------------------------
* Programmer(s): Daniel R. Reynolds @ SMU
*---------------------------------------------------------------
* SUNDIALS Copyright Start
* Copyright (c) 2002-2020, Lawrence Livermore National Security
* and Southern Methodist University.
* All rights reserved.
*
* See the top-level LICENSE and NOTICE files for details.
*
* SPDX-License-Identifier: BSD-3-Clause
* SUNDIALS Copyright End
*---------------------------------------------------------------
* This is the implementation file for ARKode's ARK time stepper
* module.
*--------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "arkode_impl.h"
#include "arkode_arkstep_impl.h"
#include "arkode_interp_impl.h"
#include <sundials/sundials_math.h>
#include <sunnonlinsol/sunnonlinsol_newton.h>
#if defined(SUNDIALS_EXTENDED_PRECISION)
#define RSYM ".32Lg"
#else
#define RSYM ".16g"
#endif
/* constants */
#define ZERO RCONST(0.0)
#define ONE RCONST(1.0)
#define FIXED_LIN_TOL
/*===============================================================
ARKStep Exported functions -- Required
===============================================================*/
void* ARKStepCreate(ARKRhsFn fe, ARKRhsFn fi, realtype t0, N_Vector y0)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
SUNNonlinearSolver NLS;
booleantype nvectorOK;
int retval;
/* Check that at least one of fe, fi is supplied and is to be used */
if (fe == NULL && fi == NULL) {
arkProcessError(NULL, ARK_ILL_INPUT, "ARKode::ARKStep",
"ARKStepCreate", MSG_ARK_NULL_F);
return(NULL);
}
/* Check for legal input parameters */
if (y0 == NULL) {
arkProcessError(NULL, ARK_ILL_INPUT, "ARKode::ARKStep",
"ARKStepCreate", MSG_ARK_NULL_Y0);
return(NULL);
}
/* Test if all required vector operations are implemented */
nvectorOK = arkStep_CheckNVector(y0);
if (!nvectorOK) {
arkProcessError(NULL, ARK_ILL_INPUT, "ARKode::ARKStep",
"ARKStepCreate", MSG_ARK_BAD_NVECTOR);
return(NULL);
}
/* Create ark_mem structure and set default values */
ark_mem = arkCreate();
if (ark_mem == NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepCreate", MSG_ARK_NO_MEM);
return(NULL);
}
/* Allocate ARKodeARKStepMem structure, and initialize to zero */
step_mem = NULL;
step_mem = (ARKodeARKStepMem) malloc(sizeof(struct ARKodeARKStepMemRec));
if (step_mem == NULL) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep",
"ARKStepCreate", MSG_ARK_ARKMEM_FAIL);
return(NULL);
}
memset(step_mem, 0, sizeof(struct ARKodeARKStepMemRec));
/* Attach step_mem structure and function pointers to ark_mem */
ark_mem->step_attachlinsol = arkStep_AttachLinsol;
ark_mem->step_attachmasssol = arkStep_AttachMasssol;
ark_mem->step_disablelsetup = arkStep_DisableLSetup;
ark_mem->step_disablemsetup = arkStep_DisableMSetup;
ark_mem->step_getlinmem = arkStep_GetLmem;
ark_mem->step_getmassmem = arkStep_GetMassMem;
ark_mem->step_getimplicitrhs = arkStep_GetImplicitRHS;
ark_mem->step_mmult = NULL;
ark_mem->step_getgammas = arkStep_GetGammas;
ark_mem->step_init = arkStep_Init;
ark_mem->step_fullrhs = arkStep_FullRHS;
ark_mem->step = arkStep_TakeStep_Z;
ark_mem->step_mem = (void*) step_mem;
/* Set default values for ARKStep optional inputs */
retval = ARKStepSetDefaults((void *)ark_mem);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, retval, "ARKode::ARKStep",
"ARKStepCreate",
"Error setting default solver options");
ARKStepFree((void**) &ark_mem); return(NULL);
}
/* Set implicit/explicit problem based on function pointers */
step_mem->explicit = (fe == NULL) ? SUNFALSE : SUNTRUE;
step_mem->implicit = (fi == NULL) ? SUNFALSE : SUNTRUE;
/* Allocate the general ARK stepper vectors using y0 as a template */
/* NOTE: Fe, Fi, cvals and Xvecs will be allocated later on
(based on the number of ARK stages) */
/* Clone the input vector to create sdata, zpred and zcor */
if (!arkAllocVec(ark_mem, y0, &(step_mem->sdata))) {
ARKStepFree((void**) &ark_mem); return(NULL); }
if (!arkAllocVec(ark_mem, y0, &(step_mem->zpred))) {
ARKStepFree((void**) &ark_mem); return(NULL); }
if (!arkAllocVec(ark_mem, y0, &(step_mem->zcor))) {
ARKStepFree((void**) &ark_mem); return(NULL); }
/* Copy the input parameters into ARKode state */
step_mem->fe = fe;
step_mem->fi = fi;
/* Update the ARKode workspace requirements */
ark_mem->liw += 41; /* fcn/data ptr, int, long int, sunindextype, booleantype */
ark_mem->lrw += 10;
/* If an implicit component is to be solved, create default Newton NLS object */
step_mem->ownNLS = SUNFALSE;
if (step_mem->implicit) {
NLS = NULL;
NLS = SUNNonlinSol_Newton(y0);
if (NLS == NULL) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep",
"ARKStepCreate", "Error creating default Newton solver");
ARKStepFree((void**) &ark_mem); return(NULL);
}
retval = ARKStepSetNonlinearSolver(ark_mem, NLS);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep",
"ARKStepCreate", "Error attaching default Newton solver");
ARKStepFree((void**) &ark_mem); return(NULL);
}
step_mem->ownNLS = SUNTRUE;
}
/* Set the linear solver addresses to NULL (we check != NULL later) */
step_mem->linit = NULL;
step_mem->lsetup = NULL;
step_mem->lsolve = NULL;
step_mem->lfree = NULL;
step_mem->lmem = NULL;
step_mem->lsolve_type = -1;
/* Set the mass matrix solver addresses to NULL */
step_mem->minit = NULL;
step_mem->msetup = NULL;
step_mem->mmult = NULL;
step_mem->msolve = NULL;
step_mem->mfree = NULL;
step_mem->mass_mem = NULL;
step_mem->mass_type = MASS_IDENTITY;
step_mem->msolve_type = -1;
/* Initialize initial error norm */
step_mem->eRNrm = ONE;
/* Initialize all the counters */
step_mem->nfe = 0;
step_mem->nfi = 0;
step_mem->nsetups = 0;
step_mem->nstlp = 0;
step_mem->nls_iters = 0;
/* Initialize fused op work space */
step_mem->cvals = NULL;
step_mem->Xvecs = NULL;
step_mem->nfusedopvecs = 0;
/* Initialize external polynomial forcing data */
step_mem->expforcing = SUNFALSE;
step_mem->impforcing = SUNFALSE;
step_mem->forcing = NULL;
step_mem->nforcing = 0;
/* Initialize main ARKode infrastructure */
retval = arkInit(ark_mem, t0, y0, FIRST_INIT);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, retval, "ARKode::ARKStep", "ARKStepCreate",
"Unable to initialize main ARKode infrastructure");
ARKStepFree((void**) &ark_mem); return(NULL);
}
return((void *)ark_mem);
}
/*---------------------------------------------------------------
ARKStepResize:
This routine resizes the memory within the ARKStep module.
It first resizes the main ARKode infrastructure memory, and
then resizes its own data.
---------------------------------------------------------------*/
int ARKStepResize(void *arkode_mem, N_Vector y0, realtype hscale,
realtype t0, ARKVecResizeFn resize, void *resize_data)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
SUNNonlinearSolver NLS;
sunindextype lrw1, liw1, lrw_diff, liw_diff;
int i, retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "ARKStepResize",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* Determing change in vector sizes */
lrw1 = liw1 = 0;
if (y0->ops->nvspace != NULL)
N_VSpace(y0, &lrw1, &liw1);
lrw_diff = lrw1 - ark_mem->lrw1;
liw_diff = liw1 - ark_mem->liw1;
ark_mem->lrw1 = lrw1;
ark_mem->liw1 = liw1;
/* resize ARKode infrastructure memory */
retval = arkResize(ark_mem, y0, hscale, t0, resize, resize_data);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, retval, "ARKode::ARKStep", "ARKStepResize",
"Unable to resize main ARKode infrastructure");
return(retval);
}
/* Resize the sdata, zpred and zcor vectors */
if (!arkResizeVec(ark_mem, resize, resize_data, lrw_diff,
liw_diff, y0, &step_mem->sdata)) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep", "ARKStepResize",
"Unable to resize vector");
return(ARK_MEM_FAIL);
}
if (!arkResizeVec(ark_mem, resize, resize_data, lrw_diff,
liw_diff, y0, &step_mem->zpred)) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep", "ARKStepResize",
"Unable to resize vector");
return(ARK_MEM_FAIL);
}
if (!arkResizeVec(ark_mem, resize, resize_data, lrw_diff,
liw_diff, y0, &step_mem->zcor)) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep", "ARKStepResize",
"Unable to resize vector");
return(ARK_MEM_FAIL);
}
/* Resize the ARKStep vectors */
/* Fe */
if (step_mem->Fe != NULL) {
for (i=0; i<step_mem->stages; i++) {
if (!arkResizeVec(ark_mem, resize, resize_data, lrw_diff,
liw_diff, y0, &step_mem->Fe[i])) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep", "ARKStepResize",
"Unable to resize vector");
return(ARK_MEM_FAIL);
}
}
}
/* Fi */
if (step_mem->Fi != NULL) {
for (i=0; i<step_mem->stages; i++) {
if (!arkResizeVec(ark_mem, resize, resize_data, lrw_diff,
liw_diff, y0, &step_mem->Fi[i])) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep", "ARKStepResize",
"Unable to resize vector");
return(ARK_MEM_FAIL);
}
}
}
/* If a NLS object was previously used, destroy and recreate default Newton
NLS object (can be replaced by user-defined object if desired) */
if ((step_mem->NLS != NULL) && (step_mem->ownNLS)) {
/* destroy existing NLS object */
retval = SUNNonlinSolFree(step_mem->NLS);
if (retval != ARK_SUCCESS) return(retval);
step_mem->NLS = NULL;
step_mem->ownNLS = SUNFALSE;
/* create new Newton NLS object */
NLS = NULL;
NLS = SUNNonlinSol_Newton(y0);
if (NLS == NULL) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep",
"ARKStepResize", "Error creating default Newton solver");
return(ARK_MEM_FAIL);
}
/* attach new Newton NLS object to ARKStep */
retval = ARKStepSetNonlinearSolver(ark_mem, NLS);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_MEM_FAIL, "ARKode::ARKStep",
"ARKStepResize", "Error attaching default Newton solver");
return(ARK_MEM_FAIL);
}
step_mem->ownNLS = SUNTRUE;
}
/* reset nonlinear solver counters */
if (step_mem->NLS != NULL) step_mem->nsetups = 0;
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
ARKStepReInit:
This routine re-initializes the ARKStep module to solve a new
problem of the same size as was previously solved. This routine
should also be called when the problem dynamics or desired solvers
have changed dramatically, so that the problem integration should
resume as if started from scratch.
Note all internal counters are set to 0 on re-initialization.
---------------------------------------------------------------*/
int ARKStepReInit(void* arkode_mem, ARKRhsFn fe,
ARKRhsFn fi, realtype t0, N_Vector y0)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "ARKStepReInit",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* Check if ark_mem was allocated */
if (ark_mem->MallocDone == SUNFALSE) {
arkProcessError(ark_mem, ARK_NO_MALLOC, "ARKode::ARKStep",
"ARKStepReInit", MSG_ARK_NO_MALLOC);
return(ARK_NO_MALLOC);
}
/* Check that at least one of fe, fi is supplied and is to be used */
if (fe == NULL && fi == NULL) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep",
"ARKStepReInit", MSG_ARK_NULL_F);
return(ARK_ILL_INPUT);
}
/* Check that y0 is supplied */
if (y0 == NULL) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep",
"ARKStepReInit", MSG_ARK_NULL_Y0);
return(ARK_ILL_INPUT);
}
/* Set implicit/explicit problem based on function pointers */
step_mem->explicit = (fe == NULL) ? SUNFALSE : SUNTRUE;
step_mem->implicit = (fi == NULL) ? SUNFALSE : SUNTRUE;
/* Copy the input parameters into ARKode state */
step_mem->fe = fe;
step_mem->fi = fi;
/* Initialize initial error norm */
step_mem->eRNrm = ONE;
/* Initialize main ARKode infrastructure */
retval = arkInit(ark_mem, t0, y0, FIRST_INIT);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, retval, "ARKode::ARKStep", "ARKStepReInit",
"Unable to reinitialize main ARKode infrastructure");
return(retval);
}
/* Initialize all the counters */
step_mem->nfe = 0;
step_mem->nfi = 0;
step_mem->nsetups = 0;
step_mem->nstlp = 0;
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
ARKStepReset:
This routine resets the ARKStep module state to solve the same
problem from the given time with the input state (all counter
values are retained).
---------------------------------------------------------------*/
int ARKStepReset(void* arkode_mem, realtype tR, N_Vector yR)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "ARKStepReset",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* Initialize main ARKode infrastructure */
retval = arkInit(ark_mem, tR, yR, RESET_INIT);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, retval, "ARKode::ARKStep", "ARKStepReset",
"Unable to initialize main ARKode infrastructure");
return(retval);
}
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
ARKStepSStolerances, ARKStepSVtolerances, ARKStepWFtolerances,
ARKStepResStolerance, ARKStepResVtolerance, ARKStepResFtolerance:
These routines set integration tolerances (wrappers for general
ARKode utility routines)
---------------------------------------------------------------*/
int ARKStepSStolerances(void *arkode_mem, realtype reltol, realtype abstol)
{
/* unpack ark_mem, call arkSStolerances, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepSStolerances", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkSStolerances(ark_mem, reltol, abstol));
}
int ARKStepSVtolerances(void *arkode_mem, realtype reltol, N_Vector abstol)
{
/* unpack ark_mem, call arkSVtolerances, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepSVtolerances", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkSVtolerances(ark_mem, reltol, abstol));
}
int ARKStepWFtolerances(void *arkode_mem, ARKEwtFn efun)
{
/* unpack ark_mem, call arkWFtolerances, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepWFtolerances", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkWFtolerances(ark_mem, efun));
}
int ARKStepResStolerance(void *arkode_mem, realtype rabstol)
{
/* unpack ark_mem, call arkResStolerance, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepResStolerance", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkResStolerance(ark_mem, rabstol));
}
int ARKStepResVtolerance(void *arkode_mem, N_Vector rabstol)
{
/* unpack ark_mem, call arkResVtolerance, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepResVtolerance", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkResVtolerance(ark_mem, rabstol));
}
int ARKStepResFtolerance(void *arkode_mem, ARKRwtFn rfun)
{
/* unpack ark_mem, call arkResFtolerance, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepResFtolerance", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkResFtolerance(ark_mem, rfun));
}
/*---------------------------------------------------------------
ARKStepRootInit:
Initialize (attach) a rootfinding problem to the stepper
(wrappers for general ARKode utility routine)
---------------------------------------------------------------*/
int ARKStepRootInit(void *arkode_mem, int nrtfn, ARKRootFn g)
{
/* unpack ark_mem, call arkRootInit, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepRootInit", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkRootInit(ark_mem, nrtfn, g));
}
/*---------------------------------------------------------------
ARKStepEvolve:
This is the main time-integration driver (wrappers for general
ARKode utility routine)
---------------------------------------------------------------*/
int ARKStepEvolve(void *arkode_mem, realtype tout, N_Vector yout,
realtype *tret, int itask)
{
/* unpack ark_mem, call arkEvolve, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepEvolve", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkEvolve(ark_mem, tout, yout, tret, itask));
}
/*---------------------------------------------------------------
ARKStepGetDky:
This returns interpolated output of the solution or its
derivatives over the most-recently-computed step (wrapper for
generic ARKode utility routine)
---------------------------------------------------------------*/
int ARKStepGetDky(void *arkode_mem, realtype t, int k, N_Vector dky)
{
/* unpack ark_mem, call arkGetDky, and return */
ARKodeMem ark_mem;
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"ARKStepGetDky", MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
ark_mem = (ARKodeMem) arkode_mem;
return(arkGetDky(ark_mem, t, k, dky));
}
/*---------------------------------------------------------------
ARKStepComputeState:
Computes y based on the current prediction and given correction.
---------------------------------------------------------------*/
int ARKStepComputeState(void *arkode_mem, N_Vector zcor, N_Vector z)
{
int retval;
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "ARKStepComputeState",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
N_VLinearSum(ONE, step_mem->zpred, ONE, zcor, z);
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
ARKStepFree frees all ARKStep memory, and then calls an ARKode
utility routine to free the ARKode infrastructure memory.
---------------------------------------------------------------*/
void ARKStepFree(void **arkode_mem)
{
int j;
sunindextype Bliw, Blrw;
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
/* nothing to do if arkode_mem is already NULL */
if (*arkode_mem == NULL) return;
/* conditional frees on non-NULL ARKStep module */
ark_mem = (ARKodeMem) (*arkode_mem);
if (ark_mem->step_mem != NULL) {
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* free the Butcher tables */
if (step_mem->Be != NULL) {
ARKodeButcherTable_Space(step_mem->Be, &Bliw, &Blrw);
ARKodeButcherTable_Free(step_mem->Be);
step_mem->Be = NULL;
ark_mem->liw -= Bliw;
ark_mem->lrw -= Blrw;
}
if (step_mem->Bi != NULL) {
ARKodeButcherTable_Space(step_mem->Bi, &Bliw, &Blrw);
ARKodeButcherTable_Free(step_mem->Bi);
step_mem->Bi = NULL;
ark_mem->liw -= Bliw;
ark_mem->lrw -= Blrw;
}
/* free the nonlinear solver memory (if applicable) */
if ((step_mem->NLS != NULL) && (step_mem->ownNLS)) {
SUNNonlinSolFree(step_mem->NLS);
step_mem->ownNLS = SUNFALSE;
}
step_mem->NLS = NULL;
/* free the linear solver memory */
if (step_mem->lfree != NULL) {
step_mem->lfree((void *) ark_mem);
step_mem->lmem = NULL;
}
/* free the mass matrix solver memory */
if (step_mem->mfree != NULL) {
step_mem->mfree((void *) ark_mem);
step_mem->mass_mem = NULL;
}
/* free the sdata, zpred and zcor vectors */
if (step_mem->sdata != NULL) {
arkFreeVec(ark_mem, &step_mem->sdata);
step_mem->sdata = NULL;
}
if (step_mem->zpred != NULL) {
arkFreeVec(ark_mem, &step_mem->zpred);
step_mem->zpred = NULL;
}
if (step_mem->zcor != NULL) {
arkFreeVec(ark_mem, &step_mem->zcor);
step_mem->zcor = NULL;
}
/* free the RHS vectors */
if (step_mem->Fe != NULL) {
for(j=0; j<step_mem->stages; j++)
arkFreeVec(ark_mem, &step_mem->Fe[j]);
free(step_mem->Fe);
step_mem->Fe = NULL;
ark_mem->liw -= step_mem->stages;
}
if (step_mem->Fi != NULL) {
for(j=0; j<step_mem->stages; j++)
arkFreeVec(ark_mem, &step_mem->Fi[j]);
free(step_mem->Fi);
step_mem->Fi = NULL;
ark_mem->liw -= step_mem->stages;
}
/* free the reusable arrays for fused vector interface */
if (step_mem->cvals != NULL) {
free(step_mem->cvals);
step_mem->cvals = NULL;
ark_mem->lrw -= step_mem->nfusedopvecs;
}
if (step_mem->Xvecs != NULL) {
free(step_mem->Xvecs);
step_mem->Xvecs = NULL;
ark_mem->liw -= step_mem->nfusedopvecs;
}
step_mem->nfusedopvecs = 0;
/* free the time stepper module itself */
free(ark_mem->step_mem);
ark_mem->step_mem = NULL;
}
/* free memory for overall ARKode infrastructure */
arkFree(arkode_mem);
}
/*---------------------------------------------------------------
ARKStepPrintMem:
This routine outputs the memory from the ARKStep structure and
the main ARKode infrastructure to a specified file pointer
(useful when debugging).
---------------------------------------------------------------*/
void ARKStepPrintMem(void* arkode_mem, FILE* outfile)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
#ifdef SUNDIALS_DEBUG_PRINTVEC
int i;
#endif
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "ARKStepPrintMem",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return;
/* if outfile==NULL, set it to stdout */
if (outfile == NULL) outfile = stdout;
/* output data from main ARKode infrastructure */
arkPrintMem(ark_mem, outfile);
/* output integer quantities */
fprintf(outfile,"ARKStep: q = %i\n", step_mem->q);
fprintf(outfile,"ARKStep: p = %i\n", step_mem->p);
fprintf(outfile,"ARKStep: istage = %i\n", step_mem->istage);
fprintf(outfile,"ARKStep: stages = %i\n", step_mem->stages);
fprintf(outfile,"ARKStep: maxcor = %i\n", step_mem->maxcor);
fprintf(outfile,"ARKStep: msbp = %i\n", step_mem->msbp);
fprintf(outfile,"ARKStep: predictor = %i\n", step_mem->predictor);
fprintf(outfile,"ARKStep: lsolve_type = %i\n", step_mem->lsolve_type);
fprintf(outfile,"ARKStep: msolve_type = %i\n", step_mem->msolve_type);
fprintf(outfile,"ARKStep: convfail = %i\n", step_mem->convfail);
/* output long integer quantities */
fprintf(outfile,"ARKStep: nfe = %li\n", step_mem->nfe);
fprintf(outfile,"ARKStep: nfi = %li\n", step_mem->nfi);
fprintf(outfile,"ARKStep: nsetups = %li\n", step_mem->nsetups);
fprintf(outfile,"ARKStep: nstlp = %li\n", step_mem->nstlp);
/* output boolean quantities */
fprintf(outfile,"ARKStep: user_linear = %i\n", step_mem->linear);
fprintf(outfile,"ARKStep: user_linear_timedep = %i\n", step_mem->linear_timedep);
fprintf(outfile,"ARKStep: user_explicit = %i\n", step_mem->explicit);
fprintf(outfile,"ARKStep: user_implicit = %i\n", step_mem->implicit);
fprintf(outfile,"ARKStep: jcur = %i\n", step_mem->jcur);
/* output realtype quantities */
if (step_mem->Be != NULL) {
fprintf(outfile,"ARKStep: explicit Butcher table:\n");
ARKodeButcherTable_Write(step_mem->Be, outfile);
}
if (step_mem->Bi != NULL) {
fprintf(outfile,"ARKStep: implicit Butcher table:\n");
ARKodeButcherTable_Write(step_mem->Bi, outfile);
}
fprintf(outfile,"ARKStep: gamma = %"RSYM"\n", step_mem->gamma);
fprintf(outfile,"ARKStep: gammap = %"RSYM"\n", step_mem->gammap);
fprintf(outfile,"ARKStep: gamrat = %"RSYM"\n", step_mem->gamrat);
fprintf(outfile,"ARKStep: crate = %"RSYM"\n", step_mem->crate);
fprintf(outfile,"ARKStep: eRNrm = %"RSYM"\n", step_mem->eRNrm);
fprintf(outfile,"ARKStep: nlscoef = %"RSYM"\n", step_mem->nlscoef);
fprintf(outfile,"ARKStep: crdown = %"RSYM"\n", step_mem->crdown);
fprintf(outfile,"ARKStep: rdiv = %"RSYM"\n", step_mem->rdiv);
fprintf(outfile,"ARKStep: dgmax = %"RSYM"\n", step_mem->dgmax);
#ifdef SUNDIALS_DEBUG_PRINTVEC
/* output vector quantities */
fprintf(outfile, "ARKStep: sdata:\n");
N_VPrintFile(step_mem->sdata, outfile);
fprintf(outfile, "ARKStep: zpred:\n");
N_VPrintFile(step_mem->zpred, outfile);
fprintf(outfile, "ARKStep: zcor:\n");
N_VPrintFile(step_mem->zcor, outfile);
if (step_mem->Fe != NULL)
for (i=0; i<step_mem->stages; i++) {
fprintf(outfile,"ARKStep: Fe[%i]:\n", i);
N_VPrintFile(step_mem->Fe[i], outfile);
}
if (step_mem->Fi != NULL)
for (i=0; i<step_mem->stages; i++) {
fprintf(outfile,"ARKStep: Fi[%i]:\n", i);
N_VPrintFile(step_mem->Fi[i], outfile);
}
#endif
}
/*===============================================================
ARKStep Private functions
===============================================================*/
/*---------------------------------------------------------------
Interface routines supplied to ARKode
---------------------------------------------------------------*/
/*---------------------------------------------------------------
arkStep_AttachLinsol:
This routine attaches the various set of system linear solver
interface routines, data structure, and solver type to the
ARKStep module.
---------------------------------------------------------------*/
int arkStep_AttachLinsol(void* arkode_mem, ARKLinsolInitFn linit,
ARKLinsolSetupFn lsetup,
ARKLinsolSolveFn lsolve,
ARKLinsolFreeFn lfree,
SUNLinearSolver_Type lsolve_type,
void *lmem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_AttachLinsol",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* free any existing system solver */
if (step_mem->lfree != NULL) step_mem->lfree(arkode_mem);
/* Attach the provided routines, data structure and solve type */
step_mem->linit = linit;
step_mem->lsetup = lsetup;
step_mem->lsolve = lsolve;
step_mem->lfree = lfree;
step_mem->lmem = lmem;
step_mem->lsolve_type = lsolve_type;
/* Reset all linear solver counters */
step_mem->nsetups = 0;
step_mem->nstlp = 0;
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_AttachMasssol:
This routine attaches the set of mass matrix linear solver
interface routines, data structure, and solver type to the
ARKStep module.
---------------------------------------------------------------*/
int arkStep_AttachMasssol(void* arkode_mem,
ARKMassInitFn minit,
ARKMassSetupFn msetup,
ARKMassMultFn mmult,
ARKMassSolveFn msolve,
ARKMassFreeFn mfree,
booleantype time_dep,
SUNLinearSolver_Type msolve_type,
void *mass_mem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_AttachMasssol",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* free any existing mass matrix solver */
if (step_mem->mfree != NULL) step_mem->mfree(arkode_mem);
/* Attach the provided routines, data structure and solve type */
step_mem->minit = minit;
step_mem->msetup = msetup;
step_mem->mmult = mmult;
step_mem->msolve = msolve;
step_mem->mfree = mfree;
step_mem->mass_mem = mass_mem;
step_mem->mass_type = (time_dep) ? MASS_TIMEDEP : MASS_FIXED;
step_mem->msolve_type = msolve_type;
/* Attach mmult function pointer to ark_mem as well */
ark_mem->step_mmult = mmult;
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_DisableLSetup:
This routine NULLifies the lsetup function pointer in the
ARKStep module.
---------------------------------------------------------------*/
void arkStep_DisableLSetup(void* arkode_mem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
/* access ARKodeARKStepMem structure */
if (arkode_mem==NULL) return;
ark_mem = (ARKodeMem) arkode_mem;
if (ark_mem->step_mem==NULL) return;
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* nullify the lsetup function pointer */
step_mem->lsetup = NULL;
}
/*---------------------------------------------------------------
arkStep_DisableMSetup:
This routine NULLifies the msetup function pointer in the
ARKStep module.
---------------------------------------------------------------*/
void arkStep_DisableMSetup(void* arkode_mem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
/* access ARKodeARKStepMem structure */
if (arkode_mem==NULL) return;
ark_mem = (ARKodeMem) arkode_mem;
if (ark_mem->step_mem==NULL) return;
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* nullify the msetup function pointer */
step_mem->msetup = NULL;
}
/*---------------------------------------------------------------
arkStep_GetLmem:
This routine returns the system linear solver interface memory
structure, lmem.
---------------------------------------------------------------*/
void* arkStep_GetLmem(void* arkode_mem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure, and return lmem */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_GetLmem",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(NULL);
return(step_mem->lmem);
}
/*---------------------------------------------------------------
arkStep_GetMassMem:
This routine returns the mass matrix solver interface memory
structure, mass_mem.
---------------------------------------------------------------*/
void* arkStep_GetMassMem(void* arkode_mem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure, and return mass_mem */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_GetMassMem",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(NULL);
return(step_mem->mass_mem);
}
/*---------------------------------------------------------------
arkStep_GetImplicitRHS:
This routine returns the implicit RHS function pointer, fi.
---------------------------------------------------------------*/
ARKRhsFn arkStep_GetImplicitRHS(void* arkode_mem)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure, and return fi */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_GetImplicitRHS",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(NULL);
return(step_mem->fi);
}
/*---------------------------------------------------------------
arkStep_GetGammas:
This routine fills the current value of gamma, and states
whether the gamma ratio fails the dgmax criteria.
---------------------------------------------------------------*/
int arkStep_GetGammas(void* arkode_mem, realtype *gamma,
realtype *gamrat, booleantype **jcur,
booleantype *dgamma_fail)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_GetGammas",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* set outputs */
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
*gamma = step_mem->gamma;
*gamrat = step_mem->gamrat;
*jcur = &step_mem->jcur;
*dgamma_fail = (SUNRabs(*gamrat - ONE) >= step_mem->dgmax);
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_Init:
This routine is called just prior to performing internal time
steps (after all user "set" routines have been called) from
within arkInitialSetup.
For all initialization types, this routine sets the relevant
TakeStep routine based on the current problem configuration.
With initialization type FIRST_INIT this routine:
- sets/checks the ARK Butcher tables to be used
- allocates any memory that depends on the number of ARK stages,
method order, or solver options
- checks for consistency between the system and mass matrix
linear solvers (if applicable)
- initializes and sets up the system and mass matrix linear
solvers (if applicable)
- initializes and sets up the nonlinear solver (if applicable)
- allocates the interpolation data structure (if needed based
on ARKStep solver options)
- updates the call_fullrhs flag if necessary
With initialization type FIRST_INIT or RESIZE_INIT, this routine:
- sets the relevant TakeStep routine based on the current
problem configuration
- checks for consistency between the system and mass matrix
linear solvers (if applicable)
- initializes and sets up the system and mass matrix linear
solvers (if applicable)
- initializes and sets up the nonlinear solver (if applicable)
With initialization type RESET_INIT, this routine does nothing.
---------------------------------------------------------------*/
int arkStep_Init(void* arkode_mem, int init_type)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int j, retval;
booleantype reset_efun;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_Init",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* immediately return if reset */
if (init_type == RESET_INIT) return(ARK_SUCCESS);
/* initializations/checks for (re-)initialization call */
if (init_type == FIRST_INIT) {
/* enforce use of arkEwtSmallReal if using a fixed step size for
an explicit method, an internal error weight function, and not
using an iterative mass matrix solver with rwt=ewt */
reset_efun = SUNTRUE;
if ( step_mem->implicit ) reset_efun = SUNFALSE;
if ( !ark_mem->fixedstep ) reset_efun = SUNFALSE;
if ( ark_mem->user_efun ) reset_efun = SUNFALSE;
if ( ark_mem->rwt_is_ewt && (step_mem->msolve_type == SUNLINEARSOLVER_ITERATIVE) )
reset_efun = SUNFALSE;
if ( ark_mem->rwt_is_ewt && (step_mem->msolve_type == SUNLINEARSOLVER_MATRIX_ITERATIVE) )
reset_efun = SUNFALSE;
if (reset_efun) {
ark_mem->user_efun = SUNFALSE;
ark_mem->efun = arkEwtSetSmallReal;
ark_mem->e_data = ark_mem;
}
/* Create Butcher tables (if not already set) */
retval = arkStep_SetButcherTables(ark_mem);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep", "arkStep_Init",
"Could not create Butcher table(s)");
return(ARK_ILL_INPUT);
}
/* Check that Butcher tables are OK */
retval = arkStep_CheckButcherTables(ark_mem);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep",
"arkStep_Init", "Error in Butcher table(s)");
return(ARK_ILL_INPUT);
}
/* Retrieve/store method and embedding orders now that tables are finalized */
if (step_mem->Bi != NULL) {
step_mem->q = ark_mem->hadapt_mem->q = step_mem->Bi->q;
step_mem->p = ark_mem->hadapt_mem->p = step_mem->Bi->p;
} else {
step_mem->q = ark_mem->hadapt_mem->q = step_mem->Be->q;
step_mem->p = ark_mem->hadapt_mem->p = step_mem->Be->p;
}
/* Ensure that if adaptivity is enabled, then method includes embedding coefficients */
if (!ark_mem->fixedstep && (step_mem->p == 0)) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep", "arkStep_Init",
"Adaptive timestepping cannot be performed without embedding coefficients");
return(ARK_ILL_INPUT);
}
/* Allocate ARK RHS vector memory, update storage requirements */
/* Allocate Fe[0] ... Fe[stages-1] if needed */
if (step_mem->explicit) {
if (step_mem->Fe == NULL)
step_mem->Fe = (N_Vector *) calloc(step_mem->stages, sizeof(N_Vector));
for (j=0; j<step_mem->stages; j++) {
if (!arkAllocVec(ark_mem, ark_mem->ewt, &(step_mem->Fe[j])))
return(ARK_MEM_FAIL);
}
ark_mem->liw += step_mem->stages; /* pointers */
}
/* Allocate Fi[0] ... Fi[stages-1] if needed */
if (step_mem->implicit) {
if (step_mem->Fi == NULL)
step_mem->Fi = (N_Vector *) calloc(step_mem->stages, sizeof(N_Vector));
for (j=0; j<step_mem->stages; j++) {
if (!arkAllocVec(ark_mem, ark_mem->ewt, &(step_mem->Fi[j])))
return(ARK_MEM_FAIL);
}
ark_mem->liw += step_mem->stages; /* pointers */
}
/* Allocate reusable arrays for fused vector operations */
step_mem->nfusedopvecs = 2 * step_mem->stages + 2 + step_mem->nforcing;
if (step_mem->cvals == NULL) {
step_mem->cvals = (realtype *) calloc(step_mem->nfusedopvecs,
sizeof(realtype));
if (step_mem->cvals == NULL) return(ARK_MEM_FAIL);
ark_mem->lrw += step_mem->nfusedopvecs;
}
if (step_mem->Xvecs == NULL) {
step_mem->Xvecs = (N_Vector *) calloc(step_mem->nfusedopvecs,
sizeof(N_Vector));
if (step_mem->Xvecs == NULL) return(ARK_MEM_FAIL);
ark_mem->liw += step_mem->nfusedopvecs; /* pointers */
}
/* Limit interpolant degree based on method order (use negative
argument to specify update instead of overwrite) */
if (ark_mem->interp != NULL) {
retval = arkInterpSetDegree(ark_mem, ark_mem->interp, -(step_mem->q-1));
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep", "arkStep_Init",
"Unable to update interpolation polynomial degree");
return(ARK_ILL_INPUT);
}
}
/* If configured with either predictor 4 or 5 and a non-identity mass
matrix, reset to trivial predictor */
if (step_mem->mass_type != MASS_IDENTITY)
if ((step_mem->predictor == 4) || (step_mem->predictor == 5))
step_mem->predictor = 0;
/* If the bootstrap predictor is enabled, signal to shared arkode module that
fullrhs is required after each step */
if (step_mem->predictor == 4) ark_mem->call_fullrhs = SUNTRUE;
}
/* set appropriate TakeStep routine based on problem configuration */
/* (only one choice for now) */
ark_mem->step = arkStep_TakeStep_Z;
/* Check for consistency between mass system and system linear system modules
(e.g., if lsolve is direct, msolve needs to match) */
if ((step_mem->mass_type != MASS_IDENTITY) && step_mem->lmem) {
if (step_mem->lsolve_type != step_mem->msolve_type) {
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep", "arkStep_Init",
"Incompatible linear and mass matrix solvers");
return(ARK_ILL_INPUT);
}
}
/* Perform mass matrix solver initialization and setup (if applicable) */
if (step_mem->mass_type != MASS_IDENTITY) {
/* Call minit (if it exists) */
if (step_mem->minit != NULL) {
retval = step_mem->minit((void *) ark_mem);
if (retval != 0) {
arkProcessError(ark_mem, ARK_MASSINIT_FAIL, "ARKode::ARKStep",
"arkStep_Init", MSG_ARK_MASSINIT_FAIL);
return(ARK_MASSINIT_FAIL);
}
}
/* Call msetup (if it exists) */
if (step_mem->msetup != NULL) {
retval = step_mem->msetup((void *) ark_mem, ark_mem->tcur,
ark_mem->tempv1, ark_mem->tempv2,
ark_mem->tempv3);
if (retval != 0) {
arkProcessError(ark_mem, ARK_MASSSETUP_FAIL, "ARKode::ARKStep",
"arkStep_Init", MSG_ARK_MASSSETUP_FAIL);
return(ARK_MASSSETUP_FAIL);
}
}
}
/* Call linit (if it exists) */
if (step_mem->linit) {
retval = step_mem->linit(ark_mem);
if (retval != 0) {
arkProcessError(ark_mem, ARK_LINIT_FAIL, "ARKode::ARKStep",
"arkStep_Init", MSG_ARK_LINIT_FAIL);
return(ARK_LINIT_FAIL);
}
}
/* Initialize the nonlinear solver object (if it exists) */
if (step_mem->NLS) {
retval = arkStep_NlsInit(ark_mem);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_NLS_INIT_FAIL, "ARKode::ARKStep", "arkStep_Init",
"Unable to initialize SUNNonlinearSolver object");
return(ARK_NLS_INIT_FAIL);
}
}
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_FullRHS:
Rewriting the problem
My' = fe(t,y) + fi(t,y)
in the form
y' = M^{-1}*[ fe(t,y) + fi(t,y) ],
this routine computes the full right-hand side vector,
f = M^{-1}*[ fe(t,y) + fi(t,y) ]
This will be called in one of three 'modes':
0 -> called at the beginning of a simulation
1 -> called at the end of a successful step
2 -> called elsewhere (e.g. for dense output)
If it is called in mode 0, we store the vectors fe(t,y) and
fi(t,y) in Fe[0] and Fi[0] for possible reuse in the first
stage of the subsequent time step.
If it is called in mode 1 and the ARK method coefficients
support it, we may just copy vectors Fe[stages] and Fi[stages]
to fill f instead of calling fe() and fi().
Mode 2 is only called for dense output in-between steps, or
when estimating the initial time step size, so we strive to
store the intermediate parts so that they do not interfere
with the other two modes.
---------------------------------------------------------------*/
int arkStep_FullRHS(void* arkode_mem, realtype t,
N_Vector y, N_Vector f, int mode)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int nvec, retval;
booleantype recomputeRHS;
realtype* cvals;
N_Vector* Xvecs;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_FullRHS",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* local shortcuts for use with fused vector operations */
cvals = step_mem->cvals;
Xvecs = step_mem->Xvecs;
/* setup mass-matrix if required (use output f as a temporary) */
if ((step_mem->mass_type == MASS_TIMEDEP) && (step_mem->msetup != NULL)) {
retval = step_mem->msetup((void *) ark_mem, t, f,
ark_mem->tempv2, ark_mem->tempv3);
if (retval != ARK_SUCCESS) return(ARK_MASSSETUP_FAIL);
}
/* perform RHS functions contingent on 'mode' argument */
switch(mode) {
/* Mode 0: called at the beginning of a simulation
Store the vectors fe(t,y) and fi(t,y) in Fe[0] and Fi[0] for
possible reuse in the first stage of the subsequent time step */
case 0:
/* call fe if the problem has an explicit component */
if (step_mem->explicit) {
retval = step_mem->fe(t, y, step_mem->Fe[0], ark_mem->user_data);
step_mem->nfe++;
if (retval != 0) {
arkProcessError(ark_mem, ARK_RHSFUNC_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", MSG_ARK_RHSFUNC_FAILED, t);
return(ARK_RHSFUNC_FAIL);
}
/* apply external polynomial forcing */
if (step_mem->expforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->Fe[0];
nvec = 1;
arkStep_ApplyForcing(step_mem, t, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->Fe[0]);
}
}
/* call fi if the problem has an implicit component */
if (step_mem->implicit) {
retval = step_mem->fi(t, y, step_mem->Fi[0], ark_mem->user_data);
step_mem->nfi++;
if (retval != 0) {
arkProcessError(ark_mem, ARK_RHSFUNC_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", MSG_ARK_RHSFUNC_FAILED, t);
return(ARK_RHSFUNC_FAIL);
}
/* apply external polynomial forcing */
if (step_mem->impforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->Fi[0];
nvec = 1;
arkStep_ApplyForcing(step_mem, t, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->Fi[0]);
}
}
/* combine RHS vector(s) into output */
if (step_mem->explicit && step_mem->implicit) { /* ImEx */
N_VLinearSum(ONE, step_mem->Fi[0], ONE, step_mem->Fe[0], f);
} else if (step_mem->implicit) { /* implicit */
N_VScale(ONE, step_mem->Fi[0], f);
} else { /* explicit */
N_VScale(ONE, step_mem->Fe[0], f);
}
break;
/* Mode 1: called at the end of a successful step
If the ARK method coefficients support it, we just copy the last stage RHS vectors
to fill f instead of calling fe() and fi().
Copy the results to Fe[0] and Fi[0] if the ARK coefficients support it. */
case 1:
/* determine if explicit/implicit RHS functions need to be recomputed */
recomputeRHS = SUNFALSE;
if ( step_mem->explicit && (SUNRabs(step_mem->Be->c[step_mem->stages-1]-ONE)>TINY) )
recomputeRHS = SUNTRUE;
if ( step_mem->implicit && (SUNRabs(step_mem->Bi->c[step_mem->stages-1]-ONE)>TINY) )
recomputeRHS = SUNTRUE;
/* base RHS calls on recomputeRHS argument */
if (recomputeRHS) {
/* call fe if the problem has an explicit component */
if (step_mem->explicit) {
retval = step_mem->fe(t, y, step_mem->Fe[0], ark_mem->user_data);
step_mem->nfe++;
if (retval != 0) {
arkProcessError(ark_mem, ARK_RHSFUNC_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", MSG_ARK_RHSFUNC_FAILED, t);
return(ARK_RHSFUNC_FAIL);
}
/* apply external polynomial forcing */
if (step_mem->expforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->Fe[0];
nvec = 1;
arkStep_ApplyForcing(step_mem, t, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->Fe[0]);
}
}
/* call fi if the problem has an implicit component */
if (step_mem->implicit) {
retval = step_mem->fi(t, y, step_mem->Fi[0], ark_mem->user_data);
step_mem->nfi++;
if (retval != 0) {
arkProcessError(ark_mem, ARK_RHSFUNC_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", MSG_ARK_RHSFUNC_FAILED, t);
return(ARK_RHSFUNC_FAIL);
}
/* apply external polynomial forcing */
if (step_mem->impforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->Fi[0];
nvec = 1;
arkStep_ApplyForcing(step_mem, t, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->Fi[0]);
}
}
} else {
if (step_mem->explicit)
N_VScale(ONE, step_mem->Fe[step_mem->stages-1], step_mem->Fe[0]);
if (step_mem->implicit)
N_VScale(ONE, step_mem->Fi[step_mem->stages-1], step_mem->Fi[0]);
}
/* combine RHS vector(s) into output */
if (step_mem->explicit && step_mem->implicit) { /* ImEx */
N_VLinearSum(ONE, step_mem->Fi[0], ONE, step_mem->Fe[0], f);
} else if (step_mem->implicit) { /* implicit */
N_VScale(ONE, step_mem->Fi[0], f);
} else { /* explicit */
N_VScale(ONE, step_mem->Fe[0], f);
}
break;
/* Mode 2: called for dense output in-between steps or for estimation
of the initial time step size, store the intermediate calculations
in such a way as to not interfere with the other two modes */
default:
/* call fe if the problem has an explicit component (store in ark_tempv2) */
if (step_mem->explicit) {
retval = step_mem->fe(t, y, ark_mem->tempv2, ark_mem->user_data);
step_mem->nfe++;
if (retval != 0) {
arkProcessError(ark_mem, ARK_RHSFUNC_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", MSG_ARK_RHSFUNC_FAILED, t);
return(ARK_RHSFUNC_FAIL);
}
/* apply external polynomial forcing */
if (step_mem->expforcing) {
cvals[0] = ONE;
Xvecs[0] = ark_mem->tempv2;
nvec = 1;
arkStep_ApplyForcing(step_mem, t, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, ark_mem->tempv2);
}
}
/* call fi if the problem has an implicit component (store in sdata) */
if (step_mem->implicit) {
retval = step_mem->fi(t, y, step_mem->sdata, ark_mem->user_data);
step_mem->nfi++;
if (retval != 0) {
arkProcessError(ark_mem, ARK_RHSFUNC_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", MSG_ARK_RHSFUNC_FAILED, t);
return(ARK_RHSFUNC_FAIL);
}
/* apply external polynomial forcing */
if (step_mem->impforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->sdata;
nvec = 1;
arkStep_ApplyForcing(step_mem, t, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->sdata);
}
}
/* combine RHS vector(s) into output */
if (step_mem->explicit && step_mem->implicit) { /* ImEx */
N_VLinearSum(ONE, step_mem->sdata, ONE, ark_mem->tempv2, f);
} else if (step_mem->implicit) { /* implicit */
N_VScale(ONE, step_mem->sdata, f);
} else { /* explicit */
N_VScale(ONE, ark_mem->tempv2, f);
}
break;
}
/* if M != I, then update f = M^{-1}*f */
if (step_mem->mass_type != MASS_IDENTITY) {
retval = step_mem->msolve((void *) ark_mem, f,
step_mem->nlscoef/ark_mem->h);
if (retval != ARK_SUCCESS) {
arkProcessError(ark_mem, ARK_MASSSOLVE_FAIL, "ARKode::ARKStep",
"arkStep_FullRHS", "Mass matrix solver failure");
return(ARK_MASSSOLVE_FAIL);
}
}
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_TakeStep_Z:
This routine serves the primary purpose of the ARKStep module:
it performs a single ARK step (with embedding, if possible).
This version solves for each ARK stage vector, z_i.
The output variable dsmPtr should contain estimate of the
weighted local error if an embedding is present; otherwise it
should be 0.
The input/output variable nflagPtr is used to gauge convergence
of any algebraic solvers within the step. At the start of a new
time step, this will initially have the value FIRST_CALL. On
return from this function, nflagPtr should have a value:
0 => algebraic solve completed successfully
>0 => solve did not converge at this step size
(but may with a smaller stepsize)
<0 => solve encountered an unrecoverable failure
The return value from this routine is:
0 => step completed successfully
>0 => step encountered recoverable failure;
reduce step and retry (if possible)
<0 => step encountered unrecoverable failure
---------------------------------------------------------------*/
int arkStep_TakeStep_Z(void* arkode_mem, realtype *dsmPtr, int *nflagPtr)
{
int retval, is, nvec;
booleantype implicit_stage;
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
N_Vector zcor0;
realtype* cvals;
N_Vector* Xvecs;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_TakeStep_Z",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
/* local shortcuts for use with fused vector operations */
cvals = step_mem->cvals;
Xvecs = step_mem->Xvecs;
/* if problem will involve no algebraic solvers, initialize nflagPtr to success */
if ((!step_mem->implicit) && (step_mem->mass_type == MASS_IDENTITY))
*nflagPtr = ARK_SUCCESS;
/* call nonlinear solver setup if it exists */
if (step_mem->NLS)
if ((step_mem->NLS)->ops->setup) {
zcor0 = ark_mem->tempv3;
N_VConst(ZERO, zcor0); /* set guess to all 0 (since using predictor-corrector form) */
retval = SUNNonlinSolSetup(step_mem->NLS, zcor0, ark_mem);
if (retval < 0) return(ARK_NLS_SETUP_FAIL);
if (retval > 0) return(ARK_NLS_SETUP_RECVR);
}
/* loop over internal stages to the step */
for (is=0; is<step_mem->stages; is++) {
/* store current stage index */
step_mem->istage = is;
/* set current stage time(s) */
if (step_mem->implicit)
ark_mem->tcur = ark_mem->tn + step_mem->Bi->c[is]*ark_mem->h;
else
ark_mem->tcur = ark_mem->tn + step_mem->Be->c[is]*ark_mem->h;
#ifdef SUNDIALS_DEBUG
printf("step %li, stage %i, h = %"RSYM", t_n = %"RSYM"\n",
ark_mem->nst, is, ark_mem->h, ark_mem->tcur);
#endif
/* setup time-dependent mass matrix */
if ((step_mem->mass_type == MASS_TIMEDEP) && (step_mem->msetup != NULL)) {
retval = step_mem->msetup((void *) ark_mem, ark_mem->tcur,
ark_mem->tempv1, ark_mem->tempv2,
ark_mem->tempv3);
if (retval != ARK_SUCCESS) return(ARK_MASSSETUP_FAIL);
}
/* determine whether implicit solve is required */
implicit_stage = SUNFALSE;
if (step_mem->implicit)
if (SUNRabs(step_mem->Bi->A[is][is]) > TINY)
implicit_stage = SUNTRUE;
/* if implicit, call built-in and user-supplied predictors
(results placed in zpred) */
if (implicit_stage) {
retval = arkStep_Predict(ark_mem, is, step_mem->zpred);
if (retval != ARK_SUCCESS) return (retval);
/* if a user-supplied predictor routine is provided, call that here.
Note that arkStep_Predict is *still* called, so this user-supplied
routine can just 'clean up' the built-in prediction, if desired. */
if (step_mem->stage_predict) {
retval = step_mem->stage_predict(ark_mem->tcur, step_mem->zpred,
ark_mem->user_data);
if (retval < 0) return(ARK_USER_PREDICT_FAIL);
if (retval > 0) return(TRY_AGAIN);
}
}
#ifdef SUNDIALS_DEBUG_PRINTVEC
printf("predictor:\n");
N_VPrint(step_mem->zpred);
#endif
/* set up explicit data for evaluation of ARK stage (store in sdata) */
retval = arkStep_StageSetup(ark_mem, implicit_stage);
if (retval != ARK_SUCCESS) return (retval);
#ifdef SUNDIALS_DEBUG_PRINTVEC
printf("rhs data:\n");
N_VPrint(step_mem->sdata);
#endif
/* solver diagnostics reporting */
if (ark_mem->report)
fprintf(ark_mem->diagfp, "ARKStep step %li %"RSYM" %i %"RSYM"\n",
ark_mem->nst, ark_mem->h, is, ark_mem->tcur);
/* perform implicit solve if required */
if (implicit_stage) {
/* implicit solve result is stored in ark_mem->ycur;
return with positive value on anything but success */
*nflagPtr = arkStep_Nls(ark_mem, *nflagPtr);
if (*nflagPtr != ARK_SUCCESS) return(TRY_AGAIN);
#ifdef SUNDIALS_DEBUG_PRINTVEC
printf("nonlinear solution:\n");
N_VPrint(ark_mem->ycur);
#endif
/* otherwise no implicit solve is needed */
} else {
/* if M is fixed, solve with it to compute update (place back in sdata) */
if (step_mem->mass_type == MASS_FIXED) {
/* perform solve; return with positive value on anything but success */
*nflagPtr = step_mem->msolve((void *) ark_mem, step_mem->sdata,
step_mem->nlscoef);
if (*nflagPtr != ARK_SUCCESS) return(TRY_AGAIN);
}
/* set y to be yn + sdata (either computed in arkStep_StageSetup,
or updated in prev. block) */
N_VLinearSum(ONE, ark_mem->yn, ONE, step_mem->sdata, ark_mem->ycur);
#ifdef SUNDIALS_DEBUG_PRINTVEC
printf("explicit solution:\n");
N_VPrint(ark_mem->ycur);
#endif
}
/* apply user-supplied stage postprocessing function (if supplied) */
/* NOTE: with internally inconsistent IMEX methods (c_i^E != c_i^I) the value
of tcur corresponds to the stage time from the implicit table (c_i^I). */
if (ark_mem->ProcessStage != NULL) {
retval = ark_mem->ProcessStage(ark_mem->tcur,
ark_mem->ycur,
ark_mem->user_data);
if (retval != 0) return(ARK_POSTPROCESS_STAGE_FAIL);
}
/* successful stage solve */
/* store implicit RHS (value in Fi[is] is from preceding nonlinear iteration) */
if (step_mem->implicit) {
retval = step_mem->fi(ark_mem->tcur, ark_mem->ycur,
step_mem->Fi[is], ark_mem->user_data);
step_mem->nfi++;
if (retval < 0) return(ARK_RHSFUNC_FAIL);
if (retval > 0) return(ARK_UNREC_RHSFUNC_ERR);
/* apply external polynomial forcing */
if (step_mem->impforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->Fi[is];
nvec = 1;
arkStep_ApplyForcing(step_mem, ark_mem->tcur, ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->Fi[is]);
}
}
/* store explicit RHS */
if (step_mem->explicit) {
retval = step_mem->fe(ark_mem->tn + step_mem->Be->c[is]*ark_mem->h,
ark_mem->ycur, step_mem->Fe[is], ark_mem->user_data);
step_mem->nfe++;
if (retval < 0) return(ARK_RHSFUNC_FAIL);
if (retval > 0) return(ARK_UNREC_RHSFUNC_ERR);
/* apply external polynomial forcing */
if (step_mem->expforcing) {
cvals[0] = ONE;
Xvecs[0] = step_mem->Fe[is];
nvec = 1;
arkStep_ApplyForcing(step_mem, ark_mem->tn+step_mem->Be->c[is]*ark_mem->h,
ONE, &nvec);
N_VLinearCombination(nvec, cvals, Xvecs, step_mem->Fe[is]);
}
}
/* if using a time-dependent mass matrix, update Fe[is] and/or Fi[is] with M(t)^{-1} */
if (step_mem->mass_type == MASS_TIMEDEP) {
if (step_mem->implicit) {
*nflagPtr = step_mem->msolve((void *) ark_mem, step_mem->Fi[is], step_mem->nlscoef);
if (*nflagPtr != ARK_SUCCESS) return(TRY_AGAIN);
}
if (step_mem->explicit) {
*nflagPtr = step_mem->msolve((void *) ark_mem, step_mem->Fe[is], step_mem->nlscoef);
if (*nflagPtr != ARK_SUCCESS) return(TRY_AGAIN);
}
}
} /* loop over stages */
/* compute time-evolved solution (in ark_ycur), error estimate (in dsm).
This can fail recoverably due to nonconvergence of the mass matrix solve,
so handle that appropriately. */
if (step_mem->mass_type == MASS_FIXED) {
retval = arkStep_ComputeSolutions_MassFixed(ark_mem, dsmPtr);
} else {
retval = arkStep_ComputeSolutions(ark_mem, dsmPtr);
}
if (retval < 0) return(retval);
if (retval > 0) {
*nflagPtr = retval;
return(TRY_AGAIN);
}
#ifdef SUNDIALS_DEBUG
printf("error estimate = %"RSYM"\n", *dsmPtr);
#endif
/* solver diagnostics reporting */
if (ark_mem->report)
fprintf(ark_mem->diagfp, "ARKStep etest %li %"RSYM" %"RSYM"\n",
ark_mem->nst, ark_mem->h, *dsmPtr);
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
Internal utility routines
---------------------------------------------------------------*/
/*---------------------------------------------------------------
arkStep_AccessStepMem:
Shortcut routine to unpack ark_mem and step_mem structures from
void* pointer. If either is missing it returns ARK_MEM_NULL.
---------------------------------------------------------------*/
int arkStep_AccessStepMem(void* arkode_mem, const char *fname,
ARKodeMem *ark_mem, ARKodeARKStepMem *step_mem)
{
/* access ARKodeMem structure */
if (arkode_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
fname, MSG_ARK_NO_MEM);
return(ARK_MEM_NULL);
}
*ark_mem = (ARKodeMem) arkode_mem;
if ((*ark_mem)->step_mem==NULL) {
arkProcessError(*ark_mem, ARK_MEM_NULL, "ARKode::ARKStep",
fname, MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
*step_mem = (ARKodeARKStepMem) (*ark_mem)->step_mem;
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_CheckNVector:
This routine checks if all required vector operations are
present. If any of them is missing it returns SUNFALSE.
---------------------------------------------------------------*/
booleantype arkStep_CheckNVector(N_Vector tmpl)
{
if ( (tmpl->ops->nvclone == NULL) ||
(tmpl->ops->nvdestroy == NULL) ||
(tmpl->ops->nvlinearsum == NULL) ||
(tmpl->ops->nvconst == NULL) ||
(tmpl->ops->nvscale == NULL) ||
(tmpl->ops->nvwrmsnorm == NULL) )
return(SUNFALSE);
return(SUNTRUE);
}
/*---------------------------------------------------------------
arkStep_SetButcherTables
This routine determines the ERK/DIRK/ARK method to use, based
on the desired accuracy and information on whether the problem
is explicit, implicit or imex.
---------------------------------------------------------------*/
int arkStep_SetButcherTables(ARKodeMem ark_mem)
{
int etable, itable;
ARKodeARKStepMem step_mem;
sunindextype Blrw, Bliw;
/* access ARKodeARKStepMem structure */
if (ark_mem->step_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_SetButcherTables", MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* if tables have already been specified, just return */
if ( (step_mem->Be != NULL) || (step_mem->Bi != NULL) )
return(ARK_SUCCESS);
/* initialize table numbers to illegal values */
etable = itable = -1;
/**** ImEx methods ****/
if (step_mem->explicit && step_mem->implicit) {
switch (step_mem->q) {
case(2):
case(3):
etable = DEFAULT_ARK_ETABLE_3;
itable = DEFAULT_ARK_ITABLE_3;
break;
case(4):
etable = DEFAULT_ARK_ETABLE_4;
itable = DEFAULT_ARK_ITABLE_4;
break;
case(5):
etable = DEFAULT_ARK_ETABLE_5;
itable = DEFAULT_ARK_ITABLE_5;
break;
default: /* no available method, set default */
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep",
"arkStep_SetButcherTables",
"No ImEx method at requested order, using q=5.");
etable = DEFAULT_ARK_ETABLE_5;
itable = DEFAULT_ARK_ITABLE_5;
break;
}
/**** implicit methods ****/
} else if (step_mem->implicit) {
switch (step_mem->q) {
case(2):
itable = DEFAULT_DIRK_2;
break;
case(3):
itable = DEFAULT_DIRK_3;
break;
case(4):
itable = DEFAULT_DIRK_4;
break;
case(5):
itable = DEFAULT_DIRK_5;
break;
default: /* no available method, set default */
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep",
"arkStep_SetButcherTables",
"No implicit method at requested order, using q=5.");
itable = DEFAULT_DIRK_5;
break;
}
/**** explicit methods ****/
} else {
switch (step_mem->q) {
case(2):
etable = DEFAULT_ERK_2;
break;
case(3):
etable = DEFAULT_ERK_3;
break;
case(4):
etable = DEFAULT_ERK_4;
break;
case(5):
etable = DEFAULT_ERK_5;
break;
case(6):
etable = DEFAULT_ERK_6;
break;
case(7):
case(8):
etable = DEFAULT_ERK_8;
break;
default: /* no available method, set default */
arkProcessError(ark_mem, ARK_ILL_INPUT, "ARKode::ARKStep",
"arkStep_SetButcherTables",
"No explicit method at requested order, using q=6.");
etable = DEFAULT_ERK_6;
break;
}
}
if (etable > -1)
step_mem->Be = ARKodeButcherTable_LoadERK(etable);
if (itable > -1)
step_mem->Bi = ARKodeButcherTable_LoadDIRK(itable);
/* note Butcher table space requirements */
ARKodeButcherTable_Space(step_mem->Be, &Bliw, &Blrw);
ark_mem->liw += Bliw;
ark_mem->lrw += Blrw;
ARKodeButcherTable_Space(step_mem->Bi, &Bliw, &Blrw);
ark_mem->liw += Bliw;
ark_mem->lrw += Blrw;
/* set [redundant] ARK stored values for stage numbers and method orders */
if (step_mem->Be != NULL) {
step_mem->stages = step_mem->Be->stages;
step_mem->q = step_mem->Be->q;
step_mem->p = step_mem->Be->p;
}
if (step_mem->Bi != NULL) {
step_mem->stages = step_mem->Bi->stages;
step_mem->q = step_mem->Bi->q;
step_mem->p = step_mem->Bi->p;
}
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_CheckButcherTables
This routine runs through the explicit and/or implicit Butcher
tables to ensure that they meet all necessary requirements,
including:
strictly lower-triangular (ERK)
lower-triangular with some nonzeros on diagonal (IRK)
method order q > 0 (all)
embedding order q > 0 (all -- if adaptive time-stepping enabled)
stages > 0 (all)
Returns ARK_SUCCESS if tables pass, ARK_INVALID_TABLE otherwise.
---------------------------------------------------------------*/
int arkStep_CheckButcherTables(ARKodeMem ark_mem)
{
int i, j;
booleantype okay;
ARKodeARKStepMem step_mem;
realtype tol = RCONST(1.0e-12);
/* access ARKodeARKStepMem structure */
if (ark_mem->step_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_CheckButcherTables", MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* check that the expected tables are set */
if (step_mem->explicit && step_mem->Be == NULL) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"explicit table is NULL!");
return(ARK_INVALID_TABLE);
}
if (step_mem->implicit && step_mem->Bi == NULL) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"implicit table is NULL!");
return(ARK_INVALID_TABLE);
}
/* check that stages > 0 */
if (step_mem->stages < 1) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"stages < 1!");
return(ARK_INVALID_TABLE);
}
/* check that method order q > 0 */
if (step_mem->q < 1) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"method order < 1!");
return(ARK_INVALID_TABLE);
}
/* check that embedding order p > 0 */
if ((step_mem->p < 1) && (!ark_mem->fixedstep)) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"embedding order < 1!");
return(ARK_INVALID_TABLE);
}
/* check that embedding exists */
if ((step_mem->p > 0) && (!ark_mem->fixedstep)) {
if (step_mem->implicit) {
if (step_mem->Bi->d == NULL) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"no implicit embedding!");
return(ARK_INVALID_TABLE);
}
}
if (step_mem->explicit) {
if (step_mem->Be->d == NULL) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"no explicit embedding!");
return(ARK_INVALID_TABLE);
}
}
}
/* check that ERK table is strictly lower triangular */
if (step_mem->explicit) {
okay = SUNTRUE;
for (i=0; i<step_mem->stages; i++)
for (j=i; j<step_mem->stages; j++)
if (SUNRabs(step_mem->Be->A[i][j]) > tol)
okay = SUNFALSE;
if (!okay) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"Ae Butcher table is implicit!");
return(ARK_INVALID_TABLE);
}
}
/* check that IRK table is implicit and lower triangular */
if (step_mem->implicit) {
okay = SUNFALSE;
for (i=0; i<step_mem->stages; i++)
if (SUNRabs(step_mem->Bi->A[i][i]) > tol)
okay = SUNTRUE;
if (!okay) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"Ai Butcher table is explicit!");
return(ARK_INVALID_TABLE);
}
okay = SUNTRUE;
for (i=0; i<step_mem->stages; i++)
for (j=i+1; j<step_mem->stages; j++)
if (SUNRabs(step_mem->Bi->A[i][j]) > tol)
okay = SUNFALSE;
if (!okay) {
arkProcessError(ark_mem, ARK_INVALID_TABLE, "ARKode::ARKStep",
"arkStep_CheckButcherTables",
"Ai Butcher table has entries above diagonal!");
return(ARK_INVALID_TABLE);
}
}
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_Predict
This routine computes the prediction for a specific internal
stage solution, storing the result in yguess. The
prediction is done using the interpolation structure in
extrapolation mode, hence stages "far" from the previous time
interval are predicted using lower order polynomials than the
"nearby" stages.
---------------------------------------------------------------*/
int arkStep_Predict(ARKodeMem ark_mem, int istage, N_Vector yguess)
{
int i, retval, jstage, nvec;
realtype tau;
realtype h;
ARKodeARKStepMem step_mem;
realtype* cvals;
N_Vector* Xvecs;
/* access ARKodeARKStepMem structure */
if (ark_mem->step_mem == NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_Predict", MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* verify that interpolation structure is provided */
if ((ark_mem->interp == NULL) && (step_mem->predictor > 0) && (step_mem->predictor < 4)) {
arkProcessError(ark_mem, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_Predict",
"Interpolation structure is NULL");
return(ARK_MEM_NULL);
}
/* local shortcuts for use with fused vector operations */
cvals = step_mem->cvals;
Xvecs = step_mem->Xvecs;
/* if the first step, use initial condition as guess */
if (ark_mem->initsetup) {
N_VScale(ONE, ark_mem->yn, yguess);
return(ARK_SUCCESS);
}
/* set evaluation time tau as relative shift from previous successful time */
tau = step_mem->Bi->c[istage]*ark_mem->h/ark_mem->hold;
/* use requested predictor formula */
switch (step_mem->predictor) {
case 1:
/***** Interpolatory Predictor 1 -- all to max order *****/
retval = arkPredict_MaximumOrder(ark_mem, tau, yguess);
if (retval != ARK_ILL_INPUT) return(retval);
break;
case 2:
/***** Interpolatory Predictor 2 -- decrease order w/ increasing level of extrapolation *****/
retval = arkPredict_VariableOrder(ark_mem, tau, yguess);
if (retval != ARK_ILL_INPUT) return(retval);
break;
case 3:
/***** Cutoff predictor: max order interpolatory output for stages "close"
to previous step, first-order predictor for subsequent stages *****/
retval = arkPredict_CutoffOrder(ark_mem, tau, yguess);
if (retval != ARK_ILL_INPUT) return(retval);
break;
case 4:
/***** Bootstrap predictor: if any previous stage in step has nonzero c_i,
construct a quadratic Hermite interpolant for prediction; otherwise
use the trivial predictor. The actual calculations are performed in
arkPredict_Bootstrap, but here we need to determine the appropriate
stage, c_j, to use. *****/
/* determine if any previous stages in step meet criteria */
jstage = -1;
for (i=0; i<istage; i++)
jstage = (step_mem->Bi->c[i] != ZERO) ? i : jstage;
/* if using the trivial predictor, break */
if (jstage == -1) break;
/* find the "optimal" previous stage to use */
for (i=0; i<istage; i++)
if ( (step_mem->Bi->c[i] > step_mem->Bi->c[jstage]) &&
(step_mem->Bi->c[i] != ZERO) )
jstage = i;
/* set stage time, stage RHS and interpolation values */
h = ark_mem->h * step_mem->Bi->c[jstage];
tau = ark_mem->h * step_mem->Bi->c[istage];
nvec = 0;
if (step_mem->implicit) { /* Implicit piece */
cvals[nvec] = ONE;
Xvecs[nvec] = step_mem->Fi[jstage];
nvec += 1;
}
if (step_mem->explicit) { /* Explicit piece */
cvals[nvec] = ONE;
Xvecs[nvec] = step_mem->Fe[jstage];
nvec += 1;
}
/* call predictor routine */
retval = arkPredict_Bootstrap(ark_mem, h, tau, nvec, cvals, Xvecs, yguess);
if (retval != ARK_ILL_INPUT) return(retval);
break;
case 5:
/***** Minimal correction predictor: use all previous stage
information in this step *****/
/* set arrays for fused vector operation */
nvec = 0;
if (step_mem->explicit) { /* Explicit pieces */
for (jstage=0; jstage<istage; jstage++) {
cvals[nvec] = ark_mem->h * step_mem->Be->A[istage][jstage];
Xvecs[nvec] = step_mem->Fe[jstage];
nvec += 1;
}
}
if (step_mem->implicit) { /* Implicit pieces */
for (jstage=0; jstage<istage; jstage++) {
cvals[nvec] = ark_mem->h * step_mem->Bi->A[istage][jstage];
Xvecs[nvec] = step_mem->Fi[jstage];
nvec += 1;
}
}
cvals[nvec] = ONE;
Xvecs[nvec] = ark_mem->yn;
nvec += 1;
/* compute predictor */
retval = N_VLinearCombination(nvec, cvals, Xvecs, yguess);
if (retval != 0) return(ARK_VECTOROP_ERR);
return(ARK_SUCCESS);
break;
}
/* if we made it here, use the trivial predictor (previous step solution) */
N_VScale(ONE, ark_mem->yn, yguess);
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_StageSetup
This routine sets up the stage data for computing the RK
residual, along with the step- and method-related factors
gamma, gammap and gamrat.
The internal behavior of this setup depends on two factors:
(a) whether the stage is explicit or implicit, and
(b) the form of mass matrix (I, M, M(t)).
In each of the following:
* yn is the previous time step solution,
* r corresponds to the nonlinear residual,
* z=zp+zc corresponds to the updated stage solution, where
zp is the predictor (zp=yn for explicit stages), and zc
is the corrector,
* i is the current stage index, and
* g = h*Ai(i,i) is the implicit coefficient.
Explicit, I:
z = yn + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
<=>
zc = h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
This routine computes zc, stored in step_mem->sdata.
Implicit, I:
z = yn - h*sum_{j=0}^{i-1} Ae(i,j)*Fe(j)
- h*sum_{j=0}^{i} Ai(i,j)*Fi(j)
<=>
r = zc - g*Fi(i) - s
s = yn - zp + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
This routine computes s, stored in step_mem->sdata.
Explicit, M:
M*z = M*yn + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
<=>
M*zc = s
s = h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
This routine computes s, stored in step_mem->sdata.
Implicit, M:
M*z = M*yn + h*sum_{j=0}^{i-1} Ae(i,j)*Fe(j)
+ h*sum_{j=0}^{i} Ai(i,j)*Fi(j)
<=>
r = M*zc - g*Fi(i) - s
s = M*(yn - zp) + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
This routine computes s, stored in step_mem->sdata.
Explicit, M(t):
z = yn + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j)+Ai(i,j)*Fi(j))
<=>
zc = h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j)+Ai(i,j)*Fi(j))
This routine computes zc, stored in step_mem->sdata.
Implicit, M(t):
M(t)*z = M(t)*yn + h*sum_{j=0}^{i-1} Ae(i,j)*Fe(j)
+ h*sum_{j=0}^{i} Ai(i,j)*Fi(j)
<=>
r = M(t)*(zc - s) - g*Fi(i)
s = yn - zp + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
This routine computes s, stored in step_mem->sdata.
Thus _internal_ to this routine, we have 3 modes:
Explicit (any):
sdata = h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
Implicit, M:
sdata = M*(yn - zp) + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
Implicit, I or M(t):
sdata = yn - zp + h*sum_{j=0}^{i-1} (Ae(i,j)*Fe(j) + Ai(i,j)*Fi(j))
---------------------------------------------------------------*/
int arkStep_StageSetup(ARKodeMem ark_mem, booleantype implicit)
{
/* local data */
ARKodeARKStepMem step_mem;
int retval, i, j, nvec;
realtype* cvals;
N_Vector* Xvecs;
/* access ARKodeARKStepMem structure */
if (ark_mem->step_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_StageSetup", MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* Set shortcut to current stage index */
i = step_mem->istage;
/* If this is the first stage, and explicit, just set sdata=0 and return */
if (!implicit && (i==0)) {
N_VConst(ZERO, step_mem->sdata);
return (ARK_SUCCESS);
}
/* local shortcuts for fused vector operations */
cvals = step_mem->cvals;
Xvecs = step_mem->Xvecs;
/* Update gamma if stage is implicit */
if (implicit) {
step_mem->gamma = ark_mem->h * step_mem->Bi->A[i][i];
if (ark_mem->firststage)
step_mem->gammap = step_mem->gamma;
step_mem->gamrat = (ark_mem->firststage) ?
ONE : step_mem->gamma / step_mem->gammap; /* protect x/x != 1.0 */
}
/* If predictor==5, then sdata=0 (plus any implicit forcing).
Set sdata appropriately and return */
if (implicit && (step_mem->predictor == 5)) {
/* apply external polynomial forcing (updates nvec, cvals, Xvecs) */
if (step_mem->impforcing) {
nvec = 0;
arkStep_ApplyForcing(step_mem, ark_mem->tcur, step_mem->gamma, &nvec);
retval = N_VLinearCombination(nvec, cvals, Xvecs, step_mem->sdata);
if (retval != 0) return(ARK_VECTOROP_ERR);
} else {
N_VConst(ZERO, step_mem->sdata);
}
return (ARK_SUCCESS);
}
/* If implicit, initialize sdata to yn - zpred (here: zpred = zp), and set
first entries for eventual N_VLinearCombination call */
nvec = 0;
if (implicit) {
N_VLinearSum(ONE, ark_mem->yn, -ONE, step_mem->zpred, step_mem->sdata);
cvals[0] = ONE;
Xvecs[0] = step_mem->sdata;
nvec = 1;
}
/* If implicit with fixed M!=I, update sdata with M*sdata */
if (implicit && (step_mem->mass_type == MASS_FIXED)) {
N_VScale(ONE, step_mem->sdata, ark_mem->tempv1);
retval = step_mem->mmult((void *) ark_mem, ark_mem->tempv1, step_mem->sdata);
if (retval != ARK_SUCCESS) return (ARK_MASSMULT_FAIL);
}
/* Update sdata with prior stage information */
if (step_mem->explicit) { /* Explicit pieces */
for (j=0; j<i; j++) {
cvals[nvec] = ark_mem->h * step_mem->Be->A[i][j];
Xvecs[nvec] = step_mem->Fe[j];
nvec += 1;
}
}
if (step_mem->implicit) { /* Implicit pieces */
for (j=0; j<i; j++) {
cvals[nvec] = ark_mem->h * step_mem->Bi->A[i][j];
Xvecs[nvec] = step_mem->Fi[j];
nvec += 1;
}
}
/* apply external polynomial forcing (updates nvec, cvals, Xvecs) */
if (step_mem->impforcing) {
arkStep_ApplyForcing(step_mem, ark_mem->tcur,
ark_mem->h * step_mem->Bi->A[i][i], &nvec);
}
/* call fused vector operation to do the work */
retval = N_VLinearCombination(nvec, cvals, Xvecs, step_mem->sdata);
if (retval != 0) return(ARK_VECTOROP_ERR);
/* return with success */
return (ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_ComputeSolutions
This routine calculates the final RK solution using the existing
data. This solution is placed directly in ark_ycur. This routine
also computes the error estimate ||y-ytilde||_WRMS, where ytilde
is the embedded solution, and the norm weights come from
ark_ewt. This norm value is returned. The vector form of this
estimated error (y-ytilde) is stored in ark_mem->tempv1, in case
the calling routine wishes to examine the error locations.
This version assumes either an identity or time-dependent mass
matrix (identical steps).
---------------------------------------------------------------*/
int arkStep_ComputeSolutions(ARKodeMem ark_mem, realtype *dsmPtr)
{
/* local data */
int retval, j, nvec;
N_Vector y, yerr;
realtype* cvals;
N_Vector* Xvecs;
ARKodeARKStepMem step_mem;
/* access ARKodeARKStepMem structure */
if (ark_mem->step_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_ComputeSolutions", MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* set N_Vector shortcuts, and shortcut to time at end of step */
y = ark_mem->ycur;
yerr = ark_mem->tempv1;
/* local shortcuts for fused vector operations */
cvals = step_mem->cvals;
Xvecs = step_mem->Xvecs;
/* initialize output */
*dsmPtr = ZERO;
/* Compute time step solution */
/* set arrays for fused vector operation */
cvals[0] = ONE;
Xvecs[0] = ark_mem->yn;
nvec = 1;
for (j=0; j<step_mem->stages; j++) {
if (step_mem->explicit) { /* Explicit pieces */
cvals[nvec] = ark_mem->h * step_mem->Be->b[j];
Xvecs[nvec] = step_mem->Fe[j];
nvec += 1;
}
if (step_mem->implicit) { /* Implicit pieces */
cvals[nvec] = ark_mem->h * step_mem->Bi->b[j];
Xvecs[nvec] = step_mem->Fi[j];
nvec += 1;
}
}
/* call fused vector operation to do the work */
retval = N_VLinearCombination(nvec, cvals, Xvecs, y);
if (retval != 0) return(ARK_VECTOROP_ERR);
/* Compute yerr (if step adaptivity enabled) */
if (!ark_mem->fixedstep) {
/* set arrays for fused vector operation */
nvec = 0;
for (j=0; j<step_mem->stages; j++) {
if (step_mem->explicit) { /* Explicit pieces */
cvals[nvec] = ark_mem->h * (step_mem->Be->b[j] - step_mem->Be->d[j]);
Xvecs[nvec] = step_mem->Fe[j];
nvec += 1;
}
if (step_mem->implicit) { /* Implicit pieces */
cvals[nvec] = ark_mem->h * (step_mem->Bi->b[j] - step_mem->Bi->d[j]);
Xvecs[nvec] = step_mem->Fi[j];
nvec += 1;
}
}
/* call fused vector operation to do the work */
retval = N_VLinearCombination(nvec, cvals, Xvecs, yerr);
if (retval != 0) return(ARK_VECTOROP_ERR);
/* fill error norm */
*dsmPtr = N_VWrmsNorm(yerr, ark_mem->ewt);
}
return(ARK_SUCCESS);
}
/*---------------------------------------------------------------
arkStep_ComputeSolutions_MassFixed
This routine calculates the final RK solution using the existing
data. This solution is placed directly in ark_ycur. This routine
also computes the error estimate ||y-ytilde||_WRMS, where ytilde
is the embedded solution, and the norm weights come from
ark_ewt. This norm value is returned. The vector form of this
estimated error (y-ytilde) is stored in ark_mem->tempv1, in case
the calling routine wishes to examine the error locations.
This version assumes a fixed mass matrix.
---------------------------------------------------------------*/
int arkStep_ComputeSolutions_MassFixed(ARKodeMem ark_mem, realtype *dsmPtr)
{
/* local data */
int retval, j, nvec;
N_Vector y, yerr;
realtype* cvals;
N_Vector* Xvecs;
ARKodeARKStepMem step_mem;
/* access ARKodeARKStepMem structure */
if (ark_mem->step_mem==NULL) {
arkProcessError(NULL, ARK_MEM_NULL, "ARKode::ARKStep",
"arkStep_ComputeSolutions_MassFixed", MSG_ARKSTEP_NO_MEM);
return(ARK_MEM_NULL);
}
step_mem = (ARKodeARKStepMem) ark_mem->step_mem;
/* set N_Vector shortcuts, and shortcut to time at end of step */
y = ark_mem->ycur;
yerr = ark_mem->tempv1;
/* local shortcuts for fused vector operations */
cvals = step_mem->cvals;
Xvecs = step_mem->Xvecs;
/* initialize output */
*dsmPtr = ZERO;
/* compute y RHS (store in y) */
/* set arrays for fused vector operation */
nvec = 0;
for (j=0; j<step_mem->stages; j++) {
if (step_mem->explicit) { /* Explicit pieces */
cvals[nvec] = ark_mem->h * step_mem->Be->b[j];
Xvecs[nvec] = step_mem->Fe[j];
nvec += 1;
}
if (step_mem->implicit) { /* Implicit pieces */
cvals[nvec] = ark_mem->h * step_mem->Bi->b[j];
Xvecs[nvec] = step_mem->Fi[j];
nvec += 1;
}
}
/* call fused vector operation to compute RHS */
retval = N_VLinearCombination(nvec, cvals, Xvecs, y);
if (retval != 0) return(ARK_VECTOROP_ERR);
/* solve for y update (stored in y) */
retval = step_mem->msolve((void *) ark_mem, y, step_mem->nlscoef);
if (retval < 0) {
*dsmPtr = RCONST(2.0); /* indicate too much error, step with smaller step */
N_VScale(ONE, ark_mem->yn, y); /* place old solution into y */
return(CONV_FAIL);
}
/* compute y = yn + update */
N_VLinearSum(ONE, ark_mem->yn, ONE, y, y);
/* compute yerr (if step adaptivity enabled) */
if (!ark_mem->fixedstep) {
/* compute yerr RHS vector */
/* set arrays for fused vector operation */
nvec = 0;
for (j=0; j<step_mem->stages; j++) {
if (step_mem->explicit) { /* Explicit pieces */
cvals[nvec] = ark_mem->h * (step_mem->Be->b[j] - step_mem->Be->d[j]);
Xvecs[nvec] = step_mem->Fe[j];
nvec += 1;
}
if (step_mem->implicit) { /* Implicit pieces */
cvals[nvec] = ark_mem->h * (step_mem->Bi->b[j] - step_mem->Bi->d[j]);
Xvecs[nvec] = step_mem->Fi[j];
nvec += 1;
}
}
/* call fused vector operation to compute yerr RHS */
retval = N_VLinearCombination(nvec, cvals, Xvecs, yerr);
if (retval != 0) return(ARK_VECTOROP_ERR);
/* solve for yerr */
retval = step_mem->msolve((void *) ark_mem, yerr, step_mem->nlscoef);
if (retval < 0) {
*dsmPtr = RCONST(2.0); /* next attempt will reduce step by 'etacf';
insert dsmPtr placeholder here */
return(CONV_FAIL);
}
/* fill error norm */
*dsmPtr = N_VWrmsNorm(yerr, ark_mem->ewt);
}
return(ARK_SUCCESS);
}
/*------------------------------------------------------------------------------
arkStep_ApplyForcing
Determines the linear combination coefficients and vectors to apply forcing
at a given value of the independent variable (t). This occurs through
appending coefficients and N_Vector pointers to the underlying cvals and Xvecs
arrays in the step_mem structure. The dereferenced input *nvec should indicate
the next available entry in the cvals/Xvecs arrays. The input 's' is a
scaling factor that should be applied to each of these coefficients.
----------------------------------------------------------------------------*/
void arkStep_ApplyForcing(ARKodeARKStepMem step_mem, realtype t,
realtype s, int *nvec)
{
realtype tau, taui;
int i;
/* always append the constant forcing term */
step_mem->cvals[*nvec] = s;
step_mem->Xvecs[*nvec] = step_mem->forcing[0];
(*nvec) += 1;
/* compute normalized time tau and initialize tau^i */
tau = (t - step_mem->tshift) / (step_mem->tscale);
taui = tau;
for (i=1; i<step_mem->nforcing; i++) {
step_mem->cvals[*nvec] = s*taui;
step_mem->Xvecs[*nvec] = step_mem->forcing[i];
taui *= tau;
(*nvec) += 1;
}
}
/*------------------------------------------------------------------------------
arkStep_SetInnerForcing
Sets an array of coefficient vectors for a time-dependent external polynomial
forcing term in the ODE RHS i.e., y' = fe(t,y) + fi(t,y) + p(t). This
function is primarily intended for use with multirate integration methods
(e.g., MRIStep) where ARKStep is used to solve a modified ODE at a fast time
scale. The polynomial is of the form
p(t) = sum_{i = 0}^{nvecs - 1} forcing[i] * ((t - tshift) / (tscale))^i
where tshift and tscale are used to normalize the time t (e.g., with MRIGARK
methods).
----------------------------------------------------------------------------*/
int arkStep_SetInnerForcing(void* arkode_mem, realtype tshift, realtype tscale,
N_Vector* forcing, int nvecs)
{
ARKodeMem ark_mem;
ARKodeARKStepMem step_mem;
int retval;
/* access ARKodeARKStepMem structure */
retval = arkStep_AccessStepMem(arkode_mem, "arkStep_SetInnerForcing",
&ark_mem, &step_mem);
if (retval != ARK_SUCCESS) return(retval);
if (nvecs > 0) {
/* enable forcing */
if (step_mem->explicit) {
step_mem->expforcing = SUNTRUE;
step_mem->impforcing = SUNFALSE;
} else {
step_mem->expforcing = SUNFALSE;
step_mem->impforcing = SUNTRUE;
}
step_mem->tshift = tshift;
step_mem->tscale = tscale;
step_mem->forcing = forcing;
step_mem->nforcing = nvecs;
/* If cvals and Xvecs are not allocated then arkStep_Init has not been
called and the number of stages has not been set yet. These arrays will
be allocated in arkStep_Init and take into account the value of nforcing.
On subsequent calls will check if enough space has allocated in case
nforcing has increased since the original allocation. */
if (step_mem->cvals != NULL && step_mem->Xvecs != NULL) {
/* check if there are enough reusable arrays for fused operations */
if ((step_mem->nfusedopvecs - nvecs) < (2 * step_mem->stages + 2)) {
/* free current work space */
if (step_mem->cvals != NULL) {
free(step_mem->cvals);
ark_mem->lrw -= step_mem->nfusedopvecs;
}
if (step_mem->Xvecs != NULL) {
free(step_mem->Xvecs);
ark_mem->liw -= step_mem->nfusedopvecs;
}
/* allocate reusable arrays for fused vector operations */
step_mem->nfusedopvecs = 2 * step_mem->stages + 2 + nvecs;
step_mem->cvals = NULL;
step_mem->cvals = (realtype *) calloc(step_mem->nfusedopvecs,
sizeof(realtype));
if (step_mem->cvals == NULL) return(ARK_MEM_FAIL);
ark_mem->lrw += step_mem->nfusedopvecs;
step_mem->Xvecs = NULL;
step_mem->Xvecs = (N_Vector *) calloc(step_mem->nfusedopvecs,
sizeof(N_Vector));
if (step_mem->Xvecs == NULL) return(ARK_MEM_FAIL);
ark_mem->liw += step_mem->nfusedopvecs;
}
}
} else {
/* disable forcing */
step_mem->expforcing = SUNFALSE;
step_mem->impforcing = SUNFALSE;
step_mem->tshift = ZERO;
step_mem->tscale = ONE;
step_mem->forcing = NULL;
step_mem->nforcing = 0;
}
return(0);
}
/*===============================================================
EOF
===============================================================*/
|
NumCosmo/NumCosmo
|
numcosmo/sundials/src/arkode/arkode_arkstep.c
|
C
|
gpl-3.0
| 94,299
|
Imports System.Runtime.InteropServices
'
' * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
' * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
' *
'
Namespace java.util.zip
''' <summary>
''' A class that can be used to compute the Adler-32 checksum of a data
''' stream. An Adler-32 checksum is almost as reliable as a CRC-32 but
''' can be computed much faster.
'''
''' <p> Passing a {@code null} argument to a method in this class will cause
''' a <seealso cref="NullPointerException"/> to be thrown.
''' </summary>
''' <seealso cref= Checksum
''' @author David Connelly </seealso>
Public Class Adler32
Implements Checksum
Private adler As Integer = 1
''' <summary>
''' Creates a new Adler32 object.
''' </summary>
Public Sub New()
End Sub
''' <summary>
''' Updates the checksum with the specified byte (the low eight
''' bits of the argument b).
''' </summary>
''' <param name="b"> the byte to update the checksum with </param>
Public Overridable Sub update( b As Integer) Implements Checksum.update
adler = update(adler, b)
End Sub
''' <summary>
''' Updates the checksum with the specified array of bytes.
''' </summary>
''' <exception cref="ArrayIndexOutOfBoundsException">
''' if {@code off} is negative, or {@code len} is negative,
''' or {@code off+len} is greater than the length of the
''' array {@code b} </exception>
Public Overridable Sub update( b As SByte(), [off] As Integer, len As Integer) Implements Checksum.update
If b Is Nothing Then Throw New NullPointerException
If [off] < 0 OrElse len < 0 OrElse [off] > b.Length - len Then Throw New ArrayIndexOutOfBoundsException
adler = updateBytes(adler, b, [off], len)
End Sub
''' <summary>
''' Updates the checksum with the specified array of bytes.
''' </summary>
''' <param name="b"> the byte array to update the checksum with </param>
Public Overridable Sub update( b As SByte())
adler = updateBytes(adler, b, 0, b.Length)
End Sub
''' <summary>
''' Updates the checksum with the bytes from the specified buffer.
'''
''' The checksum is updated using
''' buffer.<seealso cref="java.nio.Buffer#remaining() remaining()"/>
''' bytes starting at
''' buffer.<seealso cref="java.nio.Buffer#position() position()"/>
''' Upon return, the buffer's position will be updated to its
''' limit; its limit will not have been changed.
''' </summary>
''' <param name="buffer"> the ByteBuffer to update the checksum with
''' @since 1.8 </param>
Public Overridable Sub update( buffer As java.nio.ByteBuffer)
Dim pos As Integer = buffer.position()
Dim limit As Integer = buffer.limit()
assert(pos <= limit)
Dim [rem] As Integer = limit - pos
If [rem] <= 0 Then Return
If TypeOf buffer Is sun.nio.ch.DirectBuffer Then
adler = updateByteBuffer(adler, CType(buffer, sun.nio.ch.DirectBuffer).address(), pos, [rem])
ElseIf buffer.hasArray() Then
adler = updateBytes(adler, buffer.array(), pos + buffer.arrayOffset(), [rem])
Else
Dim b As SByte() = New SByte([rem] - 1){}
buffer.get(b)
adler = updateBytes(adler, b, 0, b.Length)
End If
buffer.position(limit)
End Sub
''' <summary>
''' Resets the checksum to initial value.
''' </summary>
Public Overridable Sub reset() Implements Checksum.reset
adler = 1
End Sub
''' <summary>
''' Returns the checksum value.
''' </summary>
Public Overridable Property value As Long Implements Checksum.getValue
Get
Return CLng(adler) And &HffffffffL
End Get
End Property
'JAVA TO VB CONVERTER TODO TASK: Replace 'unknown' with the appropriate dll name:
<DllImport("unknown")> _
Private Shared Function update( adler As Integer, b As Integer) As Integer
End Function
'JAVA TO VB CONVERTER TODO TASK: Replace 'unknown' with the appropriate dll name:
<DllImport("unknown")> _
Private Shared Function updateBytes( adler As Integer, b As SByte(), [off] As Integer, len As Integer) As Integer
End Function
'JAVA TO VB CONVERTER TODO TASK: Replace 'unknown' with the appropriate dll name:
<DllImport("unknown")> _
Private Shared Function updateByteBuffer( adler As Integer, addr As Long, [off] As Integer, len As Integer) As Integer
End Function
End Class
End Namespace
|
amethyst-asuka/java_dotnet
|
java/util/zip/Adler32.vb
|
Visual Basic
|
gpl-3.0
| 4,460
|
<?php
/**
* @package Flocklight
* @license GPLv3
* @see https://github.com/jarofgreen/flocklight
*/
require dirname(__FILE__).'/../src/global.php';
$word = $_GET['id'];
$tpl = getSmarty();
$search = new TwitterUserSearchByWordUse($word);
$tpl->assign('searchUsers',$search);
$tpl->assign('word',$word);
$tpl->display('word.htm');
|
jarofgreen/flocklight
|
public_html/word.php
|
PHP
|
gpl-3.0
| 341
|
<?php
require('../modelo/demo_modelo.class.php');
$cedula = trim($_POST['cedula']);
$nombre = trim($_POST['nombre']);
$apellido = trim($_POST['apellido']);
$fecha_nac = trim($_POST['fecha_nac']);
$lugar_nac = trim($_POST['lugar_nacimiento']);
$edo_civil = trim($_POST['edo_civil']);
$direccion = trim($_POST['direccion']);
$objInterno=new Interno;
if ( $objInterno->insertar(array($cedula,$nombre,$apellido,$fecha_nac,$lugar_nac,$edo_civil,$direccion)) == true){
echo "<script type='text/javascript'>
alert('Datos Guardados');
window.location='../principal.php';
</script>";
}else{
echo "<script type='text/javascript'>
alert('Se produjo un error. Intente de Nuevo');
window.location='../principal.php';
</script>";
}
?>
|
jjmoncar/PlantillaWeb
|
controlador/demo_guardar.php
|
PHP
|
gpl-3.0
| 825
|
/*
* Copyright (c) 2004-2005 The Trustees of Indiana University and Indiana
* University Research and Technology
* Corporation. All rights reserved.
* Copyright (c) 2004-2016 The University of Tennessee and The University
* of Tennessee Research Foundation. All rights
* reserved.
* Copyright (c) 2004-2005 High Performance Computing Center Stuttgart,
* University of Stuttgart. All rights reserved.
* Copyright (c) 2004-2005 The Regents of the University of California.
* All rights reserved.
* Copyright (c) 2008-2015 University of Houston. All rights reserved.
* Copyright (c) 2015 Research Organization for Information Science
* and Technology (RIST). All rights reserved.
* $COPYRIGHT$
*
* Additional copyrights may follow
*
* $HEADER$
*/
#include "ompi_config.h"
#include "ompi/communicator/communicator.h"
#include "ompi/info/info.h"
#include "ompi/file/file.h"
#include "ompi/mca/fs/fs.h"
#include "ompi/mca/fs/base/base.h"
#include "ompi/mca/fcoll/fcoll.h"
#include "ompi/mca/fcoll/base/base.h"
#include "ompi/mca/fbtl/fbtl.h"
#include "ompi/mca/fbtl/base/base.h"
#include "ompi/mca/sharedfp/sharedfp.h"
#include "ompi/mca/sharedfp/base/base.h"
#include "io_ompio.h"
#include "io_ompio_request.h"
#include "math.h"
#include <unistd.h>
/* Read and write routines are split into two interfaces.
** The
** mca_io_ompio_file_read/write[_at]
**
** routines are the ones registered with the ompio modules.
** The
**
** ompio_io_ompio_file_read/write[_at]
**
** routesin are used e.g. from the shared file pointer modules.
** The main difference is, that the first one takes an ompi_file_t
** as a file pointer argument, while the second uses the ompio internal
** mca_io_ompio_file_t structure.
*/
int mca_io_ompio_file_write (ompi_file_t *fp,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fh;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
fh = &data->ompio_fh;
ret = ompio_io_ompio_file_write(fh,buf,count,datatype,status);
return ret;
}
int ompio_io_ompio_file_write (mca_io_ompio_file_t *fh,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
int index = 0;
int cycles = 0;
uint32_t iov_count = 0;
struct iovec *decoded_iov = NULL;
size_t bytes_per_cycle=0;
size_t total_bytes_written = 0;
size_t max_data=0, real_bytes_written=0;
ssize_t ret_code=0;
int i = 0; /* index into the decoded iovec of the buffer */
int j = 0; /* index into the file view iovec */
if ( 0 == count ) {
if ( MPI_STATUS_IGNORE != status ) {
status->_ucount = 0;
}
return ret;
}
ompi_io_ompio_decode_datatype (fh,
datatype,
count,
buf,
&max_data,
&decoded_iov,
&iov_count);
if ( -1 == mca_io_ompio_cycle_buffer_size ) {
bytes_per_cycle = max_data;
}
else {
bytes_per_cycle = mca_io_ompio_cycle_buffer_size;
}
cycles = ceil((float)max_data/bytes_per_cycle);
#if 0
printf ("Bytes per Cycle: %d Cycles: %d\n", bytes_per_cycle, cycles);
#endif
j = fh->f_index_in_file_view;
for (index = 0; index < cycles; index++) {
mca_io_ompio_build_io_array ( fh,
index,
cycles,
bytes_per_cycle,
max_data,
iov_count,
decoded_iov,
&i,
&j,
&total_bytes_written);
if (fh->f_num_of_io_entries) {
ret_code =fh->f_fbtl->fbtl_pwritev (fh);
if ( 0<= ret_code ) {
real_bytes_written+= (size_t)ret_code;
}
}
fh->f_num_of_io_entries = 0;
if (NULL != fh->f_io_array) {
free (fh->f_io_array);
fh->f_io_array = NULL;
}
}
if (NULL != decoded_iov) {
free (decoded_iov);
decoded_iov = NULL;
}
if ( MPI_STATUS_IGNORE != status ) {
status->_ucount = real_bytes_written;
}
return ret;
}
int mca_io_ompio_file_write_at (ompi_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
ret = ompio_io_ompio_file_write_at (&data->ompio_fh, offset,buf,count,datatype,status);
return ret;
}
int ompio_io_ompio_file_write_at (mca_io_ompio_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
OMPI_MPI_OFFSET_TYPE prev_offset;
ompio_io_ompio_file_get_position (fh, &prev_offset );
ompi_io_ompio_set_explicit_offset (fh, offset);
ret = ompio_io_ompio_file_write (fh,
buf,
count,
datatype,
status);
// An explicit offset file operation is not suppsed to modify
// the internal file pointer. So reset the pointer
// to the previous value
ompi_io_ompio_set_explicit_offset (fh, prev_offset );
return ret;
}
int mca_io_ompio_file_iwrite (ompi_file_t *fp,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
ret = ompio_io_ompio_file_iwrite(&data->ompio_fh,buf,count,datatype,request);
return ret;
}
int ompio_io_ompio_file_iwrite (mca_io_ompio_file_t *fh,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
mca_ompio_request_t *ompio_req=NULL;
ompio_req = OBJ_NEW(mca_ompio_request_t);
ompio_req->req_type = MCA_OMPIO_REQUEST_WRITE;
ompio_req->req_ompi.req_state = OMPI_REQUEST_ACTIVE;
if ( 0 == count ) {
ompio_req->req_ompi.req_status.MPI_ERROR = OMPI_SUCCESS;
ompio_req->req_ompi.req_status._ucount = 0;
ompi_request_complete (&ompio_req->req_ompi, false);
*request = (ompi_request_t *) ompio_req;
return OMPI_SUCCESS;
}
if ( NULL != fh->f_fbtl->fbtl_ipwritev ) {
/* This fbtl has support for non-blocking operations */
uint32_t iov_count = 0;
struct iovec *decoded_iov = NULL;
size_t max_data = 0;
size_t total_bytes_written =0;
int i = 0; /* index into the decoded iovec of the buffer */
int j = 0; /* index into the file vie iovec */
ompi_io_ompio_decode_datatype (fh,
datatype,
count,
buf,
&max_data,
&decoded_iov,
&iov_count);
j = fh->f_index_in_file_view;
/* Non blocking operations have to occur in a single cycle */
mca_io_ompio_build_io_array ( fh,
0, // index of current cycle iteration
1, // number of cycles
max_data, // setting bytes_per_cycle to max_data
max_data,
iov_count,
decoded_iov,
&i,
&j,
&total_bytes_written);
if (fh->f_num_of_io_entries) {
fh->f_fbtl->fbtl_ipwritev (fh, (ompi_request_t *) ompio_req);
}
if ( false == mca_io_ompio_progress_is_registered ) {
// Lazy initialization of progress function to minimize impact
// on other ompi functionality in case its not used.
opal_progress_register (mca_io_ompio_component_progress);
mca_io_ompio_progress_is_registered=true;
}
fh->f_num_of_io_entries = 0;
if (NULL != fh->f_io_array) {
free (fh->f_io_array);
fh->f_io_array = NULL;
}
if (NULL != decoded_iov) {
free (decoded_iov);
decoded_iov = NULL;
}
}
else {
// This fbtl does not support non-blocking write operations
ompi_status_public_t status;
ret = ompio_io_ompio_file_write(fh,buf,count,datatype, &status);
ompio_req->req_ompi.req_status.MPI_ERROR = ret;
ompio_req->req_ompi.req_status._ucount = status._ucount;
ompi_request_complete (&ompio_req->req_ompi, false);
}
*request = (ompi_request_t *) ompio_req;
return ret;
}
int mca_io_ompio_file_iwrite_at (ompi_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
ret = ompio_io_ompio_file_iwrite_at(&data->ompio_fh,offset,buf,count,datatype,request);
return ret;
}
int ompio_io_ompio_file_iwrite_at (mca_io_ompio_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
OMPI_MPI_OFFSET_TYPE prev_offset;
ompio_io_ompio_file_get_position (fh, &prev_offset );
ompi_io_ompio_set_explicit_offset (fh, offset);
ret = ompio_io_ompio_file_iwrite (fh,
buf,
count,
datatype,
request);
/* An explicit offset file operation is not suppsed to modify
** the internal file pointer. So reset the pointer
** to the previous value
** It is OK to reset the position already here, althgouth
** the operation might still be pending/ongoing, since
** the entire array of <offset, length, memaddress> have
** already been constructed in the file_iwrite operation
*/
ompi_io_ompio_set_explicit_offset (fh, prev_offset);
return ret;
}
/* Helper function used by both read and write operations */
/**************************************************************/
int mca_io_ompio_build_io_array ( mca_io_ompio_file_t *fh, int index, int cycles,
size_t bytes_per_cycle, int max_data, uint32_t iov_count,
struct iovec *decoded_iov, int *ii, int *jj, size_t *tbw )
{
OPAL_PTRDIFF_TYPE disp;
int block = 1;
size_t total_bytes_written = *tbw; /* total bytes that have been written*/
size_t bytes_to_write_in_cycle = 0; /* left to be written in a cycle*/
size_t sum_previous_counts = 0;
size_t sum_previous_length = 0;
int k = 0; /* index into the io_array */
int i = *ii;
int j = *jj;
sum_previous_length = fh->f_position_in_file_view;
if ((index == cycles-1) && (max_data % bytes_per_cycle)) {
bytes_to_write_in_cycle = max_data % bytes_per_cycle;
}
else {
bytes_to_write_in_cycle = bytes_per_cycle;
}
fh->f_io_array = (mca_io_ompio_io_array_t *)malloc
(OMPIO_IOVEC_INITIAL_SIZE * sizeof (mca_io_ompio_io_array_t));
if (NULL == fh->f_io_array) {
opal_output(1, "OUT OF MEMORY\n");
return OMPI_ERR_OUT_OF_RESOURCE;
}
while (bytes_to_write_in_cycle) {
/* reallocate if needed */
if (OMPIO_IOVEC_INITIAL_SIZE*block <= k) {
block ++;
fh->f_io_array = (mca_io_ompio_io_array_t *)realloc
(fh->f_io_array, OMPIO_IOVEC_INITIAL_SIZE *
block * sizeof (mca_io_ompio_io_array_t));
if (NULL == fh->f_io_array) {
opal_output(1, "OUT OF MEMORY\n");
return OMPI_ERR_OUT_OF_RESOURCE;
}
}
if (decoded_iov[i].iov_len -
(total_bytes_written - sum_previous_counts) <= 0) {
sum_previous_counts += decoded_iov[i].iov_len;
i = i + 1;
}
disp = (OPAL_PTRDIFF_TYPE)decoded_iov[i].iov_base +
(total_bytes_written - sum_previous_counts);
fh->f_io_array[k].memory_address = (IOVBASE_TYPE *)disp;
if (decoded_iov[i].iov_len -
(total_bytes_written - sum_previous_counts) >=
bytes_to_write_in_cycle) {
fh->f_io_array[k].length = bytes_to_write_in_cycle;
}
else {
fh->f_io_array[k].length = decoded_iov[i].iov_len -
(total_bytes_written - sum_previous_counts);
}
if (! (fh->f_flags & OMPIO_CONTIGUOUS_FVIEW)) {
if (fh->f_decoded_iov[j].iov_len -
(fh->f_total_bytes - sum_previous_length) <= 0) {
sum_previous_length += fh->f_decoded_iov[j].iov_len;
j = j + 1;
if (j == (int)fh->f_iov_count) {
j = 0;
sum_previous_length = 0;
fh->f_offset += fh->f_view_extent;
fh->f_position_in_file_view = sum_previous_length;
fh->f_index_in_file_view = j;
fh->f_total_bytes = 0;
}
}
}
disp = (OPAL_PTRDIFF_TYPE)fh->f_decoded_iov[j].iov_base +
(fh->f_total_bytes - sum_previous_length);
fh->f_io_array[k].offset = (IOVBASE_TYPE *)(intptr_t)(disp + fh->f_offset);
if (! (fh->f_flags & OMPIO_CONTIGUOUS_FVIEW)) {
if (fh->f_decoded_iov[j].iov_len -
(fh->f_total_bytes - sum_previous_length)
< fh->f_io_array[k].length) {
fh->f_io_array[k].length = fh->f_decoded_iov[j].iov_len -
(fh->f_total_bytes - sum_previous_length);
}
}
total_bytes_written += fh->f_io_array[k].length;
fh->f_total_bytes += fh->f_io_array[k].length;
bytes_to_write_in_cycle -= fh->f_io_array[k].length;
k = k + 1;
}
fh->f_position_in_file_view = sum_previous_length;
fh->f_index_in_file_view = j;
fh->f_num_of_io_entries = k;
#if 0
if (fh->f_rank == 0) {
int d;
printf("*************************** %d\n", fh->f_num_of_io_entries);
for (d=0 ; d<fh->f_num_of_io_entries ; d++) {
printf(" ADDRESS: %p OFFSET: %p LENGTH: %d\n",
fh->f_io_array[d].memory_address,
fh->f_io_array[d].offset,
fh->f_io_array[d].length);
}
}
#endif
*ii = i;
*jj = j;
*tbw = total_bytes_written;
return OMPI_SUCCESS;
}
/* Collective operations */
/******************************************************************/
int mca_io_ompio_file_write_all (ompi_file_t *fh,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
ret = data->ompio_fh.
f_fcoll->fcoll_file_write_all (&data->ompio_fh,
buf,
count,
datatype,
status);
if ( MPI_STATUS_IGNORE != status ) {
size_t size;
opal_datatype_type_size (&datatype->super, &size);
status->_ucount = count * size;
}
return ret;
}
int mca_io_ompio_file_write_at_all (ompi_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
ret = ompio_io_ompio_file_write_at_all(&data->ompio_fh,offset,buf,count,datatype,status);
return ret;
}
int mca_io_ompio_file_iwrite_all (ompi_file_t *fh,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data=NULL;
mca_io_ompio_file_t *fp=NULL;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
fp = &data->ompio_fh;
if ( NULL != fp->f_fcoll->fcoll_file_iwrite_all ) {
ret = fp->f_fcoll->fcoll_file_iwrite_all (&data->ompio_fh,
buf,
count,
datatype,
request);
}
else {
/* this fcoll component does not support non-blocking
collective I/O operations. WE fake it with
individual non-blocking I/O operations. */
ret = ompio_io_ompio_file_iwrite ( fp, buf, count, datatype, request );
}
return ret;
}
int ompio_io_ompio_file_write_at_all (mca_io_ompio_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
OMPI_MPI_OFFSET_TYPE prev_offset;
ompio_io_ompio_file_get_position (fh, &prev_offset );
ompi_io_ompio_set_explicit_offset (fh, offset);
ret = fh->f_fcoll->fcoll_file_write_all (fh,
buf,
count,
datatype,
status);
ompi_io_ompio_set_explicit_offset (fh, prev_offset);
return ret;
}
int mca_io_ompio_file_iwrite_at_all (ompi_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
ret = ompio_io_ompio_file_iwrite_at_all ( &data->ompio_fh, offset, buf, count, datatype, request );
return ret;
}
int ompio_io_ompio_file_iwrite_at_all (mca_io_ompio_file_t *fp,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
OMPI_MPI_OFFSET_TYPE prev_offset;
ompio_io_ompio_file_get_position (fp, &prev_offset );
ompi_io_ompio_set_explicit_offset (fp, offset);
if ( NULL != fp->f_fcoll->fcoll_file_iwrite_all ) {
ret = fp->f_fcoll->fcoll_file_iwrite_all (fp,
buf,
count,
datatype,
request);
}
else {
/* this fcoll component does not support non-blocking
collective I/O operations. WE fake it with
individual non-blocking I/O operations. */
ret = ompio_io_ompio_file_iwrite ( fp, buf, count, datatype, request );
}
ompi_io_ompio_set_explicit_offset (fp, prev_offset);
return ret;
}
/* Infrastructure for shared file pointer operations */
/* (Individual and collective */
/******************************************************/
int mca_io_ompio_file_write_shared (ompi_file_t *fp,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t * status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fh;
mca_sharedfp_base_module_t * shared_fp_base_module;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
fh = &data->ompio_fh;
/*get the shared fp module associated with this file*/
shared_fp_base_module = fh->f_sharedfp;
if ( NULL == shared_fp_base_module ){
opal_output(0, "No shared file pointer component found for this communicator. Can not execute\n");
return OMPI_ERROR;
}
ret = shared_fp_base_module->sharedfp_write(fh,buf,count,datatype,status);
return ret;
}
int mca_io_ompio_file_iwrite_shared (ompi_file_t *fp,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_request_t **request)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fh;
mca_sharedfp_base_module_t * shared_fp_base_module;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
fh = &data->ompio_fh;
/*get the shared fp module associated with this file*/
shared_fp_base_module = fh->f_sharedfp;
if ( NULL == shared_fp_base_module ){
opal_output(0, "No shared file pointer component found for this communicator. Can not execute\n");
return OMPI_ERROR;
}
ret = shared_fp_base_module->sharedfp_iwrite(fh,buf,count,datatype,request);
return ret;
}
int mca_io_ompio_file_write_ordered (ompi_file_t *fp,
const void *buf,
int count,
struct ompi_datatype_t *datatype,
ompi_status_public_t * status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fh;
mca_sharedfp_base_module_t * shared_fp_base_module;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
fh = &data->ompio_fh;
/*get the shared fp module associated with this file*/
shared_fp_base_module = fh->f_sharedfp;
if ( NULL == shared_fp_base_module ){
opal_output(0,"No shared file pointer component found for this communicator. Can not execute\n");
return OMPI_ERROR;
}
ret = shared_fp_base_module->sharedfp_write_ordered(fh,buf,count,datatype,status);
return ret;
}
int mca_io_ompio_file_write_ordered_begin (ompi_file_t *fp,
const void *buf,
int count,
struct ompi_datatype_t *datatype)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fh;
mca_sharedfp_base_module_t * shared_fp_base_module;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
fh = &data->ompio_fh;
/*get the shared fp module associated with this file*/
shared_fp_base_module = fh->f_sharedfp;
if ( NULL == shared_fp_base_module ){
opal_output(0, "No shared file pointer component found for this communicator. Can not execute\n");
return OMPI_ERROR;
}
ret = shared_fp_base_module->sharedfp_write_ordered_begin(fh,buf,count,datatype);
return ret;
}
int mca_io_ompio_file_write_ordered_end (ompi_file_t *fp,
const void *buf,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fh;
mca_sharedfp_base_module_t * shared_fp_base_module;
data = (mca_io_ompio_data_t *) fp->f_io_selected_data;
fh = &data->ompio_fh;
/*get the shared fp module associated with this file*/
shared_fp_base_module = fh->f_sharedfp;
if ( NULL == shared_fp_base_module ){
opal_output(0, "No shared file pointer component found for this communicator. Can not execute\n");
return OMPI_ERROR;
}
ret = shared_fp_base_module->sharedfp_write_ordered_end(fh,buf,status);
return ret;
}
/* Split collectives . Not really used but infrastructure is in place */
/**********************************************************************/
int mca_io_ompio_file_write_all_begin (ompi_file_t *fh,
const void *buf,
int count,
struct ompi_datatype_t *datatype)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_file_t *fp;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
fp = &data->ompio_fh;
if ( true == fp->f_split_coll_in_use ) {
printf("Only one split collective I/O operation allowed per file handle at any given point in time!\n");
return MPI_ERR_OTHER;
}
ret = mca_io_ompio_file_iwrite_all ( fh, buf, count, datatype, &fp->f_split_coll_req );
fp->f_split_coll_in_use = true;
return ret;
}
int mca_io_ompio_file_write_all_end (ompi_file_t *fh,
const void *buf,
ompi_status_public_t *status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_file_t *fp;
mca_io_ompio_data_t *data;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
fp = &data->ompio_fh;
ret = ompi_request_wait ( &fp->f_split_coll_req, status );
/* remove the flag again */
fp->f_split_coll_in_use = false;
return ret;
}
int mca_io_ompio_file_write_at_all_begin (ompi_file_t *fh,
OMPI_MPI_OFFSET_TYPE offset,
const void *buf,
int count,
struct ompi_datatype_t *datatype)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data=NULL;
mca_io_ompio_file_t *fp=NULL;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
fp = &data->ompio_fh;
if ( true == fp->f_split_coll_in_use ) {
printf("Only one split collective I/O operation allowed per file handle at any given point in time!\n");
return MPI_ERR_REQUEST;
}
ret = ompio_io_ompio_file_iwrite_at_all ( fp, offset, buf, count, datatype, &fp->f_split_coll_req );
fp->f_split_coll_in_use = true;
return ret;
}
int mca_io_ompio_file_write_at_all_end (ompi_file_t *fh,
const void *buf,
ompi_status_public_t * status)
{
int ret = OMPI_SUCCESS;
mca_io_ompio_data_t *data;
mca_io_ompio_file_t *fp=NULL;
data = (mca_io_ompio_data_t *) fh->f_io_selected_data;
fp = &data->ompio_fh;
ret = ompi_request_wait ( &fp->f_split_coll_req, status );
/* remove the flag again */
fp->f_split_coll_in_use = false;
return ret;
}
|
ClaudioNahmad/Servicio-Social
|
Parametros/CosmoMC/prerrequisitos/openmpi-2.0.2/ompi/mca/io/ompio/io_ompio_file_write.c
|
C
|
gpl-3.0
| 24,704
|
/* RetroArch - A frontend for libretro.
* Copyright (C) 2010-2014 - Hans-Kristian Arntzen
* Copyright (C) 2011-2015 - Daniel De Matteis
*
* RetroArch 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 Found-
* ation, either version 3 of the License, or (at your option) any later version.
*
* RetroArch 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 RetroArch.
* If not, see <http://www.gnu.org/licenses/>.
*/
#include "driver.h"
#include "general.h"
#include "retroarch.h"
#include "runloop.h"
#include "compat/posix_string.h"
#include "gfx/video_monitor.h"
#include "audio/audio_monitor.h"
#ifdef HAVE_MENU
#include "menu/menu.h"
#endif
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
driver_t driver;
/**
* find_driver_nonempty:
* @label : string of driver type to be found.
* @i : index of driver.
* @str : identifier name of the found driver
* gets written to this string.
* @sizeof_str : size of @str.
*
* Find driver based on @label.
*
* Returns: NULL if no driver based on @label found, otherwise
* pointer to driver.
**/
static const void *find_driver_nonempty(const char *label, int i,
char *str, size_t sizeof_str)
{
const void *drv = NULL;
if (!strcmp(label, "camera_driver"))
{
drv = camera_driver_find_handle(i);
if (drv)
strlcpy(str, camera_driver_find_ident(i), sizeof_str);
}
else if (!strcmp(label, "location_driver"))
{
drv = location_driver_find_handle(i);
if (drv)
strlcpy(str, location_driver_find_ident(i), sizeof_str);
}
#ifdef HAVE_MENU
else if (!strcmp(label, "menu_driver"))
{
drv = menu_driver_find_handle(i);
if (drv)
strlcpy(str, menu_driver_find_ident(i), sizeof_str);
}
#endif
else if (!strcmp(label, "input_driver"))
{
drv = input_driver_find_handle(i);
if (drv)
strlcpy(str, input_driver_find_ident(i), sizeof_str);
}
else if (!strcmp(label, "input_joypad_driver"))
{
drv = joypad_driver_find_handle(i);
if (drv)
strlcpy(str, joypad_driver_find_ident(i), sizeof_str);
}
else if (!strcmp(label, "video_driver"))
{
drv = video_driver_find_handle(i);
if (drv)
strlcpy(str, video_driver_find_ident(i), sizeof_str);
}
else if (!strcmp(label, "audio_driver"))
{
drv = audio_driver_find_handle(i);
if (drv)
strlcpy(str, audio_driver_find_ident(i), sizeof_str);
}
else if (!strcmp(label, "audio_resampler_driver"))
{
drv = audio_resampler_driver_find_handle(i);
if (drv)
strlcpy(str, audio_resampler_driver_find_ident(i), sizeof_str);
}
return drv;
}
/**
* find_driver_index:
* @label : string of driver type to be found.
* @drv : identifier of driver to be found.
*
* Find index of the driver, based on @label.
*
* Returns: -1 if no driver based on @label and @drv found, otherwise
* index number of the driver found in the array.
**/
int find_driver_index(const char * label, const char *drv)
{
unsigned i;
char str[PATH_MAX_LENGTH];
const void *obj = NULL;
for (i = 0; (obj = (const void*)
find_driver_nonempty(label, i, str, sizeof(str))) != NULL; i++)
{
if (!obj)
return -1;
if (str[0] == '\0')
break;
if (!strcasecmp(drv, str))
return i;
}
return -1;
}
bool find_first_driver(const char *label, char *str, size_t sizeof_str)
{
find_driver_nonempty(label, 0, str, sizeof_str);
return true;
}
/**
* find_prev_driver:
* @label : string of driver type to be found.
* @str : identifier of driver to be found.
* @sizeof_str : size of @str.
*
* Find previous driver in driver array.
**/
bool find_prev_driver(const char *label, char *str, size_t sizeof_str)
{
int i = find_driver_index(label, str);
if (i > 0)
find_driver_nonempty(label, i - 1, str, sizeof_str);
else
{
RARCH_WARN(
"Couldn't find any previous driver (current one: \"%s\").\n", str);
return false;
}
return true;
}
/**
* find_next_driver:
* @label : string of driver type to be found.
* @str : identifier of driver to be found.
* @sizeof_str : size of @str.
*
* Find next driver in driver array.
**/
bool find_next_driver(const char *label, char *str, size_t sizeof_str)
{
int i = find_driver_index(label, str);
if (i >= 0 && (strcmp(str, "null") != 0))
find_driver_nonempty(label, i + 1, str, sizeof_str);
else
{
RARCH_WARN("Couldn't find any next driver (current one: \"%s\").\n", str);
return false;
}
return true;
}
/**
* init_drivers_pre:
*
* Attempts to find a default driver for
* all driver types.
*
* Should be run before init_drivers().
**/
void init_drivers_pre(void)
{
find_audio_driver();
find_video_driver();
find_input_driver();
find_camera_driver();
find_location_driver();
#ifdef HAVE_MENU
find_menu_driver();
#endif
}
static void driver_adjust_system_rates(void)
{
audio_monitor_adjust_system_rates();
video_monitor_adjust_system_rates();
if (!driver.video_data)
return;
if (g_extern.system.force_nonblock)
rarch_main_command(RARCH_CMD_VIDEO_SET_NONBLOCKING_STATE);
else
driver_set_nonblock_state(driver.nonblock_state);
}
/**
* driver_set_refresh_rate:
* @hz : New refresh rate for monitor.
*
* Sets monitor refresh rate to new value by calling
* video_monitor_set_refresh_rate(). Subsequently
* calls audio_monitor_set_refresh_rate().
**/
void driver_set_refresh_rate(float hz)
{
video_monitor_set_refresh_rate(hz);
audio_monitor_set_refresh_rate();
driver_adjust_system_rates();
}
/**
* driver_set_nonblock_state:
* @enable : Enable nonblock state?
*
* Sets audio and video drivers to nonblock state.
*
* If @enable is false, sets blocking state for both
* audio and video drivers instead.
**/
void driver_set_nonblock_state(bool enable)
{
/* Only apply non-block-state for video if we're using vsync. */
if (driver.video_active && driver.video_data)
{
bool video_nonblock = enable;
if (!g_settings.video.vsync || g_extern.system.force_nonblock)
video_nonblock = true;
driver.video->set_nonblock_state(driver.video_data, video_nonblock);
}
if (driver.audio_active && driver.audio_data)
driver.audio->set_nonblock_state(driver.audio_data,
g_settings.audio.sync ? enable : true);
g_extern.audio_data.chunk_size = enable ?
g_extern.audio_data.nonblock_chunk_size :
g_extern.audio_data.block_chunk_size;
}
/**
* driver_update_system_av_info:
* @info : pointer to new A/V info
*
* Update the system Audio/Video information.
* Will reinitialize audio/video drivers.
* Used by RETRO_ENVIRONMENT_SET_SYSTEM_AV_INFO.
*
* Returns: true (1) if successful, otherwise false (0).
**/
bool driver_update_system_av_info(const struct retro_system_av_info *info)
{
g_extern.system.av_info = *info;
rarch_main_command(RARCH_CMD_REINIT);
/* Cannot continue recording with different parameters.
* Take the easiest route out and just restart the recording. */
if (driver.recording_data)
{
static const char *msg = "Restarting recording due to driver reinit.";
rarch_main_msg_queue_push(msg, 2, 180, false);
RARCH_WARN("%s\n", msg);
rarch_main_command(RARCH_CMD_RECORD_DEINIT);
rarch_main_command(RARCH_CMD_RECORD_INIT);
}
return true;
}
/**
* init_drivers:
* @flags : Bitmask of drivers to initialize.
*
* Initializes drivers.
* @flags determines which drivers get initialized.
**/
void init_drivers(int flags)
{
if (flags & DRIVER_VIDEO)
driver.video_data_own = false;
if (flags & DRIVER_AUDIO)
driver.audio_data_own = false;
if (flags & DRIVER_INPUT)
driver.input_data_own = false;
if (flags & DRIVER_CAMERA)
driver.camera_data_own = false;
if (flags & DRIVER_LOCATION)
driver.location_data_own = false;
#ifdef HAVE_MENU
/* By default, we want the menu to persist through driver reinits. */
driver.menu_data_own = true;
#endif
if (flags & (DRIVER_VIDEO | DRIVER_AUDIO))
driver_adjust_system_rates();
if (flags & DRIVER_VIDEO)
{
g_runloop.frames.video.count = 0;
init_video();
if (!driver.video_cache_context_ack
&& g_extern.system.hw_render_callback.context_reset)
g_extern.system.hw_render_callback.context_reset();
driver.video_cache_context_ack = false;
g_extern.system.frame_time_last = 0;
}
if (flags & DRIVER_AUDIO)
init_audio();
/* Only initialize camera driver if we're ever going to use it. */
if ((flags & DRIVER_CAMERA) && driver.camera_active)
init_camera();
/* Only initialize location driver if we're ever going to use it. */
if ((flags & DRIVER_LOCATION) && driver.location_active)
init_location();
#ifdef HAVE_MENU
if (flags & DRIVER_MENU)
{
init_menu();
if (driver.menu_ctx && driver.menu_ctx->context_reset)
driver.menu_ctx->context_reset();
}
#endif
if (flags & (DRIVER_VIDEO | DRIVER_AUDIO))
{
/* Keep non-throttled state as good as possible. */
if (driver.nonblock_state)
driver_set_nonblock_state(driver.nonblock_state);
}
}
/**
* uninit_drivers:
* @flags : Bitmask of drivers to deinitialize.
*
* Deinitializes drivers.
* @flags determines which drivers get deinitialized.
**/
void uninit_drivers(int flags)
{
if (flags & DRIVER_AUDIO)
uninit_audio();
if (flags & DRIVER_VIDEO)
{
if (g_extern.system.hw_render_callback.context_destroy &&
!driver.video_cache_context)
g_extern.system.hw_render_callback.context_destroy();
}
#ifdef HAVE_MENU
if (flags & DRIVER_MENU)
{
if (driver.menu_ctx && driver.menu_ctx->context_destroy)
driver.menu_ctx->context_destroy();
if (!driver.menu_data_own)
{
menu_free_list(driver.menu);
menu_free(driver.menu);
driver.menu = NULL;
}
}
#endif
if (flags & DRIVERS_VIDEO_INPUT)
uninit_video_input();
if ((flags & DRIVER_VIDEO) && !driver.video_data_own)
driver.video_data = NULL;
if ((flags & DRIVER_CAMERA) && !driver.camera_data_own)
{
uninit_camera();
driver.camera_data = NULL;
}
if ((flags & DRIVER_LOCATION) && !driver.location_data_own)
{
uninit_location();
driver.location_data = NULL;
}
if ((flags & DRIVER_INPUT) && !driver.input_data_own)
driver.input_data = NULL;
if ((flags & DRIVER_AUDIO) && !driver.audio_data_own)
driver.audio_data = NULL;
}
|
CautiousAlbino/RetroArch
|
driver.c
|
C
|
gpl-3.0
| 11,298
|
/**
* @file map-core.cpp
* @brief Implementation of Map functions inherited by most format handlers.
*
* Copyright (C) 2010-2015 Adam Nielsen <malvineous@shikadi.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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "map-core.hpp"
namespace camoto {
namespace gamemaps {
const char* toString(ImagePurpose p)
{
switch (p) {
case ImagePurpose::GenericTileset1: return "GenericTileset1";
case ImagePurpose::GenericTileset2: return "GenericTileset2";
case ImagePurpose::GenericTileset3: return "GenericTileset3";
case ImagePurpose::GenericTileset4: return "GenericTileset4";
case ImagePurpose::GenericTileset5: return "GenericTileset5";
case ImagePurpose::GenericTileset6: return "GenericTileset6";
case ImagePurpose::GenericTileset7: return "GenericTileset7";
case ImagePurpose::GenericTileset8: return "GenericTileset8";
case ImagePurpose::GenericTileset9: return "GenericTileset9";
case ImagePurpose::BackgroundTileset1: return "BackgroundTileset1";
case ImagePurpose::BackgroundTileset2: return "BackgroundTileset2";
case ImagePurpose::BackgroundTileset3: return "BackgroundTileset3";
case ImagePurpose::BackgroundTileset4: return "BackgroundTileset4";
case ImagePurpose::BackgroundTileset5: return "BackgroundTileset5";
case ImagePurpose::BackgroundTileset6: return "BackgroundTileset6";
case ImagePurpose::BackgroundTileset7: return "BackgroundTileset7";
case ImagePurpose::BackgroundTileset8: return "BackgroundTileset8";
case ImagePurpose::BackgroundTileset9: return "BackgroundTileset9";
case ImagePurpose::ForegroundTileset1: return "ForegroundTileset1";
case ImagePurpose::ForegroundTileset2: return "ForegroundTileset2";
case ImagePurpose::ForegroundTileset3: return "ForegroundTileset3";
case ImagePurpose::ForegroundTileset4: return "ForegroundTileset4";
case ImagePurpose::ForegroundTileset5: return "ForegroundTileset5";
case ImagePurpose::ForegroundTileset6: return "ForegroundTileset6";
case ImagePurpose::ForegroundTileset7: return "ForegroundTileset7";
case ImagePurpose::ForegroundTileset8: return "ForegroundTileset8";
case ImagePurpose::ForegroundTileset9: return "ForegroundTileset9";
case ImagePurpose::SpriteTileset1: return "SpriteTileset1";
case ImagePurpose::SpriteTileset2: return "SpriteTileset2";
case ImagePurpose::SpriteTileset3: return "SpriteTileset3";
case ImagePurpose::SpriteTileset4: return "SpriteTileset4";
case ImagePurpose::SpriteTileset5: return "SpriteTileset5";
case ImagePurpose::SpriteTileset6: return "SpriteTileset6";
case ImagePurpose::SpriteTileset7: return "SpriteTileset7";
case ImagePurpose::SpriteTileset8: return "SpriteTileset8";
case ImagePurpose::SpriteTileset9: return "SpriteTileset9";
case ImagePurpose::FontTileset1: return "FontTileset1";
case ImagePurpose::FontTileset2: return "FontTileset2";
case ImagePurpose::FontTileset3: return "FontTileset3";
case ImagePurpose::FontTileset4: return "FontTileset4";
case ImagePurpose::FontTileset5: return "FontTileset5";
case ImagePurpose::FontTileset6: return "FontTileset6";
case ImagePurpose::FontTileset7: return "FontTileset7";
case ImagePurpose::FontTileset8: return "FontTileset8";
case ImagePurpose::FontTileset9: return "FontTileset9";
case ImagePurpose::BackgroundImage: return "BackgroundImage";
case ImagePurpose::ImagePurposeCount: break; // prevent compiler warning
}
return "<unknown ImagePurpose>";
}
MapCore::~MapCore()
{
}
} // namespace gamemaps
} // namespace camoto
|
Malvineous/libgamemaps
|
src/map-core.cpp
|
C++
|
gpl-3.0
| 4,111
|
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle 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 Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* @package block_iomad_company_admin
* @copyright 2021 Derick Turner
* @author Derick Turner
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
namespace block_iomad_company_admin\forms;
use \moodleform;
use \company;
use \potential_company_users_user_selector;
use \current_company_users_user_selector;
use \moodle_url;
use \context_system;
class company_users_form extends moodleform {
protected $context = null;
protected $selectedcompany = 0;
protected $potentialusers = null;
protected $currentusers = null;
public function __construct($actionurl, $context, $companyid) {
$this->selectedcompany = $companyid;
$this->context = $context;
$options = array('context' => $this->context, 'companyid' => $this->selectedcompany);
$this->potentialusers = new potential_company_users_user_selector('potentialusers', $options);
$this->currentusers = new current_company_users_user_selector('currentusers', $options);
parent::__construct($actionurl);
}
public function definition() {
$this->_form->addElement('hidden', 'companyid', $this->selectedcompany);
$this->_form->setType('companyid', PARAM_INT);
}
public function definition_after_data() {
global $USER, $OUTPUT;
$mform =& $this->_form;
// Adding the elements in the definition_after_data function rather than in the definition function
// so that when the currentusers or potentialusers get changed in the process function, the
// changes get displayed, rather than the lists as they are before processing.
$company = new company($this->selectedcompany);
$mform->addElement('header', 'header', get_string('company_users_for', 'block_iomad_company_admin', $company->get_name()));
if (count($this->potentialusers->find_users('')) || count($this->currentusers->find_users(''))) {
$mform->addElement('html', '<table summary=""
class="companyuserstable addremovetable generaltable generalbox boxaligncenter"
cellspacing="0">
<tr>
<td id="existingcell">');
$mform->addElement('html', $this->currentusers->display(true));
$mform->addElement('html', '
</td>
<td id="buttonscell">
<p class="arrow_button">
<input name="add" id="add" type="submit" value="' . $OUTPUT->larrow().' '.get_string('add') . '"
title="' . print_string('add') .'" class="btn btn-secondary"/><br />
<input name="remove" id="remove" type="submit" value="'. get_string('remove').' '.$OUTPUT->rarrow(). '"
title="'. print_string('remove') .'" class="btn btn-secondary"/><br />
</p>
</td>
<td id="potentialcell">');
$mform->addElement('html', $this->potentialusers->display(true));
$mform->addElement('html', '
</td>
</tr>
</table>');
} else {
$mform->addElement('html', get_string('nousers', 'block_iomad_company_admin').
' <a href="'.
new moodle_url('/blocks/iomad_company_admin/company_user_create_form.php?companyid='.
$this->selectedcompany). '">Create one now</a>');
}
}
public function process() {
global $DB, $USER, $OUTPUT;
if ($this->selectedcompany) {
$company = new company($this->selectedcompany);
$companyshortname = $company->get_shortname();
$companydefaultdepartment = company::get_company_parentnode($company->id);
// Process incoming assignments.
if (optional_param('add', false, PARAM_BOOL) && confirm_sesskey()) {
$userstoassign = $this->potentialusers->get_selected_users();
if (!empty($userstoassign)) {
// Check if the company has gone over the user quota.
$company = new company($this->selectedcompany);
if (!$company->check_usercount(count($userstoassign))) {
$maxusers = $company->get('maxusers');
$returnurl = new moodle_url('/blocks/iomad_company_admin/company_users_form.php');
print_error('maxuserswarning', 'block_iomad_company_admin', $returnurl, $maxusers);
}
// Process them.
foreach ($userstoassign as $adduser) {
$allow = true;
if ($allow) {
$user = $DB->get_record('user', array('id' => $adduser->id));
// Add user to default company department.
$company->assign_user_to_company($adduser->id);
\core\event\user_updated::create_from_userid($adduser->id)->trigger();
// Fire an event for this.
$eventother = array('companyid' => $company->id,
'companyname' => $companyshortname,
'usertype' => 0,
'usertypename' => '',
'oldcompany' => json_encode(array()));
$event = \block_iomad_company_admin\event\company_user_assigned::create(array('context' => context_system::instance(),
'userid' => $USER->id,
'objectid' => $company->id,
'relateduserid' => $adduser->id,
'other' => $eventother));
$event->trigger();
}
}
$this->potentialusers->invalidate_selected_users();
$this->currentusers->invalidate_selected_users();
}
}
// Process incoming unassignments.
if (optional_param('remove', false, PARAM_BOOL) && confirm_sesskey()) {
$company = new company($this->selectedcompany);
$userstounassign = $this->currentusers->get_selected_users();
if (!empty($userstounassign)) {
foreach ($userstounassign as $removeuser) {
// Remove the user from the company.
$company->unassign_user_from_company($removeuser->id);
// Fire the user updated event.
\core\event\user_updated::create_from_userid($removeuser->id)->trigger();
// Fire an event for this.
$eventother = array('companyid' => 0,
'companyname' => '',
'usertype' => 0,
'usertypename' => '',
'oldcompany' => json_encode($company));
$event = \block_iomad_company_admin\event\company_user_unassigned::create(array('context' => context_system::instance(),
'userid' => $USER->id,
'objectid' => 0,
'relateduserid' => $removeuser->id,
'other' => $eventother));
$event->trigger();
}
$this->potentialusers->invalidate_selected_users();
$this->currentusers->invalidate_selected_users();
}
}
}
}
}
|
iomad/iomad
|
blocks/iomad_company_admin/classes/forms/company_users_form.php
|
PHP
|
gpl-3.0
| 9,197
|
#!/bin/sh
autoreconf -fsvim
|
megacoder/vtree
|
autogen.sh
|
Shell
|
gpl-3.0
| 28
|
/* Colors - BEGIN */
.blue {
color: #3289C8;
}
.yellow {
color: #f39c12;
}
.red {
color: #e74c3c;
}
.green {
color: #5cb85c;
}
.light-grey {
color: #aaaaaa;
}
/* Colors - END */
|
daniffig/iadm-css-grid
|
assets/stylesheets/colors.css
|
CSS
|
gpl-3.0
| 204
|
/**
* Roundcube Webmail Client Script
*
* This file is part of the Roundcube Webmail client
*
* @licstart The following is the entire license notice for the
* JavaScript code in this file.
*
* Copyright (C) 2005-2015, The Roundcube Dev Team
* Copyright (C) 2011-2015, Kolab Systems AG
*
* The JavaScript code in this page is free software: you can
* redistribute it and/or modify it under the terms of the GNU
* General Public License (GNU GPL) as published by the Free Software
* Foundation, either version 3 of the License, or (at your option)
* any later version. The code is distributed WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
*
* As additional permission under GNU GPL version 3 section 7, you
* may distribute non-source (e.g., minimized or compacted) forms of
* that code without the copy of the GNU GPL normally required by
* section 4, provided you include this license notice and a URL
* through which recipients can access the Corresponding Source.
*
* @licend The above is the entire license notice
* for the JavaScript code in this file.
*
* @author Thomas Bruederli <roundcube@gmail.com>
* @author Aleksander 'A.L.E.C' Machniak <alec@alec.pl>
* @author Charles McNulty <charles@charlesmcnulty.com>
*
* @requires jquery.js, common.js, list.js
*/
function rcube_webmail()
{
this.labels = {};
this.buttons = {};
this.buttons_sel = {};
this.gui_objects = {};
this.gui_containers = {};
this.commands = {};
this.command_handlers = {};
this.onloads = [];
this.messages = {};
this.group2expand = {};
this.http_request_jobs = {};
this.menu_stack = [];
// webmail client settings
this.dblclick_time = 500;
this.message_time = 5000;
this.identifier_expr = /[^0-9a-z_-]/gi;
// environment defaults
this.env = {
request_timeout: 180, // seconds
draft_autosave: 0, // seconds
comm_path: './',
recipients_separator: ',',
recipients_delimiter: ', ',
popup_width: 1150,
popup_width_small: 900
};
// create protected reference to myself
this.ref = 'rcmail';
var ref = this;
// set jQuery ajax options
$.ajaxSetup({
cache: false,
timeout: this.env.request_timeout * 1000,
error: function(request, status, err){ ref.http_error(request, status, err); },
beforeSend: function(xmlhttp){ xmlhttp.setRequestHeader('X-Roundcube-Request', ref.env.request_token); }
});
// unload fix
$(window).on('beforeunload', function() { ref.unload = true; });
// set environment variable(s)
this.set_env = function(p, value)
{
if (p != null && typeof p === 'object' && !value)
for (var n in p)
this.env[n] = p[n];
else
this.env[p] = value;
};
// add a localized label to the client environment
this.add_label = function(p, value)
{
if (typeof p == 'string')
this.labels[p] = value;
else if (typeof p == 'object')
$.extend(this.labels, p);
};
// add a button to the button list
this.register_button = function(command, id, type, act, sel, over)
{
var button_prop = {id:id, type:type};
if (act) button_prop.act = act;
if (sel) button_prop.sel = sel;
if (over) button_prop.over = over;
if (!this.buttons[command])
this.buttons[command] = [];
this.buttons[command].push(button_prop);
if (this.loaded)
init_button(command, button_prop);
};
// register a specific gui object
this.gui_object = function(name, id)
{
this.gui_objects[name] = this.loaded ? rcube_find_object(id) : id;
};
// register a container object
this.gui_container = function(name, id)
{
this.gui_containers[name] = id;
};
// add a GUI element (html node) to a specified container
this.add_element = function(elm, container)
{
if (this.gui_containers[container] && this.gui_containers[container].jquery)
this.gui_containers[container].append(elm);
};
// register an external handler for a certain command
this.register_command = function(command, callback, enable)
{
this.command_handlers[command] = callback;
if (enable)
this.enable_command(command, true);
};
// execute the given script on load
this.add_onload = function(f)
{
this.onloads.push(f);
};
// initialize webmail client
this.init = function()
{
var n;
this.task = this.env.task;
// check browser capabilities (never use version checks here)
if (this.env.server_error != 409 && (!bw.dom || !bw.xmlhttp_test())) {
this.goto_url('error', '_code=0x199');
return;
}
if (!this.env.blankpage)
this.env.blankpage = this.assets_path('program/resources/blank.gif');
// find all registered gui containers
for (n in this.gui_containers)
this.gui_containers[n] = $('#'+this.gui_containers[n]);
// find all registered gui objects
for (n in this.gui_objects)
this.gui_objects[n] = rcube_find_object(this.gui_objects[n]);
// clickjacking protection
if (this.env.x_frame_options) {
try {
// bust frame if not allowed
if (this.env.x_frame_options == 'deny' && top.location.href != self.location.href)
top.location.href = self.location.href;
else if (top.location.hostname != self.location.hostname)
throw 1;
} catch (e) {
// possible clickjacking attack: disable all form elements
$('form').each(function(){ ref.lock_form(this, true); });
this.display_message("Blocked: possible clickjacking attack!", 'error');
return;
}
}
// init registered buttons
this.init_buttons();
// tell parent window that this frame is loaded
if (this.is_framed()) {
parent.rcmail.set_busy(false, null, parent.rcmail.env.frame_lock);
parent.rcmail.env.frame_lock = null;
}
// enable general commands
this.enable_command('close', 'logout', 'mail', 'addressbook', 'settings', 'save-pref',
'compose', 'undo', 'about', 'switch-task', 'menu-open', 'menu-close', 'menu-save', true);
// set active task button
this.set_button(this.task, 'sel');
if (this.env.permaurl)
this.enable_command('permaurl', 'extwin', true);
switch (this.task) {
case 'mail':
// enable mail commands
this.enable_command('list', 'checkmail', 'add-contact', 'search', 'reset-search', 'collapse-folder', 'import-messages', true);
if (this.gui_objects.messagelist) {
this.message_list = new rcube_list_widget(this.gui_objects.messagelist, {
multiselect:true, multiexpand:true, draggable:true, keyboard:true,
column_movable:this.env.col_movable, dblclick_time:this.dblclick_time
});
this.message_list
.addEventListener('initrow', function(o) { ref.init_message_row(o); })
.addEventListener('dblclick', function(o) { ref.msglist_dbl_click(o); })
.addEventListener('click', function(o) { ref.msglist_click(o); })
.addEventListener('keypress', function(o) { ref.msglist_keypress(o); })
.addEventListener('select', function(o) { ref.msglist_select(o); })
.addEventListener('dragstart', function(o) { ref.drag_start(o); })
.addEventListener('dragmove', function(e) { ref.drag_move(e); })
.addEventListener('dragend', function(e) { ref.drag_end(e); })
.addEventListener('expandcollapse', function(o) { ref.msglist_expand(o); })
.addEventListener('column_replace', function(o) { ref.msglist_set_coltypes(o); })
.addEventListener('listupdate', function(o) { ref.triggerEvent('listupdate', o); })
.init();
// TODO: this should go into the list-widget code
$(this.message_list.thead).on('click', 'a.sortcol', function(e){
return ref.command('sort', $(this).attr('rel'), this);
});
this.enable_command('toggle_status', 'toggle_flag', 'sort', true);
this.enable_command('set-listmode', this.env.threads && !this.is_multifolder_listing());
// load messages
this.command('list');
$(this.gui_objects.qsearchbox).val(this.env.search_text).focusin(function() { ref.message_list.blur(); });
}
this.set_button_titles();
this.env.message_commands = ['show', 'reply', 'reply-all', 'reply-list',
'move', 'copy', 'delete', 'open', 'mark', 'edit', 'viewsource',
'print', 'load-attachment', 'download-attachment', 'show-headers', 'hide-headers', 'download',
'forward', 'forward-inline', 'forward-attachment', 'change-format'];
if (this.env.action == 'show' || this.env.action == 'preview') {
this.enable_command(this.env.message_commands, this.env.uid);
this.enable_command('reply-list', this.env.list_post);
if (this.env.action == 'show') {
this.http_request('pagenav', {_uid: this.env.uid, _mbox: this.env.mailbox, _search: this.env.search_request},
this.display_message('', 'loading'));
}
if (this.env.blockedobjects) {
if (this.gui_objects.remoteobjectsmsg)
this.gui_objects.remoteobjectsmsg.style.display = 'block';
this.enable_command('load-images', 'always-load', true);
}
// make preview/message frame visible
if (this.env.action == 'preview' && this.is_framed()) {
this.enable_command('compose', 'add-contact', false);
parent.rcmail.show_contentframe(true);
}
// initialize drag-n-drop on attachments, so they can e.g.
// be dropped into mail compose attachments in another window
if (this.gui_objects.attachments)
$('li > a', this.gui_objects.attachments).not('.drop').on('dragstart', function(e) {
var n, href = this.href, dt = e.originalEvent.dataTransfer;
if (dt) {
// inject username to the uri
href = href.replace(/^https?:\/\//, function(m) { return m + urlencode(ref.env.username) + '@'});
// cleanup the node to get filename without the size test
n = $(this).clone();
n.children().remove();
dt.setData('roundcube-uri', href);
dt.setData('roundcube-name', $.trim(n.text()));
}
});
}
else if (this.env.action == 'compose') {
this.env.address_group_stack = [];
this.env.compose_commands = ['send-attachment', 'remove-attachment', 'send', 'cancel',
'toggle-editor', 'list-adresses', 'pushgroup', 'search', 'reset-search', 'extwin',
'insert-response', 'save-response', 'menu-open', 'menu-close'];
if (this.env.drafts_mailbox)
this.env.compose_commands.push('savedraft')
this.enable_command(this.env.compose_commands, 'identities', 'responses', true);
// add more commands (not enabled)
$.merge(this.env.compose_commands, ['add-recipient', 'firstpage', 'previouspage', 'nextpage', 'lastpage']);
if (window.googie) {
this.env.editor_config.spellchecker = googie;
this.env.editor_config.spellcheck_observer = function(s) { ref.spellcheck_state(); };
this.env.compose_commands.push('spellcheck')
this.enable_command('spellcheck', true);
}
// initialize HTML editor
this.editor_init(this.env.editor_config, this.env.composebody);
// init canned response functions
if (this.gui_objects.responseslist) {
$('a.insertresponse', this.gui_objects.responseslist)
.attr('unselectable', 'on')
.mousedown(function(e) { return rcube_event.cancel(e); })
.on('mouseup keypress', function(e) {
if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
ref.command('insert-response', $(this).attr('rel'));
$(document.body).trigger('mouseup'); // hides the menu
return rcube_event.cancel(e);
}
});
// avoid textarea loosing focus when hitting the save-response button/link
$.each(this.buttons['save-response'] || [], function (i, v) {
$('#' + v.id).mousedown(function(e){ return rcube_event.cancel(e); })
});
}
// init message compose form
this.init_messageform();
}
else if (this.env.action == 'get')
this.enable_command('download', 'print', true);
// show printing dialog
else if (this.env.action == 'print' && this.env.uid
&& !this.env.is_pgp_content && !this.env.pgp_mime_part
) {
this.print_dialog();
}
// get unread count for each mailbox
if (this.gui_objects.mailboxlist) {
this.env.unread_counts = {};
this.gui_objects.folderlist = this.gui_objects.mailboxlist;
this.http_request('getunread', {_page: this.env.current_page});
}
// init address book widget
if (this.gui_objects.contactslist) {
this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
{ multiselect:true, draggable:false, keyboard:true });
this.contact_list
.addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
.addEventListener('select', function(o) { ref.compose_recipient_select(o); })
.addEventListener('dblclick', function(o) { ref.compose_add_recipient(); })
.addEventListener('keypress', function(o) {
if (o.key_pressed == o.ENTER_KEY) {
if (!ref.compose_add_recipient()) {
// execute link action on <enter> if not a recipient entry
if (o.last_selected && String(o.last_selected).charAt(0) == 'G') {
$(o.rows[o.last_selected].obj).find('a').first().click();
}
}
}
})
.init();
// remember last focused address field
$('#_to,#_cc,#_bcc').focus(function() { ref.env.focused_field = this; });
}
if (this.gui_objects.addressbookslist) {
this.gui_objects.folderlist = this.gui_objects.addressbookslist;
this.enable_command('list-adresses', true);
}
// ask user to send MDN
if (this.env.mdn_request && this.env.uid) {
var postact = 'sendmdn',
postdata = {_uid: this.env.uid, _mbox: this.env.mailbox};
if (!confirm(this.get_label('mdnrequest'))) {
postdata._flag = 'mdnsent';
postact = 'mark';
}
this.http_post(postact, postdata);
}
this.check_mailvelope(this.env.action);
// detect browser capabilities
if (!this.is_framed() && !this.env.extwin)
this.browser_capabilities_check();
break;
case 'addressbook':
this.env.address_group_stack = [];
if (this.gui_objects.folderlist)
this.env.contactfolders = $.extend($.extend({}, this.env.address_sources), this.env.contactgroups);
this.enable_command('add', 'import', this.env.writable_source);
this.enable_command('list', 'listgroup', 'pushgroup', 'popgroup', 'listsearch', 'search', 'reset-search', 'advanced-search', true);
if (this.gui_objects.contactslist) {
this.contact_list = new rcube_list_widget(this.gui_objects.contactslist,
{multiselect:true, draggable:this.gui_objects.folderlist?true:false, keyboard:true});
this.contact_list
.addEventListener('initrow', function(o) { ref.triggerEvent('insertrow', { cid:o.uid, row:o }); })
.addEventListener('keypress', function(o) { ref.contactlist_keypress(o); })
.addEventListener('select', function(o) { ref.contactlist_select(o); })
.addEventListener('dragstart', function(o) { ref.drag_start(o); })
.addEventListener('dragmove', function(e) { ref.drag_move(e); })
.addEventListener('dragend', function(e) { ref.drag_end(e); })
.init();
$(this.gui_objects.qsearchbox).focusin(function() { ref.contact_list.blur(); });
this.update_group_commands();
this.command('list');
}
if (this.gui_objects.savedsearchlist) {
this.savedsearchlist = new rcube_treelist_widget(this.gui_objects.savedsearchlist, {
id_prefix: 'rcmli',
id_encode: this.html_identifier_encode,
id_decode: this.html_identifier_decode
});
this.savedsearchlist.addEventListener('select', function(node) {
ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }); });
}
this.set_page_buttons();
if (this.env.cid) {
this.enable_command('show', 'edit', true);
// register handlers for group assignment via checkboxes
if (this.gui_objects.editform) {
$('input.groupmember').change(function() {
ref.group_member_change(this.checked ? 'add' : 'del', ref.env.cid, ref.env.source, this.value);
});
}
}
if (this.gui_objects.editform) {
this.enable_command('save', true);
if (this.env.action == 'add' || this.env.action == 'edit' || this.env.action == 'search')
this.init_contact_form();
}
else if (this.env.action == 'print') {
this.print_dialog();
}
break;
case 'settings':
this.enable_command('preferences', 'identities', 'responses', 'save', 'folders', true);
if (this.env.action == 'identities') {
this.enable_command('add', this.env.identities_level < 2);
}
else if (this.env.action == 'edit-identity' || this.env.action == 'add-identity') {
this.enable_command('save', 'edit', 'toggle-editor', true);
this.enable_command('delete', this.env.identities_level < 2);
// initialize HTML editor
this.editor_init(this.env.editor_config, 'rcmfd_signature');
}
else if (this.env.action == 'folders') {
this.enable_command('subscribe', 'unsubscribe', 'create-folder', 'rename-folder', true);
}
else if (this.env.action == 'edit-folder' && this.gui_objects.editform) {
this.enable_command('save', 'folder-size', true);
parent.rcmail.env.exists = this.env.messagecount;
parent.rcmail.enable_command('purge', this.env.messagecount);
}
else if (this.env.action == 'responses') {
this.enable_command('add', true);
}
if (this.gui_objects.identitieslist) {
this.identity_list = new rcube_list_widget(this.gui_objects.identitieslist,
{multiselect:false, draggable:false, keyboard:true});
this.identity_list
.addEventListener('select', function(o) { ref.identity_select(o); })
.addEventListener('keypress', function(o) {
if (o.key_pressed == o.ENTER_KEY) {
ref.identity_select(o);
}
})
.init()
.focus();
}
else if (this.gui_objects.sectionslist) {
this.sections_list = new rcube_list_widget(this.gui_objects.sectionslist, {multiselect:false, draggable:false, keyboard:true});
this.sections_list
.addEventListener('select', function(o) { ref.section_select(o); })
.addEventListener('keypress', function(o) { if (o.key_pressed == o.ENTER_KEY) ref.section_select(o); })
.init()
.focus();
}
else if (this.gui_objects.subscriptionlist) {
this.init_subscription_list();
}
else if (this.gui_objects.responseslist) {
this.responses_list = new rcube_list_widget(this.gui_objects.responseslist, {multiselect:false, draggable:false, keyboard:true});
this.responses_list
.addEventListener('select', function(list) {
var win, id = list.get_single_selection();
ref.enable_command('delete', !!id && $.inArray(id, ref.env.readonly_responses) < 0);
if (id && (win = ref.get_frame_window(ref.env.contentframe))) {
ref.set_busy(true);
ref.location_href({ _action:'edit-response', _key:id, _framed:1 }, win);
}
})
.init()
.focus();
}
break;
case 'login':
var tz, tz_name, jstz = window.jstz,
input_user = $('#rcmloginuser'),
input_tz = $('#rcmlogintz');
input_user.keyup(function(e) { return ref.login_user_keyup(e); });
if (input_user.val() == '')
input_user.focus();
else
$('#rcmloginpwd').focus();
// detect client timezone
if (jstz && (tz = jstz.determine()))
tz_name = tz.name();
input_tz.val(tz_name ? tz_name : (new Date().getStdTimezoneOffset() / -60));
// display 'loading' message on form submit, lock submit button
$('form').submit(function () {
$('input[type=submit]', this).prop('disabled', true);
ref.clear_messages();
ref.display_message('', 'loading');
});
this.enable_command('login', true);
break;
}
// select first input field in an edit form
if (this.gui_objects.editform)
$("input,select,textarea", this.gui_objects.editform)
.not(':hidden').not(':disabled').first().select().focus();
// unset contentframe variable if preview_pane is enabled
if (this.env.contentframe && !$('#' + this.env.contentframe).is(':visible'))
this.env.contentframe = null;
// prevent from form submit with Enter key in file input fields
if (bw.ie)
$('input[type=file]').keydown(function(e) { if (e.keyCode == '13') e.preventDefault(); });
// flag object as complete
this.loaded = true;
this.env.lastrefresh = new Date();
// show message
if (this.pending_message)
this.display_message.apply(this, this.pending_message);
// init treelist widget
if (this.gui_objects.folderlist && window.rcube_treelist_widget) {
this.treelist = new rcube_treelist_widget(this.gui_objects.folderlist, {
selectable: true,
id_prefix: 'rcmli',
parent_focus: true,
id_encode: this.html_identifier_encode,
id_decode: this.html_identifier_decode,
check_droptarget: function(node) { return !node.virtual && ref.check_droptarget(node.id) }
});
this.treelist
.addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
.addEventListener('expand', function(node) { ref.folder_collapsed(node) })
.addEventListener('beforeselect', function(node) { return !ref.busy; })
.addEventListener('select', function(node) { ref.triggerEvent('selectfolder', { folder:node.id, prefix:'rcmli' }) });
}
// activate html5 file drop feature (if browser supports it and if configured)
if (this.gui_objects.filedrop && this.env.filedrop && ((window.XMLHttpRequest && XMLHttpRequest.prototype && XMLHttpRequest.prototype.sendAsBinary) || window.FormData)) {
$(document.body).on('dragover dragleave drop', function(e) { return ref.document_drag_hover(e, e.type == 'dragover'); });
$(this.gui_objects.filedrop).addClass('droptarget')
.on('dragover dragleave', function(e) { return ref.file_drag_hover(e, e.type == 'dragover'); })
.get(0).addEventListener('drop', function(e) { return ref.file_dropped(e); }, false);
}
// catch document (and iframe) mouse clicks
var body_mouseup = function(e){ return ref.doc_mouse_up(e); };
$(document.body)
.mouseup(body_mouseup)
.keydown(function(e){ return ref.doc_keypress(e); });
$('iframe').on('load', function(e) {
try { $(this.contentDocument || this.contentWindow).on('mouseup', body_mouseup); }
catch (e) {/* catch possible "Permission denied" error in IE */ }
})
.contents().on('mouseup', body_mouseup);
// trigger init event hook
this.triggerEvent('init', { task:this.task, action:this.env.action });
// execute all foreign onload scripts
// @deprecated
for (n in this.onloads) {
if (typeof this.onloads[n] === 'string')
eval(this.onloads[n]);
else if (typeof this.onloads[n] === 'function')
this.onloads[n]();
}
// start keep-alive and refresh intervals
this.start_refresh();
this.start_keepalive();
};
this.log = function(msg)
{
if (window.console && console.log)
console.log(msg);
};
/*********************************************************/
/********* client command interface *********/
/*********************************************************/
// execute a specific command on the web client
this.command = function(command, props, obj, event)
{
var ret, uid, cid, url, flag, aborted = false;
if (obj && obj.blur && !(event && rcube_event.is_keyboard(event)))
obj.blur();
// do nothing if interface is locked by another command
// with exception for searching reset and menu
if (this.busy && !(command == 'reset-search' && this.last_command == 'search') && !command.match(/^menu-/))
return false;
// let the browser handle this click (shift/ctrl usually opens the link in a new window/tab)
if ((obj && obj.href && String(obj.href).indexOf('#') < 0) && rcube_event.get_modifier(event)) {
return true;
}
// command not supported or allowed
if (!this.commands[command]) {
// pass command to parent window
if (this.is_framed())
parent.rcmail.command(command, props);
return false;
}
// check input before leaving compose step
if (this.task == 'mail' && this.env.action == 'compose' && !this.env.server_error && command != 'save-pref'
&& $.inArray(command, this.env.compose_commands) < 0
) {
if (!this.env.is_sent && this.cmp_hash != this.compose_field_hash() && !confirm(this.get_label('notsentwarning')))
return false;
// remove copy from local storage if compose screen is left intentionally
this.remove_compose_data(this.env.compose_id);
this.compose_skip_unsavedcheck = true;
}
this.last_command = command;
// process external commands
if (typeof this.command_handlers[command] === 'function') {
ret = this.command_handlers[command](props, obj, event);
return ret !== undefined ? ret : (obj ? false : true);
}
else if (typeof this.command_handlers[command] === 'string') {
ret = window[this.command_handlers[command]](props, obj, event);
return ret !== undefined ? ret : (obj ? false : true);
}
// trigger plugin hooks
this.triggerEvent('actionbefore', {props:props, action:command, originalEvent:event});
ret = this.triggerEvent('before'+command, props || event);
if (ret !== undefined) {
// abort if one of the handlers returned false
if (ret === false)
return false;
else
props = ret;
}
ret = undefined;
// process internal command
switch (command) {
case 'login':
if (this.gui_objects.loginform)
this.gui_objects.loginform.submit();
break;
// commands to switch task
case 'logout':
case 'mail':
case 'addressbook':
case 'settings':
this.switch_task(command);
break;
case 'about':
this.redirect('?_task=settings&_action=about', false);
break;
case 'permaurl':
if (obj && obj.href && obj.target)
return true;
else if (this.env.permaurl)
parent.location.href = this.env.permaurl;
break;
case 'extwin':
if (this.env.action == 'compose') {
var form = this.gui_objects.messageform,
win = this.open_window('');
if (win) {
this.save_compose_form_local();
this.compose_skip_unsavedcheck = true;
$("input[name='_action']", form).val('compose');
form.action = this.url('mail/compose', { _id: this.env.compose_id, _extwin: 1 });
form.target = win.name;
form.submit();
}
}
else {
this.open_window(this.env.permaurl, true);
}
break;
case 'change-format':
url = this.env.permaurl + '&_format=' + props;
if (this.env.action == 'preview')
url = url.replace(/_action=show/, '_action=preview') + '&_framed=1';
if (this.env.extwin)
url += '&_extwin=1';
location.href = url;
break;
case 'menu-open':
if (props && props.menu == 'attachmentmenu') {
var mimetype = this.env.attachments[props.id];
this.enable_command('open-attachment', mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0);
}
this.show_menu(props, props.show || undefined, event);
break;
case 'menu-close':
this.hide_menu(props, event);
break;
case 'menu-save':
this.triggerEvent(command, {props:props, originalEvent:event});
return false;
case 'open':
if (uid = this.get_single_uid()) {
obj.href = this.url('show', this.params_from_uid(uid));
return true;
}
break;
case 'close':
if (this.env.extwin)
window.close();
break;
case 'list':
if (props && props != '') {
this.reset_qsearch(true);
}
if (this.env.action == 'compose' && this.env.extwin) {
window.close();
}
else if (this.task == 'mail') {
this.list_mailbox(props);
this.set_button_titles();
}
else if (this.task == 'addressbook')
this.list_contacts(props);
break;
case 'set-listmode':
this.set_list_options(null, undefined, undefined, props == 'threads' ? 1 : 0);
break;
case 'sort':
var sort_order = this.env.sort_order,
sort_col = !this.env.disabled_sort_col ? props : this.env.sort_col;
if (!this.env.disabled_sort_order)
sort_order = this.env.sort_col == sort_col && sort_order == 'ASC' ? 'DESC' : 'ASC';
// set table header and update env
this.set_list_sorting(sort_col, sort_order);
// reload message list
this.list_mailbox('', '', sort_col+'_'+sort_order);
break;
case 'nextpage':
this.list_page('next');
break;
case 'lastpage':
this.list_page('last');
break;
case 'previouspage':
this.list_page('prev');
break;
case 'firstpage':
this.list_page('first');
break;
case 'expunge':
if (this.env.exists)
this.expunge_mailbox(this.env.mailbox);
break;
case 'purge':
case 'empty-mailbox':
if (this.env.exists)
this.purge_mailbox(this.env.mailbox);
break;
// common commands used in multiple tasks
case 'show':
if (this.task == 'mail') {
uid = this.get_single_uid();
if (uid && (!this.env.uid || uid != this.env.uid)) {
if (this.env.mailbox == this.env.drafts_mailbox)
this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
else
this.show_message(uid);
}
}
else if (this.task == 'addressbook') {
cid = props ? props : this.get_single_cid();
if (cid && !(this.env.action == 'show' && cid == this.env.cid))
this.load_contact(cid, 'show');
}
break;
case 'add':
if (this.task == 'addressbook')
this.load_contact(0, 'add');
else if (this.task == 'settings' && this.env.action == 'responses') {
var frame;
if ((frame = this.get_frame_window(this.env.contentframe))) {
this.set_busy(true);
this.location_href({ _action:'add-response', _framed:1 }, frame);
}
}
else if (this.task == 'settings') {
this.identity_list.clear_selection();
this.load_identity(0, 'add-identity');
}
break;
case 'edit':
if (this.task == 'addressbook' && (cid = this.get_single_cid()))
this.load_contact(cid, 'edit');
else if (this.task == 'settings' && props)
this.load_identity(props, 'edit-identity');
else if (this.task == 'mail' && (uid = this.get_single_uid())) {
url = { _mbox: this.get_message_mailbox(uid) };
url[this.env.mailbox == this.env.drafts_mailbox && props != 'new' ? '_draft_uid' : '_uid'] = uid;
this.open_compose_step(url);
}
break;
case 'save':
var input, form = this.gui_objects.editform;
if (form) {
// adv. search
if (this.env.action == 'search') {
}
// user prefs
else if ((input = $("input[name='_pagesize']", form)) && input.length && isNaN(parseInt(input.val()))) {
alert(this.get_label('nopagesizewarning'));
input.focus();
break;
}
// contacts/identities
else {
// reload form
if (props == 'reload') {
form.action += '&_reload=1';
}
else if (this.task == 'settings' && (this.env.identities_level % 2) == 0 &&
(input = $("input[name='_email']", form)) && input.length && !rcube_check_email(input.val())
) {
alert(this.get_label('noemailwarning'));
input.focus();
break;
}
// clear empty input fields
$('input.placeholder').each(function(){ if (this.value == this._placeholder) this.value = ''; });
}
// add selected source (on the list)
if (parent.rcmail && parent.rcmail.env.source)
form.action = this.add_url(form.action, '_orig_source', parent.rcmail.env.source);
form.submit();
}
break;
case 'delete':
// mail task
if (this.task == 'mail')
this.delete_messages(event);
// addressbook task
else if (this.task == 'addressbook')
this.delete_contacts();
// settings: canned response
else if (this.task == 'settings' && this.env.action == 'responses')
this.delete_response();
// settings: user identities
else if (this.task == 'settings')
this.delete_identity();
break;
// mail task commands
case 'move':
case 'moveto': // deprecated
if (this.task == 'mail')
this.move_messages(props, event);
else if (this.task == 'addressbook')
this.move_contacts(props);
break;
case 'copy':
if (this.task == 'mail')
this.copy_messages(props, event);
else if (this.task == 'addressbook')
this.copy_contacts(props);
break;
case 'mark':
if (props)
this.mark_message(props);
break;
case 'toggle_status':
case 'toggle_flag':
flag = command == 'toggle_flag' ? 'flagged' : 'read';
if (uid = props) {
// toggle flagged/unflagged
if (flag == 'flagged') {
if (this.message_list.rows[uid].flagged)
flag = 'unflagged';
}
// toggle read/unread
else if (this.message_list.rows[uid].deleted)
flag = 'undelete';
else if (!this.message_list.rows[uid].unread)
flag = 'unread';
this.mark_message(flag, uid);
}
break;
case 'always-load':
if (this.env.uid && this.env.sender) {
this.add_contact(this.env.sender);
setTimeout(function(){ ref.command('load-images'); }, 300);
break;
}
case 'load-images':
if (this.env.uid)
this.show_message(this.env.uid, true, this.env.action=='preview');
break;
case 'load-attachment':
case 'open-attachment':
case 'download-attachment':
var qstring = '_mbox='+urlencode(this.env.mailbox)+'&_uid='+this.env.uid+'&_part='+props,
mimetype = this.env.attachments[props];
// open attachment in frame if it's of a supported mimetype
if (command != 'download-attachment' && mimetype && this.env.mimetypes && $.inArray(mimetype, this.env.mimetypes) >= 0) {
if (this.open_window(this.env.comm_path+'&_action=get&'+qstring+'&_frame=1'))
break;
}
this.goto_url('get', qstring+'&_download=1', false);
break;
case 'select-all':
this.select_all_mode = props ? false : true;
this.dummy_select = true; // prevent msg opening if there's only one msg on the list
if (props == 'invert')
this.message_list.invert_selection();
else
this.message_list.select_all(props == 'page' ? '' : props);
this.dummy_select = null;
break;
case 'select-none':
this.select_all_mode = false;
this.message_list.clear_selection();
break;
case 'expand-all':
this.env.autoexpand_threads = 1;
this.message_list.expand_all();
break;
case 'expand-unread':
this.env.autoexpand_threads = 2;
this.message_list.collapse_all();
this.expand_unread();
break;
case 'collapse-all':
this.env.autoexpand_threads = 0;
this.message_list.collapse_all();
break;
case 'nextmessage':
if (this.env.next_uid)
this.show_message(this.env.next_uid, false, this.env.action == 'preview');
break;
case 'lastmessage':
if (this.env.last_uid)
this.show_message(this.env.last_uid);
break;
case 'previousmessage':
if (this.env.prev_uid)
this.show_message(this.env.prev_uid, false, this.env.action == 'preview');
break;
case 'firstmessage':
if (this.env.first_uid)
this.show_message(this.env.first_uid);
break;
case 'compose':
url = {};
if (this.task == 'mail') {
url = {_mbox: this.env.mailbox, _search: this.env.search_request};
if (props)
url._to = props;
}
// modify url if we're in addressbook
else if (this.task == 'addressbook') {
// switch to mail compose step directly
if (props && props.indexOf('@') > 0) {
url._to = props;
}
else {
var a_cids = [];
// use contact id passed as command parameter
if (props)
a_cids.push(props);
// get selected contacts
else if (this.contact_list)
a_cids = this.contact_list.get_selection();
if (a_cids.length)
this.http_post('mailto', { _cid: a_cids.join(','), _source: this.env.source }, true);
else if (this.env.group)
this.http_post('mailto', { _gid: this.env.group, _source: this.env.source }, true);
break;
}
}
else if (props && typeof props == 'string') {
url._to = props;
}
else if (props && typeof props == 'object') {
$.extend(url, props);
}
this.open_compose_step(url);
break;
case 'spellcheck':
if (this.spellcheck_state()) {
this.editor.spellcheck_stop();
}
else {
this.editor.spellcheck_start();
}
break;
case 'savedraft':
// Reset the auto-save timer
clearTimeout(this.save_timer);
// compose form did not change (and draft wasn't saved already)
if (this.env.draft_id && this.cmp_hash == this.compose_field_hash()) {
this.auto_save_start();
break;
}
this.submit_messageform(true);
break;
case 'send':
if (!props.nocheck && !this.env.is_sent && !this.check_compose_input(command))
break;
// Reset the auto-save timer
clearTimeout(this.save_timer);
this.submit_messageform();
break;
case 'send-attachment':
// Reset the auto-save timer
clearTimeout(this.save_timer);
if (!(flag = this.upload_file(props || this.gui_objects.uploadform, 'upload'))) {
if (flag !== false)
alert(this.get_label('selectimportfile'));
aborted = true;
}
break;
case 'insert-sig':
this.change_identity($("[name='_from']")[0], true);
break;
case 'list-adresses':
this.list_contacts(props);
this.enable_command('add-recipient', false);
break;
case 'add-recipient':
this.compose_add_recipient(props);
break;
case 'reply-all':
case 'reply-list':
case 'reply':
if (uid = this.get_single_uid()) {
url = {_reply_uid: uid, _mbox: this.get_message_mailbox(uid), _search: this.env.search_request};
if (command == 'reply-all')
// do reply-list, when list is detected and popup menu wasn't used
url._all = (!props && this.env.reply_all_mode == 1 && this.commands['reply-list'] ? 'list' : 'all');
else if (command == 'reply-list')
url._all = 'list';
this.open_compose_step(url);
}
break;
case 'forward-attachment':
case 'forward-inline':
case 'forward':
var uids = this.env.uid ? [this.env.uid] : (this.message_list ? this.message_list.get_selection() : []);
if (uids.length) {
url = { _forward_uid: this.uids_to_list(uids), _mbox: this.env.mailbox, _search: this.env.search_request };
if (command == 'forward-attachment' || (!props && this.env.forward_attachment) || uids.length > 1)
url._attachment = 1;
this.open_compose_step(url);
}
break;
case 'print':
if (this.task == 'addressbook') {
if (uid = this.contact_list.get_single_selection()) {
url = '&_action=print&_cid=' + uid;
if (this.env.source)
url += '&_source=' + urlencode(this.env.source);
this.open_window(this.env.comm_path + url, true, true);
}
}
else if (this.env.action == 'get') {
this.gui_objects.messagepartframe.contentWindow.print();
}
else if (uid = this.get_single_uid()) {
url = this.url('print', this.params_from_uid(uid, {_safe: this.env.safemode ? 1 : 0}));
if (this.open_window(url, true, true)) {
if (this.env.action != 'show')
this.mark_message('read', uid);
}
}
break;
case 'viewsource':
if (uid = this.get_single_uid())
this.open_window(this.url('viewsource', this.params_from_uid(uid)), true, true);
break;
case 'download':
if (this.env.action == 'get') {
location.href = location.href.replace(/_frame=/, '_download=');
}
else if (uid = this.get_single_uid()) {
this.goto_url('viewsource', this.params_from_uid(uid, {_save: 1}));
}
break;
// quicksearch
case 'search':
if (!props && this.gui_objects.qsearchbox)
props = this.gui_objects.qsearchbox.value;
if (props) {
this.qsearch(props);
break;
}
// reset quicksearch
case 'reset-search':
var n, s = this.env.search_request || this.env.qsearch;
this.reset_qsearch(true);
this.select_all_mode = false;
if (s && this.env.action == 'compose') {
if (this.contact_list)
this.list_contacts_clear();
}
else if (s && this.env.mailbox) {
this.list_mailbox(this.env.mailbox, 1);
}
else if (s && this.task == 'addressbook') {
if (this.env.source == '') {
for (n in this.env.address_sources) break;
this.env.source = n;
this.env.group = '';
}
this.list_contacts(this.env.source, this.env.group, 1);
}
break;
case 'pushgroup':
// add group ID to stack
this.env.address_group_stack.push(props.id);
if (obj && event)
rcube_event.cancel(event);
case 'listgroup':
this.reset_qsearch();
this.list_contacts(props.source, props.id);
break;
case 'popgroup':
if (this.env.address_group_stack.length > 1) {
this.env.address_group_stack.pop();
this.reset_qsearch();
this.list_contacts(props.source, this.env.address_group_stack[this.env.address_group_stack.length-1]);
}
break;
case 'import-messages':
var form = props || this.gui_objects.importform,
importlock = this.set_busy(true, 'importwait');
$('input[name="_unlock"]', form).val(importlock);
if (!(flag = this.upload_file(form, 'import', importlock))) {
this.set_busy(false, null, importlock);
if (flag !== false)
alert(this.get_label('selectimportfile'));
aborted = true;
}
break;
case 'import':
if (this.env.action == 'import' && this.gui_objects.importform) {
var file = document.getElementById('rcmimportfile');
if (file && !file.value) {
alert(this.get_label('selectimportfile'));
aborted = true;
break;
}
this.gui_objects.importform.submit();
this.set_busy(true, 'importwait');
this.lock_form(this.gui_objects.importform, true);
}
else
this.goto_url('import', (this.env.source ? '_target='+urlencode(this.env.source)+'&' : ''));
break;
case 'export':
if (this.contact_list.rowcount > 0) {
this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _search: this.env.search_request });
}
break;
case 'export-selected':
if (this.contact_list.rowcount > 0) {
this.goto_url('export', { _source: this.env.source, _gid: this.env.group, _cid: this.contact_list.get_selection().join(',') });
}
break;
case 'upload-photo':
this.upload_contact_photo(props || this.gui_objects.uploadform);
break;
case 'delete-photo':
this.replace_contact_photo('-del-');
break;
// user settings commands
case 'preferences':
case 'identities':
case 'responses':
case 'folders':
this.goto_url('settings/' + command);
break;
case 'undo':
this.http_request('undo', '', this.display_message('', 'loading'));
break;
// unified command call (command name == function name)
default:
var func = command.replace(/-/g, '_');
if (this[func] && typeof this[func] === 'function') {
ret = this[func](props, obj, event);
}
break;
}
if (!aborted && this.triggerEvent('after'+command, props) === false)
ret = false;
this.triggerEvent('actionafter', { props:props, action:command, aborted:aborted });
return ret === false ? false : obj ? false : true;
};
// set command(s) enabled or disabled
this.enable_command = function()
{
var i, n, args = Array.prototype.slice.call(arguments),
enable = args.pop(), cmd;
for (n=0; n<args.length; n++) {
cmd = args[n];
// argument of type array
if (typeof cmd === 'string') {
this.commands[cmd] = enable;
this.set_button(cmd, (enable ? 'act' : 'pas'));
this.triggerEvent('enable-command', {command: cmd, status: enable});
}
// push array elements into commands array
else {
for (i in cmd)
args.push(cmd[i]);
}
}
};
this.command_enabled = function(cmd)
{
return this.commands[cmd];
};
// lock/unlock interface
this.set_busy = function(a, message, id)
{
if (a && message) {
var msg = this.get_label(message);
if (msg == message)
msg = 'Loading...';
id = this.display_message(msg, 'loading');
}
else if (!a && id) {
this.hide_message(id);
}
this.busy = a;
//document.body.style.cursor = a ? 'wait' : 'default';
if (this.gui_objects.editform)
this.lock_form(this.gui_objects.editform, a);
return id;
};
// return a localized string
this.get_label = function(name, domain)
{
if (domain && this.labels[domain+'.'+name])
return this.labels[domain+'.'+name];
else if (this.labels[name])
return this.labels[name];
else
return name;
};
// alias for convenience reasons
this.gettext = this.get_label;
// switch to another application task
this.switch_task = function(task)
{
if (this.task === task && task != 'mail')
return;
var url = this.get_task_url(task);
if (task == 'mail')
url += '&_mbox=INBOX';
else if (task == 'logout' && !this.env.server_error) {
url += '&_token=' + this.env.request_token;
this.clear_compose_data();
}
this.redirect(url);
};
this.get_task_url = function(task, url)
{
if (!url)
url = this.env.comm_path;
if (url.match(/[?&]_task=[a-zA-Z0-9_-]+/))
return url.replace(/_task=[a-zA-Z0-9_-]+/, '_task=' + task);
else
return url.replace(/\?.*$/, '') + '?_task=' + task;
};
this.reload = function(delay)
{
if (this.is_framed())
parent.rcmail.reload(delay);
else if (delay)
setTimeout(function() { ref.reload(); }, delay);
else if (window.location)
location.href = this.url('', {_extwin: this.env.extwin});
};
// Add variable to GET string, replace old value if exists
this.add_url = function(url, name, value)
{
value = urlencode(value);
if (/(\?.*)$/.test(url)) {
var urldata = RegExp.$1,
datax = RegExp('((\\?|&)'+RegExp.escape(name)+'=[^&]*)');
if (datax.test(urldata)) {
urldata = urldata.replace(datax, RegExp.$2 + name + '=' + value);
}
else
urldata += '&' + name + '=' + value
return url.replace(/(\?.*)$/, urldata);
}
return url + '?' + name + '=' + value;
};
this.is_framed = function()
{
return this.env.framed && parent.rcmail && parent.rcmail != this && typeof parent.rcmail.command == 'function';
};
this.save_pref = function(prop)
{
var request = {_name: prop.name, _value: prop.value};
if (prop.session)
request._session = prop.session;
if (prop.env)
this.env[prop.env] = prop.value;
this.http_post('save-pref', request);
};
this.html_identifier = function(str, encode)
{
return encode ? this.html_identifier_encode(str) : String(str).replace(this.identifier_expr, '_');
};
this.html_identifier_encode = function(str)
{
return Base64.encode(String(str)).replace(/=+$/, '').replace(/\+/g, '-').replace(/\//g, '_');
};
this.html_identifier_decode = function(str)
{
str = String(str).replace(/-/g, '+').replace(/_/g, '/');
while (str.length % 4) str += '=';
return Base64.decode(str);
};
/*********************************************************/
/********* event handling methods *********/
/*********************************************************/
this.drag_menu = function(e, target)
{
var modkey = rcube_event.get_modifier(e),
menu = this.gui_objects.dragmenu;
if (menu && modkey == SHIFT_KEY && this.commands['copy']) {
var pos = rcube_event.get_mouse_pos(e);
this.env.drag_target = target;
this.show_menu(this.gui_objects.dragmenu.id, true, e);
$(menu).css({top: (pos.y-10)+'px', left: (pos.x-10)+'px'});
return true;
}
return false;
};
this.drag_menu_action = function(action)
{
var menu = this.gui_objects.dragmenu;
if (menu) {
$(menu).hide();
}
this.command(action, this.env.drag_target);
this.env.drag_target = null;
};
this.drag_start = function(list)
{
this.drag_active = true;
if (this.preview_timer)
clearTimeout(this.preview_timer);
if (this.preview_read_timer)
clearTimeout(this.preview_read_timer);
// prepare treelist widget for dragging interactions
if (this.treelist)
this.treelist.drag_start();
};
this.drag_end = function(e)
{
var list, model;
if (this.treelist)
this.treelist.drag_end();
// execute drag & drop action when mouse was released
if (list = this.message_list)
model = this.env.mailboxes;
else if (list = this.contact_list)
model = this.env.contactfolders;
if (this.drag_active && model && this.env.last_folder_target) {
var target = model[this.env.last_folder_target];
list.draglayer.hide();
if (this.contact_list) {
if (!this.contacts_drag_menu(e, target))
this.command('move', target);
}
else if (!this.drag_menu(e, target))
this.command('move', target);
}
this.drag_active = false;
this.env.last_folder_target = null;
};
this.drag_move = function(e)
{
if (this.gui_objects.folderlist) {
var drag_target, oldclass,
layerclass = 'draglayernormal',
mouse = rcube_event.get_mouse_pos(e);
if (this.contact_list && this.contact_list.draglayer)
oldclass = this.contact_list.draglayer.attr('class');
// mouse intersects a valid drop target on the treelist
if (this.treelist && (drag_target = this.treelist.intersects(mouse, true))) {
this.env.last_folder_target = drag_target;
layerclass = 'draglayer' + (this.check_droptarget(drag_target) > 1 ? 'copy' : 'normal');
}
else {
// Clear target, otherwise drag end will trigger move into last valid droptarget
this.env.last_folder_target = null;
}
if (layerclass != oldclass && this.contact_list && this.contact_list.draglayer)
this.contact_list.draglayer.attr('class', layerclass);
}
};
this.collapse_folder = function(name)
{
if (this.treelist)
this.treelist.toggle(name);
};
this.folder_collapsed = function(node)
{
var prefname = this.env.task == 'addressbook' ? 'collapsed_abooks' : 'collapsed_folders',
old = this.env[prefname];
if (node.collapsed) {
this.env[prefname] = this.env[prefname] + '&'+urlencode(node.id)+'&';
// select the folder if one of its childs is currently selected
// don't select if it's virtual (#1488346)
if (!node.virtual && this.env.mailbox && this.env.mailbox.startsWith(node.id + this.env.delimiter))
this.command('list', node.id);
}
else {
var reg = new RegExp('&'+urlencode(node.id)+'&');
this.env[prefname] = this.env[prefname].replace(reg, '');
}
if (!this.drag_active) {
if (old !== this.env[prefname])
this.command('save-pref', { name: prefname, value: this.env[prefname] });
if (this.env.unread_counts)
this.set_unread_count_display(node.id, false);
}
};
// global mouse-click handler to cleanup some UI elements
this.doc_mouse_up = function(e)
{
var list, id, target = rcube_event.get_target(e);
// ignore event if jquery UI dialog is open
if ($(target).closest('.ui-dialog, .ui-widget-overlay').length)
return;
// remove focus from list widgets
if (window.rcube_list_widget && rcube_list_widget._instances.length) {
$.each(rcube_list_widget._instances, function(i,list){
if (list && !rcube_mouse_is_over(e, list.list.parentNode))
list.blur();
});
}
// reset 'pressed' buttons
if (this.buttons_sel) {
for (id in this.buttons_sel)
if (typeof id !== 'function')
this.button_out(this.buttons_sel[id], id);
this.buttons_sel = {};
}
// reset popup menus; delayed to have updated menu_stack data
setTimeout(function(e){
var obj, skip, config, id, i, parents = $(target).parents();
for (i = ref.menu_stack.length - 1; i >= 0; i--) {
id = ref.menu_stack[i];
obj = $('#' + id);
if (obj.is(':visible')
&& target != obj.data('opener')
&& target != obj.get(0) // check if scroll bar was clicked (#1489832)
&& !parents.is(obj.data('opener'))
&& id != skip
&& (obj.attr('data-editable') != 'true' || !$(target).parents('#' + id).length)
&& (obj.attr('data-sticky') != 'true' || !rcube_mouse_is_over(e, obj.get(0)))
) {
ref.hide_menu(id, e);
}
skip = obj.data('parent');
}
}, 10, e);
};
// global keypress event handler
this.doc_keypress = function(e)
{
// Helper method to move focus to the next/prev active menu item
var focus_menu_item = function(dir) {
var obj, item, mod = dir < 0 ? 'prevAll' : 'nextAll', limit = dir < 0 ? 'last' : 'first';
if (ref.focused_menu && (obj = $('#'+ref.focused_menu))) {
item = obj.find(':focus').closest('li')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
if (!item.length)
item = obj.find(':focus').closest('ul')[mod](':has(:not([aria-disabled=true]))').find('a,input')[limit]();
return item.focus().length;
}
return 0;
};
var target = e.target || {},
keyCode = rcube_event.get_keycode(e);
// save global reference for keyboard detection on click events in IE
rcube_event._last_keyboard_event = e;
if (e.keyCode != 27 && (!this.menu_keyboard_active || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')) {
return true;
}
switch (keyCode) {
case 38:
case 40:
case 63232: // "up", in safari keypress
case 63233: // "down", in safari keypress
focus_menu_item(keyCode == 38 || keyCode == 63232 ? -1 : 1);
return rcube_event.cancel(e);
case 9: // tab
if (this.focused_menu) {
var mod = rcube_event.get_modifier(e);
if (!focus_menu_item(mod == SHIFT_KEY ? -1 : 1)) {
this.hide_menu(this.focused_menu, e);
}
}
return rcube_event.cancel(e);
case 27: // esc
if (this.menu_stack.length)
this.hide_menu(this.menu_stack[this.menu_stack.length-1], e);
break;
}
return true;
}
this.msglist_select = function(list)
{
if (this.preview_timer)
clearTimeout(this.preview_timer);
if (this.preview_read_timer)
clearTimeout(this.preview_read_timer);
var selected = list.get_single_selection();
this.enable_command(this.env.message_commands, selected != null);
if (selected) {
// Hide certain command buttons when Drafts folder is selected
if (this.env.mailbox == this.env.drafts_mailbox)
this.enable_command('reply', 'reply-all', 'reply-list', 'forward', 'forward-attachment', 'forward-inline', false);
// Disable reply-list when List-Post header is not set
else {
var msg = this.env.messages[selected];
if (!msg.ml)
this.enable_command('reply-list', false);
}
}
// Multi-message commands
this.enable_command('delete', 'move', 'copy', 'mark', 'forward', 'forward-attachment', list.selection.length > 0);
// reset all-pages-selection
if (selected || (list.selection.length && list.selection.length != list.rowcount))
this.select_all_mode = false;
// start timer for message preview (wait for double click)
if (selected && this.env.contentframe && !list.multi_selecting && !this.dummy_select)
this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, this.dblclick_time);
else if (this.env.contentframe)
this.show_contentframe(false);
};
// This allow as to re-select selected message and display it in preview frame
this.msglist_click = function(list)
{
if (list.multi_selecting || !this.env.contentframe)
return;
if (list.get_single_selection())
return;
var win = this.get_frame_window(this.env.contentframe);
if (win && win.location.href.indexOf(this.env.blankpage) >= 0) {
if (this.preview_timer)
clearTimeout(this.preview_timer);
if (this.preview_read_timer)
clearTimeout(this.preview_read_timer);
this.preview_timer = setTimeout(function() { ref.msglist_get_preview(); }, this.dblclick_time);
}
};
this.msglist_dbl_click = function(list)
{
if (this.preview_timer)
clearTimeout(this.preview_timer);
if (this.preview_read_timer)
clearTimeout(this.preview_read_timer);
var uid = list.get_single_selection();
if (uid && (this.env.messages[uid].mbox || this.env.mailbox) == this.env.drafts_mailbox)
this.open_compose_step({ _draft_uid: uid, _mbox: this.env.mailbox });
else if (uid)
this.show_message(uid, false, false);
};
this.msglist_keypress = function(list)
{
if (list.modkey == CONTROL_KEY)
return;
if (list.key_pressed == list.ENTER_KEY)
this.command('show');
else if (list.key_pressed == list.DELETE_KEY || list.key_pressed == list.BACKSPACE_KEY)
this.command('delete');
else if (list.key_pressed == 33)
this.command('previouspage');
else if (list.key_pressed == 34)
this.command('nextpage');
};
this.msglist_get_preview = function()
{
var uid = this.get_single_uid();
if (uid && this.env.contentframe && !this.drag_active)
this.show_message(uid, false, true);
else if (this.env.contentframe)
this.show_contentframe(false);
};
this.msglist_expand = function(row)
{
if (this.env.messages[row.uid])
this.env.messages[row.uid].expanded = row.expanded;
$(row.obj)[row.expanded?'addClass':'removeClass']('expanded');
};
this.msglist_set_coltypes = function(list)
{
var i, found, name, cols = list.thead.rows[0].cells;
this.env.listcols = [];
for (i=0; i<cols.length; i++)
if (cols[i].id && cols[i].id.startsWith('rcm')) {
name = cols[i].id.slice(3);
this.env.listcols.push(name);
}
if ((found = $.inArray('flag', this.env.listcols)) >= 0)
this.env.flagged_col = found;
if ((found = $.inArray('subject', this.env.listcols)) >= 0)
this.env.subject_col = found;
this.command('save-pref', { name: 'list_cols', value: this.env.listcols, session: 'list_attrib/columns' });
};
this.check_droptarget = function(id)
{
switch (this.task) {
case 'mail':
return (this.env.mailboxes[id]
&& !this.env.mailboxes[id].virtual
&& (this.env.mailboxes[id].id != this.env.mailbox || this.is_multifolder_listing())) ? 1 : 0;
case 'addressbook':
var target;
if (id != this.env.source && (target = this.env.contactfolders[id])) {
// droptarget is a group
if (target.type == 'group') {
if (target.id != this.env.group && !this.env.contactfolders[target.source].readonly) {
var is_other = this.env.selection_sources.length > 1 || $.inArray(target.source, this.env.selection_sources) == -1;
return !is_other || this.commands.move ? 1 : 2;
}
}
// droptarget is a (writable) addressbook and it's not the source
else if (!target.readonly && (this.env.selection_sources.length > 1 || $.inArray(id, this.env.selection_sources) == -1)) {
return this.commands.move ? 1 : 2;
}
}
}
return 0;
};
// open popup window
this.open_window = function(url, small, toolbar)
{
var wname = 'rcmextwin' + new Date().getTime();
url += (url.match(/\?/) ? '&' : '?') + '_extwin=1';
if (this.env.standard_windows)
var extwin = window.open(url, wname);
else {
var win = this.is_framed() ? parent.window : window,
page = $(win),
page_width = page.width(),
page_height = bw.mz ? $('body', win).height() : page.height(),
w = Math.min(small ? this.env.popup_width_small : this.env.popup_width, page_width),
h = page_height, // always use same height
l = (win.screenLeft || win.screenX) + 20,
t = (win.screenTop || win.screenY) + 20,
extwin = window.open(url, wname,
'width='+w+',height='+h+',top='+t+',left='+l+',resizable=yes,location=no,scrollbars=yes'
+(toolbar ? ',toolbar=yes,menubar=yes,status=yes' : ',toolbar=no,menubar=no,status=no'));
}
// detect popup blocker (#1489618)
// don't care this might not work with all browsers
if (!extwin || extwin.closed) {
this.display_message(this.get_label('windowopenerror'), 'warning');
return;
}
// write loading... message to empty windows
if (!url && extwin.document) {
extwin.document.write('<html><body>' + this.get_label('loading') + '</body></html>');
}
// allow plugins to grab the window reference (#1489413)
this.triggerEvent('openwindow', { url:url, handle:extwin });
// focus window, delayed to bring to front
setTimeout(function() { extwin && extwin.focus(); }, 10);
return extwin;
};
/*********************************************************/
/********* (message) list functionality *********/
/*********************************************************/
this.init_message_row = function(row)
{
var i, fn = {}, uid = row.uid,
status_icon = (this.env.status_col != null ? 'status' : 'msg') + 'icn' + row.id;
if (uid && this.env.messages[uid])
$.extend(row, this.env.messages[uid]);
// set eventhandler to status icon
if (row.icon = document.getElementById(status_icon)) {
fn.icon = function(e) { ref.command('toggle_status', uid); };
}
// save message icon position too
if (this.env.status_col != null)
row.msgicon = document.getElementById('msgicn'+row.id);
else
row.msgicon = row.icon;
// set eventhandler to flag icon
if (this.env.flagged_col != null && (row.flagicon = document.getElementById('flagicn'+row.id))) {
fn.flagicon = function(e) { ref.command('toggle_flag', uid); };
}
// set event handler to thread expand/collapse icon
if (!row.depth && row.has_children && (row.expando = document.getElementById('rcmexpando'+row.id))) {
fn.expando = function(e) { ref.expand_message_row(e, uid); };
}
// attach events
$.each(fn, function(i, f) {
row[i].onclick = function(e) { f(e); return rcube_event.cancel(e); };
if (bw.touch && row[i].addEventListener) {
row[i].addEventListener('touchend', function(e) {
if (e.changedTouches.length == 1) {
f(e);
return rcube_event.cancel(e);
}
}, false);
}
});
this.triggerEvent('insertrow', { uid:uid, row:row });
};
// create a table row in the message list
this.add_message_row = function(uid, cols, flags, attop)
{
if (!this.gui_objects.messagelist || !this.message_list)
return false;
// Prevent from adding messages from different folder (#1487752)
if (flags.mbox != this.env.mailbox && !flags.skip_mbox_check)
return false;
if (!this.env.messages[uid])
this.env.messages[uid] = {};
// merge flags over local message object
$.extend(this.env.messages[uid], {
deleted: flags.deleted?1:0,
replied: flags.answered?1:0,
unread: !flags.seen?1:0,
forwarded: flags.forwarded?1:0,
flagged: flags.flagged?1:0,
has_children: flags.has_children?1:0,
depth: flags.depth?flags.depth:0,
unread_children: flags.unread_children?flags.unread_children:0,
parent_uid: flags.parent_uid?flags.parent_uid:0,
selected: this.select_all_mode || this.message_list.in_selection(uid),
ml: flags.ml?1:0,
ctype: flags.ctype,
mbox: flags.mbox,
// flags from plugins
flags: flags.extra_flags
});
var c, n, col, html, css_class, label, status_class = '', status_label = '',
tree = '', expando = '',
list = this.message_list,
rows = list.rows,
message = this.env.messages[uid],
msg_id = this.html_identifier(uid,true),
row_class = 'message'
+ (!flags.seen ? ' unread' : '')
+ (flags.deleted ? ' deleted' : '')
+ (flags.flagged ? ' flagged' : '')
+ (message.selected ? ' selected' : ''),
row = { cols:[], style:{}, id:'rcmrow'+msg_id, uid:uid };
// message status icons
css_class = 'msgicon';
if (this.env.status_col === null) {
css_class += ' status';
if (flags.deleted) {
status_class += ' deleted';
status_label += this.get_label('deleted') + ' ';
}
else if (!flags.seen) {
status_class += ' unread';
status_label += this.get_label('unread') + ' ';
}
else if (flags.unread_children > 0) {
status_class += ' unreadchildren';
}
}
if (flags.answered) {
status_class += ' replied';
status_label += this.get_label('replied') + ' ';
}
if (flags.forwarded) {
status_class += ' forwarded';
status_label += this.get_label('forwarded') + ' ';
}
// update selection
if (message.selected && !list.in_selection(uid))
list.selection.push(uid);
// threads
if (this.env.threading) {
if (message.depth) {
// This assumes that div width is hardcoded to 15px,
tree += '<span id="rcmtab' + msg_id + '" class="branch" style="width:' + (message.depth * 15) + 'px;"> </span>';
if ((rows[message.parent_uid] && rows[message.parent_uid].expanded === false)
|| ((this.env.autoexpand_threads == 0 || this.env.autoexpand_threads == 2) &&
(!rows[message.parent_uid] || !rows[message.parent_uid].expanded))
) {
row.style.display = 'none';
message.expanded = false;
}
else
message.expanded = true;
row_class += ' thread expanded';
}
else if (message.has_children) {
if (message.expanded === undefined && (this.env.autoexpand_threads == 1 || (this.env.autoexpand_threads == 2 && message.unread_children))) {
message.expanded = true;
}
expando = '<div id="rcmexpando' + row.id + '" class="' + (message.expanded ? 'expanded' : 'collapsed') + '"> </div>';
row_class += ' thread' + (message.expanded? ' expanded' : '');
}
if (flags.unread_children && flags.seen && !message.expanded)
row_class += ' unroot';
}
tree += '<span id="msgicn'+row.id+'" class="'+css_class+status_class+'" title="'+status_label+'"></span>';
row.className = row_class;
// build subject link
if (cols.subject) {
var action = flags.mbox == this.env.drafts_mailbox ? 'compose' : 'show',
uid_param = flags.mbox == this.env.drafts_mailbox ? '_draft_uid' : '_uid',
query = { _mbox: flags.mbox };
query[uid_param] = uid;
cols.subject = '<a href="' + this.url(action, query) + '" onclick="return rcube_event.keyboard_only(event)"' +
' onmouseover="rcube_webmail.long_subject_title(this,'+(message.depth+1)+')" tabindex="-1"><span>'+cols.subject+'</span></a>';
}
// add each submitted col
for (n in this.env.listcols) {
c = this.env.listcols[n];
col = {className: String(c).toLowerCase(), events:{}};
if (this.env.coltypes[c] && this.env.coltypes[c].hidden) {
col.className += ' hidden';
}
if (c == 'flag') {
css_class = (flags.flagged ? 'flagged' : 'unflagged');
label = this.get_label(css_class);
html = '<span id="flagicn'+row.id+'" class="'+css_class+'" title="'+label+'"></span>';
}
else if (c == 'attachment') {
label = this.get_label('withattachment');
if (flags.attachmentClass)
html = '<span class="'+flags.attachmentClass+'" title="'+label+'"></span>';
else if (/application\/|multipart\/(m|signed)/.test(flags.ctype))
html = '<span class="attachment" title="'+label+'"></span>';
else if (/multipart\/report/.test(flags.ctype))
html = '<span class="report"></span>';
else
html = ' ';
}
else if (c == 'status') {
label = '';
if (flags.deleted) {
css_class = 'deleted';
label = this.get_label('deleted');
}
else if (!flags.seen) {
css_class = 'unread';
label = this.get_label('unread');
}
else if (flags.unread_children > 0) {
css_class = 'unreadchildren';
}
else
css_class = 'msgicon';
html = '<span id="statusicn'+row.id+'" class="'+css_class+status_class+'" title="'+label+'"></span>';
}
else if (c == 'threads')
html = expando;
else if (c == 'subject') {
if (bw.ie)
col.events.mouseover = function() { rcube_webmail.long_subject_title_ex(this); };
html = tree + cols[c];
}
else if (c == 'priority') {
if (flags.prio > 0 && flags.prio < 6) {
label = this.get_label('priority') + ' ' + flags.prio;
html = '<span class="prio'+flags.prio+'" title="'+label+'"></span>';
}
else
html = ' ';
}
else if (c == 'folder') {
html = '<span onmouseover="rcube_webmail.long_subject_title(this)">' + cols[c] + '<span>';
}
else
html = cols[c];
col.innerHTML = html;
row.cols.push(col);
}
list.insert_row(row, attop);
// remove 'old' row
if (attop && this.env.pagesize && list.rowcount > this.env.pagesize) {
var uid = list.get_last_row();
list.remove_row(uid);
list.clear_selection(uid);
}
};
this.set_list_sorting = function(sort_col, sort_order)
{
var sort_old = this.env.sort_col == 'arrival' ? 'date' : this.env.sort_col,
sort_new = sort_col == 'arrival' ? 'date' : sort_col;
// set table header class
$('#rcm' + sort_old).removeClass('sorted' + this.env.sort_order.toUpperCase());
if (sort_new)
$('#rcm' + sort_new).addClass('sorted' + sort_order);
// if sorting by 'arrival' is selected, click on date column should not switch to 'date'
$('#rcmdate > a').prop('rel', sort_col == 'arrival' ? 'arrival' : 'date');
this.env.sort_col = sort_col;
this.env.sort_order = sort_order;
};
this.set_list_options = function(cols, sort_col, sort_order, threads)
{
var update, post_data = {};
if (sort_col === undefined)
sort_col = this.env.sort_col;
if (!sort_order)
sort_order = this.env.sort_order;
if (this.env.sort_col != sort_col || this.env.sort_order != sort_order) {
update = 1;
this.set_list_sorting(sort_col, sort_order);
}
if (this.env.threading != threads) {
update = 1;
post_data._threads = threads;
}
if (cols && cols.length) {
// make sure new columns are added at the end of the list
var i, idx, name, newcols = [], oldcols = this.env.listcols;
for (i=0; i<oldcols.length; i++) {
name = oldcols[i];
idx = $.inArray(name, cols);
if (idx != -1) {
newcols.push(name);
delete cols[idx];
}
}
for (i=0; i<cols.length; i++)
if (cols[i])
newcols.push(cols[i]);
if (newcols.join() != oldcols.join()) {
update = 1;
post_data._cols = newcols.join(',');
}
}
if (update)
this.list_mailbox('', '', sort_col+'_'+sort_order, post_data);
};
// when user double-clicks on a row
this.show_message = function(id, safe, preview)
{
if (!id)
return;
var win, target = window,
url = this.params_from_uid(id, {_caps: this.browser_capabilities()});
if (preview && (win = this.get_frame_window(this.env.contentframe))) {
target = win;
url._framed = 1;
}
if (safe)
url._safe = 1;
// also send search request to get the right messages
if (this.env.search_request)
url._search = this.env.search_request;
if (this.env.extwin)
url._extwin = 1;
url = this.url(preview ? 'preview': 'show', url);
if (preview && String(target.location.href).indexOf(url) >= 0) {
this.show_contentframe(true);
}
else {
if (!preview && this.env.message_extwin && !this.env.extwin)
this.open_window(url, true);
else
this.location_href(url, target, true);
// mark as read and change mbox unread counter
if (preview && this.message_list && this.message_list.rows[id] && this.message_list.rows[id].unread && this.env.preview_pane_mark_read > 0) {
this.preview_read_timer = setTimeout(function() {
ref.set_unread_message(id, ref.env.mailbox);
ref.http_post('mark', {_uid: id, _flag: 'read', _mbox: ref.env.mailbox, _quiet: 1});
}, this.env.preview_pane_mark_read * 1000);
}
}
};
// update message status and unread counter after marking a message as read
this.set_unread_message = function(id, folder)
{
var self = this;
// find window with messages list
if (!self.message_list)
self = self.opener();
if (!self && window.parent)
self = parent.rcmail;
if (!self || !self.message_list)
return;
// this may fail in multifolder mode
if (self.set_message(id, 'unread', false) === false)
self.set_message(id + '-' + folder, 'unread', false);
if (self.env.unread_counts[folder] > 0) {
self.env.unread_counts[folder] -= 1;
self.set_unread_count(folder, self.env.unread_counts[folder], folder == 'INBOX' && !self.is_multifolder_listing());
}
};
this.show_contentframe = function(show)
{
var frame, win, name = this.env.contentframe;
if (name && (frame = this.get_frame_element(name))) {
if (!show && (win = this.get_frame_window(name))) {
if (win.location.href.indexOf(this.env.blankpage) < 0) {
if (win.stop)
win.stop();
else // IE
win.document.execCommand('Stop');
win.location.href = this.env.blankpage;
}
}
else if (!bw.safari && !bw.konq)
$(frame)[show ? 'show' : 'hide']();
}
if (!show && this.env.frame_lock)
this.set_busy(false, null, this.env.frame_lock);
};
this.get_frame_element = function(id)
{
var frame;
if (id && (frame = document.getElementById(id)))
return frame;
};
this.get_frame_window = function(id)
{
var frame = this.get_frame_element(id);
if (frame && frame.name && window.frames)
return window.frames[frame.name];
};
this.lock_frame = function()
{
if (!this.env.frame_lock)
(this.is_framed() ? parent.rcmail : this).env.frame_lock = this.set_busy(true, 'loading');
};
// list a specific page
this.list_page = function(page)
{
if (page == 'next')
page = this.env.current_page+1;
else if (page == 'last')
page = this.env.pagecount;
else if (page == 'prev' && this.env.current_page > 1)
page = this.env.current_page-1;
else if (page == 'first' && this.env.current_page > 1)
page = 1;
if (page > 0 && page <= this.env.pagecount) {
this.env.current_page = page;
if (this.task == 'addressbook' || this.contact_list)
this.list_contacts(this.env.source, this.env.group, page);
else if (this.task == 'mail')
this.list_mailbox(this.env.mailbox, page);
}
};
// sends request to check for recent messages
this.checkmail = function()
{
var lock = this.set_busy(true, 'checkingmail'),
params = this.check_recent_params();
this.http_post('check-recent', params, lock);
};
// list messages of a specific mailbox using filter
this.filter_mailbox = function(filter)
{
if (this.filter_disabled)
return;
var lock = this.set_busy(true, 'searching');
this.clear_message_list();
// reset vars
this.env.current_page = 1;
this.env.search_filter = filter;
this.http_request('search', this.search_params(false, filter), lock);
};
// reload the current message listing
this.refresh_list = function()
{
this.list_mailbox(this.env.mailbox, this.env.current_page || 1, null, { _clear:1 }, true);
if (this.message_list)
this.message_list.clear_selection();
};
// list messages of a specific mailbox
this.list_mailbox = function(mbox, page, sort, url, update_only)
{
var win, target = window;
if (typeof url != 'object')
url = {};
if (!mbox)
mbox = this.env.mailbox ? this.env.mailbox : 'INBOX';
// add sort to url if set
if (sort)
url._sort = sort;
// folder change, reset page, search scope, etc.
if (this.env.mailbox != mbox) {
page = 1;
this.env.current_page = page;
this.env.search_scope = 'base';
this.select_all_mode = false;
this.reset_search_filter();
}
// also send search request to get the right messages
else if (this.env.search_request)
url._search = this.env.search_request;
if (!update_only) {
// unselect selected messages and clear the list and message data
this.clear_message_list();
if (mbox != this.env.mailbox || (mbox == this.env.mailbox && !page && !sort))
url._refresh = 1;
this.select_folder(mbox, '', true);
this.unmark_folder(mbox, 'recent', '', true);
this.env.mailbox = mbox;
}
// load message list remotely
if (this.gui_objects.messagelist) {
this.list_mailbox_remote(mbox, page, url);
return;
}
if (win = this.get_frame_window(this.env.contentframe)) {
target = win;
url._framed = 1;
}
if (this.env.uid)
url._uid = this.env.uid;
// load message list to target frame/window
if (mbox) {
this.set_busy(true, 'loading');
url._mbox = mbox;
if (page)
url._page = page;
this.location_href(url, target);
}
};
this.clear_message_list = function()
{
this.env.messages = {};
this.show_contentframe(false);
if (this.message_list)
this.message_list.clear(true);
};
// send remote request to load message list
this.list_mailbox_remote = function(mbox, page, url)
{
var lock = this.set_busy(true, 'loading');
if (typeof url != 'object')
url = {};
url._mbox = mbox;
if (page)
url._page = page;
this.http_request('list', url, lock);
this.update_state({ _mbox: mbox, _page: (page && page > 1 ? page : null) });
};
// removes messages that doesn't exists from list selection array
this.update_selection = function()
{
var list = this.message_list,
selected = list.selection,
rows = list.rows,
i, selection = [];
for (i in selected)
if (rows[selected[i]])
selection.push(selected[i]);
list.selection = selection;
// reset preview frame, if currently previewed message is not selected (has been removed)
try {
var win = this.get_frame_window(this.env.contentframe),
id = win.rcmail.env.uid;
if (id && !list.in_selection(id))
this.show_contentframe(false);
}
catch (e) {};
};
// expand all threads with unread children
this.expand_unread = function()
{
var r, tbody = this.message_list.tbody,
new_row = tbody.firstChild;
while (new_row) {
if (new_row.nodeType == 1 && (r = this.message_list.rows[new_row.uid]) && r.unread_children) {
this.message_list.expand_all(r);
this.set_unread_children(r.uid);
}
new_row = new_row.nextSibling;
}
return false;
};
// thread expanding/collapsing handler
this.expand_message_row = function(e, uid)
{
var row = this.message_list.rows[uid];
// handle unread_children mark
row.expanded = !row.expanded;
this.set_unread_children(uid);
row.expanded = !row.expanded;
this.message_list.expand_row(e, uid);
};
// message list expanding
this.expand_threads = function()
{
if (!this.env.threading || !this.env.autoexpand_threads || !this.message_list)
return;
switch (this.env.autoexpand_threads) {
case 2: this.expand_unread(); break;
case 1: this.message_list.expand_all(); break;
}
};
// Initializes threads indicators/expanders after list update
this.init_threads = function(roots, mbox)
{
// #1487752
if (mbox && mbox != this.env.mailbox)
return false;
for (var n=0, len=roots.length; n<len; n++)
this.add_tree_icons(roots[n]);
this.expand_threads();
};
// adds threads tree icons to the list (or specified thread)
this.add_tree_icons = function(root)
{
var i, l, r, n, len, pos, tmp = [], uid = [],
row, rows = this.message_list.rows;
if (root)
row = rows[root] ? rows[root].obj : null;
else
row = this.message_list.tbody.firstChild;
while (row) {
if (row.nodeType == 1 && (r = rows[row.uid])) {
if (r.depth) {
for (i=tmp.length-1; i>=0; i--) {
len = tmp[i].length;
if (len > r.depth) {
pos = len - r.depth;
if (!(tmp[i][pos] & 2))
tmp[i][pos] = tmp[i][pos] ? tmp[i][pos]+2 : 2;
}
else if (len == r.depth) {
if (!(tmp[i][0] & 2))
tmp[i][0] += 2;
}
if (r.depth > len)
break;
}
tmp.push(new Array(r.depth));
tmp[tmp.length-1][0] = 1;
uid.push(r.uid);
}
else {
if (tmp.length) {
for (i in tmp) {
this.set_tree_icons(uid[i], tmp[i]);
}
tmp = [];
uid = [];
}
if (root && row != rows[root].obj)
break;
}
}
row = row.nextSibling;
}
if (tmp.length) {
for (i in tmp) {
this.set_tree_icons(uid[i], tmp[i]);
}
}
};
// adds tree icons to specified message row
this.set_tree_icons = function(uid, tree)
{
var i, divs = [], html = '', len = tree.length;
for (i=0; i<len; i++) {
if (tree[i] > 2)
divs.push({'class': 'l3', width: 15});
else if (tree[i] > 1)
divs.push({'class': 'l2', width: 15});
else if (tree[i] > 0)
divs.push({'class': 'l1', width: 15});
// separator div
else if (divs.length && !divs[divs.length-1]['class'])
divs[divs.length-1].width += 15;
else
divs.push({'class': null, width: 15});
}
for (i=divs.length-1; i>=0; i--) {
if (divs[i]['class'])
html += '<div class="tree '+divs[i]['class']+'" />';
else
html += '<div style="width:'+divs[i].width+'px" />';
}
if (html)
$('#rcmtab'+this.html_identifier(uid, true)).html(html);
};
// update parent in a thread
this.update_thread_root = function(uid, flag)
{
if (!this.env.threading)
return;
var root = this.message_list.find_root(uid);
if (uid == root)
return;
var p = this.message_list.rows[root];
if (flag == 'read' && p.unread_children) {
p.unread_children--;
}
else if (flag == 'unread' && p.has_children) {
// unread_children may be undefined
p.unread_children = p.unread_children ? p.unread_children + 1 : 1;
}
else {
return;
}
this.set_message_icon(root);
this.set_unread_children(root);
};
// update thread indicators for all messages in a thread below the specified message
// return number of removed/added root level messages
this.update_thread = function (uid)
{
if (!this.env.threading)
return 0;
var r, parent, count = 0,
rows = this.message_list.rows,
row = rows[uid],
depth = rows[uid].depth,
roots = [];
if (!row.depth) // root message: decrease roots count
count--;
else if (row.unread) {
// update unread_children for thread root
parent = this.message_list.find_root(uid);
rows[parent].unread_children--;
this.set_unread_children(parent);
}
parent = row.parent_uid;
// childrens
row = row.obj.nextSibling;
while (row) {
if (row.nodeType == 1 && (r = rows[row.uid])) {
if (!r.depth || r.depth <= depth)
break;
r.depth--; // move left
// reset width and clear the content of a tab, icons will be added later
$('#rcmtab'+r.id).width(r.depth * 15).html('');
if (!r.depth) { // a new root
count++; // increase roots count
r.parent_uid = 0;
if (r.has_children) {
// replace 'leaf' with 'collapsed'
$('#'+r.id+' .leaf:first')
.attr('id', 'rcmexpando' + r.id)
.attr('class', (r.obj.style.display != 'none' ? 'expanded' : 'collapsed'))
.mousedown({uid: r.uid}, function(e) {
return ref.expand_message_row(e, e.data.uid);
});
r.unread_children = 0;
roots.push(r);
}
// show if it was hidden
if (r.obj.style.display == 'none')
$(r.obj).show();
}
else {
if (r.depth == depth)
r.parent_uid = parent;
if (r.unread && roots.length)
roots[roots.length-1].unread_children++;
}
}
row = row.nextSibling;
}
// update unread_children for roots
for (r=0; r<roots.length; r++)
this.set_unread_children(roots[r].uid);
return count;
};
this.delete_excessive_thread_rows = function()
{
var rows = this.message_list.rows,
tbody = this.message_list.tbody,
row = tbody.firstChild,
cnt = this.env.pagesize + 1;
while (row) {
if (row.nodeType == 1 && (r = rows[row.uid])) {
if (!r.depth && cnt)
cnt--;
if (!cnt)
this.message_list.remove_row(row.uid);
}
row = row.nextSibling;
}
};
// set message icon
this.set_message_icon = function(uid)
{
var css_class, label = '',
row = this.message_list.rows[uid];
if (!row)
return false;
if (row.icon) {
css_class = 'msgicon';
if (row.deleted) {
css_class += ' deleted';
label += this.get_label('deleted') + ' ';
}
else if (row.unread) {
css_class += ' unread';
label += this.get_label('unread') + ' ';
}
else if (row.unread_children)
css_class += ' unreadchildren';
if (row.msgicon == row.icon) {
if (row.replied) {
css_class += ' replied';
label += this.get_label('replied') + ' ';
}
if (row.forwarded) {
css_class += ' forwarded';
label += this.get_label('forwarded') + ' ';
}
css_class += ' status';
}
$(row.icon).attr('class', css_class).attr('title', label);
}
if (row.msgicon && row.msgicon != row.icon) {
label = '';
css_class = 'msgicon';
if (!row.unread && row.unread_children) {
css_class += ' unreadchildren';
}
if (row.replied) {
css_class += ' replied';
label += this.get_label('replied') + ' ';
}
if (row.forwarded) {
css_class += ' forwarded';
label += this.get_label('forwarded') + ' ';
}
$(row.msgicon).attr('class', css_class).attr('title', label);
}
if (row.flagicon) {
css_class = (row.flagged ? 'flagged' : 'unflagged');
label = this.get_label(css_class);
$(row.flagicon).attr('class', css_class)
.attr('aria-label', label)
.attr('title', label);
}
};
// set message status
this.set_message_status = function(uid, flag, status)
{
var row = this.message_list.rows[uid];
if (!row)
return false;
if (flag == 'unread') {
if (row.unread != status)
this.update_thread_root(uid, status ? 'unread' : 'read');
}
if ($.inArray(flag, ['unread', 'deleted', 'replied', 'forwarded', 'flagged']) > -1)
row[flag] = status;
};
// set message row status, class and icon
this.set_message = function(uid, flag, status)
{
var row = this.message_list && this.message_list.rows[uid];
if (!row)
return false;
if (flag)
this.set_message_status(uid, flag, status);
if ($.inArray(flag, ['unread', 'deleted', 'flagged']) > -1)
$(row.obj)[row[flag] ? 'addClass' : 'removeClass'](flag);
this.set_unread_children(uid);
this.set_message_icon(uid);
};
// sets unroot (unread_children) class of parent row
this.set_unread_children = function(uid)
{
var row = this.message_list.rows[uid];
if (row.parent_uid)
return;
if (!row.unread && row.unread_children && !row.expanded)
$(row.obj).addClass('unroot');
else
$(row.obj).removeClass('unroot');
};
// copy selected messages to the specified mailbox
this.copy_messages = function(mbox, event)
{
if (mbox && typeof mbox === 'object')
mbox = mbox.id;
else if (!mbox)
return this.folder_selector(event, function(folder) { ref.command('copy', folder); });
// exit if current or no mailbox specified
if (!mbox || mbox == this.env.mailbox)
return;
var post_data = this.selection_post_data({_target_mbox: mbox});
// exit if selection is empty
if (!post_data._uid)
return;
// send request to server
this.http_post('copy', post_data, this.display_message(this.get_label('copyingmessage'), 'loading'));
};
// move selected messages to the specified mailbox
this.move_messages = function(mbox, event)
{
if (mbox && typeof mbox === 'object')
mbox = mbox.id;
else if (!mbox)
return this.folder_selector(event, function(folder) { ref.command('move', folder); });
// exit if current or no mailbox specified
if (!mbox || (mbox == this.env.mailbox && !this.is_multifolder_listing()))
return;
var lock = false, post_data = this.selection_post_data({_target_mbox: mbox});
// exit if selection is empty
if (!post_data._uid)
return;
// show wait message
if (this.env.action == 'show')
lock = this.set_busy(true, 'movingmessage');
else
this.show_contentframe(false);
// Hide message command buttons until a message is selected
this.enable_command(this.env.message_commands, false);
this._with_selected_messages('move', post_data, lock);
};
// delete selected messages from the current mailbox
this.delete_messages = function(event)
{
var list = this.message_list, trash = this.env.trash_mailbox;
// if config is set to flag for deletion
if (this.env.flag_for_deletion) {
this.mark_message('delete');
return false;
}
// if there isn't a defined trash mailbox or we are in it
else if (!trash || this.env.mailbox == trash)
this.permanently_remove_messages();
// we're in Junk folder and delete_junk is enabled
else if (this.env.delete_junk && this.env.junk_mailbox && this.env.mailbox == this.env.junk_mailbox)
this.permanently_remove_messages();
// if there is a trash mailbox defined and we're not currently in it
else {
// if shift was pressed delete it immediately
if ((list && list.modkey == SHIFT_KEY) || (event && rcube_event.get_modifier(event) == SHIFT_KEY)) {
if (confirm(this.get_label('deletemessagesconfirm')))
this.permanently_remove_messages();
}
else
this.move_messages(trash);
}
return true;
};
// delete the selected messages permanently
this.permanently_remove_messages = function()
{
var post_data = this.selection_post_data();
// exit if selection is empty
if (!post_data._uid)
return;
this.show_contentframe(false);
this._with_selected_messages('delete', post_data);
};
// Send a specific move/delete request with UIDs of all selected messages
// @private
this._with_selected_messages = function(action, post_data, lock)
{
var count = 0, msg,
remove = (action == 'delete' || !this.is_multifolder_listing());
// update the list (remove rows, clear selection)
if (this.message_list) {
var n, id, root, roots = [],
selection = this.message_list.get_selection();
for (n=0, len=selection.length; n<len; n++) {
id = selection[n];
if (this.env.threading) {
count += this.update_thread(id);
root = this.message_list.find_root(id);
if (root != id && $.inArray(root, roots) < 0) {
roots.push(root);
}
}
if (remove)
this.message_list.remove_row(id, (this.env.display_next && n == selection.length-1));
}
// make sure there are no selected rows
if (!this.env.display_next && remove)
this.message_list.clear_selection();
// update thread tree icons
for (n=0, len=roots.length; n<len; n++) {
this.add_tree_icons(roots[n]);
}
}
if (count < 0)
post_data._count = (count*-1);
// remove threads from the end of the list
else if (count > 0 && remove)
this.delete_excessive_thread_rows();
if (!remove)
post_data._refresh = 1;
if (!lock) {
msg = action == 'move' ? 'movingmessage' : 'deletingmessage';
lock = this.display_message(this.get_label(msg), 'loading');
}
// send request to server
this.http_post(action, post_data, lock);
};
// build post data for message delete/move/copy/flag requests
this.selection_post_data = function(data)
{
if (typeof(data) != 'object')
data = {};
data._mbox = this.env.mailbox;
if (!data._uid) {
var uids = this.env.uid ? [this.env.uid] : this.message_list.get_selection();
data._uid = this.uids_to_list(uids);
}
if (this.env.action)
data._from = this.env.action;
// also send search request to get the right messages
if (this.env.search_request)
data._search = this.env.search_request;
if (this.env.display_next && this.env.next_uid)
data._next_uid = this.env.next_uid;
return data;
};
// set a specific flag to one or more messages
this.mark_message = function(flag, uid)
{
var a_uids = [], r_uids = [], len, n, id,
list = this.message_list;
if (uid)
a_uids[0] = uid;
else if (this.env.uid)
a_uids[0] = this.env.uid;
else if (list)
a_uids = list.get_selection();
if (!list)
r_uids = a_uids;
else {
list.focus();
for (n=0, len=a_uids.length; n<len; n++) {
id = a_uids[n];
if ((flag == 'read' && list.rows[id].unread)
|| (flag == 'unread' && !list.rows[id].unread)
|| (flag == 'delete' && !list.rows[id].deleted)
|| (flag == 'undelete' && list.rows[id].deleted)
|| (flag == 'flagged' && !list.rows[id].flagged)
|| (flag == 'unflagged' && list.rows[id].flagged))
{
r_uids.push(id);
}
}
}
// nothing to do
if (!r_uids.length && !this.select_all_mode)
return;
switch (flag) {
case 'read':
case 'unread':
this.toggle_read_status(flag, r_uids);
break;
case 'delete':
case 'undelete':
this.toggle_delete_status(r_uids);
break;
case 'flagged':
case 'unflagged':
this.toggle_flagged_status(flag, a_uids);
break;
}
};
// set class to read/unread
this.toggle_read_status = function(flag, a_uids)
{
var i, len = a_uids.length,
post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
lock = this.display_message(this.get_label('markingmessage'), 'loading');
// mark all message rows as read/unread
for (i=0; i<len; i++)
this.set_message(a_uids[i], 'unread', (flag == 'unread' ? true : false));
this.http_post('mark', post_data, lock);
};
// set image to flagged or unflagged
this.toggle_flagged_status = function(flag, a_uids)
{
var i, len = a_uids.length,
post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: flag}),
lock = this.display_message(this.get_label('markingmessage'), 'loading');
// mark all message rows as flagged/unflagged
for (i=0; i<len; i++)
this.set_message(a_uids[i], 'flagged', (flag == 'flagged' ? true : false));
this.http_post('mark', post_data, lock);
};
// mark all message rows as deleted/undeleted
this.toggle_delete_status = function(a_uids)
{
var len = a_uids.length,
i, uid, all_deleted = true,
rows = this.message_list ? this.message_list.rows : {};
if (len == 1) {
if (!this.message_list || (rows[a_uids[0]] && !rows[a_uids[0]].deleted))
this.flag_as_deleted(a_uids);
else
this.flag_as_undeleted(a_uids);
return true;
}
for (i=0; i<len; i++) {
uid = a_uids[i];
if (rows[uid] && !rows[uid].deleted) {
all_deleted = false;
break;
}
}
if (all_deleted)
this.flag_as_undeleted(a_uids);
else
this.flag_as_deleted(a_uids);
return true;
};
this.flag_as_undeleted = function(a_uids)
{
var i, len = a_uids.length,
post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'undelete'}),
lock = this.display_message(this.get_label('markingmessage'), 'loading');
for (i=0; i<len; i++)
this.set_message(a_uids[i], 'deleted', false);
this.http_post('mark', post_data, lock);
};
this.flag_as_deleted = function(a_uids)
{
var r_uids = [],
post_data = this.selection_post_data({_uid: this.uids_to_list(a_uids), _flag: 'delete'}),
lock = this.display_message(this.get_label('markingmessage'), 'loading'),
rows = this.message_list ? this.message_list.rows : {},
count = 0;
for (var i=0, len=a_uids.length; i<len; i++) {
uid = a_uids[i];
if (rows[uid]) {
if (rows[uid].unread)
r_uids[r_uids.length] = uid;
if (this.env.skip_deleted) {
count += this.update_thread(uid);
this.message_list.remove_row(uid, (this.env.display_next && i == this.message_list.selection.length-1));
}
else
this.set_message(uid, 'deleted', true);
}
}
// make sure there are no selected rows
if (this.env.skip_deleted && this.message_list) {
if (!this.env.display_next)
this.message_list.clear_selection();
if (count < 0)
post_data._count = (count*-1);
else if (count > 0)
// remove threads from the end of the list
this.delete_excessive_thread_rows();
}
// set of messages to mark as seen
if (r_uids.length)
post_data._ruid = this.uids_to_list(r_uids);
if (this.env.skip_deleted && this.env.display_next && this.env.next_uid)
post_data._next_uid = this.env.next_uid;
this.http_post('mark', post_data, lock);
};
// flag as read without mark request (called from backend)
// argument should be a coma-separated list of uids
this.flag_deleted_as_read = function(uids)
{
var uid, i, len,
rows = this.message_list ? this.message_list.rows : {};
if (typeof uids == 'string')
uids = uids.split(',');
for (i=0, len=uids.length; i<len; i++) {
uid = uids[i];
if (rows[uid])
this.set_message(uid, 'unread', false);
}
};
// Converts array of message UIDs to comma-separated list for use in URL
// with select_all mode checking
this.uids_to_list = function(uids)
{
return this.select_all_mode ? '*' : (uids.length <= 1 ? uids.join(',') : uids);
};
// Sets title of the delete button
this.set_button_titles = function()
{
var label = 'deletemessage';
if (!this.env.flag_for_deletion
&& this.env.trash_mailbox && this.env.mailbox != this.env.trash_mailbox
&& (!this.env.delete_junk || !this.env.junk_mailbox || this.env.mailbox != this.env.junk_mailbox)
)
label = 'movemessagetotrash';
this.set_alttext('delete', label);
};
// Initialize input element for list page jump
this.init_pagejumper = function(element)
{
$(element).addClass('rcpagejumper')
.on('focus', function(e) {
// create and display popup with page selection
var i, html = '';
for (i = 1; i <= ref.env.pagecount; i++)
html += '<li>' + i + '</li>';
html = '<ul class="toolbarmenu">' + html + '</ul>';
if (!ref.pagejump) {
ref.pagejump = $('<div id="pagejump-selector" class="popupmenu"></div>')
.appendTo(document.body)
.on('click', 'li', function() {
if (!ref.busy)
$(element).val($(this).text()).change();
});
}
if (ref.pagejump.data('count') != i)
ref.pagejump.html(html);
ref.pagejump.attr('rel', '#' + this.id).data('count', i);
// display page selector
ref.show_menu('pagejump-selector', true, e);
$(this).keydown();
})
// keyboard navigation
.on('keydown keyup click', function(e) {
var current, selector = $('#pagejump-selector'),
ul = $('ul', selector),
list = $('li', ul),
height = ul.height(),
p = parseInt(this.value);
if (e.which != 27 && e.which != 9 && e.which != 13 && !selector.is(':visible'))
return ref.show_menu('pagejump-selector', true, e);
if (e.type == 'keydown') {
// arrow-down
if (e.which == 40) {
if (list.length > p)
this.value = (p += 1);
}
// arrow-up
else if (e.which == 38) {
if (p > 1 && list.length > p - 1)
this.value = (p -= 1);
}
// enter
else if (e.which == 13) {
return $(this).change();
}
// esc, tab
else if (e.which == 27 || e.which == 9) {
return $(element).val(ref.env.current_page);
}
}
$('li.selected', ul).removeClass('selected');
if ((current = $(list[p - 1])).length) {
current.addClass('selected');
$('#pagejump-selector').scrollTop(((ul.height() / list.length) * (p - 1)) - selector.height() / 2);
}
})
.on('change', function(e) {
// go to specified page
var p = parseInt(this.value);
if (p && p != ref.env.current_page && !ref.busy) {
ref.hide_menu('pagejump-selector');
ref.list_page(p);
}
});
};
// Update page-jumper state on list updates
this.update_pagejumper = function()
{
$('input.rcpagejumper').val(this.env.current_page).prop('disabled', this.env.pagecount < 2);
};
// check for mailvelope API
this.check_mailvelope = function(action)
{
if (typeof window.mailvelope !== 'undefined') {
this.mailvelope_load(action);
}
else {
$(window).on('mailvelope', function() {
ref.mailvelope_load(action);
});
}
};
// Load Mailvelope functionality (and initialize keyring if needed)
this.mailvelope_load = function(action)
{
if (this.env.browser_capabilities)
this.env.browser_capabilities['pgpmime'] = 1;
var keyring = this.env.user_id;
mailvelope.getKeyring(keyring).then(function(kr) {
ref.mailvelope_keyring = kr;
ref.mailvelope_init(action, kr);
}).catch(function(err) {
// attempt to create a new keyring for this app/user
mailvelope.createKeyring(keyring).then(function(kr) {
ref.mailvelope_keyring = kr;
ref.mailvelope_init(action, kr);
}).catch(function(err) {
console.error(err);
});
});
};
// Initializes Mailvelope editor or display container
this.mailvelope_init = function(action, keyring)
{
if (!window.mailvelope)
return;
if (action == 'show' || action == 'preview' || action == 'print') {
// decrypt text body
if (this.env.is_pgp_content) {
var data = $(this.env.is_pgp_content).text();
ref.mailvelope_display_container(this.env.is_pgp_content, data, keyring);
}
// load pgp/mime message and pass it to the mailvelope display container
else if (this.env.pgp_mime_part) {
var msgid = this.display_message(this.get_label('loadingdata'), 'loading'),
selector = this.env.pgp_mime_container;
$.ajax({
type: 'GET',
url: this.url('get', { '_mbox': this.env.mailbox, '_uid': this.env.uid, '_part': this.env.pgp_mime_part }),
error: function(o, status, err) {
ref.http_error(o, status, err, msgid);
},
success: function(data) {
ref.mailvelope_display_container(selector, data, keyring, msgid);
}
});
}
}
else if (action == 'compose') {
this.env.compose_commands.push('compose-encrypted');
var is_html = $('input[name="_is_html"]').val() > 0;
if (this.env.pgp_mime_message) {
// fetch PGP/Mime part and open load into Mailvelope editor
var lock = this.set_busy(true, this.get_label('loadingdata'));
$.ajax({
type: 'GET',
url: this.url('get', this.env.pgp_mime_message),
error: function(o, status, err) {
ref.http_error(o, status, err, lock);
ref.enable_command('compose-encrypted', !is_html);
},
success: function(data) {
ref.set_busy(false, null, lock);
if (is_html) {
ref.command('toggle-editor', {html: false, noconvert: true});
$('#' + ref.env.composebody).val('');
}
ref.compose_encrypted({ quotedMail: data });
ref.enable_command('compose-encrypted', true);
}
});
}
else {
// enable encrypted compose toggle
this.enable_command('compose-encrypted', !is_html);
}
}
};
// handler for the 'compose-encrypted' command
this.compose_encrypted = function(props)
{
var options, container = $('#' + this.env.composebody).parent();
// remove Mailvelope editor if active
if (ref.mailvelope_editor) {
ref.mailvelope_editor = null;
ref.compose_skip_unsavedcheck = false;
ref.set_button('compose-encrypted', 'act');
container.removeClass('mailvelope')
.find('iframe:not([aria-hidden=true])').remove();
$('#' + ref.env.composebody).show();
$("[name='_pgpmime']").remove();
// disable commands that operate on the compose body
ref.enable_command('spellcheck', 'insert-sig', 'toggle-editor', 'insert-response', 'save-response', true);
ref.triggerEvent('compose-encrypted', { active:false });
}
// embed Mailvelope editor container
else {
if (this.spellcheck_state())
this.editor.spellcheck_stop();
if (props.quotedMail) {
options = { quotedMail: props.quotedMail, quotedMailIndent: false };
}
else {
options = { predefinedText: $('#' + this.env.composebody).val() };
}
if (this.env.compose_mode == 'reply') {
options.quotedMailIndent = true;
options.quotedMailHeader = this.env.compose_reply_header;
}
mailvelope.createEditorContainer('#' + container.attr('id'), ref.mailvelope_keyring, options).then(function(editor) {
ref.mailvelope_editor = editor;
ref.compose_skip_unsavedcheck = true;
ref.set_button('compose-encrypted', 'sel');
container.addClass('mailvelope');
$('#' + ref.env.composebody).hide();
// disable commands that operate on the compose body
ref.enable_command('spellcheck', 'insert-sig', 'toggle-editor', 'insert-response', 'save-response', false);
ref.triggerEvent('compose-encrypted', { active:true });
// notify user about loosing attachments
if (ref.env.attachments && !$.isEmptyObject(ref.env.attachments)) {
alert(ref.get_label('encryptnoattachments'));
$.each(ref.env.attachments, function(name, attach) {
ref.remove_from_attachment_list(name);
});
}
}).catch(function(err) {
console.error(err);
console.log(options);
});
}
};
// callback to replace the message body with the full armored
this.mailvelope_submit_messageform = function(draft, saveonly)
{
// get recipients
var recipients = [];
$.each(['to', 'cc', 'bcc'], function(i,field) {
var pos, rcpt, val = $.trim($('[name="_' + field + '"]').val());
while (val.length && rcube_check_email(val, true)) {
rcpt = RegExp.$2;
recipients.push(rcpt);
val = val.substr(val.indexOf(rcpt) + rcpt.length + 1).replace(/^\s*,\s*/, '');
}
});
// check if we have keys for all recipients
var isvalid = recipients.length > 0;
ref.mailvelope_keyring.validKeyForAddress(recipients).then(function(status) {
var missing_keys = [];
$.each(status, function(k,v) {
if (v === false) {
isvalid = false;
missing_keys.push(k);
}
});
// list recipients with missing keys
if (!isvalid && missing_keys.length) {
// load publickey.js
if (!$('script#publickeyjs').length) {
$('<script>')
.attr('id', 'publickeyjs')
.attr('src', ref.assets_path('program/js/publickey.js'))
.appendTo(document.body);
}
// display dialog with missing keys
ref.show_popup_dialog(
ref.get_label('nopubkeyfor').replace('$email', missing_keys.join(', ')) +
'<p>' + ref.get_label('searchpubkeyservers') + '</p>',
ref.get_label('encryptedsendialog'),
[{
text: ref.get_label('search'),
'class': 'mainaction',
click: function() {
var $dialog = $(this);
ref.mailvelope_search_pubkeys(missing_keys, function() {
$dialog.dialog('close')
});
}
},
{
text: ref.get_label('cancel'),
click: function(){
$(this).dialog('close');
}
}]
);
return false;
}
if (!isvalid) {
if (!recipients.length) {
alert(ref.get_label('norecipientwarning'));
$("[name='_to']").focus();
}
return false;
}
// add sender identity to recipients to be able to decrypt our very own message
var senders = [], selected_sender = ref.env.identities[$("[name='_from'] option:selected").val()];
$.each(ref.env.identities, function(k, sender) {
senders.push(sender.email);
});
ref.mailvelope_keyring.validKeyForAddress(senders).then(function(status) {
valid_sender = null;
$.each(status, function(k,v) {
if (v !== false) {
valid_sender = k;
if (valid_sender == selected_sender) {
return false; // break
}
}
});
if (!valid_sender) {
if (!confirm(ref.get_label('nopubkeyforsender'))) {
return false;
}
}
recipients.push(valid_sender);
ref.mailvelope_editor.encrypt(recipients).then(function(armored) {
// all checks passed, send message
var form = ref.gui_objects.messageform,
hidden = $("[name='_pgpmime']", form),
msgid = ref.set_busy(true, draft || saveonly ? 'savingmessage' : 'sendingmessage')
form.target = 'savetarget';
form._draft.value = draft ? '1' : '';
form.action = ref.add_url(form.action, '_unlock', msgid);
form.action = ref.add_url(form.action, '_framed', 1);
if (saveonly) {
form.action = ref.add_url(form.action, '_saveonly', 1);
}
// send pgp conent via hidden field
if (!hidden.length) {
hidden = $('<input type="hidden" name="_pgpmime">').appendTo(form);
}
hidden.val(armored);
form.submit();
}).catch(function(err) {
console.log(err);
}); // mailvelope_editor.encrypt()
}).catch(function(err) {
console.error(err);
}); // mailvelope_keyring.validKeyForAddress(senders)
}).catch(function(err) {
console.error(err);
}); // mailvelope_keyring.validKeyForAddress(recipients)
return false;
};
// wrapper for the mailvelope.createDisplayContainer API call
this.mailvelope_display_container = function(selector, data, keyring, msgid)
{
mailvelope.createDisplayContainer(selector, data, keyring, { showExternalContent: this.env.safemode }).then(function() {
$(selector).addClass('mailvelope').children().not('iframe').hide();
ref.hide_message(msgid);
setTimeout(function() { $(window).resize(); }, 10);
}).catch(function(err) {
console.error(err);
ref.hide_message(msgid);
ref.display_message('Message decryption failed: ' + err.message, 'error')
});
};
// subroutine to query keyservers for public keys
this.mailvelope_search_pubkeys = function(emails, resolve)
{
// query with publickey.js
var deferreds = [],
pk = new PublicKey(),
lock = ref.display_message(ref.get_label('loading'), 'loading');
$.each(emails, function(i, email) {
var d = $.Deferred();
pk.search(email, function(results, errorCode) {
if (errorCode !== null) {
// rejecting would make all fail
// d.reject(email);
d.resolve([email]);
}
else {
d.resolve([email].concat(results));
}
});
deferreds.push(d);
});
$.when.apply($, deferreds).then(function() {
var missing_keys = [],
key_selection = [];
// alanyze results of all queries
$.each(arguments, function(i, result) {
var email = result.shift();
if (!result.length) {
missing_keys.push(email);
}
else {
key_selection = key_selection.concat(result);
}
});
ref.hide_message(lock);
resolve(true);
// show key import dialog
if (key_selection.length) {
ref.mailvelope_key_import_dialog(key_selection);
}
// some keys could not be found
if (missing_keys.length) {
ref.display_message(ref.get_label('nopubkeyfor').replace('$email', missing_keys.join(', ')), 'warning');
}
}, function() {
console.error('Pubkey lookup failed with', arguments);
ref.hide_message(lock);
ref.display_message('pubkeysearcherror', 'error');
resolve(false);
});
};
// list the given public keys in a dialog with options to import
// them into the local Maivelope keyring
this.mailvelope_key_import_dialog = function(candidates)
{
var ul = $('<div>').addClass('listing mailvelopekeyimport');
$.each(candidates, function(i, keyrec) {
var li = $('<div>').addClass('key');
if (keyrec.revoked) li.addClass('revoked');
if (keyrec.disabled) li.addClass('disabled');
if (keyrec.expired) li.addClass('expired');
li.append($('<label>').addClass('keyid').text(ref.get_label('keyid')));
li.append($('<a>').text(keyrec.keyid.substr(-8).toUpperCase())
.attr('href', keyrec.info)
.attr('target', '_blank')
.attr('tabindex', '-1'));
li.append($('<label>').addClass('keylen').text(ref.get_label('keylength')));
li.append($('<span>').text(keyrec.keylen));
if (keyrec.expirationdate) {
li.append($('<label>').addClass('keyexpired').text(ref.get_label('keyexpired')));
li.append($('<span>').text(new Date(keyrec.expirationdate * 1000).toDateString()));
}
if (keyrec.revoked) {
li.append($('<span>').addClass('keyrevoked').text(ref.get_label('keyrevoked')));
}
var ul_ = $('<ul>').addClass('uids');
$.each(keyrec.uids, function(j, uid) {
var li_ = $('<li>').addClass('uid');
if (uid.revoked) li_.addClass('revoked');
if (uid.disabled) li_.addClass('disabled');
if (uid.expired) li_.addClass('expired');
ul_.append(li_.text(uid.uid));
});
li.append(ul_);
li.append($('<input>')
.attr('type', 'button')
.attr('rel', keyrec.keyid)
.attr('value', ref.get_label('import'))
.addClass('button importkey')
.prop('disabled', keyrec.revoked || keyrec.disabled || keyrec.expired));
ul.append(li);
});
// display dialog with missing keys
ref.show_popup_dialog(
$('<div>')
.append($('<p>').html(ref.get_label('encryptpubkeysfound')))
.append(ul),
ref.get_label('importpubkeys'),
[{
text: ref.get_label('close'),
click: function(){
$(this).dialog('close');
}
}]
);
// delegate handler for import button clicks
ul.on('click', 'input.button.importkey', function() {
var btn = $(this),
keyid = btn.attr('rel'),
pk = new PublicKey(),
lock = ref.display_message(ref.get_label('loading'), 'loading');
// fetch from keyserver and import to Mailvelope keyring
pk.get(keyid, function(armored, errorCode) {
ref.hide_message(lock);
if (errorCode) {
ref.display_message(ref.get_label('keyservererror'), 'error');
return;
}
// import to keyring
ref.mailvelope_keyring.importPublicKey(armored).then(function(status) {
if (status === 'REJECTED') {
// alert(ref.get_label('Key import was rejected'));
}
else {
var $key = keyid.substr(-8).toUpperCase();
btn.closest('.key').fadeOut();
ref.display_message(ref.get_label('keyimportsuccess').replace('$key', $key), 'confirmation');
}
}).catch(function(err) {
console.log(err);
});
});
});
};
/*********************************************************/
/********* mailbox folders methods *********/
/*********************************************************/
this.expunge_mailbox = function(mbox)
{
var lock, post_data = {_mbox: mbox};
// lock interface if it's the active mailbox
if (mbox == this.env.mailbox) {
lock = this.set_busy(true, 'loading');
post_data._reload = 1;
if (this.env.search_request)
post_data._search = this.env.search_request;
}
// send request to server
this.http_post('expunge', post_data, lock);
};
this.purge_mailbox = function(mbox)
{
var lock, post_data = {_mbox: mbox};
if (!confirm(this.get_label('purgefolderconfirm')))
return false;
// lock interface if it's the active mailbox
if (mbox == this.env.mailbox) {
lock = this.set_busy(true, 'loading');
post_data._reload = 1;
}
// send request to server
this.http_post('purge', post_data, lock);
};
// test if purge command is allowed
this.purge_mailbox_test = function()
{
return (this.env.exists && (
this.env.mailbox == this.env.trash_mailbox
|| this.env.mailbox == this.env.junk_mailbox
|| this.env.mailbox.startsWith(this.env.trash_mailbox + this.env.delimiter)
|| this.env.mailbox.startsWith(this.env.junk_mailbox + this.env.delimiter)
));
};
/*********************************************************/
/********* login form methods *********/
/*********************************************************/
// handler for keyboard events on the _user field
this.login_user_keyup = function(e)
{
var key = rcube_event.get_keycode(e),
passwd = $('#rcmloginpwd');
// enter
if (key == 13 && passwd.length && !passwd.val()) {
passwd.focus();
return rcube_event.cancel(e);
}
return true;
};
/*********************************************************/
/********* message compose methods *********/
/*********************************************************/
this.open_compose_step = function(p)
{
var url = this.url('mail/compose', p);
// open new compose window
if (this.env.compose_extwin && !this.env.extwin) {
this.open_window(url);
}
else {
this.redirect(url);
if (this.env.extwin)
window.resizeTo(Math.max(this.env.popup_width, $(window).width()), $(window).height() + 24);
}
};
// init message compose form: set focus and eventhandlers
this.init_messageform = function()
{
if (!this.gui_objects.messageform)
return false;
var i, elem, pos, input_from = $("[name='_from']"),
input_to = $("[name='_to']"),
input_subject = $("input[name='_subject']"),
input_message = $("[name='_message']").get(0),
html_mode = $("input[name='_is_html']").val() == '1',
ac_fields = ['cc', 'bcc', 'replyto', 'followupto'],
ac_props, opener_rc = this.opener();
// close compose step in opener
if (opener_rc && opener_rc.env.action == 'compose') {
setTimeout(function(){
if (opener.history.length > 1)
opener.history.back();
else
opener_rc.redirect(opener_rc.get_task_url('mail'));
}, 100);
this.env.opened_extwin = true;
}
// configure parallel autocompletion
if (this.env.autocomplete_threads > 0) {
ac_props = {
threads: this.env.autocomplete_threads,
sources: this.env.autocomplete_sources
};
}
// init live search events
this.init_address_input_events(input_to, ac_props);
for (i in ac_fields) {
this.init_address_input_events($("[name='_"+ac_fields[i]+"']"), ac_props);
}
if (!html_mode) {
pos = this.env.top_posting ? 0 : input_message.value.length;
// add signature according to selected identity
// if we have HTML editor, signature is added in a callback
if (input_from.prop('type') == 'select-one') {
this.change_identity(input_from[0]);
}
// set initial cursor position
this.set_caret_pos(input_message, pos);
// scroll to the bottom of the textarea (#1490114)
if (pos) {
$(input_message).scrollTop(input_message.scrollHeight);
}
}
// check for locally stored compose data
if (this.env.save_localstorage)
this.compose_restore_dialog(0, html_mode)
if (input_to.val() == '')
elem = input_to;
else if (input_subject.val() == '')
elem = input_subject;
else if (input_message)
elem = input_message;
// focus first empty element (need to be visible on IE8)
$(elem).filter(':visible').focus();
this.env.compose_focus_elem = document.activeElement;
// get summary of all field values
this.compose_field_hash(true);
// start the auto-save timer
this.auto_save_start();
};
this.compose_restore_dialog = function(j, html_mode)
{
var i, key, formdata, index = this.local_storage_get_item('compose.index', []);
var show_next = function(i) {
if (++i < index.length)
ref.compose_restore_dialog(i, html_mode)
}
for (i = j || 0; i < index.length; i++) {
key = index[i];
formdata = this.local_storage_get_item('compose.' + key, null, true);
if (!formdata) {
continue;
}
// restore saved copy of current compose_id
if (formdata.changed && key == this.env.compose_id) {
this.restore_compose_form(key, html_mode);
break;
}
// skip records from 'other' drafts
if (this.env.draft_id && formdata.draft_id && formdata.draft_id != this.env.draft_id) {
continue;
}
// skip records on reply
if (this.env.reply_msgid && formdata.reply_msgid != this.env.reply_msgid) {
continue;
}
// show dialog asking to restore the message
if (formdata.changed && formdata.session != this.env.session_id) {
this.show_popup_dialog(
this.get_label('restoresavedcomposedata')
.replace('$date', new Date(formdata.changed).toLocaleString())
.replace('$subject', formdata._subject)
.replace(/\n/g, '<br/>'),
this.get_label('restoremessage'),
[{
text: this.get_label('restore'),
'class': 'mainaction',
click: function(){
ref.restore_compose_form(key, html_mode);
ref.remove_compose_data(key); // remove old copy
ref.save_compose_form_local(); // save under current compose_id
$(this).dialog('close');
}
},
{
text: this.get_label('delete'),
'class': 'delete',
click: function(){
ref.remove_compose_data(key);
$(this).dialog('close');
show_next(i);
}
},
{
text: this.get_label('ignore'),
click: function(){
$(this).dialog('close');
show_next(i);
}
}]
);
break;
}
}
}
this.init_address_input_events = function(obj, props)
{
this.env.recipients_delimiter = this.env.recipients_separator + ' ';
obj.keydown(function(e) { return ref.ksearch_keydown(e, this, props); })
.attr({ 'autocomplete': 'off', 'aria-autocomplete': 'list', 'aria-expanded': 'false', 'role': 'combobox' });
};
this.submit_messageform = function(draft, saveonly)
{
var form = this.gui_objects.messageform;
if (!form)
return;
// the message has been sent but not saved, ask the user what to do
if (!saveonly && this.env.is_sent) {
return this.show_popup_dialog(this.get_label('messageissent'), '',
[{
text: this.get_label('save'),
'class': 'mainaction',
click: function() {
ref.submit_messageform(false, true);
$(this).dialog('close');
}
},
{
text: this.get_label('cancel'),
click: function() {
$(this).dialog('close');
}
}]
);
}
// delegate sending to Mailvelope routine
if (this.mailvelope_editor) {
return this.mailvelope_submit_messageform(draft, saveonly);
}
// all checks passed, send message
var msgid = this.set_busy(true, draft || saveonly ? 'savingmessage' : 'sendingmessage'),
lang = this.spellcheck_lang(),
files = [];
// send files list
$('li', this.gui_objects.attachmentlist).each(function() { files.push(this.id.replace(/^rcmfile/, '')); });
$('input[name="_attachments"]', form).val(files.join());
form.target = 'savetarget';
form._draft.value = draft ? '1' : '';
form.action = this.add_url(form.action, '_unlock', msgid);
form.action = this.add_url(form.action, '_lang', lang);
form.action = this.add_url(form.action, '_framed', 1);
if (saveonly) {
form.action = this.add_url(form.action, '_saveonly', 1);
}
// register timer to notify about connection timeout
this.submit_timer = setTimeout(function(){
ref.set_busy(false, null, msgid);
ref.display_message(ref.get_label('requesttimedout'), 'error');
}, this.env.request_timeout * 1000);
form.submit();
};
this.compose_recipient_select = function(list)
{
var id, n, recipients = 0;
for (n=0; n < list.selection.length; n++) {
id = list.selection[n];
if (this.env.contactdata[id])
recipients++;
}
this.enable_command('add-recipient', recipients);
};
this.compose_add_recipient = function(field)
{
// find last focused field name
if (!field) {
field = $(this.env.focused_field).filter(':visible');
field = field.length ? field.attr('id').replace('_', '') : 'to';
}
var recipients = [], input = $('#_'+field), delim = this.env.recipients_delimiter;
if (this.contact_list && this.contact_list.selection.length) {
for (var id, n=0; n < this.contact_list.selection.length; n++) {
id = this.contact_list.selection[n];
if (id && this.env.contactdata[id]) {
recipients.push(this.env.contactdata[id]);
// group is added, expand it
if (id.charAt(0) == 'E' && this.env.contactdata[id].indexOf('@') < 0 && input.length) {
var gid = id.substr(1);
this.group2expand[gid] = { name:this.env.contactdata[id], input:input.get(0) };
this.http_request('group-expand', {_source: this.env.source, _gid: gid}, false);
}
}
}
}
if (recipients.length && input.length) {
var oldval = input.val(), rx = new RegExp(RegExp.escape(delim) + '\\s*$');
if (oldval && !rx.test(oldval))
oldval += delim + ' ';
input.val(oldval + recipients.join(delim + ' ') + delim + ' ').change();
this.triggerEvent('add-recipient', { field:field, recipients:recipients });
}
return recipients.length;
};
// checks the input fields before sending a message
this.check_compose_input = function(cmd)
{
// check input fields
var input_to = $("[name='_to']"),
input_cc = $("[name='_cc']"),
input_bcc = $("[name='_bcc']"),
input_from = $("[name='_from']"),
input_subject = $("[name='_subject']");
// check sender (if have no identities)
if (input_from.prop('type') == 'text' && !rcube_check_email(input_from.val(), true)) {
alert(this.get_label('nosenderwarning'));
input_from.focus();
return false;
}
// check for empty recipient
var recipients = input_to.val() ? input_to.val() : (input_cc.val() ? input_cc.val() : input_bcc.val());
if (!rcube_check_email(recipients.replace(/^\s+/, '').replace(/[\s,;]+$/, ''), true)) {
alert(this.get_label('norecipientwarning'));
input_to.focus();
return false;
}
// check if all files has been uploaded
for (var key in this.env.attachments) {
if (typeof this.env.attachments[key] === 'object' && !this.env.attachments[key].complete) {
alert(this.get_label('notuploadedwarning'));
return false;
}
}
// display localized warning for missing subject
if (input_subject.val() == '') {
var buttons = {},
myprompt = $('<div class="prompt">').html('<div class="message">' + this.get_label('nosubjectwarning') + '</div>')
.appendTo(document.body),
prompt_value = $('<input>').attr({type: 'text', size: 30}).val(this.get_label('nosubject'))
.appendTo(myprompt),
save_func = function() {
input_subject.val(prompt_value.val());
myprompt.dialog('close');
ref.command(cmd, { nocheck:true }); // repeat command which triggered this
};
buttons[this.get_label('sendmessage')] = function() {
save_func($(this));
};
buttons[this.get_label('cancel')] = function() {
input_subject.focus();
$(this).dialog('close');
};
myprompt.dialog({
modal: true,
resizable: false,
buttons: buttons,
close: function(event, ui) { $(this).remove(); }
});
prompt_value.select().keydown(function(e) {
if (e.which == 13) save_func();
});
return false;
}
// check for empty body
if (!this.editor.get_content() && !confirm(this.get_label('nobodywarning'))) {
this.editor.focus();
return false;
}
// move body from html editor to textarea (just to be sure, #1485860)
this.editor.save();
return true;
};
this.toggle_editor = function(props, obj, e)
{
// @todo: this should work also with many editors on page
var result = this.editor.toggle(props.html, props.noconvert || false);
// satisfy the expectations of aftertoggle-editor event subscribers
props.mode = props.html ? 'html' : 'plain';
if (!result && e) {
// fix selector value if operation failed
props.mode = props.html ? 'plain' : 'html';
$(e.target).filter('select').val(props.mode);
}
if (result) {
// update internal format flag
$("input[name='_is_html']").val(props.html ? 1 : 0);
// enable encrypted compose toggle
this.enable_command('compose-encrypted', !props.html);
}
return result;
};
this.insert_response = function(key)
{
var insert = this.env.textresponses[key] ? this.env.textresponses[key].text : null;
if (!insert)
return false;
this.editor.replace(insert);
};
/**
* Open the dialog to save a new canned response
*/
this.save_response = function()
{
// show dialog to enter a name and to modify the text to be saved
var buttons = {}, text = this.editor.get_content({selection: true, format: 'text', nosig: true}),
html = '<form class="propform">' +
'<div class="prop block"><label>' + this.get_label('responsename') + '</label>' +
'<input type="text" name="name" id="ffresponsename" size="40" /></div>' +
'<div class="prop block"><label>' + this.get_label('responsetext') + '</label>' +
'<textarea name="text" id="ffresponsetext" cols="40" rows="8"></textarea></div>' +
'</form>';
buttons[this.get_label('save')] = function(e) {
var name = $('#ffresponsename').val(),
text = $('#ffresponsetext').val();
if (!text) {
$('#ffresponsetext').select();
return false;
}
if (!name)
name = text.substring(0,40);
var lock = ref.display_message(ref.get_label('savingresponse'), 'loading');
ref.http_post('settings/responses', { _insert:1, _name:name, _text:text }, lock);
$(this).dialog('close');
};
buttons[this.get_label('cancel')] = function() {
$(this).dialog('close');
};
this.show_popup_dialog(html, this.get_label('newresponse'), buttons, {button_classes: ['mainaction']});
$('#ffresponsetext').val(text);
$('#ffresponsename').select();
};
this.add_response_item = function(response)
{
var key = response.key;
this.env.textresponses[key] = response;
// append to responses list
if (this.gui_objects.responseslist) {
var li = $('<li>').appendTo(this.gui_objects.responseslist);
$('<a>').addClass('insertresponse active')
.attr('href', '#')
.attr('rel', key)
.attr('tabindex', '0')
.html(this.quote_html(response.name))
.appendTo(li)
.mousedown(function(e) {
return rcube_event.cancel(e);
})
.on('mouseup keypress', function(e) {
if (e.type == 'mouseup' || rcube_event.get_keycode(e) == 13) {
ref.command('insert-response', $(this).attr('rel'));
$(document.body).trigger('mouseup'); // hides the menu
return rcube_event.cancel(e);
}
});
}
};
this.edit_responses = function()
{
// TODO: implement inline editing of responses
};
this.delete_response = function(key)
{
if (!key && this.responses_list) {
var selection = this.responses_list.get_selection();
key = selection[0];
}
// submit delete request
if (key && confirm(this.get_label('deleteresponseconfirm'))) {
this.http_post('settings/delete-response', { _key: key }, false);
}
};
// updates spellchecker buttons on state change
this.spellcheck_state = function()
{
var active = this.editor.spellcheck_state();
$.each(this.buttons.spellcheck || [], function(i, v) {
$('#' + v.id)[active ? 'addClass' : 'removeClass']('selected');
});
return active;
};
// get selected language
this.spellcheck_lang = function()
{
return this.editor.get_language();
};
this.spellcheck_lang_set = function(lang)
{
this.editor.set_language(lang);
};
// resume spellchecking, highlight provided mispellings without new ajax request
this.spellcheck_resume = function(data)
{
this.editor.spellcheck_resume(data);
};
this.set_draft_id = function(id)
{
if (id && id != this.env.draft_id) {
var filter = {task: 'mail', action: ''},
rc = this.opener(false, filter) || this.opener(true, filter);
// refresh the drafts folder in the opener window
if (rc && rc.env.mailbox == this.env.drafts_mailbox)
rc.command('checkmail');
this.env.draft_id = id;
$("input[name='_draft_saveid']").val(id);
// reset history of hidden iframe used for saving draft (#1489643)
// but don't do this on timer-triggered draft-autosaving (#1489789)
if (window.frames['savetarget'] && window.frames['savetarget'].history && !this.draft_autosave_submit && !this.mailvelope_editor) {
window.frames['savetarget'].history.back();
}
this.draft_autosave_submit = false;
}
// always remove local copy upon saving as draft
this.remove_compose_data(this.env.compose_id);
this.compose_skip_unsavedcheck = false;
};
this.auto_save_start = function()
{
if (this.env.draft_autosave) {
this.draft_autosave_submit = false;
this.save_timer = setTimeout(function(){
ref.draft_autosave_submit = true; // set auto-saved flag (#1489789)
ref.command("savedraft");
}, this.env.draft_autosave * 1000);
}
// save compose form content to local storage every 5 seconds
if (!this.local_save_timer && window.localStorage && this.env.save_localstorage) {
// track typing activity and only save on changes
this.compose_type_activity = this.compose_type_activity_last = 0;
$(document).keypress(function(e) { ref.compose_type_activity++; });
this.local_save_timer = setInterval(function(){
if (ref.compose_type_activity > ref.compose_type_activity_last) {
ref.save_compose_form_local();
ref.compose_type_activity_last = ref.compose_type_activity;
}
}, 5000);
$(window).on('unload', function() {
// remove copy from local storage if compose screen is left after warning
if (!ref.env.server_error)
ref.remove_compose_data(ref.env.compose_id);
});
}
// check for unsaved changes before leaving the compose page
if (!window.onbeforeunload) {
window.onbeforeunload = function() {
if (!ref.compose_skip_unsavedcheck && ref.cmp_hash != ref.compose_field_hash()) {
return ref.get_label('notsentwarning');
}
};
}
// Unlock interface now that saving is complete
this.busy = false;
};
this.compose_field_hash = function(save)
{
// check input fields
var i, id, val, str = '', hash_fields = ['to', 'cc', 'bcc', 'subject'];
for (i=0; i<hash_fields.length; i++)
if (val = $('[name="_' + hash_fields[i] + '"]').val())
str += val + ':';
str += this.editor.get_content({refresh: false});
if (this.env.attachments)
for (id in this.env.attachments)
str += id;
// we can't detect changes in the Mailvelope editor so assume it changed
if (this.mailvelope_editor) {
str += ';' + new Date().getTime();
}
if (save)
this.cmp_hash = str;
return str;
};
// store the contents of the compose form to localstorage
this.save_compose_form_local = function()
{
// feature is disabled
if (!this.env.save_localstorage)
return;
var formdata = { session:this.env.session_id, changed:new Date().getTime() },
ed, empty = true;
// get fresh content from editor
this.editor.save();
if (this.env.draft_id) {
formdata.draft_id = this.env.draft_id;
}
if (this.env.reply_msgid) {
formdata.reply_msgid = this.env.reply_msgid;
}
$('input, select, textarea', this.gui_objects.messageform).each(function(i, elem) {
switch (elem.tagName.toLowerCase()) {
case 'input':
if (elem.type == 'button' || elem.type == 'submit' || (elem.type == 'hidden' && elem.name != '_is_html')) {
break;
}
formdata[elem.name] = elem.type != 'checkbox' || elem.checked ? $(elem).val() : '';
if (formdata[elem.name] != '' && elem.type != 'hidden')
empty = false;
break;
case 'select':
formdata[elem.name] = $('option:checked', elem).val();
break;
default:
formdata[elem.name] = $(elem).val();
if (formdata[elem.name] != '')
empty = false;
}
});
if (!empty) {
var index = this.local_storage_get_item('compose.index', []),
key = this.env.compose_id;
if ($.inArray(key, index) < 0) {
index.push(key);
}
this.local_storage_set_item('compose.' + key, formdata, true);
this.local_storage_set_item('compose.index', index);
}
};
// write stored compose data back to form
this.restore_compose_form = function(key, html_mode)
{
var ed, formdata = this.local_storage_get_item('compose.' + key, true);
if (formdata && typeof formdata == 'object') {
$.each(formdata, function(k, value) {
if (k[0] == '_') {
var elem = $("*[name='"+k+"']");
if (elem[0] && elem[0].type == 'checkbox') {
elem.prop('checked', value != '');
}
else {
elem.val(value);
}
}
});
// initialize HTML editor
if ((formdata._is_html == '1' && !html_mode) || (formdata._is_html != '1' && html_mode)) {
this.command('toggle-editor', {id: this.env.composebody, html: !html_mode, noconvert: true});
}
}
};
// remove stored compose data from localStorage
this.remove_compose_data = function(key)
{
var index = this.local_storage_get_item('compose.index', []);
if ($.inArray(key, index) >= 0) {
this.local_storage_remove_item('compose.' + key);
this.local_storage_set_item('compose.index', $.grep(index, function(val,i) { return val != key; }));
}
};
// clear all stored compose data of this user
this.clear_compose_data = function()
{
var i, index = this.local_storage_get_item('compose.index', []);
for (i=0; i < index.length; i++) {
this.local_storage_remove_item('compose.' + index[i]);
}
this.local_storage_remove_item('compose.index');
};
this.change_identity = function(obj, show_sig)
{
if (!obj || !obj.options)
return false;
if (!show_sig)
show_sig = this.env.show_sig;
var id = obj.options[obj.selectedIndex].value,
sig = this.env.identity,
delim = this.env.recipients_separator,
rx_delim = RegExp.escape(delim);
// enable manual signature insert
if (this.env.signatures && this.env.signatures[id]) {
this.enable_command('insert-sig', true);
this.env.compose_commands.push('insert-sig');
}
else
this.enable_command('insert-sig', false);
// first function execution
if (!this.env.identities_initialized) {
this.env.identities_initialized = true;
if (this.env.show_sig_later)
this.env.show_sig = true;
if (this.env.opened_extwin)
return;
}
// update reply-to/bcc fields with addresses defined in identities
$.each(['replyto', 'bcc'], function() {
var rx, key = this,
old_val = sig && ref.env.identities[sig] ? ref.env.identities[sig][key] : '',
new_val = id && ref.env.identities[id] ? ref.env.identities[id][key] : '',
input = $('[name="_'+key+'"]'), input_val = input.val();
// remove old address(es)
if (old_val && input_val) {
rx = new RegExp('\\s*' + RegExp.escape(old_val) + '\\s*');
input_val = input_val.replace(rx, '');
}
// cleanup
rx = new RegExp(rx_delim + '\\s*' + rx_delim, 'g');
input_val = String(input_val).replace(rx, delim);
rx = new RegExp('^[\\s' + rx_delim + ']+');
input_val = input_val.replace(rx, '');
// add new address(es)
if (new_val && input_val.indexOf(new_val) == -1 && input_val.indexOf(new_val.replace(/"/g, '')) == -1) {
if (input_val) {
rx = new RegExp('[' + rx_delim + '\\s]+$')
input_val = input_val.replace(rx, '') + delim + ' ';
}
input_val += new_val + delim + ' ';
}
if (old_val || new_val)
input.val(input_val).change();
});
this.editor.change_signature(id, show_sig);
this.env.identity = id;
this.triggerEvent('change_identity');
return true;
};
// upload (attachment) file
this.upload_file = function(form, action, lock)
{
if (!form)
return;
// count files and size on capable browser
var size = 0, numfiles = 0;
$('input[type=file]', form).each(function(i, field) {
var files = field.files ? field.files.length : (field.value ? 1 : 0);
// check file size
if (field.files) {
for (var i=0; i < files; i++)
size += field.files[i].size;
}
numfiles += files;
});
// create hidden iframe and post upload form
if (numfiles) {
if (this.env.max_filesize && this.env.filesizeerror && size > this.env.max_filesize) {
this.display_message(this.env.filesizeerror, 'error');
return false;
}
var frame_name = this.async_upload_form(form, action || 'upload', function(e) {
var d, content = '';
try {
if (this.contentDocument) {
d = this.contentDocument;
} else if (this.contentWindow) {
d = this.contentWindow.document;
}
content = d.childNodes[1].innerHTML;
} catch (err) {}
if (!content.match(/add2attachment/) && (!bw.opera || (ref.env.uploadframe && ref.env.uploadframe == e.data.ts))) {
if (!content.match(/display_message/))
ref.display_message(ref.get_label('fileuploaderror'), 'error');
ref.remove_from_attachment_list(e.data.ts);
if (lock)
ref.set_busy(false, null, lock);
}
// Opera hack: handle double onload
if (bw.opera)
ref.env.uploadframe = e.data.ts;
});
// display upload indicator and cancel button
var content = '<span>' + this.get_label('uploading' + (numfiles > 1 ? 'many' : '')) + '</span>',
ts = frame_name.replace(/^rcmupload/, '');
this.add2attachment_list(ts, { name:'', html:content, classname:'uploading', frame:frame_name, complete:false });
// upload progress support
if (this.env.upload_progress_time) {
this.upload_progress_start('upload', ts);
}
// set reference to the form object
this.gui_objects.attachmentform = form;
return true;
}
};
// add file name to attachment list
// called from upload page
this.add2attachment_list = function(name, att, upload_id)
{
if (upload_id)
this.triggerEvent('fileuploaded', {name: name, attachment: att, id: upload_id});
if (!this.env.attachments)
this.env.attachments = {};
if (upload_id && this.env.attachments[upload_id])
delete this.env.attachments[upload_id];
this.env.attachments[name] = att;
if (!this.gui_objects.attachmentlist)
return false;
if (!att.complete && this.env.loadingicon)
att.html = '<img src="'+this.env.loadingicon+'" alt="" class="uploading" />' + att.html;
if (!att.complete && att.frame)
att.html = '<a title="'+this.get_label('cancel')+'" onclick="return rcmail.cancel_attachment_upload(\''+name+'\', \''+att.frame+'\');" href="#cancelupload" class="cancelupload">'
+ (this.env.cancelicon ? '<img src="'+this.env.cancelicon+'" alt="'+this.get_label('cancel')+'" />' : this.get_label('cancel')) + '</a>' + att.html;
var indicator, li = $('<li>');
li.attr('id', name)
.addClass(att.classname)
.html(att.html)
.on('mouseover', function() { rcube_webmail.long_subject_title_ex(this); });
// replace indicator's li
if (upload_id && (indicator = document.getElementById(upload_id))) {
li.replaceAll(indicator);
}
else { // add new li
li.appendTo(this.gui_objects.attachmentlist);
}
// set tabindex attribute
var tabindex = $(this.gui_objects.attachmentlist).attr('data-tabindex') || '0';
li.find('a').attr('tabindex', tabindex);
return true;
};
this.remove_from_attachment_list = function(name)
{
if (this.env.attachments) {
delete this.env.attachments[name];
$('#'+name).remove();
}
};
this.remove_attachment = function(name)
{
if (name && this.env.attachments[name])
this.http_post('remove-attachment', { _id:this.env.compose_id, _file:name });
return true;
};
this.cancel_attachment_upload = function(name, frame_name)
{
if (!name || !frame_name)
return false;
this.remove_from_attachment_list(name);
$("iframe[name='"+frame_name+"']").remove();
return false;
};
this.upload_progress_start = function(action, name)
{
setTimeout(function() { ref.http_request(action, {_progress: name}); },
this.env.upload_progress_time * 1000);
};
this.upload_progress_update = function(param)
{
var elem = $('#'+param.name + ' > span');
if (!elem.length || !param.text)
return;
elem.text(param.text);
if (!param.done)
this.upload_progress_start(param.action, param.name);
};
// send remote request to add a new contact
this.add_contact = function(value)
{
if (value)
this.http_post('addcontact', {_address: value});
return true;
};
// send remote request to search mail or contacts
this.qsearch = function(value)
{
if (value != '') {
var r, lock = this.set_busy(true, 'searching'),
url = this.search_params(value),
action = this.env.action == 'compose' && this.contact_list ? 'search-contacts' : 'search';
if (this.message_list)
this.clear_message_list();
else if (this.contact_list)
this.list_contacts_clear();
if (this.env.source)
url._source = this.env.source;
if (this.env.group)
url._gid = this.env.group;
// reset vars
this.env.current_page = 1;
r = this.http_request(action, url, lock);
this.env.qsearch = {lock: lock, request: r};
this.enable_command('set-listmode', this.env.threads && (this.env.search_scope || 'base') == 'base');
return true;
}
return false;
};
this.continue_search = function(request_id)
{
var lock = this.set_busy(true, 'stillsearching');
setTimeout(function() {
var url = ref.search_params();
url._continue = request_id;
ref.env.qsearch = { lock: lock, request: ref.http_request('search', url, lock) };
}, 100);
};
// build URL params for search
this.search_params = function(search, filter)
{
var n, url = {}, mods_arr = [],
mods = this.env.search_mods,
scope = this.env.search_scope || 'base',
mbox = scope == 'all' ? '*' : this.env.mailbox;
if (!filter && this.gui_objects.search_filter)
filter = this.gui_objects.search_filter.value;
if (!search && this.gui_objects.qsearchbox)
search = this.gui_objects.qsearchbox.value;
if (filter)
url._filter = filter;
if (this.gui_objects.search_interval)
url._interval = $(this.gui_objects.search_interval).val();
if (search) {
url._q = search;
if (mods && this.message_list)
mods = mods[mbox] || mods['*'];
if (mods) {
for (n in mods)
mods_arr.push(n);
url._headers = mods_arr.join(',');
}
}
if (scope)
url._scope = scope;
if (mbox && scope != 'all')
url._mbox = mbox;
return url;
};
// reset search filter
this.reset_search_filter = function()
{
this.filter_disabled = true;
if (this.gui_objects.search_filter)
$(this.gui_objects.search_filter).val('ALL').change();
this.filter_disabled = false;
};
// reset quick-search form
this.reset_qsearch = function(all)
{
if (this.gui_objects.qsearchbox)
this.gui_objects.qsearchbox.value = '';
if (this.gui_objects.search_interval)
$(this.gui_objects.search_interval).val('');
if (this.env.qsearch)
this.abort_request(this.env.qsearch);
if (all) {
this.env.search_scope = 'base';
this.reset_search_filter();
}
this.env.qsearch = null;
this.env.search_request = null;
this.env.search_id = null;
this.enable_command('set-listmode', this.env.threads);
};
this.set_searchscope = function(scope)
{
var old = this.env.search_scope;
this.env.search_scope = scope;
// re-send search query with new scope
if (scope != old && this.env.search_request) {
if (!this.qsearch(this.gui_objects.qsearchbox.value) && this.env.search_filter && this.env.search_filter != 'ALL')
this.filter_mailbox(this.env.search_filter);
if (scope != 'all')
this.select_folder(this.env.mailbox, '', true);
}
};
this.set_searchinterval = function(interval)
{
var old = this.env.search_interval;
this.env.search_interval = interval;
// re-send search query with new interval
if (interval != old && this.env.search_request) {
if (!this.qsearch(this.gui_objects.qsearchbox.value) && this.env.search_filter && this.env.search_filter != 'ALL')
this.filter_mailbox(this.env.search_filter);
if (interval)
this.select_folder(this.env.mailbox, '', true);
}
};
this.set_searchmods = function(mods)
{
var mbox = this.env.mailbox,
scope = this.env.search_scope || 'base';
if (scope == 'all')
mbox = '*';
if (!this.env.search_mods)
this.env.search_mods = {};
if (mbox)
this.env.search_mods[mbox] = mods;
};
this.is_multifolder_listing = function()
{
return this.env.multifolder_listing !== undefined ? this.env.multifolder_listing :
(this.env.search_request && (this.env.search_scope || 'base') != 'base');
};
// action executed after mail is sent
this.sent_successfully = function(type, msg, folders, save_error)
{
this.display_message(msg, type);
this.compose_skip_unsavedcheck = true;
if (this.env.extwin) {
if (!save_error)
this.lock_form(this.gui_objects.messageform);
var filter = {task: 'mail', action: ''},
rc = this.opener(false, filter) || this.opener(true, filter);
if (rc) {
rc.display_message(msg, type);
// refresh the folder where sent message was saved or replied message comes from
if (folders && $.inArray(rc.env.mailbox, folders) >= 0) {
rc.command('checkmail');
}
}
if (!save_error)
setTimeout(function() { window.close(); }, 1000);
}
else if (!save_error) {
// before redirect we need to wait some time for Chrome (#1486177)
setTimeout(function() { ref.list_mailbox(); }, 500);
}
if (save_error)
this.env.is_sent = true;
};
/*********************************************************/
/********* keyboard live-search methods *********/
/*********************************************************/
// handler for keyboard events on address-fields
this.ksearch_keydown = function(e, obj, props)
{
if (this.ksearch_timer)
clearTimeout(this.ksearch_timer);
var key = rcube_event.get_keycode(e),
mod = rcube_event.get_modifier(e);
switch (key) {
case 38: // arrow up
case 40: // arrow down
if (!this.ksearch_visible())
return;
var dir = key == 38 ? 1 : 0,
highlight = document.getElementById('rcmkSearchItem' + this.ksearch_selected);
if (!highlight)
highlight = this.ksearch_pane.__ul.firstChild;
if (highlight)
this.ksearch_select(dir ? highlight.previousSibling : highlight.nextSibling);
return rcube_event.cancel(e);
case 9: // tab
if (mod == SHIFT_KEY || !this.ksearch_visible()) {
this.ksearch_hide();
return;
}
case 13: // enter
if (!this.ksearch_visible())
return false;
// insert selected address and hide ksearch pane
this.insert_recipient(this.ksearch_selected);
this.ksearch_hide();
return rcube_event.cancel(e);
case 27: // escape
this.ksearch_hide();
return;
case 37: // left
case 39: // right
return;
}
// start timer
this.ksearch_timer = setTimeout(function(){ ref.ksearch_get_results(props); }, 200);
this.ksearch_input = obj;
return true;
};
this.ksearch_visible = function()
{
return this.ksearch_selected !== null && this.ksearch_selected !== undefined && this.ksearch_value;
};
this.ksearch_select = function(node)
{
if (this.ksearch_pane && node) {
this.ksearch_pane.find('li.selected').removeClass('selected').removeAttr('aria-selected');
}
if (node) {
$(node).addClass('selected').attr('aria-selected', 'true');
this.ksearch_selected = node._rcm_id;
$(this.ksearch_input).attr('aria-activedescendant', 'rcmkSearchItem' + this.ksearch_selected);
}
};
this.insert_recipient = function(id)
{
if (id === null || !this.env.contacts[id] || !this.ksearch_input)
return;
// get cursor pos
var inp_value = this.ksearch_input.value,
cpos = this.get_caret_pos(this.ksearch_input),
p = inp_value.lastIndexOf(this.ksearch_value, cpos),
trigger = false,
insert = '',
// replace search string with full address
pre = inp_value.substring(0, p),
end = inp_value.substring(p+this.ksearch_value.length, inp_value.length);
this.ksearch_destroy();
// insert all members of a group
if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].type == 'group' && !this.env.contacts[id].email) {
insert += this.env.contacts[id].name + this.env.recipients_delimiter;
this.group2expand[this.env.contacts[id].id] = $.extend({ input: this.ksearch_input }, this.env.contacts[id]);
this.http_request('mail/group-expand', {_source: this.env.contacts[id].source, _gid: this.env.contacts[id].id}, false);
}
else if (typeof this.env.contacts[id] === 'object' && this.env.contacts[id].name) {
insert = this.env.contacts[id].name + this.env.recipients_delimiter;
trigger = true;
}
else if (typeof this.env.contacts[id] === 'string') {
insert = this.env.contacts[id] + this.env.recipients_delimiter;
trigger = true;
}
this.ksearch_input.value = pre + insert + end;
// set caret to insert pos
this.set_caret_pos(this.ksearch_input, p + insert.length);
if (trigger) {
this.triggerEvent('autocomplete_insert', { field:this.ksearch_input, insert:insert, data:this.env.contacts[id] });
this.compose_type_activity++;
}
};
this.replace_group_recipients = function(id, recipients)
{
if (this.group2expand[id]) {
this.group2expand[id].input.value = this.group2expand[id].input.value.replace(this.group2expand[id].name, recipients);
this.triggerEvent('autocomplete_insert', { field:this.group2expand[id].input, insert:recipients });
this.group2expand[id] = null;
this.compose_type_activity++;
}
};
// address search processor
this.ksearch_get_results = function(props)
{
var inp_value = this.ksearch_input ? this.ksearch_input.value : null;
if (inp_value === null)
return;
if (this.ksearch_pane && this.ksearch_pane.is(":visible"))
this.ksearch_pane.hide();
// get string from current cursor pos to last comma
var cpos = this.get_caret_pos(this.ksearch_input),
p = inp_value.lastIndexOf(this.env.recipients_separator, cpos-1),
q = inp_value.substring(p+1, cpos),
min = this.env.autocomplete_min_length,
data = this.ksearch_data;
// trim query string
q = $.trim(q);
// Don't (re-)search if the last results are still active
if (q == this.ksearch_value)
return;
this.ksearch_destroy();
if (q.length && q.length < min) {
if (!this.ksearch_info) {
this.ksearch_info = this.display_message(
this.get_label('autocompletechars').replace('$min', min));
}
return;
}
var old_value = this.ksearch_value;
this.ksearch_value = q;
// ...string is empty
if (!q.length)
return;
// ...new search value contains old one and previous search was not finished or its result was empty
if (old_value && old_value.length && q.startsWith(old_value) && (!data || data.num <= 0) && this.env.contacts && !this.env.contacts.length)
return;
var sources = props && props.sources ? props.sources : [''];
var reqid = this.multi_thread_http_request({
items: sources,
threads: props && props.threads ? props.threads : 1,
action: props && props.action ? props.action : 'mail/autocomplete',
postdata: { _search:q, _source:'%s' },
lock: this.display_message(this.get_label('searching'), 'loading')
});
this.ksearch_data = { id:reqid, sources:sources.slice(), num:sources.length };
};
this.ksearch_query_results = function(results, search, reqid)
{
// trigger multi-thread http response callback
this.multi_thread_http_response(results, reqid);
// search stopped in meantime?
if (!this.ksearch_value)
return;
// ignore this outdated search response
if (this.ksearch_input && search != this.ksearch_value)
return;
// display search results
var i, id, len, ul, text, type, init,
value = this.ksearch_value,
maxlen = this.env.autocomplete_max ? this.env.autocomplete_max : 15;
// create results pane if not present
if (!this.ksearch_pane) {
ul = $('<ul>');
this.ksearch_pane = $('<div>').attr('id', 'rcmKSearchpane').attr('role', 'listbox')
.css({ position:'absolute', 'z-index':30000 }).append(ul).appendTo(document.body);
this.ksearch_pane.__ul = ul[0];
}
ul = this.ksearch_pane.__ul;
// remove all search results or add to existing list if parallel search
if (reqid && this.ksearch_pane.data('reqid') == reqid) {
maxlen -= ul.childNodes.length;
}
else {
this.ksearch_pane.data('reqid', reqid);
init = 1;
// reset content
ul.innerHTML = '';
this.env.contacts = [];
// move the results pane right under the input box
var pos = $(this.ksearch_input).offset();
this.ksearch_pane.css({ left:pos.left+'px', top:(pos.top + this.ksearch_input.offsetHeight)+'px', display: 'none'});
}
// add each result line to list
if (results && (len = results.length)) {
for (i=0; i < len && maxlen > 0; i++) {
text = typeof results[i] === 'object' ? (results[i].display || results[i].name) : results[i];
type = typeof results[i] === 'object' ? results[i].type : '';
id = i + this.env.contacts.length;
$('<li>').attr('id', 'rcmkSearchItem' + id)
.attr('role', 'option')
.html('<i class="icon"></i>' + this.quote_html(text.replace(new RegExp('('+RegExp.escape(value)+')', 'ig'), '##$1%%')).replace(/##([^%]+)%%/g, '<b>$1</b>'))
.addClass(type || '')
.appendTo(ul)
.mouseover(function() { ref.ksearch_select(this); })
.mouseup(function() { ref.ksearch_click(this); })
.get(0)._rcm_id = id;
maxlen -= 1;
}
}
if (ul.childNodes.length) {
// set the right aria-* attributes to the input field
$(this.ksearch_input)
.attr('aria-haspopup', 'true')
.attr('aria-expanded', 'true')
.attr('aria-owns', 'rcmKSearchpane');
this.ksearch_pane.show();
// select the first
if (!this.env.contacts.length) {
this.ksearch_select($('li:first', ul).get(0));
}
}
if (len)
this.env.contacts = this.env.contacts.concat(results);
if (this.ksearch_data.id == reqid)
this.ksearch_data.num--;
};
this.ksearch_click = function(node)
{
if (this.ksearch_input)
this.ksearch_input.focus();
this.insert_recipient(node._rcm_id);
this.ksearch_hide();
};
this.ksearch_blur = function()
{
if (this.ksearch_timer)
clearTimeout(this.ksearch_timer);
this.ksearch_input = null;
this.ksearch_hide();
};
this.ksearch_hide = function()
{
this.ksearch_selected = null;
this.ksearch_value = '';
if (this.ksearch_pane)
this.ksearch_pane.hide();
$(this.ksearch_input)
.attr('aria-haspopup', 'false')
.attr('aria-expanded', 'false')
.removeAttr('aria-activedescendant')
.removeAttr('aria-owns');
this.ksearch_destroy();
};
// Clears autocomplete data/requests
this.ksearch_destroy = function()
{
if (this.ksearch_data)
this.multi_thread_request_abort(this.ksearch_data.id);
if (this.ksearch_info)
this.hide_message(this.ksearch_info);
if (this.ksearch_msg)
this.hide_message(this.ksearch_msg);
this.ksearch_data = null;
this.ksearch_info = null;
this.ksearch_msg = null;
};
/*********************************************************/
/********* address book methods *********/
/*********************************************************/
this.contactlist_keypress = function(list)
{
if (list.key_pressed == list.DELETE_KEY)
this.command('delete');
};
this.contactlist_select = function(list)
{
if (this.preview_timer)
clearTimeout(this.preview_timer);
var n, id, sid, contact, writable = false,
selected = list.selection.length,
source = this.env.source ? this.env.address_sources[this.env.source] : null;
// we don't have dblclick handler here, so use 200 instead of this.dblclick_time
if (this.env.contentframe && (id = list.get_single_selection()))
this.preview_timer = setTimeout(function(){ ref.load_contact(id, 'show'); }, 200);
else if (this.env.contentframe)
this.show_contentframe(false);
if (selected) {
list.draggable = false;
// no source = search result, we'll need to detect if any of
// selected contacts are in writable addressbook to enable edit/delete
// we'll also need to know sources used in selection for copy
// and group-addmember operations (drag&drop)
this.env.selection_sources = [];
if (source) {
this.env.selection_sources.push(this.env.source);
}
for (n in list.selection) {
contact = list.data[list.selection[n]];
if (!source) {
sid = String(list.selection[n]).replace(/^[^-]+-/, '');
if (sid && this.env.address_sources[sid]) {
writable = writable || (!this.env.address_sources[sid].readonly && !contact.readonly);
this.env.selection_sources.push(sid);
}
}
else {
writable = writable || (!source.readonly && !contact.readonly);
}
if (contact._type != 'group')
list.draggable = true;
}
this.env.selection_sources = $.unique(this.env.selection_sources);
}
// if a group is currently selected, and there is at least one contact selected
// thend we can enable the group-remove-selected command
this.enable_command('group-remove-selected', this.env.group && selected && writable);
this.enable_command('compose', this.env.group || selected);
this.enable_command('print', selected == 1);
this.enable_command('export-selected', 'copy', selected > 0);
this.enable_command('edit', id && writable);
this.enable_command('delete', 'move', selected && writable);
return false;
};
this.list_contacts = function(src, group, page)
{
var win, folder, url = {},
refresh = src === undefined && group === undefined && page === undefined,
target = window;
if (!src)
src = this.env.source;
if (refresh)
group = this.env.group;
if (page && this.current_page == page && src == this.env.source && group == this.env.group)
return false;
if (src != this.env.source) {
page = this.env.current_page = 1;
this.reset_qsearch();
}
else if (!refresh && group != this.env.group)
page = this.env.current_page = 1;
if (this.env.search_id)
folder = 'S'+this.env.search_id;
else if (!this.env.search_request)
folder = group ? 'G'+src+group : src;
this.env.source = src;
this.env.group = group;
// truncate groups listing stack
var index = $.inArray(this.env.group, this.env.address_group_stack);
if (index < 0)
this.env.address_group_stack = [];
else
this.env.address_group_stack = this.env.address_group_stack.slice(0,index);
// make sure the current group is on top of the stack
if (this.env.group) {
this.env.address_group_stack.push(this.env.group);
// mark the first group on the stack as selected in the directory list
folder = 'G'+src+this.env.address_group_stack[0];
}
else if (this.gui_objects.addresslist_title) {
$(this.gui_objects.addresslist_title).html(this.get_label('contacts'));
}
if (!this.env.search_id)
this.select_folder(folder, '', true);
// load contacts remotely
if (this.gui_objects.contactslist) {
this.list_contacts_remote(src, group, page);
return;
}
if (win = this.get_frame_window(this.env.contentframe)) {
target = win;
url._framed = 1;
}
if (group)
url._gid = group;
if (page)
url._page = page;
if (src)
url._source = src;
// also send search request to get the correct listing
if (this.env.search_request)
url._search = this.env.search_request;
this.set_busy(true, 'loading');
this.location_href(url, target);
};
// send remote request to load contacts list
this.list_contacts_remote = function(src, group, page)
{
// clear message list first
this.list_contacts_clear();
// send request to server
var url = {}, lock = this.set_busy(true, 'loading');
if (src)
url._source = src;
if (page)
url._page = page;
if (group)
url._gid = group;
this.env.source = src;
this.env.group = group;
// also send search request to get the right records
if (this.env.search_request)
url._search = this.env.search_request;
this.http_request(this.env.task == 'mail' ? 'list-contacts' : 'list', url, lock);
};
this.list_contacts_clear = function()
{
this.contact_list.data = {};
this.contact_list.clear(true);
this.show_contentframe(false);
this.enable_command('delete', 'move', 'copy', 'print', false);
this.enable_command('compose', this.env.group);
};
this.set_group_prop = function(prop)
{
if (this.gui_objects.addresslist_title) {
var boxtitle = $(this.gui_objects.addresslist_title).html(''); // clear contents
// add link to pop back to parent group
if (this.env.address_group_stack.length > 1) {
$('<a href="#list">...</a>')
.attr('title', this.get_label('uponelevel'))
.addClass('poplink')
.appendTo(boxtitle)
.click(function(e){ return ref.command('popgroup','',this); });
boxtitle.append(' » ');
}
boxtitle.append($('<span>').text(prop.name));
}
this.triggerEvent('groupupdate', prop);
};
// load contact record
this.load_contact = function(cid, action, framed)
{
var win, url = {}, target = window,
rec = this.contact_list ? this.contact_list.data[cid] : null;
if (win = this.get_frame_window(this.env.contentframe)) {
url._framed = 1;
target = win;
this.show_contentframe(true);
// load dummy content, unselect selected row(s)
if (!cid)
this.contact_list.clear_selection();
this.enable_command('compose', rec && rec.email);
this.enable_command('export-selected', 'print', rec && rec._type != 'group');
}
else if (framed)
return false;
if (action && (cid || action == 'add') && !this.drag_active) {
if (this.env.group)
url._gid = this.env.group;
if (this.env.search_request)
url._search = this.env.search_request;
url._action = action;
url._source = this.env.source;
url._cid = cid;
this.location_href(url, target, true);
}
return true;
};
// add/delete member to/from the group
this.group_member_change = function(what, cid, source, gid)
{
if (what != 'add')
what = 'del';
var label = this.get_label(what == 'add' ? 'addingmember' : 'removingmember'),
lock = this.display_message(label, 'loading'),
post_data = {_cid: cid, _source: source, _gid: gid};
this.http_post('group-'+what+'members', post_data, lock);
};
this.contacts_drag_menu = function(e, to)
{
var dest = to.type == 'group' ? to.source : to.id,
source = this.env.source;
if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
return true;
// search result may contain contacts from many sources, but if there is only one...
if (source == '' && this.env.selection_sources.length == 1)
source = this.env.selection_sources[0];
if (to.type == 'group' && dest == source) {
var cid = this.contact_list.get_selection().join(',');
this.group_member_change('add', cid, dest, to.id);
return true;
}
// move action is not possible, "redirect" to copy if menu wasn't requested
else if (!this.commands.move && rcube_event.get_modifier(e) != SHIFT_KEY) {
this.copy_contacts(to);
return true;
}
return this.drag_menu(e, to);
};
// copy contact(s) to the specified target (group or directory)
this.copy_contacts = function(to)
{
var dest = to.type == 'group' ? to.source : to.id,
source = this.env.source,
group = this.env.group ? this.env.group : '',
cid = this.contact_list.get_selection().join(',');
if (!cid || !this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
return;
// search result may contain contacts from many sources, but if there is only one...
if (source == '' && this.env.selection_sources.length == 1)
source = this.env.selection_sources[0];
// tagret is a group
if (to.type == 'group') {
if (dest == source)
return;
var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
post_data = {_cid: cid, _source: this.env.source, _to: dest, _togid: to.id, _gid: group};
this.http_post('copy', post_data, lock);
}
// target is an addressbook
else if (to.id != source) {
var lock = this.display_message(this.get_label('copyingcontact'), 'loading'),
post_data = {_cid: cid, _source: this.env.source, _to: to.id, _gid: group};
this.http_post('copy', post_data, lock);
}
};
// move contact(s) to the specified target (group or directory)
this.move_contacts = function(to)
{
var dest = to.type == 'group' ? to.source : to.id,
source = this.env.source,
group = this.env.group ? this.env.group : '';
if (!this.env.address_sources[dest] || this.env.address_sources[dest].readonly)
return;
// search result may contain contacts from many sources, but if there is only one...
if (source == '' && this.env.selection_sources.length == 1)
source = this.env.selection_sources[0];
if (to.type == 'group') {
if (dest == source)
return;
this._with_selected_contacts('move', {_to: dest, _togid: to.id});
}
// target is an addressbook
else if (to.id != source)
this._with_selected_contacts('move', {_to: to.id});
};
// delete contact(s)
this.delete_contacts = function()
{
var undelete = this.env.source && this.env.address_sources[this.env.source].undelete;
if (!undelete && !confirm(this.get_label('deletecontactconfirm')))
return;
return this._with_selected_contacts('delete');
};
this._with_selected_contacts = function(action, post_data)
{
var selection = this.contact_list ? this.contact_list.get_selection() : [];
// exit if no contact specified or if selection is empty
if (!selection.length && !this.env.cid)
return;
var n, a_cids = [],
label = action == 'delete' ? 'contactdeleting' : 'movingcontact',
lock = this.display_message(this.get_label(label), 'loading');
if (this.env.cid)
a_cids.push(this.env.cid);
else {
for (n=0; n<selection.length; n++) {
id = selection[n];
a_cids.push(id);
this.contact_list.remove_row(id, (n == selection.length-1));
}
// hide content frame if we delete the currently displayed contact
if (selection.length == 1)
this.show_contentframe(false);
}
if (!post_data)
post_data = {};
post_data._source = this.env.source;
post_data._from = this.env.action;
post_data._cid = a_cids.join(',');
if (this.env.group)
post_data._gid = this.env.group;
// also send search request to get the right records from the next page
if (this.env.search_request)
post_data._search = this.env.search_request;
// send request to server
this.http_post(action, post_data, lock)
return true;
};
// update a contact record in the list
this.update_contact_row = function(cid, cols_arr, newcid, source, data)
{
var list = this.contact_list;
cid = this.html_identifier(cid);
// when in searching mode, concat cid with the source name
if (!list.rows[cid]) {
cid = cid + '-' + source;
if (newcid)
newcid = newcid + '-' + source;
}
list.update_row(cid, cols_arr, newcid, true);
list.data[cid] = data;
};
// add row to contacts list
this.add_contact_row = function(cid, cols, classes, data)
{
if (!this.gui_objects.contactslist)
return false;
var c, col, list = this.contact_list,
row = { cols:[] };
row.id = 'rcmrow' + this.html_identifier(cid);
row.className = 'contact ' + (classes || '');
if (list.in_selection(cid))
row.className += ' selected';
// add each submitted col
for (c in cols) {
col = {};
col.className = String(c).toLowerCase();
col.innerHTML = cols[c];
row.cols.push(col);
}
// store data in list member
list.data[cid] = data;
list.insert_row(row);
this.enable_command('export', list.rowcount > 0);
};
this.init_contact_form = function()
{
var col;
if (this.env.coltypes) {
this.set_photo_actions($('#ff_photo').val());
for (col in this.env.coltypes)
this.init_edit_field(col, null);
}
$('.contactfieldgroup .row a.deletebutton').click(function() {
ref.delete_edit_field(this);
return false;
});
$('select.addfieldmenu').change(function() {
ref.insert_edit_field($(this).val(), $(this).attr('rel'), this);
this.selectedIndex = 0;
});
// enable date pickers on date fields
if ($.datepicker && this.env.date_format) {
$.datepicker.setDefaults({
dateFormat: this.env.date_format,
changeMonth: true,
changeYear: true,
yearRange: '-120:+10',
showOtherMonths: true,
selectOtherMonths: true
// onSelect: function(dateText) { $(this).focus().val(dateText); }
});
$('input.datepicker').datepicker();
}
// Submit search form on Enter
if (this.env.action == 'search')
$(this.gui_objects.editform).append($('<input type="submit">').hide())
.submit(function() { $('input.mainaction').click(); return false; });
};
// group creation dialog
this.group_create = function()
{
var input = $('<input>').attr('type', 'text'),
content = $('<label>').text(this.get_label('namex')).append(input);
this.show_popup_dialog(content, this.get_label('newgroup'),
[{
text: this.get_label('save'),
'class': 'mainaction',
click: function() {
var name;
if (name = input.val()) {
ref.http_post('group-create', {_source: ref.env.source, _name: name},
ref.set_busy(true, 'loading'));
}
$(this).dialog('close');
}
}]
);
};
// group rename dialog
this.group_rename = function()
{
if (!this.env.group)
return;
var group_name = this.env.contactgroups['G' + this.env.source + this.env.group].name,
input = $('<input>').attr('type', 'text').val(group_name),
content = $('<label>').text(this.get_label('namex')).append(input);
this.show_popup_dialog(content, this.get_label('grouprename'),
[{
text: this.get_label('save'),
'class': 'mainaction',
click: function() {
var name;
if ((name = input.val()) && name != group_name) {
ref.http_post('group-rename', {_source: ref.env.source, _gid: ref.env.group, _name: name},
ref.set_busy(true, 'loading'));
}
$(this).dialog('close');
}
}],
{open: function() { input.select(); }}
);
};
this.group_delete = function()
{
if (this.env.group && confirm(this.get_label('deletegroupconfirm'))) {
var lock = this.set_busy(true, 'groupdeleting');
this.http_post('group-delete', {_source: this.env.source, _gid: this.env.group}, lock);
}
};
// callback from server upon group-delete command
this.remove_group_item = function(prop)
{
var key = 'G'+prop.source+prop.id;
if (this.treelist.remove(key)) {
this.triggerEvent('group_delete', { source:prop.source, id:prop.id });
delete this.env.contactfolders[key];
delete this.env.contactgroups[key];
}
this.list_contacts(prop.source, 0);
};
//remove selected contacts from current active group
this.group_remove_selected = function()
{
this.http_post('group-delmembers', {_cid: this.contact_list.selection,
_source: this.env.source, _gid: this.env.group});
};
//callback after deleting contact(s) from current group
this.remove_group_contacts = function(props)
{
if (this.env.group !== undefined && (this.env.group === props.gid)) {
var n, selection = this.contact_list.get_selection();
for (n=0; n<selection.length; n++) {
id = selection[n];
this.contact_list.remove_row(id, (n == selection.length-1));
}
}
};
// callback for creating a new contact group
this.insert_contact_group = function(prop)
{
prop.type = 'group';
var key = 'G'+prop.source+prop.id,
link = $('<a>').attr('href', '#')
.attr('rel', prop.source+':'+prop.id)
.click(function() { return ref.command('listgroup', prop, this); })
.html(prop.name);
this.env.contactfolders[key] = this.env.contactgroups[key] = prop;
this.treelist.insert({ id:key, html:link, classes:['contactgroup'] }, prop.source, 'contactgroup');
this.triggerEvent('group_insert', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key) });
};
// callback for renaming a contact group
this.update_contact_group = function(prop)
{
var key = 'G'+prop.source+prop.id,
newnode = {};
// group ID has changed, replace link node and identifiers
if (prop.newid) {
var newkey = 'G'+prop.source+prop.newid,
newprop = $.extend({}, prop);
this.env.contactfolders[newkey] = this.env.contactfolders[key];
this.env.contactfolders[newkey].id = prop.newid;
this.env.group = prop.newid;
delete this.env.contactfolders[key];
delete this.env.contactgroups[key];
newprop.id = prop.newid;
newprop.type = 'group';
newnode.id = newkey;
newnode.html = $('<a>').attr('href', '#')
.attr('rel', prop.source+':'+prop.newid)
.click(function() { return ref.command('listgroup', newprop, this); })
.html(prop.name);
}
// update displayed group name
else {
$(this.treelist.get_item(key)).children().first().html(prop.name);
this.env.contactfolders[key].name = this.env.contactgroups[key].name = prop.name;
}
// update list node and re-sort it
this.treelist.update(key, newnode, true);
this.triggerEvent('group_update', { id:prop.id, source:prop.source, name:prop.name, li:this.treelist.get_item(key), newid:prop.newid });
};
this.update_group_commands = function()
{
var source = this.env.source != '' ? this.env.address_sources[this.env.source] : null,
supported = source && source.groups && !source.readonly;
this.enable_command('group-create', supported);
this.enable_command('group-rename', 'group-delete', supported && this.env.group);
};
this.init_edit_field = function(col, elem)
{
var label = this.env.coltypes[col].label;
if (!elem)
elem = $('.ff_' + col);
if (label)
elem.placeholder(label);
};
this.insert_edit_field = function(col, section, menu)
{
// just make pre-defined input field visible
var elem = $('#ff_'+col);
if (elem.length) {
elem.show().focus();
$(menu).children('option[value="'+col+'"]').prop('disabled', true);
}
else {
var lastelem = $('.ff_'+col),
appendcontainer = $('#contactsection'+section+' .contactcontroller'+col);
if (!appendcontainer.length) {
var sect = $('#contactsection'+section),
lastgroup = $('.contactfieldgroup', sect).last();
appendcontainer = $('<fieldset>').addClass('contactfieldgroup contactcontroller'+col);
if (lastgroup.length)
appendcontainer.insertAfter(lastgroup);
else
sect.prepend(appendcontainer);
}
if (appendcontainer.length && appendcontainer.get(0).nodeName == 'FIELDSET') {
var input, colprop = this.env.coltypes[col],
input_id = 'ff_' + col + (colprop.count || 0),
row = $('<div>').addClass('row'),
cell = $('<div>').addClass('contactfieldcontent data'),
label = $('<div>').addClass('contactfieldlabel label');
if (colprop.subtypes_select)
label.html(colprop.subtypes_select);
else
label.html('<label for="' + input_id + '">' + colprop.label + '</label>');
var name_suffix = colprop.limit != 1 ? '[]' : '';
if (colprop.type == 'text' || colprop.type == 'date') {
input = $('<input>')
.addClass('ff_'+col)
.attr({type: 'text', name: '_'+col+name_suffix, size: colprop.size, id: input_id})
.appendTo(cell);
this.init_edit_field(col, input);
if (colprop.type == 'date' && $.datepicker)
input.datepicker();
}
else if (colprop.type == 'textarea') {
input = $('<textarea>')
.addClass('ff_'+col)
.attr({ name: '_'+col+name_suffix, cols:colprop.size, rows:colprop.rows, id: input_id })
.appendTo(cell);
this.init_edit_field(col, input);
}
else if (colprop.type == 'composite') {
var i, childcol, cp, first, templ, cols = [], suffices = [];
// read template for composite field order
if ((templ = this.env[col+'_template'])) {
for (i=0; i < templ.length; i++) {
cols.push(templ[i][1]);
suffices.push(templ[i][2]);
}
}
else { // list fields according to appearance in colprop
for (childcol in colprop.childs)
cols.push(childcol);
}
for (i=0; i < cols.length; i++) {
childcol = cols[i];
cp = colprop.childs[childcol];
input = $('<input>')
.addClass('ff_'+childcol)
.attr({ type: 'text', name: '_'+childcol+name_suffix, size: cp.size })
.appendTo(cell);
cell.append(suffices[i] || " ");
this.init_edit_field(childcol, input);
if (!first) first = input;
}
input = first; // set focus to the first of this composite fields
}
else if (colprop.type == 'select') {
input = $('<select>')
.addClass('ff_'+col)
.attr({ 'name': '_'+col+name_suffix, id: input_id })
.appendTo(cell);
var options = input.attr('options');
options[options.length] = new Option('---', '');
if (colprop.options)
$.each(colprop.options, function(i, val){ options[options.length] = new Option(val, i); });
}
if (input) {
var delbutton = $('<a href="#del"></a>')
.addClass('contactfieldbutton deletebutton')
.attr({title: this.get_label('delete'), rel: col})
.html(this.env.delbutton)
.click(function(){ ref.delete_edit_field(this); return false })
.appendTo(cell);
row.append(label).append(cell).appendTo(appendcontainer.show());
input.first().focus();
// disable option if limit reached
if (!colprop.count) colprop.count = 0;
if (++colprop.count == colprop.limit && colprop.limit)
$(menu).children('option[value="'+col+'"]').prop('disabled', true);
}
}
}
};
this.delete_edit_field = function(elem)
{
var col = $(elem).attr('rel'),
colprop = this.env.coltypes[col],
fieldset = $(elem).parents('fieldset.contactfieldgroup'),
addmenu = fieldset.parent().find('select.addfieldmenu');
// just clear input but don't hide the last field
if (--colprop.count <= 0 && colprop.visible)
$(elem).parent().children('input').val('').blur();
else {
$(elem).parents('div.row').remove();
// hide entire fieldset if no more rows
if (!fieldset.children('div.row').length)
fieldset.hide();
}
// enable option in add-field selector or insert it if necessary
if (addmenu.length) {
var option = addmenu.children('option[value="'+col+'"]');
if (option.length)
option.prop('disabled', false);
else
option = $('<option>').attr('value', col).html(colprop.label).appendTo(addmenu);
addmenu.show();
}
};
this.upload_contact_photo = function(form)
{
if (form && form.elements._photo.value) {
this.async_upload_form(form, 'upload-photo', function(e) {
ref.set_busy(false, null, ref.file_upload_id);
});
// display upload indicator
this.file_upload_id = this.set_busy(true, 'uploading');
}
};
this.replace_contact_photo = function(id)
{
var img_src = id == '-del-' ? this.env.photo_placeholder :
this.env.comm_path + '&_action=photo&_source=' + this.env.source + '&_cid=' + (this.env.cid || 0) + '&_photo=' + id;
this.set_photo_actions(id);
$(this.gui_objects.contactphoto).children('img').attr('src', img_src);
};
this.photo_upload_end = function()
{
this.set_busy(false, null, this.file_upload_id);
delete this.file_upload_id;
};
this.set_photo_actions = function(id)
{
var n, buttons = this.buttons['upload-photo'];
for (n=0; buttons && n < buttons.length; n++)
$('a#'+buttons[n].id).html(this.get_label(id == '-del-' ? 'addphoto' : 'replacephoto'));
$('#ff_photo').val(id);
this.enable_command('upload-photo', this.env.coltypes.photo ? true : false);
this.enable_command('delete-photo', this.env.coltypes.photo && id != '-del-');
};
// load advanced search page
this.advanced_search = function()
{
var win, url = {_form: 1, _action: 'search'}, target = window;
if (win = this.get_frame_window(this.env.contentframe)) {
url._framed = 1;
target = win;
this.contact_list.clear_selection();
}
this.location_href(url, target, true);
return true;
};
// unselect directory/group
this.unselect_directory = function()
{
this.select_folder('');
this.enable_command('search-delete', false);
};
// callback for creating a new saved search record
this.insert_saved_search = function(name, id)
{
var key = 'S'+id,
link = $('<a>').attr('href', '#')
.attr('rel', id)
.click(function() { return ref.command('listsearch', id, this); })
.html(name),
prop = { name:name, id:id };
this.savedsearchlist.insert({ id:key, html:link, classes:['contactsearch'] }, null, 'contactsearch');
this.select_folder(key,'',true);
this.enable_command('search-delete', true);
this.env.search_id = id;
this.triggerEvent('abook_search_insert', prop);
};
// creates a dialog for saved search
this.search_create = function()
{
var input = $('<input>').attr('type', 'text'),
content = $('<label>').text(this.get_label('namex')).append(input);
this.show_popup_dialog(content, this.get_label('searchsave'),
[{
text: this.get_label('save'),
'class': 'mainaction',
click: function() {
var name;
if (name = input.val()) {
ref.http_post('search-create', {_search: ref.env.search_request, _name: name},
ref.set_busy(true, 'loading'));
}
$(this).dialog('close');
}
}]
);
};
this.search_delete = function()
{
if (this.env.search_request) {
var lock = this.set_busy(true, 'savedsearchdeleting');
this.http_post('search-delete', {_sid: this.env.search_id}, lock);
}
};
// callback from server upon search-delete command
this.remove_search_item = function(id)
{
var li, key = 'S'+id;
if (this.savedsearchlist.remove(key)) {
this.triggerEvent('search_delete', { id:id, li:li });
}
this.env.search_id = null;
this.env.search_request = null;
this.list_contacts_clear();
this.reset_qsearch();
this.enable_command('search-delete', 'search-create', false);
};
this.listsearch = function(id)
{
var lock = this.set_busy(true, 'searching');
if (this.contact_list) {
this.list_contacts_clear();
}
this.reset_qsearch();
if (this.savedsearchlist) {
this.treelist.select('');
this.savedsearchlist.select('S'+id);
}
else
this.select_folder('S'+id, '', true);
// reset vars
this.env.current_page = 1;
this.http_request('search', {_sid: id}, lock);
};
/*********************************************************/
/********* user settings methods *********/
/*********************************************************/
// preferences section select and load options frame
this.section_select = function(list)
{
var win, id = list.get_single_selection(), target = window,
url = {_action: 'edit-prefs', _section: id};
if (id) {
if (win = this.get_frame_window(this.env.contentframe)) {
url._framed = 1;
target = win;
}
this.location_href(url, target, true);
}
return true;
};
this.identity_select = function(list)
{
var id;
if (id = list.get_single_selection()) {
this.enable_command('delete', list.rowcount > 1 && this.env.identities_level < 2);
this.load_identity(id, 'edit-identity');
}
};
// load identity record
this.load_identity = function(id, action)
{
if (action == 'edit-identity' && (!id || id == this.env.iid))
return false;
var win, target = window,
url = {_action: action, _iid: id};
if (win = this.get_frame_window(this.env.contentframe)) {
url._framed = 1;
target = win;
}
if (id || action == 'add-identity') {
this.location_href(url, target, true);
}
return true;
};
this.delete_identity = function(id)
{
// exit if no identity is specified or if selection is empty
var selection = this.identity_list.get_selection();
if (!(selection.length || this.env.iid))
return;
if (!id)
id = this.env.iid ? this.env.iid : selection[0];
// submit request with appended token
if (id && confirm(this.get_label('deleteidentityconfirm')))
this.http_post('settings/delete-identity', { _iid: id }, true);
};
this.update_identity_row = function(id, name, add)
{
var list = this.identity_list,
rid = this.html_identifier(id);
if (add) {
list.insert_row({ id:'rcmrow'+rid, cols:[ { className:'mail', innerHTML:name } ] });
list.select(rid);
}
else {
list.update_row(rid, [ name ]);
}
};
this.update_response_row = function(response, oldkey)
{
var list = this.responses_list;
if (list && oldkey) {
list.update_row(oldkey, [ response.name ], response.key, true);
}
else if (list) {
list.insert_row({ id:'rcmrow'+response.key, cols:[ { className:'name', innerHTML:response.name } ] });
list.select(response.key);
}
};
this.remove_response = function(key)
{
var frame;
if (this.env.textresponses) {
delete this.env.textresponses[key];
}
if (this.responses_list) {
this.responses_list.remove_row(key);
if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
frame.location.href = this.env.blankpage;
}
}
this.enable_command('delete', false);
};
this.remove_identity = function(id)
{
var frame, list = this.identity_list,
rid = this.html_identifier(id);
if (list && id) {
list.remove_row(rid);
if (this.env.contentframe && (frame = this.get_frame_window(this.env.contentframe))) {
frame.location.href = this.env.blankpage;
}
}
this.enable_command('delete', false);
};
/*********************************************************/
/********* folder manager methods *********/
/*********************************************************/
this.init_subscription_list = function()
{
var delim = RegExp.escape(this.env.delimiter);
this.last_sub_rx = RegExp('['+delim+']?[^'+delim+']+$');
this.subscription_list = new rcube_treelist_widget(this.gui_objects.subscriptionlist, {
selectable: true,
tabexit: false,
parent_focus: true,
id_prefix: 'rcmli',
id_encode: this.html_identifier_encode,
id_decode: this.html_identifier_decode,
searchbox: '#foldersearch'
});
this.subscription_list
.addEventListener('select', function(node) { ref.subscription_select(node.id); })
.addEventListener('collapse', function(node) { ref.folder_collapsed(node) })
.addEventListener('expand', function(node) { ref.folder_collapsed(node) })
.addEventListener('search', function(p) { if (p.query) ref.subscription_select(); })
.draggable({cancel: 'li.mailbox.root'})
.droppable({
// @todo: find better way, accept callback is executed for every folder
// on the list when dragging starts (and stops), this is slow, but
// I didn't find a method to check droptarget on over event
accept: function(node) {
if (!$(node).is('.mailbox'))
return false;
var source_folder = ref.folder_id2name($(node).attr('id')),
dest_folder = ref.folder_id2name(this.id),
source = ref.env.subscriptionrows[source_folder],
dest = ref.env.subscriptionrows[dest_folder];
return source && !source[2]
&& dest_folder != source_folder.replace(ref.last_sub_rx, '')
&& !dest_folder.startsWith(source_folder + ref.env.delimiter);
},
drop: function(e, ui) {
var source = ref.folder_id2name(ui.draggable.attr('id')),
dest = ref.folder_id2name(this.id);
ref.subscription_move_folder(source, dest);
}
});
};
this.folder_id2name = function(id)
{
return id ? ref.html_identifier_decode(id.replace(/^rcmli/, '')) : null;
};
this.subscription_select = function(id)
{
var folder;
if (id && id != '*' && (folder = this.env.subscriptionrows[id])) {
this.env.mailbox = id;
this.show_folder(id);
this.enable_command('delete-folder', !folder[2]);
}
else {
this.env.mailbox = null;
this.show_contentframe(false);
this.enable_command('delete-folder', 'purge', false);
}
};
this.subscription_move_folder = function(from, to)
{
if (from && to !== null && from != to && to != from.replace(this.last_sub_rx, '')) {
var path = from.split(this.env.delimiter),
basename = path.pop(),
newname = to === '' || to === '*' ? basename : to + this.env.delimiter + basename;
if (newname != from) {
this.http_post('rename-folder', {_folder_oldname: from, _folder_newname: newname},
this.set_busy(true, 'foldermoving'));
}
}
};
// tell server to create and subscribe a new mailbox
this.create_folder = function()
{
this.show_folder('', this.env.mailbox);
};
// delete a specific mailbox with all its messages
this.delete_folder = function(name)
{
if (!name)
name = this.env.mailbox;
if (name && confirm(this.get_label('deletefolderconfirm'))) {
this.http_post('delete-folder', {_mbox: name}, this.set_busy(true, 'folderdeleting'));
}
};
// Add folder row to the table and initialize it
this.add_folder_row = function (id, name, display_name, is_protected, subscribed, class_name, refrow, subfolders)
{
if (!this.gui_objects.subscriptionlist)
return false;
// reset searching
if (this.subscription_list.is_search()) {
this.subscription_select();
this.subscription_list.reset_search();
}
// disable drag-n-drop temporarily
this.subscription_list.draggable('destroy').droppable('destroy');
var row, n, tmp, tmp_name, rowid, collator, pos, p, parent = '',
folders = [], list = [], slist = [],
list_element = $(this.gui_objects.subscriptionlist);
row = refrow ? refrow : $($('li', list_element).get(1)).clone(true);
if (!row.length) {
// Refresh page if we don't have a table row to clone
this.goto_url('folders');
return false;
}
// set ID, reset css class
row.attr({id: 'rcmli' + this.html_identifier_encode(id), 'class': class_name});
if (!refrow || !refrow.length) {
// remove old data, subfolders and toggle
$('ul,div.treetoggle', row).remove();
row.removeData('filtered');
}
// set folder name
$('a:first', row).text(display_name);
// update subscription checkbox
$('input[name="_subscribed[]"]:first', row).val(id)
.prop({checked: subscribed ? true : false, disabled: is_protected ? true : false});
// add to folder/row-ID map
this.env.subscriptionrows[id] = [name, display_name, false];
// copy folders data to an array for sorting
$.each(this.env.subscriptionrows, function(k, v) { v[3] = k; folders.push(v); });
try {
// use collator if supported (FF29, IE11, Opera15, Chrome24)
collator = new Intl.Collator(this.env.locale.replace('_', '-'));
}
catch (e) {};
// sort folders
folders.sort(function(a, b) {
var i, f1, f2,
path1 = a[0].split(ref.env.delimiter),
path2 = b[0].split(ref.env.delimiter),
len = path1.length;
for (i=0; i<len; i++) {
f1 = path1[i];
f2 = path2[i];
if (f1 !== f2) {
if (f2 === undefined)
return 1;
if (collator)
return collator.compare(f1, f2);
else
return f1 < f2 ? -1 : 1;
}
else if (i == len-1) {
return -1
}
}
});
for (n in folders) {
p = folders[n][3];
// protected folder
if (folders[n][2]) {
tmp_name = p + this.env.delimiter;
// prefix namespace cannot have subfolders (#1488349)
if (tmp_name == this.env.prefix_ns)
continue;
slist.push(p);
tmp = tmp_name;
}
// protected folder's child
else if (tmp && p.startsWith(tmp))
slist.push(p);
// other
else {
list.push(p);
tmp = null;
}
}
// check if subfolder of a protected folder
for (n=0; n<slist.length; n++) {
if (id.startsWith(slist[n] + this.env.delimiter))
rowid = slist[n];
}
// find folder position after sorting
for (n=0; !rowid && n<list.length; n++) {
if (n && list[n] == id)
rowid = list[n-1];
}
// add row to the table
if (rowid && (n = this.subscription_list.get_item(rowid, true))) {
// find parent folder
if (pos = id.lastIndexOf(this.env.delimiter)) {
parent = id.substring(0, pos);
parent = this.subscription_list.get_item(parent, true);
// add required tree elements to the parent if not already there
if (!$('div.treetoggle', parent).length) {
$('<div> </div>').addClass('treetoggle collapsed').appendTo(parent);
}
if (!$('ul', parent).length) {
$('<ul>').css('display', 'none').appendTo(parent);
}
}
if (parent && n == parent) {
$('ul:first', parent).append(row);
}
else {
while (p = $(n).parent().parent().get(0)) {
if (parent && p == parent)
break;
if (!$(p).is('li.mailbox'))
break;
n = p;
}
$(n).after(row);
}
}
else {
list_element.append(row);
}
// add subfolders
$.extend(this.env.subscriptionrows, subfolders || {});
// update list widget
this.subscription_list.reset(true);
this.subscription_select();
// expand parent
if (parent) {
this.subscription_list.expand(this.folder_id2name(parent.id));
}
row = row.show().get(0);
if (row.scrollIntoView)
row.scrollIntoView();
return row;
};
// replace an existing table row with a new folder line (with subfolders)
this.replace_folder_row = function(oldid, id, name, display_name, is_protected, class_name)
{
if (!this.gui_objects.subscriptionlist) {
if (this.is_framed()) {
// @FIXME: for some reason this 'parent' variable need to be prefixed with 'window.'
return window.parent.rcmail.replace_folder_row(oldid, id, name, display_name, is_protected, class_name);
}
return false;
}
// reset searching
if (this.subscription_list.is_search()) {
this.subscription_select();
this.subscription_list.reset_search();
}
var subfolders = {},
row = this.subscription_list.get_item(oldid, true),
parent = $(row).parent(),
old_folder = this.env.subscriptionrows[oldid],
prefix_len_id = oldid.length,
prefix_len_name = old_folder[0].length,
subscribed = $('input[name="_subscribed[]"]:first', row).prop('checked');
// no renaming, only update class_name
if (oldid == id) {
$(row).attr('class', class_name || '');
return;
}
// update subfolders
$('li', row).each(function() {
var fname = ref.folder_id2name(this.id),
folder = ref.env.subscriptionrows[fname],
newid = id + fname.slice(prefix_len_id);
this.id = 'rcmli' + ref.html_identifier_encode(newid);
$('input[name="_subscribed[]"]:first', this).val(newid);
folder[0] = name + folder[0].slice(prefix_len_name);
subfolders[newid] = folder;
delete ref.env.subscriptionrows[fname];
});
// get row off the list
row = $(row).detach();
delete this.env.subscriptionrows[oldid];
// remove parent list/toggle elements if not needed
if (parent.get(0) != this.gui_objects.subscriptionlist && !$('li', parent).length) {
$('ul,div.treetoggle', parent.parent()).remove();
}
// move the existing table row
this.add_folder_row(id, name, display_name, is_protected, subscribed, class_name, row, subfolders);
};
// remove the table row of a specific mailbox from the table
this.remove_folder_row = function(folder)
{
// reset searching
if (this.subscription_list.is_search()) {
this.subscription_select();
this.subscription_list.reset_search();
}
var list = [], row = this.subscription_list.get_item(folder, true);
// get subfolders if any
$('li', row).each(function() { list.push(ref.folder_id2name(this.id)); });
// remove folder row (and subfolders)
this.subscription_list.remove(folder);
// update local list variable
list.push(folder);
$.each(list, function(i, v) { delete ref.env.subscriptionrows[v]; });
};
this.subscribe = function(folder)
{
if (folder) {
var lock = this.display_message(this.get_label('foldersubscribing'), 'loading');
this.http_post('subscribe', {_mbox: folder}, lock);
}
};
this.unsubscribe = function(folder)
{
if (folder) {
var lock = this.display_message(this.get_label('folderunsubscribing'), 'loading');
this.http_post('unsubscribe', {_mbox: folder}, lock);
}
};
// when user select a folder in manager
this.show_folder = function(folder, path, force)
{
var win, target = window,
url = '&_action=edit-folder&_mbox='+urlencode(folder);
if (path)
url += '&_path='+urlencode(path);
if (win = this.get_frame_window(this.env.contentframe)) {
target = win;
url += '&_framed=1';
}
if (String(target.location.href).indexOf(url) >= 0 && !force)
this.show_contentframe(true);
else
this.location_href(this.env.comm_path+url, target, true);
};
// disables subscription checkbox (for protected folder)
this.disable_subscription = function(folder)
{
var row = this.subscription_list.get_item(folder, true);
if (row)
$('input[name="_subscribed[]"]:first', row).prop('disabled', true);
};
this.folder_size = function(folder)
{
var lock = this.set_busy(true, 'loading');
this.http_post('folder-size', {_mbox: folder}, lock);
};
this.folder_size_update = function(size)
{
$('#folder-size').replaceWith(size);
};
// filter folders by namespace
this.folder_filter = function(prefix)
{
this.subscription_list.reset_search();
this.subscription_list.container.children('li').each(function() {
var i, folder = ref.folder_id2name(this.id);
// show all folders
if (prefix == '---') {
}
// got namespace prefix
else if (prefix) {
if (folder !== prefix) {
$(this).data('filtered', true).hide();
return
}
}
// no namespace prefix, filter out all other namespaces
else {
// first get all namespace roots
for (i in ref.env.ns_roots) {
if (folder === ref.env.ns_roots[i]) {
$(this).data('filtered', true).hide();
return;
}
}
}
$(this).removeData('filtered').show();
});
};
/*********************************************************/
/********* GUI functionality *********/
/*********************************************************/
var init_button = function(cmd, prop)
{
var elm = document.getElementById(prop.id);
if (!elm)
return;
var preload = false;
if (prop.type == 'image') {
elm = elm.parentNode;
preload = true;
}
elm._command = cmd;
elm._id = prop.id;
if (prop.sel) {
elm.onmousedown = function(e) { return ref.button_sel(this._command, this._id); };
elm.onmouseup = function(e) { return ref.button_out(this._command, this._id); };
if (preload)
new Image().src = prop.sel;
}
if (prop.over) {
elm.onmouseover = function(e) { return ref.button_over(this._command, this._id); };
elm.onmouseout = function(e) { return ref.button_out(this._command, this._id); };
if (preload)
new Image().src = prop.over;
}
};
// set event handlers on registered buttons
this.init_buttons = function()
{
for (var cmd in this.buttons) {
if (typeof cmd !== 'string')
continue;
for (var i=0; i<this.buttons[cmd].length; i++) {
init_button(cmd, this.buttons[cmd][i]);
}
}
};
// set button to a specific state
this.set_button = function(command, state)
{
var n, button, obj, $obj, a_buttons = this.buttons[command],
len = a_buttons ? a_buttons.length : 0;
for (n=0; n<len; n++) {
button = a_buttons[n];
obj = document.getElementById(button.id);
if (!obj || button.status === state)
continue;
// get default/passive setting of the button
if (button.type == 'image' && !button.status) {
button.pas = obj._original_src ? obj._original_src : obj.src;
// respect PNG fix on IE browsers
if (obj.runtimeStyle && obj.runtimeStyle.filter && obj.runtimeStyle.filter.match(/src=['"]([^'"]+)['"]/))
button.pas = RegExp.$1;
}
else if (!button.status)
button.pas = String(obj.className);
button.status = state;
// set image according to button state
if (button.type == 'image' && button[state]) {
obj.src = button[state];
}
// set class name according to button state
else if (button[state] !== undefined) {
obj.className = button[state];
}
// disable/enable input buttons
if (button.type == 'input') {
obj.disabled = state == 'pas';
}
else if (button.type == 'uibutton') {
button.status = state;
$(obj).button('option', 'disabled', state == 'pas');
}
else {
$obj = $(obj);
$obj
.attr('tabindex', state == 'pas' || state == 'sel' ? '-1' : ($obj.attr('data-tabindex') || '0'))
.attr('aria-disabled', state == 'pas' || state == 'sel' ? 'true' : 'false');
}
}
};
// display a specific alttext
this.set_alttext = function(command, label)
{
var n, button, obj, link, a_buttons = this.buttons[command],
len = a_buttons ? a_buttons.length : 0;
for (n=0; n<len; n++) {
button = a_buttons[n];
obj = document.getElementById(button.id);
if (button.type == 'image' && obj) {
obj.setAttribute('alt', this.get_label(label));
if ((link = obj.parentNode) && link.tagName.toLowerCase() == 'a')
link.setAttribute('title', this.get_label(label));
}
else if (obj)
obj.setAttribute('title', this.get_label(label));
}
};
// mouse over button
this.button_over = function(command, id)
{
this.button_event(command, id, 'over');
};
// mouse down on button
this.button_sel = function(command, id)
{
this.button_event(command, id, 'sel');
};
// mouse out of button
this.button_out = function(command, id)
{
this.button_event(command, id, 'act');
};
// event of button
this.button_event = function(command, id, event)
{
var n, button, obj, a_buttons = this.buttons[command],
len = a_buttons ? a_buttons.length : 0;
for (n=0; n<len; n++) {
button = a_buttons[n];
if (button.id == id && button.status == 'act') {
if (button[event] && (obj = document.getElementById(button.id))) {
obj[button.type == 'image' ? 'src' : 'className'] = button[event];
}
if (event == 'sel') {
this.buttons_sel[id] = command;
}
}
}
};
// write to the document/window title
this.set_pagetitle = function(title)
{
if (title && document.title)
document.title = title;
};
// display a system message, list of types in common.css (below #message definition)
this.display_message = function(msg, type, timeout, key)
{
// pass command to parent window
if (this.is_framed())
return parent.rcmail.display_message(msg, type, timeout);
if (!this.gui_objects.message) {
// save message in order to display after page loaded
if (type != 'loading')
this.pending_message = [msg, type, timeout, key];
return 1;
}
if (!type)
type = 'notice';
if (!key)
key = this.html_identifier(msg);
var date = new Date(),
id = type + date.getTime();
if (!timeout) {
switch (type) {
case 'error':
case 'warning':
timeout = this.message_time * 2;
break;
case 'uploading':
timeout = 0;
break;
default:
timeout = this.message_time;
}
}
if (type == 'loading') {
key = 'loading';
timeout = this.env.request_timeout * 1000;
if (!msg)
msg = this.get_label('loading');
}
// The same message is already displayed
if (this.messages[key]) {
// replace label
if (this.messages[key].obj)
this.messages[key].obj.html(msg);
// store label in stack
if (type == 'loading') {
this.messages[key].labels.push({'id': id, 'msg': msg});
}
// add element and set timeout
this.messages[key].elements.push(id);
setTimeout(function() { ref.hide_message(id, type == 'loading'); }, timeout);
return id;
}
// create DOM object and display it
var obj = $('<div>').addClass(type).html(msg).data('key', key),
cont = $(this.gui_objects.message).append(obj).show();
this.messages[key] = {'obj': obj, 'elements': [id]};
if (type == 'loading') {
this.messages[key].labels = [{'id': id, 'msg': msg}];
}
else if (type != 'uploading') {
obj.click(function() { return ref.hide_message(obj); })
.attr('role', 'alert');
}
this.triggerEvent('message', { message:msg, type:type, timeout:timeout, object:obj });
if (timeout > 0)
setTimeout(function() { ref.hide_message(id, type != 'loading'); }, timeout);
return id;
};
// make a message to disapear
this.hide_message = function(obj, fade)
{
// pass command to parent window
if (this.is_framed())
return parent.rcmail.hide_message(obj, fade);
if (!this.gui_objects.message)
return;
var k, n, i, o, m = this.messages;
// Hide message by object, don't use for 'loading'!
if (typeof obj === 'object') {
o = $(obj);
k = o.data('key');
this.hide_message_object(o, fade);
if (m[k])
delete m[k];
}
// Hide message by id
else {
for (k in m) {
for (n in m[k].elements) {
if (m[k] && m[k].elements[n] == obj) {
m[k].elements.splice(n, 1);
// hide DOM element if last instance is removed
if (!m[k].elements.length) {
this.hide_message_object(m[k].obj, fade);
delete m[k];
}
// set pending action label for 'loading' message
else if (k == 'loading') {
for (i in m[k].labels) {
if (m[k].labels[i].id == obj) {
delete m[k].labels[i];
}
else {
o = m[k].labels[i].msg;
m[k].obj.html(o);
}
}
}
}
}
}
}
};
// hide message object and remove from the DOM
this.hide_message_object = function(o, fade)
{
if (fade)
o.fadeOut(600, function() {$(this).remove(); });
else
o.hide().remove();
};
// remove all messages immediately
this.clear_messages = function()
{
// pass command to parent window
if (this.is_framed())
return parent.rcmail.clear_messages();
var k, n, m = this.messages;
for (k in m)
for (n in m[k].elements)
if (m[k].obj)
this.hide_message_object(m[k].obj);
this.messages = {};
};
// display uploading message with progress indicator
// data should contain: name, total, current, percent, text
this.display_progress = function(data)
{
if (!data || !data.name)
return;
var msg = this.messages['progress' + data.name];
if (!data.label)
data.label = this.get_label('uploadingmany');
if (!msg) {
if (!data.percent || data.percent < 100)
this.display_message(data.label, 'uploading', 0, 'progress' + data.name);
return;
}
if (!data.total || data.percent >= 100) {
this.hide_message(msg.obj);
return;
}
if (data.text)
data.label += ' ' + data.text;
msg.obj.text(data.label);
};
// open a jquery UI dialog with the given content
this.show_popup_dialog = function(content, title, buttons, options)
{
// forward call to parent window
if (this.is_framed()) {
return parent.rcmail.show_popup_dialog(content, title, buttons, options);
}
var popup = $('<div class="popup">');
if (typeof content == 'object')
popup.append(content);
else
popup.html(content);
options = $.extend({
title: title,
buttons: buttons,
modal: true,
resizable: true,
width: 500,
close: function(event, ui) { $(this).remove(); }
}, options || {});
popup.dialog(options);
// resize and center popup
var win = $(window), w = win.width(), h = win.height(),
width = popup.width(), height = popup.height();
popup.dialog('option', {
height: Math.min(h - 40, height + 75 + (buttons ? 50 : 0)),
width: Math.min(w - 20, width + 36)
});
// assign special classes to dialog buttons
$.each(options.button_classes || [], function(i, v) {
if (v) $($('.ui-dialog-buttonpane button.ui-button', popup.parent()).get(i)).addClass(v);
});
return popup;
};
// enable/disable buttons for page shifting
this.set_page_buttons = function()
{
this.enable_command('nextpage', 'lastpage', this.env.pagecount > this.env.current_page);
this.enable_command('previouspage', 'firstpage', this.env.current_page > 1);
this.update_pagejumper();
};
// mark a mailbox as selected and set environment variable
this.select_folder = function(name, prefix, encode)
{
if (this.savedsearchlist) {
this.savedsearchlist.select('');
}
if (this.treelist) {
this.treelist.select(name);
}
else if (this.gui_objects.folderlist) {
$('li.selected', this.gui_objects.folderlist).removeClass('selected');
$(this.get_folder_li(name, prefix, encode)).addClass('selected');
// trigger event hook
this.triggerEvent('selectfolder', { folder:name, prefix:prefix });
}
};
// adds a class to selected folder
this.mark_folder = function(name, class_name, prefix, encode)
{
$(this.get_folder_li(name, prefix, encode)).addClass(class_name);
this.triggerEvent('markfolder', {folder: name, mark: class_name, status: true});
};
// adds a class to selected folder
this.unmark_folder = function(name, class_name, prefix, encode)
{
$(this.get_folder_li(name, prefix, encode)).removeClass(class_name);
this.triggerEvent('markfolder', {folder: name, mark: class_name, status: false});
};
// helper method to find a folder list item
this.get_folder_li = function(name, prefix, encode)
{
if (!prefix)
prefix = 'rcmli';
if (this.gui_objects.folderlist) {
name = this.html_identifier(name, encode);
return document.getElementById(prefix+name);
}
};
// for reordering column array (Konqueror workaround)
// and for setting some message list global variables
this.set_message_coltypes = function(listcols, repl, smart_col)
{
var list = this.message_list,
thead = list ? list.thead : null,
repl, cell, col, n, len, tr;
this.env.listcols = listcols;
if (!this.env.coltypes)
this.env.coltypes = {};
// replace old column headers
if (thead) {
if (repl) {
thead.innerHTML = '';
tr = document.createElement('tr');
for (c=0, len=repl.length; c < len; c++) {
cell = document.createElement('th');
cell.innerHTML = repl[c].html || '';
if (repl[c].id) cell.id = repl[c].id;
if (repl[c].className) cell.className = repl[c].className;
tr.appendChild(cell);
}
thead.appendChild(tr);
}
for (n=0, len=this.env.listcols.length; n<len; n++) {
col = this.env.listcols[n];
if ((cell = thead.rows[0].cells[n]) && (col == 'from' || col == 'to' || col == 'fromto')) {
$(cell).attr('rel', col).find('span,a').text(this.get_label(col == 'fromto' ? smart_col : col));
}
}
}
this.env.subject_col = null;
this.env.flagged_col = null;
this.env.status_col = null;
if (this.env.coltypes.folder)
this.env.coltypes.folder.hidden = !(this.env.search_request || this.env.search_id) || this.env.search_scope == 'base';
if ((n = $.inArray('subject', this.env.listcols)) >= 0) {
this.env.subject_col = n;
if (list)
list.subject_col = n;
}
if ((n = $.inArray('flag', this.env.listcols)) >= 0)
this.env.flagged_col = n;
if ((n = $.inArray('status', this.env.listcols)) >= 0)
this.env.status_col = n;
if (list) {
list.hide_column('folder', (this.env.coltypes.folder && this.env.coltypes.folder.hidden) || $.inArray('folder', this.env.listcols) < 0);
list.init_header();
}
};
// replace content of row count display
this.set_rowcount = function(text, mbox)
{
// #1487752
if (mbox && mbox != this.env.mailbox)
return false;
$(this.gui_objects.countdisplay).html(text);
// update page navigation buttons
this.set_page_buttons();
};
// replace content of mailboxname display
this.set_mailboxname = function(content)
{
if (this.gui_objects.mailboxname && content)
this.gui_objects.mailboxname.innerHTML = content;
};
// replace content of quota display
this.set_quota = function(content)
{
if (this.gui_objects.quotadisplay && content && content.type == 'text')
$(this.gui_objects.quotadisplay).text((content.percent||0) + '%').attr('title', content.title);
this.triggerEvent('setquota', content);
this.env.quota_content = content;
};
// update trash folder state
this.set_trash_count = function(count)
{
this[(count ? 'un' : '') + 'mark_folder'](this.env.trash_mailbox, 'empty', '', true);
};
// update the mailboxlist
this.set_unread_count = function(mbox, count, set_title, mark)
{
if (!this.gui_objects.mailboxlist)
return false;
this.env.unread_counts[mbox] = count;
this.set_unread_count_display(mbox, set_title);
if (mark)
this.mark_folder(mbox, mark, '', true);
else if (!count)
this.unmark_folder(mbox, 'recent', '', true);
};
// update the mailbox count display
this.set_unread_count_display = function(mbox, set_title)
{
var reg, link, text_obj, item, mycount, childcount, div;
if (item = this.get_folder_li(mbox, '', true)) {
mycount = this.env.unread_counts[mbox] ? this.env.unread_counts[mbox] : 0;
link = $(item).children('a').eq(0);
text_obj = link.children('span.unreadcount');
if (!text_obj.length && mycount)
text_obj = $('<span>').addClass('unreadcount').appendTo(link);
reg = /\s+\([0-9]+\)$/i;
childcount = 0;
if ((div = item.getElementsByTagName('div')[0]) &&
div.className.match(/collapsed/)) {
// add children's counters
for (var k in this.env.unread_counts)
if (k.startsWith(mbox + this.env.delimiter))
childcount += this.env.unread_counts[k];
}
if (mycount && text_obj.length)
text_obj.html(this.env.unreadwrap.replace(/%[sd]/, mycount));
else if (text_obj.length)
text_obj.remove();
// set parent's display
reg = new RegExp(RegExp.escape(this.env.delimiter) + '[^' + RegExp.escape(this.env.delimiter) + ']+$');
if (mbox.match(reg))
this.set_unread_count_display(mbox.replace(reg, ''), false);
// set the right classes
if ((mycount+childcount)>0)
$(item).addClass('unread');
else
$(item).removeClass('unread');
}
// set unread count to window title
reg = /^\([0-9]+\)\s+/i;
if (set_title && document.title) {
var new_title = '',
doc_title = String(document.title);
if (mycount && doc_title.match(reg))
new_title = doc_title.replace(reg, '('+mycount+') ');
else if (mycount)
new_title = '('+mycount+') '+doc_title;
else
new_title = doc_title.replace(reg, '');
this.set_pagetitle(new_title);
}
};
// display fetched raw headers
this.set_headers = function(content)
{
if (this.gui_objects.all_headers_row && this.gui_objects.all_headers_box && content)
$(this.gui_objects.all_headers_box).html(content).show();
};
// display all-headers row and fetch raw message headers
this.show_headers = function(props, elem)
{
if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box || !this.env.uid)
return;
$(elem).removeClass('show-headers').addClass('hide-headers');
$(this.gui_objects.all_headers_row).show();
elem.onclick = function() { ref.command('hide-headers', '', elem); };
// fetch headers only once
if (!this.gui_objects.all_headers_box.innerHTML) {
this.http_post('headers', {_uid: this.env.uid, _mbox: this.env.mailbox},
this.display_message(this.get_label('loading'), 'loading')
);
}
};
// hide all-headers row
this.hide_headers = function(props, elem)
{
if (!this.gui_objects.all_headers_row || !this.gui_objects.all_headers_box)
return;
$(elem).removeClass('hide-headers').addClass('show-headers');
$(this.gui_objects.all_headers_row).hide();
elem.onclick = function() { ref.command('show-headers', '', elem); };
};
// create folder selector popup, position and display it
this.folder_selector = function(event, callback)
{
var container = this.folder_selector_element;
if (!container) {
var rows = [],
delim = this.env.delimiter,
ul = $('<ul class="toolbarmenu">'),
link = document.createElement('a');
container = $('<div id="folder-selector" class="popupmenu"></div>');
link.href = '#';
link.className = 'icon';
// loop over sorted folders list
$.each(this.env.mailboxes_list, function() {
var n = 0, s = 0,
folder = ref.env.mailboxes[this],
id = folder.id,
a = $(link.cloneNode(false)),
row = $('<li>');
if (folder.virtual)
a.addClass('virtual').attr('aria-disabled', 'true').attr('tabindex', '-1');
else
a.addClass('active').data('id', folder.id);
if (folder['class'])
a.addClass(folder['class']);
// calculate/set indentation level
while ((s = id.indexOf(delim, s)) >= 0) {
n++; s++;
}
a.css('padding-left', n ? (n * 16) + 'px' : 0);
// add folder name element
a.append($('<span>').text(folder.name));
row.append(a);
rows.push(row);
});
ul.append(rows).appendTo(container);
// temporarily show element to calculate its size
container.css({left: '-1000px', top: '-1000px'})
.appendTo($('body')).show();
// set max-height if the list is long
if (rows.length > 10)
container.css('max-height', $('li', container)[0].offsetHeight * 10 + 9);
// register delegate event handler for folder item clicks
container.on('click', 'a.active', function(e){
container.data('callback')($(this).data('id'));
return false;
});
this.folder_selector_element = container;
}
container.data('callback', callback);
// position menu on the screen
this.show_menu('folder-selector', true, event);
};
/***********************************************/
/********* popup menu functions *********/
/***********************************************/
// Show/hide a specific popup menu
this.show_menu = function(prop, show, event)
{
var name = typeof prop == 'object' ? prop.menu : prop,
obj = $('#'+name),
ref = event && event.target ? $(event.target) : $(obj.attr('rel') || '#'+name+'link'),
keyboard = rcube_event.is_keyboard(event),
align = obj.attr('data-align') || '',
stack = false;
// find "real" button element
if (ref.get(0).tagName != 'A' && ref.closest('a').length)
ref = ref.closest('a');
if (typeof prop == 'string')
prop = { menu:name };
// let plugins or skins provide the menu element
if (!obj.length) {
obj = this.triggerEvent('menu-get', { name:name, props:prop, originalEvent:event });
}
if (!obj || !obj.length) {
// just delegate the action to subscribers
return this.triggerEvent(show === false ? 'menu-close' : 'menu-open', { name:name, props:prop, originalEvent:event });
}
// move element to top for proper absolute positioning
obj.appendTo(document.body);
if (typeof show == 'undefined')
show = obj.is(':visible') ? false : true;
if (show && ref.length) {
var win = $(window),
pos = ref.offset(),
above = align.indexOf('bottom') >= 0;
stack = ref.attr('role') == 'menuitem' || ref.closest('[role=menuitem]').length > 0;
ref.offsetWidth = ref.outerWidth();
ref.offsetHeight = ref.outerHeight();
if (!above && pos.top + ref.offsetHeight + obj.height() > win.height()) {
above = true;
}
if (align.indexOf('right') >= 0) {
pos.left = pos.left + ref.outerWidth() - obj.width();
}
else if (stack) {
pos.left = pos.left + ref.offsetWidth - 5;
pos.top -= ref.offsetHeight;
}
if (pos.left + obj.width() > win.width()) {
pos.left = win.width() - obj.width() - 12;
}
pos.top = Math.max(0, pos.top + (above ? -obj.height() : ref.offsetHeight));
obj.css({ left:pos.left+'px', top:pos.top+'px' });
}
// add menu to stack
if (show) {
// truncate stack down to the one containing the ref link
for (var i = this.menu_stack.length - 1; stack && i >= 0; i--) {
if (!$(ref).parents('#'+this.menu_stack[i]).length && $(event.target).parent().attr('role') != 'menuitem')
this.hide_menu(this.menu_stack[i], event);
}
if (stack && this.menu_stack.length) {
obj.data('parent', $.last(this.menu_stack));
obj.css('z-index', ($('#'+$.last(this.menu_stack)).css('z-index') || 0) + 1);
}
else if (!stack && this.menu_stack.length) {
this.hide_menu(this.menu_stack[0], event);
}
obj.show().attr('aria-hidden', 'false').data('opener', ref.attr('aria-expanded', 'true').get(0));
this.triggerEvent('menu-open', { name:name, obj:obj, props:prop, originalEvent:event });
this.menu_stack.push(name);
this.menu_keyboard_active = show && keyboard;
if (this.menu_keyboard_active) {
this.focused_menu = name;
obj.find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
}
}
else { // close menu
this.hide_menu(name, event);
}
return show;
};
// hide the given popup menu (and it's childs)
this.hide_menu = function(name, event)
{
if (!this.menu_stack.length) {
// delegate to subscribers
this.triggerEvent('menu-close', { name:name, props:{ menu:name }, originalEvent:event });
return;
}
var obj, keyboard = rcube_event.is_keyboard(event);
for (var j=this.menu_stack.length-1; j >= 0; j--) {
obj = $('#' + this.menu_stack[j]).hide().attr('aria-hidden', 'true').data('parent', false);
this.triggerEvent('menu-close', { name:this.menu_stack[j], obj:obj, props:{ menu:this.menu_stack[j] }, originalEvent:event });
if (this.menu_stack[j] == name) {
j = -1; // stop loop
if (obj.data('opener')) {
$(obj.data('opener')).attr('aria-expanded', 'false');
if (keyboard)
obj.data('opener').focus();
}
}
this.menu_stack.pop();
}
// focus previous menu in stack
if (this.menu_stack.length && keyboard) {
this.menu_keyboard_active = true;
this.focused_menu = $.last(this.menu_stack);
if (!obj || !obj.data('opener'))
$('#'+this.focused_menu).find('a,input:not(:disabled)').not('[aria-disabled=true]').first().focus();
}
else {
this.focused_menu = null;
this.menu_keyboard_active = false;
}
}
// position a menu element on the screen in relation to other object
this.element_position = function(element, obj)
{
var obj = $(obj), win = $(window),
width = obj.outerWidth(),
height = obj.outerHeight(),
menu_pos = obj.data('menu-pos'),
win_height = win.height(),
elem_height = $(element).height(),
elem_width = $(element).width(),
pos = obj.offset(),
top = pos.top,
left = pos.left + width;
if (menu_pos == 'bottom') {
top += height;
left -= width;
}
else
left -= 5;
if (top + elem_height > win_height) {
top -= elem_height - height;
if (top < 0)
top = Math.max(0, (win_height - elem_height) / 2);
}
if (left + elem_width > win.width())
left -= elem_width + width;
element.css({left: left + 'px', top: top + 'px'});
};
// initialize HTML editor
this.editor_init = function(config, id)
{
this.editor = new rcube_text_editor(config, id);
};
/********************************************************/
/********* html to text conversion functions *********/
/********************************************************/
this.html2plain = function(html, func)
{
return this.format_converter(html, 'html', func);
};
this.plain2html = function(plain, func)
{
return this.format_converter(plain, 'plain', func);
};
this.format_converter = function(text, format, func)
{
// warn the user (if converted content is not empty)
if (!text
|| (format == 'html' && !(text.replace(/<[^>]+>| |\xC2\xA0|\s/g, '')).length)
|| (format != 'html' && !(text.replace(/\xC2\xA0|\s/g, '')).length)
) {
// without setTimeout() here, textarea is filled with initial (onload) content
if (func)
setTimeout(function() { func(''); }, 50);
return true;
}
var confirmed = this.env.editor_warned || confirm(this.get_label('editorwarning'));
this.env.editor_warned = true;
if (!confirmed)
return false;
var url = '?_task=utils&_action=' + (format == 'html' ? 'html2text' : 'text2html'),
lock = this.set_busy(true, 'converting');
this.log('HTTP POST: ' + url);
$.ajax({ type: 'POST', url: url, data: text, contentType: 'application/octet-stream',
error: function(o, status, err) { ref.http_error(o, status, err, lock); },
success: function(data) {
ref.set_busy(false, null, lock);
if (func) func(data);
}
});
return true;
};
/********************************************************/
/********* remote request methods *********/
/********************************************************/
// compose a valid url with the given parameters
this.url = function(action, query)
{
var querystring = typeof query === 'string' ? query : '';
if (typeof action !== 'string')
query = action;
else if (!query || typeof query !== 'object')
query = {};
if (action)
query._action = action;
else if (this.env.action)
query._action = this.env.action;
var url = this.env.comm_path, k, param = {};
// overwrite task name
if (action && action.match(/([a-z0-9_-]+)\/([a-z0-9-_.]+)/)) {
query._action = RegExp.$2;
url = url.replace(/\_task=[a-z0-9_-]+/, '_task=' + RegExp.$1);
}
// remove undefined values
for (k in query) {
if (query[k] !== undefined && query[k] !== null)
param[k] = query[k];
}
if (param = $.param(param))
url += (url.indexOf('?') > -1 ? '&' : '?') + param;
if (querystring)
url += (url.indexOf('?') > -1 ? '&' : '?') + querystring;
return url;
};
this.redirect = function(url, lock)
{
if (lock || lock === null)
this.set_busy(true);
if (this.is_framed()) {
parent.rcmail.redirect(url, lock);
}
else {
if (this.env.extwin) {
if (typeof url == 'string')
url += (url.indexOf('?') < 0 ? '?' : '&') + '_extwin=1';
else
url._extwin = 1;
}
this.location_href(url, window);
}
};
this.goto_url = function(action, query, lock)
{
this.redirect(this.url(action, query), lock);
};
this.location_href = function(url, target, frame)
{
if (frame)
this.lock_frame();
if (typeof url == 'object')
url = this.env.comm_path + '&' + $.param(url);
// simulate real link click to force IE to send referer header
if (bw.ie && target == window)
$('<a>').attr('href', url).appendTo(document.body).get(0).click();
else
target.location.href = url;
// reset keep-alive interval
this.start_keepalive();
};
// update browser location to remember current view
this.update_state = function(query)
{
if (window.history.replaceState)
window.history.replaceState({}, document.title, rcmail.url('', query));
};
// send a http request to the server
this.http_request = function(action, data, lock, type)
{
if (type != 'POST')
type = 'GET';
if (typeof data !== 'object')
data = rcube_parse_query(data);
data._remote = 1;
data._unlock = lock ? lock : 0;
// trigger plugin hook
var result = this.triggerEvent('request' + action, data);
// abort if one of the handlers returned false
if (result === false) {
if (data._unlock)
this.set_busy(false, null, data._unlock);
return false;
}
else if (result !== undefined) {
data = result;
if (data._action) {
action = data._action;
delete data._action;
}
}
var url = this.url(action);
// reset keep-alive interval
this.start_keepalive();
// send request
return $.ajax({
type: type, url: url, data: data, dataType: 'json',
success: function(data) { ref.http_response(data); },
error: function(o, status, err) { ref.http_error(o, status, err, lock, action); }
});
};
// send a http GET request to the server
this.http_get = this.http_request;
// send a http POST request to the server
this.http_post = function(action, data, lock)
{
return this.http_request(action, data, lock, 'POST');
};
// aborts ajax request
this.abort_request = function(r)
{
if (r.request)
r.request.abort();
if (r.lock)
this.set_busy(false, null, r.lock);
};
// handle HTTP response
this.http_response = function(response)
{
if (!response)
return;
if (response.unlock)
this.set_busy(false);
this.triggerEvent('responsebefore', {response: response});
this.triggerEvent('responsebefore'+response.action, {response: response});
// set env vars
if (response.env)
this.set_env(response.env);
// we have labels to add
if (typeof response.texts === 'object') {
for (var name in response.texts)
if (typeof response.texts[name] === 'string')
this.add_label(name, response.texts[name]);
}
// if we get javascript code from server -> execute it
if (response.exec) {
this.log(response.exec);
eval(response.exec);
}
// execute callback functions of plugins
if (response.callbacks && response.callbacks.length) {
for (var i=0; i < response.callbacks.length; i++)
this.triggerEvent(response.callbacks[i][0], response.callbacks[i][1]);
}
// process the response data according to the sent action
switch (response.action) {
case 'delete':
if (this.task == 'addressbook') {
var sid, uid = this.contact_list.get_selection(), writable = false;
if (uid && this.contact_list.rows[uid]) {
// search results, get source ID from record ID
if (this.env.source == '') {
sid = String(uid).replace(/^[^-]+-/, '');
writable = sid && this.env.address_sources[sid] && !this.env.address_sources[sid].readonly;
}
else {
writable = !this.env.address_sources[this.env.source].readonly;
}
}
this.enable_command('compose', (uid && this.contact_list.rows[uid]));
this.enable_command('delete', 'edit', writable);
this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
this.enable_command('export-selected', 'print', false);
}
case 'move':
if (this.env.action == 'show') {
// re-enable commands on move/delete error
this.enable_command(this.env.message_commands, true);
if (!this.env.list_post)
this.enable_command('reply-list', false);
}
else if (this.task == 'addressbook') {
this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
}
case 'purge':
case 'expunge':
if (this.task == 'mail') {
if (!this.env.exists) {
// clear preview pane content
if (this.env.contentframe)
this.show_contentframe(false);
// disable commands useless when mailbox is empty
this.enable_command(this.env.message_commands, 'purge', 'expunge',
'select-all', 'select-none', 'expand-all', 'expand-unread', 'collapse-all', false);
}
if (this.message_list)
this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:this.message_list.rowcount });
}
break;
case 'refresh':
case 'check-recent':
// update message flags
$.each(this.env.recent_flags || {}, function(uid, flags) {
ref.set_message(uid, 'deleted', flags.deleted);
ref.set_message(uid, 'replied', flags.answered);
ref.set_message(uid, 'unread', !flags.seen);
ref.set_message(uid, 'forwarded', flags.forwarded);
ref.set_message(uid, 'flagged', flags.flagged);
});
delete this.env.recent_flags;
case 'getunread':
case 'search':
this.env.qsearch = null;
case 'list':
if (this.task == 'mail') {
var is_multifolder = this.is_multifolder_listing(),
list = this.message_list,
uid = this.env.list_uid;
this.enable_command('show', 'select-all', 'select-none', this.env.messagecount > 0);
this.enable_command('expunge', this.env.exists && !is_multifolder);
this.enable_command('purge', this.purge_mailbox_test() && !is_multifolder);
this.enable_command('import-messages', !is_multifolder);
this.enable_command('expand-all', 'expand-unread', 'collapse-all', this.env.threading && this.env.messagecount && !is_multifolder);
if (list) {
if (response.action == 'list' || response.action == 'search') {
// highlight message row when we're back from message page
if (uid) {
if (!list.rows[uid])
uid += '-' + this.env.mailbox;
if (list.rows[uid]) {
list.select(uid);
}
delete this.env.list_uid;
}
this.enable_command('set-listmode', this.env.threads && !is_multifolder);
if (list.rowcount > 0 && !$(document.activeElement).is('input,textarea'))
list.focus();
this.msglist_select(list);
}
if (response.action != 'getunread')
this.triggerEvent('listupdate', { folder:this.env.mailbox, rowcount:list.rowcount });
}
}
else if (this.task == 'addressbook') {
this.enable_command('export', (this.contact_list && this.contact_list.rowcount > 0));
if (response.action == 'list' || response.action == 'search') {
this.enable_command('search-create', this.env.source == '');
this.enable_command('search-delete', this.env.search_id);
this.update_group_commands();
if (this.contact_list.rowcount > 0 && !$(document.activeElement).is('input,textarea'))
this.contact_list.focus();
this.triggerEvent('listupdate', { folder:this.env.source, rowcount:this.contact_list.rowcount });
}
}
break;
case 'list-contacts':
case 'search-contacts':
if (this.contact_list && this.contact_list.rowcount > 0)
this.contact_list.focus();
break;
}
if (response.unlock)
this.hide_message(response.unlock);
this.triggerEvent('responseafter', {response: response});
this.triggerEvent('responseafter'+response.action, {response: response});
// reset keep-alive interval
this.start_keepalive();
};
// handle HTTP request errors
this.http_error = function(request, status, err, lock, action)
{
var errmsg = request.statusText;
this.set_busy(false, null, lock);
request.abort();
// don't display error message on page unload (#1488547)
if (this.unload)
return;
if (request.status && errmsg)
this.display_message(this.get_label('servererror') + ' (' + errmsg + ')', 'error');
else if (status == 'timeout')
this.display_message(this.get_label('requesttimedout'), 'error');
else if (request.status == 0 && status != 'abort')
this.display_message(this.get_label('connerror'), 'error');
// redirect to url specified in location header if not empty
var location_url = request.getResponseHeader("Location");
if (location_url && this.env.action != 'compose') // don't redirect on compose screen, contents might get lost (#1488926)
this.redirect(location_url);
// 403 Forbidden response (CSRF prevention) - reload the page.
// In case there's a new valid session it will be used, otherwise
// login form will be presented (#1488960).
if (request.status == 403) {
(this.is_framed() ? parent : window).location.reload();
return;
}
// re-send keep-alive requests after 30 seconds
if (action == 'keep-alive')
setTimeout(function(){ ref.keep_alive(); ref.start_keepalive(); }, 30000);
};
// handler for session errors detected on the server
this.session_error = function(redirect_url)
{
this.env.server_error = 401;
// save message in local storage and do not redirect
if (this.env.action == 'compose') {
this.save_compose_form_local();
this.compose_skip_unsavedcheck = true;
}
else if (redirect_url) {
setTimeout(function(){ ref.redirect(redirect_url, true); }, 2000);
}
};
// callback when an iframe finished loading
this.iframe_loaded = function(unlock)
{
this.set_busy(false, null, unlock);
if (this.submit_timer)
clearTimeout(this.submit_timer);
};
/**
Send multi-threaded parallel HTTP requests to the server for a list if items.
The string '%' in either a GET query or POST parameters will be replaced with the respective item value.
This is the argument object expected: {
items: ['foo','bar','gna'], // list of items to send requests for
action: 'task/some-action', // Roudncube action to call
query: { q:'%s' }, // GET query parameters
postdata: { source:'%s' }, // POST data (sends a POST request if present)
threads: 3, // max. number of concurrent requests
onresponse: function(data){ }, // Callback function called for every response received from server
whendone: function(alldata){ } // Callback function called when all requests have been sent
}
*/
this.multi_thread_http_request = function(prop)
{
var i, item, reqid = new Date().getTime(),
threads = prop.threads || 1;
prop.reqid = reqid;
prop.running = 0;
prop.requests = [];
prop.result = [];
prop._items = $.extend([], prop.items); // copy items
if (!prop.lock)
prop.lock = this.display_message(this.get_label('loading'), 'loading');
// add the request arguments to the jobs pool
this.http_request_jobs[reqid] = prop;
// start n threads
for (i=0; i < threads; i++) {
item = prop._items.shift();
if (item === undefined)
break;
prop.running++;
prop.requests.push(this.multi_thread_send_request(prop, item));
}
return reqid;
};
// helper method to send an HTTP request with the given iterator value
this.multi_thread_send_request = function(prop, item)
{
var k, postdata, query;
// replace %s in post data
if (prop.postdata) {
postdata = {};
for (k in prop.postdata) {
postdata[k] = String(prop.postdata[k]).replace('%s', item);
}
postdata._reqid = prop.reqid;
}
// replace %s in query
else if (typeof prop.query == 'string') {
query = prop.query.replace('%s', item);
query += '&_reqid=' + prop.reqid;
}
else if (typeof prop.query == 'object' && prop.query) {
query = {};
for (k in prop.query) {
query[k] = String(prop.query[k]).replace('%s', item);
}
query._reqid = prop.reqid;
}
// send HTTP GET or POST request
return postdata ? this.http_post(prop.action, postdata) : this.http_request(prop.action, query);
};
// callback function for multi-threaded http responses
this.multi_thread_http_response = function(data, reqid)
{
var prop = this.http_request_jobs[reqid];
if (!prop || prop.running <= 0 || prop.cancelled)
return;
prop.running--;
// trigger response callback
if (prop.onresponse && typeof prop.onresponse == 'function') {
prop.onresponse(data);
}
prop.result = $.extend(prop.result, data);
// send next request if prop.items is not yet empty
var item = prop._items.shift();
if (item !== undefined) {
prop.running++;
prop.requests.push(this.multi_thread_send_request(prop, item));
}
// trigger whendone callback and mark this request as done
else if (prop.running == 0) {
if (prop.whendone && typeof prop.whendone == 'function') {
prop.whendone(prop.result);
}
this.set_busy(false, '', prop.lock);
// remove from this.http_request_jobs pool
delete this.http_request_jobs[reqid];
}
};
// abort a running multi-thread request with the given identifier
this.multi_thread_request_abort = function(reqid)
{
var prop = this.http_request_jobs[reqid];
if (prop) {
for (var i=0; prop.running > 0 && i < prop.requests.length; i++) {
if (prop.requests[i].abort)
prop.requests[i].abort();
}
prop.running = 0;
prop.cancelled = true;
this.set_busy(false, '', prop.lock);
}
};
// post the given form to a hidden iframe
this.async_upload_form = function(form, action, onload)
{
// create hidden iframe
var ts = new Date().getTime(),
frame_name = 'rcmupload' + ts,
frame = this.async_upload_form_frame(frame_name);
// upload progress support
if (this.env.upload_progress_name) {
var fname = this.env.upload_progress_name,
field = $('input[name='+fname+']', form);
if (!field.length) {
field = $('<input>').attr({type: 'hidden', name: fname});
field.prependTo(form);
}
field.val(ts);
}
// handle upload errors by parsing iframe content in onload
frame.on('load', {ts:ts}, onload);
$(form).attr({
target: frame_name,
action: this.url(action, {_id: this.env.compose_id || '', _uploadid: ts, _from: this.env.action}),
method: 'POST'})
.attr(form.encoding ? 'encoding' : 'enctype', 'multipart/form-data')
.submit();
return frame_name;
};
// create iframe element for files upload
this.async_upload_form_frame = function(name)
{
return $('<iframe>').attr({name: name, style: 'border: none; width: 0; height: 0; visibility: hidden'})
.appendTo(document.body);
};
// html5 file-drop API
this.document_drag_hover = function(e, over)
{
e.preventDefault();
$(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('active');
};
this.file_drag_hover = function(e, over)
{
e.preventDefault();
e.stopPropagation();
$(this.gui_objects.filedrop)[(over?'addClass':'removeClass')]('hover');
};
// handler when files are dropped to a designated area.
// compose a multipart form data and submit it to the server
this.file_dropped = function(e)
{
// abort event and reset UI
this.file_drag_hover(e, false);
// prepare multipart form data composition
var uri, files = e.target.files || e.dataTransfer.files,
formdata = window.FormData ? new FormData() : null,
fieldname = (this.env.filedrop.fieldname || '_file') + (this.env.filedrop.single ? '' : '[]'),
boundary = '------multipartformboundary' + (new Date).getTime(),
dashdash = '--', crlf = '\r\n',
multipart = dashdash + boundary + crlf,
args = {_id: this.env.compose_id || this.env.cid || '', _remote: 1, _from: this.env.action};
if (!files || !files.length) {
// Roundcube attachment, pass its uri to the backend and attach
if (uri = e.dataTransfer.getData('roundcube-uri')) {
var ts = new Date().getTime(),
// jQuery way to escape filename (#1490530)
content = $('<span>').text(e.dataTransfer.getData('roundcube-name') || this.get_label('attaching')).html();
args._uri = uri;
args._uploadid = ts;
// add to attachments list
if (!this.add2attachment_list(ts, {name: '', html: content, classname: 'uploading', complete: false}))
this.file_upload_id = this.set_busy(true, 'attaching');
this.http_post(this.env.filedrop.action || 'upload', args);
}
return;
}
// inline function to submit the files to the server
var submit_data = function() {
var multiple = files.length > 1,
ts = new Date().getTime(),
// jQuery way to escape filename (#1490530)
content = $('<span>').text(multiple ? ref.get_label('uploadingmany') : files[0].name).html();
// add to attachments list
if (!ref.add2attachment_list(ts, { name:'', html:content, classname:'uploading', complete:false }))
ref.file_upload_id = ref.set_busy(true, 'uploading');
// complete multipart content and post request
multipart += dashdash + boundary + dashdash + crlf;
args._uploadid = ts;
$.ajax({
type: 'POST',
dataType: 'json',
url: ref.url(ref.env.filedrop.action || 'upload', args),
contentType: formdata ? false : 'multipart/form-data; boundary=' + boundary,
processData: false,
timeout: 0, // disable default timeout set in ajaxSetup()
data: formdata || multipart,
headers: {'X-Roundcube-Request': ref.env.request_token},
xhr: function() { var xhr = jQuery.ajaxSettings.xhr(); if (!formdata && xhr.sendAsBinary) xhr.send = xhr.sendAsBinary; return xhr; },
success: function(data){ ref.http_response(data); },
error: function(o, status, err) { ref.http_error(o, status, err, null, 'attachment'); }
});
};
// get contents of all dropped files
var last = this.env.filedrop.single ? 0 : files.length - 1;
for (var j=0, i=0, f; j <= last && (f = files[i]); i++) {
if (!f.name) f.name = f.fileName;
if (!f.size) f.size = f.fileSize;
if (!f.type) f.type = 'application/octet-stream';
// file name contains non-ASCII characters, do UTF8-binary string conversion.
if (!formdata && /[^\x20-\x7E]/.test(f.name))
f.name_bin = unescape(encodeURIComponent(f.name));
// filter by file type if requested
if (this.env.filedrop.filter && !f.type.match(new RegExp(this.env.filedrop.filter))) {
// TODO: show message to user
continue;
}
// do it the easy way with FormData (FF 4+, Chrome 5+, Safari 5+)
if (formdata) {
formdata.append(fieldname, f);
if (j == last)
return submit_data();
}
// use FileReader supporetd by Firefox 3.6
else if (window.FileReader) {
var reader = new FileReader();
// closure to pass file properties to async callback function
reader.onload = (function(file, j) {
return function(e) {
multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
multipart += '; filename="' + (f.name_bin || file.name) + '"' + crlf;
multipart += 'Content-Length: ' + file.size + crlf;
multipart += 'Content-Type: ' + file.type + crlf + crlf;
multipart += reader.result + crlf;
multipart += dashdash + boundary + crlf;
if (j == last) // we're done, submit the data
return submit_data();
}
})(f,j);
reader.readAsBinaryString(f);
}
// Firefox 3
else if (f.getAsBinary) {
multipart += 'Content-Disposition: form-data; name="' + fieldname + '"';
multipart += '; filename="' + (f.name_bin || f.name) + '"' + crlf;
multipart += 'Content-Length: ' + f.size + crlf;
multipart += 'Content-Type: ' + f.type + crlf + crlf;
multipart += f.getAsBinary() + crlf;
multipart += dashdash + boundary +crlf;
if (j == last)
return submit_data();
}
j++;
}
};
// starts interval for keep-alive signal
this.start_keepalive = function()
{
if (!this.env.session_lifetime || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
return;
if (this._keepalive)
clearInterval(this._keepalive);
this._keepalive = setInterval(function(){ ref.keep_alive(); }, this.env.session_lifetime * 0.5 * 1000);
};
// starts interval for refresh signal
this.start_refresh = function()
{
if (!this.env.refresh_interval || this.env.framed || this.env.extwin || this.task == 'login' || this.env.action == 'print')
return;
if (this._refresh)
clearInterval(this._refresh);
this._refresh = setInterval(function(){ ref.refresh(); }, this.env.refresh_interval * 1000);
};
// sends keep-alive signal
this.keep_alive = function()
{
if (!this.busy)
this.http_request('keep-alive');
};
// sends refresh signal
this.refresh = function()
{
if (this.busy) {
// try again after 10 seconds
setTimeout(function(){ ref.refresh(); ref.start_refresh(); }, 10000);
return;
}
var params = {}, lock = this.set_busy(true, 'refreshing');
if (this.task == 'mail' && this.gui_objects.mailboxlist)
params = this.check_recent_params();
params._last = Math.floor(this.env.lastrefresh.getTime() / 1000);
this.env.lastrefresh = new Date();
// plugins should bind to 'requestrefresh' event to add own params
this.http_post('refresh', params, lock);
};
// returns check-recent request parameters
this.check_recent_params = function()
{
var params = {_mbox: this.env.mailbox};
if (this.gui_objects.mailboxlist)
params._folderlist = 1;
if (this.gui_objects.quotadisplay)
params._quota = 1;
if (this.env.search_request)
params._search = this.env.search_request;
if (this.gui_objects.messagelist) {
params._list = 1;
// message uids for flag updates check
params._uids = $.map(this.message_list.rows, function(row, uid) { return uid; }).join(',');
}
return params;
};
/********************************************************/
/********* helper methods *********/
/********************************************************/
/**
* Quote html entities
*/
this.quote_html = function(str)
{
return String(str).replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
};
// get window.opener.rcmail if available
this.opener = function(deep, filter)
{
var i, win = window.opener;
// catch Error: Permission denied to access property rcmail
try {
if (win && !win.closed) {
// try parent of the opener window, e.g. preview frame
if (deep && (!win.rcmail || win.rcmail.env.framed) && win.parent && win.parent.rcmail)
win = win.parent;
if (win.rcmail && filter)
for (i in filter)
if (win.rcmail.env[i] != filter[i])
return;
return win.rcmail;
}
}
catch (e) {}
};
// check if we're in show mode or if we have a unique selection
// and return the message uid
this.get_single_uid = function()
{
var uid = this.env.uid || (this.message_list ? this.message_list.get_single_selection() : null);
var result = ref.triggerEvent('get_single_uid', { uid: uid });
return result || uid;
};
// same as above but for contacts
this.get_single_cid = function()
{
var cid = this.env.cid || (this.contact_list ? this.contact_list.get_single_selection() : null);
var result = ref.triggerEvent('get_single_cid', { cid: cid });
return result || cid;
};
// get the IMP mailbox of the message with the given UID
this.get_message_mailbox = function(uid)
{
var msg = (this.env.messages && uid ? this.env.messages[uid] : null) || {};
return msg.mbox || this.env.mailbox;
};
// build request parameters from single message id (maybe with mailbox name)
this.params_from_uid = function(uid, params)
{
if (!params)
params = {};
params._uid = String(uid).split('-')[0];
params._mbox = this.get_message_mailbox(uid);
return params;
};
// gets cursor position
this.get_caret_pos = function(obj)
{
if (obj.selectionEnd !== undefined)
return obj.selectionEnd;
return obj.value.length;
};
// moves cursor to specified position
this.set_caret_pos = function(obj, pos)
{
try {
if (obj.setSelectionRange)
obj.setSelectionRange(pos, pos);
}
catch(e) {} // catch Firefox exception if obj is hidden
};
// get selected text from an input field
this.get_input_selection = function(obj)
{
var start = 0, end = 0, normalizedValue = '';
if (typeof obj.selectionStart == "number" && typeof obj.selectionEnd == "number") {
normalizedValue = obj.value;
start = obj.selectionStart;
end = obj.selectionEnd;
}
return {start: start, end: end, text: normalizedValue.substr(start, end-start)};
};
// disable/enable all fields of a form
this.lock_form = function(form, lock)
{
if (!form || !form.elements)
return;
var n, len, elm;
if (lock)
this.disabled_form_elements = [];
for (n=0, len=form.elements.length; n<len; n++) {
elm = form.elements[n];
if (elm.type == 'hidden')
continue;
// remember which elem was disabled before lock
if (lock && elm.disabled)
this.disabled_form_elements.push(elm);
else if (lock || $.inArray(elm, this.disabled_form_elements) < 0)
elm.disabled = lock;
}
};
this.mailto_handler_uri = function()
{
return location.href.split('?')[0] + '?_task=mail&_action=compose&_to=%s';
};
this.register_protocol_handler = function(name)
{
try {
window.navigator.registerProtocolHandler('mailto', this.mailto_handler_uri(), name);
}
catch(e) {
this.display_message(String(e), 'error');
}
};
this.check_protocol_handler = function(name, elem)
{
var nav = window.navigator;
if (!nav || (typeof nav.registerProtocolHandler != 'function')) {
$(elem).addClass('disabled').click(function(){ return false; });
}
else if (typeof nav.isProtocolHandlerRegistered == 'function') {
var status = nav.isProtocolHandlerRegistered('mailto', this.mailto_handler_uri());
if (status)
$(elem).parent().find('.mailtoprotohandler-status').html(status);
}
else {
$(elem).click(function() { ref.register_protocol_handler(name); return false; });
}
};
// Checks browser capabilities eg. PDF support, TIF support
this.browser_capabilities_check = function()
{
if (!this.env.browser_capabilities)
this.env.browser_capabilities = {};
if (this.env.browser_capabilities.pdf === undefined)
this.env.browser_capabilities.pdf = this.pdf_support_check();
if (this.env.browser_capabilities.flash === undefined)
this.env.browser_capabilities.flash = this.flash_support_check();
if (this.env.browser_capabilities.tif === undefined)
this.tif_support_check();
};
// Returns browser capabilities string
this.browser_capabilities = function()
{
if (!this.env.browser_capabilities)
return '';
var n, ret = [];
for (n in this.env.browser_capabilities)
ret.push(n + '=' + this.env.browser_capabilities[n]);
return ret.join();
};
this.tif_support_check = function()
{
var img = new Image();
img.onload = function() { ref.env.browser_capabilities.tif = 1; };
img.onerror = function() { ref.env.browser_capabilities.tif = 0; };
img.src = this.assets_path('program/resources/blank.tif');
};
this.pdf_support_check = function()
{
var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/pdf"] : {},
plugins = navigator.plugins,
len = plugins.length,
regex = /Adobe Reader|PDF|Acrobat/i;
if (plugin && plugin.enabledPlugin)
return 1;
if ('ActiveXObject' in window) {
try {
if (plugin = new ActiveXObject("AcroPDF.PDF"))
return 1;
}
catch (e) {}
try {
if (plugin = new ActiveXObject("PDF.PdfCtrl"))
return 1;
}
catch (e) {}
}
for (i=0; i<len; i++) {
plugin = plugins[i];
if (typeof plugin === 'String') {
if (regex.test(plugin))
return 1;
}
else if (plugin.name && regex.test(plugin.name))
return 1;
}
return 0;
};
this.flash_support_check = function()
{
var plugin = navigator.mimeTypes ? navigator.mimeTypes["application/x-shockwave-flash"] : {};
if (plugin && plugin.enabledPlugin)
return 1;
if ('ActiveXObject' in window) {
try {
if (plugin = new ActiveXObject("ShockwaveFlash.ShockwaveFlash"))
return 1;
}
catch (e) {}
}
return 0;
};
this.assets_path = function(path)
{
if (this.env.assets_path && !path.startsWith(this.env.assets_path)) {
path = this.env.assets_path + path;
}
return path;
};
// Cookie setter
this.set_cookie = function(name, value, expires)
{
setCookie(name, value, expires, this.env.cookie_path, this.env.cookie_domain, this.env.cookie_secure);
};
this.get_local_storage_prefix = function()
{
if (!this.local_storage_prefix)
this.local_storage_prefix = 'roundcube.' + (this.env.user_id || 'anonymous') + '.';
return this.local_storage_prefix;
};
// wrapper for localStorage.getItem(key)
this.local_storage_get_item = function(key, deflt, encrypted)
{
var item, result;
// TODO: add encryption
try {
item = localStorage.getItem(this.get_local_storage_prefix() + key);
result = JSON.parse(item);
}
catch (e) { }
return result || deflt || null;
};
// wrapper for localStorage.setItem(key, data)
this.local_storage_set_item = function(key, data, encrypted)
{
// try/catch to handle no localStorage support, but also error
// in Safari-in-private-browsing-mode where localStorage exists
// but can't be used (#1489996)
try {
// TODO: add encryption
localStorage.setItem(this.get_local_storage_prefix() + key, JSON.stringify(data));
return true;
}
catch (e) {
return false;
}
};
// wrapper for localStorage.removeItem(key)
this.local_storage_remove_item = function(key)
{
try {
localStorage.removeItem(this.get_local_storage_prefix() + key);
return true;
}
catch (e) {
return false;
}
};
this.print_dialog = function()
{
if (bw.safari)
setTimeout('window.print()', 10);
else
window.print();
};
} // end object rcube_webmail
// some static methods
rcube_webmail.long_subject_title = function(elem, indent)
{
if (!elem.title) {
var $elem = $(elem);
if ($elem.width() + (indent || 0) * 15 > $elem.parent().width())
elem.title = rcube_webmail.subject_text(elem);
}
};
rcube_webmail.long_subject_title_ex = function(elem)
{
if (!elem.title) {
var $elem = $(elem),
txt = $.trim($elem.text()),
tmp = $('<span>').text(txt)
.css({'position': 'absolute', 'float': 'left', 'visibility': 'hidden',
'font-size': $elem.css('font-size'), 'font-weight': $elem.css('font-weight')})
.appendTo($('body')),
w = tmp.width();
tmp.remove();
if (w + $('span.branch', $elem).width() * 15 > $elem.width())
elem.title = rcube_webmail.subject_text(elem);
}
};
rcube_webmail.subject_text = function(elem)
{
var t = $(elem).clone();
t.find('.skip-on-drag').remove();
return t.text();
};
rcube_webmail.prototype.get_cookie = getCookie;
// copy event engine prototype
rcube_webmail.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
rcube_webmail.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
rcube_webmail.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;
|
mhorvvitz/webmail
|
program/js/app.js
|
JavaScript
|
gpl-3.0
| 279,924
|
人生一世,梦幻一场,生老病死,在所难免。那就说一说我所思索的健康、病与医疗吧。**当然得先负责任地说,我不是个医生,只是想把很多自己在医学上的想法公诸于世**。
我们先聊一聊死亡。
灵魂 信息 火葬
守灵 熬夜 烧纸 空气 生人
现在国内的医疗现状 资源少 人口多 床位 设备 医术 名医 论文
人口危机 未富先老
|
dna2github/dna2sevord
|
prose/Life-is-Tough/4.md
|
Markdown
|
gpl-3.0
| 431
|
/*
Copyright (C) <2007-2019> <Kay Diefenthal>
SatIp is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
SatIp 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 SatIp. If not, see <http://www.gnu.org/licenses/>.
*/
namespace SatIp
{
public abstract class RtcpPacket
{
public int Version { get; private set; }
public bool Padding { get; private set; }
public int ReportCount { get; private set; }
public int Type { get; private set; }
public int Length { get; private set; }
public virtual void Parse(byte[] buffer, int offset)
{
Version = buffer[offset] >> 6;
Padding = (buffer[offset] & 0x20) != 0;
ReportCount = buffer[offset] & 0x1f;
Type = buffer[offset + 1];
Length = (Utils.Convert2BytesToInt(buffer, offset + 2) * 4) + 4;
}
}
}
|
Diefenthal/SatIp-Scan-Sample
|
Rtcp/RtcpPacket.cs
|
C#
|
gpl-3.0
| 1,370
|
using Yavsc.Abstract.Identity.Security;
namespace Yavsc.ViewModels.Relationship
{
public class CirclesViewModel
{
public CirclesViewModel(ICircleAuthorized resource)
{
Target = resource;
TargetTypeName = resource.GetType().Name;
}
public ICircleAuthorized Target { get; set; }
public string TargetTypeName { get; set; }
}
}
|
pazof/yavsc
|
src/Yavsc.Server/ViewModels/Relationship/CirclesViewModel.cs
|
C#
|
gpl-3.0
| 403
|
# OpenLearn
*OpenLearn* is an online Learning Management System solution enabling instructors to create their own private website filled with dynamic courses that extend learning anytime, anywhere. It helps the instructors create effective online teaching and learning experiences for the students in a collaborative and private environment, and helps students build their talent pool at their convenience.
It is being developed using the following languages:
(1) HTML,
(2) CSS,
(3) PHP, and
(4) JavaScript (alongwith jQuery at certain places).
The database being used is MySQL. All the queries can be found in the file called `openlearn.sql`, which can be imported from phpMyAdmin's portal.
It has the following features:
1. It is an open learning platform in which any instructor can sign up for free, and teach their students.
2. No signup required for students. Anyone can learn any time, anywhere.
3. A contact page, where any student can contact any teacher in case he/she has any questions related to the course.
4. An easy-to-use admin panel, where the instructors can manage their course(s), add content to the existing courses, view messages, and do much more!
## Note
This project has been developed as part of the recommended project assigned for the course INT301 (Open Source Technologies) by my college, and **is not meant for production**, since it was developed in a span of about two weeks and thus **contains a lot of bad code** as I had a lot of other stuff to do. Yet, you are welcome to suggest any changes to this project and raise issue(s).
|
SDey96/open-learning
|
README.md
|
Markdown
|
gpl-3.0
| 1,595
|
var path = require('path');
var Sequelize = require('sequelize');
var env = require(path.join(__dirname, '../env'));
var db = new Sequelize(env.DATABASE_URI, {
logging: env.LOGGING
});
module.exports = db;
|
qwerpoiuty/humantics-data-mapping
|
server/db/_db.js
|
JavaScript
|
gpl-3.0
| 211
|
<!-- banner -->
<!--<div class="video" data-vide-bg="video/cv">-->
<div class="container" id="container">
<div class="banner-text agileinfo-text">
<h1>BrushLogic</h1>
<div class="social-icons">
<a href="#"><span class="facebook"></span></a>
<a href="#"><span class="twitter"></span></a>
<a href="#"><span class="linkedin"></span></a>
<a href="#"><span class="googleplus"></span></a>
</div>
<h6>{{trans('mainContent.h6-1')}}</h6>
<input type="hidden" id="lenguaje" value="">
</div>
<div class="banner-text banner-info agileinfo-text">
<div>
<h1 id="slider-tittle"></h1>
<h6 id="slider-text"></h6>
</div>
</div>
</div>
</div>
<!-- //banner -->
|
BrushLogic/Portfolio
|
resources/views/include/mainContent.blade.php
|
PHP
|
gpl-3.0
| 739
|
package com.budgetynative;
import com.facebook.react.ReactActivity;
public class MainActivity extends ReactActivity {
/**
* Returns the name of the main component registered from JavaScript.
* This is used to schedule rendering of the component.
*/
@Override
protected String getMainComponentName() {
return "budgetynative";
}
}
|
andrepcg/budgety-native
|
android/app/src/main/java/com/budgetynative/MainActivity.java
|
Java
|
gpl-3.0
| 371
|
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
util.PrecacheModel ("models/items/357ammo.mdl")
function ENT:Initialize()
self.Entity:SetModel("models/items/357ammo.mdl")
self.Entity:PhysicsInit( SOLID_VPHYSICS ) -- Make us work with physics,
self.Entity:SetMoveType( MOVETYPE_VPHYSICS ) -- after all, gmod is a physics
self.Entity:SetSolid( SOLID_VPHYSICS ) -- Toolbox
self.Entity:PhysWake()
self.Entity:SetNetworkedString("NormalAmmo", "20")
if not self.Entity:GetNWString("Ammo") then
self.Entity:SetNetworkedString("Ammo", "20")
end
end
function ENT:Use( activator, caller )
if ( activator:IsPlayer() ) then
local sound = Sound("items/ammo_pickup.wav")
self.Entity:EmitSound( sound )
local ammo
if self.Entity:GetNWString("Ammo") then
ammo = tonumber(self.Entity:GetNWString("Ammo"))
else
self.Entity:SetNetworkedString("Ammo", "20")
ammo = 20
end
self.Entity:Remove()
activator:GiveAmmo( ammo, "357")
end
end
function ENT:PostEntityPaste(pl, Ent, CreatedEntities)
self:Remove()
end
|
AndyClausen/PNRP_HazG
|
postnukerp/entities/entities/ammo_357/init.lua
|
Lua
|
gpl-3.0
| 1,136
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="ro">
<head>
<!-- Generated by javadoc (version 1.7.0_80) on Mon Jun 20 18:37:21 EEST 2016 -->
<title>Uses of Interface net.sf.jasperreports.export.PrintServiceReportConfiguration (JasperReports 6.3.0 API)</title>
<meta name="date" content="2016-06-20">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Interface net.sf.jasperreports.export.PrintServiceReportConfiguration (JasperReports 6.3.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?net/sf/jasperreports/export/class-use/PrintServiceReportConfiguration.html" target="_top">Frames</a></li>
<li><a href="PrintServiceReportConfiguration.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Interface net.sf.jasperreports.export.PrintServiceReportConfiguration" class="title">Uses of Interface<br>net.sf.jasperreports.export.PrintServiceReportConfiguration</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">PrintServiceReportConfiguration</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#net.sf.jasperreports.engine.export">net.sf.jasperreports.engine.export</a></td>
<td class="colLast">
<div class="block">Provides utility classes for exporting reports to various popular formats such as
PDF, HTML, RTF, CSV, Excel, DOCX, PPTX, ODT, ODS, XML, Text, etc.</div>
</td>
</tr>
<tr class="rowColor">
<td class="colFirst"><a href="#net.sf.jasperreports.export">net.sf.jasperreports.export</a></td>
<td class="colLast">
<div class="block">Provides exporter input, exporter output and exporter configurations
Exporter Input
All the input data the exporter might need is supplied by the so-called exporter
input before the exporting process is started.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="net.sf.jasperreports.engine.export">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">PrintServiceReportConfiguration</a> in <a href="../../../../../net/sf/jasperreports/engine/export/package-summary.html">net.sf.jasperreports.engine.export</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../net/sf/jasperreports/engine/export/package-summary.html">net.sf.jasperreports.engine.export</a> that return types with arguments of type <a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">PrintServiceReportConfiguration</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>protected java.lang.Class<<a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">PrintServiceReportConfiguration</a>></code></td>
<td class="colLast"><span class="strong">JRPrintServiceExporter.</span><code><strong><a href="../../../../../net/sf/jasperreports/engine/export/JRPrintServiceExporter.html#getItemConfigurationInterface()">getItemConfigurationInterface</a></strong>()</code> </td>
</tr>
</tbody>
</table>
</li>
<li class="blockList"><a name="net.sf.jasperreports.export">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">PrintServiceReportConfiguration</a> in <a href="../../../../../net/sf/jasperreports/export/package-summary.html">net.sf.jasperreports.export</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing classes, and an explanation">
<caption><span>Classes in <a href="../../../../../net/sf/jasperreports/export/package-summary.html">net.sf.jasperreports.export</a> that implement <a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">PrintServiceReportConfiguration</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Class and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>class </code></td>
<td class="colLast"><code><strong><a href="../../../../../net/sf/jasperreports/export/SimplePrintServiceReportConfiguration.html" title="class in net.sf.jasperreports.export">SimplePrintServiceReportConfiguration</a></strong></code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../net/sf/jasperreports/export/PrintServiceReportConfiguration.html" title="interface in net.sf.jasperreports.export">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../index-all.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?net/sf/jasperreports/export/class-use/PrintServiceReportConfiguration.html" target="_top">Frames</a></li>
<li><a href="PrintServiceReportConfiguration.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<span style="font-decoration:none;font-family:Arial,Helvetica,sans-serif;font-size:8pt;font-style:normal;color:#000000;">© 2001 - 2016 TIBCO Software Inc. <a href="http://www.jaspersoft.com" target="_blank" style="color:#000000;">www.jaspersoft.com</a></span>
</small></p>
</body>
</html>
|
MHTaleb/Encologim
|
lib/JasperReport/docs/api/net/sf/jasperreports/export/class-use/PrintServiceReportConfiguration.html
|
HTML
|
gpl-3.0
| 9,007
|
#include <ATen/ATen.h>
#include <ATen/native/DispatchStub.h>
#include <ATen/native/TensorIterator.h>
namespace at {
namespace native {
using qrelu_fn = void (*)(const at::Tensor& /*qx*/, at::Tensor& /*qy*/);
using qadd_fn =
void (*)(Tensor& /*out*/, const Tensor& /*self*/, const Tensor& /*other*/);
using qmaxpool_2d_fn = void (*)(
const Tensor& qx,
int64_t iC, // input/output channels
int64_t iH,
int64_t iW, // input sizes
int64_t oH,
int64_t oW, // output sizes
int64_t kH,
int64_t kW, // kernel size
int64_t sH,
int64_t sW, // strides
int64_t pH,
int64_t pW, // padding
int64_t dH,
int64_t dW, // dilation
Tensor& qy);
using qadaptive_avg_pool2d_fn = void (*)(
const Tensor& qx,
Tensor& qy,
int64_t b,
int64_t sizeD,
int64_t isizeH,
int64_t isizeW,
int64_t osizeH,
int64_t osizeW,
int64_t istrideB,
int64_t istrideD,
int64_t istrideH,
int64_t istrideW);
using qavg_pool2d_fn = void (*)(
const Tensor& qx,
Tensor& qy,
int64_t b,
int64_t nInputPlane,
int64_t inputWidth,
int64_t inputHeight,
int64_t outputWidth,
int64_t outputHeight,
int kW,
int kH,
int dW,
int dH,
int padW,
int padH,
bool count_include_pad,
c10::optional<int64_t> divisor_override);
using qupsample_bilinear2d_fn = void (*)(
Tensor& output,
const Tensor& input,
int64_t input_height,
int64_t input_width,
int64_t output_height,
int64_t output_width,
int64_t nbatch,
int64_t channels,
bool align_corners);
using qcat_nhwc_fn = Tensor (*)(
const c10::List<Tensor>& qxs,
int64_t dim,
double scale,
int64_t zero_point);
using qtopk_fn = void(*)(Tensor&, Tensor&, const Tensor&, int64_t, int64_t, bool, bool);
// using qavg_pool2d_fn
DECLARE_DISPATCH(qrelu_fn, qrelu_stub);
DECLARE_DISPATCH(qrelu_fn, qrelu6_stub);
DECLARE_DISPATCH(qadd_fn, qadd_stub);
DECLARE_DISPATCH(qadd_fn, qadd_relu_stub);
DECLARE_DISPATCH(qmaxpool_2d_fn, qmaxpool_2d_nhwc_stub);
DECLARE_DISPATCH(qadaptive_avg_pool2d_fn, qadaptive_avg_pool2d_nhwc_stub);
DECLARE_DISPATCH(qavg_pool2d_fn, qavg_pool2d_nhwc_stub);
DECLARE_DISPATCH(qupsample_bilinear2d_fn, qupsample_bilinear2d_nhwc_stub);
DECLARE_DISPATCH(qcat_nhwc_fn, qcat_nhwc_stub);
DECLARE_DISPATCH(qcat_nhwc_fn, qcat_relu_nhwc_stub);
DECLARE_DISPATCH(qtopk_fn, qtopk_stub);
} // namespace native
} // namespace at
|
lavima/MLLib
|
src/torch/aten/src/ATen/native/quantized/cpu/quantized_ops.h
|
C
|
gpl-3.0
| 2,445
|
import re
import os
import pytz
from PIL import Image
from dateutil.parser import parse
from datetime import datetime
from decimal import Decimal
from django.template import Library
from django.conf import settings
from django.template.defaultfilters import stringfilter
from django.utils import formats
from django.utils.safestring import mark_safe
from django.utils.html import conditional_escape, strip_tags, urlize
from django.contrib.auth.models import AnonymousUser
from django.core.files.storage import default_storage
register = Library()
@register.filter(name="localize_date")
def localize_date(value, to_tz=None):
from timezones.utils import adjust_datetime_to_timezone
try:
if to_tz is None:
to_tz = settings.UI_TIME_ZONE
from_tz = settings.TIME_ZONE
return adjust_datetime_to_timezone(value, from_tz=from_tz, to_tz=to_tz)
except AttributeError:
return ''
localize_date.is_safe = True
@register.filter_function
def date_short(value, arg=None):
"""Formats a date according to the given format."""
from django.utils.dateformat import format
from tendenci.apps.site_settings.utils import get_setting
if not value:
return u''
if arg is None:
s_date_format = get_setting('site', 'global', 'dateformat')
if s_date_format:
arg = s_date_format
else:
arg = settings.SHORT_DATETIME_FORMAT
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
date_short.is_safe = False
@register.filter_function
def date_long(value, arg=None):
"""Formats a date according to the given format."""
from django.utils.dateformat import format
from tendenci.apps.site_settings.utils import get_setting
if not value:
return u''
if arg is None:
s_date_format = get_setting('site', 'global', 'dateformatlong')
if s_date_format:
arg = s_date_format
else:
arg = settings.DATETIME_FORMAT
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
date_long.is_safe = False
@register.filter_function
def date(value, arg=None):
"""Formats a date according to the given format."""
from django.utils.dateformat import format
if not value:
return u''
if arg is None:
arg = settings.DATETIME_FORMAT
else:
if arg == 'long':
return date_long(value)
if arg == 'short':
return date_short(value)
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
date_long.is_safe = False
@register.filter_function
def order_by(queryset, args):
args = [x.strip() for x in args.split(',')]
return queryset.order_by(*args)
@register.filter_function
def str_to_date(string, args=None):
"""Takes a string and converts it to a datetime object"""
date = parse(string)
if date:
return date
return ''
@register.filter_function
def exif_to_date(s, fmt='%Y:%m:%d %H:%M:%S'):
"""
The format of datetime in exif is as follows:
%Y:%m:%d %H:%M:%S
Convert the string with this format to a datetime object.
"""
if not s:
return None
try:
return datetime.strptime(s, fmt)
except ValueError:
return None
@register.filter_function
def in_group(user, group):
if group:
if isinstance(user, AnonymousUser):
return False
return group in [dict['pk'] for dict in user.group_set.values('pk')]
else:
return False
@register.filter
def domain(link):
from urlparse import urlparse
link = urlparse(link)
return link.hostname
@register.filter
def strip_template_tags(string):
p = re.compile('{[#{%][^#}%]+[%}#]}')
return re.sub(p, '', string)
@register.filter
@stringfilter
def stripentities(value):
"""Strips all [X]HTML tags."""
from django.utils.html import strip_entities
return strip_entities(value)
stripentities.is_safe = True
@register.filter
def format_currency(value):
"""format currency"""
from tendenci.apps.base.utils import tcurrency
return tcurrency(value)
format_currency.is_safe = True
@register.filter
def get_object(obj):
"""return obj.object if this obj has the attribute of object"""
if hasattr(obj, 'object'):
return obj.object
else:
return obj
@register.filter
def scope(object):
return dir(object)
@register.filter
def obj_type(object):
"""
Return object type
"""
return type(object)
@register.filter
def is_iterable(object):
"""
Return boolean
Is the object iterable or not
"""
try:
iter(object)
return True
except TypeError:
return False
@register.filter
@stringfilter
def basename(path):
from os.path import basename
return basename(path)
@register.filter
def date_diff(value, date_to_compare=None):
"""Compare two dates and return the difference in days"""
import datetime
if not isinstance(value, datetime.datetime):
return 0
if not isinstance(date_to_compare, datetime.datetime):
date_to_compare = datetime.datetime.now()
return (date_to_compare - value).days
@register.filter
def first_chars(string, arg):
""" returns the first x characters from a string """
string = str(string)
if arg:
if not arg.isdigit():
return string
return string[:int(arg)]
else:
return string
return string
@register.filter
def rss_date(value, arg=None):
"""Formats a date according to the given format."""
from django.utils import formats
from django.utils.dateformat import format
from datetime import datetime
if not value:
return u''
else:
value = datetime(*value[:-3])
if arg is None:
arg = settings.DATE_FORMAT
try:
return formats.date_format(value, arg)
except AttributeError:
try:
return format(value, arg)
except AttributeError:
return ''
rss_date.is_safe = False
@register.filter()
def obfuscate_email(email, linktext=None, autoescape=None):
"""
Given a string representing an email address,
returns a mailto link with rot13 JavaScript obfuscation.
Accepts an optional argument to use as the link text;
otherwise uses the email address itself.
"""
if autoescape:
esc = conditional_escape
else:
esc = lambda x: x
email = re.sub('@', '\\\\100', re.sub('\.', '\\\\056', \
esc(email))).encode('rot13')
if linktext:
linktext = esc(linktext).encode('rot13')
else:
linktext = email
rotten_link = """<script type="text/javascript">document.write \
("<n uers=\\\"znvygb:%s\\\">%s<\\057n>".replace(/[a-zA-Z]/g, \
function(c){return String.fromCharCode((c<="Z"?90:122)>=\
(c=c.charCodeAt(0)+13)?c:c-26);}));</script>""" % (email, linktext)
return mark_safe(rotten_link)
obfuscate_email.needs_autoescape = True
@register.filter_function
def split_str(s, args):
"""
Split a string using the python string split method
"""
if args:
if isinstance(s, str):
splitter = args[0]
return s.split(splitter)
return s
return s
@register.filter_function
def str_basename(s):
"""
Get the basename using the python basename method
"""
return basename(s)
@register.filter
@stringfilter
def twitterize(value, autoescape=None):
value = strip_tags(value)
# Link URLs
value = urlize(value, nofollow=False, autoescape=autoescape)
# Link twitter usernames for the first person
value = re.sub(r'(^[^:]+)', r'<a href="http://twitter.com/\1">\1</a>', value)
# Link twitter usernames prefixed with @
value = re.sub(r'(\s+|\A)@([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://twitter.com/\2">@\2</a>', value)
# Link hash tags
value = re.sub(r'(\s+|\A)#([a-zA-Z0-9\-_]*)\b', r'\1<a href="http://search.twitter.com/search?q=%23\2">#\2</a>', value)
return mark_safe(value)
twitterize.is_safe = True
twitterize.needs_autoescape = True
@register.filter
@stringfilter
def twitterdate(value):
from datetime import datetime, timedelta
time = value.replace(" +0000", "")
dt = datetime.strptime(time, "%a, %d %b %Y %H:%M:%S")
return dt + timedelta(hours=-6)
@register.filter
def thumbnail(file, size='200x200'):
# defining the size
x, y = [int(x) for x in size.split('x')]
# defining the filename and the miniature filename
filehead, filetail = os.path.split(file.name)
basename, format = os.path.splitext(filetail)
miniature = basename + '_' + size + format
filename = file.name
miniature_filename = os.path.join(filehead, miniature)
filehead, filetail = os.path.split(file.url)
miniature_url = filehead + '/' + miniature
thumbnail_exist = False
if default_storage.exists(miniature_filename):
mt_filename = default_storage.modified_time(filename)
mt_miniature_filename = default_storage.modified_time(
miniature_filename)
if mt_filename > mt_miniature_filename:
# remove the miniature
default_storage.delete(miniature_filename)
else:
thumbnail_exist = True
# if the image wasn't already resized, resize it
if not thumbnail_exist:
if not default_storage.exists(filename):
return u''
image = Image.open(default_storage.open(filename))
image.thumbnail([x, y], Image.ANTIALIAS)
f = default_storage.open(miniature_filename, 'w')
image.save(f, image.format, quality=90, optimize=1)
f.close()
return miniature_url
@register.filter_function
def datedelta(dt, range_):
from datetime import timedelta
range_type = 'add'
# parse the range
if '+' in range_:
range_ = range_[1:len(range_)]
if '-' in range_:
range_type = 'subtract'
range_ = range_[1:len(range_)]
k, v = range_.split('=')
set_range = {
str(k): int(v)
}
# set the date
if range_type == 'add':
dt = dt + timedelta(**set_range)
if range_type == 'subtract':
dt = dt - timedelta(**set_range)
return dt
@register.filter
def split(str, splitter):
return str.split(splitter)
@register.filter
def tag_split(str):
str = "".join(str)
str = str.replace(", ", ",")
return str.split(",")
@register.filter
def make_range(value):
try:
value = int(value)
if value > 0:
return range(int(value))
return []
except:
return []
@register.filter
def underscore_space(value):
return value.replace("_", " ")
@register.filter
def format_string(value, arg):
return arg % value
@register.filter
def md5_gs(value, arg=None):
import hashlib
from datetime import datetime, timedelta
hashdt = ''
if arg and int(arg):
timestamp = datetime.now() + timedelta(hours=int(arg))
hashdt = hashlib.md5(timestamp.strftime("%Y;%m;%d;%H;%M").replace(';0', ';')).hexdigest()
return ''.join([value, hashdt])
@register.filter
def multiply(value, arg):
return Decimal(str(value)) * Decimal(str(arg))
@register.filter
def add_decimal(value, arg):
return Decimal(str(value)) + Decimal(str(arg))
@register.filter
def phonenumber(value):
if value:
# split number from extension or any text
x = re.split(r'([a-zA-Z]+)', value)
# clean number
y = ''.join(i for i in x[0] if i.isdigit())
if len(y) > 10: # has country code
code = y[:len(y)-10]
number = y[len(y)-10:]
if code == '1':
number = "(%s) %s-%s" %(number[:3], number[3:6], number[6:])
else:
number = "+%s %s %s %s" %(code, number[:3], number[3:6], number[6:])
else: # no country code
number = "(%s) %s-%s" %(y[:3], y[3:6], y[6:])
# attach additional text extension
ext = ''
for i in xrange(1, len(x)):
ext = ''.join((ext, x[i]))
if ext:
return ' '.join((number, ext))
else:
return number
@register.filter
def timezone_label(value):
try:
now = datetime.now(pytz.timezone(value))
tzinfo = now.strftime("%z")
return "(GMT%s) %s" %(tzinfo, value)
except:
return ""
@register.filter
def field_to_string(value):
if isinstance(value, str) or isinstance(value, unicode):
return value
if isinstance(value, list):
if len(value) == 0:
return ""
if len(value) == 1:
return str(value[0])
if len(value) == 2:
return "%s and %s" % (value[0], value[1])
return ", ".join(value)
return str(value)
|
alirizakeles/tendenci
|
tendenci/apps/base/templatetags/base_filters.py
|
Python
|
gpl-3.0
| 13,196
|
# Copyright (C) 2019 The ESPResSo project
#
# This file is part of ESPResSo.
#
# ESPResSo is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# ESPResSo 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/>.
import unittest as ut
import importlib_wrapper
tutorial, skipIfMissingFeatures = importlib_wrapper.configure_and_import(
"@TUTORIALS_DIR@/04-lattice_boltzmann/04-lattice_boltzmann_part2.py",
gpu=True, loops=400)
@skipIfMissingFeatures
class Tutorial(ut.TestCase):
system = tutorial.system
if __name__ == "__main__":
ut.main()
|
mkuron/espresso
|
testsuite/scripts/tutorials/test_04-lattice_boltzmann_part2.py
|
Python
|
gpl-3.0
| 1,053
|
PROJECT_NAME := ext_micro_ecc_nrf51_library_iar
TARGETS := micro_ecc_lib
OUTPUT_DIRECTORY := _build
SDK_ROOT := ../../../..
PROJ_DIR := ../..
# Source files common to all targets
SRC_FILES += \
$(PROJ_DIR)/micro-ecc/uECC.c \
# Include folders common to all targets
INC_FOLDERS += \
# Libraries common to all targets
LIB_FILES += \
# C flags common to all targets
CFLAGS += -DuECC_ENABLE_VLI_API
CFLAGS += -DuECC_OPTIMIZATION_LEVEL=3
CFLAGS += -DuECC_SQUARE_FUNC=1
CFLAGS += -DuECC_SUPPORTS_secp256r1=1
CFLAGS += -DuECC_SUPPORT_COMPRESSED_POINT=0
CFLAGS += -DuECC_VLI_NATIVE_LITTLE_ENDIAN=1
CFLAGS += -mcpu=cortex-m0
CFLAGS += -mthumb -mabi=aapcs
CFLAGS += -Wall -Werror -Os -g3
CFLAGS += -mfloat-abi=soft
# keep every function in separate section, this allows linker to discard unused ones
CFLAGS += -ffunction-sections -fdata-sections -fno-strict-aliasing
CFLAGS += -fno-builtin --short-enums -fshort-wchar
# C++ flags common to all targets
CXXFLAGS += \
# Assembler flags common to all targets
ASMFLAGS += -x assembler-with-cpp
ASMFLAGS += -DuECC_ENABLE_VLI_API
ASMFLAGS += -DuECC_OPTIMIZATION_LEVEL=3
ASMFLAGS += -DuECC_SQUARE_FUNC=1
ASMFLAGS += -DuECC_SUPPORTS_secp256r1=1
ASMFLAGS += -DuECC_SUPPORT_COMPRESSED_POINT=0
ASMFLAGS += -DuECC_VLI_NATIVE_LITTLE_ENDIAN=1
.PHONY: $(TARGETS) default all clean help flash
# Default target - first one defined
default: micro_ecc_lib
# Print all targets that can be built
help:
@echo following targets are available:
@echo micro_ecc_lib
TEMPLATE_PATH := $(SDK_ROOT)/components/toolchain/gcc
include $(TEMPLATE_PATH)/Makefile.common
$(call define_library, $(TARGETS), $(PROJ_DIR)/nrf51_iar/armgcc/micro_ecc_lib_nrf51.a)
define create_library
@echo Creating library: $($@)
$(NO_ECHO)$(AR) $($@) $^
@echo Done
endef
micro_ecc_lib:
$(create_library)
|
jogosa/flip_dot_clock_fw301
|
MODIFIED_SDK_13.0.0_04a0bfd/external/micro-ecc/nrf51_iar/armgcc/Makefile
|
Makefile
|
gpl-3.0
| 1,827
|
/*
* Copyright (C) 2006-2015 Christopho, Solarus - http://www.solarus-games.org
*
* Solarus is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Solarus is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef SOLARUS_STREAM_H
#define SOLARUS_STREAM_H
#include "solarus/Common.h"
#include "solarus/entities/Detector.h"
#include <string>
namespace Solarus {
/**
* \brief A special terrain where the hero is moved towards a specific
* direction.
*
* The hero may or may not resist to the movement of the stream, depending
* on its properties.
*/
class Stream: public Detector {
public:
static constexpr EntityType ThisType = EntityType::STREAM;
Stream(
const std::string& name,
int layer,
const Point& xy,
int direction,
const std::string& sprite_name
);
virtual EntityType get_type() const override;
int get_speed() const;
void set_speed(int speed);
bool get_allow_movement() const;
void set_allow_movement(bool allow_movement);
bool get_allow_attack() const;
void set_allow_attack(bool allow_attack);
bool get_allow_item() const;
void set_allow_item(bool allow_item);
virtual void notify_direction_changed() override;
virtual bool is_obstacle_for(Entity& other) override;
virtual void notify_collision(
Entity& entity_overlapping,
CollisionMode collision_mode
) override;
void activate(Entity& target);
private:
int speed; /**< Speed to apply in pixels per second. */
bool allow_movement; /**< Whether the player can move the hero in this stream. */
bool allow_attack; /**< Whether the player can use the sword in this stream. */
bool allow_item; /**< Whether the player can use equipment items in this stream. */
};
}
#endif
|
DavidKnight247/solarus
|
include/solarus/entities/Stream.h
|
C
|
gpl-3.0
| 2,371
|
Joomla 3.6.4 = 644db365e12bd83154100fb1734df45e
Joomla 3.4.8 = 1743224b16f39ded0bab5438a3930786
Joomla 3.4.3 = 6d7191a684343e5a7f7c24ae6b38e89f
|
gohdan/DFC
|
known_files/hashes/media/editors/codemirror/theme/liquibyte.css
|
CSS
|
gpl-3.0
| 144
|
<div id="{{id}}">
<div id="ba-modal" class="ba-modal-alert ">
<div class="ba-content">
<div class="ba-body">
<span ng-if="!image">{{text}}</span>
<div class="ba-image" ng-if="image" style="background-image:url({{text}})"></div>
</div>
<div class="ba-footer">
<div ng-click="close()" class="ba-btn ba-emerald ba-uppercase ba-fine ba-full">Ok</div>
</div>
</div>
</div>
</div>
|
MaPhil/brainsapp
|
templates/modal/alert.html
|
HTML
|
gpl-3.0
| 436
|
package gar
import (
"archive/tar"
"bytes"
"io"
"testing"
)
func TestWriter(t *testing.T) {
// Files used for testing.
var files = []struct {
Name, Body string
}{
{"readme.txt", "This archive contains some text files."},
{"gopher.txt", "Gopher names:\nGeorge\nGeoffrey\nGonzo"},
{"todo.txt", "Get animal handling licence."},
}
// Create some random file content.
buf := bytes.NewBuffer([]byte("blah blah blah blah"))
w := NewWriter(buf)
// Write files as tar to buffer.
for _, file := range files {
if err := w.WriteFileWithName(
file.Name,
bytes.NewReader([]byte(file.Body)),
); err != nil {
t.Fatal(err)
}
}
w.Close(CompressionNone)
// Now read the gar back out.
r, err := NewReader(bytes.NewReader(buf.Bytes()))
if err != nil {
t.Fatal(err)
}
tr := tar.NewReader(r)
ctr := 0
for {
hdr, err := tr.Next()
if err == io.EOF {
break
} else if err != nil {
t.Fatal(err)
}
if ctr > len(files) {
t.Fatal("ctr incremented higher than the number of files")
}
if hdr.Name != files[ctr].Name {
t.Fatalf("Expected name %s but got %s", files[ctr].Name, hdr.Name)
}
ctr += 1
}
}
|
beefsack/gar
|
writer_test.go
|
GO
|
gpl-3.0
| 1,148
|
<?php /**
Author: SpringHack - springhack@live.cn
Last modified: 2016-01-21 01:39:32
Filename: POJ_DataPoster.php
Description: Created by SpringHack using vim automatically.
**/ ?>
<?php
class POJ_DataPoster {
private $data = "";
private $db = NULL;
private $app = NULL;
private $geter = NULL;
private $info = NULL;
private $pid = "";
private $lang = "";
private $user = "";
private $pass = "";
private $rid = "";
public function POJ_DataPoster($user = "skvj01", $pass = "forskvj", $id = "1000", $lang = "0", $code = "")
{
//MySQL
$this->db = new MySQL();
//Infomation
$rid = $_POST['rid'];
//Add record
$ret = $this->db->value(array(
'id' => $rid,
'oid' => $_GET['id'],
'tid' => $id,
'rid' => '__',
'user' => $_SESSION['user'],
'time' => time(),
'memory' => 'N/A',
'long' => 'N/A',
'lang' => $lang,
'result' => 'N/A',
'oj' => 'POJ',
'oj_u' => $user,
'oj_p' => $pass,
'code' => $code
))->insert("Record");
$_SESSION['last_id'] = $rid;
}
public function getData()
{
return $this->data;
}
}
?>
|
springhack/sk_vjudge
|
classes/POJ_DataPoster.php
|
PHP
|
gpl-3.0
| 1,234
|
#!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ProxyServe.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
|
nanshihui/ipProxyDec
|
ProxyServe/manage.py
|
Python
|
gpl-3.0
| 253
|
#include "record_table.h"
#include "lv2validator.h"
#include "lv2link.h"
#include "record_dialog.h"
#include "object_dialog.h"
#include "ui_polygoned.h"
#include "ui_arrayed.h"
#include "ui_fkeyed.h"
#include "ui_place_ed.h"
#include "ui_rplace_ed.h"
#include "ui_port_ed.h"
#include "ui_fkeyarrayed.h"
#include "mainwindow.h"
#include "popupreport.h"
bool pixmap(const cImage& o, QPixmap &_pixmap)
{
bool f;
f = o.dataIsPic();
if (f) {
const char * _type = o._getType();
QByteArray _data = o.getImage();
if (!_pixmap.loadFromData(_data, _type)) return false;
return true;
}
return false;
}
bool setPixmap(const cImage& im, QLabel *pw)
{
QPixmap pm;
bool r = pixmap(im, pm);
pw->setPixmap(pm);
return r;
}
bool setPixmap(QSqlQuery& q, qlonglong iid, QLabel *pw)
{
if (iid == NULL_ID) {
pw->setPixmap(QPixmap());
return false;
}
cImage im;
im.setById(q, iid);
return setPixmap(im, pw);
}
/* ***************************************** cSelectLanguage ***************************************** */
cSelectLanguage::cSelectLanguage(QComboBox *_pComboBox, QLabel * _pFlag, bool _nullable, QObject *_pPar)
: QObject(_pPar)
{
pComboBox = _pComboBox;
pFlag = _pFlag;
pModel = new cRecordListModel(_sLanguages);
pModel->joinWith(pComboBox);
pModel->nullable = _nullable;
pModel->setFilter();
int ix;
if (_nullable) {
ix = 0;
}
else {
QSqlQuery q = getQuery();
int id = getLanguageId(q);
ix = pModel->indexOf(id);
if (ix < 0) ix = 0;
}
pComboBox->setCurrentIndex(ix);
connect(pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(_languageChanged(int)));
_languageChanged(ix);
}
void cSelectLanguage::_languageChanged(int ix)
{
languageIdChanged(int(pModel->atId(ix)));
if (pFlag != nullptr) {
QSqlQuery q = getQuery();
cLanguage language;
language.fetchById(q, pModel->currendId());
setPixmap(q, language.getId(_sFlagImage), pFlag);
}
}
/* ***************************************** cLineWidget ***************************************** */
bool setFormEditWidget(QFormLayout *_fl, QWidget *_lw, QWidget *_ew, eEx __ex)
{
int row;
QFormLayout::ItemRole role;
_fl->getWidgetPosition(_lw, &row, &role);
if (row < 0 || role != QFormLayout::LabelRole) {
if (__ex != EX_IGNORE) EXCEPTION(EDATA, row);
return false;
}
_fl->setWidget(row, QFormLayout::FieldRole, _ew);
return true;
}
cLineWidget::cLineWidget(QWidget *par, bool _ro, bool _horizontal)
: QWidget(par)
, pLayout(_horizontal ? static_cast<QLayout *>(new QHBoxLayout) : static_cast<QLayout *>(new QVBoxLayout))
, pLineEdit(new QLineEdit)
, pNullButton(static_cast<QToolButton *>(_ro ? new cROToolButton : new QToolButton))
{
pLineEdit->setReadOnly(_ro);
pNullButton->setIcon(lv2g::iconNull);
pNullButton->setCheckable(true);
pLayout->setMargin(0);
setLayout(pLayout);
pLayout->addWidget(pLineEdit);
pLayout->addWidget(pNullButton);
if (!_ro) {
connect(pLineEdit, SIGNAL(textChanged(QString)), this, SLOT(on_LineEdit_textChanged(QString)));
connect(pNullButton, SIGNAL(toggled(bool)), this, SLOT(on_NullButton_togled(bool)));
}
}
void cLineWidget::set(const QVariant& _val)
{
val = _val;
bool _isNull = !_val.isValid();
pNullButton->setChecked(_isNull);
pLineEdit->setDisabled(_isNull);
pLineEdit->setText(_val.toString());
}
void cLineWidget::setDisabled(bool _f)
{
pLineEdit->setDisabled(_f || isNull());
pNullButton->setDisabled(_f);
}
void cLineWidget::on_NullButton_togled(bool f)
{
pLineEdit->setDisabled(f);
QVariant newVal = get();
if (val == newVal) return;
val = newVal;
changed(val);
}
void cLineWidget::on_LineEdit_textChanged(const QString& s)
{
(void)s;
QVariant newVal = get();
if (val == newVal) return;
val = newVal;
changed(val);
}
/* **************************************** cComboLineWidget **************************************** */
cComboLineWidget::cComboLineWidget(const cRecordFieldRef& _cfr, const QString& sqlWhere, bool _horizontal, QWidget *par)
: QWidget(par)
, pLayout(_horizontal ? static_cast<QLayout *>(new QHBoxLayout) : static_cast<QLayout *>(new QVBoxLayout))
, pComboBox(new QComboBox)
, pNullButton(new QToolButton)
, pModel(new cRecFieldSetOfValueModel(_cfr, QStringList(sqlWhere)))
{
pComboBox->setEditable(true);
pModel->joinWith(pComboBox);
pNullButton->setIcon(lv2g::iconNull);
pNullButton->setCheckable(true);
pLayout->setMargin(0);
setLayout(pLayout);
pLayout->addWidget(pComboBox);
pLayout->addWidget(pNullButton);
connect(pComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(on_ComboBox_textChanged(QString)));
connect(pNullButton, SIGNAL(toggled(bool)), this, SLOT(on_NullButton_togled(bool)));
}
void cComboLineWidget::set(const QVariant& _val, Qt::MatchFlags flags)
{
val = _val;
bool _isNull = !_val.isValid();
pNullButton->setChecked(_isNull);
pComboBox->setDisabled(_isNull);
if (!_isNull) {
QString s = val.toString();
pModel->setCurrent(s, flags);
}
}
void cComboLineWidget::setDisabled(bool _f)
{
pComboBox->setDisabled(_f || isNull());
pNullButton->setDisabled(_f);
}
void cComboLineWidget::on_NullButton_togled(bool f)
{
pComboBox->setDisabled(f);
QVariant newVal = get();
if (val == newVal) return;
val = newVal;
emit changed(val);
}
void cComboLineWidget::on_ComboBox_textChanged(const QString& s)
{
(void)s;
QVariant newVal = get();
if (val == newVal) return;
val = newVal;
emit changed(val);
}
/* **************************************** cImageWidget **************************************** */
double cImageWidget::scale = 1.0;
cImageWidget::cImageWidget(QWidget *__par)
: QScrollArea(__par)
, image()
{
pLabel = nullptr;
}
cImageWidget::~cImageWidget()
{
;
}
bool cImageWidget::setImage(const QString& __fn, const QString& __t)
{
hide();
QString title = __t;
if (title.isEmpty()) title = "IMAGE : " + __fn;
setWindowTitle(title);
if (!image.load(__fn)) return false;
return resetImage();
}
bool cImageWidget::setImage(QSqlQuery __q, qlonglong __id, const QString& __t)
{
cImage im;
im.setId(__id);
if (1 != im.completion(__q)) return false;
return setImage(im, __t);
}
bool cImageWidget::setImage(const cImage& __o, const QString &__t)
{
hide();
if (!pixmap(__o, image)) return false;
setWindowTitle(__t.isEmpty() ? __o.getName() : __t);
return resetImage();
}
bool cImageWidget::setText(const QString& _txt)
{
pLabel = new QLabel();
pLabel->setWordWrap(true);
pLabel->setText(_txt);
setWidget(pLabel);
show();
return true;
}
void cImageWidget::mousePressEvent(QMouseEvent * ev)
{
mousePressed(ev->pos());
}
void cImageWidget::center(QPoint p)
{
QSize s = size();
ensureVisible(p.x(), p.y(), s.width() / 2, s.height() / 2);
}
bool cImageWidget::resetImage()
{
image.setDevicePixelRatio(scale);
draw();
pLabel = new QLabel();
pLabel->setPixmap(image);
setWidget(pLabel);
show();
return true;
}
void cImageWidget::draw()
{
if (draws.isEmpty()) return;
QPainter painter(&image);
painter.setBrush(brush);
painter.setPen(pen);
foreach (QVariant g, draws) {
draw(painter, g);
}
}
void cImageWidget::draw(QPainter& painter, QVariant& d)
{
int t = d.userType();
if (t == _UMTID_tPolygonF) {
tPolygonF tPol = d.value<tPolygonF>();
QPolygonF qPol = convertPolygon(tPol);
d = QVariant::fromValue(qPol);
t = QMetaType::QPolygonF;
}
switch (t) {
case QMetaType::QPolygon:
painter.drawPolygon(d.value<QPolygon>());
break;
case QMetaType::QPolygonF:
painter.drawPolygon(d.value<QPolygonF>());
break;
default:
EXCEPTION(ENOTSUPP, t, debVariantToString(d));
}
}
void cImageWidget::zoom(double z)
{
if (z > 0.1) scale = 1/z;
else scale = 10;
resetImage();
}
/* ********************************************************************************************
******************************************************************************************** */
void cROToolButton::mousePressEvent(QMouseEvent *e)
{
(void)e;
}
void cROToolButton::mouseReleaseEvent(QMouseEvent *e)
{
(void)e;
}
/* ********************************************************************************************
************************************** cFieldEditBase **************************************
******************************************************************************************** */
static const QString _sRadioButtons = "radioButtons";
static const QString _sSpinBox = "spinBox";
static const QString _sHide = "hide";
static const QString _sAutoset = "autoset";
static const QString _sCollision = "collision";
static const QString _sColumn = "column";
static const QString _sWidgetFilter = "widget_filter";
// _sRefine
QString fieldWidgetType(int _t)
{
switch (_t) {
case FEW_UNKNOWN: return _sUnknown;
case FEW_SET: return "cSetWidget";
case FEW_ENUM_COMBO: return "cEnumComboWidget";
case FEW_ENUM_RADIO: return "cEnumRadioWidget";
case FEW_LINE: return "cFieldLineWidget";
case FEW_LINES: return "cFieldLineWidget/long";
case FEW_SPIN_BOX: return "cFieldSpinBoxWidget";
case FEW_ARRAY: return "cArrayWidget";
case FEW_FKEY_ARRAY: return "cFKeyArrayWidget";
case FEW_POLYGON: return "cPolygonWidget";
case FEW_FKEY: return "cFKeyWidget";
case FEW_DATE: return "cDateWidget";
case FEW_TIME: return "cTimeWidget";
case FEW_DATE_TIME: return "cDateTimeWidget";
case FEW_INTERVAL: return "cIntervalWidget";
case FEW_BINARY: return "cBinaryWidget";
case FEW_NULL: return "cNullWidget";
case FEW_COLOR: return "cColorWidget";
case FEW_FONT_FAMILY: return "cFontFamilyWidget";
case FEW_FONT_ATTR: return "cFontAttrWidget";
case FEW_LTEXT: return "cLTextWidget";
case FEW_LTEXT_LONG: return "cLTextWidget/long";
case FEW_FEATURES: return "cFeatureWidget";
case FEW_PARAM_VALUE: return "cParamValueWidget";
default: return sInvalidEnum();
}
}
inline bool tableIsReadOnly(const cTableShape &_tm, const cRecord& _r)
{
if (!(_r.isUpdatable())) return true; // A tábla nem modosítható
if (_tm.getBool(_sTableShapeType, TS_READ_ONLY)) return true; // Read only flag a tábla megj, leíróban
if (!lanView::isAuthorized(_tm.getId(_sEditRights))) return true; // Az aktuális user-nek nics joga modosítani a táblát
return false;
}
inline bool fieldIsReadOnly(const cTableShape &_tm, const cTableShapeField &_tf, const cRecordFieldRef& _fr)
{
static const QString _sNotRO = "!" + _sReadOnly;
if (tableIsReadOnly(_tm, _fr.record())) return true; // A táblát nem lehet/szabad modosítani
if (_tf.feature(_sFieldFlags).contains(_sNotRO)) return false;
if (!(_fr.descr().isUpdatable)) return true; // A mező nem modosítható
if (_tf.getBool(_sFieldFlags, FF_READ_ONLY)) return true; // Read only flag a mező megj, leíróban
if (!lanView::isAuthOrNull(_tf.getId(_sEditRights))) return true; // Az aktuális user-nek nics joga modosítani a mezőt
if (_fr.recDescr().autoIncrement()[_fr.index()]) return true; // Az autoincrement mezőt nem modosítjuk.
return false;
}
cFieldEditBase::cFieldEditBase(const cTableShape &_tm, const cTableShapeField &_tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
: QWidget(_par == nullptr ? nullptr : _par->pWidget())
, _pParentDialog(_par)
, _colDescr(_fr.descr())
, _tableShape(_tm)
, _fieldShape(_tf)
, _recDescr(_fr.record().descr())
, _value()
, iconSize(20,20)
{
pLayout = nullptr;
pNullButton = nullptr;
pEditWidget = nullptr;
_wType = FEW_UNKNOWN;
_readOnly = (0 == (_fl & FEB_YET_EDIT)) && ((_fl & FEB_READ_ONLY) || fieldIsReadOnly(_tm, _tf, _fr));
_value = _fr;
_actValueIsNULL = _fr.isNull();
pq = newQuery();
_nullable = _fr.isNullable();
_hasDefault = _fr.descr().colDefault.isNull() == false;
_hasAuto = _fr.recDescr().autoIncrement()[_fr.index()];
_isInsert = (_fl & FEB_INSERT); // ??!
_dcNull = DC_INVALID;
_height = 1;
if (_hasDefault) {
_dcNull = DC_DEFAULT; // can be NULL because it has a default value
}
else if (_hasAuto) {
_dcNull = DC_AUTO; // Auto (read only)
_hasDefault = true;
}
else if (_nullable) {
_dcNull = DC_NULL; // can be NULL
}
actNullIcon = _hasDefault ? lv2g::iconDefault : lv2g::iconNull;
_DBGFNL() << VDEB(_nullable) << VDEB(_hasDefault) << VDEB(_isInsert) << " Index = " << fieldIndex() << " _value = " << debVariantToString(_value) << endl;
}
cFieldEditBase::~cFieldEditBase()
{
if (pq != nullptr) delete pq;
}
QVariant cFieldEditBase::get() const
{
_DBGFN() << QChar('/') << _colDescr<< QChar(' ') << debVariantToString(_value) << endl;
return _value;
}
QString cFieldEditBase::getName() const
{
return _colDescr.toName(get());
}
qlonglong cFieldEditBase::getId() const
{
return _colDescr.toId(get());
}
int cFieldEditBase::set(const QVariant& _v)
{
_DBGFN() << QChar('/') << _colDescr<< QChar(' ') << debVariantToString(_v) << endl;
qlonglong st = 0;
QVariant v = _colDescr.set(_v, st);
if (st & ES_DEFECTIVE) return -1;
if (v == _value) return 0;
_value = v;
_actValueIsNULL = v.isNull();
if (pNullButton != nullptr) {
pNullButton->setChecked(_actValueIsNULL);
disableEditWidget(_actValueIsNULL);
}
changedValue(this);
return 1;
}
int cFieldEditBase::setName(const QString& v)
{
return set(QVariant(v));
}
int cFieldEditBase::setId(qlonglong v)
{
return set(QVariant(v));
}
void cFieldEditBase::setFromWidget(QVariant v)
{
if (_value == v) {
_DBGFN() << QChar('/') << _colDescr<< QChar(' ') << debVariantToString(v) << " dropped" << endl;
return;
}
_DBGFN() << " { " << _colDescr << " } " << debVariantToString(v) << " != " << debVariantToString(_value) << endl;
_value = v;
changedValue(this);
}
void cFieldEditBase::disableEditWidget(eTristate tsf)
{
setBool(_actValueIsNULL, tsf);
if (pEditWidget != nullptr) {
pEditWidget->setDisabled(_actValueIsNULL);
}
}
QWidget *cFieldEditBase::setupNullButton(bool isNull, QAbstractButton * p)
{
if (_readOnly) {
if (p != nullptr) delete p; // nem kell, mert csak egy cimke lessz
pNullButton = new cROToolButton;
}
else {
pNullButton = p == nullptr ? new QToolButton : p;
}
pNullButton->setIcon(actNullIcon);
pNullButton->setCheckable(true);
pNullButton->setChecked(isNull);
if (p == nullptr) {
pLayout->addWidget(pNullButton);
}
if (!_readOnly) {
connect(pNullButton, SIGNAL(clicked(bool)), this, SLOT(togleNull(bool)));
}
return pNullButton;
}
cFieldEditBase * cFieldEditBase::anotherField(const QString& __fn, eEx __ex)
{
if (_pParentDialog == nullptr) {
QString se = tr("A keresett %1 nevű mező szerkesztő objektum, nem található, nincs parent dialugus.\nMező Leiró : %2")
.arg(__fn, _fieldShape.identifying());
if (__ex != EX_IGNORE) EXCEPTION(EDATA, -1, se);
DERR() << se << endl;
return nullptr;
}
cFieldEditBase *p = (*_pParentDialog)[__fn];
if (p == nullptr) {
QString se = tr("A keresett %1 mező, nem található a '%2'.'%3'-ból.\nMező Leiró : %2")
.arg(__fn, _pParentDialog->name, _colDescr.colName(), _fieldShape.identifying());
if (__ex != EX_IGNORE) EXCEPTION(EDATA, -1, se);
DERR() << se << endl;
}
return p;
}
cFieldEditBase *cFieldEditBase::createFieldWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
{
_DBGFN() << QChar(' ') << _tm.tableName() << _sCommaSp << _fr.fullColumnName() << " ..." << endl;
PDEB(VVERBOSE) << "Field value = " << debVariantToString(_fr) << endl;
PDEB(VVERBOSE) << "Field descr = " << _fr.descr().allToString() << endl;
if (!_tf.isNull(_sViewRights) && !lanView::isAuthorized(_tf.getId(_sViewRights))) {
cNullWidget *p = new cNullWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cNullWidget" << endl;
return p;
}
int et = _fr.descr().eColType;
bool ro = (_fl & FEB_READ_ONLY) || fieldIsReadOnly(_tm, _tf, _fr);
qlonglong fieldFlags = _tf.getId(_sFieldFlags);
int fl = ro ? (_fl | FEB_READ_ONLY) : _fl;
if (ro) { // Néhány widget-nek nincs read-only módja, azok helyett read-only esetén egy soros megj. Ez hűlyeség! Legyen Read-only. Javítani!!!
switch (et) {
// ReadOnly esetén a felsoroltak kivételével egysoros megjelenítés
case cColStaticDescr::FT_SET:
case cColStaticDescr::FT_POLYGON:
case cColStaticDescr::FT_INTEGER_ARRAY:
case cColStaticDescr::FT_REAL_ARRAY:
case cColStaticDescr::FT_TEXT_ARRAY:
case cColStaticDescr::FT_BINARY:
case cColStaticDescr::FT_INTERVAL:
break;
case cColStaticDescr::FT_TEXT: // Ha a text egy szín, akkor nem szövegként jelenítjük meg!
if (fieldFlags & ENUM2SET2(FF_FG_COLOR, FF_BG_COLOR)) break;
goto if_ro_cFieldLineWidget;
case cColStaticDescr::FT_BOOLEAN:
case cColStaticDescr::FT_ENUM:
if (_tf.isFeature(_sRadioButtons)) break;
goto if_ro_cFieldLineWidget;
if_ro_cFieldLineWidget:
default: {
cFieldLineWidget *p = new cFieldLineWidget(_tm, _tf, _fr, fl, _par);
_DBGFNL() << " new cFieldLineWidget" << endl;
return p;
}
}
}
switch (et) {
// adattípus és a kivételek szerinti szerkesztő objektum típus kiválasztás.
case cColStaticDescr::FT_INTEGER:
if (_tf.getBool(_sFieldFlags, FF_RAW) == false && _fr.descr().fKeyType != cColStaticDescr::FT_NONE) { // Ha ez egy idegen kulcs
cFKeyWidget *p = new cFKeyWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cFKeyWidget" << endl;
return p;
}
if (_tf.isFeature(_sSpinBox)) {
cFieldSpinBoxWidget *p = new cFieldSpinBoxWidget(_tm, _tf, _fr, fl, _par);
_DBGFNL() << " new cFieldSpinBoxWidget" << endl;
return p;
}
goto case_FieldLineWidget; // Egy soros text...
case cColStaticDescr::FT_TEXT:
if (fieldFlags & ENUM2SET2(FF_FG_COLOR, FF_BG_COLOR)) { // Ez egy szín, mint text
cColorWidget *p = new cColorWidget(_tm, _tf, _fr, fl, _par);
_DBGFNL() << " new cColorWidget" << endl;
return p;
}
if (fieldFlags & ENUM2SET(FF_FONT)) { // Font család neve
if (ro) EXCEPTION(EPROGFAIL); // nem lehet r.o.
cFontFamilyWidget *p = new cFontFamilyWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cFontFamilyWidget" << endl;
return p;
}
if (_fr.columnName() == _sFeatures && 0 == (fieldFlags & ENUM2SET(FF_RAW))) { // features
cFeatureWidget *p = new cFeatureWidget(_tm, _tf, _fr, fl, _par);
return p;
}
goto case_FieldLineWidget; // Egy soros text...
// Egy soros bevitel (LineEdit) kivételek vége
case cColStaticDescr::FT_REAL:
if (_tf.isFeature(_sSpinBox)) {
cFieldSpinBoxWidget *p = new cFieldSpinBoxWidget(_tm, _tf, _fr, fl, _par);
_DBGFNL() << " new cFieldSpinBoxWidget/double" << endl;
return p;
}
LV2_FALLTHROUGH
case cColStaticDescr::FT_MAC:
case cColStaticDescr::FT_INET:
case cColStaticDescr::FT_CIDR: {
case_FieldLineWidget:
cFieldLineWidget *p = new cFieldLineWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cFieldLineWidget" << endl;
return p;
}
case cColStaticDescr::FT_BOOLEAN: // Enumeráció (spec esete) -ként kezeljük
case cColStaticDescr::FT_ENUM: { // Enumeráció mint radio-button-ok
if (_tf.isFeature(_sRadioButtons)) {
cEnumRadioWidget *p = new cEnumRadioWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cEnumRadioWidget" << endl;
return p;
}
else { // Enumeráció : alapértelmezetten comboBox
cEnumComboWidget *p = new cEnumComboWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cEnumComboWidget" << endl;
return p;
}
}
case cColStaticDescr::FT_SET: {
if (fieldFlags & ENUM2SET(FF_FONT)) { // Font attributum
// Csak ez a típus lehet!
if (_fr.descr().enumType() == cFontAttrWidget::sEnumTypeName) {
cFontAttrWidget *p = new cFontAttrWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cFontAttrWidget" << endl;
return p;
}
}
cSetWidget *p = new cSetWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cSetWidget" << endl;
return p;
}
case cColStaticDescr::FT_POLYGON: {
cPolygonWidget *p = new cPolygonWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cPolygonWidget" << endl;
return p;
}
case cColStaticDescr::FT_INTEGER_ARRAY:
if (_tf.getBool(_sFieldFlags, FF_RAW) == false && _fr.descr().fKeyType != cColStaticDescr::FT_NONE) { // nem szám, hanem a hivatkozott rekordok kezelése
cFKeyArrayWidget *p = new cFKeyArrayWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cFKeyArrayWidget" << endl;
return p;
}
LV2_FALLTHROUGH
case cColStaticDescr::FT_REAL_ARRAY:
case cColStaticDescr::FT_TEXT_ARRAY: {
cArrayWidget *p = new cArrayWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cArrayWidget" << endl;
return p;
}
case cColStaticDescr::FT_BINARY: {
cBinaryWidget *p = new cBinaryWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cBinaryWidget" << endl;
return p;
}
case cColStaticDescr::FT_TIME: {
cTimeWidget *p = new cTimeWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cTimeWidget" << endl;
return p;
}
case cColStaticDescr::FT_DATE: {
cDateWidget *p = new cDateWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cDateWidget" << endl;
return p;
}
case cColStaticDescr::FT_DATE_TIME: {
cDateTimeWidget *p = new cDateTimeWidget(_tm, _tf, _fr, _par);
_DBGFNL() << " new cDateTimeWidget" << endl;
return p;
}
case cColStaticDescr::FT_INTERVAL: {
cIntervalWidget *p = new cIntervalWidget(_tm, _tf, _fr, ro, _par);
_DBGFNL() << " new cIntervalWidget" << endl;
return p;
}
default:
EXCEPTION(EDATA, et);
}
}
void cFieldEditBase::togleNull(bool f)
{
disableEditWidget(f);
_setFromEdit();
}
// Alap változat, ha az edit widget QLineEdit, vagy pPlainTextEdit, ha nem kizárást dob
void cFieldEditBase::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
; // NULL/Default
}
else {
if (pEditWidget == nullptr) EXCEPTION(EPROGFAIL);
QString s;
QLineEdit *pLineEdit = qobject_cast<QLineEdit *>(pEditWidget);
if (pLineEdit != nullptr) {
s = pLineEdit->text();
}
else {
QPlainTextEdit *pPlainTextEdit = qobject_cast<QPlainTextEdit *>(pEditWidget);
if (pPlainTextEdit != nullptr) {
s = pPlainTextEdit->toPlainText();
}
else {
QTextEdit *pTextEdit = qobject_cast<QTextEdit *>(pEditWidget);
if (pTextEdit != nullptr) {
s = pTextEdit->toHtml();
}
else {
EXCEPTION(EPROGFAIL);
}
}
}
v = s;
}
setFromWidget(v);
}
/* **************************************** cNullWidget **************************************** */
cNullWidget::cNullWidget(const cTableShape &_tm, const cTableShapeField &_tf, cRecordFieldRef __fr, cRecordDialogBase* _par)
: cFieldEditBase(_tm, _tf, __fr, true, _par)
{
_DBGOBJ() << _tf.identifying() << endl;
_wType = FEW_NULL;
QLineEdit *pLineEdit = new QLineEdit;
pLineEdit->setReadOnly(true);
dcSetShort(pLineEdit, DC_NOT_PERMIT);
pLayout = new QHBoxLayout;
setLayout(pLayout);
pLayout->addWidget(pLineEdit);
}
cNullWidget::~cNullWidget()
{
DBGOBJ();
}
/* **************************************** .......... **************************************** */
bool setWidgetAutoset(qlonglong& on, const QMap<int, qlonglong> autosets)
{
foreach (int e, autosets.keys()) {
if (0 == (autosets[e] & on)) {
on |= ENUM2SET(e);
return true;
}
}
return false;
}
void nextColLayout(QHBoxLayout *pHLayout, QVBoxLayout *& pVLayout, int rows, int n)
{
if (pHLayout != nullptr && n != 0 && (n % rows) == 0) {
pVLayout = new QVBoxLayout;
pHLayout->addLayout(pVLayout);
}
}
/* **************************************** cSetWidget **************************************** */
cSetWidget::cSetWidget(const cTableShape& _tm, const cTableShapeField& _tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par)
{
_DBGOBJ() << _tf.identifying() << endl;
_wType = FEW_SET;
_hiddens = _fieldShape.features().eValue(_sHide, _colDescr.enumType().enumValues);
_autosets = _fieldShape.features().eMapValue(_sAutoset, _colDescr.enumType().enumValues);
_collisions = _fieldShape.features().eMapValue(_sCollision, _colDescr.enumType().enumValues);
if (_fieldShape.isFeature(_sDefault)) {
_defaults = _fieldShape.features().eValue(_sDefault, _colDescr.enumType().enumValues);
_dcNull = DC_DEFAULT;
}
else if (_hasDefault) {
QString s = _colDescr.colDefault;
s = unTypeQuoted(s);
_defaults = _colDescr.toId(_colDescr.fromSql(s));
_dcNull = DC_DEFAULT;
}
else {
_defaults = 0;
}
_nId = _colDescr.enumType().enumValues.size();
int cols, rows;
cols = int(_fieldShape.feature(_sColumn, 1));
rows = _nId - onCount(_hiddens);
if (_dcNull != DC_INVALID) ++rows;
rows = (rows + cols -1) / cols;
_height = rows;
pButtons = new QButtonGroup(this);
QVBoxLayout *pVLayout = new QVBoxLayout;
QHBoxLayout *pHLayout = nullptr;
pButtons->setExclusive(false); // SET, több opció is kiválasztható
if (cols > 1) {
pLayout = pHLayout = new QHBoxLayout;
setLayout(pHLayout);
pHLayout->addLayout(pVLayout);
}
else {
pLayout = pVLayout;
setLayout(pVLayout);
}
_bits = _colDescr.toId(_value);
_isNull = __fr.isNull();
int i, // sequence number
id; // enum value
for (i = id = 0; id < _nId; ++id) {
if (ENUM2SET(id) & _hiddens) continue;
nextColLayout(pHLayout, pVLayout, rows, i);
QCheckBox *pCheckBox = new QCheckBox(this);
enumSetShort(pCheckBox, _colDescr.enumType(), id, _colDescr.enumType().enum2str(id), _tf.getId(_sFieldFlags));
pButtons->addButton(pCheckBox, id);
pVLayout->addWidget(pCheckBox);
pCheckBox->setChecked(enum2set(id) & _bits);
pCheckBox->setDisabled(_readOnly);
++i;
}
if (_dcNull != DC_INVALID) {
nextColLayout(pHLayout, pVLayout, rows, i);
QCheckBox *pCheckBox = new QCheckBox(this);
dcSetShort(pCheckBox, _dcNull);
pButtons->addButton(pCheckBox, id);
pVLayout->addWidget(pCheckBox);
pCheckBox->setChecked(_isNull);
pCheckBox->setDisabled(_readOnly);
}
connect(pButtons, SIGNAL(buttonClicked(int)), this, SLOT(setFromEdit(int)));
}
cSetWidget::~cSetWidget()
{
;
}
void cSetWidget::setChecked()
{
if (_bits < 0) {
_bits = 0;
_isNull = true;
}
if (_isNull && _defaults != 0) {
_bits = _defaults;
}
QAbstractButton * pAbstractButton;
int id;
for (id = 0; id < _nId ; id++) {
pAbstractButton = pButtons->button(id);
if (nullptr != pAbstractButton) {
pAbstractButton->setChecked(enum2set(id) & _bits);
}
}
pAbstractButton = pButtons->button(id);
if (nullptr != pAbstractButton) {
pAbstractButton->setChecked(_isNull);
}
}
int cSetWidget::set(const QVariant& v)
{
_DBGFN() << debVariantToString(v) << endl;
int r = 1 == cFieldEditBase::set(v);
if (r) {
_isNull = _value.isNull();
_bits = _colDescr.toId(_value);
setChecked();
}
return r;
}
void cSetWidget::setFromEdit(int id)
{
_DBGFNL() << id << endl;
QAbstractButton *pButton = pButtons->button(id);
if (pButton == nullptr) EXCEPTION(EPROGFAIL, id);
if (id == _nId) { // NULL
_isNull = pButton->isChecked();
setChecked();
}
else {
qlonglong m = enum2set(id);
if (pButton->isChecked()) {
_bits |= m;
if (_collisions.find(id) != _collisions.end()) {
_bits &= ~_collisions[id];
setWidgetAutoset(_bits, _autosets);
}
else {
bool corr = false;
foreach (int e, _collisions.keys()) {
if (m & _collisions[e]) { // rule?
if (_bits & enum2set(e)) { // collision (reverse)
_bits &= ~enum2set(e);
corr = true;
}
}
}
if (corr) {
setWidgetAutoset(_bits, _autosets);
}
}
}
else {
_bits &= ~m;
setWidgetAutoset(_bits, _autosets);
}
// _isNull = _bits == 0; // Lehet üres tömb is!
if (_isNull && _defaults != 0) {
_bits = _defaults;
}
else {
pButton = pButtons->button(_nId);
if (pButton != nullptr) pButton->setChecked(_isNull);
}
}
setChecked();
qlonglong dummy;
set(_colDescr.set(QVariant(_bits), dummy));
}
/* **************************************** cEnumRadioWidget **************************************** */
cEnumRadioWidget::cEnumRadioWidget(const cTableShape& _tm, const cTableShapeField& _tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par)
{
_wType = FEW_ENUM_RADIO;
bool vert = _fieldShape.isFeature("horizontal");
pButtons = new QButtonGroup(this);
if (vert) {
pLayout = new QHBoxLayout;
_height = _colDescr.enumType().enumValues.size();
if (_dcNull != DC_INVALID) ++_height;
}
else {
pLayout = new QVBoxLayout;
}
pButtons->setExclusive(true);
setLayout(pLayout);
int id = 0;
eval = _colDescr.toId(_value);
for (id = 0; id < _colDescr.enumType().enumValues.size(); ++id) {
QRadioButton *pRadioButton = new QRadioButton(this);
enumSetShort(pRadioButton, _colDescr.enumType(), id, _colDescr.enumType().enum2str(id), _tf.getId(_sFieldFlags));
pButtons->addButton(pRadioButton, id);
pLayout->addWidget(pRadioButton);
pRadioButton->setChecked(id == eval);
pRadioButton->setDisabled(_readOnly);
}
if (_dcNull != DC_INVALID) {
QRadioButton *pRadioButton = new QRadioButton(this);
dcSetShort(pRadioButton, _dcNull);
pButtons->addButton(pRadioButton, id);
pLayout->addWidget(pRadioButton);
pRadioButton->setChecked(eval < 0);
pRadioButton->setDisabled(_readOnly);
}
connect(pButtons, SIGNAL(buttonClicked(int)), this, SLOT(setFromEdit(int)));
}
cEnumRadioWidget::~cEnumRadioWidget()
{
;
}
int cEnumRadioWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
if (1 == r) {
pButtons->button(pButtons->checkedId())->setChecked(false);
eval = _colDescr.toId(v);
if (eval >= 0) pButtons->button(int(eval))->setChecked(true);
else {
QAbstractButton *pRB = pButtons->button(_colDescr.enumType().enumValues.size());
if (pRB != nullptr) pRB->setChecked(true);
}
}
return r;
}
void cEnumRadioWidget::setFromEdit(int id)
{
QVariant v;
if (eval == id) {
if (pButtons->button(id)->isChecked() == false) pButtons->button(id)->setChecked(true);
return;
}
if (id == _colDescr.enumType().enumValues.size()) {
if (eval < 0) {
if (pButtons->button(id)->isChecked() == false) pButtons->button(id)->setChecked(true);
return;
}
}
else {
v = eval;
}
qlonglong dummy;
setFromWidget(_colDescr.set(v, dummy));
}
/* **************************************** cEnumComboWidget **************************************** */
cEnumComboWidget::cEnumComboWidget(const cTableShape& _tm, const cTableShapeField& _tf, cRecordFieldRef __fr, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, false, _par)
{
if (_readOnly && _par != nullptr) EXCEPTION(EPROGFAIL, 0, _tf.identifying() + "\n" + __fr.record().identifying());
eval = getId();
_wType = FEW_ENUM_COMBO;
pEditWidget = pComboBox = new QComboBox;
pLayout = new QHBoxLayout;
setLayout(pLayout);
pLayout->addWidget(pComboBox);
bool isNull = eval == NULL_ID;
evalDef = ENUM_INVALID;
if (!_hasDefault && !_nullable) { // Nem lehet NULL, nincs default, akkor a default az első érték.
_value = eval = evalDef = 0;
isNull = false;
}
else if (_hasDefault) {
evalDef = _colDescr.enumType().str2enum(_colDescr.colDefault);
if (isNull) {
_value = eval = evalDef;
isNull = false;
}
}
if (_nullable || _hasDefault) {
setupNullButton(isNull || eval == evalDef);
cFieldEditBase::disableEditWidget(isNull);
}
pModel = new cEnumListModel(&_colDescr.enumType());
pModel->joinWith(pComboBox);
pComboBox->setEditable(false);
setWidget();
connect(pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setFromEdit(int)));
if (!isNull) setFromEdit(pComboBox->currentIndex());
}
cEnumComboWidget::~cEnumComboWidget()
{
;
}
void cEnumComboWidget::setWidget()
{
if (eval < 0 && evalDef >= 0) eval = evalDef;
if (eval < 0 && pNullButton != nullptr) {
pNullButton->setChecked(true);
}
else {
if (pNullButton != nullptr) {
pNullButton->setChecked(eval == evalDef);
}
int ix = pModel->indexOf(int(eval));
if (ix < 0) ix = 0;
pComboBox->setCurrentIndex(ix);
}
}
void cEnumComboWidget::togleNull(bool f)
{
// _DBGFN() << _colDescr << VDEB(f) << endl;
if (evalDef > ENUM_INVALID) {
if (f) {
int ix = pModel->indexOf(int(evalDef));
pComboBox->setCurrentIndex(ix);
// PDEB(INFO) << VDEB(eval) << VDEB(evalDef) << endl;
}
else {
if (eval == evalDef) pNullButton->setChecked(true);
}
return;
}
disableEditWidget(f);
if (f) {
eval = NULL_ID;
setFromWidget(QVariant());
}
else {
int ix = pComboBox->currentIndex();
setFromEdit(ix);
}
}
int cEnumComboWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
if (1 == r) { // Change
setFromWidget(v);
eval = getId();
setWidget();
}
return r;
}
void cEnumComboWidget::setFromEdit(int index)
{
//_DBGFN() << VDEB(index);
qlonglong newEval = pModel->atInt(index);
if (eval == newEval) {
//PDEB(INFO) << "no change: " << VDEB(eval) << endl;
return;
}
//PDEB(INFO) << VDEB(eval) << " := " << newEval << endl;
eval = newEval;
if (pNullButton != nullptr && evalDef > ENUM_INVALID) pNullButton->setChecked(eval == evalDef);
qlonglong v = newEval;
qlonglong dummy;
setFromWidget(_colDescr.set(QVariant(v), dummy));
}
/* **************************************** cFieldLineWidget **************************************** */
cFieldLineWidget::cFieldLineWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
{
pLineEdit = nullptr;
pPlainTextEdit = nullptr;
pTextEdit = nullptr;
pComboBox = nullptr;
pModel = nullptr;
modeltype = NO_MODEL;
isPwd = false;
const QString sSetOfValue = "setOfValue";
pLayout = new QHBoxLayout;
setLayout(pLayout);
bool isText = _colDescr.eColType == cColStaticDescr::FT_TEXT;
if (isText && _fieldShape.getBool(_sFieldFlags, FF_HTML_TEXT)) {
_wType = FEW_HTML_LINES; // Widget type
pEditWidget = pTextEdit = new QTextEdit;
pLayout->addWidget(pTextEdit);
_height = 4;
}
else if (isText && _fieldShape.getBool(_sFieldFlags, FF_HUGE)) {
_wType = FEW_LINES; // Widget type
pEditWidget = pPlainTextEdit = new QPlainTextEdit;
// QSizePolicy spol = pPlainTextEdit->sizePolicy();
// spol.setVerticalPolicy(QSizePolicy::MinimumExpanding);
// pPlainTextEdit->setSizePolicy(spol);
pLayout->addWidget(pPlainTextEdit);
_height = 4;
}
else if (!_readOnly && isText && _fieldShape.isFeature(sSetOfValue)) {
_wType = FEW_COMBO_BOX; // Widget type
pEditWidget = pComboBox = new QComboBox;
pComboBox->setEditable(true);
pLayout->addWidget(pComboBox);
cRecFieldSetOfValueModel *pm = new cRecFieldSetOfValueModel(_fr, _fieldShape.features().slValue(sSetOfValue));
pModel = pm;
pm->joinWith(pComboBox);
modeltype = SETOF_MODEL;
}
else if (!_readOnly && isText && _fieldShape.getBool(_sFieldFlags, FF_IMAGE)) { // Icon name from resource
_wType = FEW_COMBO_BOX; // Widget type
pEditWidget = pComboBox = new QComboBox;
pComboBox->setEditable(false);
pLayout->addWidget(pComboBox);
cResourceIconsModel *pm = new cResourceIconsModel();
pModel = pm;
pm->joinWith(pComboBox);
modeltype = ICON_MODEL;
_nullable = false;
}
else {
_wType = FEW_LINE; // Widget type
pEditWidget = pLineEdit = new QLineEdit;
pLayout->addWidget(pLineEdit);
isPwd = _fieldShape.getBool(_sFieldFlags, FF_PASSWD); // Password?
}
// if (_colDescr.eColType == cColStaticDescr::FT_TEXT) {
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
// }
QString tx;
if (_readOnly == false) {
tx = _fr.toString();
_value = QVariant(tx);
switch (_colDescr.eColType) {
case cColStaticDescr::FT_INTEGER: pLineEdit->setValidator(new cIntValidator( _nullable, pLineEdit)); break;
case cColStaticDescr::FT_REAL: pLineEdit->setValidator(new cRealValidator(_nullable, pLineEdit)); break;
case cColStaticDescr::FT_TEXT: /* no validator */ break;
case cColStaticDescr::FT_MAC: pLineEdit->setValidator(new cMacValidator( _nullable, pLineEdit)); break;
case cColStaticDescr::FT_INET: pLineEdit->setValidator(new cINetValidator(_nullable, pLineEdit)); break;
case cColStaticDescr::FT_CIDR: pLineEdit->setValidator(new cCidrValidator(_nullable, pLineEdit)); break;
default: EXCEPTION(ENOTSUPP);
}
switch(_wType) {
case FEW_LINE:
if (isPwd) {
pLineEdit->setEchoMode(QLineEdit::Password);
pLineEdit->setText("");
_value.clear();
connect(pLineEdit, SIGNAL(editingFinished()), this, SLOT(_setFromEdit()));
break;
}
pLineEdit->setText(_fr);
connect(pLineEdit, SIGNAL(editingFinished()), this, SLOT(_setFromEdit()));
break;
case FEW_LINES:
pPlainTextEdit->setPlainText(_fr);
connect(pPlainTextEdit, SIGNAL(textChanged()), this, SLOT(_setFromEdit()));
break;
case FEW_HTML_LINES:
pTextEdit->setHtml(_fr);
connect(pTextEdit, SIGNAL(textChanged()), this, SLOT(_setFromEdit()));
break;
case FEW_COMBO_BOX:
switch (modeltype) {
case SETOF_MODEL:
static_cast<cRecFieldSetOfValueModel *>(pModel)->setCurrent(_fr);
break;
case ICON_MODEL:
static_cast<cResourceIconsModel *>(pModel)->setCurrent(_fr);
break;
case NO_MODEL:
EXCEPTION(EPROGFAIL, 0);
}
connect(pComboBox, SIGNAL(currentTextChanged(QString)), this, SLOT(_setFromEdit()));
break;
default:
EXCEPTION(EPROGFAIL);
}
}
else {
tx = _fr.view(*pq);
if (isPwd) {
tx = "********";
}
else if (_isInsert) {
if (_wType == FEW_LINE) {
if (_hasAuto) dcSetShort(pLineEdit, DC_AUTO);
else if (_hasDefault) dcSetShort(pLineEdit, DC_DEFAULT);;
}
}
switch (_wType) {
case FEW_LINE:
pLineEdit->setText(tx);
pLineEdit->setReadOnly(true);
break;
case FEW_LINES:
pPlainTextEdit->setPlainText(tx);
pPlainTextEdit->setReadOnly(true);
break;
case FEW_HTML_LINES:
pTextEdit->setHtml(tx);
pTextEdit->setReadOnly(true);
break;
default:
EXCEPTION(EPROGFAIL);
}
}
}
cFieldLineWidget::~cFieldLineWidget()
{
;
}
int cFieldLineWidget::set(const QVariant& v)
{
if (isPwd) {
pLineEdit->setText(_sNul);
return 0;
}
int r = cFieldEditBase::set(v);
if (1 == r && !_actValueIsNULL) {
QString txt;
if (_readOnly == false) {
txt = _colDescr.toName(_value);
}
else {
txt = _colDescr.toView(*pq, _value);
}
switch (_wType) {
case FEW_LINE:
pLineEdit->setText(txt);
break;
case FEW_LINES:
pPlainTextEdit->setPlainText(txt);
break;
case FEW_HTML_LINES:
pTextEdit->setHtml(txt);
break;
case FEW_COMBO_BOX:
switch (modeltype) {
case SETOF_MODEL:
static_cast<cRecFieldSetOfValueModel *>(pModel)->setCurrent(txt);
break;
case ICON_MODEL:
static_cast<cResourceIconsModel *>(pModel)->setCurrent(txt);
break;
case NO_MODEL:
EXCEPTION(EPROGFAIL, 0);
}
break;
default:
EXCEPTION(EPROGFAIL, _wType);
}
}
return r;
}
void cFieldLineWidget::_setFromEdit()
{
if ((pNullButton != nullptr && pNullButton->isChecked()) || _wType != FEW_COMBO_BOX) {
cFieldEditBase::_setFromEdit();
}
else {
QString s = pComboBox->currentText();
setFromWidget(QVariant(s));
}
}
/* **************************************** cFieldSpinBoxWidget **************************************** */
cFieldSpinBoxWidget::cFieldSpinBoxWidget(const cTableShape &_tm, const cTableShapeField& _tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase* _par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
{
_wType = FEW_SPIN_BOX;
pSpinBox = nullptr;
pDoubleSpinBox = nullptr;
pLayout = new QHBoxLayout;
setLayout(pLayout);
QStringList minmax = _tf.features().slValue(_sSpinBox);
switch (_colDescr.eColType) {
case cColStaticDescr::FT_INTEGER:
pEditWidget = pSpinBox = new QSpinBox;
if (minmax.size()) {
bool ok;
int i = minmax.first().toInt(&ok);
if (ok) { // Set minimum
pSpinBox->setMinimum(i);
}
if (minmax.size() > 1) {
i = minmax.at(1).toInt(&ok);
if (ok) { // Set maximum
pSpinBox->setMaximum(i);
}
}
}
break;
case cColStaticDescr::FT_REAL:
pEditWidget = pDoubleSpinBox = new QDoubleSpinBox;
if (minmax.size()) {
bool ok;
double d = minmax.first().toDouble(&ok);
if (ok) { // Set minimum
pDoubleSpinBox->setMinimum(d);
}
if (minmax.size() > 1) {
d = minmax.at(1).toDouble(&ok);
if (ok) { // Set maximum
pDoubleSpinBox->setMaximum(d);
}
if (minmax.size() > 2) {
int i = minmax.at(2).toInt(&ok);
if (ok) { // Set Decimal
pDoubleSpinBox->setDecimals(i);
}
}
}
}
break;
default:
EXCEPTION(EPROGFAIL);
}
pLayout->addWidget(pSpinBox);
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
if (pSpinBox != nullptr) connect(pSpinBox, SIGNAL(valueChanged(int)), this, SLOT(setFromEdit(int)));
else connect(pDoubleSpinBox, SIGNAL(valueChanged(double)), this, SLOT(setFromEdit(double)));
}
cFieldSpinBoxWidget::~cFieldSpinBoxWidget()
{
}
int cFieldSpinBoxWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && !_actValueIsNULL) {
bool ok = false;
if (pSpinBox != nullptr) pSpinBox->setValue(_value.toInt(&ok));
else pDoubleSpinBox->setValue(_value.toDouble(&ok));
if (!ok) return -1;
}
return r;
}
void cFieldSpinBoxWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
;
}
else {
if (pSpinBox != nullptr) v = pSpinBox->value();
else v = pDoubleSpinBox->value();
}
setFromWidget(v);
}
void cFieldSpinBoxWidget::setFromEdit(int i)
{
setFromWidget(QVariant(i));
}
void cFieldSpinBoxWidget::setFromEdit(double d)
{
setFromWidget(QVariant(d));
}
/* **************************************** cArrayWidget **************************************** */
cArrayWidget::cArrayWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
, last()
{
_wType = FEW_ARRAY;
_height = 4;
pUi = new Ui_arrayEd;
pUi->setupUi(this);
pEditWidget = pUi->listView;
selectedNum = 0;
pUi->pushButtonAdd->setDisabled(_readOnly);
pUi->pushButtonIns->setDisabled(_readOnly);
pUi->pushButtonUp->setDisabled(_readOnly);
pUi->pushButtonDown->setDisabled(_readOnly);
pUi->pushButtonMod->setDisabled(_readOnly);
pUi->pushButtonDel->setDisabled(_readOnly);
pUi->pushButtonClr->setDisabled(_readOnly);
pModel = new cStringListModel(this);
pModel->setStringList(_value.toStringList());
pUi->listView->setModel(pModel);
pUi->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull, new QPushButton);
cArrayWidget::disableEditWidget(bool2ts(isNull));
pUi->gridLayout->addWidget(pNullButton, 3, 1);
}
if (!_readOnly) {
connect(pUi->pushButtonAdd, SIGNAL(pressed()), this, SLOT(addRow()));
connect(pUi->pushButtonDel, SIGNAL(pressed()), this, SLOT(delRow()));
connect(pUi->pushButtonClr, SIGNAL(pressed()), this, SLOT(clrRows()));
connect(pUi->pushButtonMod, SIGNAL(pressed()), this, SLOT(modRow()));
connect(pUi->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(changed(QString)));
connect(pUi->listView->selectionModel(), SIGNAL(currentRowChanged(QModelIndex,QModelIndex)), this, SLOT(selectionChanged(QModelIndex,QModelIndex)));
connect(pUi->listView, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(doubleClickRow(QModelIndex)));
}
}
cArrayWidget::~cArrayWidget()
{
;
}
int cArrayWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
if (1 == r && !_actValueIsNULL) {
pModel->setStringList(_value.toStringList());
}
setButtons();
return r;
}
void cArrayWidget::setButtons()
{
bool eArr = _readOnly || _actValueIsNULL || pModel->isEmpty();
bool eLin = _readOnly || _actValueIsNULL || pUi->lineEdit->text().isEmpty();
bool sing = _readOnly || _actValueIsNULL || selectedNum != 1;
bool any = _readOnly || _actValueIsNULL || selectedNum == 0;
pUi->pushButtonAdd ->setDisabled(eLin );
pUi->pushButtonIns ->setDisabled(eLin || sing);
pUi->pushButtonUp ->setDisabled( any );
pUi->pushButtonDown->setDisabled( any );
pUi->pushButtonMod ->setDisabled(eLin || sing);
pUi->pushButtonDel ->setDisabled(eArr );
pUi->pushButtonClr ->setDisabled(eArr );
}
void cArrayWidget::disableEditWidget(eTristate tsf)
{
cFieldEditBase::disableEditWidget(tsf);
setButtons();
pUi->lineEdit->setDisabled(_actValueIsNULL || _readOnly);
}
// cArrayWidget SLOTS
void cArrayWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
; // NULL/Default
}
else {
qlonglong dummy;
v = _colDescr.set(pModel->stringList(), dummy);
}
setFromWidget(v);
}
void cArrayWidget::selectionChanged(QModelIndex cur, QModelIndex)
{
DBGFN();
if (cur.isValid()) {
actIndex = cur;
PDEB(INFO) << "Current row = " << actIndex.row() << endl;
}
else {
actIndex = QModelIndex();
PDEB(INFO) << "No current row." << endl;
}
setButtons();
}
void cArrayWidget::changed(QString _t)
{
if (_t.isEmpty()) {
last.clear();
pUi->lineEdit->setText(last);
}
else {
bool ok;
switch (_colDescr.eColType) {
case cColStaticDescr::FT_INTEGER_ARRAY:
_t.toLongLong(&ok);
break;
case cColStaticDescr::FT_REAL_ARRAY:
_t.toDouble(&ok);
break;
case cColStaticDescr::FT_TEXT_ARRAY:
ok = true;
break;
default:
EXCEPTION(ENOTSUPP, _colDescr.eColType);
}
if (ok) last = _t;
else pUi->lineEdit->setText(last);
}
setButtons();
}
void cArrayWidget::addRow()
{
*pModel << last;
setFromWidget(pModel->stringList());
setButtons();
}
void cArrayWidget::insRow()
{
int row = actIndex.row();
pModel->insert(last, row);
setFromWidget(pModel->stringList());
setButtons();
}
void cArrayWidget::upRow()
{
QModelIndexList mil = pUi->listView->selectionModel()->selectedRows();
pModel->up(mil);
setFromWidget(pModel->stringList());
setButtons();
}
void cArrayWidget::downRow()
{
QModelIndexList mil = pUi->listView->selectionModel()->selectedRows();
pModel->down(mil);
setFromWidget(pModel->stringList());
setButtons();
}
void cArrayWidget::modRow()
{
int row = actIndex.row();
pModel->modify(last, row);
setFromWidget(pModel->stringList());
}
void cArrayWidget::delRow()
{
QModelIndexList mil = pUi->listView->selectionModel()->selectedIndexes();
if (mil.size() > 0) {
pModel->remove(mil);
}
else {
pModel->pop_back();
}
setFromWidget(pModel->stringList());
setButtons();
}
void cArrayWidget::clrRows()
{
pModel->clear();
setFromWidget(pModel->stringList());
setButtons();
}
void cArrayWidget::doubleClickRow(const QModelIndex & index)
{
const QStringList& sl = pModel->stringList();
int row = index.row();
if (isContIx(sl, row)) {
pUi->lineEdit->setText(sl.at(row));
}
}
/* **************************************** cPolygonWidget **************************************** */
/**
A 'features' mező:\n
:<b>map</b>=<i>\<sql függvény\></i>: Ha megadtuk, és a rekordnak már van ID-je (nem új rekord felvitel), és a megadott SQL függvény a
rekord ID alapján visszaadta egy kép (images.image_id) azonosítóját, akkor feltesz egy plussz gombot, ami megjeleníti
a képet, és azon klikkelve is felvehetünk pontokat.
*/
cPolygonWidget::cPolygonWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par)
, xPrev(), yPrev()
{
_wType = FEW_POLYGON;
_height = 5;
pMapWin = nullptr;
pCImage = nullptr;
epic = NO_ANY_PIC;
parentOrPlace_id = NULL_ID;
selectedRowNum = 0;
xOk = yOk = xyOk = false ;
pUi = new Ui_polygonEd;
pUi->setupUi(this);
pUi->lineEditX->setDisabled(_readOnly);
pUi->lineEditY->setDisabled(_readOnly);
pUi->pushButtonAdd->setDisabled(true);
pUi->pushButtonIns->setDisabled(true);
pUi->pushButtonUp->setDisabled(true);
pUi->pushButtonDown->setDisabled(true);
pUi->pushButtonMod->setDisabled(true);
pUi->pushButtonDel->setDisabled(true);
pUi->pushButtonClr->setDisabled(_readOnly);
pUi->pushButtonPic->setDisabled(true);
pUi->doubleSpinBoxZoom->setDisabled(true);
pUi->doubleSpinBoxZoom->setValue(stZoom);
// Alaprajz előkészítése, ha van
// Ha egy 'places' rekordot szerkesztünk, akkor van egy parent_id mezőnk, amiből megvan az image_id
if (_recDescr == cPlace().descr()) {
cFieldEditBase *p = anotherField(_sParentId);
connect(p, SIGNAL(changedValue(cFieldEditBase*)), this, SLOT(changeId(cFieldEditBase*)));
epic = IS_PLACE_REC;
}
// Másik lehetőség, a features-ben van egy függvénynevünk, ami a rekord id-alapján megadja az image id-t
else {
id2imageFun = _tableShape.feature(_sMap); // Meg van adva a image id-t visszaadó függvlny neve ?
if (id2imageFun.isEmpty() == false) {
cFieldEditBase *p = anotherField(_recDescr.idName());
connect(p, SIGNAL(changedValue(cFieldEditBase*)), this, SLOT(changeId(cFieldEditBase*)));
epic = ID2IMAGE_FUN;
}
}
if (epic != NO_ANY_PIC) {
pCImage = new cImage;
pCImage->setParent(this);
}
if (_value.isValid()) polygon = _value.value<tPolygonF>();
pModel = new cPolygonTableModel(this);
pModel->setPolygon(polygon);
pUi->tableViewPolygon->setModel(pModel);
if (!_readOnly) {
connect(pUi->tableViewPolygon->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(tableSelectionChanged(QItemSelection,QItemSelection)));
connect(pUi->tableViewPolygon, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(tableDoubleclicked(QModelIndex)));
connect(pUi->lineEditX, SIGNAL(textChanged(QString)), this, SLOT(xChanged(QString)));
connect(pUi->lineEditY, SIGNAL(textChanged(QString)), this, SLOT(yChanged(QString)));
connect(pUi->pushButtonAdd, SIGNAL(pressed()), this, SLOT(addRow()));
connect(pUi->pushButtonIns, SIGNAL(pressed()), this, SLOT(insRow()));
connect(pUi->pushButtonUp , SIGNAL(pressed()), this, SLOT(upRow()));
connect(pUi->pushButtonDown,SIGNAL(pressed()), this, SLOT(downRow()));
connect(pUi->pushButtonMod, SIGNAL(pressed()), this, SLOT(modRow()));
connect(pUi->pushButtonDel, SIGNAL(pressed()), this, SLOT(delRow()));
connect(pUi->pushButtonClr,SIGNAL(pressed()), this, SLOT(clearRows()));
connect(pUi->pushButtonPic,SIGNAL(pressed()), this, SLOT(imageOpen()));
connect(pUi->doubleSpinBoxZoom, SIGNAL(valueChanged(double)), this, SLOT(zoom(double)));
(void)getImage();
}
setButtons();
}
cPolygonWidget::~cPolygonWidget()
{
;
}
int cPolygonWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
if (r == 1) {
polygon = _value.value<tPolygonF>();
pModel->setPolygon(polygon);
setButtons();
}
getImage(); // Feltételezi, hogy az rekord ID ha van elöbb lett megadva
return r;
}
/// Ha a feltételek teljesülnek, akkor kitölti a pCImage objektumot.
/// Ha epic == NO_ANY_PIC, akkor nem csinál semmit, és false-val tér vissza.
/// ...
bool cPolygonWidget::getImage(bool refresh)
{
if (epic == NO_ANY_PIC) return false;
if (pCImage == nullptr) EXCEPTION(EPROGFAIL);
qlonglong iid = NULL_ID;
switch (epic) {
case IS_PLACE_REC:
if (parentOrPlace_id != NULL_ID) {
bool ok;
iid = execSqlIntFunction(*pq, &ok, "get_image_id_by_place_id", parentOrPlace_id);
if (!ok || iid == 0) { // Valamiért 0-val tér vissza, NULL helyett :-o
iid = NULL_ID;
}
}
break;
case ID2IMAGE_FUN:
if (parentOrPlace_id != NULL_ID) {
bool ok;
iid = execSqlIntFunction(*pq, &ok, id2imageFun, parentOrPlace_id);
if (!ok || iid == 0) { // Valamiért 0-val tér vissza, NULL helyett :-o
iid = NULL_ID;
}
}
break;
default:
EXCEPTION(EPROGFAIL);
}
if (iid != NULL_ID) {
if ((refresh || iid != pCImage->getId())) {
pCImage->setById(*pq, iid);
pUi->pushButtonPic->setEnabled(true);
}
if (pCImage->dataIsPic()) {
if (pMapWin != nullptr) pMapWin->setImage(*pCImage);
return true;
}
else {
pDelete(pMapWin);
return false;
}
}
else {
pCImage->clear();
pDelete(pMapWin);
pUi->pushButtonPic->setDisabled(true);
return false;
}
}
void cPolygonWidget::drawPolygon()
{
if (pMapWin == nullptr) return;
if (polygon.size() < 3)
pMapWin->clearPolygon();
else
pMapWin->setPolygon(polygon);
lastPos = QPointF(0,0);
}
void cPolygonWidget::modPostprod(QModelIndex select)
{
if (select.isValid()) {
pUi->tableViewPolygon->selectionModel()->select(select, QItemSelectionModel::ClearAndSelect);
}
else {
setButtons();
}
setFromWidget(QVariant::fromValue(polygon));
drawPolygon();
}
void cPolygonWidget::setButtons()
{
bool ne = polygon.size() > 0;
bool one = selectedRowNum == 1;
bool any = selectedRowNum > 0;
pUi->pushButtonAdd ->setEnabled(xyOk && !_readOnly);
pUi->pushButtonIns ->setEnabled(xyOk && one && !_readOnly);
pUi->pushButtonUp ->setEnabled( any && !_readOnly);
pUi->pushButtonDown->setEnabled( any && !_readOnly);
pUi->pushButtonMod ->setEnabled(xyOk && one && !_readOnly);
pUi->pushButtonDel ->setEnabled( ne && !_readOnly);
pUi->pushButtonClr ->setEnabled( ne && !_readOnly);
pUi->pushButtonPic->setEnabled(pCImage->dataIsPic());
pUi->doubleSpinBoxZoom->setEnabled(pMapWin != nullptr);
}
QModelIndex cPolygonWidget::actIndex(eEx __ex)
{
if (__ex && !_actIndex.isValid()) EXCEPTION(EDATA);
return _actIndex;
}
int cPolygonWidget::actRow(eEx __ex)
{
if (__ex && _actRow < 0) EXCEPTION(EDATA);
return _actRow;
}
// ***** cPolygonWidget SLOTS *****
void cPolygonWidget::tableSelectionChanged(const QItemSelection &, const QItemSelection &)
{
QModelIndexList mil = pUi->tableViewPolygon->selectionModel()->selectedRows();
selectedRowNum = mil.size();
if (selectedRowNum == 1) {
_actIndex = mil[0];
_actRow = _actIndex.row();
}
else {
_actIndex = QModelIndex();
_actRow = -1;
}
setButtons();
}
void cPolygonWidget::tableDoubleclicked(const QModelIndex& mi)
{
int row = mi.row();
if (isContIx(polygon, row)) {
QPointF p = polygon[row];
pUi->lineEditX->setText(QString::number(p.x(), 'f', 0));
pUi->lineEditY->setText(QString::number(p.y(), 'f', 0));
}
}
void cPolygonWidget::xChanged(QString _t)
{
if (_t.isEmpty()) {
xPrev.clear();
xOk = false;
}
else {
bool ok;
x = _t.toDouble(&ok);
if (ok) {
xPrev = _t;
xOk = true;
}
else pUi->lineEditX->setText(xPrev);
}
xyOk = xOk && yOk;
setButtons();
}
void cPolygonWidget::yChanged(QString _t)
{
if (_t.isEmpty()) {
yPrev.clear();
xOk = false;
}
else {
bool ok;
y = _t.toDouble(&ok);
if (ok) {
yPrev = _t;
yOk = true;
}
else pUi->lineEditY->setText(yPrev);
}
xyOk = xOk && yOk;
setButtons();
}
void cPolygonWidget::addRow()
{
QPointF pt(x,y);
*pModel << pt;
polygon = pModel->polygon();
int row = polygon.size() -1;
QModelIndex mi = index(row);
modPostprod(mi);
}
void cPolygonWidget::insRow()
{
QPointF pt(x,y);
QModelIndex mi = actIndex();
int row = mi.row();
pModel->insert(pt, row);
polygon = pModel->polygon();
modPostprod(mi);
}
void cPolygonWidget::upRow()
{
QModelIndexList mil = pUi->tableViewPolygon->selectionModel()->selectedRows();
pModel->up(mil);
modPostprod();
}
void cPolygonWidget::downRow()
{
QModelIndexList mil = pUi->tableViewPolygon->selectionModel()->selectedRows();
pModel->down(mil);
modPostprod();
}
void cPolygonWidget::modRow()
{
int row = actRow();
QPointF p(x, y);
pModel->modify(row, p);
modPostprod();
}
void cPolygonWidget::delRow()
{
QModelIndexList mil = pUi->tableViewPolygon->selectionModel()->selectedRows();
if (mil.size()) {
polygon = pModel->remove(mil).polygon();
}
else {
pModel->pop_back();
polygon = pModel->polygon();
}
modPostprod();
}
void cPolygonWidget::clearRows()
{
polygon.clear();
pModel->clear();
modPostprod();
}
void cPolygonWidget::imageOpen()
{
if (pCImage == nullptr) EXCEPTION(EPROGFAIL);
if (pMapWin != nullptr) {
pMapWin->show();
return;
}
pMapWin = new cImagePolygonWidget(!isReadOnly(), _pParentDialog == nullptr ? nullptr : _pParentDialog->pWidget());
pMapWin->setWindowFlags(Qt::Window);
pMapWin->setImage(*pCImage);
pMapWin->show();
pMapWin->setBrush(QBrush(QColor(Qt::red)));
drawPolygon();
pUi->doubleSpinBoxZoom->setEnabled(true);
if (!isReadOnly()) {
// connect(pMapWin, SIGNAL(mousePressed(QPoint)), this, SLOT(imagePoint(QPoint)));
connect(pMapWin, SIGNAL(modifiedPolygon(QPolygonF)), this, SLOT(setted(QPolygonF)));
}
pMapWin->setScale(stZoom);
}
qreal cPolygonWidget::stZoom = 1.0;
void cPolygonWidget::zoom(double z)
{
stZoom = z;
if (pMapWin == nullptr) EXCEPTION(EPROGFAIL);
pMapWin->setScale(z);
}
void cPolygonWidget::destroyedImage(QObject *p)
{
(void)p;
pMapWin = nullptr;
pUi->doubleSpinBoxZoom->setDisabled(true);
}
void cPolygonWidget::changeId(cFieldEditBase *p)
{
(void)p;
parentOrPlace_id = p->getId();
getImage();
}
void cPolygonWidget::setted(QPolygonF pol)
{
polygon.clear();
foreach (QPointF pt, pol) {
polygon << pt;
}
pModel->setPolygon(polygon);
setFromWidget(QVariant::fromValue(polygon));
}
/* **************************************** cFKeyWidget **************************************** */
cFKeyWidget::cFKeyWidget(const cTableShape& _tm, const cTableShapeField& _tf, cRecordFieldRef __fr, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, false, _par)
{
if (_readOnly && _par != nullptr) EXCEPTION(EPROGFAIL, 0, _tf.identifying() + "\n" + __fr.record().identifying());
_wType = FEW_FKEY;
_filter = F_NO;
_height = 1;
pUi = nullptr;
pUiPlace = nullptr;
pUiRPlace = nullptr;
pUiPort = nullptr;
pModel = nullptr;
pRDescr = nullptr;
pSelectPlace= nullptr;
pSelectNode=nullptr;
pFKeyTableShape = nullptr;
owner_ix = NULL_IX;
ownerId = NULL_ID;
ixRPlaceId= NULL_IX;
// Tábla név, amire az aktuális mező, mint kulcs mutat.
QString fkTable = _colDescr.fKeyTable;
// A tábla leíró objektuma.
pRDescr = cRecStaticDescr::get(fkTable);
// A "filter" feature változó alapján az altípus (_filter) kiválasztása
if (_tf.isFeature(_sWidgetFilter)) {
QString sFilter = _tf.feature(_sWidgetFilter);
_height = 2;
if (sFilter.isEmpty()) { // SIMPLE: Az ui-ban definiált egyszerű szűrő az objektum neve alapján
_filter = F_SIMPLE;
}
else if (0 == sFilter.compare(_sPlaces, Qt::CaseInsensitive)) { // Szűrés a hely alapján
if (_sPlaces == fkTable) { // PLACE: A tábla a places, zóna, és minta szerinti szűrés
_filter = F_PLACE;
}
else { // RPLACE: A tábla egy mezője távoli kulcs (kell legyen) a places-re, hely és zóna szerinti szűrés.
ixRPlaceId = pRDescr->toIndex(_sPlaceId, EX_IGNORE);
if (ixRPlaceId == NULL_IX) EXCEPTION(EDATA, 0, tr("A filter=palces feature ebben az esetben nem támogatott : %1").arg(_tf.identifying(false)));
_filter = F_RPLACE;
_height = 3;
}
}
// PORT: Portok: zóna, hely, node alapján szűrés (a node rekordok típusát meg kell adni)
else if (sFilter.startsWith(_sPort + ".")) {
QString pt = sFilter.mid(_sPort.size() + 1);
if (0 == pt.compare(_sAll, Qt::CaseInsensitive)) _pt = P_ALL;
else if (0 == pt.compare(_sNode, Qt::CaseInsensitive)) _pt = P_NODE;
else if (0 == pt.compare(_sSnmp, Qt::CaseInsensitive)) _pt = P_SNMP;
else if (0 == pt.compare(_sPatch,Qt::CaseInsensitive)) _pt = P_PATCH;
else {
EXCEPTION(EDATA, 0, tr("Invalid filter sub type : %1; Field shape : %2").arg(sFilter, _tf.identifying(false)));
}
_filter = F_PORT;
_height = 4;
}
else {
EXCEPTION(EDATA, 0, tr("Invalid filter type : %1; Field shape : %2").arg(sFilter, _tf.identifying(false)));
}
}
// Altípus (_flter) szerinti egyedi initek, form-ok..
switch (_filter) {
case F_NO:
{
pLayout = new QHBoxLayout;
pEditWidget = pComboBox = new QComboBox;
pLayout->addWidget(pEditWidget);
pButtonEdit = new QToolButton;
pButtonEdit->setIcon(cDialogButtons::icons.at(DBT_MODIFY));
pLayout->addWidget(pButtonEdit);
pButtonAdd = new QToolButton;
pButtonAdd->setIcon(cDialogButtons::icons.at(DBT_PUT_IN));
pLayout->addWidget(pButtonAdd);
pButtonRefresh= new QToolButton;
pButtonRefresh->setIcon(cDialogButtons::icons.at(DBT_REFRESH));
pLayout->addWidget(pButtonRefresh);
pButtonInfo = new QToolButton;
pButtonInfo->setIcon(cDialogButtons::icons.at(DBT_REPORT));
pLayout->addWidget(pButtonInfo);
setLayout(pLayout);
}
break;
case F_SIMPLE:
{
pUi = new Ui_fKeyEd;
pUi->setupUi(this);
pLayout = pUi->horizontalLayout2; // A NULL gombot ebbe rakjuk
pEditWidget = pComboBox = pUi->comboBox;
pButtonEdit = pUi->toolButtonEdit;
pButtonAdd = pUi->toolButtonAdd;
pButtonRefresh= pUi->toolButtonRefresh;
pButtonInfo = pUi->toolButtonInfo;
pUi->toolButtonEdit->setDisabled(true);
}
break;
case F_PLACE:
{
pUiPlace = new Ui_placeEd;
pUiPlace->setupUi(this);
pLayout = pUiPlace->horizontalLayout2; // A NULL gombot ebbe rakjuk
pSelectPlace = new cSelectPlace(pUiPlace->comboBoxZone, pUiPlace->comboBoxPlace, pUiPlace->lineEditPlacePattern, _sNul, this);
pSelectPlace->setPlaceRefreshButton(pUiPlace->toolButtonRefresh);
pSelectPlace->setPlaceInsertButton(pUiPlace->toolButtonPlaceAdd);
pSelectPlace->setPlaceEditButton(pUiPlace->toolButtonPlaceEdit);
pSelectPlace->setPlaceInfoButton(pUiPlace->toolButtonPlaceInfo);
pEditWidget = pComboBox = pUiPlace->comboBoxPlace;
pButtonEdit = pUiPlace->toolButtonPlaceEdit;
pButtonAdd = pUiPlace->toolButtonPlaceAdd;
pButtonRefresh= pUiPlace->toolButtonRefresh;
pButtonInfo = nullptr;
// nodeName -> place
bool n2p = !cSysParam::getTextSysParam(*pq, _sNode2Place).isEmpty() && _tf.isFeature(_sNode2Place);
if (n2p) {
connect(pUiPlace->toolButtonNode2Place, SIGNAL(clicked()), this, SLOT(node2place()));
}
else {
pUiPlace->toolButtonNode2Place->hide();
}
}
break;
case F_RPLACE:
{
pUiRPlace = new Ui_fKeyPlaceEd;
pUiRPlace->setupUi(this);
pLayout = pUiRPlace->horizontalLayout2; // A NULL gombot ebbe rakjuk
pSelectPlace = new cSelectPlace(pUiRPlace->comboBoxZone, pUiRPlace->comboBoxPlace, pUiRPlace->lineEditPlacePattern, _sNul, this);
pSelectPlace->setPlaceRefreshButton(pUiRPlace->toolButtonPlaceRefresh);
pSelectPlace->setPlaceInsertButton(pUiRPlace->toolButtonPlaceAdd);
pSelectPlace->setPlaceEditButton(pUiRPlace->toolButtonPlaceEdit);
pSelectPlace->setPlaceInfoButton(pUiRPlace->toolButtonPlaceInfo);
pEditWidget = pComboBox = pUiRPlace->comboBox;
pButtonEdit = pUiRPlace->toolButtonEdit;
pButtonAdd = pUiRPlace->toolButtonAdd;
pButtonRefresh= pUiRPlace->toolButtonRefresh;
pButtonInfo = pUiRPlace->toolButtonInfo;
}
break;
case F_PORT:
{
pUiPort = new Ui_fKeyPortEd;
pUiPort->setupUi(this);
pLayout = pUiPort->horizontalLayout2; // A NULL gombot ebbe rakjuk
pSelectNode = new cSelectNode(pUiPort->comboBoxZone, pUiPort->comboBoxPlace, pUiPort->comboBoxNode,
pUiPort->lineEditPlacePattern, pUiPort->lineEditNodePattern, _sNul, _sNul, this);
pSelectNode->setPlaceRefreshButton(pUiPort->toolButtonRefresh);
pSelectNode->setPlaceInsertButton(pUiPort->toolButtonPlaceAdd);
pSelectNode->setPlaceEditButton(pUiPort->toolButtonPlaceEdit);
pSelectNode->setPlaceInfoButton(pUiPort->toolButtonPlaceInfo);
pEditWidget = pComboBox = pUiPort->comboBox;
pButtonEdit = pUiPort->toolButtonEdit;
pButtonAdd = pUiPort->toolButtonAdd;
pButtonRefresh= pUiPort->toolButtonRefresh;
pButtonInfo = pUiPort->toolButtonInfo;
}
break;
default:
EXCEPTION(EPROGFAIL);
}
if (_filter != F_PLACE) {
connect(pButtonInfo, SIGNAL(clicked()), this, SLOT(info()));
pModel = new cRecordListModel(*pRDescr, this);
if (_filter == F_PORT) {
switch (_pt) {
case P_ALL:
break;
case P_PATCH:
pSelectNode->setNodeModel(new cRecordListModel(_sPatchs), TS_FALSE);
break;
case P_NODE:
pSelectNode->setNodeModel(new cRecordListModel(_sNodes), TS_FALSE);
break;
case P_SNMP:
pSelectNode->setNodeModel(new cRecordListModel(_sSnmpDevices), TS_FALSE);
break;
default:
EXCEPTION(EPROGFAIL);
}
}
// Ha nincs név mező...
if (pRDescr->nameIndex(EX_IGNORE) < 0) pModel->setToNameF(_colDescr.fnToName);
pModel->joinWith(pComboBox);;
pFKeyTableShape = new cTableShape();
// Dialógus leíró neve a feature mezőben
QString tsn = _fieldShape.feature(_sDialog);
// ha ott nincs megadva, akkor a megjelenítő neve azonos a tulajdonság rekord nevével
if (tsn.isEmpty()) tsn = _colDescr.fKeyTable;
if (pFKeyTableShape->fetchByName(tsn)) { // Ha meg tudjuk jeleníteni
// Nem lehet öröklés !!
qlonglong tit = pFKeyTableShape->getId(_sTableInheritType);
if (tit != TIT_NO && tit != TIT_ONLY) EXCEPTION(EDATA);
pFKeyTableShape->fetchFields(*pq);
pButtonAdd->setEnabled(true);
connect(pButtonEdit, SIGNAL(pressed()), this, SLOT(modifyF()));
connect(pButtonAdd, SIGNAL(pressed()), this, SLOT(insertF()));
}
else {
pDelete(pFKeyTableShape);
pButtonEdit->setDisabled(true);
pButtonAdd->setDisabled(true);
}
connect(pButtonRefresh, SIGNAL(clicked()), this, SLOT(refresh()));
}
QString owner = _fieldShape.feature(_sOwner); //
if (!owner.isEmpty()) {
if (_filter != F_NO) EXCEPTION(EDATA, 0, tr("A filter és az owner feature együttes használata nem támogatott : %1").arg(_tf.identifying(false)));
if (0 == owner.compare(_sSelf, Qt::CaseInsensitive)) { // TREE
if (_pParentDialog == nullptr) {
QAPPMEMO(tr("Invalid feature %1.%2 'owner=self', invalid context.").arg(_tableShape.getName(), _fieldShape.getName()), RS_CRITICAL | RS_BREAK);
}
owner_ix = __fr.record().descr().ixToOwner(EX_IGNORE); // ??????!!!!!
if (owner_ix < 0) {
QAPPMEMO(tr("Invalid feature %1.%2 'owner=self', owner id index not found.").arg(_tableShape.getName(), _fieldShape.getName()), RS_CRITICAL | RS_BREAK);
}
ownerId = NULL_ID;
if (_pParentDialog->_pOwnerTable != nullptr) {
ownerId = _pParentDialog->_pOwnerTable->owner_id;
}
else if (_pParentDialog->_pOwnerDialog != nullptr) {
EXCEPTION(ENOTSUPP);
}
if (ownerId == NULL_ID) {
EXCEPTION(EDATA);
}
pModel->_setOwnerId(ownerId, __fr.record().descr().columnName(owner_ix));
}
else {
// Ha nincs parent dialog, akkor ez nem fog menni
if (_pParentDialog == nullptr) EXCEPTION(EDATA, -1, _tableShape.identifying(false));
cRecordDialog *pDialog = dynamic_cast<cRecordDialog *>(_pParentDialog);
if (pDialog == nullptr) EXCEPTION(EDATA, -1, _tableShape.identifying(false));
QList<cFieldEditBase *>::iterator it = pDialog->fields.begin(); // A hivatkozott mező a jelenlegi elött kell legyen!!
for (;it < pDialog->fields.end(); ++it) {
if (0 == (*it)->_fieldShape.getName().compare(owner, Qt::CaseInsensitive)) {
cFieldEditBase *pfeb = *it;
ownerId = pfeb->getId();
connect(pfeb, SIGNAL(changedValue(cFieldEditBase*)), this, SLOT(modifyOwnerId(cFieldEditBase*)));
pModel->_setOwnerId(ownerId, owner);
break;
}
}
if (it >= pDialog->fields.end()) EXCEPTION(EDATA);
}
if (_tf.isFeature(_sWidgetFilter)) {
_filter = F_SIMPLE;
_height = 2;
}
}
setConstFilter(); // 'refine'
actId = qlonglong(__fr);
if (_nullable || _hasDefault) {
bool isNull = __fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
switch (_filter) {
case F_NO: // Nincs szűrés
connect(pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setFromEdit(int)));
pModel->setFilter(_sNul, OT_ASC, FT_NO);
break;
case F_SIMPLE: // Egyszerű szúrés minta alapján
connect(pUi->lineEditFilter, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString)));
connect(pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setFromEdit(int)));
pModel->setFilter(_sNul, OT_ASC, FT_LIKE);
break;
case F_PLACE: // Hely
connect(pSelectPlace, SIGNAL(placeIdChanged(qlonglong)), this, SLOT(setFromEdit(qlonglong)));
break;
case F_RPLACE: // Szűrés: helyre
connect(pSelectPlace, SIGNAL(placeIdChanged(qlonglong)), this, SLOT(setPlace(qlonglong)));
connect(pUiRPlace->lineEditPattern, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString)));
connect(pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setFromEdit(int)));
pModel->_setOwnerId(pSelectPlace->currentPlaceId(), _sPlaceId, TS_TRUE, "is_parent_place");
pModel->setFilter(_sNul, OT_ASC, FT_LIKE);
break;
case F_PORT: // Port
connect(pSelectNode, SIGNAL(nodeIdChanged(qlonglong)), this, SLOT(setNode(qlonglong)));
connect(pUiPort->lineEditPattern, SIGNAL(textChanged(QString)), this, SLOT(setFilter(QString)));
connect(pComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setFromEdit(int)));
pModel->setFilter(_sNul, OT_ASC, FT_LIKE);
break;
default:
EXCEPTION(EPROGFAIL);
}
// Az aktuális érték megjelenítése
setWidget();
}
cFKeyWidget::~cFKeyWidget()
{
pDelete(pFKeyTableShape);
}
bool cFKeyWidget::setWidget()
{
setButtons();
if (pNullButton != nullptr) pNullButton->setChecked(_actValueIsNULL);
if (!_actValueIsNULL) {
if (pModel != nullptr) {
int ix;
if (_filter == F_PORT) {
QSqlQuery q = getQuery();
cNPort po;
po.setById(q, actId);
qlonglong nid = po.getId(_sNodeId);
pSelectNode->setCurrentNode(nid);
pModel->setOwnerId(nid, _sNodeId, TS_TRUE);
ix = pModel->indexOf(actId);
}
else {
ix = pModel->indexOf(actId);
if (ix < 0) {
if (pSelectPlace != nullptr) {
pSelectPlace->setCurrentZone(ALL_PLACE_GROUP_ID);
pSelectPlace->setCurrentZone(NULL_ID);
}
else if (pSelectNode) {
cPatch n;
if (!n.fetchById(actId)) return false;
pSelectNode->setCurrentNode(n.getId(_sNodeId));
}
else return false;
ix = pModel->indexOf(actId);
}
}
if (ix < 0) return false;
pComboBox->setCurrentIndex(ix);
}
else if (pSelectPlace != nullptr) {
pSelectPlace->setCurrentPlace(actId);
}
else {
EXCEPTION(EPROGFAIL);
}
}
return true;
}
int cFKeyWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
actId = _colDescr.toId(_value);
if (1 == r) {
// ? _refresh();
if (pSelectPlace != nullptr) {
pSelectPlace->refresh();
}
if (!setWidget()) r = -1;
}
return r;
}
QString cFKeyWidget::getName() const
{
QString r;
if (pModel != nullptr) {
r = pModel->currendName();
}
else if (pSelectPlace != nullptr) {
r = pSelectPlace->currentPlaceName();
}
else {
EXCEPTION(EPROGFAIL);
}
return r;
}
void cFKeyWidget::setFromEdit(int i)
{
if (pModel == nullptr) EXCEPTION(EPROGFAIL);
qlonglong id = pModel->atId(i);
setFromWidget(id);
if (pNullButton != nullptr && _actValueIsNULL) {
pNullButton->setChecked(false);
disableEditWidget(TS_FALSE);
}
}
void cFKeyWidget::setFromEdit(qlonglong id)
{
setFromWidget(id);
}
void cFKeyWidget::setButtons()
{
bool null = pFKeyTableShape == nullptr;
bool disa = _readOnly || null;
switch (_filter) {
case F_NO:
case F_SIMPLE:
pButtonEdit->setDisabled(_actValueIsNULL || disa || !lanView::isAuthorized(pFKeyTableShape->getId(_sViewRights)));
pButtonAdd->setDisabled( disa || !lanView::isAuthorized(pFKeyTableShape->getId(_sInsertRights)));
pButtonInfo->setDisabled(_actValueIsNULL || null || !lanView::isAuthorized(pFKeyTableShape->getId(_sViewRights)));
break;
case F_PLACE: // Rights ???!!!
pUiPlace->toolButtonPlaceEdit->setDisabled(_actValueIsNULL || disa);
pUiPlace->toolButtonPlaceAdd->setDisabled(disa);
break;
case F_RPLACE:
pUiRPlace->toolButtonPlaceEdit->setDisabled(_actValueIsNULL || disa);
pUiRPlace->toolButtonPlaceAdd->setDisabled(disa);
pButtonAdd->setDisabled( disa || !lanView::isAuthorized(pFKeyTableShape->getId(_sInsertRights)));
pButtonInfo->setDisabled(_actValueIsNULL || null || !lanView::isAuthorized(pFKeyTableShape->getId(_sViewRights)));
break;
case F_PORT:
pButtonEdit->setDisabled(_actValueIsNULL || disa || !lanView::isAuthorized(pFKeyTableShape->getId(_sViewRights)));
pButtonAdd->setDisabled( disa || !lanView::isAuthorized(pFKeyTableShape->getId(_sEditRights)));
pButtonInfo->setDisabled(_actValueIsNULL || null || !lanView::isAuthorized(pFKeyTableShape->getId(_sViewRights)));
break;
default:
EXCEPTION(EPROGFAIL);
}
}
void cFKeyWidget::disableEditWidget(eTristate tsf)
{
cFieldEditBase::disableEditWidget(tsf);
switch (_filter) {
case F_NO:
break;
case F_SIMPLE:
pUi->label->setVisible(!_actValueIsNULL);
// pUi->lineEditFilter->setVisible(!_actValueIsNULL);
pUi->lineEditFilter->setDisabled(_actValueIsNULL);
break;
case F_PLACE:
if (pSelectPlace == nullptr) EXCEPTION(EPROGFAIL);
pSelectPlace->setDisabled(_actValueIsNULL);
break;
case F_RPLACE:
if (pSelectPlace == nullptr) EXCEPTION(EPROGFAIL);
pSelectPlace->setDisabled(_actValueIsNULL);
pUiRPlace->lineEditPattern->setDisabled(_actValueIsNULL);
break;
case F_PORT:
if (pSelectNode == nullptr) EXCEPTION(EPROGFAIL);
pSelectNode->setDisabled(_actValueIsNULL);
pUiPort->lineEditPattern->setDisabled(_actValueIsNULL);
break;
default:
EXCEPTION(EPROGFAIL);
}
setButtons();
}
bool cFKeyWidget::setConstFilter()
{
if (_pParentDialog != nullptr) {
QStringList constFilter = _fieldShape.features().slValue(_sRefine);
if (!constFilter.isEmpty() && !constFilter.first().isEmpty()) {
const cRecord *pr = _pParentDialog->_pRecord;
QString sql = constFilter.first();
constFilter.pop_front();
foreach (QString s, constFilter) {
if (s.isEmpty()) EXCEPTION(EDATA);
switch (s[0].toLatin1()) {
case '#': // int
s = s.mid(1);
s = pr->isNull(s) ? _sNULL : QString::number(pr->getId(s));
break;
case '&': // string
s = s.mid(1);
s = pr->isNull(s) ? _sNULL : quoted(pr->getName(s));
break;
default:
s = pr->getName();
break;
}
sql = sql.arg(s);
}
if (pModel == nullptr) EXCEPTION(EPROGFAIL);
pModel->setConstFilter(sql, FT_SQL_WHERE);
return true;
}
}
return false;
}
void cFKeyWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
; // NULL/Default
}
else {
if (pModel != nullptr) {
int ix = pComboBox->currentIndex();
v = pModel->atId(ix);
}
else if (pSelectPlace != nullptr) {
v = pSelectPlace->currentPlaceId();
}
else {
EXCEPTION(EPROGFAIL);
}
}
setFromWidget(v);
}
void cFKeyWidget::setFilter(const QString& _s)
{
if(pModel == nullptr) EXCEPTION(EPROGFAIL);
qlonglong id;
int ix = pComboBox->currentIndex();
id = pModel->atId(ix);
if (_s.isNull()) {
pModel->setFilter(QVariant(), OT_DEFAULT, FT_NO);
}
else {
QString s = _s;
if (!s.contains('?') && !s.contains('%')) s = '%' + s + '%';
pModel->setFilter(s, OT_DEFAULT, FT_LIKE);
}
ix = pModel->indexOf(id);
if (ix >= 0) pComboBox->setCurrentIndex(ix);
_setFromEdit();
}
void cFKeyWidget::setPlace(qlonglong _pid)
{
if(pModel == nullptr) EXCEPTION(EPROGFAIL);
qlonglong id;
int ix = pComboBox->currentIndex();
id = pModel->atId(ix);
pModel->setOwnerId(_pid, _sPlaceId, TS_TRUE);
ix = pModel->indexOf(id);
if (ix >= 0) pComboBox->setCurrentIndex(ix);
_setFromEdit();
}
void cFKeyWidget::setNode(qlonglong _nid)
{
if(pModel == nullptr) EXCEPTION(EPROGFAIL);
qlonglong id;
int ix = pComboBox->currentIndex();
id = pModel->atId(ix);
pModel->setOwnerId(_nid, _sNodeId, TS_TRUE);
ix = pModel->indexOf(id);
if (ix >= 0) pComboBox->setCurrentIndex(ix);
_setFromEdit();
}
/// Egy tulajdosnság kulcs mezőben vagyunk.
/// Be szertnénk szúrni egy tulajdonság rekordot
void cFKeyWidget::insertF()
{
if (pModel != nullptr && pFKeyTableShape != nullptr && lanView::isAuthorized(pFKeyTableShape->getId(_sInsertRights))) {
cRecordDialog *pDialog = new cRecordDialog(*pFKeyTableShape, ENUM2SET2(DBT_OK, DBT_CANCEL), true, _pParentDialog);
while (1) {
int keyId = pDialog->exec(false);
if (keyId == DBT_CANCEL) break;
if (!pDialog->accept()) continue;
if (!cErrorMessageBox::condMsgBox(pDialog->record().tryInsert(*pq, TS_NULL, true))) continue;
pModel->setFilter(_sNul, OT_ASC, FT_NO); // Refresh combo box
cRecord& r = pDialog->record();
qlonglong id = r.getId();
int ix = pModel->indexOf(id);
pUi->comboBox->setCurrentIndex(ix);
break;
}
pDialog->close();
delete pDialog;
}
// else {
// EXCEPTION(EPROGFAIL);
// }
}
void cFKeyWidget::modifyF()
{
if (pModel != nullptr && pFKeyTableShape != nullptr && lanView::isAuthorized(pFKeyTableShape->getId(_sViewRights))) {
cRecordAny rec(pRDescr);
cRecordDialog *pDialog = new cRecordDialog(*pFKeyTableShape, ENUM2SET2(DBT_OK, DBT_CANCEL), true, _pParentDialog);
int cix = pComboBox->currentIndex();
qlonglong id = pModel->atId(cix);
if (!rec.fetchById(*pq, id)) return;
pDialog->restore(&rec);
while (1) {
int keyId = pDialog->exec(false);
if (keyId == DBT_CANCEL) break;
if (!pDialog->accept()) continue;
if (!cErrorMessageBox::condMsgBox(pDialog->record().tryUpdateById(*pq, TS_NULL, true))) continue;
pModel->setFilter(_sNul, OT_ASC, FT_NO); // Refresh combo box
pComboBox->setCurrentIndex(pModel->indexOf(rec.getId()));
break;
}
pDialog->close();
delete pDialog;
}
// else {
// EXCEPTION(EPROGFAIL);
// }
}
// Megváltozott az owner id
void cFKeyWidget::modifyOwnerId(cFieldEditBase* pof)
{
if (pModel == nullptr) EXCEPTION(EPROGFAIL);
ownerId = pof->getId();
pModel->setOwnerId(ownerId);
pComboBox->setCurrentIndex(0);
setFromEdit(0);
}
void cFKeyWidget::_refresh()
{
if (_pParentDialog != nullptr) {
QStringList constFilter = _fieldShape.features().slValue(_sRefine);
if (!constFilter.isEmpty() && !constFilter.first().isEmpty()) {
// ? if (pUi == nullptr) EXCEPTION(EPROGFAIL);
QString sql = constFilter.first();
constFilter.pop_front();
foreach (QString s, constFilter) {
if (s.isEmpty()) EXCEPTION(EDATA);
qlonglong id;
switch (s[0].toLatin1()) {
case '#': // int
s = s.mid(1);
id = (*_pParentDialog)[s]->getId();
s = id == NULL_ID ? _sNULL : QString::number(id);
break;
case '&': // string
s = s.mid(1);
if ((*_pParentDialog)[s]->get().isNull()) {
s = _sNULL;
}
else {
s = (*_pParentDialog)[s]->getName();
}
break;
default:
s = (*_pParentDialog)[s]->getName();
break;
}
sql = sql.arg(s);
}
if (pModel == nullptr) EXCEPTION(EPROGFAIL);
pModel->setConstFilter(sql, FT_SQL_WHERE);
}
}
pComboBox->blockSignals(true);
pModel->setFilter();
pComboBox->blockSignals(false);
}
void cFKeyWidget::refresh()
{
if (pModel == nullptr) EXCEPTION(EPROGFAIL);
qlonglong id = pModel->currendId();
_refresh();
int ix = pModel->indexOf(id);
if (ix < 0) ix = 0;
pComboBox->setCurrentIndex(ix);
}
void cFKeyWidget::node2place()
{
if (_pParentDialog == nullptr) {
if (pParentBatchEdit != nullptr) {
pParentBatchEdit->done(FKEY_BATCHEDIT);
}
}
else {
QString nodeName =_pParentDialog->_pRecord->getName();
cPlace place;
place.nodeName2place(*pq, nodeName);
qlonglong pid = place.getId();
if (pid != NULL_ID) pSelectPlace->setCurrentPlace(pid);
}
}
void cFKeyWidget::info()
{
qlonglong id = getId();
if (id != NULL_ID) {
cRecord *po = new cRecordAny(pRDescr);
po->setById(*pq, id);
QString name = pFKeyTableShape->feature(_sReport);
if (name.isEmpty()) name = pRDescr->tableName();
tStringPair sp = htmlReport(*pq, *po, name, pFKeyTableShape);
delete po;
popupReportWindow(_pParentDialog->pWidget(), sp.second, sp.first);
}
}
/* **************************************** cDateWidget **************************************** */
cDateWidget::cDateWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef _fr, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, 0, _par)
{
_wType = FEW_DATE;
pLayout = new QHBoxLayout;
setLayout(pLayout);
pEditWidget = pDateEdit = new QDateEdit;
pLayout->addWidget(pDateEdit);
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
connect(pDateEdit, SIGNAL(dateChanged(QDate)), this, SLOT(setFromEdit(QDate)));
}
cDateWidget::~cDateWidget()
{
;
}
int cDateWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && !_actValueIsNULL) {
pDateEdit->setDate(_value.toDate());
}
return r;
}
void cDateWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
;
}
else {
v = pDateEdit->date();
}
setFromWidget(v);
}
void cDateWidget::setFromEdit(QDate d)
{
setFromWidget(QVariant(d));
}
/* **************************************** cTimeWidget **************************************** */
cTimeWidget::cTimeWidget(const cTableShape& _tm, const cTableShapeField& _tf, cRecordFieldRef _fr, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, false, _par)
{
if (_readOnly && _par != nullptr) EXCEPTION(EPROGFAIL, 0, _tf.identifying() + "\n" + _fr.record().identifying());
_wType = FEW_TIME;
pLayout = new QHBoxLayout;
setLayout(pLayout);
pEditWidget = pTimeEdit = new QTimeEdit;
pFirstButton = new QToolButton();
pLastButton = new QToolButton();
pTimeEdit->setDisplayFormat("hh:mm:ss.zzz");
pFirstButton->setIcon(QIcon("://icons/first.ico"));
pLastButton ->setIcon(QIcon("://icons/last.ico"));
pLayout->addWidget(pTimeEdit);
pLayout->addWidget(pFirstButton);
pLayout->addWidget(pLastButton);
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
connect(pTimeEdit, SIGNAL(timeChanged(QTime)), this, SLOT(setFromEdit(QTime)));
connect(pFirstButton, SIGNAL(clicked()), this, SLOT(setFirst()));
connect(pLastButton, SIGNAL(clicked()), this, SLOT(setLast()));
}
cTimeWidget::~cTimeWidget()
{
;
}
int cTimeWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && !_actValueIsNULL) {
pTimeEdit->setTime(_value.toTime());
}
return r;
}
void cTimeWidget::disableEditWidget(eTristate tsf)
{
cFieldEditBase::disableEditWidget(tsf);
pFirstButton->setDisabled(_actValueIsNULL);
pLastButton ->setDisabled(_actValueIsNULL);
}
void cTimeWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
;
}
else {
v = pTimeEdit->time();
}
setFromWidget(v);
}
void cTimeWidget::setFromEdit(QTime d)
{
setFromWidget(QVariant(d));
}
void cTimeWidget::setFirst()
{
setName("00:00");
}
void cTimeWidget::setLast()
{
setName("23:59:59.999");
}
/* **************************************** cDateTimeWidget **************************************** */
cDateTimeWidget::cDateTimeWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef _fr, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr,false, _par)
{
if (_readOnly && _par != nullptr) EXCEPTION(EPROGFAIL, 0, _tf.identifying() + "\n" + _fr.record().identifying());
pLayout = new QHBoxLayout;
setLayout(pLayout);
_wType = FEW_DATE_TIME;
pEditWidget = pDateTimeEdit = new QDateTimeEdit;
pLayout->addWidget(pEditWidget);
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
connect(pDateTimeEdit, SIGNAL(dateTimeChanged(QDateTime)), this, SLOT(setFromEdit(QDateTime)));
}
cDateTimeWidget::~cDateTimeWidget()
{
;
}
int cDateTimeWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && !_actValueIsNULL) {
pDateTimeEdit->setDateTime(_value.toDateTime());
}
return r;
}
void cDateTimeWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
;
}
else {
v = pDateTimeEdit->dateTime();
}
setFromWidget(v);
}
void cDateTimeWidget::setFromEdit(QDateTime d)
{
setFromWidget(QVariant(d));
}
/* **************************************** cIntervalWidget **************************************** */
cIntervalWidget::cIntervalWidget(const cTableShape& _tm, const cTableShapeField& _tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
{
_wType = FEW_INTERVAL;
pLayout = new QHBoxLayout;
setLayout(pLayout);
pLineEditDay = new QLineEdit;
pLayout->addWidget(pLineEditDay);
pLabelDay = new QLabel(tr(" Nap "));
pLayout->addWidget(pLabelDay);
pTimeEdit = new QTimeEdit;
pLayout->addWidget(pTimeEdit);
pTimeEdit->setDisplayFormat("HH:mm:ss.zzz");
if (_readOnly) {
pValidatorDay = nullptr;
view();
pLineEditDay->setReadOnly(true);
pTimeEdit->setReadOnly(true);
}
else {
pValidatorDay = new QIntValidator(0, 9999, this);
pLineEditDay->setValidator(pValidatorDay);
view();
connect(pLineEditDay, SIGNAL(editingFinished()), this, SLOT(_setFromEdit()));
connect(pTimeEdit, SIGNAL(editingFinished()), this, SLOT(_setFromEdit()));
}
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cIntervalWidget::disableEditWidget(bool2ts(isNull));
}
}
cIntervalWidget::~cIntervalWidget()
{
;
}
void cIntervalWidget::disableEditWidget(eTristate tsf)
{
setBool(_actValueIsNULL, tsf);
pLineEditDay->setDisabled(_actValueIsNULL);
pLabelDay->setDisabled(_actValueIsNULL);
pTimeEdit->setDisabled(_actValueIsNULL);
}
qlonglong cIntervalWidget::getFromWideget() const
{
qlonglong r = NULL_ID;
if (!_actValueIsNULL) {
QTime t = pTimeEdit->time();
r = pLineEditDay->text().toInt();
r = (r * 24) + t.hour();
r = (r * 60) + t.minute();
r = (r * 60) + t.second();
r = (r * 1000) + t.msec();
}
return r;
}
int cIntervalWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && !_actValueIsNULL) view();
return r;
}
void cIntervalWidget::view()
{
if (_value.isValid()) {
qlonglong v = _colDescr.toId(_value);
int msec = v % 1000; v /= 1000;
int sec = v % 60; v /= 60;
int minute = v % 60; v /= 60;
int hour = v % 24; v /= 24;
QTime t(hour, minute, sec, msec);
pTimeEdit->setTime(t);
pLineEditDay->setText(QString::number(v));
}
else {
pTimeEdit->clear();
pLineEditDay->clear();
}
}
void cIntervalWidget::_setFromEdit()
{
setFromWidget(getFromWideget());
}
/* **************************************** cBinaryWidget **************************************** */
cBinaryWidget::cBinaryWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par)
, data()
{
_init();
bool z = _value.isNull();
if (!z) data = _value.toByteArray();
pRadioButtonNULL->setChecked(z);
setViewButtons();
}
cBinaryWidget::~cBinaryWidget()
{
pDelete(pCImage);
if (!pCheckBoxDetach->isChecked()) {
pDelete(pImageWidget);
}
}
void cBinaryWidget::_init()
{
_wType = FEW_BINARY;
pLayout = nullptr;
pRadioButtonNULL= nullptr;
pUpLoadButton = nullptr;
pDownLoadButton = nullptr;
pViewButton = nullptr;
pDoubleSpinBoxZoom= nullptr;
pImageWidget = nullptr;
pCImage = nullptr;
const cRecStaticDescr& cidescr = cImage().descr();
isCImage = _recDescr == cidescr; // éppen egy cImage objektumot szerkesztünk
pLayout = new QHBoxLayout;
setLayout(pLayout);
pRadioButtonNULL = new QRadioButton(_sNULL, this);
pRadioButtonNULL->setDisabled(_readOnly);
pLayout->addWidget(pRadioButtonNULL);
if (!_readOnly) {
pUpLoadButton = new QPushButton(QIcon("://icons/db_comit.ico"), tr("Feltölt"));
pUpLoadButton->setToolTip(tr("A bináris adat ill. kép betöltése egy fájlból."));
pLayout->addWidget(pUpLoadButton);
connect(pRadioButtonNULL, SIGNAL(clicked(bool)), this, SLOT(nullChecked(bool)));
connect(pUpLoadButton, SIGNAL(pressed()), this, SLOT(loadDataFromFile()));
}
pDownLoadButton = new QPushButton(QIcon("://icons/db_update.ico"), tr("Letölt"));
pUpLoadButton->setToolTip(tr("A bináris adat ill. kép letöltése egy fájlba."));
pLayout->addWidget(pDownLoadButton);
connect(pDownLoadButton, SIGNAL(pressed()), this, SLOT(saveDataToFile()));
if (isCImage) { // Ha egy cImage objektum része, akkor meg tudjuk jeleníteni.
pViewButton = new QPushButton(QIcon("://icons/view-preview.ico"), tr("Megjelenít"));
pViewButton->setDefault(true);
pLayout->addWidget(pViewButton);
pLayout->addWidget(new QLabel(tr("Nagyít :")));
pDoubleSpinBoxZoom = new QDoubleSpinBox;
pDoubleSpinBoxZoom->setValue(cImageWidget::scale);
pDoubleSpinBoxZoom->setMinimum(0.1);
pDoubleSpinBoxZoom->setMaximum(10);
pDoubleSpinBoxZoom->setStepType(QAbstractSpinBox::AdaptiveDecimalStepType);
pLayout->addWidget(pDoubleSpinBoxZoom);
connect(pViewButton, SIGNAL(pressed()), this, SLOT(viewPic()));
// Ha jó a mező sorrend, akkor ezek a mezők már megvannak.
connect(anotherField(_sImageType), SIGNAL(changedValue(cFieldEditBase*)), this, SLOT(changedAnyField(cFieldEditBase*)));
pCheckBoxDetach = new QCheckBox(tr("Leválaszt"));
pCheckBoxDetach->setToolTip(tr("A megjelenített kép leválasztása a dialógusról. A kép a dialógus bezárása után is nyitva marad."));
pCheckBoxDetach->setChecked(false);
pCheckBoxDetach->setDisabled(true);
pLayout->addWidget(pCheckBoxDetach);
}
}
bool cBinaryWidget::setCImage()
{
setNull();
if (!isCImage) EXCEPTION(EPROGFAIL); // Ha nem cImage a rekord, akkor hogy kerültünk ide ?!
if (pCImage == nullptr) pCImage = new cImage;
pCImage->clear();
if (data.size() > 0 && !pRadioButtonNULL->isChecked()) {
pCImage->setName(_sImageName, anotherField(_sImageName)->getName());
pCImage->setType(anotherField(_sImageType)->getName());
pCImage->setImage(data);
if (pCImage->dataIsPic()) {
pViewButton->setEnabled(true);
if (pImageWidget) {
closePic();
openPic();
}
return true;
}
}
if (pImageWidget) {
closePic();
}
return false;
}
void cBinaryWidget::setViewButtons()
{
if (pViewButton == nullptr) return;
bool z = data.isEmpty() || !setCImage();
if (z) {
pViewButton->setDisabled(true);
}
}
int cBinaryWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1) {
bool z = v.isNull();
pRadioButtonNULL->setChecked(z);
if (z) {
data.clear();
}
else {
data = _value.toByteArray();
}
}
if (r != 0) setCImage();
return r;
}
void cBinaryWidget::loadDataFromFile()
{
QString fn = QFileDialog::getOpenFileName(this);
if (fn.isEmpty()) return;
QFile f(fn);
if (!cMsgBox::tryOpenRead(f, this)) return;
data = f.readAll();
pRadioButtonNULL->setChecked(false);
pRadioButtonNULL->setCheckable(true);
setFromWidget(QVariant(data));
setCImage();
f.close();
}
void cBinaryWidget::saveDataToFile()
{
QString fn = QFileDialog::getSaveFileName(this);
if (fn.isEmpty()) return;
QFile f(fn);
if (!cMsgBox::tryOpenWrite(f, this)) return;
f.write(data);
f.close();
}
void cBinaryWidget::setNull()
{
if (data.isEmpty()) {
pRadioButtonNULL->setChecked(true);
pRadioButtonNULL->setDisabled(true);
}
else {
pRadioButtonNULL->setEnabled(true);
}
bool f = pRadioButtonNULL->isChecked();
if (f) {
_value.clear();
}
}
void cBinaryWidget::nullChecked(bool checked)
{
(void)checked;
setCImage();
}
void cBinaryWidget::closePic()
{
if (pImageWidget == nullptr) EXCEPTION(EPROGFAIL);
pDoubleSpinBoxZoom->setDisabled(true);
pImageWidget->close();
pDelete(pImageWidget);
pCheckBoxDetach->setChecked(false);
pCheckBoxDetach->setDisabled(true);
}
void cBinaryWidget::openPic()
{
if (pImageWidget) EXCEPTION(EPROGFAIL);
cImageWidget::scale = pDoubleSpinBoxZoom->value();
pImageWidget = new cImageWidget();
pImageWidget->setImage(*pCImage);
connect(pDoubleSpinBoxZoom, SIGNAL(valueChanged(double)), pImageWidget, SLOT(zoom(double)));
// connect(pImageWidget, SIGNAL(destroyed(QObject*)), this, SLOT(destroyedImage(QObject*)));
pCheckBoxDetach->setDisabled(false);
}
void cBinaryWidget::viewPic()
{
if (pImageWidget != nullptr) {
pImageWidget->show();
return;
}
if (pCImage == nullptr) EXCEPTION(EPROGFAIL);
if (pCImage->dataIsPic()) openPic();
}
void cBinaryWidget::changedAnyField(cFieldEditBase *p)
{
(void)p;
setCImage();
}
void cBinaryWidget::destroyedImage(QObject *p)
{
(void)p;
pImageWidget = nullptr;
}
/* **************************************** cFKeyArrayWidget **************************************** */
cFKeyArrayWidget::cFKeyArrayWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par)
, pRDescr(cRecStaticDescr::get(_colDescr.fKeyTable, _colDescr.fKeySchema))
, last()
, ra(pRDescr)
{
_wType = FEW_FKEY_ARRAY;
_height = 4;
unique = true;
if (str2tristate(_tf.feature(_sUnique), EX_IGNORE) == TS_FALSE) unique = false;
pFRecModel = nullptr;
pTableShape = nullptr;
pUi = new Ui_fKeyArrayEd;
pUi->setupUi(this);
pEditWidget = pUi->listView;
pLayout = pUi->horizontalLayout;
selectedNum = 0;
actRow = NULL_IX;
pUi->pushButtonAdd->setDisabled(_readOnly);
pUi->pushButtonIns->setDisabled(_readOnly);
pUi->pushButtonUp->setDisabled(_readOnly);
pUi->pushButtonDown->setDisabled(_readOnly);
pUi->pushButtonDel->setDisabled(_readOnly);
pUi->pushButtonClr->setDisabled(_readOnly);
pArrayModel = new cStringListModel(this);
foreach (QVariant vId, _value.toList()) {
qlonglong id = vId.toLongLong();
valueView << ra.getNameById(*pq, id);
ids << id;
}
pArrayModel->setStringList(valueView);
pUi->listView->setModel(pArrayModel);
pUi->listView->setEditTriggers(QAbstractItemView::NoEditTriggers);
pTableShape = new cTableShape();
// Dialógus leíró neve a feature mezőben
QString tsn = _fieldShape.feature(_sDialog);
// ha ott nincs megadva, akkor a megjelenítő neve azonos a tulajdonság rekord nevével
if (tsn.isEmpty()) tsn = _colDescr.fKeyTable;
if (pTableShape->fetchByName(tsn)) { // Ha meg tudjuk jeleníteni
// Nem lehet öröklés !!
qlonglong tit = pTableShape->getId(_sTableInheritType);
if (tit != TIT_NO && tit != TIT_ONLY) EXCEPTION(EDATA);
pTableShape->fetchFields(*pq);
}
else {
pDelete(pTableShape);
}
if (_nullable || _hasDefault) {
bool isNull = __fr.isNull();
setupNullButton(isNull);
cFKeyArrayWidget::disableEditWidget(bool2ts(isNull));
}
if (!_readOnly) {
pFRecModel = new cRecordListModel(*pRDescr, this);
pFRecModel->joinWith(pUi->comboBox);
pFRecModel->setFilter();
pUi->comboBox->setCurrentIndex(0);
connect(pUi->listView->selectionModel(), SIGNAL(selectionChanged(QItemSelection,QItemSelection)), this, SLOT(selectionChanged(QItemSelection,QItemSelection)));
}
}
cFKeyArrayWidget::~cFKeyArrayWidget()
{
pDelete(pTableShape);
}
int cFKeyArrayWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
if (1 == r && !_actValueIsNULL) {
valueView.clear();
foreach (QVariant vId, _value.toList()) {
qlonglong id = vId.toLongLong();
QString name = ra.getNameById(*pq, id, EX_IGNORE);
if (name.isNull()) name = dcViewShort(DC_HAVE_NO) + QString(" [%1]").arg(id); // Error ...
valueView << name;
ids << id;
}
pArrayModel->setStringList(valueView);
}
setButtons();
return r;
}
void cFKeyArrayWidget::setButtons()
{
bool disa = _readOnly || _actValueIsNULL;
bool add = !disa;
if (add) {
qlonglong id = pFRecModel->currendId();
add = id != NULL_ID;
add = add && !(unique && ids.contains(id));
}
bool up = !disa && selectedNum == 1;
bool down = up;
if (up) {
up = actRow > 0;
down = actRow < (ids.size() -1);
}
pUi->pushButtonAdd ->setEnabled(add);
pUi->pushButtonIns ->setEnabled(add && selectedNum == 1);
pUi->pushButtonUp ->setEnabled(up);
pUi->pushButtonDown->setEnabled(down);
pUi->pushButtonDel ->setDisabled(disa || selectedNum == 0);
pUi->pushButtonClr ->setDisabled(disa || ids.isEmpty());
pUi->pushButtonNew ->setDisabled(disa || pTableShape == nullptr || !lanView::isAuthorized(pTableShape->getId(_sInsertRights)));
pUi->pushButtonEdit->setDisabled(disa || pTableShape == nullptr || !lanView::isAuthorized(pTableShape->getId(_sViewRights)));
}
void cFKeyArrayWidget::disableEditWidget(eTristate tsf)
{
cFieldEditBase::disableEditWidget(tsf);
setButtons();
pUi->comboBox->setDisabled(_actValueIsNULL || _readOnly);
}
// cFKeyArrayWidget SLOTS
void cFKeyArrayWidget::selectionChanged(QItemSelection, QItemSelection)
{
QModelIndexList mil = pUi->listView->selectionModel()->selectedRows();
selectedNum = mil.size();
if (selectedNum == 1) {
actRow = mil.first().row();
}
else {
actRow = NULL_IX;
}
setButtons();
}
void cFKeyArrayWidget::on_comboBox_currentIndexChanged(int)
{
setButtons();
}
void cFKeyArrayWidget::on_pushButtonAdd_pressed()
{
int ix = pUi->comboBox->currentIndex();
qlonglong id = pFRecModel->atId(ix);
QString nm = pFRecModel->at(ix);
*pArrayModel << nm;
ids << id;
valueView << ra.getNameById(*pq, id);
_setFromEdit();
setButtons();
}
void cFKeyArrayWidget::on_pushButtonIns_pressed()
{
if (actRow < 0) return;
int ix = pUi->comboBox->currentIndex();
qlonglong id = pFRecModel->atId(ix);
QString nm = pFRecModel->at(ix);
pArrayModel->insert(nm, actRow);
ids.insert(actRow, id);
valueView.insert(actRow, ra.getNameById(*pq, id));
_setFromEdit();
setButtons();
}
void cFKeyArrayWidget::on_pushButtonUp_pressed()
{
if (actRow < 1) return;
std::swap(ids[actRow], ids[actRow -1]);
std::swap(valueView[actRow], valueView[actRow -1]);
pArrayModel->setStringList(valueView);
QModelIndex mi = pArrayModel->index(actRow, 0);
pUi->listView->selectionModel()->select(mi, QItemSelectionModel::Deselect);
mi = pArrayModel->index(actRow -1, 0);
pUi->listView->selectionModel()->select(mi, QItemSelectionModel::Select);
}
void cFKeyArrayWidget::on_pushButtonDown_pressed()
{
if (actRow < 0) return;
int n = ids.size();
if (actRow >= (n -1)) return;
std::swap(ids[actRow], ids[actRow +1]);
std::swap(valueView[actRow], valueView[actRow +1]);
pArrayModel->setStringList(valueView);
QModelIndex mi = pArrayModel->index(actRow, 0);
pUi->listView->selectionModel()->select(mi, QItemSelectionModel::Deselect);
mi = pArrayModel->index(actRow +1, 0);
pUi->listView->selectionModel()->select(mi, QItemSelectionModel::Select);
}
void cFKeyArrayWidget::on_pushButtonDel_pressed()
{
QModelIndexList mil = pUi->listView->selectionModel()->selectedIndexes();
if (mil.size() > 0) {
pArrayModel->remove(mil);
QVector<int> rows = mil2rowsDesc(mil);
foreach (int ix, rows) {
ids.removeAt(ix);
valueView.removeAt(ix);
}
}
else {
pArrayModel->pop_back();
ids.pop_back();
valueView.pop_back();
}
_setFromEdit();
setButtons();
}
void cFKeyArrayWidget::on_pushButtonClr_pressed()
{
pArrayModel->clear();
ids.clear();
valueView.clear();
setFromWidget(QVariantList());
setButtons();
}
void cFKeyArrayWidget::on_pushButtonNew_pressed()
{
if (pTableShape != nullptr && lanView::isAuthorized(pTableShape->getId(_sInsertRights))) {
cRecordDialog *pDialog = new cRecordDialog(*pTableShape, ENUM2SET2(DBT_OK, DBT_CANCEL), true, _pParentDialog);
while (1) {
int keyId = pDialog->exec(false);
if (keyId == DBT_CANCEL) break;
if (!pDialog->accept()) continue;
if (!cErrorMessageBox::condMsgBox(pDialog->record().tryInsert(*pq, TS_NULL, true))) continue;
pFRecModel->setFilter(_sNul, OT_ASC, FT_NO); // Refresh combo box
pUi->comboBox->setCurrentIndex(pFRecModel->indexOf(pDialog->record().getId()));
break;
}
pDialog->close();
delete pDialog;
}
}
void cFKeyArrayWidget::on_pushButtonEdit_pressed()
{
if (pTableShape != nullptr && lanView::isAuthorized(pTableShape->getId(_sInsertRights))) {
cRecordDialog *pDialog = new cRecordDialog(*pTableShape, ENUM2SET2(DBT_OK, DBT_CANCEL), true, _pParentDialog);
cRecordAny rec(pRDescr);
int cix = pUi->comboBox->currentIndex();
qlonglong id = pFRecModel->atId(cix);
if (!rec.fetchById(*pq, id)) return;
rec.fetchText(*pq);
pDialog->restore(&rec);
while (1) {
int keyId = pDialog->exec(false);
if (keyId == DBT_CANCEL) break;
if (!pDialog->accept()) continue;
if (!cErrorMessageBox::condMsgBox(pDialog->record().tryUpdateById(*pq, TS_NULL, true))) continue;
pFRecModel->setFilter(_sNul, OT_ASC, FT_NO); // Refresh combo box
pUi->comboBox->setCurrentIndex(pFRecModel->indexOf(pDialog->record().getId()));
break;
}
pDialog->close();
delete pDialog;
}
}
void cFKeyArrayWidget::on_listView_doubleClicked(const QModelIndex & index)
{
int row = index.row();
int ix;
if (isContIx(ids, row) && 0 <= (ix = pFRecModel->indexOf(ids[row]))) {
pUi->comboBox->setCurrentIndex(ix);
on_pushButtonEdit_pressed();
}
}
void cFKeyArrayWidget::_setFromEdit()
{
setFromWidget(list_longlong2variant(ids));
}
/* **************************************** cColorWidget **************************************** */
// EGYEDI!!!! Javítandó!!!!
cColorWidget::cColorWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par), pixmap(24, 24)
{
_wType = FEW_COLOR;
QHBoxLayout *pHBLayout = new QHBoxLayout;
pLayout = pHBLayout;
setLayout(pHBLayout);
pLineEdit = new QLineEdit(_value.toString());
pLineEdit->setReadOnly(_fl);
pHBLayout->addWidget(pLineEdit, 1);
pLabel = new QLabel;
pHBLayout->addWidget(pLabel);
if (!_readOnly) {
QToolButton *pButton = new QToolButton;
pButton->setIcon(QIcon(":/icons/colorize.ico"));
pHBLayout->addWidget(pButton, 0);
connect(pLineEdit, SIGNAL(textChanged(QString)), this, SLOT(setFromEdit(QString)));
connect(pButton, SIGNAL(pressed()), this, SLOT(colorDialog()));
sTitle = tr("Szín kiválasztása");
}
setColor(_value.toString());
pHBLayout->addStretch();
}
cColorWidget::~cColorWidget()
{
;
}
void cColorWidget::setColor(const QString& text)
{
color.setNamedColor(text);
if (color.isValid()) {
pixmap.fill(color);
pLabel->setPixmap(pixmap);
}
else {
QIcon icon(":/icons/dialog-no.ico");
pLabel->setPixmap(icon.pixmap(pixmap.size()));
}
}
int cColorWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1) {
QString cn = v.toString();
pLineEdit->setText(cn);
}
return r;
}
void cColorWidget::setFromEdit(const QString& text)
{
if (text.isEmpty()) setFromWidget(QVariant());
else setFromWidget(QVariant(text));
setColor(text);
}
void cColorWidget::colorDialog()
{
QColor c = QColorDialog::getColor(color, this, sTitle);
if (c.isValid()) {
pLineEdit->setText(c.name());
}
}
/* **************************************** cFontFamilyWidget **************************************** */
cFontFamilyWidget::cFontFamilyWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef __fr, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, false, _par)
{
if (_readOnly && _par != nullptr) EXCEPTION(EPROGFAIL, 0, _tf.identifying() + "\n" + __fr.record().identifying());
_wType = FEW_FONT_FAMILY;
QHBoxLayout *pHBLayout = new QHBoxLayout;
pLayout = pHBLayout;
setLayout(pHBLayout);
pEditWidget = pFontComboBox = new QFontComboBox;
pLayout->addWidget(pFontComboBox);
bool isNull = __fr.isNull();
if (_nullable || _hasDefault) {
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
if (!isNull) pFontComboBox->setCurrentFont(QFont(QString(__fr)));
pHBLayout->addStretch(0);
connect(pFontComboBox, SIGNAL(currentFontChanged(QFont)), this, SLOT(changeFont(QFont)));
}
cFontFamilyWidget::~cFontFamilyWidget()
{
;
}
int cFontFamilyWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && _actValueIsNULL) {
pFontComboBox->setCurrentFont(QFont(v.toString()));
}
return r;
}
void cFontFamilyWidget::changeFont(const QFont&)
{
setFromWidget(QVariant(pFontComboBox->currentText()));
}
void cFontFamilyWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
; // NULL/Default
}
else {
v = QVariant(pFontComboBox->currentText());
}
setFromWidget(v);
}
/* **************************************** cFontAttrWidget **************************************** */
const QString cFontAttrWidget::sEnumTypeName = "fontattr";
QIcon cFontAttrWidget::iconBold;
QIcon cFontAttrWidget::iconItalic;
QIcon cFontAttrWidget::iconUnderline;
QIcon cFontAttrWidget::iconStrikeout;
cFontAttrWidget::cFontAttrWidget(const cTableShape& _tm, const cTableShapeField &_tf, cRecordFieldRef __fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, __fr, _fl, _par)
{
if (iconBold.isNull()) {
iconBold. addFile("://icons/format-text-bold.ico", QSize(), QIcon::Normal, QIcon::On);
iconBold. addFile("://icons/format-text-bold-no.png", QSize(), QIcon::Normal, QIcon::Off);
iconItalic. addFile("://icons/format-text-italic.ico", QSize(), QIcon::Normal, QIcon::On);
iconItalic. addFile("://icons/format-text-italic-no.png", QSize(), QIcon::Normal, QIcon::Off);
iconUnderline.addFile("://icons/format-text-underline.ico", QSize(), QIcon::Normal, QIcon::On);
iconUnderline.addFile("://icons/format-text-underline-no.png", QSize(), QIcon::Normal, QIcon::Off);
iconStrikeout.addFile("://icons/format-text-strikethrough.ico", QSize(), QIcon::Normal, QIcon::On);
iconStrikeout.addFile("://icons/format-text-strikethrough-no.png", QSize(), QIcon::Normal, QIcon::Off);
}
_wType = FEW_FONT_ATTR;
bool isNull = __fr.isNull();
m = isNull ? 0 : qlonglong(__fr);
QHBoxLayout *pHBLayout = new QHBoxLayout;
pLayout = pHBLayout;
setLayout(pLayout);
bool f;
f = 0 != (m & ENUM2SET(FA_BOOLD));
setupFlagWidget(f, iconBold, pToolButtonBold);
f = 0 != (m & ENUM2SET(FA_ITALIC));
setupFlagWidget(f, iconItalic, pToolButtonItalic);
f = 0 != (m & ENUM2SET(FA_UNDERLINE));
setupFlagWidget(f, iconUnderline, pToolButtonUnderline);
f = 0 != (m & ENUM2SET(FA_STRIKEOUT));
setupFlagWidget(f, iconStrikeout, pToolButtonStrikeout);
pHBLayout->addStretch(0);
setupNullButton(isNull);
cFontAttrWidget::disableEditWidget(bool2ts(isNull));
QSqlQuery q = getQuery();
pEnumType = cColEnumType::fetchOrGet(q, sEnumTypeName);
if (!_readOnly) {
connect(pToolButtonBold, SIGNAL(toggled(bool)), this, SLOT(togleBoold(bool)));
connect(pToolButtonItalic, SIGNAL(toggled(bool)), this, SLOT(togleItalic(bool)));
connect(pToolButtonUnderline, SIGNAL(toggled(bool)), this, SLOT(togleUnderline(bool)));
connect(pToolButtonStrikeout, SIGNAL(toggled(bool)), this, SLOT(togleStrikeout(bool)));
}
}
cFontAttrWidget::~cFontAttrWidget()
{
;
}
int cFontAttrWidget::set(const QVariant& v)
{
bool r = cFieldEditBase::set(v);
if (r == 1 && !_actValueIsNULL) {
m = pEnumType->lst2set(v.toStringList());
pToolButtonBold ->setChecked(m & ENUM2SET(FA_BOOLD));
pToolButtonItalic ->setChecked(m & ENUM2SET(FA_ITALIC));
pToolButtonUnderline->setChecked(m & ENUM2SET(FA_UNDERLINE));
pToolButtonStrikeout->setChecked(m & ENUM2SET(FA_STRIKEOUT));
}
return r;
}
void cFontAttrWidget::setupFlagWidget(bool f, const QIcon& icon, QToolButton *& pButton)
{
pButton = _readOnly ? new cROToolButton() : new QToolButton();
pButton->setIcon(icon);
pButton->setCheckable(true);
pButton->setChecked(f);
pLayout->addWidget(pButton);
}
void cFontAttrWidget::disableEditWidget(eTristate tsf)
{
setBool(_actValueIsNULL, tsf);
bool f = _readOnly || _actValueIsNULL;
pToolButtonBold->setDisabled(f);
pToolButtonItalic->setDisabled(f);
pToolButtonUnderline->setDisabled(f);
pToolButtonStrikeout->setDisabled(f);
}
void cFontAttrWidget::_setFromEdit()
{
QVariant v;
if (pNullButton != nullptr && pNullButton->isChecked()) {
; // NULL/Default
}
else {
qlonglong m = 0;
m |= bitByButton(pToolButtonBold, ENUM2SET(FA_BOOLD));
m |= bitByButton(pToolButtonItalic, ENUM2SET(FA_ITALIC));
m |= bitByButton(pToolButtonUnderline, ENUM2SET(FA_UNDERLINE));
m |= bitByButton(pToolButtonStrikeout, ENUM2SET(FA_STRIKEOUT));
v = m;
}
setFromWidget(v);
}
void cFontAttrWidget::togleBoold(bool f)
{
if (f == (bool(m & ENUM2SET(FA_BOOLD)))) return;
if (f) m |= ENUM2SET(FA_BOOLD);
else m &= ~ENUM2SET(FA_BOOLD);
setFromWidget(QVariant(m));
}
void cFontAttrWidget::togleItalic(bool f)
{
if (f == (bool(m & ENUM2SET(FA_ITALIC)))) return;
if (f) m |= ENUM2SET(FA_ITALIC);
else m &= ~ENUM2SET(FA_ITALIC);
setFromWidget(QVariant(m));
}
void cFontAttrWidget::togleUnderline(bool f)
{
if (f == (bool(m & ENUM2SET(FA_UNDERLINE)))) return;
if (f) m |= ENUM2SET(FA_UNDERLINE);
else m &= ~ENUM2SET(FA_UNDERLINE);
setFromWidget(QVariant(m));
}
void cFontAttrWidget::togleStrikeout(bool f)
{
if (f == (bool(m & ENUM2SET(FA_STRIKEOUT)))) return;
if (f) m |= ENUM2SET(FA_STRIKEOUT);
else m &= ~ENUM2SET(FA_STRIKEOUT);
setFromWidget(QVariant(m));
}
/* **** **** */
cLTextWidget::cLTextWidget(const cTableShape &_tm, const cTableShapeField& _tf, cRecordFieldRef _fr, int _ti, int _fl, cRecordDialogBase* _par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
{
_readOnly = (_fl & FEB_READ_ONLY) || tableIsReadOnly(_tm, _fr.record())
|| !(_fr.descr().isUpdatable)
|| _tf.getBool(_sFieldFlags, FF_READ_ONLY)
|| !lanView::isAuthOrNull(_tf.getId(_sEditRights));
_value = _fr.record().getText(_ti);
_nullable = false;
_hasDefault = false;
_hasAuto = false;
_dcNull = DC_INVALID;
pLineEdit = nullptr;
pPlainTextEdit = nullptr;
pTextEdit = nullptr;
pLayout = new QHBoxLayout;
setLayout(pLayout);
if (_fieldShape.getBool(_sFieldFlags, FF_HTML_TEXT)) {
_wType = FEW_LTEXT_HTML; // Widget típus azonosító
pTextEdit = new QTextEdit;
pLayout->addWidget(pTextEdit);
pTextEdit->setText(_value.toString());
pTextEdit->setReadOnly(_readOnly);
connect(pTextEdit, SIGNAL(textChanged()), this, SLOT(_setFromEdit()));
}
else if (_fieldShape.getBool(_sFieldFlags, FF_HUGE)) {
_wType = FEW_LTEXT_LONG; // Widget típus azonosító
pPlainTextEdit = new QPlainTextEdit;
pLayout->addWidget(pPlainTextEdit);
pPlainTextEdit->setPlainText(_value.toString());
pPlainTextEdit->setReadOnly(_readOnly);
connect(pPlainTextEdit, SIGNAL(textChanged()), this, SLOT(_setFromEdit()));
}
else {
_wType = FEW_LTEXT; // Widget típus azonosító
pLineEdit = new QLineEdit;
pLayout->addWidget(pLineEdit);
pLineEdit->setText(_value.toString());
pLineEdit->setReadOnly(_readOnly);
connect(pLineEdit, SIGNAL(editingFinished()), this, SLOT(_setFromEdit()));
}
}
cLTextWidget::~cLTextWidget()
{
}
int cLTextWidget::set(const QVariant& v)
{
QString t = v.toString();
if (t == _value.toString()) return 0;
_value = t;
emit changedValue(this);
switch (_wType) {
case FEW_LTEXT: pLineEdit->setText(t); break;
case FEW_LTEXT_LONG: pPlainTextEdit->setPlainText(t); break;
case FEW_LTEXT_HTML: pTextEdit->setHtml(t); break;
default: EXCEPTION(EPROGFAIL);
}
return 1;
}
void cLTextWidget::_setFromEdit()
{
QString s;
switch (_wType) {
case FEW_LTEXT: s = pLineEdit->text(); break;
case FEW_LTEXT_LONG: s = pPlainTextEdit->toPlainText(); break;
case FEW_LTEXT_HTML: s = pTextEdit->toHtml(); break;
default: EXCEPTION(EPROGFAIL);
}
QVariant v; // NULL
if (!s.isEmpty()) {
v = QVariant(s);
}
setFromWidget(v);
}
/* **** **** */
cFeatureWidgetRow::cFeatureWidgetRow(cFeatureWidget *par, int row, const QString& key, const QString& val)
: QObject(par)
{
pDialog = nullptr;
pListWidget = nullptr;
pTableWidget = nullptr;
_pParentWidget = par;
pItemKey = new QTableWidgetItem(key);
par->pTable->setItem(row, COL_KEY, pItemKey);
pItemVal = new QTableWidgetItem(val);
par->pTable->setItem(row, COL_VAL, pItemVal);
pListButton = new QToolButton;
pListButton->setIcon(QIcon(QString(":/icons/view-list-details.ico")));
par->pTable->setCellWidget(row, COL_B_LIST, pListButton);
connect(pListButton, SIGNAL(clicked()), this, SLOT(listDialog()));
pMapButton = new QToolButton;
pMapButton->setIcon(QIcon(QString(":/icons/view-list-icon.ico")));
par->pTable->setCellWidget(row, COL_B_MAP, pMapButton);
connect(pMapButton, SIGNAL(clicked()), this, SLOT(mapDialog()));
}
cFeatureWidgetRow::~cFeatureWidgetRow()
{
;
}
void cFeatureWidgetRow::clickButton(int id)
{
if (pDialog == nullptr) return;
switch (id) {
case DBT_OK:
case DBT_CANCEL:
pDialog->done(id);
break;
case DBT_INSERT:
if (pListWidget != nullptr) {
QListWidgetItem *pItem = new QListWidgetItem;
pItem->setFlags(pItem->flags() | Qt::ItemIsEditable);
QModelIndexList mil = pListWidget->selectionModel()->selectedRows();
if (mil.isEmpty()) pListWidget->addItem(pItem);
else pListWidget->insertItem(mil.first().row(), pItem);
}
else if (pTableWidget != nullptr) {
int rows = pTableWidget->rowCount();
pTableWidget->setRowCount(rows +1);
pTableWidget->setItem(rows, 0, new QTableWidgetItem);
pTableWidget->setItem(rows, 1, new QTableWidgetItem);
}
break;
case DBT_DELETE:
if (pListWidget != nullptr) {
QModelIndexList mil = pListWidget->selectionModel()->selectedRows();
if (!mil.isEmpty()) delete pListWidget->takeItem(mil.first().row());
}
else if (pTableWidget != nullptr) {
QModelIndexList mil = pTableWidget->selectionModel()->selectedRows();
if (!mil.isEmpty()) {
pTableWidget->removeRow(mil.first().row());
}
}
break;
case DBT_REPORT:
if (pTableWidget != nullptr) {
int rows = pTableWidget->rowCount();
if (rows > 0) {
QList<QStringList> matrix;
for (int row = 0; row < rows; ++row) {
QStringList v;
v << pTableWidget->item(row, 0)->text();
v << pTableWidget->item(row, 1)->text();
matrix << v;
}
QStringList head;
head << tr("Név");
head << tr("Érték");
QString name = pItemKey->text();
QString title = tr("A features %1 nevű értékébe ágyazott nevesített érték lista.")
.arg(name);
QWidget *par = lv2g::pMainWindow;
popupReportWindow(par, htmlTable(head, matrix), title);
}
}
}
}
void cFeatureWidgetRow::listDialog()
{
pDialog = new QDialog;
pListWidget = new QListWidget;
QVBoxLayout * pVLayout = new QVBoxLayout;
cDialogButtons *pButtons = new cDialogButtons(ENUM2SET4(DBT_OK, DBT_INSERT, DBT_DELETE, DBT_CANCEL));
pDialog->setWindowTitle(tr("Lista szerkesztése"));
pDialog->setLayout(pVLayout);
pVLayout->addWidget(pListWidget);
pVLayout->addWidget(pButtons->pWidget());
QString val = pItemVal->text();
QStringList list = cFeatures::value2list(val);
foreach (QString s, list) {
QListWidgetItem *pItem = new QListWidgetItem(s);
pItem->setFlags(pItem->flags() | Qt::ItemIsEditable);
pListWidget->addItem(pItem);
}
connect(pButtons, SIGNAL(buttonClicked(int)), this, SLOT(clickButton(int)));
int id = pDialog->exec();
if (id == DBT_OK) {
list.clear();
int i, n = pListWidget->count();
for (i = 0; i < n; ++i) {
list << pListWidget->item(i)->text();
}
val = cFeatures::list2value(list);
pItemVal->setText(val);
}
pDelete(pDialog);
pListWidget = nullptr;
}
void cFeatureWidgetRow::mapDialog()
{
pDialog = new QDialog;
pTableWidget = new QTableWidget;
QVBoxLayout * pVLayout = new QVBoxLayout;
cDialogButtons *pButtons = new cDialogButtons(ENUM2SET5(DBT_OK, DBT_REPORT, DBT_INSERT, DBT_DELETE, DBT_CANCEL));
pDialog->setWindowTitle(tr("Map szerkesztése"));
pDialog->setLayout(pVLayout);
pVLayout->addWidget(pTableWidget);
pVLayout->addWidget(pButtons->pWidget());
QString val = pItemVal->text();
tStringMap map = cFeatures::value2map(val);
QStringList keys = map.keys();
pTableWidget->setRowCount(keys.size());
pTableWidget->setColumnCount(2);
pTableWidget->horizontalHeader()->setStretchLastSection(true);
QStringList labels;
labels << tr("Név") << tr("Érték");
pTableWidget->setHorizontalHeaderLabels(labels);
QTableWidgetItem *pItem;
int _row = 0;
foreach (QString key, keys) {
QString val = map[key];
pItem = new QTableWidgetItem(key);
pTableWidget->setItem(_row, 0, pItem);
pItem = new QTableWidgetItem(val);
pTableWidget->setItem(_row, 1, pItem);
++_row;
}
connect(pButtons, SIGNAL(buttonClicked(int)), this, SLOT(clickButton(int)));
int id = pDialog->exec();
if (id == DBT_OK) {
map.clear();
int i, n = pTableWidget->rowCount();
for (i = 0; i < n; ++i) {
QString key = pTableWidget->item(i, 0)->text();
QString kvl = pTableWidget->item(i, 1)->text();
map[key] = kvl;
}
val = cFeatures::map2value(map);
pItemVal->setText(val);
}
pDelete(pDialog);
pTableWidget = nullptr;
}
/* ---- ---- */
cFeatureWidget::cFeatureWidget(const cTableShape &_tm, const cTableShapeField& _tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
{
_wType = FEW_FEATURES;
_height = 6;
busy = true;
pHLayout = new QHBoxLayout;
setLayout(pHLayout);
pEditWidget = pTable = new QTableWidget;
pTable->horizontalHeader()->setStretchLastSection(true);
QStringList headLabels;
headLabels << _sNul << _sNul;
headLabels << tr("Név");
headLabels << tr("Érték");
pTable->setColumnCount(cFeatureWidgetRow::COL_NUMBER);
pTable->horizontalHeader()->setMinimumSectionSize(24);
pTable->setRowCount(0); // empty
pTable->setHorizontalHeaderLabels(headLabels);
pHLayout->addWidget(pTable, 1);
pVLayout = new QVBoxLayout;
pHLayout->addLayout(pVLayout);
pDelRow = new QPushButton(tr("Töröl"));
pInsRow = new QPushButton(tr("Beszúr"));
pVLayout->addWidget(pInsRow);
pVLayout->addWidget(pDelRow);
pVLayout->addStretch();
pLayout = new QHBoxLayout;
pVLayout->addLayout(pLayout);
pLayout->addStretch();
if (_nullable || _hasDefault) {
bool isNull = _fr.isNull();
setupNullButton(isNull);
cFieldEditBase::disableEditWidget(isNull);
}
connect(pTable, SIGNAL(cellChanged(int, int)), this, SLOT(onChangedCell(int, int)));
connect(pInsRow, SIGNAL(clicked()), this, SLOT(onInsClicked()));
connect(pDelRow, SIGNAL(clicked()), this, SLOT(onDelClicked()));
busy = false;
}
cFeatureWidget::~cFeatureWidget()
{
busy = true;
clearRows();
}
int cFeatureWidget::set(const QVariant& v)
{
int r = cFieldEditBase::set(v);
if (1 == r) {
busy = true;
clearRows();
QString s = v.toString();
if (!s.isEmpty() && s != ":") {
if (!features.split(s, false, EX_IGNORE)) {
cMsgBox::error(tr("Hibás features érték: '%1'").arg(s));
}
}
QStringList keys = features.keys();
pTable->setRowCount(keys.size());
int row = 0 ;
foreach (QString key, keys) {
QString val = features.value(key);
rowList << new cFeatureWidgetRow(this, row, key, val);
++row;
}
pTable->resizeColumnsToContents();
busy = false;
}
return r;
}
void cFeatureWidget::clearRows()
{
features.clear();
pTable->setRowCount(0);
while (!rowList.isEmpty()) delete rowList.takeLast();
}
void cFeatureWidget::onChangedCell(int, int)
{
if (!busy) _setFromEdit();
}
void cFeatureWidget::_setFromEdit()
{
if (pNullButton != nullptr && pNullButton->isChecked()) {
if (!_value.isNull()) setFromWidget(QVariant());
}
else {
features.clear();
int rows = pTable->rowCount();
for (int i = 0; i < rows; ++i) {
QTableWidgetItem *p = pTable->item(i, cFeatureWidgetRow::COL_KEY);
if (p == nullptr) {
continue;
}
QString key = p->text();
if (!key.isEmpty()) {
p = pTable->item(i, cFeatureWidgetRow::COL_VAL);
QString value;
if (p != nullptr) {
value = p->text();
}
features[key] = value;
}
}
QString s = features.join();
if (s != _value.toString()) setFromWidget(s);
}
}
void cFeatureWidget::onInsClicked()
{
busy = true;
int rows = pTable->rowCount();
pTable->setRowCount(rows +1);
rowList << new cFeatureWidgetRow(this, rows, _sNul, _sNul);
busy = false;
}
void cFeatureWidget::onDelClicked()
{
QModelIndexList mil = pTable->selectionModel()->selectedRows();
if (mil.isEmpty()) return;
busy = true;
QList<int> rowsIndexList;
foreach (QModelIndex mi, mil) { rowsIndexList << mi.row(); }
std::sort(rowsIndexList.begin(), rowsIndexList.end());
while (rowsIndexList.size() > 0) {
int row = rowsIndexList.takeLast();
pTable->removeRow(row);
delete rowList.takeAt(row);
}
busy = false;
onChangedCell(0,0);
}
/* **** **** */
cParamValueWidget::cParamValueWidget(const cTableShape &_tm, const cTableShapeField& _tf, cRecordFieldRef _fr, int _fl, cRecordDialogBase *_par)
: cFieldEditBase(_tm, _tf, _fr, _fl, _par)
{
if (_colDescr.eColType != cColStaticDescr::FT_TEXT) EXCEPTION(ECONTEXT, _colDescr.eColType, _colDescr);
lastType = NULL_ID;
typeIdIndex = NULL_IX;
rawValue = false;
pParamType = new cParamType;
pSVarType = nullptr;
pLayout = nullptr;
pPlainTextEdit = nullptr;
pLineEdit = nullptr;
pComboBox = nullptr;
cFieldEditBase *pWType = nullptr;
typeIdIndex = _pParentDialog->rDescr.toIndex(_sParamTypeId, EX_IGNORE); // sys_params, node_params, port_params
if (typeIdIndex < 0) { // service_vars, service_rrd_vars
pSVarType = new cServiceVarType;
if (_colDescr == _sServiceVarValue) {
typeIdIndex = pSVarType->toIndex(_sParamTypeId, EX_IGNORE);
}
else if (_colDescr == _sRawValue) {
typeIdIndex = pSVarType->toIndex(_sRawParamTypeId, EX_IGNORE);
}
else {
EXCEPTION(ECONTEXT);
}
pWType = _pParentDialog->fieldByTableFieldName(_sServiceVarTypeId);
}
else {
pWType = _pParentDialog->fieldByTableFieldName(_sParamTypeId);
}
if (pWType == nullptr) EXCEPTION(EPROGFAIL);
connect(pWType, SIGNAL(changedValue(cFieldEditBase *)), this, SLOT(_changeType(cFieldEditBase *)));
_changeType(pWType);
}
cParamValueWidget::~cParamValueWidget()
{
pDelete(pParamType);
pDelete(pSVarType);
}
int cParamValueWidget::set(const QVariant& _v)
{
int r = cFieldEditBase::set(_v);
if (r) refreshWidget();
return r;
}
void cParamValueWidget::refreshWidget()
{
if (lastType < 0) {
if (pLineEdit != nullptr) pLineEdit->setText(_sNul);
return;
}
if (pPlainTextEdit != nullptr) pPlainTextEdit->setPlainText(getName());
else if (pLineEdit != nullptr) pLineEdit->setText(getName());
else if (pComboBox != nullptr) pComboBox->setCurrentIndex(get().toBool() ? 1 : 0);
// ...
}
void cParamValueWidget::_changeType(cFieldEditBase *pTW)
{
qlonglong paramTypeId = NULL_ID;
if (pSVarType == nullptr) { // Changed param_type_id
paramTypeId = pTW->getId();
}
else { // Changed service_var_type_id
qlonglong varTypeId = pTW->getId();
pSVarType->fetchById(*pq, varTypeId);
paramTypeId = pSVarType->getId(typeIdIndex);
}
if (paramTypeId < 0 || !pParamType->fetchById(*pq, paramTypeId)) { // type is NULL
pParamType->clear();
lastType = NULL_ID;
return;
}
qlonglong type = pParamType->getId(_sParamTypeType);
if (lastType == type) return;
lastType = type;
pDelete(pLayout);
pPlainTextEdit = nullptr;
pLineEdit = nullptr;
pComboBox = nullptr;
pLayout = new QHBoxLayout;
switch (lastType) {
case PT_TEXT:
pEditWidget = pPlainTextEdit = new QPlainTextEdit;
pLayout->addWidget(pPlainTextEdit);
break;
case PT_BOOLEAN:
pEditWidget = pComboBox = new QComboBox;
pComboBox->addItem(langBool(false));
pComboBox->addItem(langBool(true));
pLayout->addWidget(pComboBox);
break;
case PT_INTEGER:
case PT_REAL:
case PT_MAC:
case PT_INET:
case PT_CIDR:
pLineEdit = new QLineEdit;
if (_readOnly) {
pLineEdit->setReadOnly(true);
}
else switch (lastType) {
case PT_INTEGER:
pLineEdit->setValidator(new cIntValidator);
break;
case PT_REAL:
pLineEdit->setValidator(new cRealValidator);
break;
case PT_MAC:
pLineEdit->setValidator(new cMacValidator);
break;
case PT_INET:
pLineEdit->setValidator(new cINetValidator);
break;
case PT_CIDR:
pLineEdit->setValidator(new cCidrValidator);
break;
default:
EXCEPTION(EPROGFAIL);
}
pLayout->addWidget(pLineEdit);
break;
case PT_DATE:
case PT_TIME:
case PT_DATETIME:
case PT_INTERVAL:
case PT_POINT:
case PT_BYTEA:
default:
pLineEdit = new QLineEdit;
pLineEdit->setDisabled(true);
dcSetShort(pLineEdit, DC_NOT_PERMIT);
pLayout->addWidget(pLineEdit);
break;
}
setLayout(pLayout);
set(_value);
}
void cParamValueWidget::_setFromEdit()
{
}
/* **** **** */
cSelectPlace::cSelectPlace(QComboBox *_pZone, QComboBox *_pPLace, QLineEdit *_pFilt, const QString& _constFilt, QWidget *_par)
: QObject(_par)
, bbPlace(this, &cSelectPlace::emitChangePlace)
, pComboBoxZone(_pZone)
, pComboBoxPLace(_pPLace)
, pLineEditPlaceFilt(_pFilt)
, constFilterPlace(_constFilt)
{
pButtonPlaceInsert = pButtonPlaceRefresh = pButtonPlaceInfo = pButtonPlaceEdit = nullptr;
pSlave = nullptr;
pModelZone = new cZoneListModel(this);
pModelZone->joinWith(pComboBoxZone);
if (lv2g::getInstance()->zoneId != NULL_ID) pModelZone->setCurrent(lv2g::getInstance()->zoneId);
pModelPlace = new cPlacesInZoneModel(this);
pModelPlace->joinWith(pComboBoxPLace);
pComboBoxPLace->setCurrentIndex(0);
if (!constFilterPlace.isEmpty()) {
pModelPlace->setConstFilter(constFilterPlace, FT_SQL_WHERE);
}
connect(pComboBoxZone, SIGNAL(currentIndexChanged(int)), this, SLOT(on_comboBoxZone_currentIndexChanged(int)));
connect(pComboBoxPLace, SIGNAL(currentIndexChanged(int)), this, SLOT(on_comboBoxPlace_currentIndexChanged(int)));
if (pLineEditPlaceFilt != nullptr) {
connect(pLineEditPlaceFilt, SIGNAL(textChanged(QString)), this, SLOT(lineEditPlaceFilt_textChanged(QString)));
}
}
void cSelectPlace::copyCurrents(const cSelectPlace &_o)
{
bbPlace.begin();
qlonglong pid = currentPlaceId();
pComboBoxZone->setCurrentIndex(_o.pComboBoxZone->currentIndex());
if (pLineEditPlaceFilt != nullptr) {
QString pattern = _sNul;
if (_o.pLineEditPlaceFilt != nullptr) {
pattern = _o.pLineEditPlaceFilt->text();
}
pLineEditPlaceFilt->setText(pattern); // -> lineEditPlaceFilt_textChanged()
}
int pix = _o.pComboBoxPLace->currentIndex();
pComboBoxPLace->setCurrentIndex(pix); // -> on_comboBoxPlace_currentIndexChanged()
bbPlace.end(pid != currentPlaceId());
}
void cSelectPlace::setSlave(cSelectPlace *_pSlave, bool disabled)
{
if (_pSlave == nullptr) {
if (pSlave != nullptr) pSlave->setDisableWidgets(false);
pSlave = nullptr;
}
else {
if (pSlave != nullptr && pSlave != _pSlave) EXCEPTION(EPROGFAIL);
pSlave = _pSlave;
pSlave->copyCurrents(*this);
pSlave->cSelectPlace::setDisableWidgets(disabled);
}
}
void cSelectPlace::setDisableWidgets(bool f)
{
pComboBoxZone->setDisabled(f);
if (pLineEditPlaceFilt != nullptr) pLineEditPlaceFilt->setDisabled(f);
pComboBoxPLace->setDisabled(f);
if (pButtonPlaceInsert != nullptr) pButtonPlaceInsert->setDisabled(f);
if (pButtonPlaceRefresh != nullptr) pButtonPlaceRefresh->setDisabled(f);
f = f || (currentPlaceId() == NULL_ID);
if (pButtonPlaceInfo != nullptr) pButtonPlaceInfo->setDisabled(f);
if (pButtonPlaceEdit != nullptr) pButtonPlaceEdit->setDisabled(f);
}
void cSelectPlace::setPlaceInsertButton(QAbstractButton * p)
{
pButtonPlaceInsert = p;
connect(p, SIGNAL(clicked()), this, SLOT(insertPlace()));
}
void cSelectPlace::setPlaceEditButton(QAbstractButton * p)
{
pButtonPlaceEdit = p;
connect(p, SIGNAL(clicked()), this, SLOT(editPlace()));
}
void cSelectPlace::setPlaceRefreshButton(QAbstractButton * p)
{
pButtonPlaceRefresh = p;
connect(p, SIGNAL(clicked()), this, SLOT(refresh()));
}
void cSelectPlace::setPlaceInfoButton(QAbstractButton * p)
{
pButtonPlaceInfo = p;
connect(p, SIGNAL(clicked()), this, SLOT(placeReport()));
}
bool cSelectPlace::emitChangePlace(bool f)
{
if (f && bbPlace.test()) {
placeNameChanged(currentPlaceName());
placeIdChanged(currentPlaceId());
if (pButtonPlaceInfo != nullptr) pButtonPlaceInfo->setDisabled(currentPlaceId() == NULL_ID);
return true;
}
return false;
}
void cSelectPlace::setEnabled(bool f)
{
setDisableWidgets(!f);
}
void cSelectPlace::setDisabled(bool f)
{
setDisableWidgets(f);
}
void cSelectPlace::refresh(bool f)
{
bbPlace.begin();
qlonglong zid = currentZoneId();
qlonglong pid = currentPlaceId();
if (pSlave) {
pSlave->refresh();
}
pModelZone->setFilter();
setCurrentZone(zid);
pModelPlace->setFilter();
setCurrentPlace(pid);
bbPlace.end(f && pid != currentPlaceId());
}
/// Egy új helyiség objektum adatlap megjelkenítése, és az objektum beillesztése az adatbázisba.
/// @return Ha a művelet sikeres, akkor az új objektum ID-je, ha nem akkor NULL_ID.
qlonglong cSelectPlace::insertPlace()
{
QSqlQuery q = getQuery();
cRecord *p = recordDialog(q, _sPlaces, qobject_cast<QWidget *>(parent()));
if (p == nullptr) return NULL_ID;
qlonglong pid = p->getId();
delete p;
bbPlace.begin();
if (pSlave != nullptr) {
pSlave->bbPlace.begin();
}
pModelPlace->setFilter();
setCurrentPlace(pid);
if (pSlave) {
pSlave->pModelPlace->setFilter();
pSlave->setCurrentPlace(pid);
pSlave->bbPlace.end();
}
bbPlace.end();
return pid;
}
/// Szignál:
/// Az aktuális helyiség objektum adatlap megjelkenítése, és szerkesztése. A név változtatás tiltott.
void cSelectPlace::editPlace()
{
qlonglong pid = currentPlaceId();
if (pid == NULL_ID) return;
QSqlQuery q = getQuery();
cPlace place;
place.setById(q, pid);
cTableShape shape;
shape.setByName(q, _sPlaces);
shape.fetchFields(q);
shape.shapeFields.get(_sPlaceName)->enum2setOn(_sFieldFlags, FF_READ_ONLY); // Set name (place_name) is read only
cRecord *p = recordDialog(q, shape, qobject_cast<QWidget *>(parent()), &place, pid <= ROOT_PLACE_ID, true);
pDelete(p);
}
qlonglong cSelectPlace::editCurrentPlace()
{
qlonglong pid = currentPlaceId();
if (pid <= ROOT_PLACE_ID) return NULL_ID; // A NULL, unknown, root nem editálható
QSqlQuery q = getQuery();
cPlace place;
place.setById(q, pid);
cRecord *p = recordDialog(q, _sPlaces, qobject_cast<QWidget *>(parent()), &place, false, true);
if (p == nullptr) return NULL_ID;
pid = p->getId();
delete p;
bbPlace.begin();
if (pSlave != nullptr) {
pSlave->bbPlace.begin();
}
pModelPlace->setFilter();
setCurrentPlace(pid);
if (pSlave) {
pSlave->pModelPlace->setFilter();
pSlave->setCurrentPlace(pid);
pSlave->bbPlace.end();
}
bbPlace.end();
return pid;
}
void cSelectPlace::setCurrentZone(qlonglong _zid)
{
int ix = pModelZone->indexOf(_zid);
if (ix < 0) EXCEPTION(EDATA, _zid);
if (ix != pComboBoxZone->currentIndex()) {
pComboBoxZone->blockSignals(true);
pComboBoxZone->setCurrentIndex(ix);
pComboBoxZone->blockSignals(false);
}
qlonglong pid = currentPlaceId(); // Save current plac id. We'll keep it if we can.
bool f = true;
if (pid == NULL_ID) {
pModelPlace->setZone(_zid);
}
else {
bbPlace.begin();
pModelPlace->setZone(_zid);
ix = pModelPlace->indexOf(pid);
f = ix >= 0;
if (f) pComboBoxPLace->setCurrentIndex(ix);
bbPlace.end(!f);
}
if (pSlave != nullptr) {
if (!bbPlace.test()) pSlave->bbPlace.begin();
pSlave->setCurrentZone(_zid);
if (!bbPlace.test()) pSlave->bbPlace.end(!f);
}
}
void cSelectPlace::setCurrentPlace(qlonglong _pid)
{
if (_pid == currentPlaceId()) return;
bbPlace.begin();
if (_pid == NULL_ID || _pid == UNKNOWN_PLACE_ID) { // Az 'unknown' nincs a listában! ==> NULL
if (pModelPlace->nullable) {
pComboBoxPLace->setCurrentIndex(0); // -> on_comboBoxZone_currentIndexChanged(ix)
}
else {
EXCEPTION(EDATA);
}
}
else { // NOT NULL
int ix = pModelPlace->indexOf(_pid);
if (ix < 0) {
if (pLineEditPlaceFilt != nullptr) pLineEditPlaceFilt->setText(_sNul);
setCurrentZone(ALL_PLACE_GROUP_ID);
ix = pModelPlace->indexOf(_pid);
if (ix < 0) EXCEPTION(EDATA);
}
pComboBoxPLace->setCurrentIndex(ix); // -> on_comboBoxZone_currentIndexChanged(ix)
}
bbPlace.end();
}
void cSelectPlace::placeReport()
{
qlonglong pid = currentPlaceId();
if (pid == NULL_ID) return;
QSqlQuery q = getQuery();
tStringPair r = htmlReportPlace(q, pid);
popupReportWindow(static_cast<QWidget *>(this->parent()), r.second, r.first);
}
void cSelectPlace::on_comboBoxZone_currentIndexChanged(int ix)
{
if (ix < 0) {
if (bbPlace.test()) {
DERR() << "Invalid index : " << ix << endl;
}
return;
}
qlonglong zid = pModelZone->atId(ix);
setCurrentZone(zid);
}
void cSelectPlace::on_comboBoxPlace_currentIndexChanged(int ix)
{
if (bbPlace.test()) {
if (pSlave) pSlave->pComboBoxPLace->setCurrentIndex(ix);
emitChangePlace(true);
}
}
void cSelectPlace::lineEditPlaceFilt_textChanged(const QString& s)
{
bbPlace.begin();
qlonglong pid = currentPlaceId();
if (s.isEmpty()) {
pModelPlace->setFilter(QVariant(), OT_DEFAULT, FT_NO);
}
else {
pModelPlace->setFilter(condAddJoker(s), OT_DEFAULT, FT_LIKE);
}
int pix = pModelPlace->indexOf(pid);
if (pix < 0) pix = 0;
if (pSlave != nullptr) {
pSlave->bbPlace.begin();
if (pSlave->pLineEditPlaceFilt != nullptr) pSlave->pLineEditPlaceFilt->setText(s);
pSlave->setCurrentPlace(pModelPlace->atId(pix));
pSlave->bbPlace.end(pix == 0);
}
pComboBoxPLace->setCurrentIndex(pix);
bbPlace.end(pix == 0);
}
/* **** **** */
cSelectNode::cSelectNode(QComboBox *_pZone, QComboBox *_pPlace, QComboBox *_pNode,
QLineEdit *_pPlaceFilt, QLineEdit *_pNodeFilt,
const QString& _placeConstFilt, const QString& _nodeConstFilt,
QWidget *_par)
: cSelectPlace(_pZone, _pPlace, _pPlaceFilt, _placeConstFilt, _par)
, bbNode(this, &cSelectNode::emitChangeNode)
, pComboBoxNode(_pNode)
, pLineEditNodeFilt(_pNodeFilt)
, constFilterNode(_nodeConstFilt)
{
pButtonPatchInsert = pButtonNodeRefresh = pButtonNodeInfo = nullptr;
pModelNode = nullptr;
setNodeModel(new cRecordListModel(cPatch().descr(), this), TS_TRUE);
connect(this, SIGNAL(placeIdChanged(qlonglong)), this, SLOT(setPlaceId(qlonglong)));
// Ha a kiválasztott hely NULL, akkor kell a zóna változásra is reagálni.
connect(pComboBoxZone, SIGNAL(currentIndexChanged(int)), this, SLOT(on_comboBoxZone_currenstIndexChanged(int)));
if (pLineEditNodeFilt != nullptr) { // Ha van mintára szűrés
connect(pLineEditNodeFilt, SIGNAL(textChanged(QString)), this, SLOT(on_lineEditNodeFilt_textChanged(QString)));
}
connect(pComboBoxNode, SIGNAL(currentIndexChanged(int)), this, SLOT(on_comboBoxNode_currenstIndexChanged(int)));
}
void cSelectNode::setNodeModel(cRecordListModel * _pNodeModel, eTristate _nullable)
{
bbNode.begin();
setBool(_pNodeModel->nullable, _nullable);
_pNodeModel->joinWith(pComboBoxNode);
pDelete(pModelNode); // ?
pModelNode = _pNodeModel;
pModelNode->setConstFilter(constFilterNode, FT_SQL_WHERE);
pModelNode->setOwnerId(currentPlaceId(), _sPlaceId, TS_TRUE);
bbNode.end(false);
}
void cSelectNode::reset(bool f)
{
qlonglong nid = currentNodeId();
bbNode.begin();
pComboBoxZone->setCurrentIndex(0);
pComboBoxPLace->setCurrentIndex(0);
pComboBoxNode->setCurrentIndex(0);
bbNode.end(f && nid != currentNodeId());
}
void cSelectNode::nodeSetNull(bool _sig)
{
bbNode.begin();
pComboBoxNode->setCurrentIndex(0);
bbNode.end(_sig);
}
void cSelectNode::setLocalityFilter()
{
qlonglong pid = currentPlaceId();
if (pid != NULL_ID) {
pModelNode->setOwnerId(pid, _sPlaceId, TS_TRUE, "is_parent_place");
}
else {
pModelNode->setOwnerId(currentZoneId(), _sPlaceId, TS_TRUE, "is_place_in_zone");
}
}
void cSelectNode::setExcludedNode(qlonglong _nid)
{
if (_nid == NULL_ID) {
pModelNode->setFilter(QVariant(), OT_DEFAULT, FT_NO);
}
else {
pModelNode->setFilter(QString("node_id <> %1").arg(_nid), OT_DEFAULT, FT_SQL_WHERE);
}
}
void cSelectNode::setPatchInsertButton(QAbstractButton * p)
{
pButtonPatchInsert = p;
connect(p, SIGNAL(clicked()), this, SLOT(on_buttonPatchInsert_clicked()));
}
void cSelectNode::setNodeRefreshButton(QAbstractButton * p)
{
pButtonNodeRefresh = p;
connect(p, SIGNAL(clicked()), this, SLOT(refresh()));
}
void cSelectNode::setNodeInfoButton(QAbstractButton * p)
{
pButtonNodeInfo = p;
connect(p, SIGNAL(clicked()), this, SLOT(nodeReport()));
}
void cSelectNode::changeNodeConstFilter(const QString& _sql)
{
pModelNode->setConstFilter(_sql, FT_SQL_WHERE);
}
void cSelectNode::setDisableWidgets(bool f)
{
cSelectPlace::setDisableWidgets(f);
if (pLineEditNodeFilt != nullptr) pLineEditNodeFilt->setDisabled(f);
pComboBoxNode->setDisabled(f);
if (pButtonNodeRefresh != nullptr) pButtonNodeRefresh->setDisabled(f);
if (pButtonPatchInsert != nullptr) pButtonPatchInsert->setDisabled(f);
if (pButtonNodeInfo != nullptr) pButtonNodeInfo->setDisabled(f || currentNodeId() == NULL_ID);
}
void cSelectNode::refresh(bool f)
{
qlonglong nid = currentNodeId();
bbNode.begin();
cSelectPlace::refresh();
setLocalityFilter();
bbNode.end(f && nid != currentNodeId());
}
bool cSelectNode::emitChangeNode(bool f)
{
if (f && bbNode.test()) {
nodeIdChanged(currentNodeId());
nodeNameChanged(currentNodeName());
if (pButtonNodeInfo != nullptr) pButtonNodeInfo->setDisabled(currentNodeId() == NULL_ID);
return true;
}
return false;
}
void cSelectNode::setPlaceId(qlonglong pid, bool _sig)
{
if (currentPlaceId() != pid) {
bbPlace.begin();
setCurrentPlace(pid);
bbPlace.end(false);
}
bbNode.begin();
setLocalityFilter();
pComboBoxNode->setCurrentIndex(0);
on_comboBoxNode_currenstIndexChanged(0);
bbNode.end(_sig);
}
void cSelectNode::setEnabled(bool f)
{
setDisableWidgets(!f);
}
void cSelectNode::setDisabled(bool f)
{
setDisableWidgets(f);
}
void cSelectNode::nodeReport()
{
qlonglong nid = currentNodeId();
if (nid == NULL_ID) return;
QSqlQuery q = getQuery();
popupReportNode(static_cast<QWidget *>(this->parent()), q, nid);
}
eTristate cSelectNode::setCurrentNode(qlonglong _nid)
{
if (_nid == currentNodeId()) return TS_NULL;
bbNode.begin();
int ix = pModelNode->indexOf(_nid);
if (ix < 0) { // Ha nincs az aktuális listában
setCurrentZone(ALL_PLACE_GROUP_ID);
setCurrentPlace(NULL_ID);
setPlaceId(NULL_ID, false);
refresh(false);
ix = pModelNode->indexOf(_nid);
}
eTristate r = TS_TRUE;
if (ix >= 0) pComboBoxNode->setCurrentIndex(ix);
else r = TS_FALSE;
bbNode.end();
return r;
}
qlonglong cSelectNode::insertPatch(cPatch *pSample)
{
QSqlQuery q = getQuery();
cPatch *p = patchInsertDialog(q, qobject_cast<QWidget *>(parent()), pSample);
if (p == nullptr) return NULL_ID; // cancel
qlonglong pid = p->getId();
delete p;
pModelNode->setFilter();
setCurrentNode(pid);
return pid;
}
void cSelectNode::on_buttonPatchInsert_clicked()
{
cPatch sample;
sample.setId(_sPlaceId, currentPlaceId());
insertPatch(&sample);
}
void cSelectNode::on_lineEditNodeFilt_textChanged(const QString& s)
{
qlonglong nid = currentNodeId();
bbNode.begin();
if (s.isEmpty()) {
pModelNode->setFilter(QVariant(), OT_DEFAULT, FT_NO);
}
else {
pModelNode->setFilter(condAddJoker(s), OT_DEFAULT, FT_LIKE);
}
int nix = pModelNode->indexOf(nid);
if (nix < 0) {
nix = 0;
}
pComboBoxNode->setCurrentIndex(0);
bbNode.end(nid != currentNodeId());
}
void cSelectNode::on_comboBoxNode_currenstIndexChanged(int ix)
{
(void)ix;
emitChangeNode();
}
void cSelectNode::on_comboBoxZone_currenstIndexChanged(int)
{
if (currentPlaceId() == NULL_ID) { // Ha nincs hely, akkor zónára szűrünk
setPlaceId(NULL_ID);
}
}
/* ****** */
cSelectLinkedPort::cSelectLinkedPort(QComboBox *_pZone, QComboBox *_pPlace, QComboBox *_pNode, QComboBox *_pPort, QButtonGroup *_pType, QComboBox *_pShare, const tIntVector &_shList,
QLineEdit *_pPlaceFilt, QLineEdit *_pNodeFilt, const QString& _placeConstFilt, const QString& _nodeConstFilt,
QWidget *_par)
: cSelectNode(_pZone, _pPlace, _pNode, _pPlaceFilt, _pNodeFilt, _placeConstFilt, _nodeConstFilt, _par)
{
lockSlots = 0;
_isPatch = false;
pq = newQuery();
pComboBoxPort = _pPort;
pComboBoxShare = _pShare;
pButtonGroupType = _pType;
pModelShare = new cEnumListModel("portshare", NT_NOT_NULL, _shList, this);
pModelShare->joinWith(pComboBoxShare);
//pModelShare->
pModelPort = new cRecordListModel("patchable_ports", _sNul, this);
pModelPort->_setOrder(OT_ASC, _sPortIndex); // Index szerint sorba
pModelPort->setOwnerId(NULL_ID, _sNodeId, TS_FALSE); // Üres lista lessz
pModelPort->joinWith(pComboBoxPort);
lastLinkType = LT_FRONT;
lastShare = pModelShare->atInt(0);
lastPortId = 0; // Mindegy mennyi, csak ne NULL_ID legyen
setNodeId(NULL_ID);
connect(this, SIGNAL(nodeIdChanged(qlonglong)), this, SLOT(setNodeId(qlonglong)));
connect(pButtonGroupType, SIGNAL(buttonClicked(int)), this, SLOT(setLinkTypeByButtons(int)));
connect(pComboBoxPort, SIGNAL(currentIndexChanged(int)), this, SLOT(portChanged(int)));
connect(pComboBoxShare,SIGNAL(currentIndexChanged(int)), this, SLOT(changedShareType(int)));
}
cSelectLinkedPort::~cSelectLinkedPort()
{
delete pq;
}
void cSelectLinkedPort::setLink(cPhsLink& _lnk)
{
qlonglong pid = _lnk.getId(_sPortId2);
if (pid == NULL_ID) {
pComboBoxNode->setCurrentIndex(0);
return;
}
cNPort p;
cPatch *pn;
p.setById(*pq, pid);
pn = cNode::getNodeObjById(*pq, p.getId(_sNodeId));
setCurrentPlace(pn->getId(_sPlaceId));
int ix = pModelNode->indexOf(pn->getId());
// EZ ITT NEM jÓ!
// Ha lépkedünk a linkeken, akkor ez előfordulhat ! Pl. ha meg van adva szűrés.
// JAVÍTANDÓ!!!
if (ix <= 0) EXCEPTION(EPROGFAIL);
pComboBoxNode->setCurrentIndex(ix);
_isPatch = pn->tableoid() == cPatch::_descr_cPatch().tableoid();
ix = pModelPort->indexOf(pid);
if (ix < 0) EXCEPTION(EPROGFAIL);
pComboBoxPort->setCurrentIndex(ix);
ix = 0; // Share value index (comboBox)
if (_isPatch) {
ix = pModelShare->indexOf(int(_lnk.getId(_sPortShared)));
if (ix < 0) EXCEPTION(EPROGFAIL);
}
lastShare = pModelShare->atInt(ix);
lastLinkType = int(_lnk.getId(_sPhsLinkType2));
pComboBoxShare->setCurrentIndex(ix);
if ((lastLinkType == LT_TERM) == _isPatch) {
QString msg = tr("Database or program error. Port %1:%2, link type is %3.").arg(pn->getName(), p.getName(), linkType(lastLinkType, EX_IGNORE));
EXCEPTION(EDATA, lastLinkType, msg);
}
pComboBoxShare->setEnabled(lastLinkType == LT_FRONT);
pButtonGroupType->button(lastLinkType)->setChecked(true);
pButtonGroupType->button(LT_TERM)->setDisabled(_isPatch);
pButtonGroupType->button(LT_FRONT)->setEnabled(_isPatch);
pButtonGroupType->button(LT_BACK)->setEnabled(_isPatch);
}
void cSelectLinkedPort::setNodeId(qlonglong _nid)
{
lockSlots++;
bool nodeIsNull = _nid == NULL_ID;
pComboBoxPort->setDisabled(nodeIsNull);
if (!nodeIsNull) {
cPatch p;
p.setId(_nid);
qlonglong toid = p.fetchTableOId(*pq, EX_IGNORE); // Type?
if (toid == NULL_ID) { // Deleted ?!
lockSlots--;
refresh();
return;
}
_isPatch = toid == p.tableoid();
if (_isPatch) {
if (lastLinkType == LT_TERM) {
pButtonGroupType->button(LT_FRONT)->setChecked(true);
lastLinkType = LT_FRONT;
}
}
else {
if (lastLinkType != LT_TERM) {
pButtonGroupType->button(LT_TERM)->setChecked(true);
lastLinkType = LT_TERM;
}
}
}
pModelPort->setOwnerId(_nid);
pComboBoxPort->setCurrentIndex(0);
lockSlots--;
if (lockSlots == 0) setPortIdByIndex(0);
else if (lockSlots < 0) EXCEPTION(EPROGFAIL);
}
void cSelectLinkedPort::setPortIdByIndex(int ix)
{
qlonglong pid = pModelPort->atId(ix);
if (pid == lastPortId) return;
lockSlots++;
lastPortId = pid;
bool portIsNull = pid == NULL_ID;
if (!portIsNull) {
if (_isPatch) {
if (lastLinkType == LT_TERM) lastLinkType = LT_FRONT;
}
else {
lastLinkType = LT_TERM;
lastShare = ES_;
pComboBoxShare->setCurrentIndex(0);
}
pButtonGroupType->button(lastLinkType)->setChecked(true);
pButtonGroupType->button(LT_TERM)->setDisabled(_isPatch);
pButtonGroupType->button(LT_FRONT)->setEnabled(_isPatch);
pButtonGroupType->button(LT_BACK)->setEnabled(_isPatch);
pComboBoxShare->setEnabled(_isPatch);
}
else {
pButtonGroupType->button(LT_TERM) ->setDisabled(true);
pButtonGroupType->button(LT_FRONT)->setDisabled(true);
pButtonGroupType->button(LT_BACK) ->setDisabled(true);
pComboBoxShare->setDisabled(true);
}
lockSlots--;
if (lockSlots == 0) changedLink(pid, lastLinkType, lastShare);
else if (lockSlots < 0) EXCEPTION(EPROGFAIL);
}
void cSelectLinkedPort::setLinkTypeByButtons(int _id)
{
lastLinkType = _id;
if (lockSlots) return;
changedLink(currentPortId(), _id, lastShare);
}
void cSelectLinkedPort::changedShareType(int ix)
{
int sh = pModelShare->atInt(ix);
if (lastShare == sh) return;
lastShare = sh;
if (lockSlots == 0) changedLink(currentPortId(), lastLinkType, lastShare);
else if (lockSlots < 0) EXCEPTION(EPROGFAIL);
}
void cSelectLinkedPort::portChanged(int ix)
{
if (lockSlots) return;
changedLink(pModelPort->atId(ix), lastLinkType, lastShare);
}
/* ********************************************************************************* */
cSelectVlan::cSelectVlan(QComboBox *_pComboBoxId, QComboBox *_pComboBoxName, QWidget *_par)
: QObject(_par)
{
disableSignal = false;
pq = newQuery();
pevNull = &cEnumVal::enumVal(_sDatacharacter, DC_NULL);
pComboBoxId = _pComboBoxId;
pComboBoxName = _pComboBoxName;
actId = NULL_ID;
actName = _sNul;
pModelId = new cStringListDecModel;
pModelName = new cStringListDecModel;
pModelId->setDefDecoration(&cEnumVal::enumVal(_sDatacharacter, DC_ID));
pModelName->setDefDecoration(&cEnumVal::enumVal(_sDatacharacter, DC_NAME));
pComboBoxId->setModel(pModelId);
pComboBoxName->setModel(pModelName);
idList << NULL_ID;
nameList << dcViewShort(DC_NULL);
sIdList << dcViewShort(DC_NULL);
QString sql = "SELECT vlan_id, vlan_name FROM vlans";
if (execSql(*pq, sql)) do {
qlonglong id = pq->value(0).toLongLong();
idList << id;
nameList << pq->value(1).toString();
sIdList << QString::number(id);
} while (pq->next());
pModelId->setStringList(sIdList).setDecorationAt(0, pevNull);
pModelName->setStringList(nameList).setDecorationAt(0, pevNull);
pComboBoxId->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
actId = NULL_ID;
actName = _sNul;
connect(pComboBoxId, SIGNAL(currentIndexChanged(int)), this, SLOT(_changedId(int)));
connect(pComboBoxName, SIGNAL(currentIndexChanged(int)), this, SLOT(_changedName(int)));
changedId(actId);
changedName(actName);
}
cSelectVlan::~cSelectVlan()
{
delete pq;
}
void cSelectVlan::setCurrentByVlan(qlonglong _vid)
{
if (actId == _vid) return;
if (_vid == NULL_ID) {
pComboBoxId->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
return;
}
int ix = idList.indexOf(_vid);
if (ix >= 0) {
pComboBoxId->setCurrentIndex(ix);
pComboBoxName->setCurrentIndex(ix);
}
}
void cSelectVlan::setCurrentBySubNet(qlonglong _sid)
{
if (_sid == NULL_ID) {
setCurrentByVlan(NULL_ID);
return;
}
cSubNet s;
s.setById(*pq, _sid);
qlonglong vid = s.getId(_sVlanId);
setCurrentByVlan(vid);
}
void cSelectVlan::setDisable(bool f)
{
disableSignal = true;
pComboBoxId->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
pComboBoxId->setDisabled(f);
pComboBoxName->setDisabled(f);
disableSignal = false;
}
void cSelectVlan::_changedId(int ix)
{
if (disableSignal) return;
const cEnumVal *pe = pModelId->getDecorationAt(ix);
enumSetD(pComboBoxId, *pe);
actId = idList.at(ix);
changedId(actId);
pComboBoxName->setCurrentIndex(ix);
}
void cSelectVlan::_changedName(int ix)
{
if (disableSignal) return;
const cEnumVal *pe = pModelName->getDecorationAt(ix);
enumSetD(pComboBoxName, *pe);
bool isNull = ix == 0 && idList.first() == NULL_ID;
actName = isNull ? _sNul :nameList.at(ix);
changedName(actName);
pComboBoxId->setCurrentIndex(ix);
}
/* ********************************************************************************* */
cSelectSubNet::cSelectSubNet(QComboBox *_pComboBoxNet, QComboBox *_pComboBoxName, QWidget *_par)
: QObject(_par)
{
disableSignal = false;
pq = newQuery();
pevNull = &cEnumVal::enumVal(_sDatacharacter, DC_NULL);
pComboBoxNet = _pComboBoxNet;
pComboBoxName = _pComboBoxName;
actId = NULL_ID;
actName = _sNul;
pModelNet = new cStringListDecModel;
pModelName = new cStringListDecModel;
pModelNet->setDefDecoration(&cEnumVal::enumVal(_sDatacharacter, DC_DATA));
pModelName->setDefDecoration(&cEnumVal::enumVal(_sDatacharacter, DC_NAME));
pComboBoxNet->setModel(pModelNet);
pComboBoxName->setModel(pModelName);
idList << NULL_ID;
nameList << dcViewShort(DC_NULL);
sNetList << dcViewShort(DC_NULL);
netList << netAddress();
QString sql = "SELECT subnet_id, subnet_name, netaddr FROM subnets";
if (execSql(*pq, sql)) do {
QString sNet = pq->value(2).toString();
idList << pq->value(0).toLongLong();
nameList << pq->value(1).toString();
sNetList << sNet;
netList << netAddress(sNet);
} while (pq->next());
pModelNet->setStringList(sNetList).setDecorationAt(0, pevNull);;
pModelName->setStringList(nameList).setDecorationAt(0, pevNull);;
pComboBoxNet->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
connect(pComboBoxNet, SIGNAL(currentIndexChanged(int)), this, SLOT(_changedNet(int)));
connect(pComboBoxName, SIGNAL(currentIndexChanged(int)), this, SLOT(_changedName(int)));
changedId(actId);
changedName(actName);
}
cSelectSubNet::~cSelectSubNet()
{
delete pq;
}
qlonglong cSelectSubNet::currentId()
{
int ix = pComboBoxNet->currentIndex();
return isContIx(idList, ix) ? idList.at(ix) : NULL_ID;
}
void cSelectSubNet::setCurrentByVlan(qlonglong _vid)
{
if (_vid == NULL_ID) {
setCurrentBySubNet(NULL_ID);
return;
}
cSubNet sn;
sn.setId(_sVlanId, _vid);
int n = sn.completion(*pq);
while (n > 1 && sn.getId(__sSubnetType) != NT_PRIMARY) {
sn.next(*pq);
}
setCurrentBySubNet(sn.getId());
}
void cSelectSubNet::setCurrentBySubNet(qlonglong _sid)
{
if (actId == _sid) return;
if (_sid == NULL_ID) {
pComboBoxNet->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
return;
}
int ix = idList.indexOf(_sid);
if (ix >= 0) {
pComboBoxNet->setCurrentIndex(ix);
pComboBoxName->setCurrentIndex(ix);
}
}
void cSelectSubNet::setCurrentByAddress(QHostAddress& _a)
{
if (_a.isNull()) {
pComboBoxNet->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
return;
}
for (int i = 1; i < netList.size(); ++i) {
const QPair<QHostAddress, int>& n = static_cast<const QPair<QHostAddress, int>&>(netList.at(i));
if (_a.isInSubnet(n)) {
pComboBoxNet->setCurrentIndex(i);
pComboBoxName->setCurrentIndex(i);
return;
}
}
}
void cSelectSubNet::setDisable(bool f)
{
disableSignal = true;
pComboBoxNet->setCurrentIndex(0);
pComboBoxName->setCurrentIndex(0);
pComboBoxNet->setDisabled(f);
pComboBoxName->setDisabled(f);
disableSignal = false;
}
void cSelectSubNet::_changedNet(int ix)
{
if (disableSignal) return;
const cEnumVal *pe = pModelNet->getDecorationAt(ix);
enumSetD(pComboBoxNet, *pe);
actId = idList.at(ix);
changedId(actId);
pComboBoxName->setCurrentIndex(ix);
}
void cSelectSubNet::_changedName(int ix)
{
if (disableSignal) return;
const cEnumVal *pe = pModelName->getDecorationAt(ix);
enumSetD(pComboBoxName, *pe);
bool isNull = ix == 0 && idList.first() == NULL_ID;
actName = isNull ? _sNul :nameList.at(ix);
changedName(actName);
pComboBoxNet->setCurrentIndex(ix);
}
/* ********************************************************************************* */
cStringMapEdit::cStringMapEdit(bool _isDialog, tStringMap& _map, QWidget *par)
: QObject(par), isDialog(_isDialog), map(_map)
{
pButtons = nullptr;
pTableWidget = new QTableWidget(par);
if (isDialog) {
_pWidget = new QDialog(par);
_pWidget->setWindowTitle(tr("Paraméterek"));
QVBoxLayout *layout = new QVBoxLayout;
_pWidget->setLayout(layout);
layout->addWidget(pTableWidget, 1);
pButtons = new cDialogButtons(ENUM2SET(DBT_OK));
layout->addWidget(pButtons->pWidget());
connect(pButtons, SIGNAL(buttonClicked(int)), this, SLOT(clicked(int)));
}
else {
_pWidget = pTableWidget;
}
int rows = 0;
pTableWidget->horizontalHeader()->setStretchLastSection(true);
pTableWidget->setColumnCount(2);
QStringList head;
head << tr("Név") << tr("Érték");
pTableWidget->setHorizontalHeaderLabels(head);
Qt::ItemFlags flagConst = Qt::ItemIsEnabled;
Qt::ItemFlags flagEdit = Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable;
QTableWidgetItem *pi;
foreach (QString n, map.keys()) {
rows++;
pTableWidget->setRowCount(rows);
pi = new QTableWidgetItem(n);
pi->setFlags(flagConst);
pTableWidget->setItem(rows -1, 0, pi);
pi = new QTableWidgetItem(map[n]);
pi->setFlags(flagEdit);
pTableWidget->setItem(rows -1, 1, pi);
}
pTableWidget->resizeColumnsToContents();
connect(pTableWidget, SIGNAL(cellChanged(int,int)), this, SLOT(changed(int,int)));
}
cStringMapEdit::~cStringMapEdit()
{
delete _pWidget;
}
QDialog& cStringMapEdit::dialog()
{
if (!isDialog) EXCEPTION(EPROGFAIL);
return *static_cast<QDialog *>(_pWidget);
}
void cStringMapEdit::clicked(int id)
{
switch (id) {
case DBT_OK: dialog().accept(); break;
case DBT_CANCEL:dialog().reject(); break;
default: EXCEPTION(EPROGFAIL);
}
}
void cStringMapEdit::changed(int row, int column)
{
if (column != 1) return;
QString n = pTableWidget->item(row, 0)->text();
map[n] = pTableWidget->item(row, 1)->text();
}
|
csikfer/lanview2
|
lv2g/lv2widgets.cpp
|
C++
|
gpl-3.0
| 173,312
|
package geoling.util.sim.random;
/**
* The general interface for an random number generator.
*
* @author Institute of Stochastics, Ulm University
* @version 1.0, 2001-08-22
*/
public interface Generator {
/**
* Sets the seed of the random number generator. This method is optionally.
*
* @param seed
* the seed for the random number generator.
* @throws UnsupportedOperationException
* if this method is not supported.
*/
public void setSeed(long seed);
/**
* Returns the next random integer, i.e. the next 32 random bits.
*
* @return the next 32 random bits (= integer) generated.
*/
public int nextInt();
}
|
stochastics-ulm-university/GeoLing
|
src/geoling/util/sim/random/Generator.java
|
Java
|
gpl-3.0
| 672
|
from __future__ import division
from math import sqrt, pi
import unittest
from sapphire import clusters
class SimpleClusterTest(unittest.TestCase):
def setUp(self):
self.cluster = clusters.SimpleCluster(size=100)
def test_station_positions_and_angles(self):
a = sqrt(100 ** 2 - 50 ** 2)
expected = [(0, 2 * a / 3, 0, 0), (0, 0, 0, 0),
(-50, -a / 3, 0, 2 * pi / 3), (50, -a / 3, 0, -2 * pi / 3)]
actual = [(station.x[0], station.y[0], station.z[0], station.angle[0])
for station in self.cluster.stations]
for actual_value, expected_value in zip(actual, expected):
self.assert_tuple_almost_equal(actual_value, expected_value)
def test_get_detector_coordinates(self):
for station in self.cluster.stations:
for detector in station.detectors:
detector.get_xy_coordinates()
def assert_tuple_almost_equal(self, actual, expected):
self.assertIsInstance(actual, tuple)
self.assertIsInstance(expected, tuple)
msg = "Tuples differ: %s != %s" % (str(actual), str(expected))
for actual_value, expected_value in zip(actual, expected):
self.assertAlmostEqual(actual_value, expected_value, msg=msg)
if __name__ == '__main__':
unittest.main()
|
tomkooij/sapphire
|
sapphire/tests/test_clusters_acceptance.py
|
Python
|
gpl-3.0
| 1,327
|
using System.Linq;
using UnityEditor;
using UnityEngine;
namespace AdvancedAssetImporter
{
class ModelImporter : AssetPostprocessor
{
void OnPostprocessModel(GameObject gameObject)
{
foreach (GameObject child in gameObject.GetComponentsInChildren<Transform>().Where(t => t != gameObject.transform).Select(t => t.gameObject))
{
//Box collider
if (child.name.Contains("COL_BOX"))
{
BoxCollider box = child.AddComponent<BoxCollider>();
MeshFilter filter = child.GetComponent<MeshFilter>();
box.center = filter.sharedMesh.bounds.center;
box.size = filter.sharedMesh.bounds.size;
}
//Mesh collider
if (child.name.Contains("COL_MSH"))
{
MeshCollider collider = child.AddComponent<MeshCollider>();
MeshFilter filter = child.GetComponent<MeshFilter>();
collider.sharedMesh = filter.sharedMesh;
}
//Convex mesh collider
if (child.name.Contains("COL_CVX"))
{
MeshCollider collider = child.AddComponent<MeshCollider>();
MeshFilter filter = child.GetComponent<MeshFilter>();
collider.sharedMesh = filter.sharedMesh;
collider.convex = true;
}
//Sphere collider
if (child.name.Contains("COL_SPH"))
{
SphereCollider collider = child.AddComponent<SphereCollider>();
MeshFilter filter = child.GetComponent<MeshFilter>();
collider.radius = filter.sharedMesh.bounds.size.magnitude / 2;
}
//All static
if (child.name.Contains("STC_ALL"))
{
child.isStatic = true;
}
//Lightmap static
if (child.name.Contains("STC_LGT"))
{
child.AddStaticEditorFlags(StaticEditorFlags.LightmapStatic);
}
//Occluder static
if (child.name.Contains("STC_OCR"))
{
child.AddStaticEditorFlags(StaticEditorFlags.OccluderStatic);
}
//Occludee static
if (child.name.Contains("STC_OCE"))
{
child.AddStaticEditorFlags(StaticEditorFlags.OccludeeStatic);
}
//Batching static
if (child.name.Contains("STC_BTC"))
{
child.AddStaticEditorFlags(StaticEditorFlags.BatchingStatic);
}
//Navigation static
if (child.name.Contains("STC_NAV"))
{
child.AddStaticEditorFlags(StaticEditorFlags.NavigationStatic);
}
//Off mesh link static
if (child.name.Contains("STC_LNK"))
{
child.AddStaticEditorFlags(StaticEditorFlags.OffMeshLinkGeneration);
}
//Reflection probe static
if (child.name.Contains("STC_RFL"))
{
child.AddStaticEditorFlags(StaticEditorFlags.ReflectionProbeStatic);
}
//Removes mesh filter and renderer
if (child.name.Contains("RMV_MSH"))
{
Object.DestroyImmediate(child.GetComponent<MeshFilter>());
Object.DestroyImmediate(child.GetComponent<MeshRenderer>());
}
}
}
}
}
|
PixelatedLabs/AdvancedAssetImporter
|
Scripts/Editor/ModelImporter.cs
|
C#
|
gpl-3.0
| 2,769
|
/**
* @file : lpc17xx_uart.c
* @brief : Contains all functions support for UART firmware library on LPC17xx
* @version : 1.0
* @date : 18. Mar. 2009
* @author : HieuNguyen
**************************************************************************
* Software that is described herein is for illustrative purposes only
* which provides customers with programming information regarding the
* products. This software is supplied "AS IS" without any warranties.
* NXP Semiconductors assumes no responsibility or liability for the
* use of the software, conveys no license or title under any patent,
* copyright, or mask work right to the product. NXP Semiconductors
* reserves the right to make changes in the software without
* notification. NXP Semiconductors also make no representation or
* warranty that such application will be suitable for the specified
* use without further testing or modification.
**********************************************************************/
/* Peripheral group ----------------------------------------------------------- */
/** @addtogroup UART
* @{
*/
/* Includes ------------------------------------------------------------------- */
#include "lpc17xx_uart.h"
#include "lpc17xx_clkpwr.h"
/* If this source file built with example, the LPC17xx FW library configuration
* file in each example directory ("lpc17xx_libcfg.h") must be included,
* otherwise the default FW library configuration file must be included instead
*/
#ifdef __BUILD_WITH_EXAMPLE__
#include "lpc17xx_libcfg.h"
#else
#include "lpc17xx_libcfg_default.h"
#endif /* __BUILD_WITH_EXAMPLE__ */
#ifdef _UART
/* Private Types -------------------------------------------------------------- */
/** @defgroup UART_Private_Types
* @{
*/
/**
* @brief UART call-back function type definitions
*/
typedef struct {
fnTxCbs_Type *pfnTxCbs; // Transmit callback
fnRxCbs_Type *pfnRxCbs; // Receive callback
fnABCbs_Type *pfnABCbs; // Auto-Baudrate callback
fnErrCbs_Type *pfnErrCbs; // Error callback
} UART_CBS_Type;
/**
* @}
*/
/* Private Variables ---------------------------------------------------------- */
/** @defgroup UART_Private_Variables
* @{
*/
/** Call-back function pointer data */
UART_CBS_Type uartCbsDat[4] = {
{NULL, NULL, NULL, NULL},
{NULL, NULL, NULL, NULL},
{NULL, NULL, NULL, NULL},
{NULL, NULL, NULL, NULL},
};
/** UART1 modem status interrupt callback pointer data */
fnModemCbs_Type *pfnModemCbs = NULL;
/**
* @}
*/
/* Private Functions ---------------------------------------------------------- */
/** @defgroup UART_Private_Functions
* @{
*/
/**
* @brief Get UART number due to UART peripheral pointer
* @param[in] UARTx UART pointer
* @return UART number
*/
uint8_t getUartNum(LPC_UART_TypeDef *UARTx) {
if (UARTx == LPC_UART0) return (0);
else if (UARTx == (LPC_UART_TypeDef *)LPC_UART1) return (1);
else if (UARTx == LPC_UART2) return (2);
else return (3);
}
/*********************************************************************//**
* @brief Determines best dividers to get a target clock rate
* @param[in] UARTx Pointer to selected UART peripheral, should be
* UART0, UART1, UART2 or UART3.
* @param[in] baudrate Desired UART baud rate.
* @return Error status.
**********************************************************************/
Status uart_set_divisors(LPC_UART_TypeDef *UARTx, uint32_t baudrate)
{
Status errorStatus = ERROR;
uint32_t uClk;
uint32_t calcBaudrate = 0;
uint32_t temp = 0;
uint32_t mulFracDiv, dividerAddFracDiv;
uint32_t diviser = 0 ;
uint32_t mulFracDivOptimal = 1;
uint32_t dividerAddOptimal = 0;
uint32_t diviserOptimal = 0;
uint32_t relativeError = 0;
uint32_t relativeOptimalError = 100000;
/* get UART block clock */
if (UARTx == LPC_UART0)
{
uClk = CLKPWR_GetPCLK (CLKPWR_PCLKSEL_UART0);
}
else if (UARTx == (LPC_UART_TypeDef *)LPC_UART1)
{
uClk = CLKPWR_GetPCLK (CLKPWR_PCLKSEL_UART1);
}
else if (UARTx == LPC_UART2)
{
uClk = CLKPWR_GetPCLK (CLKPWR_PCLKSEL_UART2);
}
else /*mthomas, avoid warning: if (UARTx == LPC_UART3) */
{
uClk = CLKPWR_GetPCLK (CLKPWR_PCLKSEL_UART3);
}
uClk = uClk >> 4; /* div by 16 */
/* In the Uart IP block, baud rate is calculated using FDR and DLL-DLM registers
* The formula is :
* BaudRate= uClk * (mulFracDiv/(mulFracDiv+dividerAddFracDiv) / (16 * (DLL)
* It involves floating point calculations. That's the reason the formulae are adjusted with
* Multiply and divide method.*/
/* The value of mulFracDiv and dividerAddFracDiv should comply to the following expressions:
* 0 < mulFracDiv <= 15, 0 <= dividerAddFracDiv <= 15 */
for (mulFracDiv = 1 ; mulFracDiv <= 15 ;mulFracDiv++)
{
for (dividerAddFracDiv = 0 ; dividerAddFracDiv <= 15 ;dividerAddFracDiv++)
{
temp = (mulFracDiv * uClk) / ((mulFracDiv + dividerAddFracDiv));
diviser = temp / baudrate;
if ((temp % baudrate) > (baudrate / 2))
diviser++;
if (diviser > 2 && diviser < 65536)
{
calcBaudrate = temp / diviser;
if (calcBaudrate <= baudrate)
relativeError = baudrate - calcBaudrate;
else
relativeError = calcBaudrate - baudrate;
if ((relativeError < relativeOptimalError))
{
mulFracDivOptimal = mulFracDiv ;
dividerAddOptimal = dividerAddFracDiv;
diviserOptimal = diviser;
relativeOptimalError = relativeError;
if (relativeError == 0)
break;
}
} /* End of if */
} /* end of inner for loop */
if (relativeError == 0)
break;
} /* end of outer for loop */
if (relativeOptimalError < ((baudrate * UART_ACCEPTED_BAUDRATE_ERROR)/100))
{
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->LCR |= UART_LCR_DLAB_EN;
((LPC_UART1_TypeDef *)UARTx)->/*DLIER.*/DLM = UART_LOAD_DLM(diviserOptimal);
((LPC_UART1_TypeDef *)UARTx)->/*RBTHDLR.*/DLL = UART_LOAD_DLL(diviserOptimal);
/* Then reset DLAB bit */
((LPC_UART1_TypeDef *)UARTx)->LCR &= (~UART_LCR_DLAB_EN) & UART_LCR_BITMASK;
((LPC_UART1_TypeDef *)UARTx)->FDR = (UART_FDR_MULVAL(mulFracDivOptimal) \
| UART_FDR_DIVADDVAL(dividerAddOptimal)) & UART_FDR_BITMASK;
}
else
{
UARTx->LCR |= UART_LCR_DLAB_EN;
UARTx->/*DLIER.*/DLM = UART_LOAD_DLM(diviserOptimal);
UARTx->/*RBTHDLR.*/DLL = UART_LOAD_DLL(diviserOptimal);
/* Then reset DLAB bit */
UARTx->LCR &= (~UART_LCR_DLAB_EN) & UART_LCR_BITMASK;
UARTx->FDR = (UART_FDR_MULVAL(mulFracDivOptimal) \
| UART_FDR_DIVADDVAL(dividerAddOptimal)) & UART_FDR_BITMASK;
}
errorStatus = SUCCESS;
}
return errorStatus;
}
/*********************************************************************//**
* @brief General UART interrupt handler and router
* @param[in] UARTx Selected UART peripheral, should be UART0..3
* @return None
*
* Note:
* - Handles transmit, receive, and status interrupts for the UART.
* Based on the interrupt status, routes the interrupt to the
* respective call-back to be handled by the user application using
* this driver.
* - If callback is not installed, corresponding interrupt will be disabled
* - All these interrupt source below will be checked:
* - Transmit Holding Register Empty.
* - Received Data Available and Character Time Out.
* - Receive Line Status (not implemented)
* - End of auto-baud interrupt (not implemented)
* - Auto-Baudrate Time-Out interrupt (not implemented)
* - Modem Status interrupt (UART0 Modem functionality)
* - CTS signal transition interrupt (UART0 Modem functionality)
**********************************************************************/
void UART_GenIntHandler(LPC_UART_TypeDef *UARTx)
{
uint8_t pUart, modemsts;
uint32_t intsrc, tmp, tmp1;
pUart = getUartNum(UARTx);
/* Determine the interrupt source */
intsrc = UARTx->IIR;
tmp = intsrc & UART_IIR_INTID_MASK;
/*
* In case of using UART1 with full modem,
* interrupt ID = 0 that means modem status interrupt has been detected
*/
if (pUart == 1) {
if (tmp == 0){
// Check Modem status
modemsts = LPC_UART1->MSR & UART1_MSR_BITMASK;
// Call modem status call-back
if (pfnModemCbs != NULL){
pfnModemCbs(modemsts);
}
// disable modem status interrupt and CTS status change interrupt
// if its callback is not installed
else {
LPC_UART1->IER &= ~(UART1_IER_MSINT_EN | UART1_IER_CTSINT_EN);
}
}
}
// Receive Line Status
if (tmp == UART_IIR_INTID_RLS){
// Check line status
tmp1 = UARTx->LSR;
// Mask out the Receive Ready and Transmit Holding empty status
tmp1 &= (UART_LSR_OE | UART_LSR_PE | UART_LSR_FE \
| UART_LSR_BI | UART_LSR_RXFE);
// If any error exist
if (tmp1) {
// Call Call-back function with error input value
if (uartCbsDat[pUart].pfnErrCbs != NULL) {
uartCbsDat[pUart].pfnErrCbs(tmp1);
}
// Disable interrupt if its call-back is not install
else {
UARTx->IER &= ~(UART_IER_RLSINT_EN);
}
}
}
// Receive Data Available or Character time-out
if ((tmp == UART_IIR_INTID_RDA) || (tmp == UART_IIR_INTID_CTI)){
// Call Rx call back function
if (uartCbsDat[pUart].pfnRxCbs != NULL) {
uartCbsDat[pUart].pfnRxCbs();
}
// Disable interrupt if its call-back is not install
else {
UARTx->IER &= ~(UART_IER_RBRINT_EN);
}
}
// Transmit Holding Empty
if (tmp == UART_IIR_INTID_THRE){
// Call Tx call back function
if (uartCbsDat[pUart].pfnTxCbs != NULL) {
uartCbsDat[pUart].pfnTxCbs();
}
// Disable interrupt if its call-back is not install
else {
UARTx->IER &= ~(UART_IER_THREINT_EN);
}
}
intsrc &= (UART_IIR_ABEO_INT | UART_IIR_ABTO_INT);
// Check if End of auto-baudrate interrupt or Auto baudrate time out
if (intsrc){
// Clear interrupt pending
UARTx->ACR |= ((intsrc & UART_IIR_ABEO_INT) ? UART_ACR_ABEOINT_CLR : 0) \
| ((intsrc & UART_IIR_ABTO_INT) ? UART_ACR_ABTOINT_CLR : 0);
if (uartCbsDat[pUart].pfnABCbs != NULL) {
uartCbsDat[pUart].pfnABCbs(intsrc);
} else {
// Disable End of AB interrupt
UARTx->IER &= ~(UART_IER_ABEOINT_EN | UART_IER_ABTOINT_EN);
}
}
}
/**
* @}
*/
/* Public Functions ----------------------------------------------------------- */
/** @addtogroup UART_Public_Functions
* @{
*/
/*********************************************************************//**
* @brief De-initializes the UARTx peripheral registers to their
* default reset values.
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @return None
**********************************************************************/
void UART_DeInit(LPC_UART_TypeDef* UARTx)
{
// For debug mode
CHECK_PARAM(PARAM_UARTx(UARTx));
UART_TxCmd(UARTx, DISABLE);
#ifdef _UART0
if (UARTx == LPC_UART0)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART0, DISABLE);
}
#endif
#ifdef _UART1
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART1, DISABLE);
}
#endif
#ifdef _UART2
if (UARTx == LPC_UART2)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART2, DISABLE);
}
#endif
#ifdef _UART3
if (UARTx == LPC_UART3)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART3, DISABLE);
}
#endif
}
/********************************************************************//**
* @brief Initializes the UARTx peripheral according to the specified
* parameters in the UART_ConfigStruct.
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @param[in] UART_ConfigStruct Pointer to a UART_CFG_Type structure
* that contains the configuration information for the
* specified UART peripheral.
* @return None
*********************************************************************/
void UART_Init(LPC_UART_TypeDef *UARTx, UART_CFG_Type *UART_ConfigStruct)
{
uint32_t tmp;
// For debug mode
CHECK_PARAM(PARAM_UARTx(UARTx));
CHECK_PARAM(PARAM_UART_DATABIT(UART_ConfigStruct->Databits));
CHECK_PARAM(PARAM_UART_STOPBIT(UART_ConfigStruct->Stopbits));
CHECK_PARAM(PARAM_UART_PARITY(UART_ConfigStruct->Parity));
#ifdef _UART0
if(UARTx == LPC_UART0)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART0, ENABLE);
}
#endif
#ifdef _UART1
if(((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART1, ENABLE);
}
#endif
#ifdef _UART2
if(UARTx == LPC_UART2)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART2, ENABLE);
}
#endif
#ifdef _UART3
if(UARTx == LPC_UART3)
{
/* Set up clock and power for UART module */
CLKPWR_ConfigPPWR (CLKPWR_PCONP_PCUART3, ENABLE);
}
#endif
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
/* FIFOs are empty */
((LPC_UART1_TypeDef *)UARTx)->/*IIFCR.*/FCR = ( UART_FCR_FIFO_EN \
| UART_FCR_RX_RS | UART_FCR_TX_RS);
// Disable FIFO
((LPC_UART1_TypeDef *)UARTx)->/*IIFCR.*/FCR = 0;
// Dummy reading
while (((LPC_UART1_TypeDef *)UARTx)->LSR & UART_LSR_RDR)
{
tmp = ((LPC_UART1_TypeDef *)UARTx)->/*RBTHDLR.*/RBR;
}
((LPC_UART1_TypeDef *)UARTx)->TER = UART_TER_TXEN;
// Wait for current transmit complete
while (!(((LPC_UART1_TypeDef *)UARTx)->LSR & UART_LSR_THRE));
// Disable Tx
((LPC_UART1_TypeDef *)UARTx)->TER = 0;
// Disable interrupt
((LPC_UART1_TypeDef *)UARTx)->/*DLIER.*/IER = 0;
// Set LCR to default state
((LPC_UART1_TypeDef *)UARTx)->LCR = 0;
// Set ACR to default state
((LPC_UART1_TypeDef *)UARTx)->ACR = 0;
// Set Modem Control to default state
((LPC_UART1_TypeDef *)UARTx)->MCR = 0;
// Set RS485 control to default state
((LPC_UART1_TypeDef *)UARTx)->RS485CTRL = 0;
// Set RS485 delay timer to default state
((LPC_UART1_TypeDef *)UARTx)->RS485DLY = 0;
// Set RS485 addr match to default state
((LPC_UART1_TypeDef *)UARTx)->ADRMATCH = 0;
//Dummy Reading to Clear Status
tmp = ((LPC_UART1_TypeDef *)UARTx)->MSR;
tmp = ((LPC_UART1_TypeDef *)UARTx)->LSR;
}
else
{
/* FIFOs are empty */
UARTx->/*IIFCR.*/FCR = ( UART_FCR_FIFO_EN | UART_FCR_RX_RS | UART_FCR_TX_RS);
// Disable FIFO
UARTx->/*IIFCR.*/FCR = 0;
// Dummy reading
while (UARTx->LSR & UART_LSR_RDR)
{
tmp = UARTx->/*RBTHDLR.*/RBR;
}
UARTx->TER = UART_TER_TXEN;
// Wait for current transmit complete
while (!(UARTx->LSR & UART_LSR_THRE));
// Disable Tx
UARTx->TER = 0;
// Disable interrupt
UARTx->/*DLIER.*/IER = 0;
// Set LCR to default state
UARTx->LCR = 0;
// Set ACR to default state
UARTx->ACR = 0;
// Dummy reading
tmp = UARTx->LSR;
}
if (UARTx == LPC_UART3)
{
// Set IrDA to default state
UARTx->ICR = 0;
}
// Set Line Control register ----------------------------
uart_set_divisors(UARTx, (UART_ConfigStruct->Baud_rate));
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
tmp = (((LPC_UART1_TypeDef *)UARTx)->LCR & (UART_LCR_DLAB_EN | UART_LCR_BREAK_EN)) \
& UART_LCR_BITMASK;
}
else
{
tmp = (UARTx->LCR & (UART_LCR_DLAB_EN | UART_LCR_BREAK_EN)) & UART_LCR_BITMASK;
}
switch (UART_ConfigStruct->Databits){
case UART_DATABIT_5:
tmp |= UART_LCR_WLEN5;
break;
case UART_DATABIT_6:
tmp |= UART_LCR_WLEN6;
break;
case UART_DATABIT_7:
tmp |= UART_LCR_WLEN7;
break;
case UART_DATABIT_8:
default:
tmp |= UART_LCR_WLEN8;
break;
}
if (UART_ConfigStruct->Parity == UART_PARITY_NONE)
{
// Do nothing...
}
else
{
tmp |= UART_LCR_PARITY_EN;
switch (UART_ConfigStruct->Parity)
{
case UART_PARITY_ODD:
tmp |= UART_LCR_PARITY_ODD;
break;
case UART_PARITY_EVEN:
tmp |= UART_LCR_PARITY_EVEN;
break;
case UART_PARITY_SP_1:
tmp |= UART_LCR_PARITY_F_1;
break;
case UART_PARITY_SP_0:
tmp |= UART_LCR_PARITY_F_0;
break;
default:
break;
}
}
switch (UART_ConfigStruct->Stopbits){
case UART_STOPBIT_2:
tmp |= UART_LCR_STOPBIT_SEL;
break;
case UART_STOPBIT_1:
default:
// Do no thing
break;
}
// Write back to LCR, configure FIFO and Disable Tx
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->LCR = (uint8_t)(tmp & UART_LCR_BITMASK);
}
else
{
UARTx->LCR = (uint8_t)(tmp & UART_LCR_BITMASK);
}
}
/*****************************************************************************//**
* @brief Fills each UART_InitStruct member with its default value:
* 9600 bps
* 8-bit data
* 1 Stopbit
* None Parity
* @param[in] UART_InitStruct Pointer to a UART_CFG_Type structure
* which will be initialized.
* @return None
*******************************************************************************/
void UART_ConfigStructInit(UART_CFG_Type *UART_InitStruct)
{
UART_InitStruct->Baud_rate = 9600;
UART_InitStruct->Databits = UART_DATABIT_8;
UART_InitStruct->Parity = UART_PARITY_NONE;
UART_InitStruct->Stopbits = UART_STOPBIT_1;
}
/*********************************************************************//**
* @brief Transmit a single data through UART peripheral
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @param[in] Data Data to transmit (must be 8-bit long)
* @return none
**********************************************************************/
void UART_SendData(LPC_UART_TypeDef* UARTx, uint8_t Data)
{
CHECK_PARAM(PARAM_UARTx(UARTx));
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->/*RBTHDLR.*/THR = Data & UART_THR_MASKBIT;
}
else
{
UARTx->/*RBTHDLR.*/THR = Data & UART_THR_MASKBIT;
}
}
/*********************************************************************//**
* @brief Receive a single data from UART peripheral
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @return Data received
**********************************************************************/
uint8_t UART_ReceiveData(LPC_UART_TypeDef* UARTx)
{
CHECK_PARAM(PARAM_UARTx(UARTx));
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
return (((LPC_UART1_TypeDef *)UARTx)->/*RBTHDLR.*/RBR & UART_RBR_MASKBIT);
}
else
{
return (UARTx->/*RBTHDLR.*/RBR & UART_RBR_MASKBIT);
}
}
/*********************************************************************//**
* @brief Force BREAK character on UART line, output pin UARTx TXD is
forced to logic 0.
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @return none
**********************************************************************/
void UART_ForceBreak(LPC_UART_TypeDef* UARTx)
{
CHECK_PARAM(PARAM_UARTx(UARTx));
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->LCR |= UART_LCR_BREAK_EN;
}
else
{
UARTx->LCR |= UART_LCR_BREAK_EN;
}
}
#ifdef _UART3
/*********************************************************************//**
* @brief Enable or disable inverting serial input function of IrDA
* on UART peripheral.
* @param[in] UARTx UART peripheral selected, should be UART3 (only)
* @param[in] NewState New state of inverting serial input, should be:
* - ENABLE: Enable this function.
* - DISABLE: Disable this function.
* @return none
**********************************************************************/
void UART_IrDAInvtInputCmd(LPC_UART_TypeDef* UARTx, FunctionalState NewState)
{
CHECK_PARAM(PARAM_UART_IrDA(UARTx));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(NewState));
if (NewState == ENABLE)
{
UARTx->ICR |= UART_ICR_IRDAINV;
}
else if (NewState == DISABLE)
{
UARTx->ICR &= (~UART_ICR_IRDAINV) & UART_ICR_BITMASK;
}
}
/*********************************************************************//**
* @brief Enable or disable IrDA function on UART peripheral.
* @param[in] UARTx UART peripheral selected, should be UART3 (only)
* @param[in] NewState New state of IrDA function, should be:
* - ENABLE: Enable this function.
* - DISABLE: Disable this function.
* @return none
**********************************************************************/
void UART_IrDACmd(LPC_UART_TypeDef* UARTx, FunctionalState NewState)
{
CHECK_PARAM(PARAM_UART_IrDA(UARTx));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(NewState));
if (NewState == ENABLE)
{
UARTx->ICR |= UART_ICR_IRDAEN;
}
else
{
UARTx->ICR &= (~UART_ICR_IRDAEN) & UART_ICR_BITMASK;
}
}
/*********************************************************************//**
* @brief Configure Pulse divider for IrDA function on UART peripheral.
* @param[in] UARTx UART peripheral selected, should be UART3 (only)
* @param[in] PulseDiv Pulse Divider value from Peripheral clock,
* should be one of the following:
- UART_IrDA_PULSEDIV2 : Pulse width = 2 * Tpclk
- UART_IrDA_PULSEDIV4 : Pulse width = 4 * Tpclk
- UART_IrDA_PULSEDIV8 : Pulse width = 8 * Tpclk
- UART_IrDA_PULSEDIV16 : Pulse width = 16 * Tpclk
- UART_IrDA_PULSEDIV32 : Pulse width = 32 * Tpclk
- UART_IrDA_PULSEDIV64 : Pulse width = 64 * Tpclk
- UART_IrDA_PULSEDIV128 : Pulse width = 128 * Tpclk
- UART_IrDA_PULSEDIV256 : Pulse width = 256 * Tpclk
* @return none
**********************************************************************/
void UART_IrDAPulseDivConfig(LPC_UART_TypeDef *UARTx, UART_IrDA_PULSE_Type PulseDiv)
{
uint32_t tmp, tmp1;
CHECK_PARAM(PARAM_UART_IrDA(UARTx));
CHECK_PARAM(PARAM_UART_IrDA_PULSEDIV(PulseDiv));
tmp1 = UART_ICR_PULSEDIV(PulseDiv);
tmp = UARTx->ICR & (~UART_ICR_PULSEDIV(7));
tmp |= tmp1 | UART_ICR_FIXPULSE_EN;
UARTx->ICR = tmp & UART_ICR_BITMASK;
}
#endif
/********************************************************************//**
* @brief Enable or disable specified UART interrupt.
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @param[in] UARTIntCfg Specifies the interrupt flag,
* should be one of the following:
- UART_INTCFG_RBR : RBR Interrupt enable
- UART_INTCFG_THRE : THR Interrupt enable
- UART_INTCFG_RLS : RX line status interrupt enable
- UART1_INTCFG_MS : Modem status interrupt enable (UART1 only)
- UART1_INTCFG_CTS : CTS1 signal transition interrupt enable (UART1 only)
- UART_INTCFG_ABEO : Enables the end of auto-baud interrupt
- UART_INTCFG_ABTO : Enables the auto-baud time-out interrupt
* @param[in] NewState New state of specified UART interrupt type,
* should be:
* - ENALBE: Enable this UART interrupt type.
* - DISALBE: Disable this UART interrupt type.
* @return None
*********************************************************************/
void UART_IntConfig(LPC_UART_TypeDef *UARTx, UART_INT_Type UARTIntCfg, FunctionalState NewState)
{
uint32_t tmp;
CHECK_PARAM(PARAM_UARTx(UARTx));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(NewState));
switch(UARTIntCfg){
case UART_INTCFG_RBR:
tmp = UART_IER_RBRINT_EN;
break;
case UART_INTCFG_THRE:
tmp = UART_IER_THREINT_EN;
break;
case UART_INTCFG_RLS:
tmp = UART_IER_RLSINT_EN;
break;
case UART1_INTCFG_MS:
tmp = UART1_IER_MSINT_EN;
break;
case UART1_INTCFG_CTS:
tmp = UART1_IER_CTSINT_EN;
break;
case UART_INTCFG_ABEO:
tmp = UART_IER_ABEOINT_EN;
break;
case UART_INTCFG_ABTO:
tmp = UART_IER_ABTOINT_EN;
break;
// mthomas, avoid warning:
default:
tmp = UART_IER_RBRINT_EN;
break;
}
if ((LPC_UART1_TypeDef *) UARTx == LPC_UART1)
{
CHECK_PARAM((PARAM_UART_INTCFG(UARTIntCfg)) || (PARAM_UART1_INTCFG(UARTIntCfg)));
}
else
{
CHECK_PARAM(PARAM_UART_INTCFG(UARTIntCfg));
}
if (NewState == ENABLE)
{
if ((LPC_UART1_TypeDef *) UARTx == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->/*DLIER.*/IER |= tmp;
}
else
{
UARTx->/*DLIER.*/IER |= tmp;
}
}
else
{
if ((LPC_UART1_TypeDef *) UARTx == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->/*DLIER.*/IER &= (~tmp) & UART1_IER_BITMASK;
}
else
{
UARTx->/*DLIER.*/IER &= (~tmp) & UART_IER_BITMASK;
}
}
}
/********************************************************************//**
* @brief Get current value of Line Status register in UART peripheral.
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @return Current value of Line Status register in UART peripheral.
* Note: The return value of this function must be ANDed with each member in
* UART_LS_Type enumeration to determine current flag status
* corresponding to each Line status type. Because some flags in
* Line Status register will be cleared after reading, the next reading
* Line Status register could not be correct. So this function used to
* read Line status register in one time only, then the return value
* used to check all flags.
*********************************************************************/
uint8_t UART_GetLineStatus(LPC_UART_TypeDef* UARTx)
{
CHECK_PARAM(PARAM_UARTx(UARTx));
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
return ((((LPC_UART1_TypeDef *)LPC_UART1)->LSR) & UART_LSR_BITMASK);
}
else
{
return ((UARTx->LSR) & UART_LSR_BITMASK);
}
}
/*********************************************************************//**
* @brief Check whether if UART is busy or not
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @return RESET if UART is not busy, otherwise return SET.
**********************************************************************/
FlagStatus UART_CheckBusy(LPC_UART_TypeDef *UARTx)
{
if (UARTx->LSR & UART_LSR_TEMT){
return RESET;
} else {
return SET;
}
}
/*********************************************************************//**
* @brief Configure FIFO function on selected UART peripheral
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @param[in] FIFOCfg Pointer to a UART_FIFO_CFG_Type Structure that
* contains specified information about FIFO configuration
* @return none
**********************************************************************/
void UART_FIFOConfig(LPC_UART_TypeDef *UARTx, UART_FIFO_CFG_Type *FIFOCfg)
{
uint8_t tmp = 0;
CHECK_PARAM(PARAM_UARTx(UARTx));
CHECK_PARAM(PARAM_UART_FIFO_LEVEL(FIFOCfg->FIFO_Level));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(FIFOCfg->FIFO_DMAMode));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(FIFOCfg->FIFO_ResetRxBuf));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(FIFOCfg->FIFO_ResetTxBuf));
tmp |= UART_FCR_FIFO_EN;
switch (FIFOCfg->FIFO_Level){
case UART_FIFO_TRGLEV0:
tmp |= UART_FCR_TRG_LEV0;
break;
case UART_FIFO_TRGLEV1:
tmp |= UART_FCR_TRG_LEV1;
break;
case UART_FIFO_TRGLEV2:
tmp |= UART_FCR_TRG_LEV2;
break;
case UART_FIFO_TRGLEV3:
default:
tmp |= UART_FCR_TRG_LEV3;
break;
}
if (FIFOCfg->FIFO_ResetTxBuf == ENABLE)
{
tmp |= UART_FCR_TX_RS;
}
if (FIFOCfg->FIFO_ResetRxBuf == ENABLE)
{
tmp |= UART_FCR_RX_RS;
}
if (FIFOCfg->FIFO_DMAMode == ENABLE)
{
tmp |= UART_FCR_DMAMODE_SEL;
}
//write to FIFO control register
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->/*IIFCR.*/FCR = tmp & UART_FCR_BITMASK;
}
else
{
UARTx->/*IIFCR.*/FCR = tmp & UART_FCR_BITMASK;
}
}
/*****************************************************************************//**
* @brief Fills each UART_FIFOInitStruct member with its default value:
* - FIFO_DMAMode = DISABLE
* - FIFO_Level = UART_FIFO_TRGLEV0
* - FIFO_ResetRxBuf = ENABLE
* - FIFO_ResetTxBuf = ENABLE
* - FIFO_State = ENABLE
* @param[in] UART_FIFOInitStruct Pointer to a UART_FIFO_CFG_Type structure
* which will be initialized.
* @return None
*******************************************************************************/
void UART_FIFOConfigStructInit(UART_FIFO_CFG_Type *UART_FIFOInitStruct)
{
UART_FIFOInitStruct->FIFO_DMAMode = DISABLE;
UART_FIFOInitStruct->FIFO_Level = UART_FIFO_TRGLEV0;
UART_FIFOInitStruct->FIFO_ResetRxBuf = ENABLE;
UART_FIFOInitStruct->FIFO_ResetTxBuf = ENABLE;
}
/*********************************************************************//**
* @brief Start/Stop Auto Baudrate activity
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @param[in] ABConfigStruct A pointer to UART_AB_CFG_Type structure that
* contains specified information about UART
* auto baudrate configuration
* @param[in] NewState New State of Auto baudrate activity, should be:
* - ENABLE: Start this activity
* - DISABLE: Stop this activity
* Note: Auto-baudrate mode enable bit will be cleared once this mode
* completed.
* @return none
**********************************************************************/
void UART_ABCmd(LPC_UART_TypeDef *UARTx, UART_AB_CFG_Type *ABConfigStruct, \
FunctionalState NewState)
{
uint32_t tmp;
CHECK_PARAM(PARAM_UARTx(UARTx));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(NewState));
tmp = 0;
if (NewState == ENABLE) {
if (ABConfigStruct->ABMode == UART_AUTOBAUD_MODE1){
tmp |= UART_ACR_MODE;
}
if (ABConfigStruct->AutoRestart == ENABLE){
tmp |= UART_ACR_AUTO_RESTART;
}
}
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
if (NewState == ENABLE)
{
// Clear DLL and DLM value
((LPC_UART1_TypeDef *)UARTx)->LCR |= UART_LCR_DLAB_EN;
((LPC_UART1_TypeDef *)UARTx)->DLL = 0;
((LPC_UART1_TypeDef *)UARTx)->DLM = 0;
((LPC_UART1_TypeDef *)UARTx)->LCR &= ~UART_LCR_DLAB_EN;
// FDR value must be reset to default value
((LPC_UART1_TypeDef *)UARTx)->FDR = 0x10;
((LPC_UART1_TypeDef *)UARTx)->ACR = UART_ACR_START | tmp;
}
else
{
((LPC_UART1_TypeDef *)UARTx)->ACR = 0;
}
}
else
{
if (NewState == ENABLE)
{
// Clear DLL and DLM value
UARTx->LCR |= UART_LCR_DLAB_EN;
UARTx->DLL = 0;
UARTx->DLM = 0;
UARTx->LCR &= ~UART_LCR_DLAB_EN;
// FDR value must be reset to default value
UARTx->FDR = 0x10;
UARTx->ACR = UART_ACR_START | tmp;
}
else
{
UARTx->ACR = 0;
}
}
}
/*********************************************************************//**
* @brief Enable/Disable transmission on UART TxD pin
* @param[in] UARTx UART peripheral selected, should be UART0, UART1,
* UART2 or UART3.
* @param[in] NewState New State of Tx transmission function, should be:
* - ENABLE: Enable this function
- DISABLE: Disable this function
* @return none
**********************************************************************/
void UART_TxCmd(LPC_UART_TypeDef *UARTx, FunctionalState NewState)
{
CHECK_PARAM(PARAM_UARTx(UARTx));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(NewState));
if (NewState == ENABLE)
{
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->TER |= UART_TER_TXEN;
}
else
{
UARTx->TER |= UART_TER_TXEN;
}
}
else
{
if (((LPC_UART1_TypeDef *)UARTx) == LPC_UART1)
{
((LPC_UART1_TypeDef *)UARTx)->TER &= (~UART_TER_TXEN) & UART_TER_BITMASK;
}
else
{
UARTx->TER &= (~UART_TER_TXEN) & UART_TER_BITMASK;
}
}
}
#ifdef _UART1
/*********************************************************************//**
* @brief Force pin DTR/RTS corresponding to given state (Full modem mode)
* @param[in] UARTx UART1 (only)
* @param[in] Pin Pin that NewState will be applied to, should be:
* - UART1_MODEM_PIN_DTR: DTR pin.
* - UART1_MODEM_PIN_RTS: RTS pin.
* @param[in] NewState New State of DTR/RTS pin, should be:
* - INACTIVE: Force the pin to inactive signal.
- ACTIVE: Force the pin to active signal.
* @return none
**********************************************************************/
void UART_FullModemForcePinState(LPC_UART1_TypeDef *UARTx, UART_MODEM_PIN_Type Pin, \
UART1_SignalState NewState)
{
uint8_t tmp = 0;
CHECK_PARAM(PARAM_UART1_MODEM(UARTx));
CHECK_PARAM(PARAM_UART1_MODEM_PIN(Pin));
CHECK_PARAM(PARAM_UART1_SIGNALSTATE(NewState));
switch (Pin){
case UART1_MODEM_PIN_DTR:
tmp = UART1_MCR_DTR_CTRL;
break;
case UART1_MODEM_PIN_RTS:
tmp = UART1_MCR_RTS_CTRL;
break;
default:
break;
}
if (NewState == ACTIVE){
UARTx->MCR |= tmp;
} else {
UARTx->MCR &= (~tmp) & UART1_MCR_BITMASK;
}
}
/*********************************************************************//**
* @brief Configure Full Modem mode for UART peripheral
* @param[in] UARTx UART1 (only)
* @param[in] Mode Full Modem mode, should be:
* - UART1_MODEM_MODE_LOOPBACK: Loop back mode.
* - UART1_MODEM_MODE_AUTO_RTS: Auto-RTS mode.
* - UART1_MODEM_MODE_AUTO_CTS: Auto-CTS mode.
* @param[in] NewState New State of this mode, should be:
* - ENABLE: Enable this mode.
- DISABLE: Disable this mode.
* @return none
**********************************************************************/
void UART_FullModemConfigMode(LPC_UART1_TypeDef *UARTx, UART_MODEM_MODE_Type Mode, \
FunctionalState NewState)
{
uint8_t tmp;
CHECK_PARAM(PARAM_UART1_MODEM(UARTx));
CHECK_PARAM(PARAM_UART1_MODEM_MODE(Mode));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(NewState));
switch(Mode){
case UART1_MODEM_MODE_LOOPBACK:
tmp = UART1_MCR_LOOPB_EN;
break;
case UART1_MODEM_MODE_AUTO_RTS:
tmp = UART1_MCR_AUTO_RTS_EN;
break;
case UART1_MODEM_MODE_AUTO_CTS:
tmp = UART1_MCR_AUTO_CTS_EN;
break;
default:
// mthomas, avoid warning:
tmp = UART1_MCR_LOOPB_EN;
break;
}
if (NewState == ENABLE)
{
UARTx->MCR |= tmp;
}
else
{
UARTx->MCR &= (~tmp) & UART1_MCR_BITMASK;
}
}
/*********************************************************************//**
* @brief Get current status of modem status register
* @param[in] UARTx UART1 (only)
* @return Current value of modem status register
* Note: The return value of this function must be ANDed with each member
* UART_MODEM_STAT_type enumeration to determine current flag status
* corresponding to each modem flag status. Because some flags in
* modem status register will be cleared after reading, the next reading
* modem register could not be correct. So this function used to
* read modem status register in one time only, then the return value
* used to check all flags.
**********************************************************************/
uint8_t UART_FullModemGetStatus(LPC_UART1_TypeDef *UARTx)
{
CHECK_PARAM(PARAM_UART1_MODEM(UARTx));
return ((UARTx->MSR) & UART1_MSR_BITMASK);
}
/*********************************************************************//**
* @brief Configure UART peripheral in RS485 mode according to the specified
* parameters in the RS485ConfigStruct.
* @param[in] UARTx UART1 (only)
* @param[in] RS485ConfigStruct Pointer to a UART1_RS485_CTRLCFG_Type structure
* that contains the configuration information for specified UART
* in RS485 mode.
* @return None
**********************************************************************/
void UART_RS485Config(LPC_UART1_TypeDef *UARTx, UART1_RS485_CTRLCFG_Type *RS485ConfigStruct)
{
uint32_t tmp;
CHECK_PARAM(PARAM_UART1_MODEM(UARTx));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(RS485ConfigStruct->AutoAddrDetect_State));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(RS485ConfigStruct->AutoDirCtrl_State));
CHECK_PARAM(PARAM_UART1_RS485_CFG_DELAYVALUE(RS485ConfigStruct->DelayValue));
CHECK_PARAM(PARAM_SETSTATE(RS485ConfigStruct->DirCtrlPol_Level));
CHECK_PARAM(PARAM_UART_RS485_DIRCTRL_PIN(RS485ConfigStruct->DirCtrlPin));
CHECK_PARAM(PARAM_UART1_RS485_CFG_MATCHADDRVALUE(RS485ConfigStruct->MatchAddrValue));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(RS485ConfigStruct->NormalMultiDropMode_State));
CHECK_PARAM(PARAM_FUNCTIONALSTATE(RS485ConfigStruct->Rx_State));
tmp = 0;
// If Auto Direction Control is enabled - This function is used in Master mode
if (RS485ConfigStruct->AutoDirCtrl_State == ENABLE)
{
tmp |= UART1_RS485CTRL_DCTRL_EN;
// Set polar
if (RS485ConfigStruct->DirCtrlPol_Level == SET)
{
tmp |= UART1_RS485CTRL_OINV_1;
}
// Set pin according to
if (RS485ConfigStruct->DirCtrlPin == UART1_RS485_DIRCTRL_DTR)
{
tmp |= UART1_RS485CTRL_SEL_DTR;
}
// Fill delay time
UARTx->RS485DLY = RS485ConfigStruct->DelayValue & UART1_RS485DLY_BITMASK;
}
// MultiDrop mode is enable
if (RS485ConfigStruct->NormalMultiDropMode_State == ENABLE)
{
tmp |= UART1_RS485CTRL_NMM_EN;
}
// Auto Address Detect function
if (RS485ConfigStruct->AutoAddrDetect_State == ENABLE)
{
tmp |= UART1_RS485CTRL_AADEN;
// Fill Match Address
UARTx->ADRMATCH = RS485ConfigStruct->MatchAddrValue & UART1_RS485ADRMATCH_BITMASK;
}
// Receiver is disable
if (RS485ConfigStruct->Rx_State == DISABLE)
{
tmp |= UART1_RS485CTRL_RX_DIS;
}
// write back to RS485 control register
UARTx->RS485CTRL = tmp & UART1_RS485CTRL_BITMASK;
// Enable Parity function and leave parity in stick '0' parity as default
UARTx->LCR |= (UART_LCR_PARITY_F_0 | UART_LCR_PARITY_EN);
}
/**
* @brief Enable/Disable receiver in RS485 module in UART1
* @param[in] UARTx UART1 only.
* @param[in] NewState New State of command, should be:
* - ENABLE: Enable this function.
* - DISABLE: Disable this function.
* @return None
*/
void UART_RS485ReceiverCmd(LPC_UART1_TypeDef *UARTx, FunctionalState NewState)
{
if (NewState == ENABLE){
UARTx->RS485CTRL &= ~UART1_RS485CTRL_RX_DIS;
} else {
UARTx->RS485CTRL |= UART1_RS485CTRL_RX_DIS;
}
}
/**
* @brief Send data on RS485 bus with specified parity stick value (9-bit mode).
* @param[in] UARTx UART1 (only).
* @param[in] pDatFrm Pointer to data frame.
* @param[in] size Size of data.
* @param[in] ParityStick Parity Stick value, should be 0 or 1.
* @return None.
*/
uint32_t UART_RS485Send(LPC_UART1_TypeDef *UARTx, uint8_t *pDatFrm, \
uint32_t size, uint8_t ParityStick)
{
uint8_t tmp, save;
uint32_t cnt;
if (ParityStick){
save = tmp = UARTx->LCR & UART_LCR_BITMASK;
tmp &= ~(UART_LCR_PARITY_EVEN);
UARTx->LCR = tmp;
cnt = UART_Send((LPC_UART_TypeDef *)UARTx, pDatFrm, size, BLOCKING);
while (!(UARTx->LSR & UART_LSR_TEMT));
UARTx->LCR = save;
} else {
cnt = UART_Send((LPC_UART_TypeDef *)UARTx, pDatFrm, size, BLOCKING);
while (!(UARTx->LSR & UART_LSR_TEMT));
}
return cnt;
}
/**
* @brief Send Slave address frames on RS485 bus.
* @param[in] UARTx UART1 (only).
* @param[in] SlvAddr Slave Address.
* @return None.
*/
void UART_RS485SendSlvAddr(LPC_UART1_TypeDef *UARTx, uint8_t SlvAddr)
{
UART_RS485Send(UARTx, &SlvAddr, 1, 1);
}
/**
* @brief Send Data frames on RS485 bus.
* @param[in] UARTx UART1 (only).
* @param[in] pData Pointer to data to be sent.
* @param[in] size Size of data frame to be sent.
* @return None.
*/
uint32_t UART_RS485SendData(LPC_UART1_TypeDef *UARTx, uint8_t *pData, uint32_t size)
{
return (UART_RS485Send(UARTx, pData, size, 0));
}
#endif /* _UART1 */
/* Additional driver APIs ----------------------------------------------------------------------- */
/*********************************************************************//**
* @brief Send a block of data via UART peripheral
* @param[in] UARTx Selected UART peripheral used to send data,
* should be UART0, UART1, UART2 or UART3.
* @param[in] txbuf Pointer to Transmit buffer
* @param[in] buflen Length of Transmit buffer
* @param[in] flag Flag used in UART transfer, should be
* NONE_BLOCKING or BLOCKING
* @return Number of bytes sent.
*
* Note: when using UART in BLOCKING mode, a time-out condition is used
* via defined symbol UART_BLOCKING_TIMEOUT.
**********************************************************************/
uint32_t UART_Send(LPC_UART_TypeDef *UARTx, uint8_t *txbuf,
uint32_t buflen, TRANSFER_BLOCK_Type flag)
{
uint32_t bToSend, bSent, timeOut, fifo_cnt;
uint8_t *pChar = txbuf;
bToSend = buflen;
// blocking mode
if (flag == BLOCKING) {
bSent = 0;
while (bToSend){
timeOut = UART_BLOCKING_TIMEOUT;
// Wait for THR empty with timeout
while (!(UARTx->LSR & UART_LSR_THRE)) {
if (timeOut == 0) break;
timeOut--;
}
// Time out!
if(timeOut == 0) break;
fifo_cnt = UART_TX_FIFO_SIZE;
while (fifo_cnt && bToSend){
UART_SendData(UARTx, (*pChar++));
fifo_cnt--;
bToSend--;
bSent++;
}
}
}
// None blocking mode
else {
bSent = 0;
while (bToSend) {
if (!(UARTx->LSR & UART_LSR_THRE)){
break;
}
fifo_cnt = UART_TX_FIFO_SIZE;
while (fifo_cnt && bToSend) {
UART_SendData(UARTx, (*pChar++));
bToSend--;
fifo_cnt--;
bSent++;
}
}
}
return bSent;
}
/*********************************************************************//**
* @brief Receive a block of data via UART peripheral
* @param[in] UARTx Selected UART peripheral used to send data,
* should be UART0, UART1, UART2 or UART3.
* @param[out] rxbuf Pointer to Received buffer
* @param[in] buflen Length of Received buffer
* @param[in] flag Flag mode, should be NONE_BLOCKING or BLOCKING
* @return Number of bytes received
*
* Note: when using UART in BLOCKING mode, a time-out condition is used
* via defined symbol UART_BLOCKING_TIMEOUT.
**********************************************************************/
uint32_t UART_Receive(LPC_UART_TypeDef *UARTx, uint8_t *rxbuf, \
uint32_t buflen, TRANSFER_BLOCK_Type flag)
{
uint32_t bToRecv, bRecv, timeOut;
uint8_t *pChar = rxbuf;
bToRecv = buflen;
// Blocking mode
if (flag == BLOCKING) {
bRecv = 0;
while (bToRecv){
timeOut = UART_BLOCKING_TIMEOUT;
while (!(UARTx->LSR & UART_LSR_RDR)){
if (timeOut == 0) break;
timeOut--;
}
// Time out!
if(timeOut == 0) break;
// Get data from the buffer
(*pChar++) = UART_ReceiveData(UARTx);
bToRecv--;
bRecv++;
}
}
// None blocking mode
else {
bRecv = 0;
while (bToRecv) {
if (!(UARTx->LSR & UART_LSR_RDR)) {
break;
} else {
(*pChar++) = UART_ReceiveData(UARTx);
bRecv++;
bToRecv--;
}
}
}
return bRecv;
}
/*********************************************************************//**
* @brief Setup call-back function for UART interrupt handler for each
* UART peripheral
* @param[in] UARTx Selected UART peripheral, should be UART0..3
* @param[in] CbType Call-back type, should be:
* 0 - Receive Call-back
* 1 - Transmit Call-back
* 2 - Auto Baudrate Callback
* 3 - Error Call-back
* 4 - Modem Status Call-back (UART1 only)
* @param[in] pfnCbs Pointer to Call-back function
* @return None
**********************************************************************/
void UART_SetupCbs(LPC_UART_TypeDef *UARTx, uint8_t CbType, void *pfnCbs)
{
uint8_t pUartNum;
pUartNum = getUartNum(UARTx);
switch(CbType){
case 0:
uartCbsDat[pUartNum].pfnRxCbs = (fnTxCbs_Type *)pfnCbs;
break;
case 1:
uartCbsDat[pUartNum].pfnTxCbs = (fnRxCbs_Type *)pfnCbs;
break;
case 2:
uartCbsDat[pUartNum].pfnABCbs = (fnABCbs_Type *)pfnCbs;
break;
case 3:
uartCbsDat[pUartNum].pfnErrCbs = (fnErrCbs_Type *)pfnCbs;
break;
case 4:
pfnModemCbs = (fnModemCbs_Type *)pfnCbs;
break;
default:
break;
}
}
/*********************************************************************//**
* @brief Standard UART0 interrupt handler
* @param[in] None
* @return None
**********************************************************************/
void UART0_StdIntHandler(void)
{
UART_GenIntHandler(LPC_UART0);
}
/*********************************************************************//**
* @brief Standard UART1 interrupt handler
* @param[in] None
* @return None
**********************************************************************/
void UART1_StdIntHandler(void)
{
UART_GenIntHandler((LPC_UART_TypeDef *)LPC_UART1);
}
/*********************************************************************//**
* @brief Standard UART2 interrupt handler
* @param[in] None
* @return None
**********************************************************************/
void UART2_StdIntHandler(void)
{
UART_GenIntHandler(LPC_UART2);
}
/*********************************************************************//**
* @brief Standard UART3 interrupt handler
* @param[in] None
* @return
**********************************************************************/
void UART3_StdIntHandler(void)
{
UART_GenIntHandler(LPC_UART3);
}
/**
* @}
*/
#endif /* _UART */
/**
* @}
*/
/* --------------------------------- End Of File ------------------------------ */
|
gligli/overcycler
|
firmware_17xx/drivers/lpc17xx_uart.c
|
C
|
gpl-3.0
| 44,388
|
#principal{
box-shadow:#000000;
}
#jumbobox_logo{
margin-top:30px;
padding-left:30px;
/*background-color:#CC0000;*/
background-image:url(../Imagens/youtube-logo.png);
background-position:center;
color:#000000;
font:bold 26px Tw Cen MT;
}
|
rcasanje/Portfolio
|
Scripts/WEB/Projetos/DivulgaTudo/CSS/Index.css
|
CSS
|
gpl-3.0
| 248
|
import { asyncRoute } from 'helpers/routerHelpers';
export default [
{
requireAuth: false,
module: 'goodbye',
path: 'goodbye',
getComponent: asyncRoute((nextState, cb) => {
require.ensure(
[],
() => {
const { openGoodbyeOverlay } = require('./module');
cb(null, {
overlay: openGoodbyeOverlay,
});
},
'overlay',
);
}),
},
];
// WEBPACK FOOTER //
// ./src/js/app/modules/goodbye/routes.js
|
BramscoChill/BlendleParser
|
information/blendle-frontend-react-source/app/modules/goodbye/routes.js
|
JavaScript
|
gpl-3.0
| 501
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_17) on Mon May 06 00:15:47 EDT 2013 -->
<title>PreCompInfo</title>
<meta name="date" content="2013-05-06">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="PreCompInfo";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PreCompInfo.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/spongycastle/math/ec/IntArray.html" title="class in org.spongycastle.math.ec"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/spongycastle/math/ec/ReferenceMultiplier.html" title="class in org.spongycastle.math.ec"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/spongycastle/math/ec/PreCompInfo.html" target="_top">Frames</a></li>
<li><a href="PreCompInfo.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<!-- ======== START OF CLASS DATA ======== -->
<div class="header">
<div class="subTitle">org.spongycastle.math.ec</div>
<h2 title="Interface PreCompInfo" class="title">Interface PreCompInfo</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../../org/spongycastle/math/ec/WNafPreCompInfo.html" title="class in org.spongycastle.math.ec">WNafPreCompInfo</a>, <a href="../../../../org/spongycastle/math/ec/WTauNafPreCompInfo.html" title="class in org.spongycastle.math.ec">WTauNafPreCompInfo</a></dd>
</dl>
<hr>
<br>
<pre>interface <span class="strong">PreCompInfo</span></pre>
<div class="block">Interface for classes storing precomputation data for multiplication
algorithms. Used as a Memento (see GOF patterns) for
<code>WNafMultiplier</code>.</div>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="class-use/PreCompInfo.html">Use</a></li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../../org/spongycastle/math/ec/IntArray.html" title="class in org.spongycastle.math.ec"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../../org/spongycastle/math/ec/ReferenceMultiplier.html" title="class in org.spongycastle.math.ec"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../../index.html?org/spongycastle/math/ec/PreCompInfo.html" target="_top">Frames</a></li>
<li><a href="PreCompInfo.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li>Method</li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
|
gnu-user/orwell
|
Orwell/doc/org/spongycastle/math/ec/PreCompInfo.html
|
HTML
|
gpl-3.0
| 5,730
|
/*
* Decompiled with CFR 0_115.
*/
package com.bumptech.glide.provider;
import com.bumptech.glide.provider.DataLoadProvider;
import com.bumptech.glide.provider.EmptyDataLoadProvider;
import com.bumptech.glide.util.MultiClassKey;
import java.util.HashMap;
import java.util.Map;
public class DataLoadProviderRegistry {
private static final MultiClassKey GET_KEY = new MultiClassKey();
private final Map<MultiClassKey, DataLoadProvider<?, ?>> providers = new HashMap();
/*
* Enabled aggressive block sorting
* Enabled unnecessary exception pruning
* Enabled aggressive exception aggregation
*/
public <T, Z> DataLoadProvider<T, Z> get(Class<T> dataLoadProvider, Class<Z> object) {
MultiClassKey multiClassKey = GET_KEY;
synchronized (multiClassKey) {
GET_KEY.set(dataLoadProvider, object);
object = this.providers.get(GET_KEY);
}
dataLoadProvider = object;
if (object != null) return dataLoadProvider;
return EmptyDataLoadProvider.get();
}
public <T, Z> void register(Class<T> class_, Class<Z> class_2, DataLoadProvider<T, Z> dataLoadProvider) {
this.providers.put(new MultiClassKey(class_, class_2), dataLoadProvider);
}
}
|
SPACEDAC7/TrabajoFinalGrado
|
uploads/34f7f021ecaf167f6e9669e45c4483ec/java_source/com/bumptech/glide/provider/DataLoadProviderRegistry.java
|
Java
|
gpl-3.0
| 1,256
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.