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 |
|---|---|---|---|---|---|
//@HEADER
// ************************************************************************
//
// Kokkos v. 3.0
// Copyright (2020) National Technology & Engineering
// Solutions of Sandia, LLC (NTESS).
//
// Under the terms of Contract DE-NA0003525 with NTESS,
// the U.S. Government retains certain rights in this software.
//
// Kokkos is licensed under 3-clause BSD terms of use:
//
// 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 Corporation nor the names of the
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY NTESS "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 NTESS OR THE
// 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.
//
// Questions? Contact Christian R. Trott (crtrott@sandia.gov)
//
// ************************************************************************
//@HEADER
#define KOKKOS_IMPL_COMPILING_LIBRARY true
#include <Kokkos_Core.hpp>
namespace Kokkos {
namespace Impl {
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int********, LayoutLeft, LayoutRight, Cuda,
int64_t)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int********, LayoutLeft, LayoutLeft, Cuda,
int64_t)
KOKKOS_IMPL_VIEWCOPY_ETI_INST(int********, LayoutLeft, LayoutStride, Cuda,
int64_t)
KOKKOS_IMPL_VIEWFILL_ETI_INST(int********, LayoutLeft, Cuda, int64_t)
} // namespace Impl
} // namespace Kokkos
| pastewka/lammps | lib/kokkos/core/src/eti/Cuda/Kokkos_Cuda_ViewCopyETIInst_int64_t_int_LayoutLeft_Rank8.cpp | C++ | gpl-2.0 | 2,592 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>
Archives: 2021/7 |
星空</title>
<link rel="shortcut icon" href="/favicon.ico">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/fancybox/jquery.fancybox.min.css">
<script src="/js/pace.min.js"></script>
<meta name="generator" content="Hexo 5.0.2"></head>
<body>
<main class="content">
<section class="outer">
<article class="articles">
<h1 class="page-type-title">2021/7</h1>
<div class="archives-wrap">
<div class="archive-year-wrap">
<a href="/archives/2021" class="archive-year">2021</a>
</div>
<div class="archives">
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E7%AE%A1%E7%90%86%E4%BA%8B%E5%8A%A1%E5%A4%84%E7%90%86/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E7%AE%A1%E7%90%86%E4%BA%8B%E5%8A%A1%E5%A4%84%E7%90%86/">SQL管理事务处理</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E7%BB%84%E5%90%88%E6%9F%A5%E8%AF%A2/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E7%BB%84%E5%90%88%E6%9F%A5%E8%AF%A2/">SQL组合查询</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E4%BD%BF%E7%94%A8%E5%AD%90%E6%9F%A5%E8%AF%A2/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E4%BD%BF%E7%94%A8%E5%AD%90%E6%9F%A5%E8%AF%A2/">SQL使用子查询</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E9%AB%98%E7%BA%A7SQL%E7%89%B9%E6%80%A7/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E9%AB%98%E7%BA%A7SQL%E7%89%B9%E6%80%A7/">SQL高级SQL特性</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E4%BD%BF%E7%94%A8%E6%B8%B8%E6%A0%87/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E4%BD%BF%E7%94%A8%E6%B8%B8%E6%A0%87/">SQL使用游标</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E4%BD%BF%E7%94%A8%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E4%BD%BF%E7%94%A8%E6%95%B0%E6%8D%AE%E5%A4%84%E7%90%86%E5%87%BD%E6%95%B0/">SQL使用数据处理函数</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/SQL%E6%9B%B4%E6%96%B0%E5%92%8C%E5%88%A0%E9%99%A4%E6%95%B0%E6%8D%AE/" class="archive-article-date">
<time datetime="2021-07-21T14:16:16.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/SQL%E6%9B%B4%E6%96%B0%E5%92%8C%E5%88%A0%E9%99%A4%E6%95%B0%E6%8D%AE/">SQL更新和删除数据</a>
</h2>
</header>
</div>
</article>
<article class="archive-article archive-type-post">
<div class="archive-article-inner">
<header class="archive-article-header">
<a href="/2021/07/21/%E4%BF%AE%E6%94%B9%E5%B7%B2%E6%8F%90%E4%BA%A4%E5%88%B0github%E7%9A%84%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E9%82%AE%E7%AE%B1/" class="archive-article-date">
<time datetime="2021-07-21T13:44:59.000Z" itemprop="datePublished">07/21</time>
</a>
<h2 itemprop="name">
<a class="archive-article-title" href="/2021/07/21/%E4%BF%AE%E6%94%B9%E5%B7%B2%E6%8F%90%E4%BA%A4%E5%88%B0github%E7%9A%84%E7%94%A8%E6%88%B7%E5%90%8D%E5%92%8C%E9%82%AE%E7%AE%B1/">修改已提交到github的用户名和邮箱</a>
</h2>
</header>
</div>
</article>
</div>
</div>
<nav class="page-nav">
<a class="extend prev" rel="prev" href="/archives/2021/07/">Prev page</a><a class="page-number" href="/archives/2021/07/">1</a><span class="page-number current">2</span>
</nav>
</section>
<footer class="footer">
<div class="outer">
<div class="float-right">
<ul class="list-inline">
<li><i class="fe fe-smile-alt"></i> <span id="busuanzi_value_site_uv"></span></li>
<li><i class="fe fe-bookmark"></i> <span id="busuanzi_value_page_pv"></span></li>
</ul>
</div>
<ul class="list-inline">
<li>© 2021 星空</li>
<li>Powered by <a href="http://hexo.io/" target="_blank">Hexo</a></li>
<li>Theme <a target="_blank" rel="noopener" href="https://github.com/zhwangart/hexo-theme-ocean">Ocean</a></li>
</ul>
</div>
</footer>
</main>
<aside class="sidebar">
<button class="navbar-toggle"></button>
<nav class="navbar">
<div class="logo">
<a href="/"><img src="/images/hexo.svg" alt="星空"></a>
</div>
<ul class="nav nav-main">
<li class="nav-item">
<a class="nav-item-link" href="/">Home</a>
</li>
<li class="nav-item">
<a class="nav-item-link" href="/archives">Archives</a>
</li>
<li class="nav-item">
<a class="nav-item-link" href="/gallery">Gallery</a>
</li>
<li class="nav-item">
<a class="nav-item-link" href="/about">About</a>
</li>
<li class="nav-item">
<a class="nav-item-link nav-item-search" title="Search">
<i class="fe fe-search"></i>
Search
</a>
</li>
</ul>
</nav>
<nav class="navbar navbar-bottom">
<ul class="nav">
<li class="nav-item">
<div class="totop" id="totop">
<i class="fe fe-rocket"></i>
</div>
</li>
<li class="nav-item">
<a class="nav-item-link" target="_blank" href="/atom.xml" title="RSS Feed">
<i class="fe fe-feed"></i>
</a>
</li>
</ul>
</nav>
<div class="search-form-wrap">
<div class="local-search local-search-plugin">
<input type="search" id="local-search-input" class="local-search-input" placeholder="Search...">
<div id="local-search-result" class="local-search-result"></div>
</div>
</div>
</aside>
<script src="/js/jquery-2.0.3.min.js"></script>
<script src="/js/lazyload.min.js"></script>
<script src="/js/snap.svg-min.js"></script>
<script src="/js/busuanzi-2.3.pure.min.js"></script>
<script src="/fancybox/jquery.fancybox.min.js"></script>
<script src="/js/ocean.js"></script>
</body>
</html> | xperblueray/xperblueray.github.io | archives/2021/07/page/2/index.html | HTML | gpl-2.0 | 8,474 |
# zhou
zhouhao's website
| ggjjl1/zhou | README.md | Markdown | gpl-2.0 | 25 |
/*
* Copyright 2003-2005 Red Hat, Inc. All rights reserved.
* Copyright 2003-2005 Jeff Garzik
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
*/
#ifndef __LINUX_LIBATA_H__
#define __LINUX_LIBATA_H__
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/dma-mapping.h>
#include <asm/scatterlist.h>
#include <linux/io.h>
#include <linux/ata.h>
#include <linux/workqueue.h>
#include <scsi/scsi_host.h>
#include <linux/acpi.h>
/*
* Define if arch has non-standard setup. This is a _PCI_ standard
* not a legacy or ISA standard.
*/
#ifdef CONFIG_ATA_NONSTANDARD
#include <asm/libata-portmap.h>
#else
#include <asm-generic/libata-portmap.h>
#endif
/*
* compile-time options: to be removed as soon as all the drivers are
* converted to the new debugging mechanism
*/
#undef ATA_DEBUG /* debugging output */
#undef ATA_VERBOSE_DEBUG /* yet more debugging output */
#undef ATA_IRQ_TRAP /* define to ack screaming irqs */
#undef ATA_NDEBUG /* define to disable quick runtime checks */
/* note: prints function name for you */
#ifdef ATA_DEBUG
#define DPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __FUNCTION__, ## args)
#ifdef ATA_VERBOSE_DEBUG
#define VPRINTK(fmt, args...) printk(KERN_ERR "%s: " fmt, __FUNCTION__, ## args)
#else
#define VPRINTK(fmt, args...)
#endif /* ATA_VERBOSE_DEBUG */
#else
#define DPRINTK(fmt, args...)
#define VPRINTK(fmt, args...)
#endif /* ATA_DEBUG */
#define BPRINTK(fmt, args...) if (ap->flags & ATA_FLAG_DEBUGMSG) printk(KERN_ERR "%s: " fmt, __FUNCTION__, ## args)
/* NEW: debug levels */
#define HAVE_LIBATA_MSG 1
enum {
ATA_MSG_DRV = 0x0001,
ATA_MSG_INFO = 0x0002,
ATA_MSG_PROBE = 0x0004,
ATA_MSG_WARN = 0x0008,
ATA_MSG_MALLOC = 0x0010,
ATA_MSG_CTL = 0x0020,
ATA_MSG_INTR = 0x0040,
ATA_MSG_ERR = 0x0080,
};
#define ata_msg_drv(p) ((p)->msg_enable & ATA_MSG_DRV)
#define ata_msg_info(p) ((p)->msg_enable & ATA_MSG_INFO)
#define ata_msg_probe(p) ((p)->msg_enable & ATA_MSG_PROBE)
#define ata_msg_warn(p) ((p)->msg_enable & ATA_MSG_WARN)
#define ata_msg_malloc(p) ((p)->msg_enable & ATA_MSG_MALLOC)
#define ata_msg_ctl(p) ((p)->msg_enable & ATA_MSG_CTL)
#define ata_msg_intr(p) ((p)->msg_enable & ATA_MSG_INTR)
#define ata_msg_err(p) ((p)->msg_enable & ATA_MSG_ERR)
static inline u32 ata_msg_init(int dval, int default_msg_enable_bits)
{
if (dval < 0 || dval >= (sizeof(u32) * 8))
return default_msg_enable_bits; /* should be 0x1 - only driver info msgs */
if (!dval)
return 0;
return (1 << dval) - 1;
}
/* defines only for the constants which don't work well as enums */
#define ATA_TAG_POISON 0xfafbfcfdU
/* move to PCI layer? */
static inline struct device *pci_dev_to_dev(struct pci_dev *pdev)
{
return &pdev->dev;
}
enum {
/* various global constants */
LIBATA_MAX_PRD = ATA_MAX_PRD / 2,
ATA_MAX_PORTS = 8,
ATA_DEF_QUEUE = 1,
/* tag ATA_MAX_QUEUE - 1 is reserved for internal commands */
ATA_MAX_QUEUE = 32,
ATA_TAG_INTERNAL = ATA_MAX_QUEUE - 1,
ATA_MAX_BUS = 2,
ATA_DEF_BUSY_WAIT = 10000,
ATA_SHORT_PAUSE = (HZ >> 6) + 1,
ATA_SHT_EMULATED = 1,
ATA_SHT_CMD_PER_LUN = 1,
ATA_SHT_THIS_ID = -1,
ATA_SHT_USE_CLUSTERING = 1,
/* struct ata_device stuff */
ATA_DFLAG_LBA = (1 << 0), /* device supports LBA */
ATA_DFLAG_LBA48 = (1 << 1), /* device supports LBA48 */
ATA_DFLAG_CDB_INTR = (1 << 2), /* device asserts INTRQ when ready for CDB */
ATA_DFLAG_NCQ = (1 << 3), /* device supports NCQ */
ATA_DFLAG_FLUSH_EXT = (1 << 4), /* do FLUSH_EXT instead of FLUSH */
ATA_DFLAG_CFG_MASK = (1 << 8) - 1,
ATA_DFLAG_PIO = (1 << 8), /* device limited to PIO mode */
ATA_DFLAG_NCQ_OFF = (1 << 9), /* device limited to non-NCQ mode */
ATA_DFLAG_SPUNDOWN = (1 << 10), /* XXX: for spindown_compat */
ATA_DFLAG_INIT_MASK = (1 << 16) - 1,
ATA_DFLAG_DETACH = (1 << 16),
ATA_DFLAG_DETACHED = (1 << 17),
ATA_DEV_UNKNOWN = 0, /* unknown device */
ATA_DEV_ATA = 1, /* ATA device */
ATA_DEV_ATA_UNSUP = 2, /* ATA device (unsupported) */
ATA_DEV_ATAPI = 3, /* ATAPI device */
ATA_DEV_ATAPI_UNSUP = 4, /* ATAPI device (unsupported) */
ATA_DEV_CEATA = 5, /* no device */
ATA_DEV_NONE = 6, /* no device */
/* struct ata_port flags */
ATA_FLAG_SLAVE_POSS = (1 << 0), /* host supports slave dev */
/* (doesn't imply presence) */
ATA_FLAG_SATA = (1 << 1),
ATA_FLAG_NO_LEGACY = (1 << 2), /* no legacy mode check */
ATA_FLAG_MMIO = (1 << 3), /* use MMIO, not PIO */
ATA_FLAG_SRST = (1 << 4), /* (obsolete) use ATA SRST, not E.D.D. */
ATA_FLAG_SATA_RESET = (1 << 5), /* (obsolete) use COMRESET */
ATA_FLAG_NO_ATAPI = (1 << 6), /* No ATAPI support */
ATA_FLAG_PIO_DMA = (1 << 7), /* PIO cmds via DMA */
ATA_FLAG_PIO_LBA48 = (1 << 8), /* Host DMA engine is LBA28 only */
ATA_FLAG_PIO_POLLING = (1 << 9), /* use polling PIO if LLD
* doesn't handle PIO interrupts */
ATA_FLAG_NCQ = (1 << 10), /* host supports NCQ */
ATA_FLAG_HRST_TO_RESUME = (1 << 11), /* hardreset to resume phy */
ATA_FLAG_SKIP_D2H_BSY = (1 << 12), /* can't wait for the first D2H
* Register FIS clearing BSY */
ATA_FLAG_DEBUGMSG = (1 << 13),
ATA_FLAG_IGN_SIMPLEX = (1 << 15), /* ignore SIMPLEX */
ATA_FLAG_NO_IORDY = (1 << 16), /* controller lacks iordy */
ATA_FLAG_ACPI_SATA = (1 << 17), /* need native SATA ACPI layout */
/* The following flag belongs to ap->pflags but is kept in
* ap->flags because it's referenced in many LLDs and will be
* removed in not-too-distant future.
*/
ATA_FLAG_DISABLED = (1 << 23), /* port is disabled, ignore it */
/* bits 24:31 of ap->flags are reserved for LLD specific flags */
/* struct ata_port pflags */
ATA_PFLAG_EH_PENDING = (1 << 0), /* EH pending */
ATA_PFLAG_EH_IN_PROGRESS = (1 << 1), /* EH in progress */
ATA_PFLAG_FROZEN = (1 << 2), /* port is frozen */
ATA_PFLAG_RECOVERED = (1 << 3), /* recovery action performed */
ATA_PFLAG_LOADING = (1 << 4), /* boot/loading probe */
ATA_PFLAG_UNLOADING = (1 << 5), /* module is unloading */
ATA_PFLAG_SCSI_HOTPLUG = (1 << 6), /* SCSI hotplug scheduled */
ATA_PFLAG_INITIALIZING = (1 << 7), /* being initialized, don't touch */
ATA_PFLAG_FLUSH_PORT_TASK = (1 << 16), /* flush port task */
ATA_PFLAG_SUSPENDED = (1 << 17), /* port is suspended (power) */
ATA_PFLAG_PM_PENDING = (1 << 18), /* PM operation pending */
/* struct ata_queued_cmd flags */
ATA_QCFLAG_ACTIVE = (1 << 0), /* cmd not yet ack'd to scsi lyer */
ATA_QCFLAG_SG = (1 << 1), /* have s/g table? */
ATA_QCFLAG_SINGLE = (1 << 2), /* no s/g, just a single buffer */
ATA_QCFLAG_DMAMAP = ATA_QCFLAG_SG | ATA_QCFLAG_SINGLE,
ATA_QCFLAG_IO = (1 << 3), /* standard IO command */
ATA_QCFLAG_RESULT_TF = (1 << 4), /* result TF requested */
ATA_QCFLAG_FAILED = (1 << 16), /* cmd failed and is owned by EH */
ATA_QCFLAG_SENSE_VALID = (1 << 17), /* sense data valid */
ATA_QCFLAG_EH_SCHEDULED = (1 << 18), /* EH scheduled (obsolete) */
/* host set flags */
ATA_HOST_SIMPLEX = (1 << 0), /* Host is simplex, one DMA channel per host only */
ATA_HOST_STARTED = (1 << 1), /* Host started */
/* various lengths of time */
ATA_TMOUT_BOOT = 30 * HZ, /* heuristic */
ATA_TMOUT_BOOT_QUICK = 7 * HZ, /* heuristic */
ATA_TMOUT_INTERNAL = 30 * HZ,
ATA_TMOUT_INTERNAL_QUICK = 5 * HZ,
/* ATA bus states */
BUS_UNKNOWN = 0,
BUS_DMA = 1,
BUS_IDLE = 2,
BUS_NOINTR = 3,
BUS_NODATA = 4,
BUS_TIMER = 5,
BUS_PIO = 6,
BUS_EDD = 7,
BUS_IDENTIFY = 8,
BUS_PACKET = 9,
/* SATA port states */
PORT_UNKNOWN = 0,
PORT_ENABLED = 1,
PORT_DISABLED = 2,
/* encoding various smaller bitmaps into a single
* unsigned int bitmap
*/
ATA_BITS_PIO = 7,
ATA_BITS_MWDMA = 5,
ATA_BITS_UDMA = 8,
ATA_SHIFT_PIO = 0,
ATA_SHIFT_MWDMA = ATA_SHIFT_PIO + ATA_BITS_PIO,
ATA_SHIFT_UDMA = ATA_SHIFT_MWDMA + ATA_BITS_MWDMA,
ATA_MASK_PIO = ((1 << ATA_BITS_PIO) - 1) << ATA_SHIFT_PIO,
ATA_MASK_MWDMA = ((1 << ATA_BITS_MWDMA) - 1) << ATA_SHIFT_MWDMA,
ATA_MASK_UDMA = ((1 << ATA_BITS_UDMA) - 1) << ATA_SHIFT_UDMA,
/* size of buffer to pad xfers ending on unaligned boundaries */
ATA_DMA_PAD_SZ = 4,
ATA_DMA_PAD_BUF_SZ = ATA_DMA_PAD_SZ * ATA_MAX_QUEUE,
/* ering size */
ATA_ERING_SIZE = 32,
/* desc_len for ata_eh_info and context */
ATA_EH_DESC_LEN = 80,
/* reset / recovery action types */
ATA_EH_REVALIDATE = (1 << 0),
ATA_EH_SOFTRESET = (1 << 1),
ATA_EH_HARDRESET = (1 << 2),
ATA_EH_RESET_MASK = ATA_EH_SOFTRESET | ATA_EH_HARDRESET,
ATA_EH_PERDEV_MASK = ATA_EH_REVALIDATE,
/* ata_eh_info->flags */
ATA_EHI_HOTPLUGGED = (1 << 0), /* could have been hotplugged */
ATA_EHI_RESUME_LINK = (1 << 1), /* resume link (reset modifier) */
ATA_EHI_NO_AUTOPSY = (1 << 2), /* no autopsy */
ATA_EHI_QUIET = (1 << 3), /* be quiet */
ATA_EHI_DID_SOFTRESET = (1 << 16), /* already soft-reset this port */
ATA_EHI_DID_HARDRESET = (1 << 17), /* already soft-reset this port */
ATA_EHI_PRINTINFO = (1 << 18), /* print configuration info */
ATA_EHI_SETMODE = (1 << 19), /* configure transfer mode */
ATA_EHI_POST_SETMODE = (1 << 20), /* revaildating after setmode */
ATA_EHI_DID_RESET = ATA_EHI_DID_SOFTRESET | ATA_EHI_DID_HARDRESET,
ATA_EHI_RESET_MODIFIER_MASK = ATA_EHI_RESUME_LINK,
/* max repeat if error condition is still set after ->error_handler */
ATA_EH_MAX_REPEAT = 5,
/* how hard are we gonna try to probe/recover devices */
ATA_PROBE_MAX_TRIES = 3,
ATA_EH_DEV_TRIES = 3,
/* Horkage types. May be set by libata or controller on drives
(some horkage may be drive/controller pair dependant */
ATA_HORKAGE_DIAGNOSTIC = (1 << 0), /* Failed boot diag */
ATA_HORKAGE_NODMA = (1 << 1), /* DMA problems */
ATA_HORKAGE_NONCQ = (1 << 2), /* Don't use NCQ */
ATA_HORKAGE_MAX_SEC_128 = (1 << 3), /* Limit max sects to 128 */
};
enum hsm_task_states {
HSM_ST_IDLE, /* no command on going */
HSM_ST_FIRST, /* (waiting the device to)
write CDB or first data block */
HSM_ST, /* (waiting the device to) transfer data */
HSM_ST_LAST, /* (waiting the device to) complete command */
HSM_ST_ERR, /* error */
};
enum ata_completion_errors {
AC_ERR_DEV = (1 << 0), /* device reported error */
AC_ERR_HSM = (1 << 1), /* host state machine violation */
AC_ERR_TIMEOUT = (1 << 2), /* timeout */
AC_ERR_MEDIA = (1 << 3), /* media error */
AC_ERR_ATA_BUS = (1 << 4), /* ATA bus error */
AC_ERR_HOST_BUS = (1 << 5), /* host bus error */
AC_ERR_SYSTEM = (1 << 6), /* system error */
AC_ERR_INVALID = (1 << 7), /* invalid argument */
AC_ERR_OTHER = (1 << 8), /* unknown */
AC_ERR_NODEV_HINT = (1 << 9), /* polling device detection hint */
};
/* forward declarations */
struct scsi_device;
struct ata_port_operations;
struct ata_port;
struct ata_queued_cmd;
/* typedefs */
typedef void (*ata_qc_cb_t) (struct ata_queued_cmd *qc);
typedef int (*ata_prereset_fn_t)(struct ata_port *ap, unsigned long deadline);
typedef int (*ata_reset_fn_t)(struct ata_port *ap, unsigned int *classes,
unsigned long deadline);
typedef void (*ata_postreset_fn_t)(struct ata_port *ap, unsigned int *classes);
struct ata_ioports {
void __iomem *cmd_addr;
void __iomem *data_addr;
void __iomem *error_addr;
void __iomem *feature_addr;
void __iomem *nsect_addr;
void __iomem *lbal_addr;
void __iomem *lbam_addr;
void __iomem *lbah_addr;
void __iomem *device_addr;
void __iomem *status_addr;
void __iomem *command_addr;
void __iomem *altstatus_addr;
void __iomem *ctl_addr;
void __iomem *bmdma_addr;
void __iomem *scr_addr;
};
struct ata_host {
spinlock_t lock;
struct device *dev;
unsigned long irq;
unsigned long irq2;
void __iomem * const *iomap;
unsigned int n_ports;
void *private_data;
const struct ata_port_operations *ops;
unsigned long flags;
struct ata_port *simplex_claimed; /* channel owning the DMA */
struct ata_port *ports[0];
};
struct ata_queued_cmd {
struct ata_port *ap;
struct ata_device *dev;
struct scsi_cmnd *scsicmd;
void (*scsidone)(struct scsi_cmnd *);
struct ata_taskfile tf;
u8 cdb[ATAPI_CDB_LEN];
unsigned long flags; /* ATA_QCFLAG_xxx */
unsigned int tag;
unsigned int n_elem;
unsigned int orig_n_elem;
int dma_dir;
unsigned int pad_len;
unsigned int sect_size;
unsigned int nbytes;
unsigned int curbytes;
unsigned int cursg;
unsigned int cursg_ofs;
struct scatterlist sgent;
struct scatterlist pad_sgent;
void *buf_virt;
/* DO NOT iterate over __sg manually, use ata_for_each_sg() */
struct scatterlist *__sg;
unsigned int err_mask;
struct ata_taskfile result_tf;
ata_qc_cb_t complete_fn;
void *private_data;
};
struct ata_port_stats {
unsigned long unhandled_irq;
unsigned long idle_irq;
unsigned long rw_reqbuf;
};
struct ata_ering_entry {
int is_io;
unsigned int err_mask;
u64 timestamp;
};
struct ata_ering {
int cursor;
struct ata_ering_entry ring[ATA_ERING_SIZE];
};
struct ata_device {
struct ata_port *ap;
unsigned int devno; /* 0 or 1 */
unsigned long flags; /* ATA_DFLAG_xxx */
struct scsi_device *sdev; /* attached SCSI device */
/* n_sector is used as CLEAR_OFFSET, read comment above CLEAR_OFFSET */
u64 n_sectors; /* size of device, if ATA */
unsigned int class; /* ATA_DEV_xxx */
u16 id[ATA_ID_WORDS]; /* IDENTIFY xxx DEVICE data */
u8 pio_mode;
u8 dma_mode;
u8 xfer_mode;
unsigned int xfer_shift; /* ATA_SHIFT_xxx */
unsigned int multi_count; /* sectors count for
READ/WRITE MULTIPLE */
unsigned int max_sectors; /* per-device max sectors */
unsigned int cdb_len;
/* per-dev xfer mask */
unsigned int pio_mask;
unsigned int mwdma_mask;
unsigned int udma_mask;
/* for CHS addressing */
u16 cylinders; /* Number of cylinders */
u16 heads; /* Number of heads */
u16 sectors; /* Number of sectors per track */
/* error history */
struct ata_ering ering;
int spdn_cnt;
unsigned int horkage; /* List of broken features */
#ifdef CONFIG_ATA_ACPI
/* ACPI objects info */
acpi_handle obj_handle;
#endif
};
/* Offset into struct ata_device. Fields above it are maintained
* acress device init. Fields below are zeroed.
*/
#define ATA_DEVICE_CLEAR_OFFSET offsetof(struct ata_device, n_sectors)
struct ata_eh_info {
struct ata_device *dev; /* offending device */
u32 serror; /* SError from LLDD */
unsigned int err_mask; /* port-wide err_mask */
unsigned int action; /* ATA_EH_* action mask */
unsigned int dev_action[ATA_MAX_DEVICES]; /* dev EH action */
unsigned int flags; /* ATA_EHI_* flags */
unsigned int probe_mask;
char desc[ATA_EH_DESC_LEN];
int desc_len;
};
struct ata_eh_context {
struct ata_eh_info i;
int tries[ATA_MAX_DEVICES];
unsigned int classes[ATA_MAX_DEVICES];
unsigned int did_probe_mask;
};
struct ata_port {
struct Scsi_Host *scsi_host; /* our co-allocated scsi host */
const struct ata_port_operations *ops;
spinlock_t *lock;
unsigned long flags; /* ATA_FLAG_xxx */
unsigned int pflags; /* ATA_PFLAG_xxx */
unsigned int print_id; /* user visible unique port ID */
unsigned int port_no; /* 0 based port no. inside the host */
struct ata_prd *prd; /* our SG list */
dma_addr_t prd_dma; /* and its DMA mapping */
void *pad; /* array of DMA pad buffers */
dma_addr_t pad_dma;
struct ata_ioports ioaddr; /* ATA cmd/ctl/dma register blocks */
u8 ctl; /* cache of ATA control register */
u8 last_ctl; /* Cache last written value */
unsigned int pio_mask;
unsigned int mwdma_mask;
unsigned int udma_mask;
unsigned int cbl; /* cable type; ATA_CBL_xxx */
unsigned int hw_sata_spd_limit;
unsigned int sata_spd_limit; /* SATA PHY speed limit */
/* record runtime error info, protected by host lock */
struct ata_eh_info eh_info;
/* EH context owned by EH */
struct ata_eh_context eh_context;
struct ata_device device[ATA_MAX_DEVICES];
struct ata_queued_cmd qcmd[ATA_MAX_QUEUE];
unsigned long qc_allocated;
unsigned int qc_active;
unsigned int active_tag;
u32 sactive;
struct ata_port_stats stats;
struct ata_host *host;
struct device *dev;
void *port_task_data;
struct delayed_work port_task;
struct delayed_work hotplug_task;
struct work_struct scsi_rescan_task;
unsigned int hsm_task_state;
u32 msg_enable;
struct list_head eh_done_q;
wait_queue_head_t eh_wait_q;
pm_message_t pm_mesg;
int *pm_result;
void *private_data;
u8 sector_buf[ATA_SECT_SIZE]; /* owned by EH */
};
struct ata_port_operations {
void (*port_disable) (struct ata_port *);
void (*dev_config) (struct ata_device *);
void (*set_piomode) (struct ata_port *, struct ata_device *);
void (*set_dmamode) (struct ata_port *, struct ata_device *);
unsigned long (*mode_filter) (struct ata_device *, unsigned long);
void (*tf_load) (struct ata_port *ap, const struct ata_taskfile *tf);
void (*tf_read) (struct ata_port *ap, struct ata_taskfile *tf);
void (*exec_command)(struct ata_port *ap, const struct ata_taskfile *tf);
u8 (*check_status)(struct ata_port *ap);
u8 (*check_altstatus)(struct ata_port *ap);
void (*dev_select)(struct ata_port *ap, unsigned int device);
void (*phy_reset) (struct ata_port *ap); /* obsolete */
int (*set_mode) (struct ata_port *ap, struct ata_device **r_failed_dev);
int (*cable_detect) (struct ata_port *ap);
int (*check_atapi_dma) (struct ata_queued_cmd *qc);
void (*bmdma_setup) (struct ata_queued_cmd *qc);
void (*bmdma_start) (struct ata_queued_cmd *qc);
void (*data_xfer) (struct ata_device *, unsigned char *, unsigned int, int);
void (*qc_prep) (struct ata_queued_cmd *qc);
unsigned int (*qc_issue) (struct ata_queued_cmd *qc);
/* Error handlers. ->error_handler overrides ->eng_timeout and
* indicates that new-style EH is in place.
*/
void (*eng_timeout) (struct ata_port *ap); /* obsolete */
void (*freeze) (struct ata_port *ap);
void (*thaw) (struct ata_port *ap);
void (*error_handler) (struct ata_port *ap);
void (*post_internal_cmd) (struct ata_queued_cmd *qc);
irq_handler_t irq_handler;
void (*irq_clear) (struct ata_port *);
u8 (*irq_on) (struct ata_port *);
u8 (*irq_ack) (struct ata_port *ap, unsigned int chk_drq);
u32 (*scr_read) (struct ata_port *ap, unsigned int sc_reg);
void (*scr_write) (struct ata_port *ap, unsigned int sc_reg,
u32 val);
int (*port_suspend) (struct ata_port *ap, pm_message_t mesg);
int (*port_resume) (struct ata_port *ap);
int (*port_start) (struct ata_port *ap);
void (*port_stop) (struct ata_port *ap);
void (*host_stop) (struct ata_host *host);
void (*bmdma_stop) (struct ata_queued_cmd *qc);
u8 (*bmdma_status) (struct ata_port *ap);
};
struct ata_port_info {
struct scsi_host_template *sht;
unsigned long flags;
unsigned long pio_mask;
unsigned long mwdma_mask;
unsigned long udma_mask;
const struct ata_port_operations *port_ops;
irq_handler_t irq_handler;
void *private_data;
};
struct ata_timing {
unsigned short mode; /* ATA mode */
unsigned short setup; /* t1 */
unsigned short act8b; /* t2 for 8-bit I/O */
unsigned short rec8b; /* t2i for 8-bit I/O */
unsigned short cyc8b; /* t0 for 8-bit I/O */
unsigned short active; /* t2 or tD */
unsigned short recover; /* t2i or tK */
unsigned short cycle; /* t0 */
unsigned short udma; /* t2CYCTYP/2 */
};
#define FIT(v,vmin,vmax) max_t(short,min_t(short,v,vmax),vmin)
extern const unsigned long sata_deb_timing_normal[];
extern const unsigned long sata_deb_timing_hotplug[];
extern const unsigned long sata_deb_timing_long[];
extern const struct ata_port_operations ata_dummy_port_ops;
extern const struct ata_port_info ata_dummy_port_info;
static inline const unsigned long *
sata_ehc_deb_timing(struct ata_eh_context *ehc)
{
if (ehc->i.flags & ATA_EHI_HOTPLUGGED)
return sata_deb_timing_hotplug;
else
return sata_deb_timing_normal;
}
static inline int ata_port_is_dummy(struct ata_port *ap)
{
return ap->ops == &ata_dummy_port_ops;
}
extern void sata_print_link_status(struct ata_port *ap);
extern void ata_port_probe(struct ata_port *);
extern void __sata_phy_reset(struct ata_port *ap);
extern void sata_phy_reset(struct ata_port *ap);
extern void ata_bus_reset(struct ata_port *ap);
extern int sata_set_spd(struct ata_port *ap);
extern int sata_phy_debounce(struct ata_port *ap, const unsigned long *param,
unsigned long deadline);
extern int sata_phy_resume(struct ata_port *ap, const unsigned long *param,
unsigned long deadline);
extern int ata_std_prereset(struct ata_port *ap, unsigned long deadline);
extern int ata_std_softreset(struct ata_port *ap, unsigned int *classes,
unsigned long deadline);
extern int sata_port_hardreset(struct ata_port *ap, const unsigned long *timing,
unsigned long deadline);
extern int sata_std_hardreset(struct ata_port *ap, unsigned int *class,
unsigned long deadline);
extern void ata_std_postreset(struct ata_port *ap, unsigned int *classes);
extern void ata_port_disable(struct ata_port *);
extern void ata_std_ports(struct ata_ioports *ioaddr);
#ifdef CONFIG_PCI
extern int ata_pci_init_one (struct pci_dev *pdev,
const struct ata_port_info * const * ppi);
extern void ata_pci_remove_one (struct pci_dev *pdev);
#ifdef CONFIG_PM
extern void ata_pci_device_do_suspend(struct pci_dev *pdev, pm_message_t mesg);
extern int __must_check ata_pci_device_do_resume(struct pci_dev *pdev);
extern int ata_pci_device_suspend(struct pci_dev *pdev, pm_message_t mesg);
extern int ata_pci_device_resume(struct pci_dev *pdev);
#endif
extern int ata_pci_clear_simplex(struct pci_dev *pdev);
#endif /* CONFIG_PCI */
extern struct ata_host *ata_host_alloc(struct device *dev, int max_ports);
extern struct ata_host *ata_host_alloc_pinfo(struct device *dev,
const struct ata_port_info * const * ppi, int n_ports);
extern int ata_host_start(struct ata_host *host);
extern int ata_host_register(struct ata_host *host,
struct scsi_host_template *sht);
extern int ata_host_activate(struct ata_host *host, int irq,
irq_handler_t irq_handler, unsigned long irq_flags,
struct scsi_host_template *sht);
extern void ata_host_detach(struct ata_host *host);
extern void ata_host_init(struct ata_host *, struct device *,
unsigned long, const struct ata_port_operations *);
extern int ata_scsi_detect(struct scsi_host_template *sht);
extern int ata_scsi_ioctl(struct scsi_device *dev, int cmd, void __user *arg);
extern int ata_scsi_queuecmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *));
extern void ata_sas_port_destroy(struct ata_port *);
extern struct ata_port *ata_sas_port_alloc(struct ata_host *,
struct ata_port_info *, struct Scsi_Host *);
extern int ata_sas_port_init(struct ata_port *);
extern int ata_sas_port_start(struct ata_port *ap);
extern void ata_sas_port_stop(struct ata_port *ap);
extern int ata_sas_slave_configure(struct scsi_device *, struct ata_port *);
extern int ata_sas_queuecmd(struct scsi_cmnd *cmd, void (*done)(struct scsi_cmnd *),
struct ata_port *ap);
extern unsigned int ata_host_intr(struct ata_port *ap, struct ata_queued_cmd *qc);
extern int sata_scr_valid(struct ata_port *ap);
extern int sata_scr_read(struct ata_port *ap, int reg, u32 *val);
extern int sata_scr_write(struct ata_port *ap, int reg, u32 val);
extern int sata_scr_write_flush(struct ata_port *ap, int reg, u32 val);
extern int ata_port_online(struct ata_port *ap);
extern int ata_port_offline(struct ata_port *ap);
#ifdef CONFIG_PM
extern int ata_host_suspend(struct ata_host *host, pm_message_t mesg);
extern void ata_host_resume(struct ata_host *host);
#endif
extern int ata_ratelimit(void);
extern int ata_busy_sleep(struct ata_port *ap,
unsigned long timeout_pat, unsigned long timeout);
extern int ata_wait_ready(struct ata_port *ap, unsigned long deadline);
extern void ata_port_queue_task(struct ata_port *ap, work_func_t fn,
void *data, unsigned long delay);
extern u32 ata_wait_register(void __iomem *reg, u32 mask, u32 val,
unsigned long interval_msec,
unsigned long timeout_msec);
extern unsigned int ata_dev_try_classify(struct ata_port *, unsigned int, u8 *);
/*
* Default driver ops implementations
*/
extern void ata_tf_load(struct ata_port *ap, const struct ata_taskfile *tf);
extern void ata_tf_read(struct ata_port *ap, struct ata_taskfile *tf);
extern void ata_tf_to_fis(const struct ata_taskfile *tf, u8 *fis, u8 pmp);
extern void ata_tf_from_fis(const u8 *fis, struct ata_taskfile *tf);
extern void ata_noop_dev_select (struct ata_port *ap, unsigned int device);
extern void ata_std_dev_select (struct ata_port *ap, unsigned int device);
extern u8 ata_check_status(struct ata_port *ap);
extern u8 ata_altstatus(struct ata_port *ap);
extern void ata_exec_command(struct ata_port *ap, const struct ata_taskfile *tf);
extern int ata_port_start (struct ata_port *ap);
extern void ata_port_detach (struct ata_port *ap);
extern int ata_sff_port_start (struct ata_port *ap);
extern irqreturn_t ata_interrupt (int irq, void *dev_instance);
extern void ata_data_xfer(struct ata_device *adev, unsigned char *buf,
unsigned int buflen, int write_data);
extern void ata_data_xfer_noirq(struct ata_device *adev, unsigned char *buf,
unsigned int buflen, int write_data);
extern void ata_qc_prep(struct ata_queued_cmd *qc);
extern void ata_noop_qc_prep(struct ata_queued_cmd *qc);
extern unsigned int ata_qc_issue_prot(struct ata_queued_cmd *qc);
extern void ata_sg_init_one(struct ata_queued_cmd *qc, void *buf,
unsigned int buflen);
extern void ata_sg_init(struct ata_queued_cmd *qc, struct scatterlist *sg,
unsigned int n_elem);
extern unsigned int ata_dev_classify(const struct ata_taskfile *tf);
extern void ata_dev_disable(struct ata_device *adev);
extern void ata_id_string(const u16 *id, unsigned char *s,
unsigned int ofs, unsigned int len);
extern void ata_id_c_string(const u16 *id, unsigned char *s,
unsigned int ofs, unsigned int len);
extern void ata_id_to_dma_mode(struct ata_device *dev, u8 unknown);
extern unsigned long ata_device_blacklisted(const struct ata_device *dev);
extern void ata_bmdma_setup (struct ata_queued_cmd *qc);
extern void ata_bmdma_start (struct ata_queued_cmd *qc);
extern void ata_bmdma_stop(struct ata_queued_cmd *qc);
extern u8 ata_bmdma_status(struct ata_port *ap);
extern void ata_bmdma_irq_clear(struct ata_port *ap);
extern void ata_bmdma_freeze(struct ata_port *ap);
extern void ata_bmdma_thaw(struct ata_port *ap);
extern void ata_bmdma_drive_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
ata_reset_fn_t softreset,
ata_reset_fn_t hardreset,
ata_postreset_fn_t postreset);
extern void ata_bmdma_error_handler(struct ata_port *ap);
extern void ata_bmdma_post_internal_cmd(struct ata_queued_cmd *qc);
extern int ata_hsm_move(struct ata_port *ap, struct ata_queued_cmd *qc,
u8 status, int in_wq);
extern void ata_qc_complete(struct ata_queued_cmd *qc);
extern int ata_qc_complete_multiple(struct ata_port *ap, u32 qc_active,
void (*finish_qc)(struct ata_queued_cmd *));
extern void ata_scsi_simulate(struct ata_device *dev, struct scsi_cmnd *cmd,
void (*done)(struct scsi_cmnd *));
extern int ata_std_bios_param(struct scsi_device *sdev,
struct block_device *bdev,
sector_t capacity, int geom[]);
extern int ata_scsi_slave_config(struct scsi_device *sdev);
extern void ata_scsi_slave_destroy(struct scsi_device *sdev);
extern int ata_scsi_change_queue_depth(struct scsi_device *sdev,
int queue_depth);
extern struct ata_device *ata_dev_pair(struct ata_device *adev);
extern int ata_do_set_mode(struct ata_port *ap, struct ata_device **r_failed_dev);
extern u8 ata_irq_on(struct ata_port *ap);
extern u8 ata_dummy_irq_on(struct ata_port *ap);
extern u8 ata_irq_ack(struct ata_port *ap, unsigned int chk_drq);
extern u8 ata_dummy_irq_ack(struct ata_port *ap, unsigned int chk_drq);
extern int ata_cable_40wire(struct ata_port *ap);
extern int ata_cable_80wire(struct ata_port *ap);
extern int ata_cable_sata(struct ata_port *ap);
extern int ata_cable_unknown(struct ata_port *ap);
/*
* Timing helpers
*/
extern unsigned int ata_pio_need_iordy(const struct ata_device *);
extern int ata_timing_compute(struct ata_device *, unsigned short,
struct ata_timing *, int, int);
extern void ata_timing_merge(const struct ata_timing *,
const struct ata_timing *, struct ata_timing *,
unsigned int);
enum {
ATA_TIMING_SETUP = (1 << 0),
ATA_TIMING_ACT8B = (1 << 1),
ATA_TIMING_REC8B = (1 << 2),
ATA_TIMING_CYC8B = (1 << 3),
ATA_TIMING_8BIT = ATA_TIMING_ACT8B | ATA_TIMING_REC8B |
ATA_TIMING_CYC8B,
ATA_TIMING_ACTIVE = (1 << 4),
ATA_TIMING_RECOVER = (1 << 5),
ATA_TIMING_CYCLE = (1 << 6),
ATA_TIMING_UDMA = (1 << 7),
ATA_TIMING_ALL = ATA_TIMING_SETUP | ATA_TIMING_ACT8B |
ATA_TIMING_REC8B | ATA_TIMING_CYC8B |
ATA_TIMING_ACTIVE | ATA_TIMING_RECOVER |
ATA_TIMING_CYCLE | ATA_TIMING_UDMA,
};
#ifdef CONFIG_PCI
struct pci_bits {
unsigned int reg; /* PCI config register to read */
unsigned int width; /* 1 (8 bit), 2 (16 bit), 4 (32 bit) */
unsigned long mask;
unsigned long val;
};
extern int ata_pci_init_native_host(struct ata_host *host);
extern int ata_pci_init_bmdma(struct ata_host *host);
extern int ata_pci_prepare_native_host(struct pci_dev *pdev,
const struct ata_port_info * const * ppi,
struct ata_host **r_host);
extern int pci_test_config_bits(struct pci_dev *pdev, const struct pci_bits *bits);
extern unsigned long ata_pci_default_filter(struct ata_device *, unsigned long);
#endif /* CONFIG_PCI */
/*
* EH
*/
extern void ata_eng_timeout(struct ata_port *ap);
extern void ata_port_schedule_eh(struct ata_port *ap);
extern void ata_port_wait_eh(struct ata_port *ap);
extern int ata_port_abort(struct ata_port *ap);
extern int ata_port_freeze(struct ata_port *ap);
extern void ata_eh_freeze_port(struct ata_port *ap);
extern void ata_eh_thaw_port(struct ata_port *ap);
extern void ata_eh_qc_complete(struct ata_queued_cmd *qc);
extern void ata_eh_qc_retry(struct ata_queued_cmd *qc);
extern void ata_do_eh(struct ata_port *ap, ata_prereset_fn_t prereset,
ata_reset_fn_t softreset, ata_reset_fn_t hardreset,
ata_postreset_fn_t postreset);
/*
* printk helpers
*/
#define ata_port_printk(ap, lv, fmt, args...) \
printk(lv"ata%u: "fmt, (ap)->print_id , ##args)
#define ata_dev_printk(dev, lv, fmt, args...) \
printk(lv"ata%u.%02u: "fmt, (dev)->ap->print_id, (dev)->devno , ##args)
/*
* ata_eh_info helpers
*/
#define ata_ehi_push_desc(ehi, fmt, args...) do { \
(ehi)->desc_len += scnprintf((ehi)->desc + (ehi)->desc_len, \
ATA_EH_DESC_LEN - (ehi)->desc_len, \
fmt , ##args); \
} while (0)
#define ata_ehi_clear_desc(ehi) do { \
(ehi)->desc[0] = '\0'; \
(ehi)->desc_len = 0; \
} while (0)
static inline void __ata_ehi_hotplugged(struct ata_eh_info *ehi)
{
ehi->flags |= ATA_EHI_HOTPLUGGED | ATA_EHI_RESUME_LINK;
ehi->action |= ATA_EH_SOFTRESET;
ehi->probe_mask |= (1 << ATA_MAX_DEVICES) - 1;
}
static inline void ata_ehi_hotplugged(struct ata_eh_info *ehi)
{
__ata_ehi_hotplugged(ehi);
ehi->err_mask |= AC_ERR_ATA_BUS;
}
/*
* qc helpers
*/
static inline int
ata_sg_is_last(struct scatterlist *sg, struct ata_queued_cmd *qc)
{
if (sg == &qc->pad_sgent)
return 1;
if (qc->pad_len)
return 0;
if (((sg - qc->__sg) + 1) == qc->n_elem)
return 1;
return 0;
}
static inline struct scatterlist *
ata_qc_first_sg(struct ata_queued_cmd *qc)
{
if (qc->n_elem)
return qc->__sg;
if (qc->pad_len)
return &qc->pad_sgent;
return NULL;
}
static inline struct scatterlist *
ata_qc_next_sg(struct scatterlist *sg, struct ata_queued_cmd *qc)
{
if (sg == &qc->pad_sgent)
return NULL;
if (++sg - qc->__sg < qc->n_elem)
return sg;
if (qc->pad_len)
return &qc->pad_sgent;
return NULL;
}
#define ata_for_each_sg(sg, qc) \
for (sg = ata_qc_first_sg(qc); sg; sg = ata_qc_next_sg(sg, qc))
static inline unsigned int ata_tag_valid(unsigned int tag)
{
return (tag < ATA_MAX_QUEUE) ? 1 : 0;
}
static inline unsigned int ata_tag_internal(unsigned int tag)
{
return tag == ATA_MAX_QUEUE - 1;
}
/*
* device helpers
*/
static inline unsigned int ata_class_enabled(unsigned int class)
{
return class == ATA_DEV_ATA
#if defined(CONFIG_ATA_CEATA) || defined(CONFIG_ATA_CEATA_MODULE)
|| class == ATA_DEV_CEATA
#endif
|| class == ATA_DEV_ATAPI;
}
static inline unsigned int ata_class_disabled(unsigned int class)
{
return class == ATA_DEV_ATA_UNSUP || class == ATA_DEV_ATAPI_UNSUP;
}
static inline unsigned int ata_class_absent(unsigned int class)
{
return !ata_class_enabled(class) && !ata_class_disabled(class);
}
static inline unsigned int ata_dev_enabled(const struct ata_device *dev)
{
return ata_class_enabled(dev->class);
}
static inline unsigned int ata_dev_disabled(const struct ata_device *dev)
{
return ata_class_disabled(dev->class);
}
static inline unsigned int ata_dev_absent(const struct ata_device *dev)
{
return ata_class_absent(dev->class);
}
/*
* port helpers
*/
static inline int ata_port_max_devices(const struct ata_port *ap)
{
if (ap->flags & ATA_FLAG_SLAVE_POSS)
return 2;
return 1;
}
static inline u8 ata_chk_status(struct ata_port *ap)
{
return ap->ops->check_status(ap);
}
/**
* ata_ncq_enabled - Test whether NCQ is enabled
* @dev: ATA device to test for
*
* LOCKING:
* spin_lock_irqsave(host lock)
*
* RETURNS:
* 1 if NCQ is enabled for @dev, 0 otherwise.
*/
static inline int ata_ncq_enabled(struct ata_device *dev)
{
return (dev->flags & (ATA_DFLAG_PIO | ATA_DFLAG_NCQ_OFF |
ATA_DFLAG_NCQ)) == ATA_DFLAG_NCQ;
}
/**
* ata_pause - Flush writes and pause 400 nanoseconds.
* @ap: Port to wait for.
*
* LOCKING:
* Inherited from caller.
*/
static inline void ata_pause(struct ata_port *ap)
{
ata_altstatus(ap);
ndelay(400);
}
/**
* ata_busy_wait - Wait for a port status register
* @ap: Port to wait for.
* @bits: bits that must be clear
* @max: number of 10uS waits to perform
*
* Waits up to max*10 microseconds for the selected bits in the port's
* status register to be cleared.
* Returns final value of status register.
*
* LOCKING:
* Inherited from caller.
*/
static inline u8 ata_busy_wait(struct ata_port *ap, unsigned int bits,
unsigned int max)
{
u8 status;
do {
udelay(10);
status = ata_chk_status(ap);
max--;
} while (status != 0xff && (status & bits) && (max > 0));
return status;
}
/**
* ata_wait_idle - Wait for a port to be idle.
* @ap: Port to wait for.
*
* Waits up to 10ms for port's BUSY and DRQ signals to clear.
* Returns final value of status register.
*
* LOCKING:
* Inherited from caller.
*/
static inline u8 ata_wait_idle(struct ata_port *ap)
{
u8 status = ata_busy_wait(ap, ATA_BUSY | ATA_DRQ, 1000);
if (status != 0xff && (status & (ATA_BUSY | ATA_DRQ)))
DPRINTK("ATA: abnormal status 0x%X on port 0x%p\n",
status, ap->ioaddr.status_addr);
return status;
}
static inline void ata_qc_set_polling(struct ata_queued_cmd *qc)
{
qc->tf.ctl |= ATA_NIEN;
}
static inline struct ata_queued_cmd *__ata_qc_from_tag(struct ata_port *ap,
unsigned int tag)
{
if (likely(ata_tag_valid(tag)))
return &ap->qcmd[tag];
return NULL;
}
static inline struct ata_queued_cmd *ata_qc_from_tag(struct ata_port *ap,
unsigned int tag)
{
struct ata_queued_cmd *qc = __ata_qc_from_tag(ap, tag);
if (unlikely(!qc) || !ap->ops->error_handler)
return qc;
if ((qc->flags & (ATA_QCFLAG_ACTIVE |
ATA_QCFLAG_FAILED)) == ATA_QCFLAG_ACTIVE)
return qc;
return NULL;
}
static inline void ata_tf_init(struct ata_device *dev, struct ata_taskfile *tf)
{
memset(tf, 0, sizeof(*tf));
tf->ctl = dev->ap->ctl;
if (dev->devno == 0)
tf->device = ATA_DEVICE_OBS;
else
tf->device = ATA_DEVICE_OBS | ATA_DEV1;
}
static inline void ata_qc_reinit(struct ata_queued_cmd *qc)
{
qc->dma_dir = DMA_NONE;
qc->__sg = NULL;
qc->flags = 0;
qc->cursg = qc->cursg_ofs = 0;
qc->nbytes = qc->curbytes = 0;
qc->n_elem = 0;
qc->err_mask = 0;
qc->pad_len = 0;
qc->sect_size = ATA_SECT_SIZE;
ata_tf_init(qc->dev, &qc->tf);
/* init result_tf such that it indicates normal completion */
qc->result_tf.command = ATA_DRDY;
qc->result_tf.feature = 0;
}
static inline int ata_try_flush_cache(const struct ata_device *dev)
{
return ata_id_wcache_enabled(dev->id) ||
ata_id_has_flush(dev->id) ||
ata_id_has_flush_ext(dev->id);
}
static inline unsigned int ac_err_mask(u8 status)
{
if (status & (ATA_BUSY | ATA_DRQ))
return AC_ERR_HSM;
if (status & (ATA_ERR | ATA_DF))
return AC_ERR_DEV;
return 0;
}
static inline unsigned int __ac_err_mask(u8 status)
{
unsigned int mask = ac_err_mask(status);
if (mask == 0)
return AC_ERR_OTHER;
return mask;
}
static inline int ata_pad_alloc(struct ata_port *ap, struct device *dev)
{
ap->pad_dma = 0;
ap->pad = dmam_alloc_coherent(dev, ATA_DMA_PAD_BUF_SZ,
&ap->pad_dma, GFP_KERNEL);
return (ap->pad == NULL) ? -ENOMEM : 0;
}
static inline void ata_pad_free(struct ata_port *ap, struct device *dev)
{
dmam_free_coherent(dev, ATA_DMA_PAD_BUF_SZ, ap->pad, ap->pad_dma);
}
static inline struct ata_port *ata_shost_to_port(struct Scsi_Host *host)
{
return *(struct ata_port **)&host->hostdata[0];
}
#endif /* __LINUX_LIBATA_H__ */
| archos-sa/archos-gpl-gen6-kernel | include/linux/libata.h | C | gpl-2.0 | 38,068 |
# -*- coding: utf-8 -*-
default_app_config = 'escolar.apps.EscolarConfig' | kaajavi/ninformes | escolar/__init__.py | Python | gpl-2.0 | 73 |
#ifndef strings_h
#define strings_h
/* MSVC doesn't define ffs/ffsl. This dummy strings.h header is provided
* for both */
#include <intrin.h>
#pragma intrinsic(_BitScanForward)
static __forceinline int ffsl(long x)
{
unsigned long i;
if (_BitScanForward(&i, x))
return (i + 1);
return (0);
}
static __forceinline int ffs(int x)
{
return (ffsl(x));
}
#endif
| mynew/FuckerCrazyEmu | dep/jemalloc/include/msvc_compat/strings.h | C | gpl-2.0 | 412 |
/*
** Copyright (C) 1998-2002 Martin Roesch <roesch@sourcefire.com>
** Copyright (C) 2003 Sourcefire, Inc.
** Chris Green <cmg@sourcefire.com>
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software
** Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* $Id$ */
/* I N C L U D E S ************************************************/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <sys/types.h>
#include <stdlib.h>
#include <rpc/types.h>
#include <string.h>
#include <ctype.h>
#include "decode.h"
#include "rules.h"
#include "debug.h"
#include "util.h"
#include "generators.h"
#include "log.h"
#include "snort.h"
#include "ubi_SplayTree.h"
/* @todo Move all inlines to one central place */
#ifndef DEBUG
#ifndef INLINE
#define INLINE inline
#endif
#else
#ifdef INLINE
#undef INLINE
#endif
#define INLINE
#endif /* DEBUG */
/* D E F I N E S **************************************************/
#define TAG_SESSION 1
#define TAG_HOST 2
#define TAG_HOST_SRC 3
#define TAG_HOST_DST 4
#define TAG_METRIC_SECONDS 0x1
#define TAG_METRIC_PACKETS 0x2
#define TAG_METRIC_BYTES 0x4
#define TAG_METRIC_UNLIMITED 0x8
#define MAX_TAG_NODES 256
/* by default we'll set a 5 minute timeout if we see no activity
* on a tag with a 'count' metric so that we prune dead sessions
* periodically since we're not doing TCP state tracking
*/
#define TAG_PRUNE_QUANTUM 300
#define TAG_MEMCAP 4194304 /* 4MB */
/* D A T A S T R U C T U R E S **********************************/
typedef struct _PruneData
{
u_int32_t pruned;
u_int32_t time;
ubi_trRootPtr tree;
} PruneData;
typedef struct _TagNode
{
ubi_trNode Node;
/* ip addrs */
u_int32_t sip;
u_int32_t dip;
/* ports */
u_int16_t sp;
u_int16_t dp;
/* transport proto */
u_int8_t proto;
/* number of packets/seconds/bytes to tag for */
int seconds;
int packets;
int bytes;
/* counters of number of packets tagged and max to
* prevent Eventing DOS */
int pkt_count;
/* packets/seconds selector */
int metric;
/* session or host mode */
int mode;
/* last UNIX second that this node had a successful match */
u_int32_t last_access;
/* event id number for correlation with trigger events */
u_int16_t event_id;
struct timeval event_time;
/* for later expansion... */
OptTreeNode *otn;
} TagNode;
/* G L O B A L S **************************************************/
static ubi_trRoot host_tag_cache;
static ubi_trRootPtr host_tag_cache_ptr = &host_tag_cache;
static ubi_trRoot ssn_tag_cache;
static ubi_trRootPtr ssn_tag_cache_ptr = &ssn_tag_cache;
static u_int32_t last_prune_time;
static u_int32_t tag_alloc_faults;
static u_int32_t tag_memory_usage;
extern char check_tags_flag;
extern char *file_name;
extern int file_line;
/* P R O T O T Y P E S ********************************************/
static void *TagAlloc(unsigned long);
static int PruneTagCache(u_int32_t, int);
static int PruneTime(ubi_trRootPtr, u_int32_t);
static void TagSession(Packet *, TagData *, u_int32_t, u_int16_t);
static void TagHost(Packet *, TagData *, u_int32_t, u_int16_t);
static void AddTagNode(Packet *, TagData *, int, u_int32_t, u_int16_t);
static INLINE void SwapTag(TagNode *);
/* I should really make a generic function to do this... */
static void *TagAlloc(unsigned long size)
{
void *tmp;
tag_memory_usage += size;
if(tag_memory_usage > TAG_MEMCAP)
{
/* aggressively prune */
struct timeval tv;
struct timezone tz;
tag_alloc_faults++;
gettimeofday(&tv, &tz);
if(!PruneTagCache((u_int32_t)tv.tv_sec, 0))
{
/* if we can't prune due to time, just nuke 5 random sessions */
PruneTagCache(0, 5);
}
}
tmp = (void *) calloc(size, sizeof(char));
if(tmp == NULL)
{
FatalError("TagAlloc(): Unable to allocate memory! (%d bytes in use)\n",
tag_memory_usage);
}
return tmp;
}
#ifdef DEBUG
/**
* Print out a tag node IFF we are current in debug_flow
*
* @param np tagnode pointer to print
*/
static void PrintTagNode(TagNode *np)
{
if(!DebugThis(DEBUG_FLOW))
{
return;
}
printf("+--------------------------------------------------------------\n");
printf("| Ssn Counts: %u, Host Counts: %u\n",
ssn_tag_cache.count,
host_tag_cache.count);
printf("| (%u) %x:%d -> %x:%d Metric: %u "
"LastAccess: %u, event_id: %u mode: %u event_time.tv_sec: %u\n"
"| Packets: %d, Bytes: %d, Seconds: %d\n",
np->proto,
np->sip, np->sp,
np->dip, np->dp,
np->metric,
np->last_access,
np->event_id,
np->mode,
np->event_time.tv_sec,
np->packets,
np->bytes,
np->seconds);
printf("+--------------------------------------------------------------\n");
}
#endif /* DEBUG */
/**
* swap the sips and dips, dp's and sp's
*
* @param np TagNode ptr
*/
static INLINE void SwapTag(TagNode *np)
{
u_int32_t tip;
u_int16_t tport;
tip = np->sip;
np->sip = np->dip;
np->dip = tip;
tport = np->sp;
np->sp = np->dp;
np->dp = tport;
}
static int TagCompareSession(ubi_trItemPtr ItemPtr, ubi_trNodePtr NodePtr)
{
TagNode *nTag;
TagNode *iTag;
nTag = ((TagNode *)NodePtr);
iTag = ((TagNode *)ItemPtr);
if(nTag->sip < iTag->sip)
{
return 1;
}
else if(nTag->sip > iTag->sip)
{
return -1;
}
if(nTag->dip < iTag->dip)
{
return 1;
}
else if(nTag->dip > iTag->dip)
{
return -1;
}
if(nTag->sp < iTag->sp)
{
return 1;
}
else if(nTag->sp > iTag->sp)
{
return -1;
}
if(nTag->dp < iTag->dp)
{
return 1;
}
else if(nTag->dp > iTag->dp)
{
return -1;
}
return 0;
}
static int TagCompareHost(ubi_trItemPtr ItemPtr, ubi_trNodePtr NodePtr)
{
TagNode *nTag;
TagNode *iTag;
nTag = ((TagNode *)NodePtr);
iTag = ((TagNode *)ItemPtr);
if(nTag->sip < iTag->sip)
{
return 1;
}
else if(nTag->sip > iTag->sip)
{
return -1;
}
return 0;
}
void InitTag()
{
(void)ubi_trInitTree(ssn_tag_cache_ptr, /* ptr to the tree head */
TagCompareSession, /* comparison function */
0); /* don't allow overwrites/duplicates */
(void)ubi_trInitTree(host_tag_cache_ptr, /* ptr to the tree head */
TagCompareHost, /* comparison function */
0); /* don't allow overwrites/duplicates */
}
static void TagSession(Packet *p, TagData *tag, u_int32_t time, u_int16_t event_id)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "TAGGING SESSION\n"););
AddTagNode(p, tag, TAG_SESSION, time, event_id);
}
static void TagHost(Packet *p, TagData *tag, u_int32_t time, u_int16_t event_id)
{
int mode;
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "TAGGING HOST\n"););
switch(tag->tag_direction)
{
case TAG_HOST_DST:
mode = TAG_HOST_DST;
break;
case TAG_HOST_SRC:
mode = TAG_HOST_SRC;
break;
default:
mode = TAG_HOST_SRC;
break;
}
AddTagNode(p, tag, mode, time, event_id);
}
static void AddTagNode(Packet *p, TagData *tag, int mode, u_int32_t now,
u_int16_t event_id)
{
TagNode *idx; /* index pointer */
TagNode *returned;
ubi_trRootPtr tag_cache_ptr = NULL;
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "Adding new Tag Head\n"););
idx = (TagNode *) TagAlloc(sizeof(TagNode));
idx->sip = p->iph->ip_src.s_addr;
idx->dip = p->iph->ip_dst.s_addr;
idx->sp = p->sp;
idx->dp = p->dp;
idx->proto = p->iph->ip_proto;
idx->metric = tag->tag_metric;
idx->last_access = now;
idx->event_id = event_id;
idx->event_time.tv_sec = p->pkth->ts.tv_sec;
idx->event_time.tv_usec = p->pkth->ts.tv_usec;
idx->mode = mode;
idx->pkt_count = 0;
if(idx->metric & TAG_METRIC_SECONDS)
{
/* set the expiration time for this tag */
idx->seconds = now + tag->tag_seconds;
}
if(idx->metric & TAG_METRIC_BYTES)
{
/* set the expiration time for this tag */
idx->bytes = tag->tag_bytes;
}
if(idx->metric & TAG_METRIC_PACKETS)
{
/* set the expiration time for this tag */
idx->packets = tag->tag_packets;
}
DEBUG_WRAP(PrintTagNode(idx););
if(mode == TAG_SESSION)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Session Tag!\n"););
tag_cache_ptr = ssn_tag_cache_ptr;
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Host Tag!\n"););
tag_cache_ptr = host_tag_cache_ptr;
}
/* check for duplicates */
returned = (TagNode *) ubi_sptFind(tag_cache_ptr,
(ubi_btItemPtr)idx);
if(returned == NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Looking the other way!!\n"););
SwapTag(idx);
returned = (TagNode *) ubi_sptFind(tag_cache_ptr,
(ubi_btItemPtr)idx);
SwapTag(idx);
}
if(returned == NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Inserting a New Tag!\n"););
/* if we're supposed to be tagging the other side, swap it
around -- Lawrence Reed */
if(mode == TAG_HOST_DST)
{
SwapTag(idx);
}
if(ubi_sptInsert(tag_cache_ptr,
(ubi_btNodePtr)idx, (ubi_btNodePtr)idx, NULL) == FALSE)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,
"sptInsert failed, that's going to "
"make life difficult\n"););
return;
}
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Existing Tag found!\n"););
if(idx->metric & TAG_METRIC_SECONDS)
returned->seconds = idx->seconds;
else
returned->seconds += idx->seconds;
/* get rid of the new tag since we are using an existing one */
free(idx);
tag_memory_usage -= sizeof(TagNode);
}
DEBUG_WRAP(PrintTagNode(idx););
return;
}
int CheckTagList(Packet *p, Event *event)
{
TagNode idx;
TagNode *returned = NULL;
ubi_trRootPtr taglist = NULL;
char create_event = 1;
/* check for active tags */
if(!ubi_trCount(host_tag_cache_ptr) && !ubi_trCount(ssn_tag_cache_ptr))
{
return 0;
}
if(p == NULL || p->iph == NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "bailing from CheckTagList, p->iph == NULL\n"););
return 0;
}
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Host Tags Active: %d Session Tags Active: %d\n",
ubi_trCount(host_tag_cache_ptr), ubi_trCount(ssn_tag_cache_ptr)););
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "[*] Checking session tag list (forward)...\n"););
idx.sip = p->iph->ip_src.s_addr;
idx.dip = p->iph->ip_dst.s_addr;
idx.sp = p->sp;
idx.dp = p->dp;
/* check for session tags... */
returned = (TagNode *) ubi_sptFind(ssn_tag_cache_ptr, (ubi_btItemPtr)&idx);
if(returned == NULL)
{
idx.dip = p->iph->ip_src.s_addr;
idx.sip = p->iph->ip_dst.s_addr;
idx.dp = p->sp;
idx.sp = p->dp;
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, " Checking session tag list (reverse)...\n"););
returned = (TagNode *) ubi_sptFind(ssn_tag_cache_ptr,
(ubi_btItemPtr)&idx);
if(returned == NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, " Checking host tag list "
"(forward)...\n"););
returned = (TagNode *) ubi_sptFind(host_tag_cache_ptr,
(ubi_btItemPtr)&idx);
if(returned == NULL)
{
/*
** Only switch sip, because that's all we check for
** the host tags.
*/
idx.sip = p->iph->ip_src.s_addr;
returned = (TagNode *) ubi_sptFind(host_tag_cache_ptr,
(ubi_btItemPtr)&idx);
}
if(returned != NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW," [*!*] Found host node\n"););
taglist = host_tag_cache_ptr;
}
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW," [*!*] Found session node\n"););
taglist = ssn_tag_cache_ptr;
}
}
else
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW," [*!*] Found session node\n"););
taglist = ssn_tag_cache_ptr;
}
if(returned != NULL)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, " ! Found tag node !\n"););
returned->last_access = p->pkth->ts.tv_sec;
if(returned->metric & TAG_METRIC_SECONDS)
{
if(p->pkth->ts.tv_sec > returned->seconds)
{
returned->seconds = 0;
}
}
if(returned->metric & TAG_METRIC_PACKETS)
{
/* decrement the packet count */
returned->packets--;
if (returned->packets < 0)
{
returned->packets = 0;
create_event = 0;
}
}
if(returned->metric & TAG_METRIC_BYTES)
{
returned->bytes -= (int) ntohs(p->iph->ip_len);
if(returned->bytes < 0)
{
returned->bytes = 0;
}
}
returned->pkt_count++;
/* Check whether or not to actually log an event.
* This is used to prevent a poorly written tag rule
* from DOSing a backend event processors on high
* bandwidth sensors. */
if (!(returned->metric & (TAG_METRIC_PACKETS|TAG_METRIC_UNLIMITED)))
{
/* Use the global max. */
/* If its non-0, check count for this tag node */
if (pv.tagged_packet_limit &&
returned->pkt_count > pv.tagged_packet_limit)
{
create_event = 0;
}
}
if (create_event)
{
/* set the event info */
SetEvent(event, GENERATOR_TAG, TAG_LOG_PKT, 1, 1, 1,
returned->event_id);
/* set event reference details */
event->ref_time.tv_sec = returned->event_time.tv_sec;
event->ref_time.tv_usec = returned->event_time.tv_usec;
}
if(returned->bytes == 0 && returned->packets == 0 &&
returned->seconds == 0)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW," Prune condition met for tag, removing"
" from list\n"););
returned = (TagNode *) ubi_sptRemove(taglist,
(ubi_btNodePtr)returned);
free(returned);
tag_memory_usage -= sizeof(TagNode);
}
}
if( (u_int)(p->pkth->ts.tv_sec) > last_prune_time + TAG_PRUNE_QUANTUM)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,
"Exceeded Prune Quantum, pruning tag trees\n"););
PruneTagCache(p->pkth->ts.tv_sec, 0);
last_prune_time = p->pkth->ts.tv_sec;
}
if((returned != NULL) && (create_event))
{
return 1;
}
return 0;
}
static int PruneTagCache(u_int32_t thetime, int mustdie)
{
TagNode *idx;
int pruned = 0;
if(!mustdie)
{
if(ubi_trCount(ssn_tag_cache_ptr))
{
pruned = PruneTime(ssn_tag_cache_ptr, thetime);
}
if(ubi_trCount(host_tag_cache_ptr))
{
pruned += PruneTime(host_tag_cache_ptr, thetime);
}
return pruned;
}
else
{
while(mustdie > 0)
{
if(ubi_trCount(ssn_tag_cache_ptr))
{
idx = (TagNode *)
ubi_btLeafNode((ubi_btNodePtr)ssn_tag_cache_ptr);
mustdie--;
free(idx);
tag_memory_usage -= sizeof(TagNode);
}
if(ubi_trCount(host_tag_cache_ptr))
{
idx = (TagNode *)
ubi_btLeafNode((ubi_btNodePtr)host_tag_cache_ptr);
mustdie--;
free(idx);
tag_memory_usage -= sizeof(TagNode);
}
}
return 0;
}
}
static int PruneTime(ubi_trRootPtr tree, u_int32_t thetime)
{
int pruned = 0;
TagNode *idx;
TagNode *savidx;
TagNode *killme;
idx = (TagNode *) ubi_btFirst((ubi_btNodePtr)tree);
if(idx == NULL)
{
return 0;
}
do
{
if((idx->last_access+TAG_PRUNE_QUANTUM) < thetime)
{
savidx = idx;
idx = (TagNode *) ubi_btNext((ubi_btNodePtr)idx);
killme = (TagNode *) ubi_sptRemove(tree, (ubi_btNodePtr) savidx);
free(killme);
tag_memory_usage -= sizeof(TagNode);
pruned++;
}
else
{
if(idx != NULL && ubi_trCount(tree))
{
idx = (TagNode *) ubi_btNext((ubi_btNodePtr)idx);
}
else
{
return pruned;
}
}
} while(idx != NULL);
return pruned;
}
void SetTags(Packet *p, OptTreeNode *otn, u_int16_t event_id)
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "Setting tags\n"););
if(otn != NULL && otn->tag != NULL)
{
if (otn->tag->tag_type != 0)
{
switch(otn->tag->tag_type)
{
case TAG_SESSION:
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Setting session tag:\n");
DebugMessage(DEBUG_FLOW,"SIP: 0x%X SP: %d DIP: 0x%X "
"DP: %d\n", p->iph->ip_src.s_addr,p->sp,
p->iph->ip_dst.s_addr,p->dp););
TagSession(p, otn->tag, p->pkth->ts.tv_sec, event_id);
break;
case TAG_HOST:
DEBUG_WRAP(DebugMessage(DEBUG_FLOW,"Setting host tag:\n");
DebugMessage(DEBUG_FLOW,"SIP: 0x%X SP: %d DIP: 0x%X "
"DP: %d\n", p->iph->ip_src.s_addr,p->sp,
p->iph->ip_dst.s_addr,p->dp););
TagHost(p, otn->tag, p->pkth->ts.tv_sec, event_id);
break;
default:
LogMessage("WARNING: Trying to tag with unknown "
"tag type!\n");
break;
}
check_tags_flag = 0;
}
}
return;
}
void ParseTag(char *args, OptTreeNode *otn)
{
char *arg = args;
int type = 0;
int count = 0;
int metric = 0;
int packets = 0;
int seconds = 0;
int bytes = 0;
int direction = 0;
int i = 0;
DEBUG_WRAP(DebugMessage(DEBUG_RULES, "Parsing tag args: %s\n", args););
while ((arg = strtok( arg, " ,")))
{
DEBUG_WRAP(DebugMessage(DEBUG_RULES, "parsing tag tok: \"%s\"\n", arg););
while(isspace((int)*arg))
{
arg++;
}
if(!strncasecmp(arg, "session", 7))
{
DEBUG_WRAP(DebugMessage(DEBUG_FLOW, "Setting type to SESSION\n"););
type = TAG_SESSION;
}
else if(!strncasecmp(arg, "host", 4))
{
type = TAG_HOST;
}
else if(!strncasecmp(arg, "src", 3))
{
direction = TAG_HOST_SRC;
}
else if(!strncasecmp(arg, "dst", 3))
{
direction = TAG_HOST_DST;
}
else if(!strncasecmp(arg, "seconds", 7))
{
metric |= TAG_METRIC_SECONDS;
seconds = count;
}
else if (!strncasecmp(arg, "packets", 7))
{
if (count)
{
metric |= TAG_METRIC_PACKETS;
packets = count;
}
else
{
metric |= TAG_METRIC_UNLIMITED;
/* Set count in case 'packets' is the last
* option parsed since 0 is a valid value now */
count = -1;
}
}
else if(!strncasecmp(arg, "bytes", 5))
{
metric |= TAG_METRIC_BYTES;
bytes = count;
}
else if(isdigit((int) *arg))
{
count = atoi(arg);
}
else
{
FatalError("%s(%d) Unable to Parse Tag option: %s\n", file_name, file_line, arg);
}
arg = NULL;
i++;
}
DEBUG_WRAP(DebugMessage(DEBUG_PLUGIN, "Set type: %d metric: %x count: %d\n", type,
metric, count););
/* check that we've got enough to set a tag with */
if(type && metric && count)
{
otn->tag = (TagData *)calloc(sizeof(TagData), sizeof(char));
otn->tag->tag_type = type;
otn->tag->tag_metric = metric;
otn->tag->tag_seconds = seconds;
otn->tag->tag_bytes = bytes;
otn->tag->tag_packets = packets;
otn->tag->tag_direction = direction;
}
if ((metric & TAG_METRIC_UNLIMITED) &&
!(metric & (TAG_METRIC_BYTES|TAG_METRIC_SECONDS)))
{
FatalError("%s(%d) Invalid Tag options. 'packets' parameter '0' but\n"
"neither seconds or bytes specified: %s\n",
file_name, file_line, arg);
}
return;
}
| scs/uclinux | user/snort/src/tag.c | C | gpl-2.0 | 22,397 |
/*****************************************************************************
1 Í·Îļþ°üº¬
*****************************************************************************/
#include "TafCbsInterface.h"
#include "TafCbaProcAs.h"
#include "TafCbaComFunc.h"
#include "TafCbaProcEtwsPrimNtf.h"
#include "TafCbaProcNvim.h"
#include "TafCbaMntn.h"
#include "TafCbaProcUsim.h"
#include "TafCbaProcAt.h"
#include "MnComm.h"
#include "mnmsgcbencdec.h"
#include "MnMsgReport.h"
#include "MnMsgTimerProc.h"
#include "TafLog.h"
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
#define THIS_FILE_ID PS_FILE_ID_TAF_CBA_PROC_AS_C
#if ((FEATURE_ON == FEATURE_GCBS) || (FEATURE_ON == FEATURE_WCBS))
/*****************************************************************************
2 È«¾Ö±äÁ¿¶¨Òå
*****************************************************************************/
/*lint -save -e958 */
/*****************************************************************************
3 º¯ÊýʵÏÖ
*****************************************************************************/
VOS_VOID TAF_CBA_ProcGasMsg(
struct MsgCB *pstMsg
)
{
TAF_CBS_MSG_DATA *pstMsgData;
pstMsgData = (TAF_CBS_MSG_DATA *)pstMsg;
switch (pstMsgData->enMsgID)
{
case ID_GAS_CBS_CFG_CNF:
TAF_CBA_RcvAsCbsCfgCnf((BMC_CBS_CFG_CNF_STRU *)pstMsg);
break;
case ID_GAS_CBS_DATA_IND :
TAF_CBA_RcvGasCbsDataInd((GAS_CBS_DATA_IND_STRU *)pstMsg);
break;
case ID_RR_CBS_GS_STATUS_CHANGE_IND:
TAF_CBA_RcvAsGsStatusChangeInd((RR_CBS_GS_STATUS_CHANGE_IND_STRU *)pstMsg);
break;
default:
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_ProcGasMsg:Invalid Msg");
break;
}
}
VOS_VOID TAF_CBA_ProcWrrMsg(
struct MsgCB *pstMsg
)
{
TAF_CBS_MSG_DATA *pstMsgData;
pstMsgData = (TAF_CBS_MSG_DATA *)pstMsg;
switch (pstMsgData->enMsgID)
{
#if (FEATURE_ETWS == FEATURE_ON)
case ID_RR_CBS_ETWS_PRIMARY_NOTIFY_IND:
TAF_CBA_RcvAsEtwsPrimNotifyInd((RR_CBS_ETWS_PRIMARY_NOTIFY_IND_STRU *)pstMsg);
break;
#endif
case ID_RR_CBS_GS_STATUS_CHANGE_IND:
TAF_CBA_RcvAsGsStatusChangeInd((RR_CBS_GS_STATUS_CHANGE_IND_STRU *)pstMsg);
break;
default:
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_ProcWrrMsg:Invalid Msg");
break;
}
}
VOS_VOID TAF_CBA_ProcBmcMsg(
struct MsgCB *pstMsg
)
{
TAF_CBS_MSG_DATA *pstMsgData;
pstMsgData = (TAF_CBS_MSG_DATA *)pstMsg;
switch (pstMsgData->enMsgID)
{
case ID_BMC_CBS_CFG_CNF:
TAF_CBA_RcvAsCbsCfgCnf((BMC_CBS_CFG_CNF_STRU *)pstMsg);
break;
case ID_BMC_CBS_DATA_IND :
TAF_CBA_RcvBmcCbsDataInd((BMC_CBS_DATA_IND_STRU *)pstMsg);
break;
default:
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_ProcBmcMsg:Invalid Msg");
break;
}
}
#if (FEATURE_ON == FEATURE_LTE)
VOS_VOID TAF_CBA_ProcLrrcMsg(
struct MsgCB *pstMsg
)
{
TAF_CBS_MSG_DATA *pstMsgData;
pstMsgData = (TAF_CBS_MSG_DATA *)pstMsg;
switch (pstMsgData->enMsgID)
{
#if (FEATURE_ETWS == FEATURE_ON)
case ID_RR_CBS_ETWS_PRIMARY_NOTIFY_IND:
TAF_CBA_RcvAsEtwsPrimNotifyInd((RR_CBS_ETWS_PRIMARY_NOTIFY_IND_STRU *)pstMsg);
break;
#endif
case ID_LRRC_CBS_DATA_IND:
TAF_CBA_SetNetRatType(TAF_CBA_NET_RAT_TYPE_LTE);
TAF_CBA_RcvLrrcCbsDataInd((LRRC_CBS_DATA_IND_STRU *)pstMsg);
break;
case ID_RR_CBS_GS_STATUS_CHANGE_IND:
TAF_CBA_RcvAsGsStatusChangeInd((RR_CBS_GS_STATUS_CHANGE_IND_STRU *)pstMsg);
break;
default:
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_ProcLrrcMsg:Invalid Msg");
break;
}
}
#endif /* (FEATURE_ON == FEATURE_LTE) */
VOS_VOID TAF_CBA_RcvAsCbsCfgCnf(
BMC_CBS_CFG_CNF_STRU *pstCfgCnf
)
{
if ( TAF_CBS_CFG_RSLT_FAIL == pstCfgCnf->enRslt )
{
TAF_WARNING_LOG(WUEPS_PID_TAF, "TAF_CBA_RcvAsCbsCfgCnf: Active cnf fail");
}
}
VOS_VOID TAF_CBA_RcvGasCbsDataInd(
GAS_CBS_DATA_IND_STRU *pstGasDataInd
)
{
VOS_UINT8 ucPageLen;
MN_MSG_CBRAW_TS_DATA_STRU *pstCbRawData;
VOS_UINT8 ucPageNum;
MN_MSG_CBGSMPAGE_STRU *pstGsmPage;
TAF_CBA_RECORD_STRU stNewRecord;
VOS_UINT8 ucIndex;
VOS_UINT8 ucTotalPage;
VOS_UINT8 ucPageIndex;
pstCbRawData = (MN_MSG_CBRAW_TS_DATA_STRU *)PS_MEM_ALLOC(WUEPS_PID_TAF, sizeof(MN_MSG_CBRAW_TS_DATA_STRU) * (pstGasDataInd->ucPageNum));
if ( VOS_NULL_PTR == pstCbRawData )
{
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_RcvGasCbsDataInd:Alloc Mem Failed");
return;
}
PS_MEM_SET(pstCbRawData, 0x00, sizeof(MN_MSG_CBRAW_TS_DATA_STRU) * (pstGasDataInd->ucPageNum));
ucPageNum = 0;
for ( ucIndex = 0 ; ucIndex < pstGasDataInd->ucPageNum; ucIndex++ )
{
/* ½«Ã¿¶ÎCBSµÄ³¤¶ÈÈ¥³ýÌî³äÖµ,¸üÐÂΪʵ¼ÊµÄ³¤¶È */
if ( VOS_TRUE == TAF_CBA_GetRptAppFullPageFlg() )
{
ucPageLen = (VOS_UINT8)(pstGasDataInd->astPageData[ucIndex].ulLength);
}
else
{
ucPageLen = TAF_CBA_GetGsmCbsPageLen(&(pstGasDataInd->astPageData[ucIndex]));
}
/* Èç¹û³¤¶ÈСÓÚÍ·µÄ³¤¶È,Ôò²»Éϱ¨ */
if ( ucPageLen < TAF_CBA_MAX_CB_HEADER_LEN )
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmLogInfo(TAF_CBA_OM_LOG_PAGELEN_INVALID);
continue;
}
pstGsmPage = (MN_MSG_CBGSMPAGE_STRU*)pstGasDataInd->astPageData[ucIndex].aucData;
/* ÅжϸÃÒ³µÄË÷ÒýÖµÊÇ·ñ´óÓÚ×ÜÒ³Êý */
ucTotalPage = pstGsmPage->Pagesbit4;
ucPageIndex = pstGsmPage->Pagebit4;
/* Èç¹û ucTotalPage»òucPageNumberÖÐÒ»¸öΪ0,Ôòµ±×÷ 0001 0001 ,²Î¼ûÐÒé23041 9.4.1.2.4 */
if ( ( 0x00 == ucTotalPage )
|| ( 0x00 == ucPageIndex ) )
{
ucTotalPage = 0x01;
ucPageIndex = 0x01;
}
if (ucPageIndex > ucTotalPage)
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmLogInfo(TAF_CBA_OM_LOG_PAGEINDEX_INVALID);
continue;
}
/* ÅжÏCBSÏûÏ¢µÄMSG IDÊÇ·ñÔÚ¼¤»îÁбíÖУ¬²»ÔÚÔò¼ÌÐø±È½ÏÏÂÒ³ */
if ( VOS_TRUE != TAF_CBA_IsCbsMsgIdValid( TAF_CBA_BuildCbsMsgId(pstGsmPage->ucMIdHigh, pstGsmPage->ucMIdLow)) )
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmLogInfo(TAF_CBA_OM_LOG_CBS_MSGID_INVALID);
continue;
}
/* ɾ³ýÖØ¸´¼ì²âʱ³¤³¬Ê±µÄCBS¼Ç¼ */
TAF_CBA_DelCbsExpiredRecord();
/* ¹¹ÔìÊý¾Ý¼Ç¼ */
TAF_CBA_BuildGsmCbsRecord(pstGsmPage, &pstGasDataInd->stCurrNetworkInfo, &stNewRecord);
/* ¼ì²éÊÇ·ñÊÇÖØ¸´µÄÏûÏ¢Ò³, ÖØ¸´µÄÏûÏ¢Ò³²»Óñ£´æºÍÉϱ¨µ½AT */
if (VOS_TRUE == TAF_CBA_IsDupGsmCbsRecord(&stNewRecord))
{
continue;
}
/* ±£´æ¸Ã¼Ç¼Ïî */
TAF_CBA_SaveGsmCbsRecord(&stNewRecord);
pstCbRawData[ucIndex].ulLen = ucPageLen;
PS_MEM_CPY(pstCbRawData[ucIndex].aucData,
pstGasDataInd->astPageData[ucIndex].aucData,
ucPageLen);
ucPageNum++;
}
/* ÎÞÓÐЧҳÔò²»ÓÃÉϱ¨ */
if (ucPageNum > 0)
{
/* µ÷ÓÃͳһµÄ´¦Àíº¯ÊýÉϱ¨CBS»òEnvelopeµ½USIM */
TAF_CBA_ReportRcvCbsData(ucPageNum, pstCbRawData);
}
PS_MEM_FREE(WUEPS_PID_TAF, pstCbRawData);
}
VOS_UINT32 TAF_CBA_ConvertBmcCbsToGsmCbsFormat(
BMC_CBS_DATA_IND_STRU *pstDataPdu,
VOS_UINT8 *pucPageNum,
MN_MSG_CBRAW_TS_DATA_STRU *pstPageDataInd
)
{
VOS_UINT8 ucPageIdx;
VOS_UINT32 ulIndex;
MN_MSG_CBGSMPAGE_STRU *pstGsmPage;
VOS_UINT8 ucPageSegment;
VOS_UINT8 ucPageSegmentOffset;
VOS_UINT8 ucPageNumInMsg;
VOS_UINT16 usLeftLength;
TAF_CBA_CB_W_AIR_DATA_STRU *pstCbWData;
*pucPageNum = 0;
ucPageIdx = 1;
/* 23041 9.3.19 This parameter is of a fixed length of 82 octets and carries up to and including 82 octets of user information. Where the
user information is less than 82 octets, the remaining octets must be filled with padding (see 3GPP TS 23.038 [3]).
The content of a CBS-Message-Information-Page is passed transparently from the CBC to the MS/UE.
In GSM the CBS-Message-Information-Page n becomes the 'Content of Message' parameter at the MS.
In UMTS the CBS-Message-Information-Pages together with the associated CBS-Message-Information-Length
parameter is broadcasted as a single unit over the radio inteface.
In the case where the user information is GSM 7 bit default alphabet encoded, the appropriate padding characters and
bit-fill are added to the end of the user information to complete the CBC-Message-Information-Page
(see 3GPP TS 23.038 [3]).
In the case where the user information is 8 bit encoded, the appropriate padding octets are added to the end of the user
information to complete the CBC-Message-Information-Page (see 3GPP TS 23.038 [3]). */
/*
23041 9.4.2.2.5 CBDATA
- Number-of-Pages;
- CBS-Message-Information-Page;
- CBS-Message-Information-Length.
Octet Number(s) Parameter
1 Number-of-Pages
2 ¨C 83 CBS-Message-Information-Page 1
84 CBS-Message-Information-Length 1
¡ ¡
CBS-Message-Information-Page n
CBS-Message-Information-Length n
*/
/* ÓÉÓÚÏûÏ¢ÖÐЯ´øÁËPage¸öÊý,Ìî³äµ½ÏûÏ¢ÄÚÈÝÖÐÒÔÏûÏ¢ÖÐЯ´øµÄPage¸öÊýΪ׼,
µ«»ñȡҳÊýÐèÒª×ۺϿ¼ÂÇÏûÏ¢³¤¶ÈºÍÏûÏ¢ÖÐЯ´øµÄÒ³Êý */
if ( pstDataPdu->usCBDataLen <= TAF_CBA_CB_W_NUM_OF_PAGES_POS )
{
TAF_WARNING_LOG(WUEPS_PID_TAF, "TAF_CBA_ConvertBmcCbsToGsmCbsFormat: CbDataLen too small");
return VOS_ERR;
}
/* µÚ0¸ö×Ö½Ú±íʾҳÊý */
ucPageNumInMsg = pstDataPdu->aucCBData[0];
/* ¼ÆË㵱ǰCBSÏûÏ¢µÄ³¤¶ÈµÄ·Ö¶Î */
ucPageSegmentOffset = (pstDataPdu->usCBDataLen
- TAF_CBA_CB_W_NUM_OF_PAGES_POS)%TAF_CBA_MAX_CB_PAGE_LEN;
ucPageSegment = (VOS_UINT8)((pstDataPdu->usCBDataLen
- TAF_CBA_CB_W_NUM_OF_PAGES_POS)/TAF_CBA_MAX_CB_PAGE_LEN);
if ( 0 != ucPageSegmentOffset )
{
ucPageSegment++;
}
/* Ò³Êý²»ÕýÈ·,ÔòÖ±½Ó·µ»Ø */
if ( ( 0 == ucPageNumInMsg ) || ( 0 == ucPageSegment ) )
{
TAF_WARNING_LOG(WUEPS_PID_TAF, "TAF_CBA_ConvertBmcCbsToGsmCbsFormat:Empty CbDataLen");
return VOS_ERR;
}
*pucPageNum = ucPageSegment;
if ( *pucPageNum > TAF_CBA_MAX_CBMPAGE_NUM )
{
TAF_WARNING_LOG(WUEPS_PID_TAF, "TAF_CBA_ConvertBmcCbsToGsmCbsFormat:Too Long CbDataLen");
*pucPageNum = TAF_CBA_MAX_CBMPAGE_NUM;
}
pstCbWData = (TAF_CBA_CB_W_AIR_DATA_STRU *)(&(pstDataPdu->aucCBData[TAF_CBA_CB_W_NUM_OF_PAGES_POS]));
/* ½«Õû¸öCBSÏûϢģÄâΪGÄ£ÏÂCBSÏûÏ¢µÄ¸ñʽ */
usLeftLength = pstDataPdu->usCBDataLen - TAF_CBA_CB_W_NUM_OF_PAGES_POS;
for ( ulIndex = 0 ; ulIndex < *pucPageNum ; ulIndex++ )
{
pstGsmPage = (MN_MSG_CBGSMPAGE_STRU *)(pstPageDataInd->aucData);
pstGsmPage->ucDCS = pstDataPdu->ucDataCodeScheme;
pstGsmPage->ucSnHigh = (VOS_UINT8)((pstDataPdu->usSerialNum & 0xFF00) >> 8);
pstGsmPage->ucSnLow = (VOS_UINT8)(pstDataPdu->usSerialNum & 0x00FF);
pstGsmPage->ucMIdHigh = (VOS_UINT8)((pstDataPdu->usCBMID & 0xFF00) >> 8);
pstGsmPage->ucMIdLow = (VOS_UINT8)((pstDataPdu->usCBMID & 0x00FF));
pstGsmPage->Pagebit4 = ucPageIdx;
pstGsmPage->Pagesbit4 = ucPageNumInMsg;
/* »ñÈ¡µ±Ç°CBSÏûÏ¢µÄÓÐЧ³¤¶È */
if (usLeftLength >= TAF_CBA_MAX_CB_PAGE_LEN)
{
if ( VOS_TRUE == TAF_CBA_GetRptAppFullPageFlg() )
{
pstPageDataInd->ulLen = TAF_CBA_MAX_CBDATA_LEN + TAF_CBA_MAX_CB_HEADER_LEN;
}
else
{
pstPageDataInd->ulLen = pstCbWData->ucCbsDataLen + TAF_CBA_MAX_CB_HEADER_LEN;
}
/*´Ë´¦ÐèÒª½øÐб£»¤ÒÔÃâÍøÂçÊý¾Ý³ö´í*/
if ( pstPageDataInd->ulLen > TAF_CBA_MAX_CBPAGE_LEN )
{
pstPageDataInd->ulLen = TAF_CBA_MAX_CBPAGE_LEN;
}
PS_MEM_CPY(pstGsmPage->aucContent,
pstCbWData->aucCbsData,
TAF_CBA_MAX_CBDATA_LEN);
usLeftLength -= TAF_CBA_MAX_CB_PAGE_LEN;
}
else
{
pstPageDataInd->ulLen = usLeftLength + TAF_CBA_MAX_CB_HEADER_LEN;
PS_MEM_CPY(pstGsmPage->aucContent,
pstCbWData->aucCbsData,
usLeftLength);
break;
}
ucPageIdx++;
pstCbWData++;
pstPageDataInd++;
}
return VOS_OK;
}
VOS_VOID TAF_CBA_RcvBmcCbsDataInd(
BMC_CBS_DATA_IND_STRU *pstBmcDataInd
)
{
MN_MSG_CBRAW_TS_DATA_STRU *pstCbRawData;
VOS_UINT8 ucPageNum;
VOS_UINT32 ulRet;
TAF_CBA_RECORD_STRU stNewRecord;
/* ÅжÏÏûÏ¢IDÊÇ·ñÓÐЧ */
if (VOS_TRUE != TAF_CBA_IsCbsMsgIdValid(pstBmcDataInd->usCBMID))
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmLogInfo(TAF_CBA_OM_LOG_CBS_MSGID_INVALID);
return;
}
/* ¼ì²éºÍɾ³ýÖØ¸´¼ì²âʱ³¤³¬Ê±µÄCBS¼Ç¼ */
TAF_CBA_DelCbsExpiredRecord();
/* ¹¹ÔìCBSÏûÏ¢Êý¾Ý¼Ç¼ */
TAF_CBA_BuildBmcCbsRecord(pstBmcDataInd, &stNewRecord);
/* ¼ì²éÊÇ·ñÊÇÖØ¸´µÄÏûÏ¢, ÖØ¸´µÄÏûÏ¢, ²»Óñ£´æºÍÉϱ¨µ½AT */
if (VOS_TRUE == TAF_CBA_IsDupBmcCbsRecord(&stNewRecord))
{
return;
}
/* ±£´æ¼Ç¼ */
TAF_CBA_SaveBmcCbsRecord(&stNewRecord);
pstCbRawData = (MN_MSG_CBRAW_TS_DATA_STRU *)PS_MEM_ALLOC(WUEPS_PID_TAF, sizeof(MN_MSG_CBRAW_TS_DATA_STRU) * TAF_CBA_MAX_CBMPAGE_NUM);
if (VOS_NULL_PTR == pstCbRawData)
{
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_RcvBmcCbsDataInd:Alloc Mem Failed");
return;
}
PS_MEM_SET(pstCbRawData, 0x00, sizeof(MN_MSG_CBRAW_TS_DATA_STRU) * TAF_CBA_MAX_CBMPAGE_NUM);
/* ÓÉÓÚÉϱ¨µÄCBSÄÚÈÝÊÇGSMģʽµÄ,ËùÒÔÐèÒª½«W¸ñʽµÄCBSÏûϢת»»ÎªGģʽµÄCBSÏûÏ¢ÄÚÈÝ */
ulRet = TAF_CBA_ConvertBmcCbsToGsmCbsFormat(pstBmcDataInd, &ucPageNum, pstCbRawData);
if ( VOS_OK != ulRet )
{
PS_MEM_FREE(WUEPS_PID_TAF, pstCbRawData);
return;
}
/* µ÷ÓÃͳһµÄ´¦Àíº¯ÊýÉϱ¨CBS»òEnvelopeµ½USIM */
TAF_CBA_ReportRcvCbsData(ucPageNum, pstCbRawData);
PS_MEM_FREE(WUEPS_PID_TAF, pstCbRawData);
}
VOS_VOID TAF_CBA_RcvLrrcCbsDataInd(
LRRC_CBS_DATA_IND_STRU *pstBmcDataInd
)
{
/* LRRC·¢ËÍCBSÏûϢʱ²ÉÓÃÓëBMCÏàͬµÄÊý¾Ý½á¹¹, ¹ÊÖ±½Óµ÷ÓÃBMCµÄ´¦Àíº¯Êý´¦Àí */
TAF_CBA_RcvBmcCbsDataInd((BMC_CBS_DATA_IND_STRU*)pstBmcDataInd);
}
VOS_VOID TAF_CBA_RcvAsGsStatusChangeInd(
RR_CBS_GS_STATUS_CHANGE_IND_STRU *pstGsChangeInd
)
{
TAF_CBS_GS_CHG_TYPE_ENUM_UINT8 enTmpGsChgType;
TAF_CBA_NET_RAT_TYPE_ENUM_UINT8 enNetRatType;
TAF_CBA_NETWORK_INFO_STRU stCurrNetworkInfo;
/* ͨ¹ýSenderPid»ñÈ¡½ÓÈëģʽ */
enNetRatType = TAF_CBA_GetRatTypeBySenderPid(pstGsChangeInd->ulSenderPid);
if ( TAF_CBA_NET_RAT_TYPE_BUTT == enNetRatType )
{
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_RcvAsGsStatusChangeInd: ERR enNetRatType.");
return;
}
/* »ñÈ¡GS CHG ÏûÏ¢ÖÐµÄ CHG TYPE, ²¢×ö´íÎó¼ì²é */
enTmpGsChgType = pstGsChangeInd->enGsChgType;
if (enTmpGsChgType >= TAF_CBS_GS_CHG_TYPE_CHG_BUTT)
{
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_RcvAsGsStatusChangeInd: ERR GS CHG TYPE.");
return;
}
/* ¼ì²éGS CHG ÏûÏ¢ÖÐµÄ ÍøÂçÐÅÏ¢ */
if ( (VOS_TRUE != pstGsChangeInd->stCurrNetworkInfo.bitOpPlmnId)
|| (VOS_TRUE != pstGsChangeInd->stCurrNetworkInfo.bitOpSa)
|| (VOS_TRUE != pstGsChangeInd->stCurrNetworkInfo.bitOpCellId) )
{
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_RcvAsGsStatusChangeInd: ERR NetworkInfo.");
return;
}
/* »ñÈ¡µ±Ç°µÄÍøÂçÐÅÏ¢ */
PS_MEM_SET( &stCurrNetworkInfo, 0x00, sizeof(stCurrNetworkInfo) );
stCurrNetworkInfo.enCurrNetRatType = enNetRatType;
stCurrNetworkInfo.stCurPlmn.ulMcc = pstGsChangeInd->stCurrNetworkInfo.stCurPlmn.ulMcc;
stCurrNetworkInfo.stCurPlmn.ulMnc = pstGsChangeInd->stCurrNetworkInfo.stCurPlmn.ulMnc;
stCurrNetworkInfo.usSa = pstGsChangeInd->stCurrNetworkInfo.usSa;
stCurrNetworkInfo.ulCellId = pstGsChangeInd->stCurrNetworkInfo.ulCellId;
/* »ñÈ¡ÉÏ´Î GS_STATUS_CHANGE_IND ÖеÄÍøÂçÐÅÏ¢ */
/* Èç¹ûÊÇÒìϵͳµÄ³¡¾°, ÐèÒªÖØÐÂÅжÏGS CHGµÄÀàÐÍ.
ÒòΪĿǰ:
WÄ£, ÍøÂçÐÅϢȫΪÓÐЧֵ(Ö»ÔÚIDLEºÍP̬Éϱ¨GS CHG IND).
Òìϵͳ¹ý³ÌÖÐ, ÿ´ÎÖØÐ½øÈëWפÁô³É¹¦, W»áÏòNASÉϱ¨GS_CHG_IND(±ä»¯ÀàÐÍÒÀÀµºÍWģȫ¾Ö±äÁ¿ÖеÄÍøÂçÐÅÏ¢µÄ±È½Ï);
GÄ£, ÍøÂçÐÅÏ¢¶¼ÎªÓÐЧֵ.
Òìϵͳ¹ý³ÌÖÐ, ÿ´ÎÖØÐ½øÈëGפÁô³É¹¦, G»áÏòNASÉϱ¨GS_CHG_IND(GÄ£»áÇåÍøÂçÐÅÏ¢µÄÈ«¾Ö±äÁ¿, ËùÒÔ¶¼ÊÇPLMN±ä»¯);
LÄ£, ÍøÂçÐÅÏ¢¶¼ÎªÓÐЧֵ.
Òìϵͳ¹ý³ÌÖÐ, ÿ´ÎÖØÐ½øÈëLפÁô³É¹¦, L»áÏòNASÉϱ¨GS_CHG_IND(±ä»¯ÀàÐͺÍWÀàËÆ)
*/
/* ±£´æ±¾´ÎGS_STATUS_CHANGE_IND ÖеÄÍøÂçÐÅÏ¢ */
TAF_CBA_SetOldNetworkInfo(&stCurrNetworkInfo);
/* δ±ä»¯Ôò²»´¦Àí */
if ( (TAF_CBS_GS_CHG_TYPE_NO_CHG == enTmpGsChgType)
|| (TAF_CBS_GS_CHG_TYPE_CHG_RAT == enTmpGsChgType) )
{
return;
}
#if (FEATURE_ETWS == FEATURE_ON)
/* ɾ³ýÖ÷֪ͨ¼Ç¼ÖеÄÎÞЧÏî */
TAF_CBA_DelInvalidEtwsPrimNtfRecordByGsChgType(enTmpGsChgType, enNetRatType);
#endif
/* ɾ³ýCBS¼Ç¼ÖеÄÎÞЧÏî */
TAF_CBA_DelInvalidCbsRecordByGsChgType(enTmpGsChgType, enNetRatType);
}
TAF_CBA_NET_RAT_TYPE_ENUM_UINT8 TAF_CBA_GetRatTypeBySenderPid(
VOS_UINT32 ulSenderPid
)
{
TAF_CBA_NET_RAT_TYPE_ENUM_UINT8 enNetRatType;
switch (ulSenderPid)
{
case WUEPS_PID_WRR:
case WUEPS_PID_BMC:
enNetRatType = TAF_CBA_NET_RAT_TYPE_WCDMA;
break;
case UEPS_PID_GAS:
enNetRatType = TAF_CBA_NET_RAT_TYPE_GSM;
break;
#if (FEATURE_ON == FEATURE_LTE)
case PS_PID_ERRC:
enNetRatType = TAF_CBA_NET_RAT_TYPE_LTE;
break;
#endif
default:
enNetRatType = TAF_CBA_NET_RAT_TYPE_BUTT;
TAF_ERROR_LOG(WUEPS_PID_TAF, "TAF_CBA_GetRatTypeBySenderPid: ERR ulSenderPid.");
break;
}
return enNetRatType;
}
VOS_UINT32 TAF_CBA_IsCbsEnable(VOS_VOID)
{
TAF_CBA_CBSTATUS_ENUM_UINT8 enCbsStatus;
TAF_CBA_NET_RAT_TYPE_ENUM_UINT8 enNetMode;
/* »ñÈ¡µ±Ç°CBSÏûÏ¢ÊÇ·ñ¼¤»î±êÖ¾ */
enCbsStatus = TAF_CBA_GetCbsStatus();
enNetMode = TAF_CBA_GetNetRatType();
/* ±ØÐëÂú×ãNVÖиÃģʽCBS¼¤»îͬʱ¸Ãģʽºê¿ª¹ØÒÑ´ò¿ª²ÅĬÈÏCBS¼¤»î */
#if (FEATURE_ON == FEATURE_WCBS)
if ( ((TAF_CBA_CBSTATUS_W_ENABLE == enCbsStatus) || (TAF_CBA_CBSTATUS_WG_ENABLE == enCbsStatus))
&& (TAF_CBA_NET_RAT_TYPE_WCDMA == enNetMode) )
{
return VOS_TRUE;
}
#endif
#if (FEATURE_ON == FEATURE_GCBS)
if ( ((TAF_CBA_CBSTATUS_G_ENABLE == enCbsStatus) || (TAF_CBA_CBSTATUS_WG_ENABLE == enCbsStatus))
&& (TAF_CBA_NET_RAT_TYPE_GSM == enNetMode) )
{
return VOS_TRUE;
}
#endif
#if (FEATURE_ON == FEATURE_LTE)
if (TAF_CBA_NET_RAT_TYPE_LTE == enNetMode)
{
return VOS_TRUE;
}
#endif
return VOS_FALSE;
}
#if (FEATURE_ETWS == FEATURE_ON)
VOS_UINT32 TAF_CBA_IsCbsMsgIdValid_ETWS(
VOS_UINT16 usMsgId
)
{
VOS_UINT32 ulIsInCbsActiveList;
VOS_UINT32 ulIsInEtwsList;
ulIsInCbsActiveList = TAF_CBA_IsMsgIdInCbsActiveList(usMsgId);
/* CBS¿ªÆô£¬ETWS¿ªÆôµÄÇé¿ö, °´Óû§ÉèÖõ碌îÁбíÅжÏ;
CBS¿ªÆô£¬ETWS¹Ø±Õ, °´Óû§ÉèÖõ碌îÁбíÅжÏ, ETWSÒ²µ±×÷ÆÕͨCBSÉϱ¨ */
if (VOS_TRUE == TAF_CBA_IsCbsEnable())
{
if (VOS_TRUE == ulIsInCbsActiveList)
{
return VOS_TRUE;
}
return VOS_FALSE;
}
ulIsInEtwsList = TAF_CBA_IsMsgIdInEtwsMsgIdList(usMsgId);
/* CBS¹Ø±Õ£¬ETWS¿ªÆôµÄÇé¿ö£¬Ðè½ö°üº¬¼¤»îÁбíÖÐ ETWSÏà¹ØµÄMSG ID */
if (VOS_TRUE == TAF_CBA_GetEtwsEnableFlg())
{
if ( (VOS_TRUE == ulIsInCbsActiveList)
&& (VOS_TRUE == ulIsInEtwsList) )
{
return VOS_TRUE;
}
return VOS_FALSE;
}
/* ETWS¹Ø±Õ£¬CBS¹Ø±Õ */
return VOS_FALSE;
}
#endif
VOS_UINT32 TAF_CBA_IsCbsMsgIdValid(
VOS_UINT16 usMsgId
)
{
#if (FEATURE_ETWS == FEATURE_ON)
return TAF_CBA_IsCbsMsgIdValid_ETWS(usMsgId);
#else
/* ÅжÏCBSÏûÏ¢IDÊÇ·ñÔÚ¼¤»îÁбíÖÐ */
return TAF_CBA_IsMsgIdInCbsActiveList(usMsgId);
#endif
}
/*****************************************************************************
º¯ Êý Ãû : TAF_CBA_GetGsmCbsPageLen
¹¦ÄÜÃèÊö : »ñÈ¡GASϹ㲥¶ÌÏûÏ¢Ò»Ò³µÄʵ¼Ê³¤¶È
ÊäÈë²ÎÊý : pstCbTpduData - °´GSM¸ñʽ´æ·ÅµÄ¹ã²¥¶ÌÏûÏ¢Ò³
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ : ¹ã²¥¶ÌÏûÏ¢Ò»Ò³µÄʵ¼Ê³¤¶È
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2006Äê12ÔÂ20ÈÕ
×÷ Õß : ¸µÓ³¾ý 62575
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
VOS_UINT8 TAF_CBA_GetGsmCbsPageLen(
GAS_CBS_PAGE_DATA_STRU *pstCbPageData
)
{
VOS_UINT32 ulPos;
VOS_UINT8 ucPageLen;
VOS_UINT32 ulCbpageIdx;
/* 3GPP 23.041 9.4.1.2½Ú:
Octet Number(s) Field
1-2 Serial Number
3-4 Message Identifier
5 Data Coding Scheme
6 Page Parameter
7-88 Content of Message
*/
ucPageLen = TAF_CBA_MAX_CBPAGE_LEN;
for (ulCbpageIdx = 0; ulCbpageIdx < TAF_CBA_MAX_CBPAGE_LEN; ulCbpageIdx++)
{
ulPos = (TAF_CBA_MAX_CBPAGE_LEN - ulCbpageIdx) - 1;
if (TAF_CBA_PADDING_OCTET != pstCbPageData->aucData[ulPos])
{
break;
}
ucPageLen--;
}
return ucPageLen;
}
VOS_VOID TAF_CBA_BuildGsmCbsRecord(
MN_MSG_CBGSMPAGE_STRU *pstGsmPage,
TAF_CBS_NETWORK_INFO_STRU *pstCampPlmnInfo,
TAF_CBA_RECORD_STRU *pstNewRecord
)
{
VOS_UINT8 ucTotalPage;
VOS_UINT8 ucPageIndex;
ucTotalPage = pstGsmPage->Pagesbit4;
ucPageIndex = pstGsmPage->Pagebit4;
/* Èç¹û ucTotalPage»òucPageNumberÖÐÒ»¸öΪ0,Ôòµ±×÷ 0001 0001 ,²Î¼ûÐÒé23041 9.4.1.2.4 */
if ( ( 0x00 == ucTotalPage )
|| ( 0x00 == ucPageIndex ) )
{
ucTotalPage = 0x01;
ucPageIndex = 0x01;
}
PS_MEM_SET(pstNewRecord, 0x00, sizeof(TAF_CBA_RECORD_STRU));
pstNewRecord->enNetMode = TAF_CBA_NET_RAT_TYPE_GSM;
pstNewRecord->ucTotalPage = ucTotalPage;
pstNewRecord->usMsgID = TAF_CBA_BuildCbsMsgId(pstGsmPage->ucMIdHigh, pstGsmPage->ucMIdLow);
pstNewRecord->usSN = TAF_CBA_BuildCbsSN(pstGsmPage->ucSnHigh, pstGsmPage->ucSnLow);
pstNewRecord->stPlmn.ulMcc = pstCampPlmnInfo->stCurPlmn.ulMcc;
pstNewRecord->stPlmn.ulMnc = pstCampPlmnInfo->stCurPlmn.ulMnc;
pstNewRecord->ulRcvTimeTick = VOS_GetTick();
/*lint -e701*/
/* ¼ÆËãbitmap ,´Ë´¦ucPageIndex×îСΪ1,ËùÒÔÐèÒª×óÒÆ(ucPageIndex - 1) */
pstNewRecord->usPageBitmap = TAF_CBA_BuildGsmCbsPageBitmap(ucPageIndex);
/*lint +e701*/
/* ÆÕͨCBSûÓÐÖØ¸´¼ì²âʱЧҪÇ󣬳ÌÐòʵÏÖÖÐÉèΪ0 ±íʾÓÀ¾ÃÓÐЧ */
pstNewRecord->ulDupDetcTimeLen = 0;
}
VOS_UINT32 TAF_CBA_IsDupGsmCbsRecord(
TAF_CBA_RECORD_STRU *pstNewRecord
)
{
TAF_CBA_RECORD_STRU *pstRcvCbsList;
VOS_UINT16 usRcvCbsNum;
VOS_UINT16 ulIndex;
VOS_UINT32 ulSameGsCode;
VOS_UINT32 ulSameMsgCode;
VOS_UINT32 ulSameUpdateNumber;
if ( VOS_TRUE != TAF_CBA_IsNeedDupDetectCbs((pstNewRecord->usMsgID)) )
{
/* ²»ÐèÒª×öÖØ¸´¹ýÂËÔòÈÏΪ ²»ÊÇÖØ¸´µÄ¼Ç¼Ïî */
return VOS_FALSE;
}
pstRcvCbsList = TAF_CBA_GetRcvCbsList();
usRcvCbsNum = TAF_CBA_GetRcvCbsNum();
for ( ulIndex = 0; ulIndex < usRcvCbsNum; ulIndex++ )
{
/* ÅжϽÓÈëģʽ */
if (pstNewRecord->enNetMode != pstRcvCbsList[ulIndex].enNetMode)
{
continue;
}
/* ÅÐ¶Ï MSG ID */
if (pstNewRecord->usMsgID != pstRcvCbsList[ulIndex].usMsgID)
{
continue;
}
ulSameGsCode = TAF_CBA_IsSameGsCode(pstNewRecord->usSN, pstRcvCbsList[ulIndex].usSN);
ulSameMsgCode = TAF_CBA_IsSameMsgCode(pstNewRecord->usSN, pstRcvCbsList[ulIndex].usSN);
ulSameUpdateNumber = TAF_CBA_IsSameUpdateNum(pstNewRecord->usSN, pstRcvCbsList[ulIndex].usSN);
if ( !((VOS_TRUE == ulSameGsCode)
&& (VOS_TRUE == ulSameMsgCode)
&& (VOS_TRUE == ulSameUpdateNumber)))
{
continue;
}
/* ¸öÈ˸оõ±ê¸Ë³öÏÖ³öÏÖÒÔÏÂÇé¿ö²»·ûºÏÐÒé: GS,MSG ID,MSG CODEÏàͬʱ£¬ÏÈÊÕµ½update numberΪ1£¬
×ÜÒ³ÊýΪ2£¬indexΪ1µÄCBSÏûÏ¢£¬ÔÙÊÕµ½update numberΪ0£¬×ÜÒ³ÊýΪ2£¬indexΪ2µÄCBSÏûϢʱ£¬
¾¹È»Éϱ¨¡£¸öÈËÈÏΪ²»·ûºÏÐÒ飬¹Ê´Ë´¦Ã»°´±ê¸ËÐ޸ġ£
*/
if ( pstNewRecord->usSN == pstRcvCbsList[ulIndex].usSN)
{
/* ±È½Ï Total Page */
if (pstNewRecord->ucTotalPage != pstRcvCbsList[ulIndex].ucTotalPage)
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmDupRecordInfo(TAF_CBA_OM_MSG_DUP_CBS_RECORD,
&(pstRcvCbsList[ulIndex]));
/* ÒѽÓÊÕ¹ýÔòÊÇÖØ¸´ÏûÏ¢Ò³ */
return VOS_TRUE;
}
/* ÅжϸÃÒ³ÊÇ·ñÒѽÓÊÕ¹ý */
if (0 != (pstNewRecord->usPageBitmap & pstRcvCbsList[ulIndex].usPageBitmap))
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmDupRecordInfo(TAF_CBA_OM_MSG_DUP_CBS_RECORD,
&(pstRcvCbsList[ulIndex]));
/* ÒѽÓÊÕ¹ýÔòÊÇÖØ¸´ÏûÏ¢Ò³ */
return VOS_TRUE;
}
}
else
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmDupRecordInfo(TAF_CBA_OM_MSG_DUP_CBS_RECORD,
&(pstRcvCbsList[ulIndex]));
/* ÒѽÓÊÕ¹ýÔòÊÇÖØ¸´ÏûÏ¢Ò³ */
return VOS_TRUE;
}
}
return VOS_FALSE;
}
VOS_VOID TAF_CBA_AppendCbsRecord(
TAF_CBA_RECORD_STRU *pstAppendRecord
)
{
TAF_CBA_RECORD_STRU *pstRcvCbsList;
VOS_UINT16 usRcvCbsNum;
VOS_UINT16 usAppendInx;
TAF_CBA_OM_SAVE_TYPE_ENUM_UINT8 enSaveType;
pstRcvCbsList = TAF_CBA_GetRcvCbsList();
usRcvCbsNum = TAF_CBA_GetRcvCbsNum();
usAppendInx = 0;
/* ¼Ç¼±íÖв»´æÔÚºÍмǼµÄMSG IDºÍMSG CODEÏàͬµÄ¼Ç¼Ïî, ÔòÐÂÔö¼Ç¼Ïî */
if ( TAF_CBA_MAX_CBS_RECORD_NUM == usRcvCbsNum )
{
/* ÁбíÒÑÂúÔò»ñÈ¡×îÔçµÄ¼Ç¼ÏîµÄindex, ¸²¸ÇÖ® */
usAppendInx = TAF_CBA_GetEarliestCbsRecordInx();
/* ×îÔç¼Ç¼µÄ¿Éά¿É²âÐÅÏ¢ */
TAF_CBA_SndOmDeledRecordInfo(TAF_CBA_OM_MSG_DEL_DEL_CBS_RECORD,
TAF_CBA_OM_DEL_REASON_LIST_FULL,
&pstRcvCbsList[usAppendInx]);
/* ±£´æ¼Ç¼ */
pstRcvCbsList[usAppendInx] = (*pstAppendRecord);
enSaveType = TAF_CBA_OM_SAVE_TYPE_RECORD_FULL;
}
else
{
/* ÁбíδÂú£¬ÔòÔÚ×îºóÔö¼ÓÒ»¸ö¼Ç¼ */
usAppendInx = usRcvCbsNum;
/* ±£´æ¼Ç¼ */
pstRcvCbsList[usAppendInx] = (*pstAppendRecord);
/* ¸üмǼ¸öÊý */
usRcvCbsNum++;
TAF_CBA_SetRcvCbsNum(usRcvCbsNum);
enSaveType = TAF_CBA_OM_SAVE_TYPE_APPEND_RECORD;
}
/* ¿Éά¿É²â */
TAF_CBS_SndOmSavedRecordInfo(TAF_CBA_OM_MSG_SAVE_CBS_RECORD,
enSaveType,
pstAppendRecord,
usRcvCbsNum);
}
VOS_VOID TAF_CBA_SaveGsmCbsRecord(
TAF_CBA_RECORD_STRU *pstNewRecord
)
{
VOS_UINT32 ulSameRecordInx;
TAF_CBA_RECORD_STRU *pstRcvCbsList;
VOS_UINT32 ulSameGsCode;
VOS_UINT32 ulSameUpdateNum;
TAF_CBA_OM_SAVE_TYPE_ENUM_UINT8 enSaveType;
pstRcvCbsList = TAF_CBA_GetRcvCbsList();
ulSameRecordInx = 0;
/* ¼Ç¼±íÖв»´æÔÚºÍмǼµÄMSG IDºÍMSG CODEÏàͬµÄ¼Ç¼Ïî, ÔòÐÂÔö¼Ç¼Ïî */
if ( VOS_TRUE != TAF_CBA_GetCbsRecordInxByMsgIdCode(pstNewRecord, &ulSameRecordInx) )
{
TAF_CBA_AppendCbsRecord(pstNewRecord);
return;
}
/* ¼Ç¼±íÖдæÔÚºÍмǼµÄMSG IDºÍMSG CODEÏàͬµÄ¼Ç¼Ïî, Ôò¸üÐÂÆä PageBitmap »ò ¸²¸ÇԼǼ */
ulSameGsCode = TAF_CBA_IsSameGsCode(pstNewRecord->usSN, pstRcvCbsList[ulSameRecordInx].usSN);
ulSameUpdateNum = TAF_CBA_IsSameUpdateNum(pstNewRecord->usSN, pstRcvCbsList[ulSameRecordInx].usSN);
/* ÅжÏGS£¬UpdaeNumberºÍ×ÜÒ³ÊýÕâÈý¸ö×Ö¶ÎÊÇ·ñÈ«Ïàͬ, È«ÏàͬÔò¸üÐÂÆä PageBitMap, ·ñÔò¸²¸ÇԼǼÏî */
if ( (VOS_TRUE == ulSameGsCode)
&& (VOS_TRUE == ulSameUpdateNum)
&& (pstNewRecord->ucTotalPage == pstRcvCbsList[ulSameRecordInx].ucTotalPage) )
{
/* ½ö¸üРPageBitMap */
pstRcvCbsList[ulSameRecordInx].usPageBitmap |= (pstNewRecord->usPageBitmap);
enSaveType = TAF_CBA_OM_SAVE_TYPE_UPDATE_RECORD_BITMAP;
}
else
{
/* ±£´æ ¸²¸Ç */
pstRcvCbsList[ulSameRecordInx] = (*pstNewRecord);
enSaveType = TAF_CBA_OM_SAVE_TYPE_REPLACE_RECORD;
}
/* ¿Éά¿É²â */
TAF_CBS_SndOmSavedRecordInfo(TAF_CBA_OM_MSG_SAVE_CBS_RECORD,
enSaveType,
pstNewRecord,
TAF_CBA_GetRcvCbsNum());
}
VOS_UINT32 TAF_CBA_GetCbsRecordInxByMsgIdCode(
TAF_CBA_RECORD_STRU *pstRecord,
VOS_UINT32 *pulIndex
)
{
TAF_CBA_RECORD_STRU *pstListAddr;
VOS_UINT32 usCbsRecordNum;
VOS_UINT32 ulInx;
pstListAddr = TAF_CBA_GetRcvCbsList();
usCbsRecordNum = TAF_CBA_GetRcvCbsNum();
for ( ulInx = 0; ulInx < usCbsRecordNum; ulInx++ )
{
/* ÅжϽÓÈëģʽ */
if (pstRecord->enNetMode != pstListAddr[ulInx].enNetMode)
{
continue;
}
/* ÅжÏPLMN */
if ( (pstRecord->stPlmn.ulMcc != pstListAddr[ulInx].stPlmn.ulMcc)
|| (pstRecord->stPlmn.ulMnc != pstListAddr[ulInx].stPlmn.ulMnc) )
{
continue;
}
/* ÅÐ¶Ï MSG ID ºÍ MSG CODE */
if ( (VOS_TRUE == TAF_CBA_IsSameMsgCode(pstRecord->usSN, pstListAddr[ulInx].usSN))
&& (pstRecord->usMsgID == pstListAddr[ulInx].usMsgID) )
{
*pulIndex = ulInx;
return VOS_TRUE;
}
}
return VOS_FALSE;
}
VOS_UINT16 TAF_CBA_GetEarliestCbsRecordInx(VOS_VOID)
{
TAF_CBA_RECORD_STRU *pstRecordList;
VOS_UINT16 usEarliestInx;
VOS_UINT16 usIndex;
VOS_UINT32 ulEarliestTick;
pstRecordList = TAF_CBA_GetRcvCbsList();
usEarliestInx = 0;
ulEarliestTick = pstRecordList[0].ulRcvTimeTick;
for ( usIndex = 1; usIndex < TAF_CBA_GetRcvCbsNum(); usIndex++ )
{
if ( pstRecordList[usIndex].ulRcvTimeTick < ulEarliestTick )
{
usEarliestInx = usIndex;
ulEarliestTick = pstRecordList[usIndex].ulRcvTimeTick;
}
}
return usEarliestInx;
}
VOS_VOID TAF_CBA_BuildBmcCbsRecord(
BMC_CBS_DATA_IND_STRU *pstBmcDataInd,
TAF_CBA_RECORD_STRU *pstNewRecord
)
{
TAF_CBA_NET_RAT_TYPE_ENUM_UINT8 enRatType;
enRatType = TAF_CBA_GetRatTypeBySenderPid(pstBmcDataInd->ulSenderPid);
PS_MEM_SET(pstNewRecord, 0x00, sizeof(TAF_CBA_RECORD_STRU));
pstNewRecord->enNetMode = enRatType;
pstNewRecord->usMsgID = pstBmcDataInd->usCBMID;
pstNewRecord->usSN = pstBmcDataInd->usSerialNum;
pstNewRecord->stPlmn.ulMcc = pstBmcDataInd->stCurrNetworkInfo.stCurPlmn.ulMcc;
pstNewRecord->stPlmn.ulMnc = pstBmcDataInd->stCurrNetworkInfo.stCurPlmn.ulMnc;
pstNewRecord->ulRcvTimeTick = VOS_GetTick();
#if (FEATURE_ETWS == FEATURE_ON)
pstNewRecord->ulDupDetcTimeLen = TAF_CBA_GetCbsDupDetcTimeLen(&(pstNewRecord->stPlmn),
pstNewRecord->usMsgID);
#else
/* ÆÕͨCBSûÓÐÖØ¸´¼ì²âʱЧҪÇ󣬳ÌÐòʵÏÖÖÐÉèΪ0 ±íʾÓÀ¾ÃÓÐЧ */
pstNewRecord->ulDupDetcTimeLen = 0;
#endif
}
#if (FEATURE_ON == FEATURE_ETWS)
VOS_UINT32 TAF_CBA_IsCbsRecordSamePlmn(
TAF_CBA_RECORD_STRU *pstSrcRecord,
TAF_CBA_RECORD_STRU *pstDstRecord
)
{
/* ÅжÏPLMN */
if ( (pstSrcRecord->stPlmn.ulMcc != pstDstRecord->stPlmn.ulMcc)
|| (pstSrcRecord->stPlmn.ulMnc != pstDstRecord->stPlmn.ulMnc) )
{
return VOS_FALSE;
}
return VOS_TRUE;
}
#endif
VOS_UINT32 TAF_CBA_IsDupBmcCbsRecord(
TAF_CBA_RECORD_STRU *pstRecord
)
{
TAF_CBA_RECORD_STRU *pstCbsListAddr;
VOS_UINT16 usCbsRecordNum;
VOS_UINT16 usInx;
VOS_UINT32 ulSameGsCode;
VOS_UINT32 ulSameMsgCode;
VOS_UINT32 ulSameUpdateNumber;
if ( VOS_TRUE != TAF_CBA_IsNeedDupDetectCbs(pstRecord->usMsgID) )
{
/* ²»ÐèÒª×öÖØ¸´¹ýÂËÔòÈÏΪ ²»ÊÇÖØ¸´µÄ¼Ç¼Ïî */
return VOS_FALSE;
}
pstCbsListAddr = TAF_CBA_GetRcvCbsList();
usCbsRecordNum = TAF_CBA_GetRcvCbsNum();
for ( usInx = 0; usInx < usCbsRecordNum; usInx++ )
{
/* ÅжϽÓÈëģʽ */
if (pstRecord->enNetMode != pstCbsListAddr[usInx].enNetMode)
{
continue;
}
#if (FEATURE_ON == FEATURE_ETWS)
/* DoCoMo¶ÔETWSµÄÔöÇ¿µÄÖØ¸´¼ì²â¶¨ÖÆÌØÐÔ¼¤»îʱ, ÐèÒªÅжÏPLMN */
if (VOS_TRUE == TAF_CBA_GetEnhDupDetcFlg())
{
if ( VOS_TRUE != TAF_CBA_IsCbsRecordSamePlmn(pstRecord, &(pstCbsListAddr[usInx]) ))
{
continue;
}
}
#endif
/* ÅÐ¶Ï MSG ID */
if (pstRecord->usMsgID != pstCbsListAddr[usInx].usMsgID)
{
continue;
}
/* ±È½ÏÕû¸öSN, ĿǰÎÞÐè·Ö±ðÅÐ¶Ï MSG CODE, GS ºÍ UPDATE NUMBER */
ulSameGsCode = TAF_CBA_IsSameGsCode(pstRecord->usSN, pstCbsListAddr[usInx].usSN);
ulSameMsgCode = TAF_CBA_IsSameMsgCode(pstRecord->usSN, pstCbsListAddr[usInx].usSN);
ulSameUpdateNumber = TAF_CBA_IsSameUpdateNum(pstRecord->usSN, pstCbsListAddr[usInx].usSN);
if ( ((VOS_TRUE == ulSameGsCode)
&& (VOS_TRUE == ulSameMsgCode)
&& (VOS_TRUE == ulSameUpdateNumber)))
{
/* ¿Éά¿É²â */
TAF_CBA_SndOmDupRecordInfo(TAF_CBA_OM_MSG_DUP_CBS_RECORD,
&(pstCbsListAddr[usInx]));
return VOS_TRUE;
}
}
return VOS_FALSE;
}
VOS_VOID TAF_CBA_SaveBmcCbsRecord (
TAF_CBA_RECORD_STRU *pstNewRecord
)
{
TAF_CBA_RECORD_STRU *pstRcvCbsList;
VOS_UINT16 usRcvCbsNum;
VOS_UINT32 ulSameMsgIdCodeInx;
pstRcvCbsList = TAF_CBA_GetRcvCbsList();
usRcvCbsNum = TAF_CBA_GetRcvCbsNum();
ulSameMsgIdCodeInx = 0;
usRcvCbsNum = 0;
/* ¼Ç¼±íÖв»´æÔÚºÍмǼµÄMSG IDºÍMSG CODEÏàͬµÄ¼Ç¼Ïî, ÔòÐÂÔöÒ»¸ö¼Ç¼Ïî */
if ( VOS_TRUE != TAF_CBA_GetCbsRecordInxByMsgIdCode(pstNewRecord, &ulSameMsgIdCodeInx) )
{
TAF_CBA_AppendCbsRecord(pstNewRecord);
return;
}
/* ¼Ç¼±íÖдæÔÚºÍмǼµÄMSG IDºÍMSG CODEÏàͬµÄ¼Ç¼Ïî, Ôò¸²¸ÇԼǼÏî */
pstRcvCbsList[ulSameMsgIdCodeInx] = (*pstNewRecord);
/* ¿Éά¿É²â */
TAF_CBS_SndOmSavedRecordInfo(TAF_CBA_OM_MSG_SAVE_CBS_RECORD,
TAF_CBA_OM_SAVE_TYPE_REPLACE_RECORD,
pstNewRecord,
usRcvCbsNum);
}
/*lint -e429 -e830*/
VOS_UINT32 TAF_CBA_ReportRcvCbsData(
VOS_UINT8 ucPageNum,
MN_MSG_CBRAW_TS_DATA_STRU *pstPageData
)
{
VOS_UINT16 usMsgId;
VOS_UINT32 ulPageIdx;
MN_MSG_CBGSMPAGE_STRU *pstGsmPage;
VOS_UINT32 ulNeedDownLoad;
for ( ulPageIdx = 0 ; ulPageIdx < ucPageNum ; ulPageIdx++ )
{
pstGsmPage = (MN_MSG_CBGSMPAGE_STRU *)(pstPageData[ulPageIdx].aucData);
usMsgId = TAF_CBA_BuildCbsMsgId(pstGsmPage->ucMIdHigh, pstGsmPage->ucMIdLow);
ulNeedDownLoad = TAF_CBA_IsNeedDownloadToUsim(usMsgId);
if ( VOS_TRUE == ulNeedDownLoad )
{
/* Ò»Ò³Ò»Ò³envelop downloadµ½UISM */
TAF_CBA_SndUsimCbMsg(WUEPS_PID_TAF, 0, pstPageData+ulPageIdx);
}
else
{
/* Ò»Ò³Ò»Ò³Éϱ¨ */
TAF_CBA_SndAtRcvCbmMsg(pstPageData+ulPageIdx);
}
}
return VOS_OK;
}
/*lint +e429 +e830*/
VOS_UINT32 TAF_CBA_IsNeedDownloadToUsim(
VOS_UINT16 usMsgId
)
{
VOS_UINT32 ulIsDownLoad;
TAF_CBA_USIM_EFCBMID_FILE_INFO_STRU *pstEfCbmidFileInfo;
TAF_CBA_CBMI_DOWNLOAD_LIST_STRU *pstCbmidList;
pstEfCbmidFileInfo = TAF_CBA_GetEfCbmidInfo();
pstCbmidList = TAF_CBA_GetCbmiDownloadList();
/* ÎÞCBMIDÎļþʱ֮¼ä·µ»Ø²»ÐèÒªDownLoad */
if ( ( VOS_FALSE == pstEfCbmidFileInfo->ucEfCbmidExistFlg)
|| (0 == pstEfCbmidFileInfo->usEfCbmidFileLen)
|| (0 == pstCbmidList->usCbmidNum) )
{
return VOS_FALSE;
}
ulIsDownLoad = TAF_CBA_IsMsgIdInCbmid(usMsgId, pstCbmidList);
return ulIsDownLoad;
}
/*****************************************************************************
º¯ Êý Ãû : TAF_CBA_IsMsgIdInCbmid
¹¦ÄÜÃèÊö : ¼ì²éÏûÏ¢IDÊÇ·ñΪDOWNLOADµÄÏûÏ¢ID
ÊäÈë²ÎÊý : usMsgId - Óû§ÏûÏ¢ID
pstCbmidList - USIMÖ¸¶¨µÄDOWNLOADµÄÏûÏ¢IDÁбí
Êä³ö²ÎÊý : ÎÞ
·µ »Ø Öµ : VOS_TRUE ÏûÏ¢IDÔÚDOWNLOADµÄÏûÏ¢IDÁбíÖÐ,·ñÔò,²»ÔÚDOWNLOADµÄÏûÏ¢IDÁбíÖÐ
µ÷Óú¯Êý :
±»µ÷º¯Êý :
ÐÞ¸ÄÀúÊ· :
1.ÈÕ ÆÚ : 2008Äê2ÔÂ17ÈÕ
×÷ Õß : ¸µÓ³¾ý 62575
ÐÞ¸ÄÄÚÈÝ : ÐÂÉú³Éº¯Êý
*****************************************************************************/
VOS_UINT32 TAF_CBA_IsMsgIdInCbmid(
VOS_UINT16 usMsgId,
TAF_CBA_CBMI_DOWNLOAD_LIST_STRU *pstCbmidList
)
{
VOS_UINT32 ulLoop;
for ( ulLoop = 0; ulLoop < pstCbmidList->usCbmidNum; ulLoop++ )
{
if (usMsgId == pstCbmidList->ausMsgId[ulLoop])
{
return VOS_TRUE;
}
}
return VOS_FALSE;
}
#if (FEATURE_ON == FEATURE_ETWS)
VOS_UINT32 TAF_CBA_GetCbsDupDetcTimeLen(
TAF_CBA_PLMN_ID_STRU *pstPlmn,
VOS_UINT16 usMsgId
)
{
TAF_CBA_ENH_DUP_DETECT_TIME_LEN_CFG_STRU *pstEnhDupDetcTimeLenCfg;
VOS_UINT8 ucEnhDupDetcFlg;
VOS_UINT32 i;
ucEnhDupDetcFlg = TAF_CBA_GetEnhDupDetcFlg();
pstEnhDupDetcTimeLenCfg = TAF_CBA_GetEnhDupDetcTimeLenCfg();
/* ÔöÇ¿µÄÖØ¸´¼ì²â¶¨ÖÆÌØÐÔ먦ÆôʱµÄȡֵ, ETWSÏûÏ¢ÓÐÖØ¸´¼ì²âʱЧҪÇó, ÆÕͨCBSÏûϢûÓÐʱЧҪÇó */
if (VOS_TRUE != ucEnhDupDetcFlg)
{
if ( VOS_TRUE == TAF_CBA_IsMsgIdInEtwsMsgIdList(usMsgId))
{
return TAF_CBA_GetNormalDupDetcTimeLen();
}
/* ÆÕͨCBSûÓÐÖØ¸´¼ì²âʱЧҪÇ󣬳ÌÐòʵÏÖÖÐÉèΪ0 ±íʾÓÀ¾ÃÓÐЧ */
return 0;
}
/* DoCoMo ÔöÇ¿µÄÖØ¸´¼ì²â¶¨ÖÆÌØÐÔ¿ªÆôʱµÄȡֵ:
1. ETWSºÍÆÕͨCBSÏûÏ¢µÄÖØ¸´¼ì²âʱЧҪÇóÏàͬ£¬
2. µ±Ç°PLMNµÄMCCÔÚ¶¨ÖÆMCC·¶Î§ÀàºÍ¶¨ÖÆMCCÍâȡֵ²»Í¬ */
for ( i = 0; i < TAF_CBA_MAX_ETWS_DUP_DETECT_SPEC_MCC_NUM; i++ )
{
if (pstPlmn->ulMcc == pstEnhDupDetcTimeLenCfg->aulSpecMcc[i])
{
return pstEnhDupDetcTimeLenCfg->ulSpecMccTimeLen;
}
}
return pstEnhDupDetcTimeLenCfg->ulOtherMccTimeLen;
}
#endif
VOS_UINT32 TAF_CBA_IsNeedDupDetectCbs(
VOS_UINT16 usMsgID
)
{
TAF_CBA_DUP_DETECT_CFG_ENUM_UINT8 enDupDetectCfg;
enDupDetectCfg = TAF_CBA_GetDupDetectCfg();
if (TAF_CBA_DUP_DETECT_CFG_ALL_ENABLE == enDupDetectCfg)
{
return VOS_TRUE;
}
/* ÅжÏÏÂÔØµ½USIMµÄCBSÊÇ·ñÐèÒª¹ýÂË */
if ( (VOS_TRUE == TAF_CBA_IsNeedDownloadToUsim(usMsgID))
&& (TAF_CBA_DUP_DETECT_CFG_ONLY_DOWNLOAD_TYPE_ENABLE == enDupDetectCfg) )
{
return VOS_TRUE;
}
return VOS_FALSE;
}
/*lint -restore */
#endif /* ((FEATURE_ON == FEATURE_GCBS) || (FEATURE_ON == FEATURE_WCBS)) */
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
| wbrambley/Grace-kernel | drivers/vendor/hisi/modem/taf/gu/src/ccore/src/CBA/Src/TafCbaProcAs.c | C | gpl-2.0 | 43,145 |
#
# Copyright 2006-2009 Zuza Software Foundation
#
# This file is part of the Translate Toolkit.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, see <http://www.gnu.org/licenses/>.
"""XLIFF classes specifically suited for handling the PO representation in
XLIFF.
This way the API supports plurals as if it was a PO file, for example.
"""
import re
from lxml import etree
from translate.misc.multistring import multistring
from translate.misc.xml_helpers import setXMLspace
from translate.storage import base, lisa, poheader, xliff
from translate.storage.placeables import general
def hasplurals(thing):
if not isinstance(thing, multistring):
return False
return len(thing.strings) > 1
class PoXliffUnit(xliff.xliffunit):
"""A class to specifically handle the plural units created from a po file."""
rich_parsers = general.parsers
def __init__(self, source=None, empty=False, **kwargs):
self._rich_source = None
self._rich_target = None
self._state_n = 0
self.units = []
if empty:
return
if not hasplurals(source):
super().__init__(source)
return
self.xmlelement = etree.Element(self.namespaced("group"))
self.xmlelement.set("restype", "x-gettext-plurals")
self.source = source
def __eq__(self, other):
if isinstance(other, PoXliffUnit):
if len(self.units) != len(other.units):
return False
if not super().__eq__(other):
return False
for i in range(len(self.units) - 1):
if not self.units[i + 1] == other.units[i + 1]:
return False
return True
if len(self.units) <= 1:
if isinstance(other, lisa.LISAunit):
return super().__eq__(other)
else:
return self.source == other.source and self.target == other.target
return False
# XXX: We don't return language nodes correctly at the moment
# def getlanguageNodes(self):
# if not self.hasplural():
# return super().getlanguageNodes()
# else:
# return self.units[0].getlanguageNodes()
@property
def source(self):
if not self.hasplural():
return super().source
return multistring([unit.source for unit in self.units])
@source.setter
def source(self, source):
self.setsource(source, sourcelang="en")
def setsource(self, source, sourcelang="en"):
# TODO: consider changing from plural to singular, etc.
self._rich_source = None
if not hasplurals(source):
super().setsource(source, sourcelang)
else:
target = self.target
for unit in self.units:
try:
self.xmlelement.remove(unit.xmlelement)
except ValueError:
pass
self.units = []
for s in source.strings:
newunit = xliff.xliffunit(s)
# newunit.namespace = self.namespace #XXX?necessary?
self.units.append(newunit)
self.xmlelement.append(newunit.xmlelement)
self.target = target
# We don't support any rich strings yet
multistring_to_rich = base.TranslationUnit.multistring_to_rich
rich_to_multistring = base.TranslationUnit.rich_to_multistring
rich_source = base.TranslationUnit.rich_source
rich_target = base.TranslationUnit.rich_target
def gettarget(self, lang=None):
if self.hasplural():
strings = [unit.target for unit in self.units]
if strings:
return multistring(strings)
else:
return None
else:
return super().gettarget(lang)
def settarget(self, target, lang="xx", append=False):
self._rich_target = None
if self.target == target:
return
if not self.hasplural():
super().settarget(target, lang, append)
return
if not isinstance(target, multistring):
target = multistring(target)
source = self.source
sourcel = len(source.strings)
targetl = len(target.strings)
if sourcel < targetl:
sources = source.strings + [source.strings[-1]] * (targetl - sourcel)
targets = target.strings
id = self.getid()
self.source = multistring(sources)
self.setid(id)
elif targetl < sourcel:
targets = target.strings + [""] * (sourcel - targetl)
else:
targets = target.strings
for i in range(len(self.units)):
self.units[i].target = targets[i]
def addnote(self, text, origin=None, position="append"):
"""Add a note specifically in a "note" tag"""
note = etree.SubElement(self.xmlelement, self.namespaced("note"))
note.text = text
if origin:
note.set("from", origin)
for unit in self.units[1:]:
unit.addnote(text, origin)
def getnotes(self, origin=None):
# NOTE: We support both <context> and <note> tags in xliff files for comments
if origin == "translator":
notes = super().getnotes("translator")
trancomments = self.gettranslatorcomments()
if notes == trancomments or trancomments.find(notes) >= 0:
notes = ""
elif notes.find(trancomments) >= 0:
trancomments = notes
notes = ""
return trancomments + notes
elif origin in ["programmer", "developer", "source code"]:
devcomments = super().getnotes("developer")
autocomments = self.getautomaticcomments()
if devcomments == autocomments or autocomments.find(devcomments) >= 0:
devcomments = ""
elif devcomments.find(autocomments) >= 0:
autocomments = devcomments
devcomments = ""
return autocomments
else:
return super().getnotes(origin)
def markfuzzy(self, value=True):
super().markfuzzy(value)
for unit in self.units[1:]:
unit.markfuzzy(value)
def marktranslated(self):
super().marktranslated()
for unit in self.units[1:]:
unit.marktranslated()
def setid(self, id):
super().setid(id)
if len(self.units) > 1:
for i in range(len(self.units)):
self.units[i].setid("%s[%d]" % (id, i))
def getlocations(self):
"""Returns all the references (source locations)"""
groups = self.getcontextgroups("po-reference")
references = []
for group in groups:
sourcefile = ""
linenumber = ""
for (type, text) in group:
if type == "sourcefile":
sourcefile = text
elif type == "linenumber":
linenumber = text
assert sourcefile
if linenumber:
sourcefile = sourcefile + ":" + linenumber
references.append(sourcefile)
return references
def getautomaticcomments(self):
"""Returns the automatic comments (x-po-autocomment), which corresponds
to the #. style po comments.
"""
def hasautocomment(grp):
return grp[0] == "x-po-autocomment"
groups = self.getcontextgroups("po-entry")
comments = []
for group in groups:
commentpairs = filter(hasautocomment, group)
for (type, text) in commentpairs:
comments.append(text)
return "\n".join(comments)
def gettranslatorcomments(self):
"""Returns the translator comments (x-po-trancomment), which
corresponds to the # style po comments.
"""
def hastrancomment(grp):
return grp[0] == "x-po-trancomment"
groups = self.getcontextgroups("po-entry")
comments = []
for group in groups:
commentpairs = filter(hastrancomment, group)
for (type, text) in commentpairs:
comments.append(text)
return "\n".join(comments)
def isheader(self):
return "gettext-domain-header" in (self.getrestype() or "")
def istranslatable(self):
return super().istranslatable() and not self.isheader()
@classmethod
def createfromxmlElement(cls, element, namespace=None):
if element.tag.endswith("trans-unit"):
object = cls(None, empty=True)
object.xmlelement = element
object.namespace = namespace
return object
assert element.tag.endswith("group")
group = cls(None, empty=True)
group.xmlelement = element
group.namespace = namespace
units = list(element.iterdescendants(group.namespaced("trans-unit")))
for unit in units:
subunit = xliff.xliffunit.createfromxmlElement(unit)
subunit.namespace = namespace
group.units.append(subunit)
return group
def hasplural(self):
return self.xmlelement.tag == self.namespaced("group")
class PoXliffFile(xliff.xlifffile, poheader.poheader):
"""a file for the po variant of Xliff files"""
UnitClass = PoXliffUnit
def __init__(self, *args, **kwargs):
if "sourcelanguage" not in kwargs:
kwargs["sourcelanguage"] = "en-US"
xliff.xlifffile.__init__(self, *args, **kwargs)
def createfilenode(self, filename, sourcelanguage="en-US", datatype="po"):
# Let's ignore the sourcelanguage parameter opting for the internal
# one. PO files will probably be one language
return super().createfilenode(
filename, sourcelanguage=self.sourcelanguage, datatype="po"
)
def _insert_header(self, header):
header.xmlelement.set("restype", "x-gettext-domain-header")
header.xmlelement.set("approved", "no")
setXMLspace(header.xmlelement, "preserve")
self.addunit(header)
def addheaderunit(self, target, filename):
unit = self.addsourceunit(target, filename, True)
unit.target = target
unit.xmlelement.set("restype", "x-gettext-domain-header")
unit.xmlelement.set("approved", "no")
setXMLspace(unit.xmlelement, "preserve")
return unit
def addplural(self, source, target, filename, createifmissing=False):
"""This method should now be unnecessary, but is left for reference"""
assert isinstance(source, multistring)
if not isinstance(target, multistring):
target = multistring(target)
sourcel = len(source.strings)
targetl = len(target.strings)
if sourcel < targetl:
sources = source.strings + [source.strings[-1]] * targetl - sourcel
targets = target.strings
else:
sources = source.strings
targets = target.strings
self._messagenum += 1
pluralnum = 0
group = self.creategroup(filename, True, restype="x-gettext-plural")
for (src, tgt) in zip(sources, targets):
unit = self.UnitClass(src)
unit.target = tgt
unit.setid("%d[%d]" % (self._messagenum, pluralnum))
pluralnum += 1
group.append(unit.xmlelement)
self.units.append(unit)
if pluralnum < sourcel:
for string in sources[pluralnum:]:
unit = self.UnitClass(src)
unit.xmlelement.set("translate", "no")
unit.setid("%d[%d]" % (self._messagenum, pluralnum))
pluralnum += 1
group.append(unit.xmlelement)
self.units.append(unit)
return self.units[-pluralnum]
def parse(self, xml):
"""Populates this object from the given xml string"""
# TODO: Make more robust
def ispluralgroup(node):
"""determines whether the xml node refers to a getttext plural"""
return node.get("restype") == "x-gettext-plurals"
def isnonpluralunit(node):
"""determindes whether the xml node contains a plural like id.
We want to filter out all the plural nodes, except the very first
one in each group.
"""
return re.match(r".+\[[123456]\]$", node.get("id") or "") is None
def pluralunits(pluralgroups):
for pluralgroup in pluralgroups:
yield self.UnitClass.createfromxmlElement(
pluralgroup, namespace=self.namespace
)
self.filename = getattr(xml, "name", "")
if hasattr(xml, "read"):
xml.seek(0)
xmlsrc = xml.read()
xml = xmlsrc
parser = etree.XMLParser(resolve_entities=False)
self.document = etree.fromstring(xml, parser).getroottree()
self.initbody()
root_node = self.document.getroot()
assert root_node.tag == self.namespaced(self.rootNode)
groups = root_node.iterdescendants(self.namespaced("group"))
pluralgroups = filter(ispluralgroup, groups)
termEntries = root_node.iterdescendants(
self.namespaced(self.UnitClass.rootNode)
)
singularunits = list(filter(isnonpluralunit, termEntries))
if len(singularunits) == 0:
return
pluralunit_iter = pluralunits(pluralgroups)
nextplural = next(pluralunit_iter, None)
for entry in singularunits:
term = self.UnitClass.createfromxmlElement(entry, namespace=self.namespace)
if nextplural and str(term.getid()) == ("%s[0]" % nextplural.getid()):
self.addunit(nextplural, new=False)
nextplural = next(pluralunit_iter, None)
else:
self.addunit(term, new=False)
| miurahr/translate | translate/storage/poxliff.py | Python | gpl-2.0 | 14,579 |
package hillfly.wifichat.common.view;
import android.content.Context;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
public abstract class HandyListView extends ListView implements
OnScrollListener {
protected Context mContext;
protected LayoutInflater mInflater;
protected int mFirstVisibleItem;
protected boolean mIsTop;
protected boolean mIsBottom;
protected Point mDownPoint;
protected Point mMovePoint;
protected Point mUpPoint;
public HandyListView(Context context) {
super(context);
init(context);
}
public HandyListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public HandyListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
private void init(Context context) {
mContext = context;
mInflater = LayoutInflater.from(context);
setOnScrollListener(this);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
mFirstVisibleItem = firstVisibleItem;
if (view.getFirstVisiblePosition() == 1) {
mIsTop = true;
} else if (view.getLastVisiblePosition() == view.getCount() - 1) {
mIsBottom = true;
} else {
mIsTop = false;
mIsBottom = false;
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
int action = ev.getAction();
int x = 0;
int y = 0;
switch (action) {
case MotionEvent.ACTION_DOWN:
x = (int) ev.getX();
y = (int) ev.getY();
mDownPoint = new Point(x, y);
onDown(ev);
break;
case MotionEvent.ACTION_MOVE:
x = (int) ev.getX();
y = (int) ev.getY();
mMovePoint = new Point(x, y);
onMove(ev);
break;
case MotionEvent.ACTION_UP:
x = (int) ev.getX();
y = (int) ev.getY();
mUpPoint = new Point(x, y);
onUp(ev);
break;
}
return super.onTouchEvent(ev);
}
public abstract void onDown(MotionEvent ev);
public abstract void onMove(MotionEvent ev);
public abstract void onUp(MotionEvent ev);
}
| hillfly/WifiChat | src/hillfly/wifichat/common/view/HandyListView.java | Java | gpl-2.0 | 2,296 |
#ifndef _LINUX_SCHED_H
#define _LINUX_SCHED_H
#include <uapi/linux/sched.h>
#include <linux/sched/prio.h>
struct sched_param {
int sched_priority;
};
#include <asm/param.h> /* for HZ */
#include <linux/capability.h>
#include <linux/threads.h>
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/timex.h>
#include <linux/jiffies.h>
#include <linux/plist.h>
#include <linux/rbtree.h>
#include <linux/thread_info.h>
#include <linux/cpumask.h>
#include <linux/errno.h>
#include <linux/nodemask.h>
#include <linux/mm_types.h>
#include <linux/preempt_mask.h>
#include <asm/page.h>
#include <asm/ptrace.h>
#include <linux/cputime.h>
#include <linux/smp.h>
#include <linux/sem.h>
#include <linux/shm.h>
#include <linux/signal.h>
#include <linux/compiler.h>
#include <linux/completion.h>
#include <linux/pid.h>
#include <linux/percpu.h>
#include <linux/topology.h>
#include <linux/proportions.h>
#include <linux/seccomp.h>
#include <linux/rcupdate.h>
#include <linux/rculist.h>
#include <linux/rtmutex.h>
#include <linux/time.h>
#include <linux/param.h>
#include <linux/resource.h>
#include <linux/timer.h>
#include <linux/hrtimer.h>
#include <linux/task_io_accounting.h>
#include <linux/latencytop.h>
#include <linux/cred.h>
#include <linux/llist.h>
#include <linux/uidgid.h>
#include <linux/gfp.h>
#include <linux/magic.h>
#include <asm/processor.h>
#define SCHED_ATTR_SIZE_VER0 48 /* sizeof first published struct */
/*
* Extended scheduling parameters data structure.
*
* This is needed because the original struct sched_param can not be
* altered without introducing ABI issues with legacy applications
* (e.g., in sched_getparam()).
*
* However, the possibility of specifying more than just a priority for
* the tasks may be useful for a wide variety of application fields, e.g.,
* multimedia, streaming, automation and control, and many others.
*
* This variant (sched_attr) is meant at describing a so-called
* sporadic time-constrained task. In such model a task is specified by:
* - the activation period or minimum instance inter-arrival time;
* - the maximum (or average, depending on the actual scheduling
* discipline) computation time of all instances, a.k.a. runtime;
* - the deadline (relative to the actual activation time) of each
* instance.
* Very briefly, a periodic (sporadic) task asks for the execution of
* some specific computation --which is typically called an instance--
* (at most) every period. Moreover, each instance typically lasts no more
* than the runtime and must be completed by time instant t equal to
* the instance activation time + the deadline.
*
* This is reflected by the actual fields of the sched_attr structure:
*
* @size size of the structure, for fwd/bwd compat.
*
* @sched_policy task's scheduling policy
* @sched_flags for customizing the scheduler behaviour
* @sched_nice task's nice value (SCHED_NORMAL/BATCH)
* @sched_priority task's static priority (SCHED_FIFO/RR)
* @sched_deadline representative of the task's deadline
* @sched_runtime representative of the task's runtime
* @sched_period representative of the task's period
*
* Given this task model, there are a multiplicity of scheduling algorithms
* and policies, that can be used to ensure all the tasks will make their
* timing constraints.
*
* As of now, the SCHED_DEADLINE policy (sched_dl scheduling class) is the
* only user of this new interface. More information about the algorithm
* available in the scheduling class file or in Documentation/.
*/
struct sched_attr {
u32 size;
u32 sched_policy;
u64 sched_flags;
/* SCHED_NORMAL, SCHED_BATCH */
s32 sched_nice;
/* SCHED_FIFO, SCHED_RR */
u32 sched_priority;
/* SCHED_DEADLINE */
u64 sched_runtime;
u64 sched_deadline;
u64 sched_period;
};
struct exec_domain;
struct futex_pi_state;
struct robust_list_head;
struct bio_list;
struct fs_struct;
struct perf_event_context;
struct blk_plug;
struct filename;
#define VMACACHE_BITS 2
#define VMACACHE_SIZE (1U << VMACACHE_BITS)
#define VMACACHE_MASK (VMACACHE_SIZE - 1)
/*
* These are the constant used to fake the fixed-point load-average
* counting. Some notes:
* - 11 bit fractions expand to 22 bits by the multiplies: this gives
* a load-average precision of 10 bits integer + 11 bits fractional
* - if you want to count load-averages more often, you need more
* precision, or rounding will get you. With 2-second counting freq,
* the EXP_n values would be 1981, 2034 and 2043 if still using only
* 11 bit fractions.
*/
extern unsigned long avenrun[]; /* Load averages */
extern void get_avenrun(unsigned long *loads, unsigned long offset, int shift);
#define FSHIFT 11 /* nr of bits of precision */
#define FIXED_1 (1<<FSHIFT) /* 1.0 as fixed-point */
#define LOAD_FREQ (5*HZ+1) /* 5 sec intervals */
#define EXP_1 1884 /* 1/exp(5sec/1min) as fixed-point */
#define EXP_5 2014 /* 1/exp(5sec/5min) */
#define EXP_15 2037 /* 1/exp(5sec/15min) */
#define CALC_LOAD(load,exp,n) \
load *= exp; \
load += n*(FIXED_1-exp); \
load >>= FSHIFT;
extern unsigned long total_forks;
extern int nr_threads;
DECLARE_PER_CPU(unsigned long, process_counts);
extern int nr_processes(void);
extern unsigned long nr_running(void);
extern bool single_task_running(void);
extern unsigned long nr_iowait(void);
extern unsigned long nr_iowait_cpu(int cpu);
extern void get_iowait_load(unsigned long *nr_waiters, unsigned long *load);
#ifdef CONFIG_SCHED_HMP
extern unsigned long nr_running_cpu(unsigned int cpu);
extern int register_hmp_task_migration_notifier(struct notifier_block *nb);
#define HMP_UP_MIGRATION 0
#define HMP_DOWN_MIGRATION 1
#endif
extern void calc_global_load(unsigned long ticks);
extern void update_cpu_load_nohz(void);
extern unsigned long get_parent_ip(unsigned long addr);
extern void dump_cpu_task(int cpu);
struct seq_file;
struct cfs_rq;
struct task_group;
#ifdef CONFIG_SCHED_DEBUG
extern void proc_sched_show_task(struct task_struct *p, struct seq_file *m);
extern void proc_sched_set_task(struct task_struct *p);
extern void
print_cfs_rq(struct seq_file *m, int cpu, struct cfs_rq *cfs_rq);
#endif
/*
* Task state bitmask. NOTE! These bits are also
* encoded in fs/proc/array.c: get_task_state().
*
* We have two separate sets of flags: task->state
* is about runnability, while task->exit_state are
* about the task exiting. Confusing, but this way
* modifying one set can't modify the other one by
* mistake.
*/
#define TASK_RUNNING 0
#define TASK_INTERRUPTIBLE 1
#define TASK_UNINTERRUPTIBLE 2
#define __TASK_STOPPED 4
#define __TASK_TRACED 8
/* in tsk->exit_state */
#define EXIT_DEAD 16
#define EXIT_ZOMBIE 32
#define EXIT_TRACE (EXIT_ZOMBIE | EXIT_DEAD)
/* in tsk->state again */
#define TASK_DEAD 64
#define TASK_WAKEKILL 128
#define TASK_WAKING 256
#define TASK_PARKED 512
#define TASK_STATE_MAX 1024
#define TASK_STATE_TO_CHAR_STR "RSDTtXZxKWP"
extern char ___assert_task_state[1 - 2*!!(
sizeof(TASK_STATE_TO_CHAR_STR)-1 != ilog2(TASK_STATE_MAX)+1)];
/* Convenience macros for the sake of set_task_state */
#define TASK_KILLABLE (TASK_WAKEKILL | TASK_UNINTERRUPTIBLE)
#define TASK_STOPPED (TASK_WAKEKILL | __TASK_STOPPED)
#define TASK_TRACED (TASK_WAKEKILL | __TASK_TRACED)
/* Convenience macros for the sake of wake_up */
#define TASK_NORMAL (TASK_INTERRUPTIBLE | TASK_UNINTERRUPTIBLE)
#define TASK_ALL (TASK_NORMAL | __TASK_STOPPED | __TASK_TRACED)
/* get_task_state() */
#define TASK_REPORT (TASK_RUNNING | TASK_INTERRUPTIBLE | \
TASK_UNINTERRUPTIBLE | __TASK_STOPPED | \
__TASK_TRACED | EXIT_ZOMBIE | EXIT_DEAD)
#define task_is_traced(task) ((task->state & __TASK_TRACED) != 0)
#define task_is_stopped(task) ((task->state & __TASK_STOPPED) != 0)
#define task_is_stopped_or_traced(task) \
((task->state & (__TASK_STOPPED | __TASK_TRACED)) != 0)
#define task_contributes_to_load(task) \
((task->state & TASK_UNINTERRUPTIBLE) != 0 && \
(task->flags & PF_FROZEN) == 0)
#define __set_task_state(tsk, state_value) \
do { (tsk)->state = (state_value); } while (0)
#define set_task_state(tsk, state_value) \
set_mb((tsk)->state, (state_value))
/*
* set_current_state() includes a barrier so that the write of current->state
* is correctly serialised wrt the caller's subsequent test of whether to
* actually sleep:
*
* set_current_state(TASK_UNINTERRUPTIBLE);
* if (do_i_need_to_sleep())
* schedule();
*
* If the caller does not need such serialisation then use __set_current_state()
*/
#define __set_current_state(state_value) \
do { current->state = (state_value); } while (0)
#define set_current_state(state_value) \
set_mb(current->state, (state_value))
/* Task command name length */
#define TASK_COMM_LEN 16
#include <linux/spinlock.h>
/*
* This serializes "schedule()" and also protects
* the run-queue from deletions/modifications (but
* _adding_ to the beginning of the run-queue has
* a separate lock).
*/
extern rwlock_t tasklist_lock;
extern spinlock_t mmlist_lock;
struct task_struct;
#ifdef CONFIG_PROVE_RCU
extern int lockdep_tasklist_lock_is_held(void);
#endif /* #ifdef CONFIG_PROVE_RCU */
extern void sched_init(void);
extern void sched_init_smp(void);
extern asmlinkage void schedule_tail(struct task_struct *prev);
extern void init_idle(struct task_struct *idle, int cpu);
extern void init_idle_bootup_task(struct task_struct *idle);
extern int runqueue_is_locked(int cpu);
#if defined(CONFIG_SMP) && defined(CONFIG_NO_HZ_COMMON)
extern void nohz_balance_enter_idle(int cpu);
extern void set_cpu_sd_state_idle(void);
extern int get_nohz_timer_target(int pinned);
#else
static inline void nohz_balance_enter_idle(int cpu) { }
static inline void set_cpu_sd_state_idle(void) { }
static inline int get_nohz_timer_target(int pinned)
{
return smp_processor_id();
}
#endif
/*
* Only dump TASK_* tasks. (0 for all tasks)
*/
extern void show_state_filter(unsigned long state_filter);
static inline void show_state(void)
{
show_state_filter(0);
}
extern void show_regs(struct pt_regs *);
/*
* TASK is a pointer to the task whose backtrace we want to see (or NULL for current
* task), SP is the stack pointer of the first frame that should be shown in the back
* trace (or NULL if the entire call-chain of the task should be shown).
*/
extern void show_stack(struct task_struct *task, unsigned long *sp);
void io_schedule(void);
long io_schedule_timeout(long timeout);
extern void cpu_init (void);
extern void trap_init(void);
extern void update_process_times(int user);
extern void scheduler_tick(void);
extern void sched_show_task(struct task_struct *p);
#ifdef CONFIG_LOCKUP_DETECTOR
extern void touch_softlockup_watchdog(void);
extern void touch_softlockup_watchdog_sync(void);
extern void touch_all_softlockup_watchdogs(void);
extern int proc_dowatchdog_thresh(struct ctl_table *table, int write,
void __user *buffer,
size_t *lenp, loff_t *ppos);
extern unsigned int softlockup_panic;
void lockup_detector_init(void);
#else
static inline void touch_softlockup_watchdog(void)
{
}
static inline void touch_softlockup_watchdog_sync(void)
{
}
static inline void touch_all_softlockup_watchdogs(void)
{
}
static inline void lockup_detector_init(void)
{
}
#endif
#ifdef CONFIG_DETECT_HUNG_TASK
void reset_hung_task_detector(void);
#else
static inline void reset_hung_task_detector(void)
{
}
#endif
/* Attach to any functions which should be ignored in wchan output. */
#define __sched __attribute__((__section__(".sched.text")))
/* Linker adds these: start and end of __sched functions */
extern char __sched_text_start[], __sched_text_end[];
/* Is this address in the __sched functions? */
extern int in_sched_functions(unsigned long addr);
#define MAX_SCHEDULE_TIMEOUT LONG_MAX
extern signed long schedule_timeout(signed long timeout);
extern signed long schedule_timeout_interruptible(signed long timeout);
extern signed long schedule_timeout_killable(signed long timeout);
extern signed long schedule_timeout_uninterruptible(signed long timeout);
asmlinkage void schedule(void);
extern void schedule_preempt_disabled(void);
struct nsproxy;
struct user_namespace;
#ifdef CONFIG_MMU
extern void arch_pick_mmap_layout(struct mm_struct *mm);
extern unsigned long
arch_get_unmapped_area(struct file *, unsigned long, unsigned long,
unsigned long, unsigned long);
extern unsigned long
arch_get_unmapped_area_topdown(struct file *filp, unsigned long addr,
unsigned long len, unsigned long pgoff,
unsigned long flags);
#else
static inline void arch_pick_mmap_layout(struct mm_struct *mm) {}
#endif
#define SUID_DUMP_DISABLE 0 /* No setuid dumping */
#define SUID_DUMP_USER 1 /* Dump as user of process */
#define SUID_DUMP_ROOT 2 /* Dump as root */
/* mm flags */
/* for SUID_DUMP_* above */
#define MMF_DUMPABLE_BITS 2
#define MMF_DUMPABLE_MASK ((1 << MMF_DUMPABLE_BITS) - 1)
extern void set_dumpable(struct mm_struct *mm, int value);
/*
* This returns the actual value of the suid_dumpable flag. For things
* that are using this for checking for privilege transitions, it must
* test against SUID_DUMP_USER rather than treating it as a boolean
* value.
*/
static inline int __get_dumpable(unsigned long mm_flags)
{
return mm_flags & MMF_DUMPABLE_MASK;
}
static inline int get_dumpable(struct mm_struct *mm)
{
return __get_dumpable(mm->flags);
}
/* coredump filter bits */
#define MMF_DUMP_ANON_PRIVATE 2
#define MMF_DUMP_ANON_SHARED 3
#define MMF_DUMP_MAPPED_PRIVATE 4
#define MMF_DUMP_MAPPED_SHARED 5
#define MMF_DUMP_ELF_HEADERS 6
#define MMF_DUMP_HUGETLB_PRIVATE 7
#define MMF_DUMP_HUGETLB_SHARED 8
#define MMF_DUMP_FILTER_SHIFT MMF_DUMPABLE_BITS
#define MMF_DUMP_FILTER_BITS 7
#define MMF_DUMP_FILTER_MASK \
(((1 << MMF_DUMP_FILTER_BITS) - 1) << MMF_DUMP_FILTER_SHIFT)
#define MMF_DUMP_FILTER_DEFAULT \
((1 << MMF_DUMP_ANON_PRIVATE) | (1 << MMF_DUMP_ANON_SHARED) |\
(1 << MMF_DUMP_HUGETLB_PRIVATE) | MMF_DUMP_MASK_DEFAULT_ELF)
#ifdef CONFIG_CORE_DUMP_DEFAULT_ELF_HEADERS
# define MMF_DUMP_MASK_DEFAULT_ELF (1 << MMF_DUMP_ELF_HEADERS)
#else
# define MMF_DUMP_MASK_DEFAULT_ELF 0
#endif
/* leave room for more dump flags */
#define MMF_VM_MERGEABLE 16 /* KSM may merge identical pages */
#define MMF_VM_HUGEPAGE 17 /* set when VM_HUGEPAGE is set on vma */
#define MMF_EXE_FILE_CHANGED 18 /* see prctl_set_mm_exe_file() */
#define MMF_HAS_UPROBES 19 /* has uprobes */
#define MMF_RECALC_UPROBES 20 /* MMF_HAS_UPROBES can be wrong */
#define MMF_INIT_MASK (MMF_DUMPABLE_MASK | MMF_DUMP_FILTER_MASK)
struct sighand_struct {
atomic_t count;
struct k_sigaction action[_NSIG];
spinlock_t siglock;
wait_queue_head_t signalfd_wqh;
};
struct pacct_struct {
int ac_flag;
long ac_exitcode;
unsigned long ac_mem;
cputime_t ac_utime, ac_stime;
unsigned long ac_minflt, ac_majflt;
};
struct cpu_itimer {
cputime_t expires;
cputime_t incr;
u32 error;
u32 incr_error;
};
/**
* struct cputime - snaphsot of system and user cputime
* @utime: time spent in user mode
* @stime: time spent in system mode
*
* Gathers a generic snapshot of user and system time.
*/
struct cputime {
cputime_t utime;
cputime_t stime;
};
/**
* struct task_cputime - collected CPU time counts
* @utime: time spent in user mode, in &cputime_t units
* @stime: time spent in kernel mode, in &cputime_t units
* @sum_exec_runtime: total time spent on the CPU, in nanoseconds
*
* This is an extension of struct cputime that includes the total runtime
* spent by the task from the scheduler point of view.
*
* As a result, this structure groups together three kinds of CPU time
* that are tracked for threads and thread groups. Most things considering
* CPU time want to group these counts together and treat all three
* of them in parallel.
*/
struct task_cputime {
cputime_t utime;
cputime_t stime;
unsigned long long sum_exec_runtime;
};
/* Alternate field names when used to cache expirations. */
#define prof_exp stime
#define virt_exp utime
#define sched_exp sum_exec_runtime
#define INIT_CPUTIME \
(struct task_cputime) { \
.utime = 0, \
.stime = 0, \
.sum_exec_runtime = 0, \
}
#ifdef CONFIG_PREEMPT_COUNT
#define PREEMPT_DISABLED (1 + PREEMPT_ENABLED)
#else
#define PREEMPT_DISABLED PREEMPT_ENABLED
#endif
/*
* Disable preemption until the scheduler is running.
* Reset by start_kernel()->sched_init()->init_idle().
*
* We include PREEMPT_ACTIVE to avoid cond_resched() from working
* before the scheduler is active -- see should_resched().
*/
#define INIT_PREEMPT_COUNT (PREEMPT_DISABLED + PREEMPT_ACTIVE)
/**
* struct thread_group_cputimer - thread group interval timer counts
* @cputime: thread group interval timers.
* @running: non-zero when there are timers running and
* @cputime receives updates.
* @lock: lock for fields in this struct.
*
* This structure contains the version of task_cputime, above, that is
* used for thread group CPU timer calculations.
*/
struct thread_group_cputimer {
struct task_cputime cputime;
int running;
raw_spinlock_t lock;
};
#include <linux/rwsem.h>
struct autogroup;
/*
* NOTE! "signal_struct" does not have its own
* locking, because a shared signal_struct always
* implies a shared sighand_struct, so locking
* sighand_struct is always a proper superset of
* the locking of signal_struct.
*/
struct signal_struct {
atomic_t sigcnt;
atomic_t live;
int nr_threads;
struct list_head thread_head;
wait_queue_head_t wait_chldexit; /* for wait4() */
/* current thread group signal load-balancing target: */
struct task_struct *curr_target;
/* shared signal handling: */
struct sigpending shared_pending;
/* thread group exit support */
int group_exit_code;
/* overloaded:
* - notify group_exit_task when ->count is equal to notify_count
* - everyone except group_exit_task is stopped during signal delivery
* of fatal signals, group_exit_task processes the signal.
*/
int notify_count;
struct task_struct *group_exit_task;
/* thread group stop support, overloads group_exit_code too */
int group_stop_count;
unsigned int flags; /* see SIGNAL_* flags below */
/*
* PR_SET_CHILD_SUBREAPER marks a process, like a service
* manager, to re-parent orphan (double-forking) child processes
* to this process instead of 'init'. The service manager is
* able to receive SIGCHLD signals and is able to investigate
* the process until it calls wait(). All children of this
* process will inherit a flag if they should look for a
* child_subreaper process at exit.
*/
unsigned int is_child_subreaper:1;
unsigned int has_child_subreaper:1;
/* POSIX.1b Interval Timers */
int posix_timer_id;
struct list_head posix_timers;
/* ITIMER_REAL timer for the process */
struct hrtimer real_timer;
struct pid *leader_pid;
ktime_t it_real_incr;
/*
* ITIMER_PROF and ITIMER_VIRTUAL timers for the process, we use
* CPUCLOCK_PROF and CPUCLOCK_VIRT for indexing array as these
* values are defined to 0 and 1 respectively
*/
struct cpu_itimer it[2];
/*
* Thread group totals for process CPU timers.
* See thread_group_cputimer(), et al, for details.
*/
struct thread_group_cputimer cputimer;
/* Earliest-expiration cache. */
struct task_cputime cputime_expires;
struct list_head cpu_timers[3];
struct pid *tty_old_pgrp;
/* boolean value for session group leader */
int leader;
struct tty_struct *tty; /* NULL if no tty */
#ifdef CONFIG_SCHED_AUTOGROUP
struct autogroup *autogroup;
#endif
/*
* Cumulative resource counters for dead threads in the group,
* and for reaped dead child processes forked by this group.
* Live threads maintain their own counters and add to these
* in __exit_signal, except for the group leader.
*/
seqlock_t stats_lock;
cputime_t utime, stime, cutime, cstime;
cputime_t gtime;
cputime_t cgtime;
#ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
struct cputime prev_cputime;
#endif
unsigned long nvcsw, nivcsw, cnvcsw, cnivcsw;
unsigned long min_flt, maj_flt, cmin_flt, cmaj_flt;
unsigned long inblock, oublock, cinblock, coublock;
unsigned long maxrss, cmaxrss;
struct task_io_accounting ioac;
/*
* Cumulative ns of schedule CPU time fo dead threads in the
* group, not including a zombie group leader, (This only differs
* from jiffies_to_ns(utime + stime) if sched_clock uses something
* other than jiffies.)
*/
unsigned long long sum_sched_runtime;
/*
* We don't bother to synchronize most readers of this at all,
* because there is no reader checking a limit that actually needs
* to get both rlim_cur and rlim_max atomically, and either one
* alone is a single word that can safely be read normally.
* getrlimit/setrlimit use task_lock(current->group_leader) to
* protect this instead of the siglock, because they really
* have no need to disable irqs.
*/
struct rlimit rlim[RLIM_NLIMITS];
#ifdef CONFIG_BSD_PROCESS_ACCT
struct pacct_struct pacct; /* per-process accounting information */
#endif
#ifdef CONFIG_TASKSTATS
struct taskstats *stats;
#endif
#ifdef CONFIG_AUDIT
unsigned audit_tty;
unsigned audit_tty_log_passwd;
struct tty_audit_buf *tty_audit_buf;
#endif
#ifdef CONFIG_CGROUPS
/*
* group_rwsem prevents new tasks from entering the threadgroup and
* member tasks from exiting,a more specifically, setting of
* PF_EXITING. fork and exit paths are protected with this rwsem
* using threadgroup_change_begin/end(). Users which require
* threadgroup to remain stable should use threadgroup_[un]lock()
* which also takes care of exec path. Currently, cgroup is the
* only user.
*/
struct rw_semaphore group_rwsem;
#endif
oom_flags_t oom_flags;
short oom_score_adj; /* OOM kill score adjustment */
short oom_score_adj_min; /* OOM kill score adjustment min value.
* Only settable by CAP_SYS_RESOURCE. */
struct mutex cred_guard_mutex; /* guard against foreign influences on
* credential calculations
* (notably. ptrace) */
};
/*
* Bits in flags field of signal_struct.
*/
#define SIGNAL_STOP_STOPPED 0x00000001 /* job control stop in effect */
#define SIGNAL_STOP_CONTINUED 0x00000002 /* SIGCONT since WCONTINUED reap */
#define SIGNAL_GROUP_EXIT 0x00000004 /* group exit in progress */
#define SIGNAL_GROUP_COREDUMP 0x00000008 /* coredump in progress */
/*
* Pending notifications to parent.
*/
#define SIGNAL_CLD_STOPPED 0x00000010
#define SIGNAL_CLD_CONTINUED 0x00000020
#define SIGNAL_CLD_MASK (SIGNAL_CLD_STOPPED|SIGNAL_CLD_CONTINUED)
#define SIGNAL_UNKILLABLE 0x00000040 /* for init: ignore fatal signals */
/* If true, all threads except ->group_exit_task have pending SIGKILL */
static inline int signal_group_exit(const struct signal_struct *sig)
{
return (sig->flags & SIGNAL_GROUP_EXIT) ||
(sig->group_exit_task != NULL);
}
/*
* Some day this will be a full-fledged user tracking system..
*/
struct user_struct {
atomic_t __count; /* reference count */
atomic_t processes; /* How many processes does this user have? */
atomic_t sigpending; /* How many pending signals does this user have? */
#ifdef CONFIG_INOTIFY_USER
atomic_t inotify_watches; /* How many inotify watches does this user have? */
atomic_t inotify_devs; /* How many inotify devs does this user have opened? */
#endif
#ifdef CONFIG_FANOTIFY
atomic_t fanotify_listeners;
#endif
#ifdef CONFIG_EPOLL
atomic_long_t epoll_watches; /* The number of file descriptors currently watched */
#endif
#ifdef CONFIG_POSIX_MQUEUE
/* protected by mq_lock */
unsigned long mq_bytes; /* How many bytes can be allocated to mqueue? */
#endif
unsigned long locked_shm; /* How many pages of mlocked shm ? */
atomic_long_t pipe_bufs; /* how many pages are allocated in pipe buffers */
#ifdef CONFIG_KEYS
struct key *uid_keyring; /* UID specific keyring */
struct key *session_keyring; /* UID's default session keyring */
#endif
/* Hash table maintenance information */
struct hlist_node uidhash_node;
kuid_t uid;
#ifdef CONFIG_PERF_EVENTS
atomic_long_t locked_vm;
#endif
};
extern int uids_sysfs_init(void);
extern struct user_struct *find_user(kuid_t);
extern struct user_struct root_user;
#define INIT_USER (&root_user)
struct backing_dev_info;
struct reclaim_state;
#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
struct sched_info {
/* cumulative counters */
unsigned long pcount; /* # of times run on this cpu */
unsigned long long run_delay; /* time spent waiting on a runqueue */
/* timestamps */
unsigned long long last_arrival,/* when we last ran on a cpu */
last_queued; /* when we were last queued to run */
};
#endif /* defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT) */
#ifdef CONFIG_TASK_DELAY_ACCT
struct task_delay_info {
spinlock_t lock;
unsigned int flags; /* Private per-task flags */
/* For each stat XXX, add following, aligned appropriately
*
* struct timespec XXX_start, XXX_end;
* u64 XXX_delay;
* u32 XXX_count;
*
* Atomicity of updates to XXX_delay, XXX_count protected by
* single lock above (split into XXX_lock if contention is an issue).
*/
/*
* XXX_count is incremented on every XXX operation, the delay
* associated with the operation is added to XXX_delay.
* XXX_delay contains the accumulated delay time in nanoseconds.
*/
u64 blkio_start; /* Shared by blkio, swapin */
u64 blkio_delay; /* wait for sync block io completion */
u64 swapin_delay; /* wait for swapin block io completion */
u32 blkio_count; /* total count of the number of sync block */
/* io operations performed */
u32 swapin_count; /* total count of the number of swapin block */
/* io operations performed */
u64 freepages_start;
u64 freepages_delay; /* wait for memory reclaim */
u32 freepages_count; /* total count of memory reclaim */
};
#endif /* CONFIG_TASK_DELAY_ACCT */
static inline int sched_info_on(void)
{
#ifdef CONFIG_SCHEDSTATS
return 1;
#elif defined(CONFIG_TASK_DELAY_ACCT)
extern int delayacct_on;
return delayacct_on;
#else
return 0;
#endif
}
enum cpu_idle_type {
CPU_IDLE,
CPU_NOT_IDLE,
CPU_NEWLY_IDLE,
CPU_MAX_IDLE_TYPES
};
/*
* Increase resolution of cpu_capacity calculations
*/
#define SCHED_CAPACITY_SHIFT 10
#define SCHED_CAPACITY_SCALE (1L << SCHED_CAPACITY_SHIFT)
/*
* Increase resolution of cpu_power calculations
*/
#define SCHED_POWER_SHIFT 10
#define SCHED_POWER_SCALE (1L << SCHED_POWER_SHIFT)
/*
* sched-domains (multiprocessor balancing) declarations:
*/
#ifdef CONFIG_SMP
#define SD_LOAD_BALANCE 0x0001 /* Do load balancing on this domain. */
#define SD_BALANCE_NEWIDLE 0x0002 /* Balance when about to become idle */
#define SD_BALANCE_EXEC 0x0004 /* Balance on exec */
#define SD_BALANCE_FORK 0x0008 /* Balance on fork, clone */
#define SD_BALANCE_WAKE 0x0010 /* Balance on wakeup */
#define SD_WAKE_AFFINE 0x0020 /* Wake task to waking CPU */
#define SD_SHARE_CPUCAPACITY 0x0080 /* Domain members share cpu power */
#define SD_SHARE_POWERDOMAIN 0x0100 /* Domain members share power domain */
#define SD_SHARE_PKG_RESOURCES 0x0200 /* Domain members share cpu pkg resources */
#define SD_SERIALIZE 0x0400 /* Only a single load balancing instance */
#define SD_ASYM_PACKING 0x0800 /* Place busy groups earlier in the domain */
#define SD_PREFER_SIBLING 0x1000 /* Prefer to place tasks in a sibling domain */
#define SD_OVERLAP 0x2000 /* sched_domains of this level overlap */
#define SD_NUMA 0x4000 /* cross-node balancing */
#define SD_NO_LOAD_BALANCE 0x8000 /* flag for hmp scheduler */
#ifdef CONFIG_SCHED_SMT
static inline int cpu_smt_flags(void)
{
return SD_SHARE_CPUCAPACITY | SD_SHARE_PKG_RESOURCES;
}
#endif
#ifdef CONFIG_SCHED_MC
static inline int cpu_core_flags(void)
{
return SD_SHARE_PKG_RESOURCES;
}
#endif
#ifdef CONFIG_NUMA
static inline int cpu_numa_flags(void)
{
return SD_NUMA;
}
#endif
struct sched_domain_attr {
int relax_domain_level;
};
#define SD_ATTR_INIT (struct sched_domain_attr) { \
.relax_domain_level = -1, \
}
extern int sched_domain_level_max;
struct sched_group;
struct sched_domain {
/* These fields must be setup */
struct sched_domain *parent; /* top domain must be null terminated */
struct sched_domain *child; /* bottom domain must be null terminated */
struct sched_group *groups; /* the balancing groups of the domain */
unsigned long min_interval; /* Minimum balance interval ms */
unsigned long max_interval; /* Maximum balance interval ms */
unsigned int busy_factor; /* less balancing by factor if busy */
unsigned int imbalance_pct; /* No balance until over watermark */
unsigned int cache_nice_tries; /* Leave cache hot tasks for # tries */
unsigned int busy_idx;
unsigned int idle_idx;
unsigned int newidle_idx;
unsigned int wake_idx;
unsigned int forkexec_idx;
unsigned int smt_gain;
int nohz_idle; /* NOHZ IDLE status */
int flags; /* See SD_* */
int level;
/* Runtime fields. */
unsigned long last_balance; /* init to jiffies. units in jiffies */
unsigned int balance_interval; /* initialise to 1. units in ms. */
unsigned int nr_balance_failed; /* initialise to 0 */
/* idle_balance() stats */
u64 max_newidle_lb_cost;
unsigned long next_decay_max_lb_cost;
#ifdef CONFIG_SCHEDSTATS
/* load_balance() stats */
unsigned int lb_count[CPU_MAX_IDLE_TYPES];
unsigned int lb_failed[CPU_MAX_IDLE_TYPES];
unsigned int lb_balanced[CPU_MAX_IDLE_TYPES];
unsigned int lb_imbalance[CPU_MAX_IDLE_TYPES];
unsigned int lb_gained[CPU_MAX_IDLE_TYPES];
unsigned int lb_hot_gained[CPU_MAX_IDLE_TYPES];
unsigned int lb_nobusyg[CPU_MAX_IDLE_TYPES];
unsigned int lb_nobusyq[CPU_MAX_IDLE_TYPES];
/* Active load balancing */
unsigned int alb_count;
unsigned int alb_failed;
unsigned int alb_pushed;
/* SD_BALANCE_EXEC stats */
unsigned int sbe_count;
unsigned int sbe_balanced;
unsigned int sbe_pushed;
/* SD_BALANCE_FORK stats */
unsigned int sbf_count;
unsigned int sbf_balanced;
unsigned int sbf_pushed;
/* try_to_wake_up() stats */
unsigned int ttwu_wake_remote;
unsigned int ttwu_move_affine;
unsigned int ttwu_move_balance;
#endif
#ifdef CONFIG_SCHED_DEBUG
char *name;
#endif
union {
void *private; /* used during construction */
struct rcu_head rcu; /* used during destruction */
};
unsigned int span_weight;
/*
* Span of all CPUs in this domain.
*
* NOTE: this field is variable length. (Allocated dynamically
* by attaching extra space to the end of the structure,
* depending on how many CPUs the kernel has booted up with)
*/
unsigned long span[0];
};
static inline struct cpumask *sched_domain_span(struct sched_domain *sd)
{
return to_cpumask(sd->span);
}
extern void partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
struct sched_domain_attr *dattr_new);
/* Allocate an array of sched domains, for partition_sched_domains(). */
cpumask_var_t *alloc_sched_domains(unsigned int ndoms);
void free_sched_domains(cpumask_var_t doms[], unsigned int ndoms);
bool cpus_share_cache(int this_cpu, int that_cpu);
typedef const struct cpumask *(*sched_domain_mask_f)(int cpu);
typedef int (*sched_domain_flags_f)(void);
#define SDTL_OVERLAP 0x01
struct sd_data {
struct sched_domain **__percpu sd;
struct sched_group **__percpu sg;
struct sched_group_capacity **__percpu sgc;
};
struct sched_domain_topology_level {
sched_domain_mask_f mask;
sched_domain_flags_f sd_flags;
int flags;
int numa_level;
struct sd_data data;
#ifdef CONFIG_SCHED_DEBUG
char *name;
#endif
};
extern struct sched_domain_topology_level *sched_domain_topology;
extern void set_sched_topology(struct sched_domain_topology_level *tl);
extern void wake_up_if_idle(int cpu);
#ifdef CONFIG_SCHED_DEBUG
# define SD_INIT_NAME(type) .name = #type
#else
# define SD_INIT_NAME(type)
#endif
#ifdef CONFIG_SCHED_HMP
struct hmp_domain {
struct cpumask cpus;
struct cpumask possible_cpus;
struct list_head hmp_domains;
};
extern int set_hmp_boost(int enable);
extern int set_hmp_semiboost(int enable);
extern int set_hmp_boostpulse(int duration);
extern int get_hmp_boost(void);
extern int get_hmp_semiboost(void);
extern int set_hmp_up_threshold(int value);
extern int set_hmp_down_threshold(int value);
extern int set_active_down_migration(int enable);
extern int set_hmp_aggressive_up_migration(int enable);
extern int set_hmp_aggressive_yield(int enable);
#endif /* CONFIG_SCHED_HMP */
#else /* CONFIG_SMP */
struct sched_domain_attr;
static inline void
partition_sched_domains(int ndoms_new, cpumask_var_t doms_new[],
struct sched_domain_attr *dattr_new)
{
}
static inline bool cpus_share_cache(int this_cpu, int that_cpu)
{
return true;
}
#endif /* !CONFIG_SMP */
struct io_context; /* See blkdev.h */
#ifdef ARCH_HAS_PREFETCH_SWITCH_STACK
extern void prefetch_stack(struct task_struct *t);
#else
static inline void prefetch_stack(struct task_struct *t) { }
#endif
struct audit_context; /* See audit.c */
struct mempolicy;
struct pipe_inode_info;
struct uts_namespace;
struct load_weight {
unsigned long weight;
u32 inv_weight;
};
struct sched_avg {
/*
* These sums represent an infinite geometric series and so are bound
* above by 1024/(1-y). Thus we only need a u32 to store them for all
* choices of y < 1-2^(-32)*1024.
*/
u32 runnable_avg_sum, runnable_avg_period;
u32 remainder;
u64 last_runnable_update;
s64 decay_count;
unsigned long load_avg_contrib;
unsigned long load_avg_ratio;
#ifdef CONFIG_SCHED_HMP
u64 hmp_last_up_migration;
u64 hmp_last_down_migration;
#ifdef CONFIG_HP_EVENT_HMP_SYSTEM_LOAD
bool is_big_thread;
#endif
#endif
u32 usage_avg_sum;
};
#ifdef CONFIG_SCHEDSTATS
struct sched_statistics {
u64 wait_start;
u64 wait_max;
u64 wait_count;
u64 wait_sum;
u64 iowait_count;
u64 iowait_sum;
u64 sleep_start;
u64 sleep_max;
s64 sum_sleep_runtime;
u64 block_start;
u64 block_max;
u64 exec_max;
u64 slice_max;
u64 nr_migrations_cold;
u64 nr_failed_migrations_affine;
u64 nr_failed_migrations_running;
u64 nr_failed_migrations_hot;
u64 nr_forced_migrations;
u64 nr_wakeups;
u64 nr_wakeups_sync;
u64 nr_wakeups_migrate;
u64 nr_wakeups_local;
u64 nr_wakeups_remote;
u64 nr_wakeups_affine;
u64 nr_wakeups_affine_attempts;
u64 nr_wakeups_passive;
u64 nr_wakeups_idle;
};
#endif
struct sched_entity {
struct load_weight load; /* for load-balancing */
struct rb_node run_node;
struct list_head group_node;
unsigned int on_rq;
u64 exec_start;
u64 sum_exec_runtime;
u64 vruntime;
u64 prev_sum_exec_runtime;
u64 nr_migrations;
#ifdef CONFIG_SCHEDSTATS
struct sched_statistics statistics;
#endif
#ifdef CONFIG_FAIR_GROUP_SCHED
int depth;
struct sched_entity *parent;
/* rq on which this entity is (to be) queued: */
struct cfs_rq *cfs_rq;
/* rq "owned" by this entity/group: */
struct cfs_rq *my_q;
#endif
#ifdef CONFIG_SMP
/* Per-entity load-tracking */
struct sched_avg avg;
#endif
};
struct sched_rt_entity {
struct list_head run_list;
unsigned long timeout;
unsigned long watchdog_stamp;
unsigned int time_slice;
struct sched_rt_entity *back;
#ifdef CONFIG_RT_GROUP_SCHED
struct sched_rt_entity *parent;
/* rq on which this entity is (to be) queued: */
struct rt_rq *rt_rq;
/* rq "owned" by this entity/group: */
struct rt_rq *my_q;
#endif
};
struct sched_dl_entity {
struct rb_node rb_node;
/*
* Original scheduling parameters. Copied here from sched_attr
* during sched_setattr(), they will remain the same until
* the next sched_setattr().
*/
u64 dl_runtime; /* maximum runtime for each instance */
u64 dl_deadline; /* relative deadline of each instance */
u64 dl_period; /* separation of two instances (period) */
u64 dl_bw; /* dl_runtime / dl_deadline */
/*
* Actual scheduling parameters. Initialized with the values above,
* they are continously updated during task execution. Note that
* the remaining runtime could be < 0 in case we are in overrun.
*/
s64 runtime; /* remaining runtime for this instance */
u64 deadline; /* absolute deadline for this instance */
unsigned int flags; /* specifying the scheduler behaviour */
/*
* Some bool flags:
*
* @dl_throttled tells if we exhausted the runtime. If so, the
* task has to wait for a replenishment to be performed at the
* next firing of dl_timer.
*
* @dl_new tells if a new instance arrived. If so we must
* start executing it with full runtime and reset its absolute
* deadline;
*
* @dl_boosted tells if we are boosted due to DI. If so we are
* outside bandwidth enforcement mechanism (but only until we
* exit the critical section);
*
* @dl_yielded tells if task gave up the cpu before consuming
* all its available runtime during the last job.
*/
int dl_throttled, dl_new, dl_boosted, dl_yielded;
/*
* Bandwidth enforcement timer. Each -deadline task has its
* own bandwidth to be enforced, thus we need one timer per task.
*/
struct hrtimer dl_timer;
};
union rcu_special {
struct {
bool blocked;
bool need_qs;
} b;
short s;
};
struct rcu_node;
enum perf_event_task_context {
perf_invalid_context = -1,
perf_hw_context = 0,
perf_sw_context,
perf_nr_task_contexts,
};
struct task_struct {
volatile long state; /* -1 unrunnable, 0 runnable, >0 stopped */
void *stack;
atomic_t usage;
unsigned int flags; /* per process flags, defined below */
unsigned int ptrace;
#ifdef CONFIG_SMP
struct llist_node wake_entry;
int on_cpu;
struct task_struct *last_wakee;
unsigned long wakee_flips;
unsigned long wakee_flip_decay_ts;
int wake_cpu;
#endif
int on_rq;
int prio, static_prio, normal_prio;
unsigned int rt_priority;
const struct sched_class *sched_class;
struct sched_entity se;
struct sched_rt_entity rt;
#ifdef CONFIG_CGROUP_SCHED
struct task_group *sched_task_group;
#endif
struct sched_dl_entity dl;
#ifdef CONFIG_PREEMPT_NOTIFIERS
/* list of struct preempt_notifier: */
struct hlist_head preempt_notifiers;
#endif
#ifdef CONFIG_BLK_DEV_IO_TRACE
unsigned int btrace_seq;
#endif
unsigned int policy;
int nr_cpus_allowed;
cpumask_t cpus_allowed;
#ifdef CONFIG_PREEMPT_RCU
int rcu_read_lock_nesting;
union rcu_special rcu_read_unlock_special;
struct list_head rcu_node_entry;
#endif /* #ifdef CONFIG_PREEMPT_RCU */
#ifdef CONFIG_TREE_PREEMPT_RCU
struct rcu_node *rcu_blocked_node;
#endif /* #ifdef CONFIG_TREE_PREEMPT_RCU */
#ifdef CONFIG_TASKS_RCU
unsigned long rcu_tasks_nvcsw;
bool rcu_tasks_holdout;
struct list_head rcu_tasks_holdout_list;
int rcu_tasks_idle_cpu;
#endif /* #ifdef CONFIG_TASKS_RCU */
#if defined(CONFIG_SCHEDSTATS) || defined(CONFIG_TASK_DELAY_ACCT)
struct sched_info sched_info;
#endif
struct list_head tasks;
#ifdef CONFIG_SMP
struct plist_node pushable_tasks;
struct rb_node pushable_dl_tasks;
#endif
struct mm_struct *mm, *active_mm;
#ifdef CONFIG_COMPAT_BRK
unsigned brk_randomized:1;
#endif
/* per-thread vma caching */
u32 vmacache_seqnum;
struct vm_area_struct *vmacache[VMACACHE_SIZE];
#if defined(SPLIT_RSS_COUNTING)
struct task_rss_stat rss_stat;
#endif
/* task state */
int exit_state;
int exit_code, exit_signal;
int pdeath_signal; /* The signal sent when the parent dies */
unsigned int jobctl; /* JOBCTL_*, siglock protected */
/* Used for emulating ABI behavior of previous Linux versions */
unsigned int personality;
unsigned in_execve:1; /* Tell the LSMs that the process is doing an
* execve */
unsigned in_iowait:1;
/* Revert to default priority/policy when forking */
unsigned sched_reset_on_fork:1;
unsigned sched_contributes_to_load:1;
unsigned long atomic_flags; /* Flags needing atomic access. */
pid_t pid;
pid_t tgid;
#ifdef CONFIG_CC_STACKPROTECTOR
/* Canary value for the -fstack-protector gcc feature */
unsigned long stack_canary;
#endif
/*
* pointers to (original) parent process, youngest child, younger sibling,
* older sibling, respectively. (p->father can be replaced with
* p->real_parent->pid)
*/
struct task_struct __rcu *real_parent; /* real parent process */
struct task_struct __rcu *parent; /* recipient of SIGCHLD, wait4() reports */
/*
* children/sibling forms the list of my natural children
*/
struct list_head children; /* list of my children */
struct list_head sibling; /* linkage in my parent's children list */
struct task_struct *group_leader; /* threadgroup leader */
/*
* ptraced is the list of tasks this task is using ptrace on.
* This includes both natural children and PTRACE_ATTACH targets.
* p->ptrace_entry is p's link on the p->parent->ptraced list.
*/
struct list_head ptraced;
struct list_head ptrace_entry;
/* PID/PID hash table linkage. */
struct pid_link pids[PIDTYPE_MAX];
struct list_head thread_group;
struct list_head thread_node;
#ifdef CONFIG_HP_EVENT_THREAD_GROUP
unsigned long thread_group_load;
int nr_thread_group;
raw_spinlock_t thread_group_lock;
bool hp_boost_requested; /* This task requested hotplug boost */
bool applied_to_group_load;
bool member_of_group;
unsigned long group_applied_load;
#endif
struct completion *vfork_done; /* for vfork() */
int __user *set_child_tid; /* CLONE_CHILD_SETTID */
int __user *clear_child_tid; /* CLONE_CHILD_CLEARTID */
cputime_t utime, stime, utimescaled, stimescaled;
cputime_t gtime;
unsigned long long cpu_power;
#ifndef CONFIG_VIRT_CPU_ACCOUNTING_NATIVE
struct cputime prev_cputime;
#endif
#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
seqlock_t vtime_seqlock;
unsigned long long vtime_snap;
enum {
VTIME_SLEEPING = 0,
VTIME_USER,
VTIME_SYS,
} vtime_snap_whence;
#endif
unsigned long nvcsw, nivcsw; /* context switch counts */
u64 start_time; /* monotonic time in nsec */
u64 real_start_time; /* boot based time in nsec */
/* mm fault and swap info: this can arguably be seen as either mm-specific or thread-specific */
unsigned long min_flt, maj_flt;
struct task_cputime cputime_expires;
struct list_head cpu_timers[3];
/* process credentials */
const struct cred __rcu *real_cred; /* objective and real subjective task
* credentials (COW) */
const struct cred __rcu *cred; /* effective (overridable) subjective task
* credentials (COW) */
char comm[TASK_COMM_LEN]; /* executable name excluding path
- access with [gs]et_task_comm (which lock
it with task_lock())
- initialized normally by setup_new_exec */
/* file system info */
int link_count, total_link_count;
#ifdef CONFIG_SYSVIPC
/* ipc stuff */
struct sysv_sem sysvsem;
struct sysv_shm sysvshm;
#endif
#ifdef CONFIG_DETECT_HUNG_TASK
/* hung task detection */
unsigned long last_switch_count;
#endif
/* CPU-specific state of this task */
struct thread_struct thread;
/* filesystem information */
struct fs_struct *fs;
/* open file information */
struct files_struct *files;
/* namespaces */
struct nsproxy *nsproxy;
/* signal handlers */
struct signal_struct *signal;
struct sighand_struct *sighand;
sigset_t blocked, real_blocked;
sigset_t saved_sigmask; /* restored if set_restore_sigmask() was used */
struct sigpending pending;
unsigned long sas_ss_sp;
size_t sas_ss_size;
int (*notifier)(void *priv);
void *notifier_data;
sigset_t *notifier_mask;
struct callback_head *task_works;
struct audit_context *audit_context;
#ifdef CONFIG_AUDITSYSCALL
kuid_t loginuid;
unsigned int sessionid;
#endif
struct seccomp seccomp;
/* Thread group tracking */
u32 parent_exec_id;
u32 self_exec_id;
/* Protection of (de-)allocation: mm, files, fs, tty, keyrings, mems_allowed,
* mempolicy */
spinlock_t alloc_lock;
/* Protection of the PI data structures: */
raw_spinlock_t pi_lock;
#ifdef CONFIG_RT_MUTEXES
/* PI waiters blocked on a rt_mutex held by this task */
struct rb_root pi_waiters;
struct rb_node *pi_waiters_leftmost;
/* Deadlock detection and priority inheritance handling */
struct rt_mutex_waiter *pi_blocked_on;
#endif
#ifdef CONFIG_DEBUG_MUTEXES
/* mutex deadlock detection */
struct mutex_waiter *blocked_on;
#endif
#ifdef CONFIG_TRACE_IRQFLAGS
unsigned int irq_events;
unsigned long hardirq_enable_ip;
unsigned long hardirq_disable_ip;
unsigned int hardirq_enable_event;
unsigned int hardirq_disable_event;
int hardirqs_enabled;
int hardirq_context;
unsigned long softirq_disable_ip;
unsigned long softirq_enable_ip;
unsigned int softirq_disable_event;
unsigned int softirq_enable_event;
int softirqs_enabled;
int softirq_context;
#endif
#ifdef CONFIG_LOCKDEP
# define MAX_LOCK_DEPTH 48UL
u64 curr_chain_key;
int lockdep_depth;
unsigned int lockdep_recursion;
struct held_lock held_locks[MAX_LOCK_DEPTH];
gfp_t lockdep_reclaim_gfp;
#endif
/* journalling filesystem info */
void *journal_info;
/* stacked block device info */
struct bio_list *bio_list;
#ifdef CONFIG_BLOCK
/* stack plugging */
struct blk_plug *plug;
#endif
/* VM state */
struct reclaim_state *reclaim_state;
struct backing_dev_info *backing_dev_info;
struct io_context *io_context;
unsigned long ptrace_message;
siginfo_t *last_siginfo; /* For ptrace use. */
struct task_io_accounting ioac;
#if defined(CONFIG_TASK_XACCT)
u64 acct_rss_mem1; /* accumulated rss usage */
u64 acct_vm_mem1; /* accumulated virtual memory usage */
cputime_t acct_timexpd; /* stime + utime since last update */
#endif
#ifdef CONFIG_CPUSETS
nodemask_t mems_allowed; /* Protected by alloc_lock */
seqcount_t mems_allowed_seq; /* Seqence no to catch updates */
int cpuset_mem_spread_rotor;
int cpuset_slab_spread_rotor;
#endif
#ifdef CONFIG_CGROUPS
/* Control Group info protected by css_set_lock */
struct css_set __rcu *cgroups;
/* cg_list protected by css_set_lock and tsk->alloc_lock */
struct list_head cg_list;
#endif
#ifdef CONFIG_FUTEX
struct robust_list_head __user *robust_list;
#ifdef CONFIG_COMPAT
struct compat_robust_list_head __user *compat_robust_list;
#endif
struct list_head pi_state_list;
struct futex_pi_state *pi_state_cache;
#endif
#ifdef CONFIG_PERF_EVENTS
struct perf_event_context *perf_event_ctxp[perf_nr_task_contexts];
struct mutex perf_event_mutex;
struct list_head perf_event_list;
#endif
#ifdef CONFIG_DEBUG_PREEMPT
unsigned long preempt_disable_ip;
#endif
#ifdef CONFIG_NUMA
struct mempolicy *mempolicy; /* Protected by alloc_lock */
short il_next;
short pref_node_fork;
#endif
#ifdef CONFIG_NUMA_BALANCING
int numa_scan_seq;
unsigned int numa_scan_period;
unsigned int numa_scan_period_max;
int numa_preferred_nid;
unsigned long numa_migrate_retry;
u64 node_stamp; /* migration stamp */
u64 last_task_numa_placement;
u64 last_sum_exec_runtime;
struct callback_head numa_work;
struct list_head numa_entry;
struct numa_group *numa_group;
/*
* Exponential decaying average of faults on a per-node basis.
* Scheduling placement decisions are made based on the these counts.
* The values remain static for the duration of a PTE scan
*/
unsigned long *numa_faults_memory;
unsigned long total_numa_faults;
/*
* numa_faults_buffer records faults per node during the current
* scan window. When the scan completes, the counts in
* numa_faults_memory decay and these values are copied.
*/
unsigned long *numa_faults_buffer_memory;
/*
* Track the nodes the process was running on when a NUMA hinting
* fault was incurred.
*/
unsigned long *numa_faults_cpu;
unsigned long *numa_faults_buffer_cpu;
/*
* numa_faults_locality tracks if faults recorded during the last
* scan window were remote/local. The task scan period is adapted
* based on the locality of the faults with different weights
* depending on whether they were shared or private faults
*/
unsigned long numa_faults_locality[2];
unsigned long numa_pages_migrated;
#endif /* CONFIG_NUMA_BALANCING */
struct rcu_head rcu;
/*
* cache last used pipe for splice
*/
struct pipe_inode_info *splice_pipe;
struct page_frag task_frag;
#ifdef CONFIG_TASK_DELAY_ACCT
struct task_delay_info *delays;
#endif
#ifdef CONFIG_FAULT_INJECTION
int make_it_fail;
#endif
/*
* when (nr_dirtied >= nr_dirtied_pause), it's time to call
* balance_dirty_pages() for some dirty throttling pause
*/
int nr_dirtied;
int nr_dirtied_pause;
unsigned long dirty_paused_when; /* start of a write-and-pause period */
#ifdef CONFIG_LATENCYTOP
int latency_record_count;
struct latency_record latency_record[LT_SAVECOUNT];
#endif
/*
* time slack values; these are used to round up poll() and
* select() etc timeout values. These are in nanoseconds.
*/
unsigned long timer_slack_ns;
unsigned long default_timer_slack_ns;
#ifdef CONFIG_FUNCTION_GRAPH_TRACER
/* Index of current stored address in ret_stack */
int curr_ret_stack;
/* Stack of return addresses for return function tracing */
struct ftrace_ret_stack *ret_stack;
/* time stamp for last schedule */
unsigned long long ftrace_timestamp;
/*
* Number of functions that haven't been traced
* because of depth overrun.
*/
atomic_t trace_overrun;
/* Pause for the tracing */
atomic_t tracing_graph_pause;
#endif
#ifdef CONFIG_TRACING
/* state flags for use by tracers */
unsigned long trace;
/* bitmask and counter of trace recursion */
unsigned long trace_recursion;
#endif /* CONFIG_TRACING */
#ifdef CONFIG_MEMCG /* memcg uses this to do batch job */
unsigned int memcg_kmem_skip_account;
struct memcg_oom_info {
struct mem_cgroup *memcg;
gfp_t gfp_mask;
int order;
unsigned int may_oom:1;
} memcg_oom;
#endif
#ifdef CONFIG_UPROBES
struct uprobe_task *utask;
#endif
#if defined(CONFIG_BCACHE) || defined(CONFIG_BCACHE_MODULE)
unsigned int sequential_io;
unsigned int sequential_io_avg;
#endif
#ifdef CONFIG_SDP
unsigned int sensitive;
#endif
};
/* Future-safe accessor for struct task_struct's cpus_allowed. */
#define tsk_cpus_allowed(tsk) (&(tsk)->cpus_allowed)
#define TNF_MIGRATED 0x01
#define TNF_NO_GROUP 0x02
#define TNF_SHARED 0x04
#define TNF_FAULT_LOCAL 0x08
#ifdef CONFIG_NUMA_BALANCING
extern void task_numa_fault(int last_node, int node, int pages, int flags);
extern pid_t task_numa_group_id(struct task_struct *p);
extern void set_numabalancing_state(bool enabled);
extern void task_numa_free(struct task_struct *p);
extern bool should_numa_migrate_memory(struct task_struct *p, struct page *page,
int src_nid, int dst_cpu);
#else
static inline void task_numa_fault(int last_node, int node, int pages,
int flags)
{
}
static inline pid_t task_numa_group_id(struct task_struct *p)
{
return 0;
}
static inline void set_numabalancing_state(bool enabled)
{
}
static inline void task_numa_free(struct task_struct *p)
{
}
static inline bool should_numa_migrate_memory(struct task_struct *p,
struct page *page, int src_nid, int dst_cpu)
{
return true;
}
#endif
static inline struct pid *task_pid(struct task_struct *task)
{
return task->pids[PIDTYPE_PID].pid;
}
static inline struct pid *task_tgid(struct task_struct *task)
{
return task->group_leader->pids[PIDTYPE_PID].pid;
}
/*
* Without tasklist or rcu lock it is not safe to dereference
* the result of task_pgrp/task_session even if task == current,
* we can race with another thread doing sys_setsid/sys_setpgid.
*/
static inline struct pid *task_pgrp(struct task_struct *task)
{
return task->group_leader->pids[PIDTYPE_PGID].pid;
}
static inline struct pid *task_session(struct task_struct *task)
{
return task->group_leader->pids[PIDTYPE_SID].pid;
}
struct pid_namespace;
/*
* the helpers to get the task's different pids as they are seen
* from various namespaces
*
* task_xid_nr() : global id, i.e. the id seen from the init namespace;
* task_xid_vnr() : virtual id, i.e. the id seen from the pid namespace of
* current.
* task_xid_nr_ns() : id seen from the ns specified;
*
* set_task_vxid() : assigns a virtual id to a task;
*
* see also pid_nr() etc in include/linux/pid.h
*/
pid_t __task_pid_nr_ns(struct task_struct *task, enum pid_type type,
struct pid_namespace *ns);
static inline pid_t task_pid_nr(struct task_struct *tsk)
{
return tsk->pid;
}
static inline pid_t task_pid_nr_ns(struct task_struct *tsk,
struct pid_namespace *ns)
{
return __task_pid_nr_ns(tsk, PIDTYPE_PID, ns);
}
static inline pid_t task_pid_vnr(struct task_struct *tsk)
{
return __task_pid_nr_ns(tsk, PIDTYPE_PID, NULL);
}
static inline pid_t task_tgid_nr(struct task_struct *tsk)
{
return tsk->tgid;
}
pid_t task_tgid_nr_ns(struct task_struct *tsk, struct pid_namespace *ns);
static inline pid_t task_tgid_vnr(struct task_struct *tsk)
{
return pid_vnr(task_tgid(tsk));
}
static inline int pid_alive(const struct task_struct *p);
static inline pid_t task_ppid_nr_ns(const struct task_struct *tsk, struct pid_namespace *ns)
{
pid_t pid = 0;
rcu_read_lock();
if (pid_alive(tsk))
pid = task_tgid_nr_ns(rcu_dereference(tsk->real_parent), ns);
rcu_read_unlock();
return pid;
}
static inline pid_t task_ppid_nr(const struct task_struct *tsk)
{
return task_ppid_nr_ns(tsk, &init_pid_ns);
}
static inline pid_t task_pgrp_nr_ns(struct task_struct *tsk,
struct pid_namespace *ns)
{
return __task_pid_nr_ns(tsk, PIDTYPE_PGID, ns);
}
static inline pid_t task_pgrp_vnr(struct task_struct *tsk)
{
return __task_pid_nr_ns(tsk, PIDTYPE_PGID, NULL);
}
static inline pid_t task_session_nr_ns(struct task_struct *tsk,
struct pid_namespace *ns)
{
return __task_pid_nr_ns(tsk, PIDTYPE_SID, ns);
}
static inline pid_t task_session_vnr(struct task_struct *tsk)
{
return __task_pid_nr_ns(tsk, PIDTYPE_SID, NULL);
}
/* obsolete, do not use */
static inline pid_t task_pgrp_nr(struct task_struct *tsk)
{
return task_pgrp_nr_ns(tsk, &init_pid_ns);
}
/**
* pid_alive - check that a task structure is not stale
* @p: Task structure to be checked.
*
* Test if a process is not yet dead (at most zombie state)
* If pid_alive fails, then pointers within the task structure
* can be stale and must not be dereferenced.
*
* Return: 1 if the process is alive. 0 otherwise.
*/
static inline int pid_alive(const struct task_struct *p)
{
return p->pids[PIDTYPE_PID].pid != NULL;
}
/**
* is_global_init - check if a task structure is init
* @tsk: Task structure to be checked.
*
* Check if a task structure is the first user space task the kernel created.
*
* Return: 1 if the task structure is init. 0 otherwise.
*/
static inline int is_global_init(struct task_struct *tsk)
{
return tsk->pid == 1;
}
extern struct pid *cad_pid;
extern void free_task(struct task_struct *tsk);
#define get_task_struct(tsk) do { atomic_inc(&(tsk)->usage); } while(0)
extern void __put_task_struct(struct task_struct *t);
static inline void put_task_struct(struct task_struct *t)
{
if (atomic_dec_and_test(&t->usage))
__put_task_struct(t);
}
#ifdef CONFIG_VIRT_CPU_ACCOUNTING_GEN
extern void task_cputime(struct task_struct *t,
cputime_t *utime, cputime_t *stime);
extern void task_cputime_scaled(struct task_struct *t,
cputime_t *utimescaled, cputime_t *stimescaled);
extern cputime_t task_gtime(struct task_struct *t);
#else
static inline void task_cputime(struct task_struct *t,
cputime_t *utime, cputime_t *stime)
{
if (utime)
*utime = t->utime;
if (stime)
*stime = t->stime;
}
static inline void task_cputime_scaled(struct task_struct *t,
cputime_t *utimescaled,
cputime_t *stimescaled)
{
if (utimescaled)
*utimescaled = t->utimescaled;
if (stimescaled)
*stimescaled = t->stimescaled;
}
static inline cputime_t task_gtime(struct task_struct *t)
{
return t->gtime;
}
#endif
extern void task_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st);
extern void thread_group_cputime_adjusted(struct task_struct *p, cputime_t *ut, cputime_t *st);
extern int task_free_register(struct notifier_block *n);
extern int task_free_unregister(struct notifier_block *n);
/*
* Per process flags
*/
#define PF_EXITING 0x00000004 /* getting shut down */
#define PF_EXITPIDONE 0x00000008 /* pi exit done on shut down */
#define PF_VCPU 0x00000010 /* I'm a virtual CPU */
#define PF_WQ_WORKER 0x00000020 /* I'm a workqueue worker */
#define PF_FORKNOEXEC 0x00000040 /* forked but didn't exec */
#define PF_MCE_PROCESS 0x00000080 /* process policy on mce errors */
#define PF_SUPERPRIV 0x00000100 /* used super-user privileges */
#define PF_DUMPCORE 0x00000200 /* dumped core */
#define PF_SIGNALED 0x00000400 /* killed by a signal */
#define PF_MEMALLOC 0x00000800 /* Allocating memory */
#define PF_NPROC_EXCEEDED 0x00001000 /* set_user noticed that RLIMIT_NPROC was exceeded */
#define PF_USED_MATH 0x00002000 /* if unset the fpu must be initialized before use */
#define PF_USED_ASYNC 0x00004000 /* used async_schedule*(), used by module init */
#define PF_NOFREEZE 0x00008000 /* this thread should not be frozen */
#define PF_FROZEN 0x00010000 /* frozen for system suspend */
#define PF_FSTRANS 0x00020000 /* inside a filesystem transaction */
#define PF_KSWAPD 0x00040000 /* I am kswapd */
#define PF_MEMALLOC_NOIO 0x00080000 /* Allocating memory without IO involved */
#define PF_LESS_THROTTLE 0x00100000 /* Throttle me less: I clean memory */
#define PF_KTHREAD 0x00200000 /* I am a kernel thread */
#define PF_RANDOMIZE 0x00400000 /* randomize virtual address space */
#define PF_SWAPWRITE 0x00800000 /* Allowed to write to swap */
#define PF_NO_SETAFFINITY 0x04000000 /* Userland is not allowed to meddle with cpus_allowed */
#define PF_MCE_EARLY 0x08000000 /* Early kill for mce process policy */
#define PF_MUTEX_TESTER 0x20000000 /* Thread belongs to the rt mutex tester */
#define PF_FREEZER_SKIP 0x40000000 /* Freezer should not count it as freezable */
#define PF_SUSPEND_TASK 0x80000000 /* this thread called freeze_processes and should not be frozen */
/*
* Only the _current_ task can read/write to tsk->flags, but other
* tasks can access tsk->flags in readonly mode for example
* with tsk_used_math (like during threaded core dumping).
* There is however an exception to this rule during ptrace
* or during fork: the ptracer task is allowed to write to the
* child->flags of its traced child (same goes for fork, the parent
* can write to the child->flags), because we're guaranteed the
* child is not running and in turn not changing child->flags
* at the same time the parent does it.
*/
#define clear_stopped_child_used_math(child) do { (child)->flags &= ~PF_USED_MATH; } while (0)
#define set_stopped_child_used_math(child) do { (child)->flags |= PF_USED_MATH; } while (0)
#define clear_used_math() clear_stopped_child_used_math(current)
#define set_used_math() set_stopped_child_used_math(current)
#define conditional_stopped_child_used_math(condition, child) \
do { (child)->flags &= ~PF_USED_MATH, (child)->flags |= (condition) ? PF_USED_MATH : 0; } while (0)
#define conditional_used_math(condition) \
conditional_stopped_child_used_math(condition, current)
#define copy_to_stopped_child_used_math(child) \
do { (child)->flags &= ~PF_USED_MATH, (child)->flags |= current->flags & PF_USED_MATH; } while (0)
/* NOTE: this will return 0 or PF_USED_MATH, it will never return 1 */
#define tsk_used_math(p) ((p)->flags & PF_USED_MATH)
#define used_math() tsk_used_math(current)
/* __GFP_IO isn't allowed if PF_MEMALLOC_NOIO is set in current->flags
* __GFP_FS is also cleared as it implies __GFP_IO.
*/
static inline gfp_t memalloc_noio_flags(gfp_t flags)
{
if (unlikely(current->flags & PF_MEMALLOC_NOIO))
flags &= ~(__GFP_IO | __GFP_FS);
return flags;
}
static inline unsigned int memalloc_noio_save(void)
{
unsigned int flags = current->flags & PF_MEMALLOC_NOIO;
current->flags |= PF_MEMALLOC_NOIO;
return flags;
}
static inline void memalloc_noio_restore(unsigned int flags)
{
current->flags = (current->flags & ~PF_MEMALLOC_NOIO) | flags;
}
/* Per-process atomic flags. */
#define PFA_NO_NEW_PRIVS 0 /* May not gain new privileges. */
#define PFA_SPREAD_PAGE 1 /* Spread page cache over cpuset */
#define PFA_SPREAD_SLAB 2 /* Spread some slab caches over cpuset */
#define TASK_PFA_TEST(name, func) \
static inline bool task_##func(struct task_struct *p) \
{ return test_bit(PFA_##name, &p->atomic_flags); }
#define TASK_PFA_SET(name, func) \
static inline void task_set_##func(struct task_struct *p) \
{ set_bit(PFA_##name, &p->atomic_flags); }
#define TASK_PFA_CLEAR(name, func) \
static inline void task_clear_##func(struct task_struct *p) \
{ clear_bit(PFA_##name, &p->atomic_flags); }
TASK_PFA_TEST(NO_NEW_PRIVS, no_new_privs)
TASK_PFA_SET(NO_NEW_PRIVS, no_new_privs)
TASK_PFA_TEST(SPREAD_PAGE, spread_page)
TASK_PFA_SET(SPREAD_PAGE, spread_page)
TASK_PFA_CLEAR(SPREAD_PAGE, spread_page)
TASK_PFA_TEST(SPREAD_SLAB, spread_slab)
TASK_PFA_SET(SPREAD_SLAB, spread_slab)
TASK_PFA_CLEAR(SPREAD_SLAB, spread_slab)
/*
* task->jobctl flags
*/
#define JOBCTL_STOP_SIGMASK 0xffff /* signr of the last group stop */
#define JOBCTL_STOP_DEQUEUED_BIT 16 /* stop signal dequeued */
#define JOBCTL_STOP_PENDING_BIT 17 /* task should stop for group stop */
#define JOBCTL_STOP_CONSUME_BIT 18 /* consume group stop count */
#define JOBCTL_TRAP_STOP_BIT 19 /* trap for STOP */
#define JOBCTL_TRAP_NOTIFY_BIT 20 /* trap for NOTIFY */
#define JOBCTL_TRAPPING_BIT 21 /* switching to TRACED */
#define JOBCTL_LISTENING_BIT 22 /* ptracer is listening for events */
#define JOBCTL_STOP_DEQUEUED (1 << JOBCTL_STOP_DEQUEUED_BIT)
#define JOBCTL_STOP_PENDING (1 << JOBCTL_STOP_PENDING_BIT)
#define JOBCTL_STOP_CONSUME (1 << JOBCTL_STOP_CONSUME_BIT)
#define JOBCTL_TRAP_STOP (1 << JOBCTL_TRAP_STOP_BIT)
#define JOBCTL_TRAP_NOTIFY (1 << JOBCTL_TRAP_NOTIFY_BIT)
#define JOBCTL_TRAPPING (1 << JOBCTL_TRAPPING_BIT)
#define JOBCTL_LISTENING (1 << JOBCTL_LISTENING_BIT)
#define JOBCTL_TRAP_MASK (JOBCTL_TRAP_STOP | JOBCTL_TRAP_NOTIFY)
#define JOBCTL_PENDING_MASK (JOBCTL_STOP_PENDING | JOBCTL_TRAP_MASK)
extern bool task_set_jobctl_pending(struct task_struct *task,
unsigned int mask);
extern void task_clear_jobctl_trapping(struct task_struct *task);
extern void task_clear_jobctl_pending(struct task_struct *task,
unsigned int mask);
static inline void rcu_copy_process(struct task_struct *p)
{
#ifdef CONFIG_PREEMPT_RCU
p->rcu_read_lock_nesting = 0;
p->rcu_read_unlock_special.s = 0;
p->rcu_blocked_node = NULL;
INIT_LIST_HEAD(&p->rcu_node_entry);
#endif /* #ifdef CONFIG_PREEMPT_RCU */
#ifdef CONFIG_TASKS_RCU
p->rcu_tasks_holdout = false;
INIT_LIST_HEAD(&p->rcu_tasks_holdout_list);
p->rcu_tasks_idle_cpu = -1;
#endif /* #ifdef CONFIG_TASKS_RCU */
}
static inline void tsk_restore_flags(struct task_struct *task,
unsigned long orig_flags, unsigned long flags)
{
task->flags &= ~flags;
task->flags |= orig_flags & flags;
}
#ifdef CONFIG_SMP
extern void do_set_cpus_allowed(struct task_struct *p,
const struct cpumask *new_mask);
extern int set_cpus_allowed_ptr(struct task_struct *p,
const struct cpumask *new_mask);
#else
static inline void do_set_cpus_allowed(struct task_struct *p,
const struct cpumask *new_mask)
{
}
static inline int set_cpus_allowed_ptr(struct task_struct *p,
const struct cpumask *new_mask)
{
if (!cpumask_test_cpu(0, new_mask))
return -EINVAL;
return 0;
}
#endif
#ifdef CONFIG_NO_HZ_COMMON
void calc_load_enter_idle(void);
void calc_load_exit_idle(void);
#else
static inline void calc_load_enter_idle(void) { }
static inline void calc_load_exit_idle(void) { }
#endif /* CONFIG_NO_HZ_COMMON */
#ifndef CONFIG_CPUMASK_OFFSTACK
static inline int set_cpus_allowed(struct task_struct *p, cpumask_t new_mask)
{
return set_cpus_allowed_ptr(p, &new_mask);
}
#endif
/*
* Do not use outside of architecture code which knows its limitations.
*
* sched_clock() has no promise of monotonicity or bounded drift between
* CPUs, use (which you should not) requires disabling IRQs.
*
* Please use one of the three interfaces below.
*/
extern unsigned long long notrace sched_clock(void);
/*
* See the comment in kernel/sched/clock.c
*/
extern u64 cpu_clock(int cpu);
extern u64 local_clock(void);
extern u64 sched_clock_cpu(int cpu);
extern void sched_clock_init(void);
#ifndef CONFIG_HAVE_UNSTABLE_SCHED_CLOCK
static inline void sched_clock_tick(void)
{
}
static inline void sched_clock_idle_sleep_event(void)
{
}
static inline void sched_clock_idle_wakeup_event(u64 delta_ns)
{
}
#else
/*
* Architectures can set this to 1 if they have specified
* CONFIG_HAVE_UNSTABLE_SCHED_CLOCK in their arch Kconfig,
* but then during bootup it turns out that sched_clock()
* is reliable after all:
*/
extern int sched_clock_stable(void);
extern void set_sched_clock_stable(void);
extern void clear_sched_clock_stable(void);
extern void sched_clock_tick(void);
extern void sched_clock_idle_sleep_event(void);
extern void sched_clock_idle_wakeup_event(u64 delta_ns);
#endif
#ifdef CONFIG_IRQ_TIME_ACCOUNTING
/*
* An i/f to runtime opt-in for irq time accounting based off of sched_clock.
* The reason for this explicit opt-in is not to have perf penalty with
* slow sched_clocks.
*/
extern void enable_sched_clock_irqtime(void);
extern void disable_sched_clock_irqtime(void);
#else
static inline void enable_sched_clock_irqtime(void) {}
static inline void disable_sched_clock_irqtime(void) {}
#endif
extern unsigned long long
task_sched_runtime(struct task_struct *task);
/* sched_exec is called by processes performing an exec */
#ifdef CONFIG_SMP
extern void sched_exec(void);
#else
#define sched_exec() {}
#endif
extern void sched_clock_idle_sleep_event(void);
extern void sched_clock_idle_wakeup_event(u64 delta_ns);
#ifdef CONFIG_HOTPLUG_CPU
extern void idle_task_exit(void);
#else
static inline void idle_task_exit(void) {}
#endif
#if defined(CONFIG_NO_HZ_COMMON) && defined(CONFIG_SMP)
extern void wake_up_nohz_cpu(int cpu);
#else
static inline void wake_up_nohz_cpu(int cpu) { }
#endif
#ifdef CONFIG_NO_HZ_FULL
extern bool sched_can_stop_tick(void);
extern u64 scheduler_tick_max_deferment(void);
#else
static inline bool sched_can_stop_tick(void) { return false; }
#endif
#ifdef CONFIG_SCHED_AUTOGROUP
extern void sched_autogroup_create_attach(struct task_struct *p);
extern void sched_autogroup_detach(struct task_struct *p);
extern void sched_autogroup_fork(struct signal_struct *sig);
extern void sched_autogroup_exit(struct signal_struct *sig);
#ifdef CONFIG_PROC_FS
extern void proc_sched_autogroup_show_task(struct task_struct *p, struct seq_file *m);
extern int proc_sched_autogroup_set_nice(struct task_struct *p, int nice);
#endif
#else
static inline void sched_autogroup_create_attach(struct task_struct *p) { }
static inline void sched_autogroup_detach(struct task_struct *p) { }
static inline void sched_autogroup_fork(struct signal_struct *sig) { }
static inline void sched_autogroup_exit(struct signal_struct *sig) { }
#endif
extern int yield_to(struct task_struct *p, bool preempt);
extern void set_user_nice(struct task_struct *p, long nice);
extern int task_prio(const struct task_struct *p);
/**
* task_nice - return the nice value of a given task.
* @p: the task in question.
*
* Return: The nice value [ -20 ... 0 ... 19 ].
*/
static inline int task_nice(const struct task_struct *p)
{
return PRIO_TO_NICE((p)->static_prio);
}
extern int can_nice(const struct task_struct *p, const int nice);
extern int task_curr(const struct task_struct *p);
extern int idle_cpu(int cpu);
extern int sched_setscheduler(struct task_struct *, int,
const struct sched_param *);
extern int sched_setscheduler_nocheck(struct task_struct *, int,
const struct sched_param *);
extern int sched_setattr(struct task_struct *,
const struct sched_attr *);
extern struct task_struct *idle_task(int cpu);
/**
* is_idle_task - is the specified task an idle task?
* @p: the task in question.
*
* Return: 1 if @p is an idle task. 0 otherwise.
*/
static inline bool is_idle_task(const struct task_struct *p)
{
return p->pid == 0;
}
extern struct task_struct *curr_task(int cpu);
extern void set_curr_task(int cpu, struct task_struct *p);
void yield(void);
/*
* The default (Linux) execution domain.
*/
extern struct exec_domain default_exec_domain;
union thread_union {
struct thread_info thread_info;
unsigned long stack[THREAD_SIZE/sizeof(long)];
};
#ifndef __HAVE_ARCH_KSTACK_END
static inline int kstack_end(void *addr)
{
/* Reliable end of stack detection:
* Some APM bios versions misalign the stack
*/
return !(((unsigned long)addr+sizeof(void*)-1) & (THREAD_SIZE-sizeof(void*)));
}
#endif
extern union thread_union init_thread_union;
extern struct task_struct init_task;
extern struct mm_struct init_mm;
extern struct pid_namespace init_pid_ns;
/*
* find a task by one of its numerical ids
*
* find_task_by_pid_ns():
* finds a task by its pid in the specified namespace
* find_task_by_vpid():
* finds a task by its virtual pid
*
* see also find_vpid() etc in include/linux/pid.h
*/
extern struct task_struct *find_task_by_vpid(pid_t nr);
extern struct task_struct *find_task_by_pid_ns(pid_t nr,
struct pid_namespace *ns);
/* per-UID process charging. */
extern struct user_struct * alloc_uid(kuid_t);
static inline struct user_struct *get_uid(struct user_struct *u)
{
atomic_inc(&u->__count);
return u;
}
extern void free_uid(struct user_struct *);
#include <asm/current.h>
extern void xtime_update(unsigned long ticks);
extern int wake_up_state(struct task_struct *tsk, unsigned int state);
extern int wake_up_process(struct task_struct *tsk);
extern void wake_up_new_task(struct task_struct *tsk);
#ifdef CONFIG_SMP
extern void kick_process(struct task_struct *tsk);
#else
static inline void kick_process(struct task_struct *tsk) { }
#endif
extern int sched_fork(unsigned long clone_flags, struct task_struct *p);
extern void sched_dead(struct task_struct *p);
extern void proc_caches_init(void);
extern void flush_signals(struct task_struct *);
extern void __flush_signals(struct task_struct *);
extern void ignore_signals(struct task_struct *);
extern void flush_signal_handlers(struct task_struct *, int force_default);
extern int dequeue_signal(struct task_struct *tsk, sigset_t *mask, siginfo_t *info);
static inline int dequeue_signal_lock(struct task_struct *tsk, sigset_t *mask, siginfo_t *info)
{
unsigned long flags;
int ret;
spin_lock_irqsave(&tsk->sighand->siglock, flags);
ret = dequeue_signal(tsk, mask, info);
spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
return ret;
}
extern void block_all_signals(int (*notifier)(void *priv), void *priv,
sigset_t *mask);
extern void unblock_all_signals(void);
extern void release_task(struct task_struct * p);
extern int send_sig_info(int, struct siginfo *, struct task_struct *);
extern int force_sigsegv(int, struct task_struct *);
extern int force_sig_info(int, struct siginfo *, struct task_struct *);
extern int __kill_pgrp_info(int sig, struct siginfo *info, struct pid *pgrp);
extern int kill_pid_info(int sig, struct siginfo *info, struct pid *pid);
extern int kill_pid_info_as_cred(int, struct siginfo *, struct pid *,
const struct cred *, u32);
extern int kill_pgrp(struct pid *pid, int sig, int priv);
extern int kill_pid(struct pid *pid, int sig, int priv);
extern int kill_proc_info(int, struct siginfo *, pid_t);
extern __must_check bool do_notify_parent(struct task_struct *, int);
extern void __wake_up_parent(struct task_struct *p, struct task_struct *parent);
extern void force_sig(int, struct task_struct *);
extern int send_sig(int, struct task_struct *, int);
extern int zap_other_threads(struct task_struct *p);
extern struct sigqueue *sigqueue_alloc(void);
extern void sigqueue_free(struct sigqueue *);
extern int send_sigqueue(struct sigqueue *, struct task_struct *, int group);
extern int do_sigaction(int, struct k_sigaction *, struct k_sigaction *);
static inline void restore_saved_sigmask(void)
{
if (test_and_clear_restore_sigmask())
__set_current_blocked(¤t->saved_sigmask);
}
static inline sigset_t *sigmask_to_save(void)
{
sigset_t *res = ¤t->blocked;
if (unlikely(test_restore_sigmask()))
res = ¤t->saved_sigmask;
return res;
}
static inline int kill_cad_pid(int sig, int priv)
{
return kill_pid(cad_pid, sig, priv);
}
/* These can be the second arg to send_sig_info/send_group_sig_info. */
#define SEND_SIG_NOINFO ((struct siginfo *) 0)
#define SEND_SIG_PRIV ((struct siginfo *) 1)
#define SEND_SIG_FORCED ((struct siginfo *) 2)
/*
* True if we are on the alternate signal stack.
*/
static inline int on_sig_stack(unsigned long sp)
{
#ifdef CONFIG_STACK_GROWSUP
return sp >= current->sas_ss_sp &&
sp - current->sas_ss_sp < current->sas_ss_size;
#else
return sp > current->sas_ss_sp &&
sp - current->sas_ss_sp <= current->sas_ss_size;
#endif
}
static inline int sas_ss_flags(unsigned long sp)
{
if (!current->sas_ss_size)
return SS_DISABLE;
return on_sig_stack(sp) ? SS_ONSTACK : 0;
}
static inline unsigned long sigsp(unsigned long sp, struct ksignal *ksig)
{
if (unlikely((ksig->ka.sa.sa_flags & SA_ONSTACK)) && ! sas_ss_flags(sp))
#ifdef CONFIG_STACK_GROWSUP
return current->sas_ss_sp;
#else
return current->sas_ss_sp + current->sas_ss_size;
#endif
return sp;
}
/*
* Routines for handling mm_structs
*/
extern struct mm_struct * mm_alloc(void);
/* mmdrop drops the mm and the page tables */
extern void __mmdrop(struct mm_struct *);
static inline void mmdrop(struct mm_struct * mm)
{
if (unlikely(atomic_dec_and_test(&mm->mm_count)))
__mmdrop(mm);
}
/* mmput gets rid of the mappings and all user-space */
extern void mmput(struct mm_struct *);
/* Grab a reference to a task's mm, if it is not already going away */
extern struct mm_struct *get_task_mm(struct task_struct *task);
/*
* Grab a reference to a task's mm, if it is not already going away
* and ptrace_may_access with the mode parameter passed to it
* succeeds.
*/
extern struct mm_struct *mm_access(struct task_struct *task, unsigned int mode);
/* Remove the current tasks stale references to the old mm_struct */
extern void mm_release(struct task_struct *, struct mm_struct *);
extern int copy_thread(unsigned long, unsigned long, unsigned long,
struct task_struct *);
extern void flush_thread(void);
extern void exit_thread(void);
extern void exit_files(struct task_struct *);
extern void __cleanup_sighand(struct sighand_struct *);
extern void exit_itimers(struct signal_struct *);
extern void flush_itimer_signals(void);
extern void do_group_exit(int);
extern int do_execve(struct filename *,
const char __user * const __user *,
const char __user * const __user *);
extern long do_fork(unsigned long, unsigned long, unsigned long, int __user *, int __user *);
struct task_struct *fork_idle(int);
extern pid_t kernel_thread(int (*fn)(void *), void *arg, unsigned long flags);
extern void __set_task_comm(struct task_struct *tsk, const char *from, bool exec);
static inline void set_task_comm(struct task_struct *tsk, const char *from)
{
__set_task_comm(tsk, from, false);
}
extern char *get_task_comm(char *to, struct task_struct *tsk);
#ifdef CONFIG_SMP
void scheduler_ipi(void);
extern unsigned long wait_task_inactive(struct task_struct *, long match_state);
#else
static inline void scheduler_ipi(void) { }
static inline unsigned long wait_task_inactive(struct task_struct *p,
long match_state)
{
return 1;
}
#endif
#define next_task(p) \
list_entry_rcu((p)->tasks.next, struct task_struct, tasks)
#define for_each_process(p) \
for (p = &init_task ; (p = next_task(p)) != &init_task ; )
extern bool current_is_single_threaded(void);
/*
* Careful: do_each_thread/while_each_thread is a double loop so
* 'break' will not work as expected - use goto instead.
*/
#define do_each_thread(g, t) \
for (g = t = &init_task ; (g = t = next_task(g)) != &init_task ; ) do
#define while_each_thread(g, t) \
while ((t = next_thread(t)) != g)
#define __for_each_thread(signal, t) \
list_for_each_entry_rcu(t, &(signal)->thread_head, thread_node)
#define for_each_thread(p, t) \
__for_each_thread((p)->signal, t)
/* Careful: this is a double loop, 'break' won't work as expected. */
#define for_each_process_thread(p, t) \
for_each_process(p) for_each_thread(p, t)
static inline int get_nr_threads(struct task_struct *tsk)
{
return tsk->signal->nr_threads;
}
static inline bool thread_group_leader(struct task_struct *p)
{
return p->exit_signal >= 0;
}
/* Do to the insanities of de_thread it is possible for a process
* to have the pid of the thread group leader without actually being
* the thread group leader. For iteration through the pids in proc
* all we care about is that we have a task with the appropriate
* pid, we don't actually care if we have the right task.
*/
static inline bool has_group_leader_pid(struct task_struct *p)
{
return task_pid(p) == p->signal->leader_pid;
}
static inline
bool same_thread_group(struct task_struct *p1, struct task_struct *p2)
{
return p1->signal == p2->signal;
}
static inline struct task_struct *next_thread(const struct task_struct *p)
{
return list_entry_rcu(p->thread_group.next,
struct task_struct, thread_group);
}
static inline int thread_group_empty(struct task_struct *p)
{
return list_empty(&p->thread_group);
}
#define delay_group_leader(p) \
(thread_group_leader(p) && !thread_group_empty(p))
/*
* Protects ->fs, ->files, ->mm, ->group_info, ->comm, keyring
* subscriptions and synchronises with wait4(). Also used in procfs. Also
* pins the final release of task.io_context. Also protects ->cpuset and
* ->cgroup.subsys[]. And ->vfork_done.
*
* Nests both inside and outside of read_lock(&tasklist_lock).
* It must not be nested with write_lock_irq(&tasklist_lock),
* neither inside nor outside.
*/
static inline void task_lock(struct task_struct *p)
{
spin_lock(&p->alloc_lock);
}
static inline void task_unlock(struct task_struct *p)
{
spin_unlock(&p->alloc_lock);
}
extern struct sighand_struct *__lock_task_sighand(struct task_struct *tsk,
unsigned long *flags);
static inline struct sighand_struct *lock_task_sighand(struct task_struct *tsk,
unsigned long *flags)
{
struct sighand_struct *ret;
ret = __lock_task_sighand(tsk, flags);
(void)__cond_lock(&tsk->sighand->siglock, ret);
return ret;
}
static inline void unlock_task_sighand(struct task_struct *tsk,
unsigned long *flags)
{
spin_unlock_irqrestore(&tsk->sighand->siglock, *flags);
}
#ifdef CONFIG_CGROUPS
static inline void threadgroup_change_begin(struct task_struct *tsk)
{
down_read(&tsk->signal->group_rwsem);
}
static inline void threadgroup_change_end(struct task_struct *tsk)
{
up_read(&tsk->signal->group_rwsem);
}
/**
* threadgroup_lock - lock threadgroup
* @tsk: member task of the threadgroup to lock
*
* Lock the threadgroup @tsk belongs to. No new task is allowed to enter
* and member tasks aren't allowed to exit (as indicated by PF_EXITING) or
* change ->group_leader/pid. This is useful for cases where the threadgroup
* needs to stay stable across blockable operations.
*
* fork and exit paths explicitly call threadgroup_change_{begin|end}() for
* synchronization. While held, no new task will be added to threadgroup
* and no existing live task will have its PF_EXITING set.
*
* de_thread() does threadgroup_change_{begin|end}() when a non-leader
* sub-thread becomes a new leader.
*/
static inline void threadgroup_lock(struct task_struct *tsk)
{
down_write(&tsk->signal->group_rwsem);
}
/**
* threadgroup_unlock - unlock threadgroup
* @tsk: member task of the threadgroup to unlock
*
* Reverse threadgroup_lock().
*/
static inline void threadgroup_unlock(struct task_struct *tsk)
{
up_write(&tsk->signal->group_rwsem);
}
#else
static inline void threadgroup_change_begin(struct task_struct *tsk) {}
static inline void threadgroup_change_end(struct task_struct *tsk) {}
static inline void threadgroup_lock(struct task_struct *tsk) {}
static inline void threadgroup_unlock(struct task_struct *tsk) {}
#endif
#ifndef __HAVE_THREAD_FUNCTIONS
#define task_thread_info(task) ((struct thread_info *)(task)->stack)
#define task_stack_page(task) ((task)->stack)
static inline void setup_thread_stack(struct task_struct *p, struct task_struct *org)
{
*task_thread_info(p) = *task_thread_info(org);
task_thread_info(p)->task = p;
}
/*
* Return the address of the last usable long on the stack.
*
* When the stack grows down, this is just above the thread
* info struct. Going any lower will corrupt the threadinfo.
*
* When the stack grows up, this is the highest address.
* Beyond that position, we corrupt data on the next page.
*/
static inline unsigned long *end_of_stack(struct task_struct *p)
{
#ifdef CONFIG_STACK_GROWSUP
return (unsigned long *)((unsigned long)task_thread_info(p) + THREAD_SIZE) - 1;
#else
return (unsigned long *)(task_thread_info(p) + 1);
#endif
}
#endif
#define task_stack_end_corrupted(task) \
(*(end_of_stack(task)) != STACK_END_MAGIC)
static inline int object_is_on_stack(void *obj)
{
void *stack = task_stack_page(current);
return (obj >= stack) && (obj < (stack + THREAD_SIZE));
}
extern void thread_info_cache_init(void);
#ifdef CONFIG_DEBUG_STACK_USAGE
static inline unsigned long stack_not_used(struct task_struct *p)
{
unsigned long *n = end_of_stack(p);
do { /* Skip over canary */
n++;
} while (!*n);
return (unsigned long)n - (unsigned long)end_of_stack(p);
}
#endif
extern void set_task_stack_end_magic(struct task_struct *tsk);
/* set thread flags in other task's structures
* - see asm/thread_info.h for TIF_xxxx flags available
*/
static inline void set_tsk_thread_flag(struct task_struct *tsk, int flag)
{
set_ti_thread_flag(task_thread_info(tsk), flag);
}
static inline void clear_tsk_thread_flag(struct task_struct *tsk, int flag)
{
clear_ti_thread_flag(task_thread_info(tsk), flag);
}
static inline int test_and_set_tsk_thread_flag(struct task_struct *tsk, int flag)
{
return test_and_set_ti_thread_flag(task_thread_info(tsk), flag);
}
static inline int test_and_clear_tsk_thread_flag(struct task_struct *tsk, int flag)
{
return test_and_clear_ti_thread_flag(task_thread_info(tsk), flag);
}
static inline int test_tsk_thread_flag(struct task_struct *tsk, int flag)
{
return test_ti_thread_flag(task_thread_info(tsk), flag);
}
static inline void set_tsk_need_resched(struct task_struct *tsk)
{
set_tsk_thread_flag(tsk,TIF_NEED_RESCHED);
}
static inline void clear_tsk_need_resched(struct task_struct *tsk)
{
clear_tsk_thread_flag(tsk,TIF_NEED_RESCHED);
}
static inline int test_tsk_need_resched(struct task_struct *tsk)
{
return unlikely(test_tsk_thread_flag(tsk,TIF_NEED_RESCHED));
}
static inline int restart_syscall(void)
{
set_tsk_thread_flag(current, TIF_SIGPENDING);
return -ERESTARTNOINTR;
}
static inline int signal_pending(struct task_struct *p)
{
return unlikely(test_tsk_thread_flag(p,TIF_SIGPENDING));
}
static inline int __fatal_signal_pending(struct task_struct *p)
{
return unlikely(sigismember(&p->pending.signal, SIGKILL));
}
static inline int fatal_signal_pending(struct task_struct *p)
{
return signal_pending(p) && __fatal_signal_pending(p);
}
static inline int signal_pending_state(long state, struct task_struct *p)
{
if (!(state & (TASK_INTERRUPTIBLE | TASK_WAKEKILL)))
return 0;
if (!signal_pending(p))
return 0;
return (state & TASK_INTERRUPTIBLE) || __fatal_signal_pending(p);
}
/*
* cond_resched() and cond_resched_lock(): latency reduction via
* explicit rescheduling in places that are safe. The return
* value indicates whether a reschedule was done in fact.
* cond_resched_lock() will drop the spinlock before scheduling,
* cond_resched_softirq() will enable bhs before scheduling.
*/
extern int _cond_resched(void);
#define cond_resched() ({ \
__might_sleep(__FILE__, __LINE__, 0); \
_cond_resched(); \
})
extern int __cond_resched_lock(spinlock_t *lock);
#ifdef CONFIG_PREEMPT_COUNT
#define PREEMPT_LOCK_OFFSET PREEMPT_OFFSET
#else
#define PREEMPT_LOCK_OFFSET 0
#endif
#define cond_resched_lock(lock) ({ \
__might_sleep(__FILE__, __LINE__, PREEMPT_LOCK_OFFSET); \
__cond_resched_lock(lock); \
})
extern int __cond_resched_softirq(void);
#define cond_resched_softirq() ({ \
__might_sleep(__FILE__, __LINE__, SOFTIRQ_DISABLE_OFFSET); \
__cond_resched_softirq(); \
})
static inline void cond_resched_rcu(void)
{
#if defined(CONFIG_DEBUG_ATOMIC_SLEEP) || !defined(CONFIG_PREEMPT_RCU)
rcu_read_unlock();
cond_resched();
rcu_read_lock();
#endif
}
/*
* Does a critical section need to be broken due to another
* task waiting?: (technically does not depend on CONFIG_PREEMPT,
* but a general need for low latency)
*/
static inline int spin_needbreak(spinlock_t *lock)
{
#ifdef CONFIG_PREEMPT
return spin_is_contended(lock);
#else
return 0;
#endif
}
/*
* Idle thread specific functions to determine the need_resched
* polling state.
*/
#ifdef TIF_POLLING_NRFLAG
static inline int tsk_is_polling(struct task_struct *p)
{
return test_tsk_thread_flag(p, TIF_POLLING_NRFLAG);
}
static inline void __current_set_polling(void)
{
set_thread_flag(TIF_POLLING_NRFLAG);
}
static inline bool __must_check current_set_polling_and_test(void)
{
__current_set_polling();
/*
* Polling state must be visible before we test NEED_RESCHED,
* paired by resched_curr()
*/
smp_mb__after_atomic();
return unlikely(tif_need_resched());
}
static inline void __current_clr_polling(void)
{
clear_thread_flag(TIF_POLLING_NRFLAG);
}
static inline bool __must_check current_clr_polling_and_test(void)
{
__current_clr_polling();
/*
* Polling state must be visible before we test NEED_RESCHED,
* paired by resched_curr()
*/
smp_mb__after_atomic();
return unlikely(tif_need_resched());
}
#else
static inline int tsk_is_polling(struct task_struct *p) { return 0; }
static inline void __current_set_polling(void) { }
static inline void __current_clr_polling(void) { }
static inline bool __must_check current_set_polling_and_test(void)
{
return unlikely(tif_need_resched());
}
static inline bool __must_check current_clr_polling_and_test(void)
{
return unlikely(tif_need_resched());
}
#endif
static inline void current_clr_polling(void)
{
__current_clr_polling();
/*
* Ensure we check TIF_NEED_RESCHED after we clear the polling bit.
* Once the bit is cleared, we'll get IPIs with every new
* TIF_NEED_RESCHED and the IPI handler, scheduler_ipi(), will also
* fold.
*/
smp_mb(); /* paired with resched_curr() */
preempt_fold_need_resched();
}
static __always_inline bool need_resched(void)
{
return unlikely(tif_need_resched());
}
/*
* Thread group CPU time accounting.
*/
void thread_group_cputime(struct task_struct *tsk, struct task_cputime *times);
void thread_group_cputimer(struct task_struct *tsk, struct task_cputime *times);
static inline void thread_group_cputime_init(struct signal_struct *sig)
{
raw_spin_lock_init(&sig->cputimer.lock);
}
/*
* Reevaluate whether the task has signals pending delivery.
* Wake the task if so.
* This is required every time the blocked sigset_t changes.
* callers must hold sighand->siglock.
*/
extern void recalc_sigpending_and_wake(struct task_struct *t);
extern void recalc_sigpending(void);
extern void signal_wake_up_state(struct task_struct *t, unsigned int state);
static inline void signal_wake_up(struct task_struct *t, bool resume)
{
signal_wake_up_state(t, resume ? TASK_WAKEKILL : 0);
}
static inline void ptrace_signal_wake_up(struct task_struct *t, bool resume)
{
signal_wake_up_state(t, resume ? __TASK_TRACED : 0);
}
/*
* Wrappers for p->thread_info->cpu access. No-op on UP.
*/
#ifdef CONFIG_SMP
static inline unsigned int task_cpu(const struct task_struct *p)
{
return task_thread_info(p)->cpu;
}
static inline int task_node(const struct task_struct *p)
{
return cpu_to_node(task_cpu(p));
}
extern void set_task_cpu(struct task_struct *p, unsigned int cpu);
#else
static inline unsigned int task_cpu(const struct task_struct *p)
{
return 0;
}
static inline void set_task_cpu(struct task_struct *p, unsigned int cpu)
{
}
#endif /* CONFIG_SMP */
extern long sched_setaffinity(pid_t pid, const struct cpumask *new_mask);
extern long sched_getaffinity(pid_t pid, struct cpumask *mask);
#ifdef CONFIG_CGROUP_SCHED
extern struct task_group root_task_group;
#endif /* CONFIG_CGROUP_SCHED */
extern int task_can_switch_user(struct user_struct *up,
struct task_struct *tsk);
#ifdef CONFIG_TASK_XACCT
static inline void add_rchar(struct task_struct *tsk, ssize_t amt)
{
tsk->ioac.rchar += amt;
}
static inline void add_wchar(struct task_struct *tsk, ssize_t amt)
{
tsk->ioac.wchar += amt;
}
static inline void inc_syscr(struct task_struct *tsk)
{
tsk->ioac.syscr++;
}
static inline void inc_syscw(struct task_struct *tsk)
{
tsk->ioac.syscw++;
}
#else
static inline void add_rchar(struct task_struct *tsk, ssize_t amt)
{
}
static inline void add_wchar(struct task_struct *tsk, ssize_t amt)
{
}
static inline void inc_syscr(struct task_struct *tsk)
{
}
static inline void inc_syscw(struct task_struct *tsk)
{
}
#endif
#ifndef TASK_SIZE_OF
#define TASK_SIZE_OF(tsk) TASK_SIZE
#endif
#ifdef CONFIG_MEMCG
extern void mm_update_next_owner(struct mm_struct *mm);
#else
static inline void mm_update_next_owner(struct mm_struct *mm)
{
}
#endif /* CONFIG_MEMCG */
static inline unsigned long task_rlimit(const struct task_struct *tsk,
unsigned int limit)
{
return ACCESS_ONCE(tsk->signal->rlim[limit].rlim_cur);
}
static inline unsigned long task_rlimit_max(const struct task_struct *tsk,
unsigned int limit)
{
return ACCESS_ONCE(tsk->signal->rlim[limit].rlim_max);
}
static inline unsigned long rlimit(unsigned int limit)
{
return task_rlimit(current, limit);
}
static inline unsigned long rlimit_max(unsigned int limit)
{
return task_rlimit_max(current, limit);
}
#if defined(CONFIG_HP_EVENT_THREAD_GROUP) || defined(CONFIG_HP_EVENT_HMP_SYSTEM_LOAD)
void hp_event_enqueue_entity(struct sched_entity *se, int flags);
void hp_event_dequeue_entity(struct sched_entity *se, int flags);
void hp_event_update_entity_load(struct sched_entity *se);
void hp_event_switched_from(struct sched_entity *se);
void hp_event_do_exit(struct task_struct *p);
void hp_event_update_rq_load(int cpu);
extern unsigned int *pcpu_efficiency;
#else
static inline void hp_event_update_entity_load(struct sched_entity *se) { };
static inline void hp_event_enqueue_entity(struct sched_entity *se, int flags) { };
static inline void hp_event_dequeue_entity(struct sched_entity *se, int flags) { };
static inline void hp_event_switched_from(struct sched_entity *se) { };
static inline void hp_event_do_exit(struct task_struct *p) { };
static inline void hp_event_update_rq_load(int cpu) { };
#endif
#if defined(CONFIG_HP_EVENT_HMP_SYSTEM_LOAD)
extern int hp_sysload_to_quad_ratio;
extern int hp_sysload_to_dual_ratio;
extern int hp_sysload_param_calc(void);
extern int hp_little_multiplier_ratio;
#endif
#endif
| morogoku/MoRoKernel-S7-v2 | include/linux/sched.h | C | gpl-2.0 | 91,018 |
#include "../../StdAfx.h"
#include "PlaylistView_Win.h"
#include "../../resource.h"
#include <Strings.h>
#include "../../Controller/SPlayerDefs.h"
#include "../../Controller/PlayerPreference.h"
#include "../../Controller/PlaylistController.h"
PlaylistView::PlaylistView(void) :
m_caption_height(::GetSystemMetrics(SM_CYICON) * 7 / 8),
m_bottom_height(::GetSystemMetrics(SM_CYICON)),
m_button_height(::GetSystemMetrics(SM_CYICON) * 2 / 3),
m_padding(::GetSystemMetrics(SM_CXICON) / 4),
m_entry_height(::GetSystemMetrics(SM_CYSMICON) * 5 / 4),
m_entry_padding(::GetSystemMetrics(SM_CYSMICON) / 8),
m_basecolor(RGB(78, 78, 78)),
m_basecolor2(RGB(32, 32, 32)),
m_basecolor3(RGB(128, 128, 128)),
m_basecolor4(RGB(192, 192, 192)),
m_textcolor(RGB(255, 255, 255)),
m_textcolor_hilite(RGB(255, 200, 20))
{
WTL::CLogFont lf;
lf.SetMessageBoxFont();
m_font_normal.CreateFontIndirect(&lf);
lf.SetBold();
m_font_bold.CreateFontIndirect(&lf);
lf.SetMessageBoxFont();
wcscpy_s(lf.lfFaceName, 32, L"Webdings");
lf.lfHeight = lf.lfHeight * 5 / 4;
m_font_symbol.CreateFontIndirect(&lf);
WTL::CString text;
text.LoadString(IDS_PLAYLIST);
Strings::Split(text, L"|", m_texts);
m_br_list.CreateSolidBrush(m_basecolor);
}
void PlaylistView::Refresh()
{
m_list.SetCount(PlaylistController::GetInstance()->GetListDisplay().size());
m_list.Invalidate();
}
int PlaylistView::OnCreate(LPCREATESTRUCT lpcs)
{
m_list.Create(m_hWnd, NULL, NULL,
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE | WS_VSCROLL |
LBS_NODATA | LBS_OWNERDRAWFIXED | LBS_NOTIFY, 0, IDC_LISTBOX);
m_btn_load.Create(m_hWnd, NULL, NULL,
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE, 0, IDC_BTNLOAD);
m_btn_save.Create(m_hWnd, NULL, NULL,
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE, 0, IDC_BTNSAVE);
m_btn_clear.Create(m_hWnd, NULL, NULL,
WS_CHILD | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_VISIBLE, 0, IDC_BTNCLEAR);
Refresh();
return 0;
}
void PlaylistView::OnPaint(WTL::CDCHandle dc)
{
RECT rc;
GetClientRect(&rc);
WTL::CPaintDC pdc(m_hWnd);
WTL::CMemoryDC mdc(pdc, pdc.m_ps.rcPaint);
_PaintWorker(mdc, rc);
}
BOOL PlaylistView::OnEraseBkgnd(WTL::CDCHandle dc)
{
return TRUE;
}
void PlaylistView::OnSize(UINT nType, CSize size)
{
HDWP hdwp = ::BeginDeferWindowPos(4);
::DeferWindowPos(hdwp, m_list, NULL, m_padding, m_caption_height + m_padding,
size.cx - m_padding * 2, size.cy - m_bottom_height - m_caption_height,
SWP_NOACTIVATE | SWP_NOZORDER);
int btn_top = size.cy - m_bottom_height + (m_bottom_height - m_button_height) / 2;
int btn_width = size.cx / 4;
::DeferWindowPos(hdwp, m_btn_load, NULL, m_padding, btn_top, btn_width, m_button_height,
SWP_NOACTIVATE | SWP_NOZORDER);
::DeferWindowPos(hdwp, m_btn_save, NULL, m_padding * 3 / 2 + btn_width, btn_top, btn_width, m_button_height,
SWP_NOACTIVATE | SWP_NOZORDER);
::DeferWindowPos(hdwp, m_btn_clear, NULL, size.cx - btn_width - m_padding, btn_top, btn_width, m_button_height,
SWP_NOACTIVATE | SWP_NOZORDER);
::EndDeferWindowPos(hdwp);
}
HBRUSH PlaylistView::OnColorListBox(WTL::CDCHandle dc, WTL::CListBox listBox)
{
return m_br_list;
}
LRESULT PlaylistView::OnLbnDblClk(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
PlayerPreference* pref = PlayerPreference::GetInstance();
pref->SetIntVar(INTVAR_PLAYLIST_CURRENT, m_list.GetCurSel());
::SendMessage(reinterpret_cast<HWND>(pref->GetInt64Var(INT64VAR_MAINWINDOW)),
WM_SPLAYER_CMD, CMD_OPEN_CURRENTPLAYLISTITEM, 0);
return 0;
}
LRESULT PlaylistView::OnBtnLoad(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
PlayerPreference* pref = PlayerPreference::GetInstance();
::SendMessage(reinterpret_cast<HWND>(pref->GetInt64Var(INT64VAR_MAINWINDOW)),
WM_SPLAYER_CMD, CMD_OPEN_PLAYLIST, 0);
return 0;
}
LRESULT PlaylistView::OnBtnSave(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
return 0;
}
LRESULT PlaylistView::OnBtnClear(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
return 0;
}
void PlaylistView::DrawItem(LPDRAWITEMSTRUCT lpdis)
{
std::vector<std::wstring> list =
PlaylistController::GetInstance()->GetListDisplay();
if (lpdis->itemID < list.size() && lpdis->itemID >= 0)
{
RECT& rc = lpdis->rcItem;
WTL::CDCHandle dc(lpdis->hDC);
WTL::CBrush bkgnd_brush;
bkgnd_brush.CreateSolidBrush(m_basecolor);
if (lpdis->itemState & ODS_SELECTED)
{
WTL::CPen pen;
pen.CreatePen(PS_SOLID, 1, m_basecolor4);
HPEN old_pen = dc.SelectPen(pen);
_DrawRectNoCorner(dc, rc, 1);
dc.SelectPen(old_pen);
rc.left++;
rc.top++;
rc.bottom--;
rc.right--;
_FillGradient(dc, rc, m_basecolor3, m_basecolor);
}
else
dc.FillRect(&rc, bkgnd_brush);
rc.left += m_entry_padding * 7;
bool iscurrent = PlayerPreference::GetInstance()->GetIntVar(INTVAR_PLAYLIST_CURRENT) == lpdis->itemID;
HFONT old_font = iscurrent ? dc.SelectFont(m_font_bold) : dc.SelectFont(m_font_normal);
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(iscurrent ? m_textcolor_hilite : m_textcolor);
dc.DrawText(list[lpdis->itemID].c_str(), -1, &rc, DT_LEFT | DT_SINGLELINE | DT_VCENTER);
if (iscurrent)
{
dc.SetTextColor(m_textcolor_hilite);
dc.SelectFont(m_font_symbol);
rc.left -= m_entry_padding * 7;
dc.DrawText(L"4", -1, &rc, DT_LEFT | DT_SINGLELINE | DT_VCENTER);
}
dc.SelectFont(old_font);
}
}
void PlaylistView::MeasureItem(LPMEASUREITEMSTRUCT lpmis)
{
lpmis->itemHeight = m_entry_height;
}
DWORD PlaylistView::OnPrePaint(int idCtrl, LPNMCUSTOMDRAW lpnmcd)
{
WTL::CDCHandle dc(lpnmcd->hdc);
RECT& rc = lpnmcd->rc;
bool is_hot = (lpnmcd->uItemState & CDIS_HOT) ? true : false;
bool is_pressed = (lpnmcd->uItemState & CDIS_SELECTED) ? true : false;
switch (idCtrl)
{
case IDC_BTNCLEAR:
case IDC_BTNLOAD:
case IDC_BTNSAVE:
{
WTL::CPen pen_dark, pen_bright, pen_vbright;
pen_dark.CreatePen(PS_SOLID, 1, m_basecolor2);
pen_bright.CreatePen(PS_SOLID, 1, m_basecolor3);
pen_vbright.CreatePen(PS_SOLID, 1, is_hot ? m_textcolor_hilite : m_basecolor4);
dc.FillRect(&rc, m_br_list);
HPEN old_pen = dc.SelectPen(pen_dark);
_DrawRectNoCorner(dc, rc, 2);
rc.left++;
rc.right--;
rc.top++;
rc.bottom--;
dc.SelectPen(pen_bright);
dc.Rectangle(&rc);
dc.SelectPen(pen_vbright);
dc.MoveTo(rc.left, rc.top);
dc.LineTo(rc.right, rc.top);
dc.SelectPen(old_pen);
rc.left++;
rc.right--;
rc.top++;
if (is_pressed)
rc.bottom--;
_FillGradient(dc, rc, is_pressed ? m_basecolor : m_basecolor3,
is_pressed ? m_basecolor3 : m_basecolor);
}
break;
}
HFONT old_font = dc.SelectFont(m_font_normal);
dc.SetTextColor(is_hot ? m_textcolor_hilite : m_textcolor);
dc.SetBkMode(TRANSPARENT);
switch (idCtrl)
{
case IDC_BTNLOAD:
dc.DrawText(m_texts[1].c_str(), -1, &rc, DT_VCENTER | DT_SINGLELINE | DT_CENTER);
break;
case IDC_BTNSAVE:
dc.DrawText(m_texts[2].c_str(), -1, &rc, DT_VCENTER | DT_SINGLELINE | DT_CENTER);
break;
case IDC_BTNCLEAR:
dc.DrawText(m_texts[3].c_str(), -1, &rc, DT_VCENTER | DT_SINGLELINE | DT_CENTER);
break;
}
dc.SelectFont(old_font);
return CDRF_SKIPDEFAULT;
}
void PlaylistView::_PaintWorker(HDC hdc, RECT rc)
{
WTL::CDCHandle dc(hdc);
WTL::CBrush bkgnd;
bkgnd.CreateSolidBrush(m_basecolor);
dc.FillRect(&rc, bkgnd);
RECT rc_grad1 = { rc.left, rc.top, rc.right, rc.top + m_caption_height - m_padding / 2 };
RECT rc_grad2 = { rc.left, rc.top + m_caption_height - m_padding / 2, rc.right,
rc.top + m_caption_height };
_FillGradient(dc, rc_grad1, m_basecolor3, m_basecolor);
_FillGradient(dc, rc_grad2, m_basecolor2, m_basecolor);
HFONT old_font = dc.SelectFont(m_font_normal);
RECT rc_text = { rc.left + m_padding, rc.top, rc.right - m_padding, rc.top + m_caption_height - m_padding / 2 };
dc.SetBkMode(TRANSPARENT);
dc.SetTextColor(m_textcolor);
dc.DrawText(m_texts[0].c_str(), -1, &rc_text, DT_LEFT | DT_VCENTER | DT_SINGLELINE);
dc.SelectFont(old_font);
}
void PlaylistView::_FillGradient(HDC hdc, RECT rc, int color_tl, int color_br, bool vert /* = true */)
{
WTL::CDCHandle dc(hdc);
TRIVERTEX v[2];
GRADIENT_RECT grc;
v[0].x = rc.left;
v[0].y = rc.top;
v[0].Red = GetRValue(color_tl) << 8;
v[0].Green = GetGValue(color_tl) << 8;
v[0].Blue = GetBValue(color_tl) << 8;
v[0].Alpha = 0x0000;
v[1].x = rc.right;
v[1].y = rc.bottom;
v[1].Red = GetRValue(color_br) << 8;
v[1].Green = GetGValue(color_br) << 8;
v[1].Blue = GetBValue(color_br) << 8;
v[1].Alpha = 0x0000;
grc.UpperLeft = 0;
grc.LowerRight = 1;
dc.GradientFill(v, 2, &grc, 1, vert ? GRADIENT_FILL_RECT_V : GRADIENT_FILL_RECT_H);
}
void PlaylistView::_DrawRectNoCorner(WTL::CDCHandle& dc, RECT& rc, int offset)
{
dc.MoveTo(rc.left + offset, rc.top);
dc.LineTo(rc.right - offset, rc.top);
dc.MoveTo(rc.right - 1, rc.top + offset);
dc.LineTo(rc.right - 1, rc.bottom - offset);
dc.MoveTo(rc.right - 1 - offset, rc.bottom - 1);
dc.LineTo(rc.left + offset - 1, rc.bottom - 1);
dc.MoveTo(rc.left, rc.bottom - 1 - offset);
dc.LineTo(rc.left, rc.top + offset - 1);
}
| systembugtj/playasa | src/Source/apps/mplayerc/UserInterface/Renderer/PlaylistView_Win.cc | C++ | gpl-2.0 | 8,995 |
/***************************************************************************
* Copyright (C) 2010 by Jean-Baptiste Mardelle (jb@kdenlive.org) *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA *
***************************************************************************/
#include "capturehandler.h"
#include "kdenlivesettings.h"
CaptureHandler::CaptureHandler(QVBoxLayout *lay, QWidget *parent):
m_layout(lay),
m_parent(parent),
m_analyseFrame(KdenliveSettings::analyse_stopmotion())
{
}
CaptureHandler::~CaptureHandler()
{
stopCapture();
}
void CaptureHandler::stopCapture()
{
}
//static
void CaptureHandler::uyvy2rgb(unsigned char *yuv_buffer, unsigned char *rgb_buffer, int width, int height)
{
int len;
int rgb_ptr, y_ptr;
len = width * height / 2;
rgb_ptr = 0;
y_ptr = 0;
for (int t = 0; t < len; ++t) { /* process 2 pixels at a time */
/* Compute parts of the UV components */
int U = yuv_buffer[y_ptr];
int Y = yuv_buffer[y_ptr+1];
int V = yuv_buffer[y_ptr+2];
int Y2 = yuv_buffer[y_ptr+3];
y_ptr += 4;
int r = ((298 * (Y - 16) + 409 * (V - 128) + 128) >> 8);
int g = ((298 * (Y - 16) - 100 * (U - 128) - 208 * (V - 128) + 128) >> 8);
int b = ((298 * (Y - 16) + 516 * (U - 128) + 128) >> 8);
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
rgb_buffer[rgb_ptr] = b;
rgb_buffer[rgb_ptr+1] = g;
rgb_buffer[rgb_ptr+2] = r;
rgb_buffer[rgb_ptr+3] = 255;
rgb_ptr += 4;
/*r = 1.164*(Y2-16) + 1.596*(V-128);
g = 1.164*(Y2-16) - 0.813*(V-128) - 0.391*(U-128);
b = 1.164*(Y2-16) + 2.018*(U-128);*/
r = ((298 * (Y2 - 16) + 409 * (V - 128) + 128) >> 8);
g = ((298 * (Y2 - 16) - 100 * (U - 128) - 208 * (V - 128) + 128) >> 8);
b = ((298 * (Y2 - 16) + 516 * (U - 128) + 128) >> 8);
if (r > 255) r = 255;
if (g > 255) g = 255;
if (b > 255) b = 255;
if (r < 0) r = 0;
if (g < 0) g = 0;
if (b < 0) b = 0;
rgb_buffer[rgb_ptr] = b;
rgb_buffer[rgb_ptr+1] = g;
rgb_buffer[rgb_ptr+2] = r;
rgb_buffer[rgb_ptr+3] = 255;
rgb_ptr += 4;
}
}
| rugubara/kdenlive-15.08.1 | src/stopmotion/capturehandler.cpp | C++ | gpl-2.0 | 3,528 |
<?php
/**
* A manager to handle project objects
*
* @package : Museo test for Naoned
*
* @author Vibby <vincent.beauvivre@gmail.com>
*/
namespace Museo\Lib;
class objectManager
{
protected $db = null;
public function __construct(\PDO $db = null) {
$this->db = $db;
}
// sanitize data (to run before creating object)
public function sanitizeData($data) {
$filters = $this->getFilters();
// verify that only accepted data are coming
$unwantedData = array_diff_key($data, $filters);
if (!empty($unwantedData)) {
throw new \exception("Object sanitization failed because of extra parameter(s)");
}
// sanitize data
$data = filter_var_array($data, $filters);
return $data;
}
// prepare the query to insert the created object
public function initInsert($data) {
$query = "INSERT INTO `".$this->getTableName()."` SET ";
$i = 0;
$directFields = array_intersect(array_keys($this->getFilters()), $this->getFields());
unset ($directFields[array_search('id',$directFields)]);
foreach ($directFields as $fieldName) {
if ($i) { $query .= ", "; }
$query .= $fieldName . " = :param" . $i ;
$i++;
}
$prepared = $this->db->prepare($query);
$i = 0;
foreach ($directFields as $fieldName) {
$prepared->bindParam(":param" . $i, $data[$fieldName]);
$i++;
}
return $prepared;
}
// prepare the query to update the modified object
public function initUpdate($data) {
$query = "UPDATE `".$this->getTableName()."` SET ";
$i = 0;
$directFields = array_intersect(array_keys($this->getFilters()), $this->getFields());
unset ($directFields[array_search('id',$directFields)]);
foreach ($directFields as $fieldName) {
if ($i) { $query .= ", "; }
$query .= $fieldName . " = :param" . $i ;
$i++;
}
$query .= " WHERE id = :id ";
// prepare query
$prepared = $this->db->prepare($query);
$i = 0;
foreach ($directFields as $fieldName) {
$prepared->bindParam(":param" . $i, $data[$fieldName]);
$i++;
}
$prepared->bindParam(":id", $data['id'], \PDO::PARAM_INT);
return $prepared;
}
}
| vibby/Museo | Museo/Lib/ObjectManager.php | PHP | gpl-2.0 | 2,093 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Sun Feb 15 12:27:17 PST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.hadoop.SolrInputDocumentWritable (Solr 5.0.0 API)</title>
<meta name="date" content="2015-02-15">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.hadoop.SolrInputDocumentWritable (Solr 5.0.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/hadoop/class-use/SolrInputDocumentWritable.html" target="_top">Frames</a></li>
<li><a href="SolrInputDocumentWritable.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.hadoop.SolrInputDocumentWritable" class="title">Uses of Class<br>org.apache.solr.hadoop.SolrInputDocumentWritable</h2>
</div>
<div class="classUseContainer">
<ul class="blockList">
<li class="blockList">
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing packages, and an explanation">
<caption><span>Packages that use <a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">SolrInputDocumentWritable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Package</th>
<th class="colLast" scope="col">Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><a href="#org.apache.solr.hadoop">org.apache.solr.hadoop</a></td>
<td class="colLast">
<div class="block"><a href="../../../../../org/apache/solr/hadoop/MapReduceIndexerTool.html" title="class in org.apache.solr.hadoop"><code>MapReduceIndexerTool</code></a> and related code.</div>
</td>
</tr>
</tbody>
</table>
</li>
<li class="blockList">
<ul class="blockList">
<li class="blockList"><a name="org.apache.solr.hadoop">
<!-- -->
</a>
<h3>Uses of <a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">SolrInputDocumentWritable</a> in <a href="../../../../../org/apache/solr/hadoop/package-summary.html">org.apache.solr.hadoop</a></h3>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Methods in <a href="../../../../../org/apache/solr/hadoop/package-summary.html">org.apache.solr.hadoop</a> with parameters of type <a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">SolrInputDocumentWritable</a></span><span class="tabEnd"> </span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tbody>
<tr class="altColor">
<td class="colFirst"><code>int</code></td>
<td class="colLast"><span class="strong">SolrCloudPartitioner.</span><code><strong><a href="../../../../../org/apache/solr/hadoop/SolrCloudPartitioner.html#getPartition(org.apache.hadoop.io.Text, org.apache.solr.hadoop.SolrInputDocumentWritable, int)">getPartition</a></strong>(org.apache.hadoop.io.Text key,
<a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">SolrInputDocumentWritable</a> value,
int numPartitions)</code> </td>
</tr>
</tbody>
</table>
<table border="0" cellpadding="3" cellspacing="0" summary="Use table, listing methods, and an explanation">
<caption><span>Method parameters in <a href="../../../../../org/apache/solr/hadoop/package-summary.html">org.apache.solr.hadoop</a> with type arguments of type <a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">SolrInputDocumentWritable</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 void</code></td>
<td class="colLast"><span class="strong">SolrReducer.</span><code><strong><a href="../../../../../org/apache/solr/hadoop/SolrReducer.html#reduce(org.apache.hadoop.io.Text, java.lang.Iterable, org.apache.hadoop.mapreduce.Reducer.Context)">reduce</a></strong>(org.apache.hadoop.io.Text key,
<a href="http://download.oracle.com/javase/7/docs/api/java/lang/Iterable.html?is-external=true" title="class or interface in java.lang">Iterable</a><<a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">SolrInputDocumentWritable</a>> values,
org.apache.hadoop.mapreduce.Reducer.Context context)</code> </td>
</tr>
</tbody>
</table>
</li>
</ul>
</li>
</ul>
</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/hadoop/SolrInputDocumentWritable.html" title="class in org.apache.solr.hadoop">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/hadoop/class-use/SolrInputDocumentWritable.html" target="_top">Frames</a></li>
<li><a href="SolrInputDocumentWritable.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| annieweng/solr_example | solr-5.0.0/docs/solr-map-reduce/org/apache/solr/hadoop/class-use/SolrInputDocumentWritable.html | HTML | gpl-2.0 | 8,712 |
<?php // $Id: node.tpl.php,v 1.1 2009/07/03 07:40:11 agileware Exp $ ?>
<div id="node-<?php print $node->nid; ?>" class="node<?php if ($sticky) { print ' sticky'; } ?><?php if (!$status) { print ' node-unpublished'; } ?> Post">
<div class="Post-tl"></div>
<div class="Post-tr"></div>
<div class="Post-bl"></div>
<div class="Post-br"></div>
<div class="Post-tc"></div>
<div class="Post-bc"></div>
<div class="Post-cl"></div>
<div class="Post-cr"></div>
<div class="Post-cc"></div>
<div class="Post-body">
<div class="Post-inner">
<?php if ($teaser): ?>
<h2 class="PostHeaderIcon-wrapper"> <span class="PostHeader"><a href="<?php echo $node_url; ?>" title="<?php echo $title; ?>"><?php echo $title; ?></a></span></h2>
<?php endif; ?>
<div class="PostHeaderIcons metadata-icons">
<?php if ($submitted) { echo art_submitted_worker($submitted, $date, $name);} ?>
</div>
<div class="PostContent">
<div class="article">
<?php hide($content['comments']);
hide($content['links']);
print render($content);?>
<?php if (isset($content['links']['node'])) { print '<div class="read_more">'.render($content['links']['node']).'</div>'; }?>
</div>
</div>
<div class="cleared"></div>
<div class="PostFooterIcons metadata-icons">
<?php print render($content['links']); ?>
<?php print render ($content['comments']); ?>
<?php if (!empty($terms)) { print render($terms); } ?>
</div>
</div>
</div>
</div>
| robertkein/dieta-dev | sites/all/themes/energetic/templates/node.tpl.php | PHP | gpl-2.0 | 1,561 |
#!/bin/bash
# exp/resnet1b: num-iters=130 nj=2..4 num-params=1.3M dim=96->10 combine=-0.04->-0.04 loglike:train/valid[85,129,final]=(-0.049,-0.044,-0.036/-0.098,-0.085,-0.076) accuracy:train/valid[85,129,final]=(0.9904,0.9908,0.9940/0.9764,0.9804,0.9831)
# This setup is based on the one in cifar/v1/local/nnet3/run_resnet_1{a,b}.sh.
# We are reducing the number of epochs quite a bit, since there is so much
# more data here; and reducing the proportional-shrink value since there is
# more data.
# The augmentation options are changed, with no horizontal flip, less vertical
# shift, and much less horizontal shift.
# Set -e here so that we catch if any executable fails immediately
set -euo pipefail
# training options
stage=0
train_stage=-10
srand=0
reporting_email=
affix=1b
# End configuration section.
echo "$0 $@" # Print the command line for logging
. ./cmd.sh
. ./path.sh
. ./utils/parse_options.sh
if ! cuda-compiled; then
cat <<EOF && exit 1
This script is intended to be used with GPUs but you have not compiled Kaldi with CUDA
If you want to use GPUs (and have them), go to src/, and configure and make on a machine
where "nvcc" is installed.
EOF
fi
dir=exp/resnet${affix}
egs=exp/egs
if [ ! -d $egs ]; then
echo "$0: expected directory $egs to exist. Run the get_egs.sh commands in the"
echo " run.sh before this script."
exit 1
fi
# check that the expected files are in the egs directory.
for f in $egs/egs.1.ark $egs/train_diagnostic.egs $egs/valid_diagnostic.egs $egs/combine.egs \
$egs/info/feat_dim $egs/info/left_context $egs/info/right_context \
$egs/info/output_dim; do
if [ ! -e $f ]; then
echo "$0: expected file $f to exist."
exit 1;
fi
done
mkdir -p $dir/log
if [ $stage -le 1 ]; then
mkdir -p $dir
echo "$0: creating neural net configs using the xconfig parser";
num_targets=$(cat $egs/info/output_dim)
# Note: we hardcode in the CNN config that we are dealing with 32x3x color
# images.
nf1=48
nf2=96
nf3=256
nb3=128
common="required-time-offsets=0 height-offsets=-1,0,1"
res_opts="bypass-source=batchnorm"
mkdir -p $dir/configs
cat <<EOF > $dir/configs/network.xconfig
input dim=96 name=input
conv-layer name=conv1 height-in=32 height-out=32 time-offsets=-1,0,1 required-time-offsets=0 height-offsets=-1,0,1 num-filters-out=$nf1
res-block name=res2 num-filters=$nf1 height=32 time-period=1 $res_opts
res-block name=res3 num-filters=$nf1 height=32 time-period=1 $res_opts
conv-layer name=conv4 height-in=32 height-out=16 height-subsample-out=2 time-offsets=-1,0,1 $common num-filters-out=$nf2
res-block name=res5 num-filters=$nf2 height=16 time-period=2 $res_opts
res-block name=res6 num-filters=$nf2 height=16 time-period=2 $res_opts
conv-layer name=conv7 height-in=16 height-out=8 height-subsample-out=2 time-offsets=-2,0,2 $common num-filters-out=$nf3
res-block name=res8 num-filters=$nf3 num-bottleneck-filters=$nb3 height=8 time-period=4 $res_opts
res-block name=res9 num-filters=$nf3 num-bottleneck-filters=$nb3 height=8 time-period=4 $res_opts
res-block name=res10 num-filters=$nf3 num-bottleneck-filters=$nb3 height=8 time-period=4 $res_opts
channel-average-layer name=channel-average input=Append(2,6,10,14,18,22,24,28) dim=$nf3
output-layer name=output learning-rate-factor=0.1 dim=$num_targets
EOF
steps/nnet3/xconfig_to_configs.py --xconfig-file $dir/configs/network.xconfig --config-dir $dir/configs/
fi
if [ $stage -le 2 ]; then
steps/nnet3/train_raw_dnn.py --stage=$train_stage \
--cmd="$cmd" \
--image.augmentation-opts="--horizontal-shift=0.04 --vertical-shift=0.08 --num-channels=3" \
--trainer.srand=$srand \
--trainer.max-param-change=2.0 \
--trainer.num-epochs=30 \
--egs.frames-per-eg=1 \
--trainer.optimization.num-jobs-initial=2 \
--trainer.optimization.num-jobs-final=4 \
--trainer.optimization.initial-effective-lrate=0.003 \
--trainer.optimization.final-effective-lrate=0.0003 \
--trainer.optimization.minibatch-size=256,128,64 \
--trainer.optimization.proportional-shrink=25.0 \
--trainer.shuffle-buffer-size=2000 \
--egs.dir="$egs" \
--use-gpu=true \
--reporting.email="$reporting_email" \
--dir=$dir || exit 1;
fi
exit 0;
| michellemorales/OpenMM | kaldi/egs/svhn/v1/local/nnet3/run_resnet_1b.sh | Shell | gpl-2.0 | 4,283 |
'use strict';
module.exports = function(sequelize, DataTypes){
var Order = sequelize.define('Order', {
state: {
type: DataTypes.ENUM('active', 'purchased', 'cancelled')
}
}, {
classMethods: {
associate: function(models){
Order.belongsTo(models.User);
Order.belongsTo(models.Listing);
}
}
});
return Order;
}; | CagataySonmez/MobilHackathon2014 | WebApp/models/order.js | JavaScript | gpl-2.0 | 366 |
var pkg = require([__dirname, "..", "package"].join("/"));
var _ = require("lodash");
var yargs = require("yargs");
var commands = require([__dirname, "commands"].join("/"));
module.exports = {
initialize: function(options){
var options = _.merge(options, {
version: {
describe: "Print the Cuisine version"
}
});
yargs.help("help");
yargs.version(pkg.version, "version");
yargs.options(options).argv;
},
run: function(command){
if(_.has(commands, command)){
this.initialize(commands[command].options);
commands[command].execute(yargs.argv);
}
else{
this.initialize({});
console.log(["Subcommand ", command, " not found!"].join("'"))
}
}
}
| normanjoyner/cuisine | lib/cli.js | JavaScript | gpl-2.0 | 820 |
/** @file
The form data for user profile manager driver.
Copyright (c) 2009 - 2011, Intel Corporation. All rights reserved.<BR>
This program and the accompanying materials
are licensed and made available under the terms and conditions of the BSD License
which accompanies this distribution. The full text of the license may be found at
http://opensource.org/licenses/bsd-license.php
THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#ifndef __USER_PROFILE_MANAGER_DATA_H__
#define __USER_PROFILE_MANAGER_DATA_H__
#include <Guid/UserProfileManagerHii.h>
//
// Form ID
//
#define FORMID_USER_MANAGE 0x0001
#define FORMID_MODIFY_USER 0x0002
#define FORMID_DEL_USER 0x0003
#define FORMID_USER_INFO 0x0004
#define FORMID_MODIFY_IP 0x0005
#define FORMID_MODIFY_AP 0x0006
#define FORMID_LOAD_DP 0x0007
#define FORMID_CONNECT_DP 0x0008
#define FORMID_PERMIT_LOAD_DP 0x0009
#define FORMID_FORBID_LOAD_DP 0x000A
#define FORMID_PERMIT_CONNECT_DP 0x000B
#define FORMID_FORBID_CONNECT_DP 0x000C
//
// Label ID
//
#define LABEL_USER_MANAGE_FUNC 0x0010
#define LABEL_USER_DEL_FUNC 0x0020
#define LABEL_USER_MOD_FUNC 0x0030
#define LABEL_USER_INFO_FUNC 0x0040
#define LABEL_IP_MOD_FUNC 0x0050
#define LABEL_AP_MOD_FUNC 0x0060
#define LABEL_PERMIT_LOAD_FUNC 0x0070
#define LABLE_FORBID_LOAD_FUNC 0x0080
#define LABEL_END 0x00F0
//
// First form key (Add/modify/del user profile).
// First 2 bits (bit 16~15).
//
#define KEY_MODIFY_USER 0x4000
#define KEY_DEL_USER 0x8000
#define KEY_ADD_USER 0xC000
#define KEY_FIRST_FORM_MASK 0xC000
//
// Second form key (Display new form /Select user / modify device path in access policy).
// Next 2 bits (bit 14~13).
//
#define KEY_ENTER_NEXT_FORM 0x0000
#define KEY_SELECT_USER 0x1000
#define KEY_MODIFY_AP_DP 0x2000
#define KEY_OPEN_CLOSE_FORM_ACTION 0x3000
#define KEY_SECOND_FORM_MASK 0x3000
//
// User profile information form key.
// Next 3 bits (bit 12~10).
//
#define KEY_MODIFY_NAME 0x0200
#define KEY_MODIFY_IP 0x0400
#define KEY_MODIFY_AP 0x0600
#define KEY_MODIFY_INFO_MASK 0x0E00
//
// Specified key, used in VFR (KEY_MODIFY_USER | KEY_SELECT_USER | KEY_MODIFY_NAME).
//
#define KEY_MODIFY_USER_NAME 0x5200
//
// Modify identity policy form key.
// Next 3 bits (bit 9~7).
//
#define KEY_MODIFY_PROV 0x0040
#define KEY_MODIFY_MTYPE 0x0080
#define KEY_MODIFY_CONN 0x00C0
#define KEY_ADD_IP_OP 0x0100
#define KEY_IP_RETURN_UIF 0x0140
#define KEY_MODIFY_IP_MASK 0x01C0
//
// Specified key.
//
#define KEY_ADD_LOGICAL_OP 0x5500
#define KEY_IP_RETURN 0x5540
//
// Modify access policy form key.
// Next 3 bits (bit 9~7).
//
#define KEY_MODIFY_RIGHT 0x0040
#define KEY_MODIFY_SETUP 0x0080
#define KEY_MODIFY_BOOT 0x00C0
#define KEY_MODIFY_LOAD 0x0100
#define KEY_MODIFY_CONNECT 0x0140
#define KEY_AP_RETURN_UIF 0x0180
#define KEY_MODIFY_AP_MASK 0x01C0
//
// Specified key.
//
#define KEY_LOAD_DP 0x5700
#define KEY_CONN_DP 0x5740
#define KEY_AP_RETURN 0x5780
//
// Device path form key.
// Next 2 bits (bit 6~5).
//
#define KEY_PERMIT_MODIFY 0x0010
#define KEY_FORBID_MODIFY 0x0020
#define KEY_DISPLAY_DP_MASK 0x0030
//
// Specified key.
//
#define KEY_LOAD_PERMIT 0x5710
#define KEY_LOAD_FORBID 0x5720
#define KEY_CONNECT_PERMIT 0x5750
#define KEY_CONNECT_FORBID 0x5760
//
// Device path modify key.
// 2 bits (bit 12~11).
//
#define KEY_LOAD_PERMIT_MODIFY 0x0000
#define KEY_LOAD_FORBID_MODIFY 0x0400
#define KEY_CONNECT_PERMIT_MODIFY 0x0800
#define KEY_CONNECT_FORBID_MODIFY 0x0C00
#define KEY_MODIFY_DP_MASK 0x0C00
//
// The permissions usable when configuring the platform.
//
#define ACCESS_SETUP_RESTRICTED 1
#define ACCESS_SETUP_NORMAL 2
#define ACCESS_SETUP_ADMIN 3
//
// Question ID for the question used in each form (KEY_OPEN_CLOSE_FORM_ACTION | FORMID_FORM_USER_MANAGE)
// This ID is used in FORM OPEN/CLOSE CallBack action.
//
#define QUESTIONID_USER_MANAGE 0x3001
#endif
| miguelinux/vbox | src/VBox/Devices/EFI/Firmware/SecurityPkg/UserIdentification/UserProfileManagerDxe/UserProfileManagerData.h | C | gpl-2.0 | 4,590 |
FROM nikowoot/base
MAINTAINER Frédéric TURPIN <lumiru@turp.in>
## ================================
## INSTALLATION PART
## ================================
# Copy, change rights, execute, delete script file "install.sh"
ADD ./install.sh /install.sh
RUN chmod 755 /install.sh
RUN /install.sh
RUN rm -f /install.sh
ADD ./nginx.conf /opt/nginx/conf/nginx.conf
# Copy, change rights "run.sh"
ADD ./run.sh /run.sh
RUN chmod 755 /run.sh
## ================================
## LAUNCH PART
## ================================
# Expose sockets
EXPOSE 22 80
# Launch run script
CMD /run.sh
| lumiru/dev-dockerstack | dockers/passenger/Dockerfile | Dockerfile | gpl-2.0 | 588 |
/* UIToggleButton.h
*
* Copyright (C) 2011 Belledonne Comunications, Grenoble, France
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#import <UIKit/UIKit.h>
#import "UIIconButton.h"
@protocol UIToggleButtonDelegate
- (void)onOn;
- (void)onOff;
- (bool)onUpdate;
@end
@interface UIToggleButton : UIIconButton <UIToggleButtonDelegate> {
}
#if 0 // Changed Linphone code - Need to call this from UI thread otherwise get exceptions
- (bool)update;
#else
- (void)update;
#endif
- (void)setOn;
- (void)setOff;
- (bool)toggle;
@end
| raj-bhatia/grooveip-ios-public | Classes/LinphoneUI/UIToggleButton.h | C | gpl-2.0 | 1,452 |
<?php
/** Plugin Information
*
*/
?>
<div class="wrap">
<div id="icon-edit" class="icon32"><br/></div>
<h2>
<?php _e('Info') ?>
</h2>
<div class="form-wrap" id="poststuff">
<div id="post-body">
<div id="post-body-content">
<div class="form-field">
<p><?php _e( 'Check out the <a href="http://otwthemes.com/online-documentation-widgetize-pages-light/?utm_source=wp.org&utm_medium=admin&utm_content=docs&utm_campaign=wpl">Online documentation</a> for this plugin<br /><br /> Upgrade to the full version of <a href="http://codecanyon.net/item/sidebar-widget-manager-for-wordpress/2287447?ref=OTWthemes">Sidebar and Widget Manager</a> | <a href="http://otwthemes.com/demos/1ts/?item=Sidebar%20Widget%20Manager&utm_source=wp.org&utm_medium=admin&utm_content=upgrade&utm_campaign=wpl">Demo site</a> <br /><br /> <a href="http://otwthemes.com/widgetizing-pages-in-wordpress-can-be-even-easier-and-faster?utm_source=wp.org&utm_medium=admin&utm_content=site&utm_campaign=wpl">Create responsive layouts in minutes, drag & drop interface, feature rich.</a>' );?></p>
</div>
</div>
</div>
</div>
</div>
| rm913/lamaze-dc | wp-content/plugins/widgetize-pages-light/include/otw_sidebar_info.php | PHP | gpl-2.0 | 1,130 |
/*****************************************************************************
* vlc_variables.h: variables handling
*****************************************************************************
* Copyright (C) 2002-2004 VLC authors and VideoLAN
* $Id$
*
* Authors: Samuel Hocevar <sam@zoy.org>
* Gildas Bazin <gbazin@netcourrier.com>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
*****************************************************************************/
#ifndef VLC_VARIABLES_H
#define VLC_VARIABLES_H 1
/**
* \file
* This file defines functions and structures for dynamic variables in vlc
*/
/**
* \defgroup variables Variables
*
* Functions for using the object variables in vlc.
*
* Vlc have a very powerful "object variable" infrastructure useful
* for many things.
*
* @{
*/
#define VLC_VAR_TYPE 0x00ff
#define VLC_VAR_CLASS 0x00f0
#define VLC_VAR_FLAGS 0xff00
/**
* \defgroup var_type Variable types
* These are the different types a vlc variable can have.
* @{
*/
#define VLC_VAR_VOID 0x0010
#define VLC_VAR_BOOL 0x0020
#define VLC_VAR_INTEGER 0x0030
#define VLC_VAR_STRING 0x0040
#define VLC_VAR_FLOAT 0x0050
#define VLC_VAR_ADDRESS 0x0070
#define VLC_VAR_COORDS 0x00A0
/**@}*/
/** \defgroup var_flags Additive flags
* These flags are added to the type field of the variable. Most as a result of
* a var_Change() call, but some may be added at creation time
* @{
*/
#define VLC_VAR_HASCHOICE 0x0100
#define VLC_VAR_HASMIN 0x0200
#define VLC_VAR_HASMAX 0x0400
#define VLC_VAR_HASSTEP 0x0800
#define VLC_VAR_ISCOMMAND 0x2000
/** Creation flag */
/* If the variable is not found on the current module
search all parents and finally module config until found */
#define VLC_VAR_DOINHERIT 0x8000
/**@}*/
/**
* \defgroup var_action Variable actions
* These are the different actions that can be used with var_Change().
* The parameters given are the meaning of the two last parameters of
* var_Change() when this action is being used.
* @{
*/
/**
* Set the minimum value of this variable
* \param p_val The new minimum value
* \param p_val2 Unused
*/
#define VLC_VAR_SETMIN 0x0010
/**
* Set the maximum value of this variable
* \param p_val The new maximum value
* \param p_val2 Unused
*/
#define VLC_VAR_SETMAX 0x0011
#define VLC_VAR_SETSTEP 0x0012
/**
* Set the value of this variable without triggering any callbacks
* \param p_val The new value
* \param p_val2 Unused
*/
#define VLC_VAR_SETVALUE 0x0013
#define VLC_VAR_SETTEXT 0x0014
#define VLC_VAR_GETTEXT 0x0015
#define VLC_VAR_GETMIN 0x0016
#define VLC_VAR_GETMAX 0x0017
#define VLC_VAR_GETSTEP 0x0018
#define VLC_VAR_ADDCHOICE 0x0020
#define VLC_VAR_DELCHOICE 0x0021
#define VLC_VAR_CLEARCHOICES 0x0022
#define VLC_VAR_SETDEFAULT 0x0023
#define VLC_VAR_GETCHOICES 0x0024
#define VLC_VAR_CHOICESCOUNT 0x0026
/**@}*/
/** \defgroup var_GetAndSet Variable actions
* These are the different actions that can be used with var_GetAndSet()
* @{
*/
enum {
VLC_VAR_BOOL_TOGGLE, /**< Invert a boolean value (param ignored) */
VLC_VAR_INTEGER_ADD, /**< Add parameter to an integer value */
VLC_VAR_INTEGER_OR, /**< Binary OR over an integer bits field */
VLC_VAR_INTEGER_NAND,/**< Binary NAND over an integer bits field */
};
/**@}*/
/*****************************************************************************
* Prototypes
*****************************************************************************/
VLC_API int var_Create( vlc_object_t *, const char *, int );
#define var_Create(a,b,c) var_Create( VLC_OBJECT(a), b, c )
VLC_API void var_Destroy( vlc_object_t *, const char * );
#define var_Destroy(a,b) var_Destroy( VLC_OBJECT(a), b )
VLC_API int var_Change( vlc_object_t *, const char *, int, vlc_value_t *, vlc_value_t * );
#define var_Change(a,b,c,d,e) var_Change( VLC_OBJECT(a), b, c, d, e )
VLC_API int var_Type( vlc_object_t *, const char * ) VLC_USED;
#define var_Type(a,b) var_Type( VLC_OBJECT(a), b )
VLC_API int var_Set( vlc_object_t *, const char *, vlc_value_t );
#define var_Set(a,b,c) var_Set( VLC_OBJECT(a), b, c )
VLC_API int var_Get( vlc_object_t *, const char *, vlc_value_t * );
#define var_Get(a,b,c) var_Get( VLC_OBJECT(a), b, c )
VLC_API int var_SetChecked( vlc_object_t *, const char *, int, vlc_value_t );
#define var_SetChecked(o,n,t,v) var_SetChecked(VLC_OBJECT(o),n,t,v)
VLC_API int var_GetChecked( vlc_object_t *, const char *, int, vlc_value_t * );
#define var_GetChecked(o,n,t,v) var_GetChecked(VLC_OBJECT(o),n,t,v)
VLC_API int var_GetAndSet( vlc_object_t *, const char *, int, vlc_value_t * );
VLC_API int var_Inherit( vlc_object_t *, const char *, int, vlc_value_t * );
VLC_API void var_FreeList( vlc_value_t *, vlc_value_t * );
/*****************************************************************************
* Variable callbacks
*****************************************************************************
* int MyCallback( vlc_object_t *p_this,
* char const *psz_variable,
* vlc_value_t oldvalue,
* vlc_value_t newvalue,
* void *p_data);
*****************************************************************************/
VLC_API int var_AddCallback( vlc_object_t *, const char *, vlc_callback_t, void * );
VLC_API int var_DelCallback( vlc_object_t *, const char *, vlc_callback_t, void * );
VLC_API int var_TriggerCallback( vlc_object_t *, const char * );
VLC_API int var_AddListCallback( vlc_object_t *, const char *, vlc_list_callback_t, void * );
VLC_API int var_DelListCallback( vlc_object_t *, const char *, vlc_list_callback_t, void * );
#define var_AddCallback(a,b,c,d) var_AddCallback( VLC_OBJECT(a), b, c, d )
#define var_DelCallback(a,b,c,d) var_DelCallback( VLC_OBJECT(a), b, c, d )
#define var_TriggerCallback(a,b) var_TriggerCallback( VLC_OBJECT(a), b )
#define var_AddListCallback(a,b,c,d) var_AddListCallback( VLC_OBJECT(a), b, c, d )
#define var_DelListCallback(a,b,c,d) var_DelListCallback( VLC_OBJECT(a), b, c, d )
/*****************************************************************************
* helpers functions
*****************************************************************************/
/**
* Set the value of an integer variable
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
* \param i The new integer value of this variable
*/
static inline int var_SetInteger( vlc_object_t *p_obj, const char *psz_name,
int64_t i )
{
vlc_value_t val;
val.i_int = i;
return var_SetChecked( p_obj, psz_name, VLC_VAR_INTEGER, val );
}
/**
* Set the value of an boolean variable
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
* \param b The new boolean value of this variable
*/
static inline int var_SetBool( vlc_object_t *p_obj, const char *psz_name, bool b )
{
vlc_value_t val;
val.b_bool = b;
return var_SetChecked( p_obj, psz_name, VLC_VAR_BOOL, val );
}
static inline int var_SetCoords( vlc_object_t *obj, const char *name,
int32_t x, int32_t y )
{
vlc_value_t val;
val.coords.x = x;
val.coords.y = y;
return var_SetChecked (obj, name, VLC_VAR_COORDS, val);
}
#define var_SetCoords(o,n,x,y) var_SetCoords(VLC_OBJECT(o),n,x,y)
/**
* Set the value of a float variable
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
* \param f The new float value of this variable
*/
static inline int var_SetFloat( vlc_object_t *p_obj, const char *psz_name, float f )
{
vlc_value_t val;
val.f_float = f;
return var_SetChecked( p_obj, psz_name, VLC_VAR_FLOAT, val );
}
/**
* Set the value of a string variable
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
* \param psz_string The new string value of this variable
*/
static inline int var_SetString( vlc_object_t *p_obj, const char *psz_name, const char *psz_string )
{
vlc_value_t val;
val.psz_string = (char *)psz_string;
return var_SetChecked( p_obj, psz_name, VLC_VAR_STRING, val );
}
/**
* Set the value of a pointer variable
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
* \param ptr The new pointer value of this variable
*/
static inline
int var_SetAddress( vlc_object_t *p_obj, const char *psz_name, void *ptr )
{
vlc_value_t val;
val.p_address = ptr;
return var_SetChecked( p_obj, psz_name, VLC_VAR_ADDRESS, val );
}
#define var_SetInteger(a,b,c) var_SetInteger( VLC_OBJECT(a),b,c)
#define var_SetBool(a,b,c) var_SetBool( VLC_OBJECT(a),b,c)
#define var_SetFloat(a,b,c) var_SetFloat( VLC_OBJECT(a),b,c)
#define var_SetString(a,b,c) var_SetString( VLC_OBJECT(a),b,c)
#define var_SetAddress(o, n, p) var_SetAddress(VLC_OBJECT(o), n, p)
/**
* Get an integer value
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline int64_t var_GetInteger( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val;
if( !var_GetChecked( p_obj, psz_name, VLC_VAR_INTEGER, &val ) )
return val.i_int;
else
return 0;
}
/**
* Get a boolean value
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline bool var_GetBool( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val; val.b_bool = false;
if( !var_GetChecked( p_obj, psz_name, VLC_VAR_BOOL, &val ) )
return val.b_bool;
else
return false;
}
static inline void var_GetCoords( vlc_object_t *obj, const char *name,
int32_t *px, int32_t *py )
{
vlc_value_t val;
if (likely(!var_GetChecked (obj, name, VLC_VAR_COORDS, &val)))
{
*px = val.coords.x;
*py = val.coords.y;
}
else
*px = *py = 0;
}
#define var_GetCoords(o,n,x,y) var_GetCoords(VLC_OBJECT(o),n,x,y)
/**
* Get a float value
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline float var_GetFloat( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val; val.f_float = 0.0;
if( !var_GetChecked( p_obj, psz_name, VLC_VAR_FLOAT, &val ) )
return val.f_float;
else
return 0.0;
}
/**
* Get a string value
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED VLC_MALLOC
static inline char *var_GetString( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val; val.psz_string = NULL;
if( var_GetChecked( p_obj, psz_name, VLC_VAR_STRING, &val ) )
return NULL;
else
return val.psz_string;
}
VLC_USED VLC_MALLOC
static inline char *var_GetNonEmptyString( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val;
if( var_GetChecked( p_obj, psz_name, VLC_VAR_STRING, &val ) )
return NULL;
if( val.psz_string && *val.psz_string )
return val.psz_string;
free( val.psz_string );
return NULL;
}
VLC_USED
static inline void *var_GetAddress( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val;
if( var_GetChecked( p_obj, psz_name, VLC_VAR_ADDRESS, &val ) )
return NULL;
else
return val.p_address;
}
/**
* Increment an integer variable
* \param p_obj the object that holds the variable
* \param psz_name the name of the variable
*/
static inline int64_t var_IncInteger( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val;
val.i_int = 1;
if( var_GetAndSet( p_obj, psz_name, VLC_VAR_INTEGER_ADD, &val ) )
return 0;
return val.i_int;
}
#define var_IncInteger(a,b) var_IncInteger( VLC_OBJECT(a), b )
/**
* Decrement an integer variable
* \param p_obj the object that holds the variable
* \param psz_name the name of the variable
*/
static inline int64_t var_DecInteger( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val;
val.i_int = -1;
if( var_GetAndSet( p_obj, psz_name, VLC_VAR_INTEGER_ADD, &val ) )
return 0;
return val.i_int;
}
#define var_DecInteger(a,b) var_DecInteger( VLC_OBJECT(a), b )
static inline uint64_t var_OrInteger( vlc_object_t *obj, const char *name,
unsigned v )
{
vlc_value_t val;
val.i_int = v;
if( var_GetAndSet( obj, name, VLC_VAR_INTEGER_OR, &val ) )
return 0;
return val.i_int;
}
#define var_OrInteger(a,b,c) var_OrInteger(VLC_OBJECT(a),b,c)
static inline uint64_t var_NAndInteger( vlc_object_t *obj, const char *name,
unsigned v )
{
vlc_value_t val;
val.i_int = v;
if( var_GetAndSet( obj, name, VLC_VAR_INTEGER_NAND, &val ) )
return 0;
return val.i_int;
}
#define var_NAndInteger(a,b,c) var_NAndInteger(VLC_OBJECT(a),b,c)
/**
* Create a integer variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline int64_t var_CreateGetInteger( vlc_object_t *p_obj, const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_INTEGER | VLC_VAR_DOINHERIT );
return var_GetInteger( p_obj, psz_name );
}
/**
* Create a boolean variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline bool var_CreateGetBool( vlc_object_t *p_obj, const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_BOOL | VLC_VAR_DOINHERIT );
return var_GetBool( p_obj, psz_name );
}
/**
* Create a float variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline float var_CreateGetFloat( vlc_object_t *p_obj, const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_FLOAT | VLC_VAR_DOINHERIT );
return var_GetFloat( p_obj, psz_name );
}
/**
* Create a string variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED VLC_MALLOC
static inline char *var_CreateGetString( vlc_object_t *p_obj,
const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_STRING | VLC_VAR_DOINHERIT );
return var_GetString( p_obj, psz_name );
}
VLC_USED VLC_MALLOC
static inline char *var_CreateGetNonEmptyString( vlc_object_t *p_obj,
const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_STRING | VLC_VAR_DOINHERIT );
return var_GetNonEmptyString( p_obj, psz_name );
}
/**
* Create an address variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline void *var_CreateGetAddress( vlc_object_t *p_obj,
const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_ADDRESS | VLC_VAR_DOINHERIT );
return var_GetAddress( p_obj, psz_name );
}
#define var_CreateGetInteger(a,b) var_CreateGetInteger( VLC_OBJECT(a),b)
#define var_CreateGetBool(a,b) var_CreateGetBool( VLC_OBJECT(a),b)
#define var_CreateGetFloat(a,b) var_CreateGetFloat( VLC_OBJECT(a),b)
#define var_CreateGetString(a,b) var_CreateGetString( VLC_OBJECT(a),b)
#define var_CreateGetNonEmptyString(a,b) var_CreateGetNonEmptyString( VLC_OBJECT(a),b)
#define var_CreateGetAddress(a,b) var_CreateGetAddress( VLC_OBJECT(a),b)
/**
* Create a integer command variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline int64_t var_CreateGetIntegerCommand( vlc_object_t *p_obj, const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_INTEGER | VLC_VAR_DOINHERIT
| VLC_VAR_ISCOMMAND );
return var_GetInteger( p_obj, psz_name );
}
/**
* Create a boolean command variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline bool var_CreateGetBoolCommand( vlc_object_t *p_obj, const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_BOOL | VLC_VAR_DOINHERIT
| VLC_VAR_ISCOMMAND );
return var_GetBool( p_obj, psz_name );
}
/**
* Create a float command variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED
static inline float var_CreateGetFloatCommand( vlc_object_t *p_obj, const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_FLOAT | VLC_VAR_DOINHERIT
| VLC_VAR_ISCOMMAND );
return var_GetFloat( p_obj, psz_name );
}
/**
* Create a string command variable with inherit and get its value.
*
* \param p_obj The object that holds the variable
* \param psz_name The name of the variable
*/
VLC_USED VLC_MALLOC
static inline char *var_CreateGetStringCommand( vlc_object_t *p_obj,
const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_STRING | VLC_VAR_DOINHERIT
| VLC_VAR_ISCOMMAND );
return var_GetString( p_obj, psz_name );
}
VLC_USED VLC_MALLOC
static inline char *var_CreateGetNonEmptyStringCommand( vlc_object_t *p_obj,
const char *psz_name )
{
var_Create( p_obj, psz_name, VLC_VAR_STRING | VLC_VAR_DOINHERIT
| VLC_VAR_ISCOMMAND );
return var_GetNonEmptyString( p_obj, psz_name );
}
#define var_CreateGetIntegerCommand(a,b) var_CreateGetIntegerCommand( VLC_OBJECT(a),b)
#define var_CreateGetBoolCommand(a,b) var_CreateGetBoolCommand( VLC_OBJECT(a),b)
#define var_CreateGetFloatCommand(a,b) var_CreateGetFloatCommand( VLC_OBJECT(a),b)
#define var_CreateGetStringCommand(a,b) var_CreateGetStringCommand( VLC_OBJECT(a),b)
#define var_CreateGetNonEmptyStringCommand(a,b) var_CreateGetNonEmptyStringCommand( VLC_OBJECT(a),b)
VLC_USED
static inline int var_CountChoices( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t count;
if( var_Change( p_obj, psz_name, VLC_VAR_CHOICESCOUNT, &count, NULL ) )
return 0;
return count.i_int;
}
#define var_CountChoices(a,b) var_CountChoices( VLC_OBJECT(a),b)
static inline bool var_ToggleBool( vlc_object_t *p_obj, const char *psz_name )
{
vlc_value_t val;
if( var_GetAndSet( p_obj, psz_name, VLC_VAR_BOOL_TOGGLE, &val ) )
return false;
return val.b_bool;
}
#define var_ToggleBool(a,b) var_ToggleBool( VLC_OBJECT(a),b )
VLC_USED
static inline bool var_InheritBool( vlc_object_t *obj, const char *name )
{
vlc_value_t val;
if( var_Inherit( obj, name, VLC_VAR_BOOL, &val ) )
val.b_bool = false;
return val.b_bool;
}
#define var_InheritBool(o, n) var_InheritBool(VLC_OBJECT(o), n)
VLC_USED
static inline int64_t var_InheritInteger( vlc_object_t *obj, const char *name )
{
vlc_value_t val;
if( var_Inherit( obj, name, VLC_VAR_INTEGER, &val ) )
val.i_int = 0;
return val.i_int;
}
#define var_InheritInteger(o, n) var_InheritInteger(VLC_OBJECT(o), n)
VLC_USED
static inline float var_InheritFloat( vlc_object_t *obj, const char *name )
{
vlc_value_t val;
if( var_Inherit( obj, name, VLC_VAR_FLOAT, &val ) )
val.f_float = 0.;
return val.f_float;
}
#define var_InheritFloat(o, n) var_InheritFloat(VLC_OBJECT(o), n)
VLC_USED VLC_MALLOC
static inline char *var_InheritString( vlc_object_t *obj, const char *name )
{
vlc_value_t val;
if( var_Inherit( obj, name, VLC_VAR_STRING, &val ) )
val.psz_string = NULL;
else if( val.psz_string && !*val.psz_string )
{
free( val.psz_string );
val.psz_string = NULL;
}
return val.psz_string;
}
#define var_InheritString(o, n) var_InheritString(VLC_OBJECT(o), n)
VLC_USED
static inline void *var_InheritAddress( vlc_object_t *obj, const char *name )
{
vlc_value_t val;
if( var_Inherit( obj, name, VLC_VAR_ADDRESS, &val ) )
val.p_address = NULL;
return val.p_address;
}
#define var_InheritAddress(o, n) var_InheritAddress(VLC_OBJECT(o), n)
VLC_API int var_InheritURational( vlc_object_t *, unsigned *num, unsigned *den, const char *var );
#define var_InheritURational(a,b,c,d) var_InheritURational(VLC_OBJECT(a), b, c, d)
#define var_GetInteger(a,b) var_GetInteger( VLC_OBJECT(a),b)
#define var_GetBool(a,b) var_GetBool( VLC_OBJECT(a),b)
#define var_GetFloat(a,b) var_GetFloat( VLC_OBJECT(a),b)
#define var_GetString(a,b) var_GetString( VLC_OBJECT(a),b)
#define var_GetNonEmptyString(a,b) var_GetNonEmptyString( VLC_OBJECT(a),b)
#define var_GetAddress(a,b) var_GetAddress( VLC_OBJECT(a),b)
VLC_API int var_LocationParse(vlc_object_t *, const char *mrl, const char *prefix);
#define var_LocationParse(o, m, p) var_LocationParse(VLC_OBJECT(o), m, p)
/**
* @}
*/
#endif /* _VLC_VARIABLES_H */
| Rodeo314/tim-vlc | include/vlc_variables.h | C | gpl-2.0 | 22,209 |
using Server.Gumps;
using Server.Network;
namespace Server.Engines.MLQuests.Gumps
{
public class QuestCancelConfirmGump : Gump
{
private MLQuestInstance m_Instance;
private bool m_CloseGumps;
public QuestCancelConfirmGump( MLQuestInstance instance )
: this( instance, true )
{
}
public QuestCancelConfirmGump( MLQuestInstance instance, bool closeGumps )
: base( 120, 50 )
{
m_Instance = instance;
m_CloseGumps = closeGumps;
if ( closeGumps )
BaseQuestGump.CloseOtherGumps( instance.Player );
AddPage( 0 );
Closable = false;
AddImageTiled( 0, 0, 348, 262, 0xA8E );
AddAlphaRegion( 0, 0, 348, 262 );
AddImage( 0, 15, 0x27A8 );
AddImageTiled( 0, 30, 17, 200, 0x27A7 );
AddImage( 0, 230, 0x27AA );
AddImage( 15, 0, 0x280C );
AddImageTiled( 30, 0, 300, 17, 0x280A );
AddImage( 315, 0, 0x280E );
AddImage( 15, 244, 0x280C );
AddImageTiled( 30, 244, 300, 17, 0x280A );
AddImage( 315, 244, 0x280E );
AddImage( 330, 15, 0x27A8 );
AddImageTiled( 330, 30, 17, 200, 0x27A7 );
AddImage( 330, 230, 0x27AA );
AddImage( 333, 2, 0x2716 );
AddImage( 333, 248, 0x2716 );
AddImage( 2, 248, 0x2716 );
AddImage( 2, 2, 0x2716 );
AddHtmlLocalized( 25, 22, 200, 20, 1049000, 0x7D00, false, false ); // Confirm Quest Cancellation
AddImage( 25, 40, 0xBBF );
/*
* This quest will give you valuable information, skills
* and equipment that will help you advance in the
* game at a quicker pace.<BR>
* <BR>
* Are you certain you wish to cancel at this time?
*/
AddHtmlLocalized( 25, 55, 300, 120, 1060836, 0xFFFFFF, false, false );
MLQuest quest = instance.Quest;
if ( quest.IsChainTriggered || quest.NextQuest != null )
{
AddRadio( 25, 145, 0x25F8, 0x25FB, false, 2 );
AddHtmlLocalized( 60, 150, 280, 20, 1075023, 0xFFFFFF, false, false ); // Yes, I want to quit this entire chain!
}
AddRadio( 25, 180, 0x25F8, 0x25FB, true, 1 );
AddHtmlLocalized( 60, 185, 280, 20, 1049005, 0xFFFFFF, false, false ); // Yes, I really want to quit this quest!
AddRadio( 25, 215, 0x25F8, 0x25FB, false, 0 );
AddHtmlLocalized( 60, 220, 280, 20, 1049006, 0xFFFFFF, false, false ); // No, I don't want to quit.
AddButton( 265, 220, 0xF7, 0xF8, 7, GumpButtonType.Reply, 0 );
}
public override void OnResponse( NetState sender, RelayInfo info )
{
if ( m_Instance.Removed )
return;
switch ( info.ButtonID )
{
case 7: // Okay
{
if ( info.IsSwitched( 2 ) )
m_Instance.Cancel( true );
else if ( info.IsSwitched( 1 ) )
m_Instance.Cancel( false );
sender.Mobile.SendGump( new QuestLogGump( m_Instance.Player, m_CloseGumps ) );
break;
}
}
}
}
}
| felladrin/last-wish | Scripts/Engines/MLQuests/Gumps/QuestCancelConfirmGump.cs | C# | gpl-2.0 | 2,848 |
/**
* sidewaysparker - Sample application for realizing a sideways parking car.
* Copyright (C) 2012 - 2015 Christian Berger
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "DecitionMaker.h"
int32_t main(int32_t argc, char **argv) {
scaledcars::DecitionMaker swp(argc, argv);
return swp.runModule();
}
| QuoBono/opendlv.scaledcars | code/decitionmaker/apps/decitionmaker.cpp | C++ | gpl-2.0 | 1,001 |
/*
* HyFi forwarding database
* QCA HyFi Bridge
*
* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, 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.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/rculist.h>
#include <linux/spinlock.h>
#include <linux/etherdevice.h>
#include <mc_private.h>
#include "hyfi_netfilter.h"
#include "hyfi_netlink.h"
#include "hyfi_bridge.h"
#include "hyfi_api.h"
#include "hyfi_fdb.h"
static inline unsigned long hold_time(const struct net_bridge *br)
{
return br->topology_change ? br->forward_delay : br->ageing_time;
}
static inline int has_expired(const struct net_bridge *br,
const struct net_bridge_fdb_entry *fdb)
{
return !fdb->is_static
&& time_before_eq(hyfi_updated_time_get(fdb) + hold_time( br ), jiffies );
}
/*
* Fill buffer with forwarding table records in
* the API format.
*/
int hyfi_fdb_fillbuf(struct net_bridge *br, void *buf, u_int32_t buf_len,
u_int32_t skip, u_int32_t *bytes_written, u_int32_t *bytes_needed)
{
struct __hfdb_entry *fe = buf;
u_int32_t i, total = 0, num = 0, num_entries;
int ret = 0;
struct hlist_node *h;
struct net_bridge_fdb_entry *f;
memset(buf, 0, buf_len);
num_entries = buf_len / sizeof(struct __hfdb_entry);
rcu_read_lock();
for (i = 0; i < BR_HASH_SIZE; i++) {
os_hlist_for_each_entry_rcu(f, h, &br->hash[i], hlist) {
if (has_expired(br, f))
continue;
total++;
if (num >= num_entries) {
ret = -EAGAIN;
continue;
}
/* Ignore any local entries that do not have a valid
* port
*/
if (!f->dst)
continue;
if (skip) {
skip--;
continue;
}
/* convert from internal format to API */
memcpy(fe->mac_addr, f->addr.addr, ETH_ALEN);
/* due to ABI compat need to split into hi/lo */
fe->ifindex = f->dst->dev->ifindex & 0xff;
fe->ifindex_hi = (f->dst->dev->ifindex >> 8) & 0xff;
fe->is_local = f->is_local;
if (!f->is_static)
fe->ageing_timer_value = jiffies_to_clock_t(
jiffies - hyfi_updated_time_get(f));
++fe;
++num;
}
}
rcu_read_unlock();
if (bytes_written)
*bytes_written = num * sizeof(struct __hfdb_entry);
if (bytes_needed) {
if (ret == -EAGAIN)
*bytes_needed = total * sizeof(struct __hfdb_entry);
else
*bytes_needed = 0;
}
return ret;
}
| dan82840/Netgear-RBR40 | git_home/kmod-qsdk-hyfi.git/qca-hyfi-bridge/hyfi-netfilter/hyfi_fdb.c | C | gpl-2.0 | 2,992 |
/*
* SocialLedge.com - Copyright (C) 2013
*
* This file is part of free software framework for embedded processors.
* You can use it and/or distribute it as long as this copyright header
* remains unmodified. The code is free for personal use and requires
* permission to use in a commercial product.
*
* THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES, WHETHER EXPRESS, IMPLIED
* OR STATUTORY, INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE.
* I SHALL NOT, IN ANY CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR
* CONSEQUENTIAL DAMAGES, FOR ANY REASON WHATSOEVER.
*
* You can reach the author of this software at :
* p r e e t . w i k i @ g m a i l . c o m
*/
/**
* @file
* @ingroup Drivers
*/
#ifndef SPI1_H_
#define SPI1_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "LPC17xx.h"
#include "base/ssp_prv.h"
/**
* Initializes SPI 1
* Configures CLK, MISO, MOSI pins with a slow SCK speed
*/
static inline void ssp1_init(void)
{
lpc_pconp(pconp_ssp1, true);
lpc_pclk(pclk_ssp1, clkdiv_1);
ssp_init(LPC_SSP1);
void ssp1_dma_init();
ssp1_dma_init();
}
/**
* Sets SPI Clock speed
* @param max_clock_mhz The maximum speed of this SPI in Megahertz
* @note The speed may be set lower to max_clock_mhz if it cannot be attained.
*/
static inline void ssp1_set_max_clock(unsigned int max_clock_mhz)
{
ssp_set_max_clock(LPC_SSP1, max_clock_mhz);
}
/**
* Exchanges a byte over SPI bus
* @param out The byte to send out
* @returns The byte received over SPI
*/
static inline char ssp1_exchange_byte(char out)
{
return ssp_exchange_byte(LPC_SSP1, out);
}
/**
* Writes a byte to the SPI FIFO
* @warning YOU MUST ENSURE SPI IS NOT BUSY before calling this function
*/
static inline void ssp1_exchange_data(void* data, int len)
{
ssp_exchange_data(LPC_SSP1, data, len);
}
/**
* Transfers data over SPI (SSP#1)
* @param pBuffer The read or write buffer
* @param num_bytes The length of the transfer in bytes
* @param is_write_op Non-zero for Write-operation, zero for read operation
*
* @note If is_write_op is true:
* - SPI data is sent from pBuffer
* - SPI data is copied from SSP DR to dummy buffer and discarded
* If is_write_op is false (read operation) :
* - SPI data is copied from SSP DR to pBuffer
* - 0xFF is sent out for each byte transfered
*
* @return 0 upon success, or non-zero upon failure.
*/
unsigned ssp1_dma_transfer_block(unsigned char* pBuffer, uint32_t num_bytes, char is_write_op);
#ifdef __cplusplus
}
#endif
#endif /* SPI1_H_ */
| kammce/SJSU-DEV-Linux | firmware/default/lib/L2_Drivers/ssp1.h | C | gpl-2.0 | 2,838 |
#define USE_THE_INDEX_COMPATIBILITY_MACROS
#include "builtin.h"
#include "config.h"
#include "parse-options.h"
#include "refs.h"
#include "lockfile.h"
#include "cache-tree.h"
#include "unpack-trees.h"
#include "merge-recursive.h"
#include "argv-array.h"
#include "run-command.h"
#include "dir.h"
#include "rerere.h"
#include "revision.h"
#include "log-tree.h"
#include "diffcore.h"
#include "exec-cmd.h"
#define INCLUDE_ALL_FILES 2
static const char * const git_stash_usage[] = {
N_("git stash list [<options>]"),
N_("git stash show [<options>] [<stash>]"),
N_("git stash drop [-q|--quiet] [<stash>]"),
N_("git stash ( pop | apply ) [--index] [-q|--quiet] [<stash>]"),
N_("git stash branch <branchname> [<stash>]"),
N_("git stash clear"),
N_("git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
" [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
" [--] [<pathspec>...]]"),
N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
" [-u|--include-untracked] [-a|--all] [<message>]"),
NULL
};
static const char * const git_stash_list_usage[] = {
N_("git stash list [<options>]"),
NULL
};
static const char * const git_stash_show_usage[] = {
N_("git stash show [<options>] [<stash>]"),
NULL
};
static const char * const git_stash_drop_usage[] = {
N_("git stash drop [-q|--quiet] [<stash>]"),
NULL
};
static const char * const git_stash_pop_usage[] = {
N_("git stash pop [--index] [-q|--quiet] [<stash>]"),
NULL
};
static const char * const git_stash_apply_usage[] = {
N_("git stash apply [--index] [-q|--quiet] [<stash>]"),
NULL
};
static const char * const git_stash_branch_usage[] = {
N_("git stash branch <branchname> [<stash>]"),
NULL
};
static const char * const git_stash_clear_usage[] = {
N_("git stash clear"),
NULL
};
static const char * const git_stash_store_usage[] = {
N_("git stash store [-m|--message <message>] [-q|--quiet] <commit>"),
NULL
};
static const char * const git_stash_push_usage[] = {
N_("git stash [push [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
" [-u|--include-untracked] [-a|--all] [-m|--message <message>]\n"
" [--] [<pathspec>...]]"),
NULL
};
static const char * const git_stash_save_usage[] = {
N_("git stash save [-p|--patch] [-k|--[no-]keep-index] [-q|--quiet]\n"
" [-u|--include-untracked] [-a|--all] [<message>]"),
NULL
};
static const char *ref_stash = "refs/stash";
static struct strbuf stash_index_path = STRBUF_INIT;
/*
* w_commit is set to the commit containing the working tree
* b_commit is set to the base commit
* i_commit is set to the commit containing the index tree
* u_commit is set to the commit containing the untracked files tree
* w_tree is set to the working tree
* b_tree is set to the base tree
* i_tree is set to the index tree
* u_tree is set to the untracked files tree
*/
struct stash_info {
struct object_id w_commit;
struct object_id b_commit;
struct object_id i_commit;
struct object_id u_commit;
struct object_id w_tree;
struct object_id b_tree;
struct object_id i_tree;
struct object_id u_tree;
struct strbuf revision;
int is_stash_ref;
int has_u;
};
static void free_stash_info(struct stash_info *info)
{
strbuf_release(&info->revision);
}
static void assert_stash_like(struct stash_info *info, const char *revision)
{
if (get_oidf(&info->b_commit, "%s^1", revision) ||
get_oidf(&info->w_tree, "%s:", revision) ||
get_oidf(&info->b_tree, "%s^1:", revision) ||
get_oidf(&info->i_tree, "%s^2:", revision))
die(_("'%s' is not a stash-like commit"), revision);
}
static int get_stash_info(struct stash_info *info, int argc, const char **argv)
{
int ret;
char *end_of_rev;
char *expanded_ref;
const char *revision;
const char *commit = NULL;
struct object_id dummy;
struct strbuf symbolic = STRBUF_INIT;
if (argc > 1) {
int i;
struct strbuf refs_msg = STRBUF_INIT;
for (i = 0; i < argc; i++)
strbuf_addf(&refs_msg, " '%s'", argv[i]);
fprintf_ln(stderr, _("Too many revisions specified:%s"),
refs_msg.buf);
strbuf_release(&refs_msg);
return -1;
}
if (argc == 1)
commit = argv[0];
strbuf_init(&info->revision, 0);
if (!commit) {
if (!ref_exists(ref_stash)) {
free_stash_info(info);
fprintf_ln(stderr, _("No stash entries found."));
return -1;
}
strbuf_addf(&info->revision, "%s@{0}", ref_stash);
} else if (strspn(commit, "0123456789") == strlen(commit)) {
strbuf_addf(&info->revision, "%s@{%s}", ref_stash, commit);
} else {
strbuf_addstr(&info->revision, commit);
}
revision = info->revision.buf;
if (get_oid(revision, &info->w_commit)) {
error(_("%s is not a valid reference"), revision);
free_stash_info(info);
return -1;
}
assert_stash_like(info, revision);
info->has_u = !get_oidf(&info->u_tree, "%s^3:", revision);
end_of_rev = strchrnul(revision, '@');
strbuf_add(&symbolic, revision, end_of_rev - revision);
ret = dwim_ref(symbolic.buf, symbolic.len, &dummy, &expanded_ref);
strbuf_release(&symbolic);
switch (ret) {
case 0: /* Not found, but valid ref */
info->is_stash_ref = 0;
break;
case 1:
info->is_stash_ref = !strcmp(expanded_ref, ref_stash);
break;
default: /* Invalid or ambiguous */
free_stash_info(info);
}
free(expanded_ref);
return !(ret == 0 || ret == 1);
}
static int do_clear_stash(void)
{
struct object_id obj;
if (get_oid(ref_stash, &obj))
return 0;
return delete_ref(NULL, ref_stash, &obj, 0);
}
static int clear_stash(int argc, const char **argv, const char *prefix)
{
struct option options[] = {
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_clear_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
if (argc)
return error(_("git stash clear with parameters is "
"unimplemented"));
return do_clear_stash();
}
static int reset_tree(struct object_id *i_tree, int update, int reset)
{
int nr_trees = 1;
struct unpack_trees_options opts;
struct tree_desc t[MAX_UNPACK_TREES];
struct tree *tree;
struct lock_file lock_file = LOCK_INIT;
read_cache_preload(NULL);
if (refresh_cache(REFRESH_QUIET))
return -1;
hold_locked_index(&lock_file, LOCK_DIE_ON_ERROR);
memset(&opts, 0, sizeof(opts));
tree = parse_tree_indirect(i_tree);
if (parse_tree(tree))
return -1;
init_tree_desc(t, tree->buffer, tree->size);
opts.head_idx = 1;
opts.src_index = &the_index;
opts.dst_index = &the_index;
opts.merge = 1;
opts.reset = reset;
opts.update = update;
opts.fn = oneway_merge;
if (unpack_trees(nr_trees, t, &opts))
return -1;
if (write_locked_index(&the_index, &lock_file, COMMIT_LOCK))
return error(_("unable to write new index file"));
return 0;
}
static int diff_tree_binary(struct strbuf *out, struct object_id *w_commit)
{
struct child_process cp = CHILD_PROCESS_INIT;
const char *w_commit_hex = oid_to_hex(w_commit);
/*
* Diff-tree would not be very hard to replace with a native function,
* however it should be done together with apply_cached.
*/
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "diff-tree", "--binary", NULL);
argv_array_pushf(&cp.args, "%s^2^..%s^2", w_commit_hex, w_commit_hex);
return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
}
static int apply_cached(struct strbuf *out)
{
struct child_process cp = CHILD_PROCESS_INIT;
/*
* Apply currently only reads either from stdin or a file, thus
* apply_all_patches would have to be updated to optionally take a
* buffer.
*/
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "apply", "--cached", NULL);
return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
}
static int reset_head(void)
{
struct child_process cp = CHILD_PROCESS_INIT;
/*
* Reset is overall quite simple, however there is no current public
* API for resetting.
*/
cp.git_cmd = 1;
argv_array_push(&cp.args, "reset");
return run_command(&cp);
}
static void add_diff_to_buf(struct diff_queue_struct *q,
struct diff_options *options,
void *data)
{
int i;
for (i = 0; i < q->nr; i++) {
strbuf_addstr(data, q->queue[i]->one->path);
/* NUL-terminate: will be fed to update-index -z */
strbuf_addch(data, '\0');
}
}
static int get_newly_staged(struct strbuf *out, struct object_id *c_tree)
{
struct child_process cp = CHILD_PROCESS_INIT;
const char *c_tree_hex = oid_to_hex(c_tree);
/*
* diff-index is very similar to diff-tree above, and should be
* converted together with update_index.
*/
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "diff-index", "--cached", "--name-only",
"--diff-filter=A", NULL);
argv_array_push(&cp.args, c_tree_hex);
return pipe_command(&cp, NULL, 0, out, 0, NULL, 0);
}
static int update_index(struct strbuf *out)
{
struct child_process cp = CHILD_PROCESS_INIT;
/*
* Update-index is very complicated and may need to have a public
* function exposed in order to remove this forking.
*/
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "update-index", "--add", "--stdin", NULL);
return pipe_command(&cp, out->buf, out->len, NULL, 0, NULL, 0);
}
static int restore_untracked(struct object_id *u_tree)
{
int res;
struct child_process cp = CHILD_PROCESS_INIT;
/*
* We need to run restore files from a given index, but without
* affecting the current index, so we use GIT_INDEX_FILE with
* run_command to fork processes that will not interfere.
*/
cp.git_cmd = 1;
argv_array_push(&cp.args, "read-tree");
argv_array_push(&cp.args, oid_to_hex(u_tree));
argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
stash_index_path.buf);
if (run_command(&cp)) {
remove_path(stash_index_path.buf);
return -1;
}
child_process_init(&cp);
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "checkout-index", "--all", NULL);
argv_array_pushf(&cp.env_array, "GIT_INDEX_FILE=%s",
stash_index_path.buf);
res = run_command(&cp);
remove_path(stash_index_path.buf);
return res;
}
static int do_apply_stash(const char *prefix, struct stash_info *info,
int index, int quiet)
{
int ret;
int has_index = index;
struct merge_options o;
struct object_id c_tree;
struct object_id index_tree;
struct commit *result;
const struct object_id *bases[1];
read_cache_preload(NULL);
if (refresh_and_write_cache(REFRESH_QUIET, 0, 0))
return -1;
if (write_cache_as_tree(&c_tree, 0, NULL))
return error(_("cannot apply a stash in the middle of a merge"));
if (index) {
if (oideq(&info->b_tree, &info->i_tree) ||
oideq(&c_tree, &info->i_tree)) {
has_index = 0;
} else {
struct strbuf out = STRBUF_INIT;
if (diff_tree_binary(&out, &info->w_commit)) {
strbuf_release(&out);
return error(_("could not generate diff %s^!."),
oid_to_hex(&info->w_commit));
}
ret = apply_cached(&out);
strbuf_release(&out);
if (ret)
return error(_("conflicts in index."
"Try without --index."));
discard_cache();
read_cache();
if (write_cache_as_tree(&index_tree, 0, NULL))
return error(_("could not save index tree"));
reset_head();
discard_cache();
read_cache();
}
}
if (info->has_u && restore_untracked(&info->u_tree))
return error(_("could not restore untracked files from stash"));
init_merge_options(&o, the_repository);
o.branch1 = "Updated upstream";
o.branch2 = "Stashed changes";
if (oideq(&info->b_tree, &c_tree))
o.branch1 = "Version stash was based on";
if (quiet)
o.verbosity = 0;
if (o.verbosity >= 3)
printf_ln(_("Merging %s with %s"), o.branch1, o.branch2);
bases[0] = &info->b_tree;
ret = merge_recursive_generic(&o, &c_tree, &info->w_tree, 1, bases,
&result);
if (ret) {
rerere(0);
if (index)
fprintf_ln(stderr, _("Index was not unstashed."));
return ret;
}
if (has_index) {
if (reset_tree(&index_tree, 0, 0))
return -1;
} else {
struct strbuf out = STRBUF_INIT;
if (get_newly_staged(&out, &c_tree)) {
strbuf_release(&out);
return -1;
}
if (reset_tree(&c_tree, 0, 1)) {
strbuf_release(&out);
return -1;
}
ret = update_index(&out);
strbuf_release(&out);
if (ret)
return -1;
discard_cache();
}
if (quiet) {
if (refresh_and_write_cache(REFRESH_QUIET, 0, 0))
warning("could not refresh index");
} else {
struct child_process cp = CHILD_PROCESS_INIT;
/*
* Status is quite simple and could be replaced with calls to
* wt_status in the future, but it adds complexities which may
* require more tests.
*/
cp.git_cmd = 1;
cp.dir = prefix;
argv_array_pushf(&cp.env_array, GIT_WORK_TREE_ENVIRONMENT"=%s",
absolute_path(get_git_work_tree()));
argv_array_pushf(&cp.env_array, GIT_DIR_ENVIRONMENT"=%s",
absolute_path(get_git_dir()));
argv_array_push(&cp.args, "status");
run_command(&cp);
}
return 0;
}
static int apply_stash(int argc, const char **argv, const char *prefix)
{
int ret;
int quiet = 0;
int index = 0;
struct stash_info info;
struct option options[] = {
OPT__QUIET(&quiet, N_("be quiet, only report errors")),
OPT_BOOL(0, "index", &index,
N_("attempt to recreate the index")),
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_apply_usage, 0);
if (get_stash_info(&info, argc, argv))
return -1;
ret = do_apply_stash(prefix, &info, index, quiet);
free_stash_info(&info);
return ret;
}
static int do_drop_stash(struct stash_info *info, int quiet)
{
int ret;
struct child_process cp_reflog = CHILD_PROCESS_INIT;
struct child_process cp = CHILD_PROCESS_INIT;
/*
* reflog does not provide a simple function for deleting refs. One will
* need to be added to avoid implementing too much reflog code here
*/
cp_reflog.git_cmd = 1;
argv_array_pushl(&cp_reflog.args, "reflog", "delete", "--updateref",
"--rewrite", NULL);
argv_array_push(&cp_reflog.args, info->revision.buf);
ret = run_command(&cp_reflog);
if (!ret) {
if (!quiet)
printf_ln(_("Dropped %s (%s)"), info->revision.buf,
oid_to_hex(&info->w_commit));
} else {
return error(_("%s: Could not drop stash entry"),
info->revision.buf);
}
/*
* This could easily be replaced by get_oid, but currently it will throw
* a fatal error when a reflog is empty, which we can not recover from.
*/
cp.git_cmd = 1;
/* Even though --quiet is specified, rev-parse still outputs the hash */
cp.no_stdout = 1;
argv_array_pushl(&cp.args, "rev-parse", "--verify", "--quiet", NULL);
argv_array_pushf(&cp.args, "%s@{0}", ref_stash);
ret = run_command(&cp);
/* do_clear_stash if we just dropped the last stash entry */
if (ret)
do_clear_stash();
return 0;
}
static void assert_stash_ref(struct stash_info *info)
{
if (!info->is_stash_ref) {
error(_("'%s' is not a stash reference"), info->revision.buf);
free_stash_info(info);
exit(1);
}
}
static int drop_stash(int argc, const char **argv, const char *prefix)
{
int ret;
int quiet = 0;
struct stash_info info;
struct option options[] = {
OPT__QUIET(&quiet, N_("be quiet, only report errors")),
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_drop_usage, 0);
if (get_stash_info(&info, argc, argv))
return -1;
assert_stash_ref(&info);
ret = do_drop_stash(&info, quiet);
free_stash_info(&info);
return ret;
}
static int pop_stash(int argc, const char **argv, const char *prefix)
{
int ret;
int index = 0;
int quiet = 0;
struct stash_info info;
struct option options[] = {
OPT__QUIET(&quiet, N_("be quiet, only report errors")),
OPT_BOOL(0, "index", &index,
N_("attempt to recreate the index")),
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_pop_usage, 0);
if (get_stash_info(&info, argc, argv))
return -1;
assert_stash_ref(&info);
if ((ret = do_apply_stash(prefix, &info, index, quiet)))
printf_ln(_("The stash entry is kept in case "
"you need it again."));
else
ret = do_drop_stash(&info, quiet);
free_stash_info(&info);
return ret;
}
static int branch_stash(int argc, const char **argv, const char *prefix)
{
int ret;
const char *branch = NULL;
struct stash_info info;
struct child_process cp = CHILD_PROCESS_INIT;
struct option options[] = {
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_branch_usage, 0);
if (!argc) {
fprintf_ln(stderr, _("No branch name specified"));
return -1;
}
branch = argv[0];
if (get_stash_info(&info, argc - 1, argv + 1))
return -1;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "checkout", "-b", NULL);
argv_array_push(&cp.args, branch);
argv_array_push(&cp.args, oid_to_hex(&info.b_commit));
ret = run_command(&cp);
if (!ret)
ret = do_apply_stash(prefix, &info, 1, 0);
if (!ret && info.is_stash_ref)
ret = do_drop_stash(&info, 0);
free_stash_info(&info);
return ret;
}
static int list_stash(int argc, const char **argv, const char *prefix)
{
struct child_process cp = CHILD_PROCESS_INIT;
struct option options[] = {
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_list_usage,
PARSE_OPT_KEEP_UNKNOWN);
if (!ref_exists(ref_stash))
return 0;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "log", "--format=%gd: %gs", "-g",
"--first-parent", "-m", NULL);
argv_array_pushv(&cp.args, argv);
argv_array_push(&cp.args, ref_stash);
argv_array_push(&cp.args, "--");
return run_command(&cp);
}
static int show_stat = 1;
static int show_patch;
static int git_stash_config(const char *var, const char *value, void *cb)
{
if (!strcmp(var, "stash.showstat")) {
show_stat = git_config_bool(var, value);
return 0;
}
if (!strcmp(var, "stash.showpatch")) {
show_patch = git_config_bool(var, value);
return 0;
}
return git_default_config(var, value, cb);
}
static int show_stash(int argc, const char **argv, const char *prefix)
{
int i;
int ret = 0;
struct stash_info info;
struct rev_info rev;
struct argv_array stash_args = ARGV_ARRAY_INIT;
struct argv_array revision_args = ARGV_ARRAY_INIT;
struct option options[] = {
OPT_END()
};
init_diff_ui_defaults();
git_config(git_diff_ui_config, NULL);
init_revisions(&rev, prefix);
argv_array_push(&revision_args, argv[0]);
for (i = 1; i < argc; i++) {
if (argv[i][0] != '-')
argv_array_push(&stash_args, argv[i]);
else
argv_array_push(&revision_args, argv[i]);
}
ret = get_stash_info(&info, stash_args.argc, stash_args.argv);
argv_array_clear(&stash_args);
if (ret)
return -1;
/*
* The config settings are applied only if there are not passed
* any options.
*/
if (revision_args.argc == 1) {
git_config(git_stash_config, NULL);
if (show_stat)
rev.diffopt.output_format = DIFF_FORMAT_DIFFSTAT;
if (show_patch)
rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
if (!show_stat && !show_patch) {
free_stash_info(&info);
return 0;
}
}
argc = setup_revisions(revision_args.argc, revision_args.argv, &rev, NULL);
if (argc > 1) {
free_stash_info(&info);
usage_with_options(git_stash_show_usage, options);
}
if (!rev.diffopt.output_format) {
rev.diffopt.output_format = DIFF_FORMAT_PATCH;
diff_setup_done(&rev.diffopt);
}
rev.diffopt.flags.recursive = 1;
setup_diff_pager(&rev.diffopt);
diff_tree_oid(&info.b_commit, &info.w_commit, "", &rev.diffopt);
log_tree_diff_flush(&rev);
free_stash_info(&info);
return diff_result_code(&rev.diffopt, 0);
}
static int do_store_stash(const struct object_id *w_commit, const char *stash_msg,
int quiet)
{
if (!stash_msg)
stash_msg = "Created via \"git stash store\".";
if (update_ref(stash_msg, ref_stash, w_commit, NULL,
REF_FORCE_CREATE_REFLOG,
quiet ? UPDATE_REFS_QUIET_ON_ERR :
UPDATE_REFS_MSG_ON_ERR)) {
if (!quiet) {
fprintf_ln(stderr, _("Cannot update %s with %s"),
ref_stash, oid_to_hex(w_commit));
}
return -1;
}
return 0;
}
static int store_stash(int argc, const char **argv, const char *prefix)
{
int quiet = 0;
const char *stash_msg = NULL;
struct object_id obj;
struct object_context dummy;
struct option options[] = {
OPT__QUIET(&quiet, N_("be quiet")),
OPT_STRING('m', "message", &stash_msg, "message",
N_("stash message")),
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_store_usage,
PARSE_OPT_KEEP_UNKNOWN);
if (argc != 1) {
if (!quiet)
fprintf_ln(stderr, _("\"git stash store\" requires one "
"<commit> argument"));
return -1;
}
if (get_oid_with_context(the_repository,
argv[0], quiet ? GET_OID_QUIETLY : 0, &obj,
&dummy)) {
if (!quiet)
fprintf_ln(stderr, _("Cannot update %s with %s"),
ref_stash, argv[0]);
return -1;
}
return do_store_stash(&obj, stash_msg, quiet);
}
static void add_pathspecs(struct argv_array *args,
const struct pathspec *ps) {
int i;
for (i = 0; i < ps->nr; i++)
argv_array_push(args, ps->items[i].original);
}
/*
* `untracked_files` will be filled with the names of untracked files.
* The return value is:
*
* = 0 if there are not any untracked files
* > 0 if there are untracked files
*/
static int get_untracked_files(const struct pathspec *ps, int include_untracked,
struct strbuf *untracked_files)
{
int i;
int max_len;
int found = 0;
char *seen;
struct dir_struct dir;
memset(&dir, 0, sizeof(dir));
if (include_untracked != INCLUDE_ALL_FILES)
setup_standard_excludes(&dir);
seen = xcalloc(ps->nr, 1);
max_len = fill_directory(&dir, the_repository->index, ps);
for (i = 0; i < dir.nr; i++) {
struct dir_entry *ent = dir.entries[i];
if (dir_path_match(&the_index, ent, ps, max_len, seen)) {
found++;
strbuf_addstr(untracked_files, ent->name);
/* NUL-terminate: will be fed to update-index -z */
strbuf_addch(untracked_files, '\0');
}
free(ent);
}
free(seen);
free(dir.entries);
free(dir.ignored);
clear_directory(&dir);
return found;
}
/*
* The return value of `check_changes_tracked_files()` can be:
*
* < 0 if there was an error
* = 0 if there are no changes.
* > 0 if there are changes.
*/
static int check_changes_tracked_files(const struct pathspec *ps)
{
int result;
struct rev_info rev;
struct object_id dummy;
int ret = 0;
/* No initial commit. */
if (get_oid("HEAD", &dummy))
return -1;
if (read_cache() < 0)
return -1;
init_revisions(&rev, NULL);
copy_pathspec(&rev.prune_data, ps);
rev.diffopt.flags.quick = 1;
rev.diffopt.flags.ignore_submodules = 1;
rev.abbrev = 0;
add_head_to_pending(&rev);
diff_setup_done(&rev.diffopt);
result = run_diff_index(&rev, 1);
if (diff_result_code(&rev.diffopt, result)) {
ret = 1;
goto done;
}
object_array_clear(&rev.pending);
result = run_diff_files(&rev, 0);
if (diff_result_code(&rev.diffopt, result)) {
ret = 1;
goto done;
}
done:
clear_pathspec(&rev.prune_data);
return ret;
}
/*
* The function will fill `untracked_files` with the names of untracked files
* It will return 1 if there were any changes and 0 if there were not.
*/
static int check_changes(const struct pathspec *ps, int include_untracked,
struct strbuf *untracked_files)
{
int ret = 0;
if (check_changes_tracked_files(ps))
ret = 1;
if (include_untracked && get_untracked_files(ps, include_untracked,
untracked_files))
ret = 1;
return ret;
}
static int save_untracked_files(struct stash_info *info, struct strbuf *msg,
struct strbuf files)
{
int ret = 0;
struct strbuf untracked_msg = STRBUF_INIT;
struct child_process cp_upd_index = CHILD_PROCESS_INIT;
struct index_state istate = { NULL };
cp_upd_index.git_cmd = 1;
argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
"--remove", "--stdin", NULL);
argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
stash_index_path.buf);
strbuf_addf(&untracked_msg, "untracked files on %s\n", msg->buf);
if (pipe_command(&cp_upd_index, files.buf, files.len, NULL, 0,
NULL, 0)) {
ret = -1;
goto done;
}
if (write_index_as_tree(&info->u_tree, &istate, stash_index_path.buf, 0,
NULL)) {
ret = -1;
goto done;
}
if (commit_tree(untracked_msg.buf, untracked_msg.len,
&info->u_tree, NULL, &info->u_commit, NULL, NULL)) {
ret = -1;
goto done;
}
done:
discard_index(&istate);
strbuf_release(&untracked_msg);
remove_path(stash_index_path.buf);
return ret;
}
static int stash_patch(struct stash_info *info, const struct pathspec *ps,
struct strbuf *out_patch, int quiet)
{
int ret = 0;
struct child_process cp_read_tree = CHILD_PROCESS_INIT;
struct child_process cp_add_i = CHILD_PROCESS_INIT;
struct child_process cp_diff_tree = CHILD_PROCESS_INIT;
struct index_state istate = { NULL };
remove_path(stash_index_path.buf);
cp_read_tree.git_cmd = 1;
argv_array_pushl(&cp_read_tree.args, "read-tree", "HEAD", NULL);
argv_array_pushf(&cp_read_tree.env_array, "GIT_INDEX_FILE=%s",
stash_index_path.buf);
if (run_command(&cp_read_tree)) {
ret = -1;
goto done;
}
/* Find out what the user wants. */
cp_add_i.git_cmd = 1;
argv_array_pushl(&cp_add_i.args, "add--interactive", "--patch=stash",
"--", NULL);
add_pathspecs(&cp_add_i.args, ps);
argv_array_pushf(&cp_add_i.env_array, "GIT_INDEX_FILE=%s",
stash_index_path.buf);
if (run_command(&cp_add_i)) {
ret = -1;
goto done;
}
/* State of the working tree. */
if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
NULL)) {
ret = -1;
goto done;
}
cp_diff_tree.git_cmd = 1;
argv_array_pushl(&cp_diff_tree.args, "diff-tree", "-p", "HEAD",
oid_to_hex(&info->w_tree), "--", NULL);
if (pipe_command(&cp_diff_tree, NULL, 0, out_patch, 0, NULL, 0)) {
ret = -1;
goto done;
}
if (!out_patch->len) {
if (!quiet)
fprintf_ln(stderr, _("No changes selected"));
ret = 1;
}
done:
discard_index(&istate);
remove_path(stash_index_path.buf);
return ret;
}
static int stash_working_tree(struct stash_info *info, const struct pathspec *ps)
{
int ret = 0;
struct rev_info rev;
struct child_process cp_upd_index = CHILD_PROCESS_INIT;
struct strbuf diff_output = STRBUF_INIT;
struct index_state istate = { NULL };
init_revisions(&rev, NULL);
copy_pathspec(&rev.prune_data, ps);
set_alternate_index_output(stash_index_path.buf);
if (reset_tree(&info->i_tree, 0, 0)) {
ret = -1;
goto done;
}
set_alternate_index_output(NULL);
rev.diffopt.output_format = DIFF_FORMAT_CALLBACK;
rev.diffopt.format_callback = add_diff_to_buf;
rev.diffopt.format_callback_data = &diff_output;
if (read_cache_preload(&rev.diffopt.pathspec) < 0) {
ret = -1;
goto done;
}
add_pending_object(&rev, parse_object(the_repository, &info->b_commit),
"");
if (run_diff_index(&rev, 0)) {
ret = -1;
goto done;
}
cp_upd_index.git_cmd = 1;
argv_array_pushl(&cp_upd_index.args, "update-index", "-z", "--add",
"--remove", "--stdin", NULL);
argv_array_pushf(&cp_upd_index.env_array, "GIT_INDEX_FILE=%s",
stash_index_path.buf);
if (pipe_command(&cp_upd_index, diff_output.buf, diff_output.len,
NULL, 0, NULL, 0)) {
ret = -1;
goto done;
}
if (write_index_as_tree(&info->w_tree, &istate, stash_index_path.buf, 0,
NULL)) {
ret = -1;
goto done;
}
done:
discard_index(&istate);
UNLEAK(rev);
object_array_clear(&rev.pending);
clear_pathspec(&rev.prune_data);
strbuf_release(&diff_output);
remove_path(stash_index_path.buf);
return ret;
}
static int do_create_stash(const struct pathspec *ps, struct strbuf *stash_msg_buf,
int include_untracked, int patch_mode,
struct stash_info *info, struct strbuf *patch,
int quiet)
{
int ret = 0;
int flags = 0;
int untracked_commit_option = 0;
const char *head_short_sha1 = NULL;
const char *branch_ref = NULL;
const char *branch_name = "(no branch)";
struct commit *head_commit = NULL;
struct commit_list *parents = NULL;
struct strbuf msg = STRBUF_INIT;
struct strbuf commit_tree_label = STRBUF_INIT;
struct strbuf untracked_files = STRBUF_INIT;
prepare_fallback_ident("git stash", "git@stash");
read_cache_preload(NULL);
if (refresh_and_write_cache(REFRESH_QUIET, 0, 0) < 0) {
ret = -1;
goto done;
}
if (get_oid("HEAD", &info->b_commit)) {
if (!quiet)
fprintf_ln(stderr, _("You do not have "
"the initial commit yet"));
ret = -1;
goto done;
} else {
head_commit = lookup_commit(the_repository, &info->b_commit);
}
if (!check_changes(ps, include_untracked, &untracked_files)) {
ret = 1;
goto done;
}
branch_ref = resolve_ref_unsafe("HEAD", 0, NULL, &flags);
if (flags & REF_ISSYMREF)
branch_name = strrchr(branch_ref, '/') + 1;
head_short_sha1 = find_unique_abbrev(&head_commit->object.oid,
DEFAULT_ABBREV);
strbuf_addf(&msg, "%s: %s ", branch_name, head_short_sha1);
pp_commit_easy(CMIT_FMT_ONELINE, head_commit, &msg);
strbuf_addf(&commit_tree_label, "index on %s\n", msg.buf);
commit_list_insert(head_commit, &parents);
if (write_cache_as_tree(&info->i_tree, 0, NULL) ||
commit_tree(commit_tree_label.buf, commit_tree_label.len,
&info->i_tree, parents, &info->i_commit, NULL, NULL)) {
if (!quiet)
fprintf_ln(stderr, _("Cannot save the current "
"index state"));
ret = -1;
goto done;
}
if (include_untracked) {
if (save_untracked_files(info, &msg, untracked_files)) {
if (!quiet)
fprintf_ln(stderr, _("Cannot save "
"the untracked files"));
ret = -1;
goto done;
}
untracked_commit_option = 1;
}
if (patch_mode) {
ret = stash_patch(info, ps, patch, quiet);
if (ret < 0) {
if (!quiet)
fprintf_ln(stderr, _("Cannot save the current "
"worktree state"));
goto done;
} else if (ret > 0) {
goto done;
}
} else {
if (stash_working_tree(info, ps)) {
if (!quiet)
fprintf_ln(stderr, _("Cannot save the current "
"worktree state"));
ret = -1;
goto done;
}
}
if (!stash_msg_buf->len)
strbuf_addf(stash_msg_buf, "WIP on %s", msg.buf);
else
strbuf_insertf(stash_msg_buf, 0, "On %s: ", branch_name);
/*
* `parents` will be empty after calling `commit_tree()`, so there is
* no need to call `free_commit_list()`
*/
parents = NULL;
if (untracked_commit_option)
commit_list_insert(lookup_commit(the_repository,
&info->u_commit),
&parents);
commit_list_insert(lookup_commit(the_repository, &info->i_commit),
&parents);
commit_list_insert(head_commit, &parents);
if (commit_tree(stash_msg_buf->buf, stash_msg_buf->len, &info->w_tree,
parents, &info->w_commit, NULL, NULL)) {
if (!quiet)
fprintf_ln(stderr, _("Cannot record "
"working tree state"));
ret = -1;
goto done;
}
done:
strbuf_release(&commit_tree_label);
strbuf_release(&msg);
strbuf_release(&untracked_files);
return ret;
}
static int create_stash(int argc, const char **argv, const char *prefix)
{
int ret = 0;
struct strbuf stash_msg_buf = STRBUF_INIT;
struct stash_info info;
struct pathspec ps;
/* Starting with argv[1], since argv[0] is "create" */
strbuf_join_argv(&stash_msg_buf, argc - 1, ++argv, ' ');
memset(&ps, 0, sizeof(ps));
if (!check_changes_tracked_files(&ps))
return 0;
ret = do_create_stash(&ps, &stash_msg_buf, 0, 0, &info,
NULL, 0);
if (!ret)
printf_ln("%s", oid_to_hex(&info.w_commit));
strbuf_release(&stash_msg_buf);
return ret;
}
static int do_push_stash(const struct pathspec *ps, const char *stash_msg, int quiet,
int keep_index, int patch_mode, int include_untracked)
{
int ret = 0;
struct stash_info info;
struct strbuf patch = STRBUF_INIT;
struct strbuf stash_msg_buf = STRBUF_INIT;
struct strbuf untracked_files = STRBUF_INIT;
if (patch_mode && keep_index == -1)
keep_index = 1;
if (patch_mode && include_untracked) {
fprintf_ln(stderr, _("Can't use --patch and --include-untracked"
" or --all at the same time"));
ret = -1;
goto done;
}
read_cache_preload(NULL);
if (!include_untracked && ps->nr) {
int i;
char *ps_matched = xcalloc(ps->nr, 1);
for (i = 0; i < active_nr; i++)
ce_path_match(&the_index, active_cache[i], ps,
ps_matched);
if (report_path_error(ps_matched, ps)) {
fprintf_ln(stderr, _("Did you forget to 'git add'?"));
ret = -1;
free(ps_matched);
goto done;
}
free(ps_matched);
}
if (refresh_and_write_cache(REFRESH_QUIET, 0, 0)) {
ret = -1;
goto done;
}
if (!check_changes(ps, include_untracked, &untracked_files)) {
if (!quiet)
printf_ln(_("No local changes to save"));
goto done;
}
if (!reflog_exists(ref_stash) && do_clear_stash()) {
ret = -1;
if (!quiet)
fprintf_ln(stderr, _("Cannot initialize stash"));
goto done;
}
if (stash_msg)
strbuf_addstr(&stash_msg_buf, stash_msg);
if (do_create_stash(ps, &stash_msg_buf, include_untracked, patch_mode,
&info, &patch, quiet)) {
ret = -1;
goto done;
}
if (do_store_stash(&info.w_commit, stash_msg_buf.buf, 1)) {
ret = -1;
if (!quiet)
fprintf_ln(stderr, _("Cannot save the current status"));
goto done;
}
if (!quiet)
printf_ln(_("Saved working directory and index state %s"),
stash_msg_buf.buf);
if (!patch_mode) {
if (include_untracked && !ps->nr) {
struct child_process cp = CHILD_PROCESS_INIT;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "clean", "--force",
"--quiet", "-d", NULL);
if (include_untracked == INCLUDE_ALL_FILES)
argv_array_push(&cp.args, "-x");
if (run_command(&cp)) {
ret = -1;
goto done;
}
}
discard_cache();
if (ps->nr) {
struct child_process cp_add = CHILD_PROCESS_INIT;
struct child_process cp_diff = CHILD_PROCESS_INIT;
struct child_process cp_apply = CHILD_PROCESS_INIT;
struct strbuf out = STRBUF_INIT;
cp_add.git_cmd = 1;
argv_array_push(&cp_add.args, "add");
if (!include_untracked)
argv_array_push(&cp_add.args, "-u");
if (include_untracked == INCLUDE_ALL_FILES)
argv_array_push(&cp_add.args, "--force");
argv_array_push(&cp_add.args, "--");
add_pathspecs(&cp_add.args, ps);
if (run_command(&cp_add)) {
ret = -1;
goto done;
}
cp_diff.git_cmd = 1;
argv_array_pushl(&cp_diff.args, "diff-index", "-p",
"--cached", "--binary", "HEAD", "--",
NULL);
add_pathspecs(&cp_diff.args, ps);
if (pipe_command(&cp_diff, NULL, 0, &out, 0, NULL, 0)) {
ret = -1;
goto done;
}
cp_apply.git_cmd = 1;
argv_array_pushl(&cp_apply.args, "apply", "--index",
"-R", NULL);
if (pipe_command(&cp_apply, out.buf, out.len, NULL, 0,
NULL, 0)) {
ret = -1;
goto done;
}
} else {
struct child_process cp = CHILD_PROCESS_INIT;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "reset", "--hard", "-q",
"--no-recurse-submodules", NULL);
if (run_command(&cp)) {
ret = -1;
goto done;
}
}
if (keep_index == 1 && !is_null_oid(&info.i_tree)) {
struct child_process cp = CHILD_PROCESS_INIT;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "checkout", "--no-overlay",
oid_to_hex(&info.i_tree), "--", NULL);
if (!ps->nr)
argv_array_push(&cp.args, ":/");
else
add_pathspecs(&cp.args, ps);
if (run_command(&cp)) {
ret = -1;
goto done;
}
}
goto done;
} else {
struct child_process cp = CHILD_PROCESS_INIT;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "apply", "-R", NULL);
if (pipe_command(&cp, patch.buf, patch.len, NULL, 0, NULL, 0)) {
if (!quiet)
fprintf_ln(stderr, _("Cannot remove "
"worktree changes"));
ret = -1;
goto done;
}
if (keep_index < 1) {
struct child_process cp = CHILD_PROCESS_INIT;
cp.git_cmd = 1;
argv_array_pushl(&cp.args, "reset", "-q", "--", NULL);
add_pathspecs(&cp.args, ps);
if (run_command(&cp)) {
ret = -1;
goto done;
}
}
goto done;
}
done:
strbuf_release(&stash_msg_buf);
return ret;
}
static int push_stash(int argc, const char **argv, const char *prefix)
{
int keep_index = -1;
int patch_mode = 0;
int include_untracked = 0;
int quiet = 0;
const char *stash_msg = NULL;
struct pathspec ps;
struct option options[] = {
OPT_BOOL('k', "keep-index", &keep_index,
N_("keep index")),
OPT_BOOL('p', "patch", &patch_mode,
N_("stash in patch mode")),
OPT__QUIET(&quiet, N_("quiet mode")),
OPT_BOOL('u', "include-untracked", &include_untracked,
N_("include untracked files in stash")),
OPT_SET_INT('a', "all", &include_untracked,
N_("include ignore files"), 2),
OPT_STRING('m', "message", &stash_msg, N_("message"),
N_("stash message")),
OPT_END()
};
if (argc)
argc = parse_options(argc, argv, prefix, options,
git_stash_push_usage,
0);
parse_pathspec(&ps, 0, PATHSPEC_PREFER_FULL | PATHSPEC_PREFIX_ORIGIN,
prefix, argv);
return do_push_stash(&ps, stash_msg, quiet, keep_index, patch_mode,
include_untracked);
}
static int save_stash(int argc, const char **argv, const char *prefix)
{
int keep_index = -1;
int patch_mode = 0;
int include_untracked = 0;
int quiet = 0;
int ret = 0;
const char *stash_msg = NULL;
struct pathspec ps;
struct strbuf stash_msg_buf = STRBUF_INIT;
struct option options[] = {
OPT_BOOL('k', "keep-index", &keep_index,
N_("keep index")),
OPT_BOOL('p', "patch", &patch_mode,
N_("stash in patch mode")),
OPT__QUIET(&quiet, N_("quiet mode")),
OPT_BOOL('u', "include-untracked", &include_untracked,
N_("include untracked files in stash")),
OPT_SET_INT('a', "all", &include_untracked,
N_("include ignore files"), 2),
OPT_STRING('m', "message", &stash_msg, "message",
N_("stash message")),
OPT_END()
};
argc = parse_options(argc, argv, prefix, options,
git_stash_save_usage,
PARSE_OPT_KEEP_DASHDASH);
if (argc)
stash_msg = strbuf_join_argv(&stash_msg_buf, argc, argv, ' ');
memset(&ps, 0, sizeof(ps));
ret = do_push_stash(&ps, stash_msg, quiet, keep_index,
patch_mode, include_untracked);
strbuf_release(&stash_msg_buf);
return ret;
}
static int use_builtin_stash(void)
{
struct child_process cp = CHILD_PROCESS_INIT;
struct strbuf out = STRBUF_INIT;
int ret, env = git_env_bool("GIT_TEST_STASH_USE_BUILTIN", -1);
if (env != -1)
return env;
argv_array_pushl(&cp.args,
"config", "--bool", "stash.usebuiltin", NULL);
cp.git_cmd = 1;
if (capture_command(&cp, &out, 6)) {
strbuf_release(&out);
return 1;
}
strbuf_trim(&out);
ret = !strcmp("true", out.buf);
strbuf_release(&out);
return ret;
}
int cmd_stash(int argc, const char **argv, const char *prefix)
{
int i = -1;
pid_t pid = getpid();
const char *index_file;
struct argv_array args = ARGV_ARRAY_INIT;
struct option options[] = {
OPT_END()
};
if (!use_builtin_stash()) {
const char *path = mkpath("%s/git-legacy-stash",
git_exec_path());
if (sane_execvp(path, (char **)argv) < 0)
die_errno(_("could not exec %s"), path);
else
BUG("sane_execvp() returned???");
}
prefix = setup_git_directory();
trace_repo_setup(prefix);
setup_work_tree();
git_config(git_diff_basic_config, NULL);
argc = parse_options(argc, argv, prefix, options, git_stash_usage,
PARSE_OPT_KEEP_UNKNOWN | PARSE_OPT_KEEP_DASHDASH);
index_file = get_index_file();
strbuf_addf(&stash_index_path, "%s.stash.%" PRIuMAX, index_file,
(uintmax_t)pid);
if (!argc)
return !!push_stash(0, NULL, prefix);
else if (!strcmp(argv[0], "apply"))
return !!apply_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "clear"))
return !!clear_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "drop"))
return !!drop_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "pop"))
return !!pop_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "branch"))
return !!branch_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "list"))
return !!list_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "show"))
return !!show_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "store"))
return !!store_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "create"))
return !!create_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "push"))
return !!push_stash(argc, argv, prefix);
else if (!strcmp(argv[0], "save"))
return !!save_stash(argc, argv, prefix);
else if (*argv[0] != '-')
usage_msg_opt(xstrfmt(_("unknown subcommand: %s"), argv[0]),
git_stash_usage, options);
if (strcmp(argv[0], "-p")) {
while (++i < argc && strcmp(argv[i], "--")) {
/*
* `akpqu` is a string which contains all short options,
* except `-m` which is verified separately.
*/
if ((strlen(argv[i]) == 2) && *argv[i] == '-' &&
strchr("akpqu", argv[i][1]))
continue;
if (!strcmp(argv[i], "--all") ||
!strcmp(argv[i], "--keep-index") ||
!strcmp(argv[i], "--no-keep-index") ||
!strcmp(argv[i], "--patch") ||
!strcmp(argv[i], "--quiet") ||
!strcmp(argv[i], "--include-untracked"))
continue;
/*
* `-m` and `--message=` are verified separately because
* they need to be immediately followed by a string
* (i.e.`-m"foobar"` or `--message="foobar"`).
*/
if (starts_with(argv[i], "-m") ||
starts_with(argv[i], "--message="))
continue;
usage_with_options(git_stash_usage, options);
}
}
argv_array_push(&args, "push");
argv_array_pushv(&args, argv);
return !!push_stash(args.argc, args.argv, prefix);
}
| devzero2000/git-core | builtin/stash.c | C | gpl-2.0 | 41,265 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/REC-html40/loose.dtd">
<HTML>
<HEAD>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<META name="GENERATOR" content="hevea 1.10">
<LINK rel="stylesheet" type="text/css" href="cascmd_fr.css">
<TITLE>Les fonctions de base sur les complexes : +,-,*,/,^</TITLE>
</HEAD>
<BODY >
<A HREF="cascmd_fr239.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
<A HREF="cascmd_fr241.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
<HR>
<H3 CLASS="subsection"><A NAME="htoc311">6.12.1</A> Les fonctions de base sur les complexes : <TT>+,-,*,/,^</TT></H3><P><A NAME="@default409"></A>
<TT>+,-,*,/,^</TT> sont les opérateurs habituels pour faire
des additions, des soustractions, des multiplications, des divisions et des
élévations à une puissance entière ou fractionnaire.<BR>
On tape :
</P><DIV CLASS="center"><TT>(1+2*i)</TT><CODE><TT>^</TT></CODE><TT>2</TT></DIV><P>
On obtient :
</P><DIV CLASS="center"><TT>-3+4*i</TT></DIV><HR>
<A HREF="cascmd_fr239.html"><IMG SRC="previous_motif.gif" ALT="Previous"></A>
<A HREF="index.html"><IMG SRC="contents_motif.gif" ALT="Up"></A>
<A HREF="cascmd_fr241.html"><IMG SRC="next_motif.gif" ALT="Next"></A>
</BODY>
</HTML>
| hiplayer/giac | giac/giac-1.2.1/doc/fr/cascmd_fr/cascmd_fr240.html | HTML | gpl-2.0 | 1,343 |
// PendingBuffer.cs
//
// Copyright (C) 2001 Mike Krueger
// Copyright (C) 2004 John Reilly
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 2001 Free Software Foundation, Inc.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
using System;
namespace AL.Utils.ZipLib.Zip.Compression
{
/// <summary>
/// This class is general purpose class for writing data to a buffer.
///
/// It allows you to write bits as well as bytes
/// Based on DeflaterPending.java
///
/// author of the original java version : Jochen Hoenicke
/// </summary>
public class PendingBuffer
{
#region Instance Fields
/// <summary>
/// Internal work buffer
/// </summary>
byte[] buffer_;
int start;
int end;
uint bits;
int bitCount;
#endregion
#region Constructors
/// <summary>
/// construct instance using default buffer size of 4096
/// </summary>
public PendingBuffer() : this( 4096 )
{
}
/// <summary>
/// construct instance using specified buffer size
/// </summary>
/// <param name="bufferSize">
/// size to use for internal buffer
/// </param>
public PendingBuffer(int bufferSize)
{
buffer_ = new byte[bufferSize];
}
#endregion
/// <summary>
/// Clear internal state/buffers
/// </summary>
public void Reset()
{
start = end = bitCount = 0;
}
/// <summary>
/// Write a byte to buffer
/// </summary>
/// <param name="value">
/// The value to write
/// </param>
public void WriteByte(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) value);
}
/// <summary>
/// Write a short value to buffer LSB first
/// </summary>
/// <param name="value">
/// The value to write.
/// </param>
public void WriteShort(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) value);
buffer_[end++] = unchecked((byte) (value >> 8));
}
/// <summary>
/// write an integer LSB first
/// </summary>
/// <param name="value">The value to write.</param>
public void WriteInt(int value)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) value);
buffer_[end++] = unchecked((byte) (value >> 8));
buffer_[end++] = unchecked((byte) (value >> 16));
buffer_[end++] = unchecked((byte) (value >> 24));
}
/// <summary>
/// Write a block of data to buffer
/// </summary>
/// <param name="block">data to write</param>
/// <param name="offset">offset of first byte to write</param>
/// <param name="length">number of bytes to write</param>
public void WriteBlock(byte[] block, int offset, int length)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
System.Array.Copy(block, offset, buffer_, end, length);
end += length;
}
/// <summary>
/// The number of bits written to the buffer
/// </summary>
public int BitCount {
get {
return bitCount;
}
}
/// <summary>
/// Align internal buffer on a byte boundary
/// </summary>
public void AlignToByte()
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
if (bitCount > 0)
{
buffer_[end++] = unchecked((byte) bits);
if (bitCount > 8) {
buffer_[end++] = unchecked((byte) (bits >> 8));
}
}
bits = 0;
bitCount = 0;
}
/// <summary>
/// Write bits to internal buffer
/// </summary>
/// <param name="b">source of bits</param>
/// <param name="count">number of bits to write</param>
public void WriteBits(int b, int count)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
// if (DeflaterConstants.DEBUGGING) {
// //Console.WriteLine("writeBits("+b+","+count+")");
// }
#endif
bits |= (uint)(b << bitCount);
bitCount += count;
if (bitCount >= 16) {
buffer_[end++] = unchecked((byte) bits);
buffer_[end++] = unchecked((byte) (bits >> 8));
bits >>= 16;
bitCount -= 16;
}
}
/// <summary>
/// Write a short value to internal buffer most significant byte first
/// </summary>
/// <param name="s">value to write</param>
public void WriteShortMSB(int s)
{
#if DebugDeflation
if (DeflaterConstants.DEBUGGING && (start != 0) )
{
throw new SharpZipBaseException("Debug check: start != 0");
}
#endif
buffer_[end++] = unchecked((byte) (s >> 8));
buffer_[end++] = unchecked((byte) s);
}
/// <summary>
/// Indicates if buffer has been flushed
/// </summary>
public bool IsFlushed {
get {
return end == 0;
}
}
/// <summary>
/// Flushes the pending buffer into the given output array. If the
/// output array is to small, only a partial flush is done.
/// </summary>
/// <param name="output">The output array.</param>
/// <param name="offset">The offset into output array.</param>
/// <param name="length">The maximum number of bytes to store.</param>
/// <returns>The number of bytes flushed.</returns>
public int Flush(byte[] output, int offset, int length)
{
if (bitCount >= 8) {
buffer_[end++] = unchecked((byte) bits);
bits >>= 8;
bitCount -= 8;
}
if (length > end - start) {
length = end - start;
System.Array.Copy(buffer_, start, output, offset, length);
start = 0;
end = 0;
} else {
System.Array.Copy(buffer_, start, output, offset, length);
start += length;
}
return length;
}
/// <summary>
/// Convert internal buffer to byte array.
/// Buffer is empty on completion
/// </summary>
/// <returns>
/// The internal buffer contents converted to a byte array.
/// </returns>
public byte[] ToByteArray()
{
byte[] result = new byte[end - start];
System.Array.Copy(buffer_, start, result, 0, result.Length);
start = 0;
end = 0;
return result;
}
}
}
| alexchentao/AL.Web | AL.Utils/Compress/Ziplib/Zip/Compression/PendingBuffer.cs | C# | gpl-2.0 | 8,060 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<div class="sourceContainer">
<pre><span class="sourceLineNo">001</span>/* ===========================================================<a name="line.1"></a>
<span class="sourceLineNo">002</span> * JFreeChart : a free chart library for the Java(tm) platform<a name="line.2"></a>
<span class="sourceLineNo">003</span> * ===========================================================<a name="line.3"></a>
<span class="sourceLineNo">004</span> *<a name="line.4"></a>
<span class="sourceLineNo">005</span> * (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.<a name="line.5"></a>
<span class="sourceLineNo">006</span> *<a name="line.6"></a>
<span class="sourceLineNo">007</span> * Project Info: http://www.jfree.org/jfreechart/index.html<a name="line.7"></a>
<span class="sourceLineNo">008</span> *<a name="line.8"></a>
<span class="sourceLineNo">009</span> * This library is free software; you can redistribute it and/or modify it<a name="line.9"></a>
<span class="sourceLineNo">010</span> * under the terms of the GNU Lesser General Public License as published by<a name="line.10"></a>
<span class="sourceLineNo">011</span> * the Free Software Foundation; either version 2.1 of the License, or<a name="line.11"></a>
<span class="sourceLineNo">012</span> * (at your option) any later version.<a name="line.12"></a>
<span class="sourceLineNo">013</span> *<a name="line.13"></a>
<span class="sourceLineNo">014</span> * This library is distributed in the hope that it will be useful, but<a name="line.14"></a>
<span class="sourceLineNo">015</span> * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY<a name="line.15"></a>
<span class="sourceLineNo">016</span> * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public<a name="line.16"></a>
<span class="sourceLineNo">017</span> * License for more details.<a name="line.17"></a>
<span class="sourceLineNo">018</span> *<a name="line.18"></a>
<span class="sourceLineNo">019</span> * You should have received a copy of the GNU Lesser General Public<a name="line.19"></a>
<span class="sourceLineNo">020</span> * License along with this library; if not, write to the Free Software<a name="line.20"></a>
<span class="sourceLineNo">021</span> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,<a name="line.21"></a>
<span class="sourceLineNo">022</span> * USA.<a name="line.22"></a>
<span class="sourceLineNo">023</span> *<a name="line.23"></a>
<span class="sourceLineNo">024</span> * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. <a name="line.24"></a>
<span class="sourceLineNo">025</span> * Other names may be trademarks of their respective owners.]<a name="line.25"></a>
<span class="sourceLineNo">026</span> *<a name="line.26"></a>
<span class="sourceLineNo">027</span> * ---------------------------<a name="line.27"></a>
<span class="sourceLineNo">028</span> * SimpleHistogramDataset.java<a name="line.28"></a>
<span class="sourceLineNo">029</span> * ---------------------------<a name="line.29"></a>
<span class="sourceLineNo">030</span> * (C) Copyright 2005-2008, by Object Refinery Limited and Contributors.<a name="line.30"></a>
<span class="sourceLineNo">031</span> *<a name="line.31"></a>
<span class="sourceLineNo">032</span> * Original Author: David Gilbert (for Object Refinery Limited);<a name="line.32"></a>
<span class="sourceLineNo">033</span> * Contributor(s): Sergei Ivanov;<a name="line.33"></a>
<span class="sourceLineNo">034</span> *<a name="line.34"></a>
<span class="sourceLineNo">035</span> * Changes<a name="line.35"></a>
<span class="sourceLineNo">036</span> * -------<a name="line.36"></a>
<span class="sourceLineNo">037</span> * 10-Jan-2005 : Version 1 (DG);<a name="line.37"></a>
<span class="sourceLineNo">038</span> * 21-May-2007 : Added clearObservations() and removeAllBins() (SI);<a name="line.38"></a>
<span class="sourceLineNo">039</span> * 10-Jul-2007 : Added null argument check to constructor (DG);<a name="line.39"></a>
<span class="sourceLineNo">040</span> *<a name="line.40"></a>
<span class="sourceLineNo">041</span> */<a name="line.41"></a>
<span class="sourceLineNo">042</span><a name="line.42"></a>
<span class="sourceLineNo">043</span>package org.jfree.data.statistics;<a name="line.43"></a>
<span class="sourceLineNo">044</span><a name="line.44"></a>
<span class="sourceLineNo">045</span>import java.io.Serializable;<a name="line.45"></a>
<span class="sourceLineNo">046</span>import java.util.ArrayList;<a name="line.46"></a>
<span class="sourceLineNo">047</span>import java.util.Collections;<a name="line.47"></a>
<span class="sourceLineNo">048</span>import java.util.Iterator;<a name="line.48"></a>
<span class="sourceLineNo">049</span>import java.util.List;<a name="line.49"></a>
<span class="sourceLineNo">050</span><a name="line.50"></a>
<span class="sourceLineNo">051</span>import org.jfree.data.DomainOrder;<a name="line.51"></a>
<span class="sourceLineNo">052</span>import org.jfree.data.general.DatasetChangeEvent;<a name="line.52"></a>
<span class="sourceLineNo">053</span>import org.jfree.data.xy.AbstractIntervalXYDataset;<a name="line.53"></a>
<span class="sourceLineNo">054</span>import org.jfree.data.xy.IntervalXYDataset;<a name="line.54"></a>
<span class="sourceLineNo">055</span>import org.jfree.util.ObjectUtilities;<a name="line.55"></a>
<span class="sourceLineNo">056</span>import org.jfree.util.PublicCloneable;<a name="line.56"></a>
<span class="sourceLineNo">057</span><a name="line.57"></a>
<span class="sourceLineNo">058</span>/**<a name="line.58"></a>
<span class="sourceLineNo">059</span> * A dataset used for creating simple histograms with custom defined bins.<a name="line.59"></a>
<span class="sourceLineNo">060</span> *<a name="line.60"></a>
<span class="sourceLineNo">061</span> * @see HistogramDataset<a name="line.61"></a>
<span class="sourceLineNo">062</span> */<a name="line.62"></a>
<span class="sourceLineNo">063</span>public class SimpleHistogramDataset extends AbstractIntervalXYDataset<a name="line.63"></a>
<span class="sourceLineNo">064</span> implements IntervalXYDataset, Cloneable, PublicCloneable,<a name="line.64"></a>
<span class="sourceLineNo">065</span> Serializable {<a name="line.65"></a>
<span class="sourceLineNo">066</span><a name="line.66"></a>
<span class="sourceLineNo">067</span> /** For serialization. */<a name="line.67"></a>
<span class="sourceLineNo">068</span> private static final long serialVersionUID = 7997996479768018443L;<a name="line.68"></a>
<span class="sourceLineNo">069</span><a name="line.69"></a>
<span class="sourceLineNo">070</span> /** The series key. */<a name="line.70"></a>
<span class="sourceLineNo">071</span> private Comparable key;<a name="line.71"></a>
<span class="sourceLineNo">072</span><a name="line.72"></a>
<span class="sourceLineNo">073</span> /** The bins. */<a name="line.73"></a>
<span class="sourceLineNo">074</span> private List bins;<a name="line.74"></a>
<span class="sourceLineNo">075</span><a name="line.75"></a>
<span class="sourceLineNo">076</span> /**<a name="line.76"></a>
<span class="sourceLineNo">077</span> * A flag that controls whether or not the bin count is divided by the<a name="line.77"></a>
<span class="sourceLineNo">078</span> * bin size.<a name="line.78"></a>
<span class="sourceLineNo">079</span> */<a name="line.79"></a>
<span class="sourceLineNo">080</span> private boolean adjustForBinSize;<a name="line.80"></a>
<span class="sourceLineNo">081</span><a name="line.81"></a>
<span class="sourceLineNo">082</span> /**<a name="line.82"></a>
<span class="sourceLineNo">083</span> * Creates a new histogram dataset. Note that the<a name="line.83"></a>
<span class="sourceLineNo">084</span> * <code>adjustForBinSize</code> flag defaults to <code>true</code>.<a name="line.84"></a>
<span class="sourceLineNo">085</span> *<a name="line.85"></a>
<span class="sourceLineNo">086</span> * @param key the series key (<code>null</code> not permitted).<a name="line.86"></a>
<span class="sourceLineNo">087</span> */<a name="line.87"></a>
<span class="sourceLineNo">088</span> public SimpleHistogramDataset(Comparable key) {<a name="line.88"></a>
<span class="sourceLineNo">089</span> if (key == null) {<a name="line.89"></a>
<span class="sourceLineNo">090</span> throw new IllegalArgumentException("Null 'key' argument.");<a name="line.90"></a>
<span class="sourceLineNo">091</span> }<a name="line.91"></a>
<span class="sourceLineNo">092</span> this.key = key;<a name="line.92"></a>
<span class="sourceLineNo">093</span> this.bins = new ArrayList();<a name="line.93"></a>
<span class="sourceLineNo">094</span> this.adjustForBinSize = true;<a name="line.94"></a>
<span class="sourceLineNo">095</span> }<a name="line.95"></a>
<span class="sourceLineNo">096</span><a name="line.96"></a>
<span class="sourceLineNo">097</span> /**<a name="line.97"></a>
<span class="sourceLineNo">098</span> * Returns a flag that controls whether or not the bin count is divided by<a name="line.98"></a>
<span class="sourceLineNo">099</span> * the bin size in the {@link #getXValue(int, int)} method.<a name="line.99"></a>
<span class="sourceLineNo">100</span> *<a name="line.100"></a>
<span class="sourceLineNo">101</span> * @return A boolean.<a name="line.101"></a>
<span class="sourceLineNo">102</span> *<a name="line.102"></a>
<span class="sourceLineNo">103</span> * @see #setAdjustForBinSize(boolean)<a name="line.103"></a>
<span class="sourceLineNo">104</span> */<a name="line.104"></a>
<span class="sourceLineNo">105</span> public boolean getAdjustForBinSize() {<a name="line.105"></a>
<span class="sourceLineNo">106</span> return this.adjustForBinSize;<a name="line.106"></a>
<span class="sourceLineNo">107</span> }<a name="line.107"></a>
<span class="sourceLineNo">108</span><a name="line.108"></a>
<span class="sourceLineNo">109</span> /**<a name="line.109"></a>
<span class="sourceLineNo">110</span> * Sets the flag that controls whether or not the bin count is divided by<a name="line.110"></a>
<span class="sourceLineNo">111</span> * the bin size in the {@link #getYValue(int, int)} method, and sends a<a name="line.111"></a>
<span class="sourceLineNo">112</span> * {@link DatasetChangeEvent} to all registered listeners.<a name="line.112"></a>
<span class="sourceLineNo">113</span> *<a name="line.113"></a>
<span class="sourceLineNo">114</span> * @param adjust the flag.<a name="line.114"></a>
<span class="sourceLineNo">115</span> *<a name="line.115"></a>
<span class="sourceLineNo">116</span> * @see #getAdjustForBinSize()<a name="line.116"></a>
<span class="sourceLineNo">117</span> */<a name="line.117"></a>
<span class="sourceLineNo">118</span> public void setAdjustForBinSize(boolean adjust) {<a name="line.118"></a>
<span class="sourceLineNo">119</span> this.adjustForBinSize = adjust;<a name="line.119"></a>
<span class="sourceLineNo">120</span> notifyListeners(new DatasetChangeEvent(this, this));<a name="line.120"></a>
<span class="sourceLineNo">121</span> }<a name="line.121"></a>
<span class="sourceLineNo">122</span><a name="line.122"></a>
<span class="sourceLineNo">123</span> /**<a name="line.123"></a>
<span class="sourceLineNo">124</span> * Returns the number of series in the dataset (always 1 for this dataset).<a name="line.124"></a>
<span class="sourceLineNo">125</span> *<a name="line.125"></a>
<span class="sourceLineNo">126</span> * @return The series count.<a name="line.126"></a>
<span class="sourceLineNo">127</span> */<a name="line.127"></a>
<span class="sourceLineNo">128</span> public int getSeriesCount() {<a name="line.128"></a>
<span class="sourceLineNo">129</span> return 1;<a name="line.129"></a>
<span class="sourceLineNo">130</span> }<a name="line.130"></a>
<span class="sourceLineNo">131</span><a name="line.131"></a>
<span class="sourceLineNo">132</span> /**<a name="line.132"></a>
<span class="sourceLineNo">133</span> * Returns the key for a series. Since this dataset only stores a single<a name="line.133"></a>
<span class="sourceLineNo">134</span> * series, the <code>series</code> argument is ignored.<a name="line.134"></a>
<span class="sourceLineNo">135</span> *<a name="line.135"></a>
<span class="sourceLineNo">136</span> * @param series the series (zero-based index, ignored in this dataset).<a name="line.136"></a>
<span class="sourceLineNo">137</span> *<a name="line.137"></a>
<span class="sourceLineNo">138</span> * @return The key for the series.<a name="line.138"></a>
<span class="sourceLineNo">139</span> */<a name="line.139"></a>
<span class="sourceLineNo">140</span> public Comparable getSeriesKey(int series) {<a name="line.140"></a>
<span class="sourceLineNo">141</span> return this.key;<a name="line.141"></a>
<span class="sourceLineNo">142</span> }<a name="line.142"></a>
<span class="sourceLineNo">143</span><a name="line.143"></a>
<span class="sourceLineNo">144</span> /**<a name="line.144"></a>
<span class="sourceLineNo">145</span> * Returns the order of the domain (or X) values returned by the dataset.<a name="line.145"></a>
<span class="sourceLineNo">146</span> *<a name="line.146"></a>
<span class="sourceLineNo">147</span> * @return The order (never <code>null</code>).<a name="line.147"></a>
<span class="sourceLineNo">148</span> */<a name="line.148"></a>
<span class="sourceLineNo">149</span> public DomainOrder getDomainOrder() {<a name="line.149"></a>
<span class="sourceLineNo">150</span> return DomainOrder.ASCENDING;<a name="line.150"></a>
<span class="sourceLineNo">151</span> }<a name="line.151"></a>
<span class="sourceLineNo">152</span><a name="line.152"></a>
<span class="sourceLineNo">153</span> /**<a name="line.153"></a>
<span class="sourceLineNo">154</span> * Returns the number of items in a series. Since this dataset only stores<a name="line.154"></a>
<span class="sourceLineNo">155</span> * a single series, the <code>series</code> argument is ignored.<a name="line.155"></a>
<span class="sourceLineNo">156</span> *<a name="line.156"></a>
<span class="sourceLineNo">157</span> * @param series the series index (zero-based, ignored in this dataset).<a name="line.157"></a>
<span class="sourceLineNo">158</span> *<a name="line.158"></a>
<span class="sourceLineNo">159</span> * @return The item count.<a name="line.159"></a>
<span class="sourceLineNo">160</span> */<a name="line.160"></a>
<span class="sourceLineNo">161</span> public int getItemCount(int series) {<a name="line.161"></a>
<span class="sourceLineNo">162</span> return this.bins.size();<a name="line.162"></a>
<span class="sourceLineNo">163</span> }<a name="line.163"></a>
<span class="sourceLineNo">164</span><a name="line.164"></a>
<span class="sourceLineNo">165</span> /**<a name="line.165"></a>
<span class="sourceLineNo">166</span> * Adds a bin to the dataset. An exception is thrown if the bin overlaps<a name="line.166"></a>
<span class="sourceLineNo">167</span> * with any existing bin in the dataset.<a name="line.167"></a>
<span class="sourceLineNo">168</span> *<a name="line.168"></a>
<span class="sourceLineNo">169</span> * @param bin the bin (<code>null</code> not permitted).<a name="line.169"></a>
<span class="sourceLineNo">170</span> *<a name="line.170"></a>
<span class="sourceLineNo">171</span> * @see #removeAllBins()<a name="line.171"></a>
<span class="sourceLineNo">172</span> */<a name="line.172"></a>
<span class="sourceLineNo">173</span> public void addBin(SimpleHistogramBin bin) {<a name="line.173"></a>
<span class="sourceLineNo">174</span> // check that the new bin doesn't overlap with any existing bin<a name="line.174"></a>
<span class="sourceLineNo">175</span> Iterator iterator = this.bins.iterator();<a name="line.175"></a>
<span class="sourceLineNo">176</span> while (iterator.hasNext()) {<a name="line.176"></a>
<span class="sourceLineNo">177</span> SimpleHistogramBin existingBin<a name="line.177"></a>
<span class="sourceLineNo">178</span> = (SimpleHistogramBin) iterator.next();<a name="line.178"></a>
<span class="sourceLineNo">179</span> if (bin.overlapsWith(existingBin)) {<a name="line.179"></a>
<span class="sourceLineNo">180</span> throw new RuntimeException("Overlapping bin");<a name="line.180"></a>
<span class="sourceLineNo">181</span> }<a name="line.181"></a>
<span class="sourceLineNo">182</span> }<a name="line.182"></a>
<span class="sourceLineNo">183</span> this.bins.add(bin);<a name="line.183"></a>
<span class="sourceLineNo">184</span> Collections.sort(this.bins);<a name="line.184"></a>
<span class="sourceLineNo">185</span> }<a name="line.185"></a>
<span class="sourceLineNo">186</span><a name="line.186"></a>
<span class="sourceLineNo">187</span> /**<a name="line.187"></a>
<span class="sourceLineNo">188</span> * Adds an observation to the dataset (by incrementing the item count for<a name="line.188"></a>
<span class="sourceLineNo">189</span> * the appropriate bin). A runtime exception is thrown if the value does<a name="line.189"></a>
<span class="sourceLineNo">190</span> * not fit into any bin.<a name="line.190"></a>
<span class="sourceLineNo">191</span> *<a name="line.191"></a>
<span class="sourceLineNo">192</span> * @param value the value.<a name="line.192"></a>
<span class="sourceLineNo">193</span> */<a name="line.193"></a>
<span class="sourceLineNo">194</span> public void addObservation(double value) {<a name="line.194"></a>
<span class="sourceLineNo">195</span> addObservation(value, true);<a name="line.195"></a>
<span class="sourceLineNo">196</span> }<a name="line.196"></a>
<span class="sourceLineNo">197</span><a name="line.197"></a>
<span class="sourceLineNo">198</span> /**<a name="line.198"></a>
<span class="sourceLineNo">199</span> * Adds an observation to the dataset (by incrementing the item count for<a name="line.199"></a>
<span class="sourceLineNo">200</span> * the appropriate bin). A runtime exception is thrown if the value does<a name="line.200"></a>
<span class="sourceLineNo">201</span> * not fit into any bin.<a name="line.201"></a>
<span class="sourceLineNo">202</span> *<a name="line.202"></a>
<span class="sourceLineNo">203</span> * @param value the value.<a name="line.203"></a>
<span class="sourceLineNo">204</span> * @param notify send {@link DatasetChangeEvent} to listeners?<a name="line.204"></a>
<span class="sourceLineNo">205</span> */<a name="line.205"></a>
<span class="sourceLineNo">206</span> public void addObservation(double value, boolean notify) {<a name="line.206"></a>
<span class="sourceLineNo">207</span> boolean placed = false;<a name="line.207"></a>
<span class="sourceLineNo">208</span> Iterator iterator = this.bins.iterator();<a name="line.208"></a>
<span class="sourceLineNo">209</span> while (iterator.hasNext() && !placed) {<a name="line.209"></a>
<span class="sourceLineNo">210</span> SimpleHistogramBin bin = (SimpleHistogramBin) iterator.next();<a name="line.210"></a>
<span class="sourceLineNo">211</span> if (bin.accepts(value)) {<a name="line.211"></a>
<span class="sourceLineNo">212</span> bin.setItemCount(bin.getItemCount() + 1);<a name="line.212"></a>
<span class="sourceLineNo">213</span> placed = true;<a name="line.213"></a>
<span class="sourceLineNo">214</span> }<a name="line.214"></a>
<span class="sourceLineNo">215</span> }<a name="line.215"></a>
<span class="sourceLineNo">216</span> if (!placed) {<a name="line.216"></a>
<span class="sourceLineNo">217</span> throw new RuntimeException("No bin.");<a name="line.217"></a>
<span class="sourceLineNo">218</span> }<a name="line.218"></a>
<span class="sourceLineNo">219</span> if (notify) {<a name="line.219"></a>
<span class="sourceLineNo">220</span> notifyListeners(new DatasetChangeEvent(this, this));<a name="line.220"></a>
<span class="sourceLineNo">221</span> }<a name="line.221"></a>
<span class="sourceLineNo">222</span> }<a name="line.222"></a>
<span class="sourceLineNo">223</span><a name="line.223"></a>
<span class="sourceLineNo">224</span> /**<a name="line.224"></a>
<span class="sourceLineNo">225</span> * Adds a set of values to the dataset and sends a<a name="line.225"></a>
<span class="sourceLineNo">226</span> * {@link DatasetChangeEvent} to all registered listeners.<a name="line.226"></a>
<span class="sourceLineNo">227</span> *<a name="line.227"></a>
<span class="sourceLineNo">228</span> * @param values the values (<code>null</code> not permitted).<a name="line.228"></a>
<span class="sourceLineNo">229</span> *<a name="line.229"></a>
<span class="sourceLineNo">230</span> * @see #clearObservations()<a name="line.230"></a>
<span class="sourceLineNo">231</span> */<a name="line.231"></a>
<span class="sourceLineNo">232</span> public void addObservations(double[] values) {<a name="line.232"></a>
<span class="sourceLineNo">233</span> for (int i = 0; i < values.length; i++) {<a name="line.233"></a>
<span class="sourceLineNo">234</span> addObservation(values[i], false);<a name="line.234"></a>
<span class="sourceLineNo">235</span> }<a name="line.235"></a>
<span class="sourceLineNo">236</span> notifyListeners(new DatasetChangeEvent(this, this));<a name="line.236"></a>
<span class="sourceLineNo">237</span> }<a name="line.237"></a>
<span class="sourceLineNo">238</span><a name="line.238"></a>
<span class="sourceLineNo">239</span> /**<a name="line.239"></a>
<span class="sourceLineNo">240</span> * Removes all current observation data and sends a<a name="line.240"></a>
<span class="sourceLineNo">241</span> * {@link DatasetChangeEvent} to all registered listeners.<a name="line.241"></a>
<span class="sourceLineNo">242</span> *<a name="line.242"></a>
<span class="sourceLineNo">243</span> * @since 1.0.6<a name="line.243"></a>
<span class="sourceLineNo">244</span> *<a name="line.244"></a>
<span class="sourceLineNo">245</span> * @see #addObservations(double[])<a name="line.245"></a>
<span class="sourceLineNo">246</span> * @see #removeAllBins()<a name="line.246"></a>
<span class="sourceLineNo">247</span> */<a name="line.247"></a>
<span class="sourceLineNo">248</span> public void clearObservations() {<a name="line.248"></a>
<span class="sourceLineNo">249</span> Iterator iterator = this.bins.iterator();<a name="line.249"></a>
<span class="sourceLineNo">250</span> while (iterator.hasNext()) {<a name="line.250"></a>
<span class="sourceLineNo">251</span> SimpleHistogramBin bin = (SimpleHistogramBin) iterator.next();<a name="line.251"></a>
<span class="sourceLineNo">252</span> bin.setItemCount(0);<a name="line.252"></a>
<span class="sourceLineNo">253</span> }<a name="line.253"></a>
<span class="sourceLineNo">254</span> notifyListeners(new DatasetChangeEvent(this, this));<a name="line.254"></a>
<span class="sourceLineNo">255</span> }<a name="line.255"></a>
<span class="sourceLineNo">256</span><a name="line.256"></a>
<span class="sourceLineNo">257</span> /**<a name="line.257"></a>
<span class="sourceLineNo">258</span> * Removes all bins and sends a {@link DatasetChangeEvent} to all<a name="line.258"></a>
<span class="sourceLineNo">259</span> * registered listeners.<a name="line.259"></a>
<span class="sourceLineNo">260</span> *<a name="line.260"></a>
<span class="sourceLineNo">261</span> * @since 1.0.6<a name="line.261"></a>
<span class="sourceLineNo">262</span> *<a name="line.262"></a>
<span class="sourceLineNo">263</span> * @see #addBin(SimpleHistogramBin)<a name="line.263"></a>
<span class="sourceLineNo">264</span> */<a name="line.264"></a>
<span class="sourceLineNo">265</span> public void removeAllBins() {<a name="line.265"></a>
<span class="sourceLineNo">266</span> this.bins = new ArrayList();<a name="line.266"></a>
<span class="sourceLineNo">267</span> notifyListeners(new DatasetChangeEvent(this, this));<a name="line.267"></a>
<span class="sourceLineNo">268</span> }<a name="line.268"></a>
<span class="sourceLineNo">269</span><a name="line.269"></a>
<span class="sourceLineNo">270</span> /**<a name="line.270"></a>
<span class="sourceLineNo">271</span> * Returns the x-value for an item within a series. The x-values may or<a name="line.271"></a>
<span class="sourceLineNo">272</span> * may not be returned in ascending order, that is up to the class<a name="line.272"></a>
<span class="sourceLineNo">273</span> * implementing the interface.<a name="line.273"></a>
<span class="sourceLineNo">274</span> *<a name="line.274"></a>
<span class="sourceLineNo">275</span> * @param series the series index (zero-based).<a name="line.275"></a>
<span class="sourceLineNo">276</span> * @param item the item index (zero-based).<a name="line.276"></a>
<span class="sourceLineNo">277</span> *<a name="line.277"></a>
<span class="sourceLineNo">278</span> * @return The x-value (never <code>null</code>).<a name="line.278"></a>
<span class="sourceLineNo">279</span> */<a name="line.279"></a>
<span class="sourceLineNo">280</span> public Number getX(int series, int item) {<a name="line.280"></a>
<span class="sourceLineNo">281</span> return new Double(getXValue(series, item));<a name="line.281"></a>
<span class="sourceLineNo">282</span> }<a name="line.282"></a>
<span class="sourceLineNo">283</span><a name="line.283"></a>
<span class="sourceLineNo">284</span> /**<a name="line.284"></a>
<span class="sourceLineNo">285</span> * Returns the x-value (as a double primitive) for an item within a series.<a name="line.285"></a>
<span class="sourceLineNo">286</span> *<a name="line.286"></a>
<span class="sourceLineNo">287</span> * @param series the series index (zero-based).<a name="line.287"></a>
<span class="sourceLineNo">288</span> * @param item the item index (zero-based).<a name="line.288"></a>
<span class="sourceLineNo">289</span> *<a name="line.289"></a>
<span class="sourceLineNo">290</span> * @return The x-value.<a name="line.290"></a>
<span class="sourceLineNo">291</span> */<a name="line.291"></a>
<span class="sourceLineNo">292</span> public double getXValue(int series, int item) {<a name="line.292"></a>
<span class="sourceLineNo">293</span> SimpleHistogramBin bin = (SimpleHistogramBin) this.bins.get(item);<a name="line.293"></a>
<span class="sourceLineNo">294</span> return (bin.getLowerBound() + bin.getUpperBound()) / 2.0;<a name="line.294"></a>
<span class="sourceLineNo">295</span> }<a name="line.295"></a>
<span class="sourceLineNo">296</span><a name="line.296"></a>
<span class="sourceLineNo">297</span> /**<a name="line.297"></a>
<span class="sourceLineNo">298</span> * Returns the y-value for an item within a series.<a name="line.298"></a>
<span class="sourceLineNo">299</span> *<a name="line.299"></a>
<span class="sourceLineNo">300</span> * @param series the series index (zero-based).<a name="line.300"></a>
<span class="sourceLineNo">301</span> * @param item the item index (zero-based).<a name="line.301"></a>
<span class="sourceLineNo">302</span> *<a name="line.302"></a>
<span class="sourceLineNo">303</span> * @return The y-value (possibly <code>null</code>).<a name="line.303"></a>
<span class="sourceLineNo">304</span> */<a name="line.304"></a>
<span class="sourceLineNo">305</span> public Number getY(int series, int item) {<a name="line.305"></a>
<span class="sourceLineNo">306</span> return new Double(getYValue(series, item));<a name="line.306"></a>
<span class="sourceLineNo">307</span> }<a name="line.307"></a>
<span class="sourceLineNo">308</span><a name="line.308"></a>
<span class="sourceLineNo">309</span> /**<a name="line.309"></a>
<span class="sourceLineNo">310</span> * Returns the y-value (as a double primitive) for an item within a series.<a name="line.310"></a>
<span class="sourceLineNo">311</span> *<a name="line.311"></a>
<span class="sourceLineNo">312</span> * @param series the series index (zero-based).<a name="line.312"></a>
<span class="sourceLineNo">313</span> * @param item the item index (zero-based).<a name="line.313"></a>
<span class="sourceLineNo">314</span> *<a name="line.314"></a>
<span class="sourceLineNo">315</span> * @return The y-value.<a name="line.315"></a>
<span class="sourceLineNo">316</span> *<a name="line.316"></a>
<span class="sourceLineNo">317</span> * @see #getAdjustForBinSize()<a name="line.317"></a>
<span class="sourceLineNo">318</span> */<a name="line.318"></a>
<span class="sourceLineNo">319</span> public double getYValue(int series, int item) {<a name="line.319"></a>
<span class="sourceLineNo">320</span> SimpleHistogramBin bin = (SimpleHistogramBin) this.bins.get(item);<a name="line.320"></a>
<span class="sourceLineNo">321</span> if (this.adjustForBinSize) {<a name="line.321"></a>
<span class="sourceLineNo">322</span> return bin.getItemCount()<a name="line.322"></a>
<span class="sourceLineNo">323</span> / (bin.getUpperBound() - bin.getLowerBound());<a name="line.323"></a>
<span class="sourceLineNo">324</span> }<a name="line.324"></a>
<span class="sourceLineNo">325</span> else {<a name="line.325"></a>
<span class="sourceLineNo">326</span> return bin.getItemCount();<a name="line.326"></a>
<span class="sourceLineNo">327</span> }<a name="line.327"></a>
<span class="sourceLineNo">328</span> }<a name="line.328"></a>
<span class="sourceLineNo">329</span><a name="line.329"></a>
<span class="sourceLineNo">330</span> /**<a name="line.330"></a>
<span class="sourceLineNo">331</span> * Returns the starting X value for the specified series and item.<a name="line.331"></a>
<span class="sourceLineNo">332</span> *<a name="line.332"></a>
<span class="sourceLineNo">333</span> * @param series the series index (zero-based).<a name="line.333"></a>
<span class="sourceLineNo">334</span> * @param item the item index (zero-based).<a name="line.334"></a>
<span class="sourceLineNo">335</span> *<a name="line.335"></a>
<span class="sourceLineNo">336</span> * @return The value.<a name="line.336"></a>
<span class="sourceLineNo">337</span> */<a name="line.337"></a>
<span class="sourceLineNo">338</span> public Number getStartX(int series, int item) {<a name="line.338"></a>
<span class="sourceLineNo">339</span> return new Double(getStartXValue(series, item));<a name="line.339"></a>
<span class="sourceLineNo">340</span> }<a name="line.340"></a>
<span class="sourceLineNo">341</span><a name="line.341"></a>
<span class="sourceLineNo">342</span> /**<a name="line.342"></a>
<span class="sourceLineNo">343</span> * Returns the start x-value (as a double primitive) for an item within a<a name="line.343"></a>
<span class="sourceLineNo">344</span> * series.<a name="line.344"></a>
<span class="sourceLineNo">345</span> *<a name="line.345"></a>
<span class="sourceLineNo">346</span> * @param series the series (zero-based index).<a name="line.346"></a>
<span class="sourceLineNo">347</span> * @param item the item (zero-based index).<a name="line.347"></a>
<span class="sourceLineNo">348</span> *<a name="line.348"></a>
<span class="sourceLineNo">349</span> * @return The start x-value.<a name="line.349"></a>
<span class="sourceLineNo">350</span> */<a name="line.350"></a>
<span class="sourceLineNo">351</span> public double getStartXValue(int series, int item) {<a name="line.351"></a>
<span class="sourceLineNo">352</span> SimpleHistogramBin bin = (SimpleHistogramBin) this.bins.get(item);<a name="line.352"></a>
<span class="sourceLineNo">353</span> return bin.getLowerBound();<a name="line.353"></a>
<span class="sourceLineNo">354</span> }<a name="line.354"></a>
<span class="sourceLineNo">355</span><a name="line.355"></a>
<span class="sourceLineNo">356</span> /**<a name="line.356"></a>
<span class="sourceLineNo">357</span> * Returns the ending X value for the specified series and item.<a name="line.357"></a>
<span class="sourceLineNo">358</span> *<a name="line.358"></a>
<span class="sourceLineNo">359</span> * @param series the series index (zero-based).<a name="line.359"></a>
<span class="sourceLineNo">360</span> * @param item the item index (zero-based).<a name="line.360"></a>
<span class="sourceLineNo">361</span> *<a name="line.361"></a>
<span class="sourceLineNo">362</span> * @return The value.<a name="line.362"></a>
<span class="sourceLineNo">363</span> */<a name="line.363"></a>
<span class="sourceLineNo">364</span> public Number getEndX(int series, int item) {<a name="line.364"></a>
<span class="sourceLineNo">365</span> return new Double(getEndXValue(series, item));<a name="line.365"></a>
<span class="sourceLineNo">366</span> }<a name="line.366"></a>
<span class="sourceLineNo">367</span><a name="line.367"></a>
<span class="sourceLineNo">368</span> /**<a name="line.368"></a>
<span class="sourceLineNo">369</span> * Returns the end x-value (as a double primitive) for an item within a<a name="line.369"></a>
<span class="sourceLineNo">370</span> * series.<a name="line.370"></a>
<span class="sourceLineNo">371</span> *<a name="line.371"></a>
<span class="sourceLineNo">372</span> * @param series the series index (zero-based).<a name="line.372"></a>
<span class="sourceLineNo">373</span> * @param item the item index (zero-based).<a name="line.373"></a>
<span class="sourceLineNo">374</span> *<a name="line.374"></a>
<span class="sourceLineNo">375</span> * @return The end x-value.<a name="line.375"></a>
<span class="sourceLineNo">376</span> */<a name="line.376"></a>
<span class="sourceLineNo">377</span> public double getEndXValue(int series, int item) {<a name="line.377"></a>
<span class="sourceLineNo">378</span> SimpleHistogramBin bin = (SimpleHistogramBin) this.bins.get(item);<a name="line.378"></a>
<span class="sourceLineNo">379</span> return bin.getUpperBound();<a name="line.379"></a>
<span class="sourceLineNo">380</span> }<a name="line.380"></a>
<span class="sourceLineNo">381</span><a name="line.381"></a>
<span class="sourceLineNo">382</span> /**<a name="line.382"></a>
<span class="sourceLineNo">383</span> * Returns the starting Y value for the specified series and item.<a name="line.383"></a>
<span class="sourceLineNo">384</span> *<a name="line.384"></a>
<span class="sourceLineNo">385</span> * @param series the series index (zero-based).<a name="line.385"></a>
<span class="sourceLineNo">386</span> * @param item the item index (zero-based).<a name="line.386"></a>
<span class="sourceLineNo">387</span> *<a name="line.387"></a>
<span class="sourceLineNo">388</span> * @return The value.<a name="line.388"></a>
<span class="sourceLineNo">389</span> */<a name="line.389"></a>
<span class="sourceLineNo">390</span> public Number getStartY(int series, int item) {<a name="line.390"></a>
<span class="sourceLineNo">391</span> return getY(series, item);<a name="line.391"></a>
<span class="sourceLineNo">392</span> }<a name="line.392"></a>
<span class="sourceLineNo">393</span><a name="line.393"></a>
<span class="sourceLineNo">394</span> /**<a name="line.394"></a>
<span class="sourceLineNo">395</span> * Returns the start y-value (as a double primitive) for an item within a<a name="line.395"></a>
<span class="sourceLineNo">396</span> * series.<a name="line.396"></a>
<span class="sourceLineNo">397</span> *<a name="line.397"></a>
<span class="sourceLineNo">398</span> * @param series the series index (zero-based).<a name="line.398"></a>
<span class="sourceLineNo">399</span> * @param item the item index (zero-based).<a name="line.399"></a>
<span class="sourceLineNo">400</span> *<a name="line.400"></a>
<span class="sourceLineNo">401</span> * @return The start y-value.<a name="line.401"></a>
<span class="sourceLineNo">402</span> */<a name="line.402"></a>
<span class="sourceLineNo">403</span> public double getStartYValue(int series, int item) {<a name="line.403"></a>
<span class="sourceLineNo">404</span> return getYValue(series, item);<a name="line.404"></a>
<span class="sourceLineNo">405</span> }<a name="line.405"></a>
<span class="sourceLineNo">406</span><a name="line.406"></a>
<span class="sourceLineNo">407</span> /**<a name="line.407"></a>
<span class="sourceLineNo">408</span> * Returns the ending Y value for the specified series and item.<a name="line.408"></a>
<span class="sourceLineNo">409</span> *<a name="line.409"></a>
<span class="sourceLineNo">410</span> * @param series the series index (zero-based).<a name="line.410"></a>
<span class="sourceLineNo">411</span> * @param item the item index (zero-based).<a name="line.411"></a>
<span class="sourceLineNo">412</span> *<a name="line.412"></a>
<span class="sourceLineNo">413</span> * @return The value.<a name="line.413"></a>
<span class="sourceLineNo">414</span> */<a name="line.414"></a>
<span class="sourceLineNo">415</span> public Number getEndY(int series, int item) {<a name="line.415"></a>
<span class="sourceLineNo">416</span> return getY(series, item);<a name="line.416"></a>
<span class="sourceLineNo">417</span> }<a name="line.417"></a>
<span class="sourceLineNo">418</span><a name="line.418"></a>
<span class="sourceLineNo">419</span> /**<a name="line.419"></a>
<span class="sourceLineNo">420</span> * Returns the end y-value (as a double primitive) for an item within a<a name="line.420"></a>
<span class="sourceLineNo">421</span> * series.<a name="line.421"></a>
<span class="sourceLineNo">422</span> *<a name="line.422"></a>
<span class="sourceLineNo">423</span> * @param series the series index (zero-based).<a name="line.423"></a>
<span class="sourceLineNo">424</span> * @param item the item index (zero-based).<a name="line.424"></a>
<span class="sourceLineNo">425</span> *<a name="line.425"></a>
<span class="sourceLineNo">426</span> * @return The end y-value.<a name="line.426"></a>
<span class="sourceLineNo">427</span> */<a name="line.427"></a>
<span class="sourceLineNo">428</span> public double getEndYValue(int series, int item) {<a name="line.428"></a>
<span class="sourceLineNo">429</span> return getYValue(series, item);<a name="line.429"></a>
<span class="sourceLineNo">430</span> }<a name="line.430"></a>
<span class="sourceLineNo">431</span><a name="line.431"></a>
<span class="sourceLineNo">432</span> /**<a name="line.432"></a>
<span class="sourceLineNo">433</span> * Compares the dataset for equality with an arbitrary object.<a name="line.433"></a>
<span class="sourceLineNo">434</span> *<a name="line.434"></a>
<span class="sourceLineNo">435</span> * @param obj the object (<code>null</code> permitted).<a name="line.435"></a>
<span class="sourceLineNo">436</span> *<a name="line.436"></a>
<span class="sourceLineNo">437</span> * @return A boolean.<a name="line.437"></a>
<span class="sourceLineNo">438</span> */<a name="line.438"></a>
<span class="sourceLineNo">439</span> public boolean equals(Object obj) {<a name="line.439"></a>
<span class="sourceLineNo">440</span> if (obj == this) {<a name="line.440"></a>
<span class="sourceLineNo">441</span> return true;<a name="line.441"></a>
<span class="sourceLineNo">442</span> }<a name="line.442"></a>
<span class="sourceLineNo">443</span> if (!(obj instanceof SimpleHistogramDataset)) {<a name="line.443"></a>
<span class="sourceLineNo">444</span> return false;<a name="line.444"></a>
<span class="sourceLineNo">445</span> }<a name="line.445"></a>
<span class="sourceLineNo">446</span> SimpleHistogramDataset that = (SimpleHistogramDataset) obj;<a name="line.446"></a>
<span class="sourceLineNo">447</span> if (!this.key.equals(that.key)) {<a name="line.447"></a>
<span class="sourceLineNo">448</span> return false;<a name="line.448"></a>
<span class="sourceLineNo">449</span> }<a name="line.449"></a>
<span class="sourceLineNo">450</span> if (this.adjustForBinSize != that.adjustForBinSize) {<a name="line.450"></a>
<span class="sourceLineNo">451</span> return false;<a name="line.451"></a>
<span class="sourceLineNo">452</span> }<a name="line.452"></a>
<span class="sourceLineNo">453</span> if (!this.bins.equals(that.bins)) {<a name="line.453"></a>
<span class="sourceLineNo">454</span> return false;<a name="line.454"></a>
<span class="sourceLineNo">455</span> }<a name="line.455"></a>
<span class="sourceLineNo">456</span> return true;<a name="line.456"></a>
<span class="sourceLineNo">457</span> }<a name="line.457"></a>
<span class="sourceLineNo">458</span><a name="line.458"></a>
<span class="sourceLineNo">459</span> /**<a name="line.459"></a>
<span class="sourceLineNo">460</span> * Returns a clone of the dataset.<a name="line.460"></a>
<span class="sourceLineNo">461</span> *<a name="line.461"></a>
<span class="sourceLineNo">462</span> * @return A clone.<a name="line.462"></a>
<span class="sourceLineNo">463</span> *<a name="line.463"></a>
<span class="sourceLineNo">464</span> * @throws CloneNotSupportedException not thrown by this class, but maybe<a name="line.464"></a>
<span class="sourceLineNo">465</span> * by subclasses (if any).<a name="line.465"></a>
<span class="sourceLineNo">466</span> */<a name="line.466"></a>
<span class="sourceLineNo">467</span> public Object clone() throws CloneNotSupportedException {<a name="line.467"></a>
<span class="sourceLineNo">468</span> SimpleHistogramDataset clone = (SimpleHistogramDataset) super.clone();<a name="line.468"></a>
<span class="sourceLineNo">469</span> clone.bins = (List) ObjectUtilities.deepClone(this.bins);<a name="line.469"></a>
<span class="sourceLineNo">470</span> return clone;<a name="line.470"></a>
<span class="sourceLineNo">471</span> }<a name="line.471"></a>
<span class="sourceLineNo">472</span><a name="line.472"></a>
<span class="sourceLineNo">473</span>}<a name="line.473"></a>
</pre>
</div>
</body>
</html>
| jclazzarim/TrabalhoPID2013 | Trabalho PID2013/libs/jfreechart-1.0.14-javadocs/src-html/org/jfree/data/statistics/SimpleHistogramDataset.html | HTML | gpl-2.0 | 43,358 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html><head><title></title>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta name="generator" content="Doxygen 1.8.5">
<link rel="stylesheet" type="text/css" href="search.css"/>
<script type="text/javascript" src="functions_66.js"></script>
<script type="text/javascript" src="search.js"></script>
</head>
<body class="SRPage">
<div id="SRIndex">
<div class="SRStatus" id="Loading">Loading...</div>
<div id="SRResults"></div>
<script type="text/javascript"><!--
createResults();
--></script>
<div class="SRStatus" id="Searching">Searching...</div>
<div class="SRStatus" id="NoMatches">No Matches</div>
<script type="text/javascript"><!--
document.getElementById("Loading").style.display="none";
document.getElementById("NoMatches").style.display="none";
var searchResults = new SearchResults("searchResults");
searchResults.Search();
--></script>
</div>
</body>
</html>
| iclosure/jdataanalyse | source/core/3rdpart/qwt/doc/html/search/functions_66.html | HTML | gpl-2.0 | 1,044 |
# -*- coding: iso-8859-1 -*-
require 'albacore'
require 'pathname'
require 'albacore/support/logging'
require 'command'
# require 'win32/file'
require 'rake'
require 'tcfileutils'
require 'projects/vs'
require 'projects/vb6'
require 'uuidtools'
require 'common'
require 'config/src'
require 'rake/hooks'
# Redefine Albacore Logging module to use FilteredLogger
module Logging
def initialize
@logger = TC::Common.logger
super()
end
end
# Redefine Albacore::RunCommand#run_command to use TC::Command#run
module Albacore
module RunCommand
def run_command(name="Command Line", parameters=nil)
begin
params = []
params << parameters unless parameters.nil?
params << @parameters unless (@parameters.nil? || !@parameters.any?)
executable = @command
unless command.nil?
executable = File.expand_path(@command) if File.exists?(@command)
end
Dir.chdir(@working_directory) do
TC::Command.run(executable,params.join(" "))
end
rescue Exception => e
TC::Common.logger.fatal "Error while running '#{name}': #{e}"
raise
end
end
end
end
def tfsco(*args)
args ||= []
config = Struct.new(:files, :recursive).new
config.files=[]
config.recursive=true
yield(config)
body = proc {
TFSCoTask.new.execute(config.files,
config.recursive)
}
Rake::Task.define_task(*args, &body)
end
class TFSCoTask
def execute(files, recursive)
options = "/recursive" if recursive
files.each do |file|
if !file.nil? &&
File.exists?(file) &&
(File.readonly?(file) || File.directory?(file))
TFS.checkout file, options
end
end
end
end
def build_setup_project(*args)
args ||= []
config = Struct.new(:solution, :project_file, :product_version).new
yield(config)
body = proc {
BuildSetupProjectTask.new.execute(config.solution,
config.project_file,
config.product_version)
}
Rake::Task.define_task(*args, &body)
end
class BuildSetupProjectTask
def execute(solution, project_file, product_version)
raise "unrecognized setup type #{project_file}" unless SetupProjectBuilder.setup_project? project_file
SetupProjectBuilder.create(solution, project_file, product_version).run
end
end
class SetupProjectBuilder
class << self
def setup_classes
@setup_classes ||= []
end
def inherited(sub_class)
setup_classes << sub_class
end
def setup_project?(project_file)
!setup_class(project_file).nil?
end
def setup_class(project_file)
setup_classes.find {|c| c.project_file_pattern =~ project_file }
end
def outputs(project_file)
setup_class(project_file).new.tap {|c| c.project_file=project_file }.outputs
end
def create(solution, project_file, product_version)
setup_class(project_file).new.tap do |c|
c.solution=solution
c.project_file=project_file
c.product_version=product_version
end
end
end
attr_accessor :solution, :project_file, :product_version
def new_uuid
"{#{UUIDTools::UUID.random_create.to_s.upcase}}"
end
def outputs
raise "unimplemented method 'outputs' in #{self.class}"
end
def run
raise "unimplemented method 'run' in #{self.class}"
end
end
class VDProjBuilder < SetupProjectBuilder
def self.project_file_pattern
/\.vdproj$/
end
def outputs
vdproj.outputs
end
def run
prepare_vdproj
devenv = TC::Devenv.new solution.to_win_path, project_file.to_win_path
devenv.run
end
private
def vdproj
@vdproj ||= VDProj.new(project_file)
end
def prepare_vdproj
vdproj.version=product_version
vdproj.subject=product_version
vdproj.product_code=new_uuid
vdproj.package_code=new_uuid
end
end
# Stub for a class to build WiX setup projects, implement outputs and run
class WiXBuilder < SetupProjectBuilder
def self.project_file_pattern
/\.wsi$/
end
end
module TC
class NoGeneratorFoundException < RuntimeError; end
class TaskGenerator
include ::Rake
include ::Rake::DSL
attr_reader :product, :project_file, :tag
class << self
def generator_classes
@generator_classes ||= []
end
def inherited(sub_class)
generator_classes << sub_class
end
def all_project_files(product)
Conf::Src.project_info_collection(product.to_s)
end
def create(product)
all_project_files(product).collect do |project_info|
generator_class = generator_classes.find { |c| c.project_file_pattern =~ project_info[:file] }
raise NoGeneratorFoundException,
"Cannot build project file #{project_file}."+
" Extend TaskGenerator to implement a new generator that "+
"matches the file type" unless generator_class
generator_class.new(project_info,product)
end
end
end
def initialize(project_info,product)
@product=product.to_s
raise "Illegal arg #{project_info}" unless project_info.class == Hash
@project_file=project_info[:file]
@tag=project_info[:tag]
@target = project_info[:target]
end
def build_co_name
"#{product}:build:co"
end
def create_name(file,suffix)
"#{product}:#{TCFileUtils.simple_name(file)}:#{suffix}"
end
def tfs_co_task_name(file)
create_name file, "checkout"
end
def build_task_name(file)
create_name file, "build"
end
def version_task_name(file)
create_name file, "version"
end
def build_msi_task_name(file)
create_name file, "build_msi"
end
def build_tasks
@build_tasks ||= generate_build_tasks
end
def build_msi_tasks
@build_msi_tasks ||= generate_build_msi_tasks
end
def generate_test_tasks
[]
end
def test_tasks
@test_tasks ||= generate_test_tasks
end
end
class MSBuildTaskGenerator < TaskGenerator
alias_method :solution_file, :project_file
attr_reader :solution
def self.project_file_pattern
/\.sln$/i
end
def self.language(file_name)
file_name.end_with?("cs") ? "C#" : "VB.Net"
end
def initialize(project_info,product)
super
@solution = VSSolution.new solution_file
end
def asm_task_name(file)
create_name file, "updateAssemblyInfo"
end
def clean_task_name(file)
create_name file, "clean"
end
def test_task_name(file)
create_name file, "test"
end
def projects_with_asm
solution.projects.select {|p| p.asm_file }
end
def asm_tasks
projects_with_asm.collect do |project|
assemblyinfo_file = project.asm_file
project_file=project.project_file
version=Conf::Build.version(product)+".0" # Hack to introduce an extra build digit..
assemblyinfo asm_task_name(project_file) => tfs_co_task_name(solution_file) do |asm|
asm.version = version
asm.file_version = version
asm.product_name = Conf::Build.product_name(product)
asm.output_file = assemblyinfo_file.to_win_path
asm.language = MSBuildTaskGenerator.language assemblyinfo_file
asm.description = Conf::Build.description(product)
end
asm_task_name(project_file)
end
end
def setup_solution_tasks(build_deps)
project_files = solution.project_files
setup_project_files = project_files.select {|f| SetupProjectBuilder.setup_project? f }
setup_project_files.collect do |project_file|
tfsco tfs_co_task_name(project_file) => :checkout do |tfs|
tfs.files << project_file
tfs.files += SetupProjectBuilder.outputs(project_file)
end
build_setup_project build_msi_task_name(project_file) => build_deps+[tfs_co_task_name(project_file)] do |setup|
setup.solution = solution_file
setup.project_file = project_file
setup.product_version = Conf::Build.version(product)
end
build_msi_task_name(project_file)
end
end
def generate_build_tasks
tfsco tfs_co_task_name(solution_file) => :checkout do |tfs|
tfs.files = projects_with_asm.collect { |p| p.asm_file }
tfs.files += solution.vs_projects.collect {|p| p.absolute_output_path }
end
build_deps = [tfs_co_task_name(solution_file)] + asm_tasks
msbuild build_task_name(solution_file) => build_deps do |msb|
msb.solution = solution_file
msb.properties[:target] = @target
end
[build_task_name(solution_file)]
end
def generate_build_msi_tasks
setup_solution_tasks [build_task_name(solution_file)]
end
def generate_test_tasks build_deps
test_assemblies = solution.vs_projects.select { |p| p.mstest? }.collect { |p| p.output_name }
if test_assemblies.any?
mstest test_task_name(solution_file) => build_deps do |t|
t.assemblies = test_assemblies
end
else
task test_task_name(solution_file) do
TC::Common.logger.info "No MSTest test projects found in #{solution_file}"
end
end
[test_task_name(solution_file)]
end
def test_tasks
@test_tasks ||= generate_test_tasks [build_task_name(solution_file)]
end
end
class VBPTaskGenerator < TaskGenerator
alias_method :vbp_file, :project_file
def self.project_file_pattern
/\.vbp$/i
end
def project
@project ||= VB6Project.new(vbp_file,Conf::Src.project_root(product))
end
# Build VB6 projects
def generate_build_tasks
name=build_task_name(vbp_file)
# Check out the project file
tfsco tfs_co_task_name(vbp_file) => :checkout do |tfs|
projects= []
project.recursively do |p,_|
projects << p
end
tfs.files = projects.collect_concat do |p|
[p.project_file,p.output]
end
end
# Update versions
task version_task_name(vbp_file) => tfs_co_task_name(vbp_file) do
version=Conf::Build.version(product)
# Update the version number and back up project files
project.recursively do |p,_|
p.version=version
p.backup
# Set file descriptions to include build timestamps
p.version_file_description=Conf::Build.description(product)
end
end
task name => version_task_name(vbp_file)
# Compile the project and its dependents in the correct order
task name do
project.compile
Common.logger.info("Built #{Conf::Build.product_name(product)}"+
" (#{File.basename(vbp_file)})"+
" v.#{Conf::Build.version(product)}")
end
[name]
end
def generate_build_msi_tasks
task build_msi_task_name(vbp_file) => build_task_name(vbp_file) do
# Restore project files (so project references are kept intact
# after compilation)
project.recursively do |p,_|
p.restore
end
end
[build_msi_task_name(vbp_file)]
end
end
end
# Yields to the given code block, the product names given in
# config/environment.yml. The first invocation of this method also
# results in a sanity check that verifies the existence of project
# files and TFS root directory for each product.
# All methods may be invoced with a code block as the last parameter,
# which can be accessed explicitly by prefixing the last parameter
# name with '&'. By using yield you can use this parameter without
# giving it a name. For more information on the yield construct, see
# http://www.tutorialspoint.com/ruby/ruby_blocks.htm
def each_product
@products ||= Conf::Environment.products# .collect do |product|
# root=Conf::Src.project_root(product)
# non_existent_project_files = Conf::Src.project_files(product.to_s).select {|f| !File.exist?(f) }
# if !File.exists?(root)
# raise "Illegal TFS root in config/src.yml: #{root}"
# elsif !non_existent_project_files.empty?
# raise "Illegal project file(s) in config/src.yml:"+
# " #{non_existent_project_files}"
# else
# product
# end
# end
@products.each {|p| yield(p) }
end
def task_generators(product)
@task_generators ||= {}
@task_generators[product] ||= TaskGenerator.create(product)
end
def get_tasks re
Rake.application.tasks.select {|t| re =~ t.name }
end
def create_parallel_task parents_regexp, child_name
parents=get_tasks parents_regexp
parent_deps=parents.collect_concat {|t| t.prerequisites }
TC::Common.logger.debug "enhanced Rake task #{child_name} with #{parent_deps} from #{parents_regexp.inspect}"
Rake::Task[child_name].enhance(parent_deps)
end
def inject_before(parents_regexp,child_name)
parents=get_tasks parents_regexp
parents.each do |parent|
before parent do
Rake::Task[child_name].invoke
end
end
TC::Common.logger.debug "injected #{child_name} before #{parents.join ', '}"
end
def inject_after(parents_regexp,child_name)
parents=get_tasks parents_regexp
parents.each do |parent|
after parent do
Rake::Task[child_name].invoke
end
end
TC::Common.logger.debug "injected #{child_name} after #{parents.join ', '}"
end
| olale/merlin | Merlin/lib/tasklib.rb | Ruby | gpl-2.0 | 14,075 |
#ifndef GRAPHICS_SHADERPROGRAM_H
#define GRAPHICS_SHADERPROGRAM_H
#include <panda/core.h>
#include <memory>
#include <string>
#include <vector>
namespace panda
{
namespace graphics
{
enum class ShaderType : char
{ Vertex = 1, Fragment, Geometry, TessellationControl, TessellationEvaluation, Compute };
// To free the shader only when every copy is destroyed
class PANDA_CORE_API ShaderId
{
public:
using SPtr = std::shared_ptr<ShaderId>;
ShaderId(ShaderType type, unsigned int id);
~ShaderId();
unsigned int id() const;
ShaderType type() const;
private:
unsigned int m_id;
ShaderType m_type;
};
// To free the shader program only when every copy is destroyed
class PANDA_CORE_API ShaderProgramId
{
public:
using SPtr = std::shared_ptr<ShaderProgramId>;
ShaderProgramId(unsigned int id = 0);
~ShaderProgramId();
unsigned int id() const;
private:
unsigned int m_id;
};
//****************************************************************************//
class PANDA_CORE_API ShaderProgram
{
public:
ShaderProgram(ShaderProgramId::SPtr id = nullptr);
bool addShaderFromMemory(ShaderType type, const std::string& content);
bool addShaderFromFile(ShaderType type, const std::string& path);
void addShader(ShaderId::SPtr id);
static ShaderId::SPtr compileShader(ShaderType type, const std::string& content, std::string* errorString = nullptr);
bool link(std::string* errorString = nullptr);
bool isLinked();
void clear(); // Remove shaders
unsigned int id() const;
ShaderProgramId::SPtr getProgramId() const;
void bind() const;
void release() const;
int uniformLocation(const char* name) const;
void setUniformValue(int location, int value) const;
void setUniformValue(int location, float value) const;
void setUniformValue(int location, const std::vector<int>& value) const;
void setUniformValue(int location, const std::vector<float>& value) const;
void setUniformValueArray(int location, const float* values, int count, int tupleSize) const;
void setUniformValueMat4(int location, const float* value) const;
void setUniformValue(const char* name, int value) const;
void setUniformValue(const char* name, float value) const;
void setUniformValue(const char* name, const std::vector<int>& value) const;
void setUniformValue(const char* name, const std::vector<float>& value) const;
void setUniformValueArray(const char* name, const float* values, int count, int tupleSize) const;
void setUniformValueMat4(const char* name, const float* value) const;
int attributeLocation(const char* name) const;
protected:
std::vector<ShaderId::SPtr> m_shaders;
ShaderProgramId::SPtr m_programId;
};
//****************************************************************************//
inline ShaderId::ShaderId(ShaderType type, unsigned int id)
: m_type(type), m_id(id) {}
inline unsigned int ShaderId::id() const
{ return m_id; }
inline ShaderType ShaderId::type() const
{ return m_type; }
//****************************************************************************//
inline ShaderProgramId::ShaderProgramId(unsigned int id)
: m_id(id) {}
inline unsigned int ShaderProgramId::id() const
{ return m_id; }
//****************************************************************************//
inline ShaderProgram::ShaderProgram(ShaderProgramId::SPtr id)
: m_programId(id) {}
inline ShaderProgramId::SPtr ShaderProgram::getProgramId() const
{ return m_programId; }
inline bool ShaderProgram::isLinked()
{ return m_programId != nullptr; }
inline unsigned int ShaderProgram::id() const
{ return m_programId ? m_programId->id() : 0; }
} // namespace graphics
} // namespace panda
#endif // GRAPHICS_SHADERPROGRAM_H
| cguebert/Panda | core/panda/graphics/ShaderProgram.h | C | gpl-2.0 | 3,664 |
package com.karniyarik.common.site;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import com.karniyarik.common.util.StringUtil;
public class FeaturedMerchantFactory
{
public static FeaturedMerchantVO create(String jsonStr)
{
try
{
return create(new JSONObject(jsonStr));
} catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public static List<FeaturedMerchantVO> createList(String jsonStr)
{
List<FeaturedMerchantVO> resultList = new ArrayList<FeaturedMerchantVO>();
if(StringUtils.isNotBlank(jsonStr))
{
try {
JSONArray siteJSONList = new JSONArray(jsonStr);
for(int index = 0; index < siteJSONList.length(); index++)
{
JSONObject jsonObj = siteJSONList.getJSONObject(index);
FeaturedMerchantVO info = create(jsonObj);
resultList.add(info);
}
} catch (Exception e) {
//e.printStackTrace();
}
}
return resultList;
}
public static FeaturedMerchantVO create(JSONObject rootObject)
{
FeaturedMerchantVO vo = new FeaturedMerchantVO();
try
{
String rootUrl = StringUtil.optJSONString(rootObject,"urlroot");
vo.setSitename(StringUtil.optJSONString(rootObject, "sitename"));
JSONObject jsonObject = rootObject.optJSONObject("merchant");
if(jsonObject != null)
{
vo.setFacebook(StringUtil.optJSONString(jsonObject,"facebook"));
vo.setLogo(StringUtil.optJSONString(rootObject,"logo"));
vo.setTwitter(StringUtil.optJSONString(jsonObject, "twitter"));
vo.setAboutus(StringUtil.optJSONString(jsonObject,"aboutus"));
vo.getContact().setContactus(StringUtil.optJSONString(jsonObject,"contactus"));
vo.getContact().setUrl(StringUtil.optJSONString(jsonObject, "url"));
vo.setName(jsonObject.optString("name"));
//vo.getContact().set(jsonObject.optString("sitename"));
vo.getContact().setCompany(StringUtil.optJSONString(jsonObject, "company"));
vo.getContact().setAddress(StringUtil.optJSONString(jsonObject, "address"));
vo.getContact().setEmail(StringUtil.optJSONString(jsonObject, "email"));
vo.getContact().setPhone(StringUtil.optJSONString(jsonObject, "phone"));
vo.getContact().setFax(StringUtil.optJSONString(jsonObject, "fax"));
vo.getContact().setUrl(StringUtil.optJSONString(jsonObject, "url"));
vo.getContact().setNotes(StringUtil.optJSONString(jsonObject, "notes"));
JSONArray jsonArray = jsonObject.optJSONArray("certificates");
for(int index=0; index< jsonArray.length(); index++)
{
JSONObject tmpObj = jsonArray.getJSONObject(index);
vo.getCertificates().add(new Certificate(StringUtil.optJSONString(tmpObj, "name"), rootUrl + "/" + StringUtil.optJSONString(tmpObj,"image")));
}
jsonArray = jsonObject.optJSONArray("shipmentTypes");
for(int index=0; index< jsonArray.length(); index++)
{
JSONObject tmpObj = jsonArray.getJSONObject(index);
vo.getShipment().add(new Shipment(StringUtil.optJSONString(tmpObj,"name"), rootUrl + "/" + StringUtil.optJSONString(tmpObj, "image")));
}
jsonArray = jsonObject.optJSONArray("paymentMethods");
for(int index=0; index< jsonArray.length(); index++)
{
JSONObject tmpObj = jsonArray.getJSONObject(index);
vo.getPayment().add(new Payment(StringUtil.optJSONString(tmpObj, "name"), rootUrl + "/" + StringUtil.optJSONString(tmpObj, "image")));
}
jsonArray = jsonObject.optJSONArray("links");
for(int index=0; index< jsonArray.length(); index++)
{
JSONObject tmpObj = jsonArray.getJSONObject(index);
vo.getLinks().put(StringUtil.optJSONString(tmpObj, "name"), StringUtil.optJSONString(tmpObj,"url"));
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return vo;
}
} | Karniyarik/karniyarik | karniyarik-common/src/main/java/com/karniyarik/common/site/FeaturedMerchantFactory.java | Java | gpl-2.0 | 4,045 |
namespace OpenNos.DAL.EF.MySQL.Migrations
{
using System.Data.Entity.Migrations;
internal sealed class Configuration : DbMigrationsConfiguration<OpenNos.DAL.EF.MySQL.DB.OpenNosContext>
{
#region Instantiation
public Configuration()
{
AutomaticMigrationsEnabled = false;
SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}
#endregion
}
} | Dactylr/OpenNos | OpenNos.DAL.EF.MySQL/Migrations/Configuration.cs | C# | gpl-2.0 | 464 |
<?php
// Create and instance of our rewrite machine
$more_fields_rewrite = new more_fields_rewrite_object;
class more_fields_rewrite_object {
/*
** more_fields_rewrite_object()
**
*/
function more_fields_rewrite_object () {
// Enable querying of Custom Fields using rewrite engine
add_filter('query_vars', array(&$this, 'query_vars'));
add_filter('posts_join', array(&$this, 'query_join'));
add_filter('posts_where', array(&$this, 'query_where'));
// add_filter('generate_rewrite_rules', array(&$this, 'generate_rewrite_rules'));
}
/*
** query_vars()
**
*/
function query_vars( $qvars ) {
$qvars[] = 'mf_key';
$qvars[] = 'mf_value';
return $qvars;
}
/*
** query_join()
**
*/
function query_join( $join ) {
global $wpdb, $wp_query;
if (!is_callable(array($wp_query, 'get'))) return false;
$gettype = (array_key_exists('type', $_GET)) ? esc_attr($_GET['type']) : 0;
if ($key = $wp_query->get('mf_key') || $type = $gettype) {
$join .= " LEFT JOIN $wpdb->postmeta as meta ON $wpdb->posts.ID = meta.post_id";
}
return $join;
}
/*
**
**
*/
function query_where( $where ) {
global $wpdb, $wp_query;
if (!is_callable(array($wp_query, 'get'))) return false;
// Should probably be exclusive instead of inclusive
if(strpos($_SERVER['SCRIPT_NAME'], '/media-upload.php')) return $where;
$key = $wp_query->get('mf_key');
$value = $wp_query->get('mf_value');
if ( $key )
$catch = "and $wpdb->posts.post_status='publish'";
if ( $key && $value ) $where .= " AND meta.meta_value='$value'" . $catch;
else if ($key) $where .= " AND meta.meta_value=!''" . $catch;
// We want to be able to sort by panel type
$gettype = (array_key_exists('type', $_GET)) ? esc_attr($_GET['type']) : 0;
if (($type = $gettype) && is_admin()) {
$where .= " AND meta.meta_key='mf_page_type' AND meta.meta_value='$type'";
}
//echo $where;
//exit(0);
return $where;
}
}
?>
| adrianjonmiller/Anacap-Tech | wp-content/plugins/more-fields/more-fields-rewrite-object.php | PHP | gpl-2.0 | 1,953 |
package de.steinberg.gyp.gui.view.tree.filesystem;
import de.steinberg.gyp.gui.icons.IconResolver;
import javafx.scene.control.TreeCell;
import javafx.scene.control.TreeView;
import javafx.util.Callback;
import javax.inject.Inject;
/**
* Created by LKLeen on 17.12.2014.
*/
public class PathTreeCellFactory implements Callback<TreeView<PathView>, TreeCell<PathView>> {
@Inject
IconResolver iconResolver;
@Inject
PathNodeHandler pathNodeHandler;
@Inject
PathTreeCellContextMenuFactory contextMenuFactory;
@Override
public TreeCell<PathView> call(TreeView<PathView> param) {
return new PathTreeCell(iconResolver, pathNodeHandler, contextMenuFactory);
}
}
| lkleen/de.steinberg.gyp | gui/src/main/java/de/steinberg/gyp/gui/view/tree/filesystem/PathTreeCellFactory.java | Java | gpl-2.0 | 706 |
# Be sure to restart your server when you modify this file.
ActorExpenses::Application.config.session_store :cookie_store, key: '_ActorExpenses_session'
# Use the database for sessions instead of the cookie-based default,
# which shouldn't be used to store highly confidential information
# (create the session table with "rails generate session_migration")
# ActorExpenses::Application.config.session_store :active_record_store
| adigitalnative/expenses | config/initializers/session_store.rb | Ruby | gpl-2.0 | 431 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright 2017-2022 Mike Fährmann
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
import os
import sys
import unittest
from unittest import mock
import time
import logging
import tempfile
from os.path import join
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from gallery_dl import config, extractor # noqa E402
class TestCookiejar(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.path = tempfile.TemporaryDirectory()
cls.cookiefile = join(cls.path.name, "cookies.txt")
with open(cls.cookiefile, "w") as file:
file.write("""# HTTP Cookie File
.example.org\tTRUE\t/\tFALSE\t253402210800\tNAME\tVALUE
""")
cls.invalid_cookiefile = join(cls.path.name, "invalid.txt")
with open(cls.invalid_cookiefile, "w") as file:
file.write("""# asd
.example.org\tTRUE/FALSE\t253402210800\tNAME\tVALUE
""")
@classmethod
def tearDownClass(cls):
cls.path.cleanup()
config.clear()
def test_cookiefile(self):
config.set((), "cookies", self.cookiefile)
cookies = extractor.find("test:").session.cookies
self.assertEqual(len(cookies), 1)
cookie = next(iter(cookies))
self.assertEqual(cookie.domain, ".example.org")
self.assertEqual(cookie.path , "/")
self.assertEqual(cookie.name , "NAME")
self.assertEqual(cookie.value , "VALUE")
def test_invalid_cookiefile(self):
self._test_warning(self.invalid_cookiefile, ValueError)
def test_invalid_filename(self):
self._test_warning(join(self.path.name, "nothing"), FileNotFoundError)
def _test_warning(self, filename, exc):
config.set((), "cookies", filename)
log = logging.getLogger("test")
with mock.patch.object(log, "warning") as mock_warning:
cookies = extractor.find("test:").session.cookies
self.assertEqual(len(cookies), 0)
self.assertEqual(mock_warning.call_count, 1)
self.assertEqual(mock_warning.call_args[0][0], "cookies: %s")
self.assertIsInstance(mock_warning.call_args[0][1], exc)
class TestCookiedict(unittest.TestCase):
def setUp(self):
self.cdict = {"NAME1": "VALUE1", "NAME2": "VALUE2"}
config.set((), "cookies", self.cdict)
def tearDown(self):
config.clear()
def test_dict(self):
cookies = extractor.find("test:").session.cookies
self.assertEqual(len(cookies), len(self.cdict))
self.assertEqual(sorted(cookies.keys()), sorted(self.cdict.keys()))
self.assertEqual(sorted(cookies.values()), sorted(self.cdict.values()))
def test_domain(self):
for category in ["exhentai", "idolcomplex", "nijie", "seiga"]:
extr = _get_extractor(category)
cookies = extr.session.cookies
for key in self.cdict:
self.assertTrue(key in cookies)
for c in cookies:
self.assertEqual(c.domain, extr.cookiedomain)
class TestCookieLogin(unittest.TestCase):
def tearDown(self):
config.clear()
def test_cookie_login(self):
extr_cookies = {
"exhentai" : ("ipb_member_id", "ipb_pass_hash"),
"idolcomplex": ("login", "pass_hash"),
"nijie" : ("nemail", "nlogin"),
"seiga" : ("user_session",),
}
for category, cookienames in extr_cookies.items():
cookies = {name: "value" for name in cookienames}
config.set((), "cookies", cookies)
extr = _get_extractor(category)
with mock.patch.object(extr, "_login_impl") as mock_login:
extr.login()
mock_login.assert_not_called()
class TestCookieUtils(unittest.TestCase):
def test_check_cookies(self):
extr = extractor.find("test:")
self.assertFalse(extr._cookiejar, "empty")
self.assertFalse(extr.cookiedomain, "empty")
# always returns False when checking for empty cookie list
self.assertFalse(extr._check_cookies(()))
self.assertFalse(extr._check_cookies(("a",)))
self.assertFalse(extr._check_cookies(("a", "b")))
self.assertFalse(extr._check_cookies(("a", "b", "c")))
extr._cookiejar.set("a", "1")
self.assertTrue(extr._check_cookies(("a",)))
self.assertFalse(extr._check_cookies(("a", "b")))
self.assertFalse(extr._check_cookies(("a", "b", "c")))
extr._cookiejar.set("b", "2")
self.assertTrue(extr._check_cookies(("a",)))
self.assertTrue(extr._check_cookies(("a", "b")))
self.assertFalse(extr._check_cookies(("a", "b", "c")))
def test_check_cookies_domain(self):
extr = extractor.find("test:")
self.assertFalse(extr._cookiejar, "empty")
extr.cookiedomain = ".example.org"
self.assertFalse(extr._check_cookies(("a",)))
self.assertFalse(extr._check_cookies(("a", "b")))
extr._cookiejar.set("a", "1")
self.assertFalse(extr._check_cookies(("a",)))
extr._cookiejar.set("a", "1", domain=extr.cookiedomain)
self.assertTrue(extr._check_cookies(("a",)))
extr._cookiejar.set("a", "1", domain="www" + extr.cookiedomain)
self.assertEqual(len(extr._cookiejar), 3)
self.assertTrue(extr._check_cookies(("a",)))
extr._cookiejar.set("b", "2", domain=extr.cookiedomain)
extr._cookiejar.set("c", "3", domain=extr.cookiedomain)
self.assertTrue(extr._check_cookies(("a", "b", "c")))
def test_check_cookies_expires(self):
extr = extractor.find("test:")
self.assertFalse(extr._cookiejar, "empty")
self.assertFalse(extr.cookiedomain, "empty")
now = int(time.time())
log = logging.getLogger("test")
extr._cookiejar.set("a", "1", expires=now-100)
with mock.patch.object(log, "warning") as mw:
self.assertFalse(extr._check_cookies(("a",)))
self.assertEqual(mw.call_count, 1)
self.assertEqual(mw.call_args[0], ("Cookie '%s' has expired", "a"))
extr._cookiejar.set("a", "1", expires=now+100)
with mock.patch.object(log, "warning") as mw:
self.assertFalse(extr._check_cookies(("a",)))
self.assertEqual(mw.call_count, 1)
self.assertEqual(mw.call_args[0], (
"Cookie '%s' will expire in less than %s hour%s", "a", 1, ""))
extr._cookiejar.set("a", "1", expires=now+100+7200)
with mock.patch.object(log, "warning") as mw:
self.assertFalse(extr._check_cookies(("a",)))
self.assertEqual(mw.call_count, 1)
self.assertEqual(mw.call_args[0], (
"Cookie '%s' will expire in less than %s hour%s", "a", 3, "s"))
extr._cookiejar.set("a", "1", expires=now+100+24*3600)
with mock.patch.object(log, "warning") as mw:
self.assertTrue(extr._check_cookies(("a",)))
self.assertEqual(mw.call_count, 0)
def _get_extractor(category):
for extr in extractor.extractors():
if extr.category == category and hasattr(extr, "_login_impl"):
url = next(extr._get_tests())[0]
return extr.from_url(url)
if __name__ == "__main__":
unittest.main()
| mikf/gallery-dl | test/test_cookies.py | Python | gpl-2.0 | 7,492 |
/*
* luaa.c - Lua configuration management
*
* Copyright © 2008-2009 Julien Danjou <julien@danjou.info>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
*/
/** AwesomeWM lifecycle API.
*
* This module contains the functions and signal to manage the lifecycle of the
* AwesomeWM process. It allows to execute code at specific point from the early
* initialization all the way to the last events before exiting or restarting.
*
* Additionally it handles signals for spawn and keyboard related events.
*
* @author Julien Danjou <julien@danjou.info>
* @copyright 2008-2009 Julien Danjou
* @coreclassmod awesome
*/
/** Register a new xproperty.
*
* @tparam string name The name of the X11 property.
* @tparam string type One of "string", "number" or "boolean".
* @staticfct register_xproperty
*/
#define _GNU_SOURCE
#include "luaa.h"
#include "globalconf.h"
#include "awesome.h"
#include "common/backtrace.h"
#include "common/version.h"
#include "config.h"
#include "event.h"
#include "objects/client.h"
#include "objects/drawable.h"
#include "objects/drawin.h"
#include "objects/selection_getter.h"
#include "objects/screen.h"
#include "objects/selection_acquire.h"
#include "objects/selection_transfer.h"
#include "objects/selection_watcher.h"
#include "objects/tag.h"
#include "property.h"
#include "selection.h"
#include "spawn.h"
#include "systray.h"
#include "xkb.h"
#include "xrdb.h"
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
/* for strings and Unicode handling */
#include <glib.h>
#include <stdlib.h>
#include <string.h>
#include <basedir_fs.h>
#include <xcb/xcb_atom.h>
#include <xcb/xcb_aux.h>
#include "xkb_utf32_to_keysym.c"
#include <unistd.h> /* for gethostname() */
#ifdef WITH_DBUS
extern const struct luaL_Reg awesome_dbus_lib[];
#endif
extern const struct luaL_Reg awesome_keygrabber_lib[];
extern const struct luaL_Reg awesome_mousegrabber_lib[];
extern const struct luaL_Reg awesome_mouse_methods[];
extern const struct luaL_Reg awesome_mouse_meta[];
extern const struct luaL_Reg awesome_root_methods[];
extern const struct luaL_Reg awesome_root_meta[];
signal_array_t global_signals;
/** A call into the Lua code aborted with an error.
*
* This signal is used in the example configuration, @{05-awesomerc.md},
* to let a notification box pop up.
* @param err Table with the error object, can be converted to a string with
* `tostring(err)`.
* @signal debug::error
*/
/** A deprecated Lua function was called.
*
* @tparam string hint String with a hint on what to use instead of the
* deprecated functionality.
* @tparam[opt=nil] string|nil see The name of the newer API
* @tparam[opt=nil] table|nil args The name of the newer API
* @signal debug::deprecation
*/
/** An invalid key was read from an object.
*
* This can happen if `foo` in an `c.foo` access does not exist.
* @param unknown1 Class?
* @param unknown2 Key?
* @signal debug::index::miss
*/
/** An invalid key was written to an object.
*
* This can happen if `foo` in an `c.foo = "bar"` assignment doesn't exist.
* @param unknown1 Class?
* @param unknown2 Key?
* @param unknown3 Value?
* @signal debug::newindex::miss
*/
/** The systray should be updated.
*
* This signal is used in `wibox.widget.systray`.
* @signal systray::update
*/
/** The wallpaper has changed.
*
* This signal is used for pseudo-transparency in `wibox.drawable` if no
* composite manager is running.
* @signal wallpaper_changed
*/
/** Keyboard map has changed.
*
* This signal is sent after the new keymap has been loaded. It is used in
* `awful.widget.keyboardlayout` to redraw the layout.
* @signal xkb::map_changed
*/
/** Keyboard group has changed.
*
* It's used in `awful.widget.keyboardlayout` to redraw the layout.
* @param group Integer containing the changed group
* @signal xkb::group_changed.
*/
/** Refresh.
*
* This signal is emitted as a kind of idle signal in the event loop.
* One example usage is in `gears.timer` to executed delayed calls.
* @signal refresh
*/
/** AwesomeWM is about to enter the event loop.
*
* This means all initialization has been done.
* @signal startup
*/
/** AwesomeWM is exiting / about to restart.
*
* This signal is emitted in the `atexit` handler as well when awesome
* restarts.
* @param reason_restart Boolean value is true if the signal was sent
* because of a restart.
* @signal exit
*/
/** The output status of a screen has changed.
*
* @tparam string output String containing which output has changed.
* @tparam string connection_state String containing the connection status of
* the output: It will be either "Connected", "Disconnected" or
* "Unknown".
* @signal screen::change
*/
/** Path to config file */
static char *conffile;
/** Check whether a composite manager is running.
* \return True if such a manager is running.
*/
static bool
composite_manager_running(void)
{
xcb_intern_atom_reply_t *atom_r;
xcb_get_selection_owner_reply_t *selection_r;
char *atom_name;
bool result;
if(!(atom_name = xcb_atom_name_by_screen("_NET_WM_CM", globalconf.default_screen)))
{
warn("error getting composite manager atom");
return false;
}
atom_r = xcb_intern_atom_reply(globalconf.connection,
xcb_intern_atom_unchecked(globalconf.connection, false,
a_strlen(atom_name), atom_name),
NULL);
p_delete(&atom_name);
if(!atom_r)
return false;
selection_r = xcb_get_selection_owner_reply(globalconf.connection,
xcb_get_selection_owner_unchecked(globalconf.connection,
atom_r->atom),
NULL);
p_delete(&atom_r);
result = selection_r != NULL && selection_r->owner != XCB_NONE;
p_delete(&selection_r);
return result;
}
/** Quit awesome.
* @tparam[opt=0] integer code The exit code to use when exiting.
* @staticfct quit
*/
static int
luaA_quit(lua_State *L)
{
if (!lua_isnoneornil(L, 1))
globalconf.exit_code = luaL_checkinteger(L, 1);
if (globalconf.loop == NULL)
globalconf.loop = g_main_loop_new(NULL, FALSE);
g_main_loop_quit(globalconf.loop);
return 0;
}
/** Execute another application, probably a window manager, to replace
* awesome.
*
* @param cmd The command line to execute.
* @staticfct exec
*/
static int
luaA_exec(lua_State *L)
{
const char *cmd = luaL_checkstring(L, 1);
awesome_atexit(false);
a_exec(cmd);
return 0;
}
/** Restart awesome.
* @staticfct restart
*/
static int
luaA_restart(lua_State *L)
{
awesome_restart();
return 0;
}
/** Send a signal to a process.
* @tparam integer pid Process identifier. 0 and negative values have special
* meaning. See `man 3 kill`.
* @tparam integer sig Signal number.
* See `awesome.unix_signal` for a list of signals.
* @treturn boolean true if the signal was successfully sent, else false
* @staticfct kill
*/
static int
luaA_kill(lua_State *L)
{
int pid = luaL_checknumber(L, 1);
int sig = luaA_checknumber_range(L, 2, 0, INT_MAX);
int result = kill(pid, sig);
lua_pushboolean(L, result == 0);
return 1;
}
/** Synchronize with the X11 server. This is needed in the test suite to avoid
* some race conditions. You should never need to use this function.
* @staticfct sync
*/
static int
luaA_sync(lua_State *L)
{
xcb_aux_sync(globalconf.connection);
return 0;
}
/** Translate a GdkPixbuf to a cairo image surface..
*
* @param pixbuf The pixbuf as a light user datum.
* @param path The pixbuf origin path
* @return A cairo surface as light user datum.
* @staticfct pixbuf_to_surface
*/
static int
luaA_pixbuf_to_surface(lua_State *L)
{
GdkPixbuf *pixbuf = (GdkPixbuf *) lua_touserdata(L, 1);
cairo_surface_t *surface = draw_surface_from_pixbuf(pixbuf);
/* lua has to make sure to free the ref or we have a leak */
lua_pushlightuserdata(L, surface);
return 1;
}
/** Load an image from a given path.
*
* @param name The file name.
* @return[1] A cairo surface as light user datum.
* @return[2] nil
* @treturn[2] string Error message
* @staticfct load_image
*/
static int
luaA_load_image(lua_State *L)
{
/* TODO: Deprecate this function, Lua can use GdkPixbuf directly plus
* awesome.pixbuf_to_surface
*/
GError *error = NULL;
const char *filename = luaL_checkstring(L, 1);
cairo_surface_t *surface = draw_load_image(L, filename, &error);
if (!surface) {
lua_pushnil(L);
lua_pushstring(L, error->message);
g_error_free(error);
return 2;
}
/* lua has to make sure to free the ref or we have a leak */
lua_pushlightuserdata(L, surface);
return 1;
}
/** Set the preferred size for client icons.
*
* The closest equal or bigger size is picked if present, otherwise the closest
* smaller size is picked. The default is 0 pixels, ie. the smallest icon.
*
* @param size The size of the icons in pixels.
* @staticfct set_preferred_icon_size
*/
static int
luaA_set_preferred_icon_size(lua_State *L)
{
globalconf.preferred_icon_size = luaA_checkinteger_range(L, 1, 0, UINT32_MAX);
return 0;
}
/** UTF-8 aware string length computing.
* \param L The Lua VM state.
* \return The number of elements pushed on stack.
*/
static int
luaA_mbstrlen(lua_State *L)
{
const char *cmd = luaL_checkstring(L, 1);
lua_pushinteger(L, (ssize_t) mbstowcs(NULL, NONULL(cmd), 0));
return 1;
}
/** Enhanced type() function which recognize awesome objects.
* \param L The Lua VM state.
* \return The number of arguments pushed on the stack.
*/
static int
luaAe_type(lua_State *L)
{
luaL_checkany(L, 1);
lua_pushstring(L, luaA_typename(L, 1));
return 1;
}
/** Replace various standards Lua functions with our own.
* \param L The Lua VM state.
*/
static void
luaA_fixups(lua_State *L)
{
/* export string.wlen */
lua_getglobal(L, "string");
lua_pushcfunction(L, luaA_mbstrlen);
lua_setfield(L, -2, "wlen");
lua_pop(L, 1);
/* replace type */
lua_pushcfunction(L, luaAe_type);
lua_setglobal(L, "type");
}
static const char *
get_modifier_name(int map_index)
{
switch (map_index) {
case XCB_MAP_INDEX_SHIFT: return "Shift";
case XCB_MAP_INDEX_LOCK: return "Lock";
case XCB_MAP_INDEX_CONTROL: return "Control";
case XCB_MAP_INDEX_1: return "Mod1"; /* Alt */
case XCB_MAP_INDEX_2: return "Mod2";
case XCB_MAP_INDEX_3: return "Mod3";
case XCB_MAP_INDEX_4: return "Mod4";
case XCB_MAP_INDEX_5: return "Mod5";
}
return 0; /* \0 */
}
/* Helper function for luaA_get_key_name() below.
* Will return the UTF-32 codepoint IF AND ONLY IF the input is exactly one
* valid UTF-8 character. Otherwise, it will return zero.
*/
static uint32_t
one_utf8_to_utf32(const char* input, const size_t length) {
gunichar character = g_utf8_get_char_validated(input, length);
// Return 0 if there is more than one UTF-8 character:
if (g_unichar_to_utf8(character, NULL) != (gint)length)
return 0;
// Return 0 if the character is invalid.
if (character == (gunichar)-1 || character == (gunichar)-2)
return 0;
return character;
}
/* Get X11 keysym and a one-character representation from an Awesome keycode.
*
* A "one-character representation" is a single UTF-8 representing the typical
* output from that keysym in a text editor (e.g. " " for space, "ñ" for
* n_tilde, "Ā" for A_macron). It usually matches the main engraving of the key
* for level-0 symbols (but lowercase).
*
* Keycodes may be given in a string in any valid format for `awful.key`:
* "#" + keycode, the symkey name and the UTF-8 representation will all work.
*
* If no suitable keysym is found, or a malformed keycode is given as an
* argument, this function will return (nil, nil)
*
* @treturn[1] string keysym The keysym name
* @treturn[1] nil keysym If no valid keysym is found
* @treturn[2] string printsymbol The xkb_keysym_to_utf8 result
* @treturn[2] nil printsymbol If the keysym has no printable representation.
* @staticfct awful.keyboard.get_key_name
*/
static int
luaA_get_key_name(lua_State *L)
{
// check if argument is valid
if (lua_gettop(L) > 1 || lua_type(L, 1) != LUA_TSTRING)
{
return 0;
}
const char* input = luaL_checkstring(L, 1);
const xkb_keysym_t *keysyms;
xkb_keysym_t keysym = XKB_KEY_NoSymbol;
const size_t length = strlen(input);
uint32_t ucs;
/* Checking for the three possible syntaxes awful.key uses:
* 1: #keycode (#8 to #255, any other is invalid)
* 2: the symbol itself (the result of xkb_keysym_to_utf8, e.g. @ for at).
* 3: the keysym
*/
if (input[0] == '#' && input[1] != '\0' && length < 5) // syntax #1
{
int keycode_from_hash = atoi(input+1);
// We discard keycodes with invalid values:
const xcb_setup_t *setup = xcb_get_setup(globalconf.connection);
if (keycode_from_hash < setup->min_keycode ||
keycode_from_hash > setup->max_keycode)
return 0;
xkb_keycode_t keycode = (xkb_keycode_t) keycode_from_hash;
struct xkb_keymap *keymap = xkb_state_get_keymap(globalconf.xkb_state);
xkb_keymap_key_get_syms_by_level(keymap, keycode, 0, 0, &keysyms);
keysym = keysyms[0];
}
else if ((ucs = one_utf8_to_utf32(input, length)) > 0) //syntax #2
keysym = xkb_utf32_to_keysym(ucs);
else //syntax #3
keysym = xkb_keysym_from_name(input, XKB_KEYSYM_NO_FLAGS);
if (keysym == XKB_KEY_NoSymbol)
return 0;
else
{
char *name = key_get_keysym_name(keysym);
lua_pushstring(L, name);
char utfname[8];
if (xkb_keysym_to_utf8(keysym, utfname, 8) > 0)
lua_pushstring(L, utfname);
else
return 1; // this will make the second returned value a nil
}
return 2;
}
/* Undocumented */
/*
* The table of keybindings modifiers.
*
* Each modifier has zero to many entries depending on the keyboard layout.
* For example, `Shift` usually both has a left and right variant. Each
* modifier entry has a `keysym` and `keycode` entry. For the US PC 105
* keyboard, it looks like:
*
* awesome.modifiers = {
* Shift = {
* {keycode = 50 , keysym = 'Shift_L' },
* {keycode = 62 , keysym = 'Shift_R' },
* },
* Lock = {},
* Control = {
* {keycode = 37 , keysym = 'Control_L' },
* {keycode = 105, keysym = 'Control_R' },
* },
* Mod1 = {
* {keycode = 64 , keysym = 'Alt_L' },
* {keycode = 108, keysym = 'Alt_R' },
* },
* Mod2 = {
* {keycode = 77 , keysym = 'Num_Lock' },
* },
* Mod3 = {},
* Mod4 = {
* {keycode = 133, keysym = 'Super_L' },
* {keycode = 134, keysym = 'Super_R' },
* },
* Mod5 = {
* {keycode = 203, keysym = 'Mode_switch'},
* },
* };
*
* @tfield table modifiers
* @tparam table modifiers.Shift The Shift modifiers.
* @tparam table modifiers.Lock The Lock modifiers.
* @tparam table modifiers.Control The Control modifiers.
* @tparam table modifiers.Mod1 The Mod1 (Alt) modifiers.
* @tparam table modifiers.Mod2 The Mod2 modifiers.
* @tparam table modifiers.Mod3 The Mod3 modifiers.
* @tparam table modifiers.Mod4 The Mod4 modifiers.
* @tparam table modifiers.Mod5 The Mod5 modifiers.
*/
/*
* Modifiers can change over time, given they are currently not tracked, just
* query them each time. Use with moderation.
*/
static int luaA_get_modifiers(lua_State *L)
{
xcb_get_modifier_mapping_reply_t *mods = xcb_get_modifier_mapping_reply(globalconf.connection,
xcb_get_modifier_mapping(globalconf.connection), NULL);
if (!mods)
return 0;
xcb_keycode_t *mappings = xcb_get_modifier_mapping_keycodes(mods);
struct xkb_keymap *keymap = xkb_state_get_keymap(globalconf.xkb_state);
lua_newtable(L);
/* This get the MAPPED modifiers, not all of them are */
for (int i = XCB_MAP_INDEX_SHIFT; i <= XCB_MAP_INDEX_5; i++) {
lua_pushstring(L, get_modifier_name(i));
lua_newtable(L);
for (int j = 0; j < mods->keycodes_per_modifier; j++) {
const xkb_keysym_t *keysyms;
const xcb_keycode_t key_code = mappings[i * mods->keycodes_per_modifier + j];
xkb_keymap_key_get_syms_by_level(keymap, key_code, 0, 0, &keysyms);
if (keysyms != NULL) {
/* The +1 because j starts at zero and Lua at 1 */
lua_pushinteger(L, j+1);
lua_newtable(L);
lua_pushstring(L, "keycode");
lua_pushinteger(L, key_code);
lua_settable(L, -3);
/* Technically it is possible to get multiple keysyms here,
* but... we just use the first one.
*/
lua_pushstring(L, "keysym");
char *string = key_get_keysym_name(keysyms[0]);
lua_pushstring(L, string);
p_delete(&string);
lua_settable(L, -3);
lua_settable(L, -3);
}
}
lua_settable(L, -3);
}
free(mods);
return 0;
}
/* Undocumented */
/*
* A table with the currently active modifier names.
*
* @tfield table _active_modifiers
*/
static int luaA_get_active_modifiers(lua_State *L)
{
int count = 1;
lua_newtable(L);
for (int i = XCB_MAP_INDEX_SHIFT; i <= XCB_MAP_INDEX_5; i++) {
const int active = xkb_state_mod_index_is_active (globalconf.xkb_state, i,
XKB_STATE_MODS_DEPRESSED | XKB_STATE_MODS_EFFECTIVE
);
if (active) {
lua_pushstring(L, get_modifier_name(i));
lua_rawseti(L,-2, count++);
}
}
return 0;
}
/**
* The AwesomeWM version.
* @tfield string version
*/
/**
* The AwesomeWM release name.
* @tfield string release
*/
/**
* The AwesomeWM API level.
*
* By default, this matches the major version (first component of the version).
*
* API levels are used to allow newer version of AwesomeWM to alter the behavior
* and subset deprecated APIs. Using an older API level than the current major
* version allows to use legacy `rc.lua` with little porting. However, they wont
* be able to use all the new features. Attempting to use a newer feature along
* with an older API level is not and will not be supported, even if it almost
* works. Keeping up to date with the newer API levels is highly recommended.
*
* Going the other direction, setting an higher API level allows to take
* advantage of experimental feature. It will also be much harsher when it comes
* to deprecation. Setting the API level value beyond `current+3` will treat
* using APIs currently pending deprecation as fatal errors. All new code
* submitted to the upstream AwesomeWM codebase is forbidden to use deprecated
* APIs. Testing your patches with mode and the default config is recommended
* before submitting a patch.
*
* You can use the `-l` command line option or `api-level` modeline key to set
* the API level for your `rc.lua`. This setting is global and read only,
* individual modules cannot set their own API level.
*
* @tfield string api_level
*/
/**
* The configuration file which has been loaded.
* @tfield string conffile
*/
/**
* True if we are still in startup, false otherwise.
* @tfield boolean startup
*/
/**
* Error message for errors that occured during
* startup.
* @tfield string startup_errors
*/
/**
* True if a composite manager is running.
* @tfield boolean composite_manager_running
*/
/**
* Table mapping between signal numbers and signal identifiers.
* @tfield table unix_signal
*/
/**
* The hostname of the computer on which we are running.
* @tfield string hostname
*/
/**
* The path where themes were installed to.
* @tfield string themes_path
*/
/**
* The path where icons were installed to.
* @tfield string icon_path
*/
static int
luaA_awesome_index(lua_State *L)
{
if(luaA_usemetatable(L, 1, 2))
return 1;
const char *buf = luaL_checkstring(L, 2);
if(A_STREQ(buf, "conffile"))
{
lua_pushstring(L, conffile);
return 1;
}
if(A_STREQ(buf, "version"))
{
lua_pushstring(L, awesome_version_string());
return 1;
}
if(A_STREQ(buf, "release"))
{
lua_pushstring(L, awesome_release_string());
return 1;
}
if(A_STREQ(buf, "api_level"))
{
lua_pushinteger(L, globalconf.api_level);
return 1;
}
if(A_STREQ(buf, "startup"))
{
lua_pushboolean(L, globalconf.loop == NULL);
return 1;
}
if(A_STREQ(buf, "_modifiers"))
{
luaA_get_modifiers(L);
return 1;
}
if(A_STREQ(buf, "_active_modifiers"))
{
luaA_get_active_modifiers(L);
return 1;
}
if(A_STREQ(buf, "startup_errors"))
{
if (globalconf.startup_errors.len == 0)
return 0;
lua_pushstring(L, globalconf.startup_errors.s);
return 1;
}
if(A_STREQ(buf, "composite_manager_running"))
{
lua_pushboolean(L, composite_manager_running());
return 1;
}
if(A_STREQ(buf, "hostname"))
{
/* No good way to handle failures... */
char hostname[256] = "";
gethostname(&hostname[0], countof(hostname));
hostname[countof(hostname) - 1] = '\0';
lua_pushstring(L, hostname);
return 1;
}
if(A_STREQ(buf, "themes_path"))
{
lua_pushliteral(L, AWESOME_THEMES_PATH);
return 1;
}
if(A_STREQ(buf, "icon_path"))
{
lua_pushliteral(L, AWESOME_ICON_PATH);
return 1;
}
return luaA_default_index(L);
}
/** Add a global signal.
*
* @param name A string with the event name.
* @param func The function to call.
* @staticfct connect_signal
*/
static int
luaA_awesome_connect_signal(lua_State *L)
{
const char *name = luaL_checkstring(L, 1);
luaA_checkfunction(L, 2);
signal_connect(&global_signals, name, luaA_object_ref(L, 2));
return 0;
}
/** Remove a global signal.
*
* @param name A string with the event name.
* @param func The function to call.
* @staticfct disconnect_signal
*/
static int
luaA_awesome_disconnect_signal(lua_State *L)
{
const char *name = luaL_checkstring(L, 1);
luaA_checkfunction(L, 2);
const void *func = lua_topointer(L, 2);
if (signal_disconnect(&global_signals, name, func))
luaA_object_unref(L, (void *) func);
return 0;
}
/** Emit a global signal.
*
* @param name A string with the event name.
* @param ... The signal arguments.
* @staticfct emit_signal
*/
static int
luaA_awesome_emit_signal(lua_State *L)
{
signal_object_emit(L, &global_signals, luaL_checkstring(L, 1), lua_gettop(L) - 1);
return 0;
}
static int
luaA_panic(lua_State *L)
{
warn("unprotected error in call to Lua API (%s)",
lua_tostring(L, -1));
buffer_t buf;
backtrace_get(&buf);
warn("dumping backtrace\n%s", buf.s);
warn("restarting awesome");
awesome_restart();
return 0;
}
#if LUA_VERSION_NUM >= 502
static const char *
luaA_tolstring(lua_State *L, int idx, size_t *len)
{
return luaL_tolstring(L, idx, len);
}
#else
static const char *
luaA_tolstring(lua_State *L, int idx, size_t *len)
{
/* Try using the metatable. If that fails, push the value itself onto
* the stack.
*/
if (!luaL_callmeta(L, idx, "__tostring"))
lua_pushvalue(L, idx);
switch (lua_type(L, -1)) {
case LUA_TSTRING:
lua_pushvalue(L, -1);
break;
case LUA_TBOOLEAN:
if (lua_toboolean(L, -1))
lua_pushliteral(L, "true");
else
lua_pushliteral(L, "false");
break;
case LUA_TNUMBER:
lua_pushfstring(L, "%f", lua_tonumber(L, -1));
break;
case LUA_TNIL:
lua_pushstring(L, "nil");
break;
default:
lua_pushfstring(L, "%s: %p",
lua_typename(L, lua_type(L, -1)),
lua_topointer(L, -1));
break;
}
lua_remove(L, -2);
return lua_tolstring(L, -1, len);
}
#endif
static int
luaA_dofunction_on_error(lua_State *L)
{
/* Convert error to string, to prevent a follow-up error with lua_concat. */
luaA_tolstring(L, -1, NULL);
/* duplicate string error */
lua_pushvalue(L, -1);
/* emit error signal */
signal_object_emit(L, &global_signals, "debug::error", 1);
if(!luaL_dostring(L, "return debug.traceback(\"error while running function!\", 3)"))
{
/* Move traceback before error */
lua_insert(L, -2);
/* Insert sentence */
lua_pushliteral(L, "\nerror: ");
/* Move it before error */
lua_insert(L, -2);
lua_concat(L, 3);
}
return 1;
}
static void
setup_awesome_signals(lua_State *L)
{
lua_getglobal(L, "awesome");
lua_pushstring(L, "unix_signal");
lua_newtable(L);
#define SETUP_SIGNAL(sig) \
do { \
/* Set awesome.unix_signal["SIGSTOP"] = 42 */ \
lua_pushinteger(L, sig); \
lua_setfield(L, -2, #sig); \
/* Set awesome.unix_signal[42] = "SIGSTOP" */ \
lua_pushinteger(L, sig); \
lua_pushstring(L, #sig); \
lua_settable(L, -3); \
} while (0)
/* Non-standard signals. These are first so that e.g. (on my system)
* signals[29] is SIGPOLL and not SIGIO (the value gets overwritten).
*/
#ifdef SIGIOT
SETUP_SIGNAL(SIGIOT);
#endif
#ifdef SIGEMT
SETUP_SIGNAL(SIGEMT);
#endif
#ifdef SIGSTKFLT
SETUP_SIGNAL(SIGSTKFLT);
#endif
#ifdef SIGIO
SETUP_SIGNAL(SIGIO);
#endif
#ifdef SIGCLD
SETUP_SIGNAL(SIGCLD);
#endif
#ifdef SIGPWR
SETUP_SIGNAL(SIGPWR);
#endif
#ifdef SIGINFO
SETUP_SIGNAL(SIGINFO);
#endif
#ifdef SIGLOST
SETUP_SIGNAL(SIGLOST);
#endif
#ifdef SIGWINCH
SETUP_SIGNAL(SIGWINCH);
#endif
#ifdef SIGUNUSED
SETUP_SIGNAL(SIGUNUSED);
#endif
/* POSIX.1-1990, according to man 7 signal */
SETUP_SIGNAL(SIGHUP);
SETUP_SIGNAL(SIGINT);
SETUP_SIGNAL(SIGQUIT);
SETUP_SIGNAL(SIGILL);
SETUP_SIGNAL(SIGABRT);
SETUP_SIGNAL(SIGFPE);
SETUP_SIGNAL(SIGKILL);
SETUP_SIGNAL(SIGSEGV);
SETUP_SIGNAL(SIGPIPE);
SETUP_SIGNAL(SIGALRM);
SETUP_SIGNAL(SIGTERM);
SETUP_SIGNAL(SIGUSR1);
SETUP_SIGNAL(SIGUSR2);
SETUP_SIGNAL(SIGCHLD);
SETUP_SIGNAL(SIGCONT);
SETUP_SIGNAL(SIGSTOP);
SETUP_SIGNAL(SIGTSTP);
SETUP_SIGNAL(SIGTTIN);
SETUP_SIGNAL(SIGTTOU);
/* POSIX.1-2001, according to man 7 signal */
SETUP_SIGNAL(SIGBUS);
/* Some Operating Systems doesn't have SIGPOLL (e.g. FreeBSD) */
#ifdef SIGPOLL
SETUP_SIGNAL(SIGPOLL);
#endif
SETUP_SIGNAL(SIGPROF);
SETUP_SIGNAL(SIGSYS);
SETUP_SIGNAL(SIGTRAP);
SETUP_SIGNAL(SIGURG);
SETUP_SIGNAL(SIGVTALRM);
SETUP_SIGNAL(SIGXCPU);
SETUP_SIGNAL(SIGXFSZ);
#undef SETUP_SIGNAL
/* Set awesome.signal to the table we just created, key was already pushed */
lua_rawset(L, -3);
/* Pop "awesome" */
lua_pop(L, 1);
}
/* Add things to the string on top of the stack */
static void
add_to_search_path(lua_State *L, string_array_t *searchpath, bool for_lua)
{
if (LUA_TSTRING != lua_type(L, -1))
{
warn("package.path is not a string");
return;
}
foreach(entry, *searchpath)
{
int components;
size_t len = a_strlen(*entry);
lua_pushliteral(L, ";");
lua_pushlstring(L, *entry, len);
if (for_lua)
lua_pushliteral(L, "/?.lua");
else
lua_pushliteral(L, "/?.so");
lua_concat(L, 3);
if (for_lua)
{
lua_pushliteral(L, ";");
lua_pushlstring(L, *entry, len);
lua_pushliteral(L, "/?/init.lua");
lua_concat(L, 3);
components = 2;
} else {
components = 1;
}
lua_concat(L, components + 1); /* concatenate with string on top of the stack */
}
/* add Lua lib path (/usr/share/awesome/lib by default) */
if (for_lua)
{
lua_pushliteral(L, ";" AWESOME_LUA_LIB_PATH "/?.lua");
lua_pushliteral(L, ";" AWESOME_LUA_LIB_PATH "/?/init.lua");
lua_concat(L, 3); /* concatenate with thing on top of the stack when we were called */
} else {
lua_pushliteral(L, ";" AWESOME_LUA_LIB_PATH "/?.so");
lua_concat(L, 2); /* concatenate with thing on top of the stack when we were called */
}
}
/** Initialize the Lua VM
* \param xdg An xdg handle to use to get XDG basedir.
*/
void
luaA_init(xdgHandle* xdg, string_array_t *searchpath)
{
lua_State *L;
static const struct luaL_Reg awesome_lib[] =
{
{ "quit", luaA_quit },
{ "exec", luaA_exec },
{ "spawn", luaA_spawn },
{ "restart", luaA_restart },
{ "connect_signal", luaA_awesome_connect_signal },
{ "disconnect_signal", luaA_awesome_disconnect_signal },
{ "emit_signal", luaA_awesome_emit_signal },
{ "systray", luaA_systray },
{ "load_image", luaA_load_image },
{ "pixbuf_to_surface", luaA_pixbuf_to_surface },
{ "set_preferred_icon_size", luaA_set_preferred_icon_size },
{ "register_xproperty", luaA_register_xproperty },
{ "set_xproperty", luaA_set_xproperty },
{ "get_xproperty", luaA_get_xproperty },
{ "__index", luaA_awesome_index },
{ "__newindex", luaA_default_newindex },
{ "xkb_set_layout_group", luaA_xkb_set_layout_group},
{ "xkb_get_layout_group", luaA_xkb_get_layout_group},
{ "xkb_get_group_names", luaA_xkb_get_group_names},
{ "xrdb_get_value", luaA_xrdb_get_value},
{ "kill", luaA_kill},
{ "sync", luaA_sync},
{ "_get_key_name", luaA_get_key_name},
{ NULL, NULL }
};
L = globalconf.L.real_L_dont_use_directly = luaL_newstate();
/* Set panic function */
lua_atpanic(L, luaA_panic);
/* Set error handling function */
lualib_dofunction_on_error = luaA_dofunction_on_error;
luaL_openlibs(L);
luaA_fixups(L);
luaA_object_setup(L);
/* Export awesome lib */
luaA_openlib(L, "awesome", awesome_lib, awesome_lib);
setup_awesome_signals(L);
/* Export root lib */
luaA_openlib(L, "root", awesome_root_methods, awesome_root_meta);
#ifdef WITH_DBUS
/* Export D-Bus lib */
luaA_registerlib(L, "dbus", awesome_dbus_lib);
lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
#endif
/* Export keygrabber lib */
luaA_registerlib(L, "keygrabber", awesome_keygrabber_lib);
lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
/* Export mousegrabber lib */
luaA_registerlib(L, "mousegrabber", awesome_mousegrabber_lib);
lua_pop(L, 1); /* luaA_registerlib() leaves the table on stack */
/* Export mouse */
luaA_openlib(L, "mouse", awesome_mouse_methods, awesome_mouse_meta);
/* Export screen */
screen_class_setup(L);
/* Export button */
button_class_setup(L);
/* Export tag */
tag_class_setup(L);
/* Export window */
window_class_setup(L);
/* Export drawable */
drawable_class_setup(L);
/* Export drawin */
drawin_class_setup(L);
/* Export client */
client_class_setup(L);
/* Export selection getter */
selection_getter_class_setup(L);
/* Export keys */
key_class_setup(L);
/* Export selection acquire */
selection_acquire_class_setup(L);
/* Export selection transfer */
selection_transfer_class_setup(L);
/* Export selection watcher */
selection_watcher_class_setup(L);
/* Setup the selection interface */
selection_setup(L);
/* add Lua search paths */
lua_getglobal(L, "package");
if (LUA_TTABLE != lua_type(L, 1))
{
warn("package is not a table");
return;
}
lua_getfield(L, 1, "path");
add_to_search_path(L, searchpath, true);
lua_setfield(L, 1, "path"); /* package.path = "concatenated string" */
lua_getfield(L, 1, "cpath");
add_to_search_path(L, searchpath, false);
lua_setfield(L, 1, "cpath"); /* package.cpath = "concatenated string" */
lua_pop(L, 1); /* pop "package" */
}
static void
luaA_startup_error(const char *err)
{
if (globalconf.startup_errors.len > 0)
buffer_addsl(&globalconf.startup_errors, "\n\n");
buffer_adds(&globalconf.startup_errors, err);
}
static bool
luaA_loadrc(const char *confpath)
{
lua_State *L = globalconf_get_lua_State();
if(luaL_loadfile(L, confpath))
{
const char *err = lua_tostring(L, -1);
luaA_startup_error(err);
fprintf(stderr, "%s\n", err);
lua_pop(L, 1);
return false;
}
/* Set the conffile right now so it can be used inside the
* configuration file. */
conffile = a_strdup(confpath);
/* Move error handling function before function */
lua_pushcfunction(L, luaA_dofunction_on_error);
lua_insert(L, -2);
if(!lua_pcall(L, 0, 0, -2))
{
/* Pop luaA_dofunction_on_error */
lua_pop(L, 1);
return true;
}
const char *err = lua_tostring(L, -1);
luaA_startup_error(err);
fprintf(stderr, "%s\n", err);
/* An error happened, so reset this. */
conffile = NULL;
/* Pop luaA_dofunction_on_error() and the error message */
lua_pop(L, 2);
return false;
}
/** Load a configuration file.
* \param xdg An xdg handle to use to get XDG basedir.
* \param confpatharg The configuration file to load.
* \param run Run the configuration file.
*/
bool
luaA_parserc(xdgHandle* xdg, const char *confpatharg)
{
const char *confpath = luaA_find_config(xdg, confpatharg, luaA_loadrc);
bool ret = confpath != NULL;
p_delete(&confpath);
return ret;
}
/** Find a config file for which the given callback returns true.
* \param xdg An xdg handle to use to get XDG basedir.
* \param confpatharg The configuration file to load.
* \param callback The callback to call.
*/
const char *
luaA_find_config(xdgHandle* xdg, const char *confpatharg, luaA_config_callback *callback)
{
char *confpath = NULL;
if(confpatharg && callback(confpatharg))
{
return a_strdup(confpatharg);
}
confpath = xdgConfigFind("awesome/rc.lua", xdg);
char *tmp = confpath;
/* confpath is "string1\0string2\0string3\0\0" */
while(*tmp)
{
if(callback(tmp))
{
const char *ret = a_strdup(tmp);
p_delete(&confpath);
return ret;
}
tmp += a_strlen(tmp) + 1;
}
p_delete(&confpath);
if(callback(AWESOME_DEFAULT_CONF))
{
return a_strdup(AWESOME_DEFAULT_CONF);
}
return NULL;
}
int
luaA_class_index_miss_property(lua_State *L, lua_object_t *obj)
{
signal_object_emit(L, &global_signals, "debug::index::miss", 2);
return 0;
}
int
luaA_class_newindex_miss_property(lua_State *L, lua_object_t *obj)
{
signal_object_emit(L, &global_signals, "debug::newindex::miss", 3);
return 0;
}
void
luaA_emit_startup()
{
lua_State *L = globalconf_get_lua_State();
signal_object_emit(L, &global_signals, "startup", 0);
}
void
luaA_emit_refresh()
{
lua_State *L = globalconf_get_lua_State();
signal_object_emit(L, &global_signals, "refresh", 0);
}
int
luaA_default_index(lua_State *L)
{
return luaA_class_index_miss_property(L, NULL);
}
int
luaA_default_newindex(lua_State *L)
{
return luaA_class_newindex_miss_property(L, NULL);
}
// vim: filetype=c:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| petoju/awesome | luaa.c | C | gpl-2.0 | 37,086 |
/* This file is part of the KDE project
Copyright (C) 2001 David Faure <faure@kde.org>
Copyright 2003 Nicolas GOUTTE <goutte@kde.org>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public License
along with this library; see the file COPYING.LIB. If not, write to
the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "KoGlobal.h"
#include <KoConfig.h>
#include <QPaintDevice>
#include <QFont>
#include <QFontInfo>
#ifdef Q_WS_X11
#include <QX11Info>
#endif
#include <kdebug.h>
#include <kconfiggroup.h>
#include <kglobalsettings.h>
#include <kglobal.h>
#include <klocale.h>
#include <kconfig.h>
#include <kstandarddirs.h>
KoGlobal* KoGlobal::self()
{
K_GLOBAL_STATIC(KoGlobal, s_instance)
return s_instance;
}
KoGlobal::KoGlobal()
: m_pointSize(-1), m_calligraConfig(0)
{
if (KGlobal::locale()) {
// Install the libcalligra* translations
KGlobal::locale()->insertCatalog("calligra");
}
// When running unittests, there is not necessarily a main component
if (KGlobal::hasMainComponent()) {
// Tell KStandardDirs about the calligra prefix
KGlobal::dirs()->addPrefix(CALLIGRAPREFIX);
}
// Add calligra styles dir
KGlobal::dirs()->addResourceType("styles", "data", "calligra/styles/");
}
KoGlobal::~KoGlobal()
{
delete m_calligraConfig;
}
QFont KoGlobal::_defaultFont()
{
QFont font = KGlobalSettings::generalFont();
// we have to use QFontInfo, in case the font was specified with a pixel size
if (font.pointSize() == -1) {
// cache size into m_pointSize, since QFontInfo loads the font -> slow
if (m_pointSize == -1)
m_pointSize = QFontInfo(font).pointSize();
Q_ASSERT(m_pointSize != -1);
font.setPointSize(m_pointSize);
}
//kDebug( 30003 )<<"QFontInfo(font).pointSize() :"<<QFontInfo(font).pointSize();
//kDebug( 30003 )<<"font.name() :"<<font.family ();
return font;
}
QStringList KoGlobal::_listOfLanguageTags()
{
if (m_langMap.isEmpty())
createListOfLanguages();
return m_langMap.values();
}
QStringList KoGlobal::_listOfLanguages()
{
if (m_langMap.empty())
createListOfLanguages();
return m_langMap.keys();
}
void KoGlobal::createListOfLanguages()
{
KConfig config("all_languages", KConfig::NoGlobals, "locale");
// Note that we could also use KLocale::allLanguagesTwoAlpha
QMap<QString, bool> seenLanguages;
const QStringList langlist = config.groupList();
for (QStringList::ConstIterator itall = langlist.begin();
itall != langlist.end(); ++itall) {
const QString tag = *itall;
const QString name = config.group(tag).readEntry("Name", tag);
// e.g. name is "French" and tag is "fr"
// The QMap does the sorting on the display-name, so that
// comboboxes are sorted.
m_langMap.insert(name, tag);
seenLanguages.insert(tag, true);
}
// Also take a look at the installed translations.
// Many of them are already in all_languages but all_languages doesn't
// currently have en_GB or en_US etc.
const QStringList translationList = KGlobal::dirs()->findAllResources("locale",
QString::fromLatin1("*/entry.desktop"));
for (QStringList::ConstIterator it = translationList.begin();
it != translationList.end(); ++it) {
// Extract the language tag from the directory name
QString tag = *it;
int index = tag.lastIndexOf('/');
tag = tag.left(index);
index = tag.lastIndexOf('/');
tag = tag.mid(index + 1);
if (seenLanguages.find(tag) == seenLanguages.end()) {
KConfig entry(*it, KConfig::SimpleConfig);
const QString name = entry.group("KCM Locale").readEntry("Name", tag);
// e.g. name is "US English" and tag is "en_US"
m_langMap.insert(name, tag);
// enable this if writing a third way of finding languages below
//seenLanguages.insert( tag, true );
}
}
// #### We also might not have an entry for a language where spellchecking is supported,
// but no KDE translation is available, like fr_CA.
// How to add them?
}
QString KoGlobal::tagOfLanguage(const QString & _lang)
{
const LanguageMap& map = self()->m_langMap;
QMap<QString, QString>::ConstIterator it = map.find(_lang);
if (it != map.end())
return *it;
return QString();
}
QString KoGlobal::languageFromTag(const QString &langTag)
{
const LanguageMap& map = self()->m_langMap;
QMap<QString, QString>::ConstIterator it = map.begin();
const QMap<QString, QString>::ConstIterator end = map.end();
for (; it != end; ++it)
if (it.value() == langTag)
return it.key();
// Language code not found. Better return the code (tag) than nothing.
return langTag;
}
KConfig* KoGlobal::_calligraConfig()
{
if (!m_calligraConfig) {
m_calligraConfig = new KConfig("calligrarc");
}
return m_calligraConfig;
}
| ddelemeny/calligra | libs/main/KoGlobal.cpp | C++ | gpl-2.0 | 5,670 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using Workflow.DBUtility;
namespace Workflow.DAL
{
/// <summary>
/// 数据访问类:Sys_Code_MstrDAL
/// </summary>
public partial class Sys_Code_MstrDAL
{
public Sys_Code_MstrDAL()
{ }
#region BasicMethod
/// <summary>
/// 是否存在该记录
/// </summary>
public bool Exists(string code_cmmt, string code_desc, string code_fldname, string code_user1, string code_user2, string code_value)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from Sys_Code_Mstr");
strSql.Append(" where code_cmmt=@code_cmmt and code_desc=@code_desc and code_fldname=@code_fldname and code_user1=@code_user1 and code_user2=@code_user2 and code_value=@code_value ");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_desc", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200),
new SqlParameter("@code_user1", SqlDbType.NVarChar,200),
new SqlParameter("@code_user2", SqlDbType.NVarChar,200),
new SqlParameter("@code_value", SqlDbType.NVarChar,200) };
parameters[0].Value = code_cmmt;
parameters[1].Value = code_desc;
parameters[2].Value = code_fldname;
parameters[3].Value = code_user1;
parameters[4].Value = code_user2;
parameters[5].Value = code_value;
return DbHelperSQL.Exists(strSql.ToString(), parameters);
}
public bool Exists(string code_cmmt,string code_fldname)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) from Sys_Code_Mstr");
strSql.Append(" where code_cmmt=@code_cmmt and code_fldname=@code_fldname ");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200) };
parameters[0].Value = code_cmmt;
parameters[1].Value = code_fldname;
return DbHelperSQL.Exists(strSql.ToString(), parameters);
}
/// <summary>
/// 增加一条数据
/// </summary>
public bool Add(Workflow.Model.Sys_Code_Mstr_Model model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("insert into Sys_Code_Mstr(");
strSql.Append("code_cmmt,code_desc,code_fldname,code_user1,code_user2,code_value)");
strSql.Append(" values (");
strSql.Append("@code_cmmt,@code_desc,@code_fldname,@code_user1,@code_user2,@code_value)");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_desc", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200),
new SqlParameter("@code_user1", SqlDbType.NVarChar,200),
new SqlParameter("@code_user2", SqlDbType.NVarChar,200),
new SqlParameter("@code_value", SqlDbType.NVarChar,200)};
parameters[0].Value = model.code_cmmt;
parameters[1].Value = model.code_desc;
parameters[2].Value = model.code_fldname;
parameters[3].Value = model.code_user1;
parameters[4].Value = model.code_user2;
parameters[5].Value = model.code_value;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 更新一条数据
/// </summary>
public bool Update(Workflow.Model.Sys_Code_Mstr_Model model)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("update Sys_Code_Mstr set ");
strSql.Append("code_cmmt=@code_cmmt,");
strSql.Append("code_desc=@code_desc,");
strSql.Append("code_fldname=@code_fldname,");
strSql.Append("code_user1=@code_user1,");
strSql.Append("code_user2=@code_user2,");
strSql.Append("code_value=@code_value");
strSql.Append(" where code_cmmt=@code_cmmt and code_desc=@code_desc and code_fldname=@code_fldname and code_user1=@code_user1 and code_user2=@code_user2 and code_value=@code_value ");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_desc", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200),
new SqlParameter("@code_user1", SqlDbType.NVarChar,200),
new SqlParameter("@code_user2", SqlDbType.NVarChar,200),
new SqlParameter("@code_value", SqlDbType.NVarChar,200)};
parameters[0].Value = model.code_cmmt;
parameters[1].Value = model.code_desc;
parameters[2].Value = model.code_fldname;
parameters[3].Value = model.code_user1;
parameters[4].Value = model.code_user2;
parameters[5].Value = model.code_value;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 删除一条数据
/// </summary>
public bool Delete(string code_cmmt, string code_desc, string code_fldname, string code_user1, string code_user2, string code_value)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("delete from Sys_Code_Mstr ");
strSql.Append(" where code_cmmt=@code_cmmt and code_desc=@code_desc and code_fldname=@code_fldname and code_user1=@code_user1 and code_user2=@code_user2 and code_value=@code_value ");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_desc", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200),
new SqlParameter("@code_user1", SqlDbType.NVarChar,200),
new SqlParameter("@code_user2", SqlDbType.NVarChar,200),
new SqlParameter("@code_value", SqlDbType.NVarChar,200) };
parameters[0].Value = code_cmmt;
parameters[1].Value = code_desc;
parameters[2].Value = code_fldname;
parameters[3].Value = code_user1;
parameters[4].Value = code_user2;
parameters[5].Value = code_value;
int rows = DbHelperSQL.ExecuteSql(strSql.ToString(), parameters);
if (rows > 0)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public Workflow.Model.Sys_Code_Mstr_Model GetModel(string code_cmmt, string code_desc, string code_fldname, string code_user1, string code_user2, string code_value)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 code_cmmt,code_desc,code_fldname,code_user1,code_user2,code_value from Sys_Code_Mstr ");
strSql.Append(" where code_cmmt=@code_cmmt and code_desc=@code_desc and code_fldname=@code_fldname and code_user1=@code_user1 and code_user2=@code_user2 and code_value=@code_value ");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_desc", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200),
new SqlParameter("@code_user1", SqlDbType.NVarChar,200),
new SqlParameter("@code_user2", SqlDbType.NVarChar,200),
new SqlParameter("@code_value", SqlDbType.NVarChar,200) };
parameters[0].Value = code_cmmt;
parameters[1].Value = code_desc;
parameters[2].Value = code_fldname;
parameters[3].Value = code_user1;
parameters[4].Value = code_user2;
parameters[5].Value = code_value;
Workflow.Model.Sys_Code_Mstr_Model model = new Workflow.Model.Sys_Code_Mstr_Model();
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
public Workflow.Model.Sys_Code_Mstr_Model GetModel(string code_cmmt, string code_fldname)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select top 1 code_cmmt,code_desc,code_fldname,code_user1,code_user2,code_value from Sys_Code_Mstr ");
strSql.Append(" where code_cmmt=@code_cmmt and code_fldname=@code_fldname ");
SqlParameter[] parameters = {
new SqlParameter("@code_cmmt", SqlDbType.NVarChar,200),
new SqlParameter("@code_fldname", SqlDbType.NVarChar,200) };
parameters[0].Value = code_cmmt;
parameters[1].Value = code_fldname;
Workflow.Model.Sys_Code_Mstr_Model model = new Workflow.Model.Sys_Code_Mstr_Model();
DataSet ds = DbHelperSQL.Query(strSql.ToString(), parameters);
if (ds.Tables[0].Rows.Count > 0)
{
return DataRowToModel(ds.Tables[0].Rows[0]);
}
else
{
return null;
}
}
/// <summary>
/// 得到一个对象实体
/// </summary>
public Workflow.Model.Sys_Code_Mstr_Model DataRowToModel(DataRow row)
{
Workflow.Model.Sys_Code_Mstr_Model model = new Workflow.Model.Sys_Code_Mstr_Model();
if (row != null)
{
if (row["code_cmmt"] != null)
{
model.code_cmmt = row["code_cmmt"].ToString();
}
if (row["code_desc"] != null)
{
model.code_desc = row["code_desc"].ToString();
}
if (row["code_fldname"] != null)
{
model.code_fldname = row["code_fldname"].ToString();
}
if (row["code_user1"] != null)
{
model.code_user1 = row["code_user1"].ToString();
}
if (row["code_user2"] != null)
{
model.code_user2 = row["code_user2"].ToString();
}
if (row["code_value"] != null)
{
model.code_value = row["code_value"].ToString();
}
}
return model;
}
/// <summary>
/// 获得数据列表
/// </summary>
public DataSet GetList(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select code_cmmt,code_desc,code_fldname,code_user1,code_user2,code_value ");
strSql.Append(" FROM Sys_Code_Mstr ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获得前几行数据
/// </summary>
public DataSet GetList(int Top, string strWhere, string filedOrder)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select ");
if (Top > 0)
{
strSql.Append(" top " + Top.ToString());
}
strSql.Append(" code_cmmt,code_desc,code_fldname,code_user1,code_user2,code_value ");
strSql.Append(" FROM Sys_Code_Mstr ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
strSql.Append(" order by " + filedOrder);
return DbHelperSQL.Query(strSql.ToString());
}
/// <summary>
/// 获取记录总数
/// </summary>
public int GetRecordCount(string strWhere)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("select count(1) FROM Sys_Code_Mstr ");
if (strWhere.Trim() != "")
{
strSql.Append(" where " + strWhere);
}
object obj = DbHelperSQL.GetSingle(strSql.ToString());
if (obj == null)
{
return 0;
}
else
{
return Convert.ToInt32(obj);
}
}
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetListByPage(string strWhere, string orderby, int startIndex, int endIndex)
{
StringBuilder strSql = new StringBuilder();
strSql.Append("SELECT * FROM ( ");
strSql.Append(" SELECT ROW_NUMBER() OVER (");
if (!string.IsNullOrEmpty(orderby.Trim()))
{
strSql.Append("order by T." + orderby);
}
else
{
strSql.Append("order by T.code_value desc");
}
strSql.Append(")AS Row, T.* from Sys_Code_Mstr T ");
if (!string.IsNullOrEmpty(strWhere.Trim()))
{
strSql.Append(" WHERE " + strWhere);
}
strSql.Append(" ) TT");
strSql.AppendFormat(" WHERE TT.Row between {0} and {1}", startIndex, endIndex);
return DbHelperSQL.Query(strSql.ToString());
}
/*
/// <summary>
/// 分页获取数据列表
/// </summary>
public DataSet GetList(int PageSize,int PageIndex,string strWhere)
{
SqlParameter[] parameters = {
new SqlParameter("@Name", SqlDbType.VarChar, 255),
new SqlParameter("@fldName", SqlDbType.VarChar, 255),
new SqlParameter("@PageSize", SqlDbType.Int),
new SqlParameter("@PageIndex", SqlDbType.Int),
new SqlParameter("@IsReCount", SqlDbType.Bit),
new SqlParameter("@OrderType", SqlDbType.Bit),
new SqlParameter("@strWhere", SqlDbType.VarChar,1000),
};
parameters[0].Value = "Sys_Code_Mstr";
parameters[1].Value = "code_value";
parameters[2].Value = PageSize;
parameters[3].Value = PageIndex;
parameters[4].Value = 0;
parameters[5].Value = 0;
parameters[6].Value = strWhere;
return DbHelperSQL.RunProcedure("UP_GetRecordByPage",parameters,"ds");
}*/
#endregion BasicMethod
#region ExtensionMethod
#endregion ExtensionMethod
}
}
| xlgwr/wf | Workflow.DAL/Sys_Code_MstrDAL.cs | C# | gpl-2.0 | 15,272 |
// --------------------------------------------------------------------------
//
// Macro for reconstruction of simulated events with standard settings
//
// HitProducers in (MVD, RICH, TRD, TOF, ECAL,) PSD (detector in brackets not included by default)
// Digitizer and HitFinder in STS
// FAST MC for ECAL
// STS track finding and fitting (L1 / KF)
// TRD track finding and fitting (L1 / KF)
// RICH ring finding (ideal) and fitting
// Global track finding (ideal), rich assignment
// Primary vertex finding (ideal)
// Matching of reconstructed and MC tracks in STS, RICH and TRD
//
// V. Friese 24/02/2006
// Version 24/04/2007 (V. Friese)
// Version 22/10/2014 (Selim)
// --------------------------------------------------------------------------
void run_reco_flow(Double_t En=10, Int_t nEvents = 2, Int_t fileNum = 5)
{
Int_t gen = 0;
TString sGen = "";
if (gen == 0) sGen = "urqmd";
if (gen == 1) sGen = "shield";
TString numEvt = "";
if(nEvents<10) numEvt="000";
if(nEvents>=10 && nEvents<100) numEvt="00";
if(nEvents>=100 && nEvents<1000) numEvt="0";
if(nEvents>=1000 && nEvents<10000) numEvt="";
numEvt += nEvents;
TString sEn = "";
sEn += En;
TString sfileNum = "";
if(fileNum<10) sfileNum="000";
if(fileNum>=10 && fileNum<100) sfileNum="00";
if(fileNum>=100 && fileNum<1000) sfileNum="0";
if(fileNum>=1000 && fileNum<10000) sfileNum="";
sfileNum += fileNum;
// ========================================================================
// Adjust this part according to your requirements
// Verbosity level (0=quiet, 1=event level, 2=track level, 3=debug)
Int_t iVerbose = 0;
TString dir = "/hera/cbm/users/sseddiki/test/";
TString inFile = dir + "sim/mc_" + numEvt + "evt_" + sfileNum + ".root";
TString parFile = dir + "sim/params_" + numEvt + "evt_" + sfileNum + ".root";
TString outFile = dir + "reco/reco_" + numEvt + "evt_" + sfileNum + ".root";
// Digitisation files.
// Add TObjectString containing the different file names to
// a TList which is passed as input to the FairParAsciiFileIo.
// The FairParAsciiFileIo will take care to create on the fly
// a concatenated input parameter file which is then used during
// the reconstruction.
TList *parFileList = new TList();
TString workDir = gSystem->Getenv("VMCWORKDIR");
TString paramDir = workDir + "/parameters";
TObjString stsDigiFile = paramDir + "/sts/sts_v13d_std.digi.par";
parFileList->Add(&stsDigiFile);
TString stsMatBudgetFileName = paramDir + "/sts/sts_matbudget_v13d.root";
cout << "STS MB : " << stsMatBudgetFileName << endl;
//TObjString trdDigiFile = paramDir + "/trd/trd_v13o.digi.par";
//parFileList->Add(&trdDigiFile);
//TObjString tofDigiFile = paramDir + "/tof/tof_v13b.digi.par";
//parFileList->Add(&tofDigiFile);
// In general, the following parts need not be touched
// ========================================================================
// ---- Debug option -------------------------------------------------
gDebug = 0;
// ------------------------------------------------------------------------
// ----- Timer --------------------------------------------------------
TStopwatch timer;
timer.Start();
// ------------------------------------------------------------------------
// ---- Load libraries -------------------------------------------------
gROOT->LoadMacro("$VMCWORKDIR/gconfig/basiclibs.C");
basiclibs();
gSystem->Load("libGeoBase");
gSystem->Load("libParBase");
gSystem->Load("libBase");
gSystem->Load("libCbmBase");
gSystem->Load("libCbmData");
gSystem->Load("libField");
gSystem->Load("libGen");
gSystem->Load("libPassive");
gSystem->Load("libEcal");
gSystem->Load("libKF");
gSystem->Load("libMvd");
gSystem->Load("libSts");
gSystem->Load("libLittrack");
gSystem->Load("libRich");
gSystem->Load("libTrd");
gSystem->Load("libTof");
gSystem->Load("libGlobal");
gSystem->Load("libL1");
gSystem->Load("libMinuit2"); // Nedded for rich ellipse fitter
gSystem->Load("libPsd");
// ------------------------------------------------------------------------
// ----- Reconstruction run -------------------------------------------
FairRunAna *run = new FairRunAna();
run->SetInputFile(inFile);
run->SetOutputFile(outFile);
// ------------------------------------------------------------------------
// =========================================================================
// === Detector Response Simulation (Digitiser) ===
// === (where available) ===
// =========================================================================
// ----- MVD Digitiser -------------------------------------------------
CbmMvdDigitizeL* mvdDigi =
new CbmMvdDigitizeL("MVD Digitiser", 0, iVerbose);
//run->AddTask(mvdDigi);
// -------------------------------------------------------------------------
// ----- STS digitizer -------------------------------------------------
Double_t threshold = 4;
Double_t noiseWidth = 0.01;
Int_t nofBits = 12;
Double_t electronsPerAdc = 10;
Double_t StripDeadTime = 0.1;
CbmStsDigitize* stsDigitize = new CbmStsDigitize();
stsDigitize->SetRealisticResponse();
stsDigitize->SetFrontThreshold (threshold);
stsDigitize->SetBackThreshold (threshold);
stsDigitize->SetFrontNoiseWidth(noiseWidth);
stsDigitize->SetBackNoiseWidth (noiseWidth);
stsDigitize->SetFrontNofBits (nofBits);
stsDigitize->SetBackNofBits (nofBits);
stsDigitize->SetFrontNofElPerAdc(electronsPerAdc);
stsDigitize->SetBackNofElPerAdc(electronsPerAdc);
stsDigitize->SetStripDeadTime (StripDeadTime);
run->AddTask(stsDigitize);
// -------------------------------------------------------------------------
// =========================================================================
// === MVD local reconstruction ===
// =========================================================================
// ----- MVD Hit Finder ------------------------------------------------
CbmMvdFindHits* mvdHitFinder = new CbmMvdFindHits("MVD Hit Finder", 0,
iVerbose);
//run->AddTask(mvdHitFinder);
// -------------------------------------------------------------------------
// === End of MVD local reconstruction ===
// =========================================================================
// =========================================================================
// === STS local reconstruction ===
// =========================================================================
// ----- STS Cluster Finder --------------------------------------------
FairTask* stsClusterFinder = new CbmStsClusterFinder();
run->AddTask(stsClusterFinder);
// -------------------------------------------------------------------------
// ----- STS hit finder ------------------------------------------------
FairTask* stsFindHits = new CbmStsFindHits();
run->AddTask(stsFindHits);
// -------------------------------------------------------------------------
// ----- STS hit matching -----------------------------------------------
FairTask* stsMatchHits = new CbmStsMatchHits();
run->AddTask(stsMatchHits);
// -------------------------------------------------------------------------
// --- STS track finding ------------------------------------------------
CbmKF* kalman = new CbmKF();
run->AddTask(kalman);
CbmL1* l1 = new CbmL1();
l1->SetMaterialBudgetFileName(stsMatBudgetFileName);
run->AddTask(l1);
CbmStsTrackFinder* stsTrackFinder = new CbmL1StsTrackFinder();
FairTask* stsFindTracks = new CbmStsFindTracks(iVerbose, stsTrackFinder);
run->AddTask(stsFindTracks);
// -------------------------------------------------------------------------
// --- STS track matching ----------------------------------------------
FairTask* stsMatchTracks = new CbmStsMatchTracks(iVerbose);
run->AddTask(stsMatchTracks);
// -------------------------------------------------------------------------
// --- STS track fitting -----------------------------------------------
CbmStsTrackFitter* stsTrackFitter = new CbmStsKFTrackFitter();
FairTask* stsFitTracks = new CbmStsFitTracks(stsTrackFitter, iVerbose);
run->AddTask(stsFitTracks);
// -------------------------------------------------------------------------
// === End of STS local reconstruction ===
// =========================================================================
// =========================================================================
// === TRD local reconstruction ===
// =========================================================================
// Update of the values for the radiator F.U. 17.08.07
Int_t trdNFoils = 130; // number of polyetylene foils
Float_t trdDFoils = 0.0013; // thickness of 1 foil [cm]
Float_t trdDGap = 0.02; // thickness of gap between foils [cm]
Bool_t simpleTR = kTRUE; // use fast and simple version for TR
// production
CbmTrdRadiator *radiator = new CbmTrdRadiator(simpleTR, trdNFoils,
trdDFoils, trdDGap);
CbmTrdHitProducerSmearing* trdHitProd = new CbmTrdHitProducerSmearing(radiator);
//run->AddTask(trdHitProd);
// -------------------------------------------------------------------------
// === End of TRD local reconstruction ===
// =========================================================================
// =========================================================================
// === TOF local reconstruction ===
// =========================================================================
// ------ TOF hit producer ---------------------------------------------
CbmTofHitProducerNew* tofHitProd = new CbmTofHitProducerNew("TOF HitProducerNew",iVerbose);
tofHitProd->SetInitFromAscii(kFALSE);
//run->AddTask(tofHitProd);
// -------------------------------------------------------------------------
// === End of TOF local reconstruction ===
// =========================================================================
// =========================================================================
// === Global tracking ===
// =========================================================================
CbmLitFindGlobalTracks* finder = new CbmLitFindGlobalTracks();
// Tracking method to be used
// "branch" - branching tracking
// "nn" - nearest neighbor tracking
// "weight" - weighting tracking
finder->SetTrackingType("branch");
// Hit-to-track merger method to be used
// "nearest_hit" - assigns nearest hit to the track
finder->SetMergerType("nearest_hit");
//run->AddTask(finder);
// ----- Primary vertex finding ---------------------------------------
CbmPrimaryVertexFinder* pvFinder = new CbmPVFinderKF();
CbmFindPrimaryVertex* findVertex = new CbmFindPrimaryVertex(pvFinder);
run->AddTask(findVertex);
// ------------------------------------------------------------------------
// === End of global tracking ===
// =========================================================================
// ----- TRD track matching --------------------------------------------
//CbmTrdMatchTracks* trdMatchTracks = new CbmTrdMatchTracks(iVerbose);
//run->AddTask(trdMatchTracks);
// ----------------------------------------------------
// ----------- TRD track Pid Wkn ----------------------
//CbmTrdSetTracksPidWkn* trdSetTracksPidTask = new CbmTrdSetTracksPidWkn( "trdFindTracks", "trdFindTracks");
//run->AddTask(trdSetTracksPidTask);
// ----------------------------------------------------
// ----------- TRD track Pid Ann ----------------------
//CbmTrdSetTracksPidANN* trdSetTracksPidAnnTask = new CbmTrdSetTracksPidANN( "Ann", "Ann");
//run->AddTask(trdSetTracksPidAnnTask);
// ----------------------------------------------------
// ----------- TRD track Pid Like ----------------------
// Since in the newest version of this method depends on the global
// track the task has to move after the global tracking
// FU 08.02.12 Switch the task off since the input file needed for the new geometry has to be generated first.
// CbmTrdSetTracksPidLike* trdSetTracksPidLikeTask =
// new CbmTrdSetTracksPidLike("Likelihood", "Likelihood");
// run->AddTask(trdSetTracksPidLikeTask);
// ----------------------------------------------------
// =========================================================================
// === RICH reconstruction ===
// =========================================================================
// ---------------------RICH Hit Producer ----------------------------------
CbmRichHitProducer* richHitProd = new CbmRichHitProducer();
richHitProd->SetDetectorType(4);
richHitProd->SetNofNoiseHits(220);
richHitProd->SetCollectionEfficiency(1.0);
richHitProd->SetSigmaMirror(0.06);
//run->AddTask(richHitProd);
//--------------------------------------------------------------------------
//--------------------- RICH Reconstruction ----------------------------------
CbmRichReconstruction* richReco = new CbmRichReconstruction();
//run->AddTask(richReco);
// ------------------- RICH Ring matching ---------------------------------
CbmRichMatchRings* matchRings = new CbmRichMatchRings();
//run->AddTask(matchRings);
// -------------------------------------------------------------------------
// === End of RICH local reconstruction ===
// =========================================================================
/*
// =========================================================================
// === ECAL reconstruction ===
// =========================================================================
// ----- ECAL hit producer ----------------------------------------------
CbmEcalHitProducerFastMC* ecalHitProd = new CbmEcalHitProducerFastMC(
"ECAL Hitproducer");
run->AddTask(ecalHitProd);
// -------------------------------------------------------------------------
// === End of ECAL reconstruction ===
// =========================================================================
*/
// =========================================================================
// === PSD reconstruction ===
// =========================================================================
// ----- PSD hit producer ----------------------------------------------
CbmPsdIdealDigitizer* psdDigi = new CbmPsdIdealDigitizer();
run->AddTask(psdDigi);
CbmPsdHitProducer* psdHit = new CbmPsdHitProducer();
run->AddTask(psdHit);
// ------ KF particle finder
/*
float cuts[2][3] = {{3.,3..-100.},{3.,3.,-100.}};
CbmKFParticlesFinder* kfPartFinder = new CbmKFParticlesFinder(cuts,1);
run->AddTask(kfPartFinder);
CbmKFParticlesFinderQA* kfPartFinderQA = new CbmKFParticlesFinderQA(kfPartFinder,1,3);
kfPartFinderQA->SaveParticles(1);
kfPartFinderQA->SaveMCParticles(1);
run->AddTask(kfPartFinderQA);
*/
// ----- Parameter database --------------------------------------------
FairRuntimeDb* rtdb = run->GetRuntimeDb();
FairParRootFileIo* parIo1 = new FairParRootFileIo();
FairParAsciiFileIo* parIo2 = new FairParAsciiFileIo();
parIo1->open(parFile.Data());
parIo2->open(parFileList, "in");
rtdb->setFirstInput(parIo1);
rtdb->setSecondInput(parIo2);
rtdb->setOutput(parIo1);
rtdb->saveOutput();
// ------------------------------------------------------------------------
// ----- Intialise and run --------------------------------------------
run->Init();
cout << "Starting run" << endl;
run->Run(0, nEvents);
// ------------------------------------------------------------------------
// ----- Finish -------------------------------------------------------
timer.Stop();
Double_t rtime = timer.RealTime();
Double_t ctime = timer.CpuTime();
cout << endl << endl;
cout << "Macro finished succesfully." << endl;
cout << "Output file is " << outFile << endl;
cout << "Parameter file is " << parFile << endl;
cout << "Real time " << rtime << " s, CPU time " << ctime << " s" << endl;
cout << endl;
// ------------------------------------------------------------------------
// delete run;
cout << " Test passed" << endl;
cout << " All ok " << endl;
}
| desdemonda/cbmroot | macro/analysis/flow/run_reco_flow.C | C++ | gpl-2.0 | 17,117 |
<?php
/*
Simple:Press
Admin Components Display Rendering
$LastChangedDate: 2012-11-18 10:04:10 -0800 (Sun, 18 Nov 2012) $
$Rev: 9312 $
*/
if (preg_match('#'.basename(__FILE__).'#', $_SERVER['PHP_SELF'])) die('Access denied - you cannot directly call this file');
function spa_render_components_panel($formid) {
?>
<div class="clearboth"></div>
<div class="wrap sfatag">
<?php
spa_render_sidemenu();
?>
<div id='sfmsgspot'></div>
<div id="sfmaincontainer">
<?php spa_render_components_container($formid); ?>
</div>
<div class="clearboth"></div>
</div>
<?php
}
function spa_render_components_container($formid) {
switch ($formid) {
case 'smileys':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-smileys-form.php');
spa_components_smileys_form();
break;
case 'login':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-login-form.php');
spa_components_login_form();
break;
case 'seo':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-seo-form.php');
spa_components_seo_form();
break;
case 'forumranks':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-forumranks-form.php');
spa_components_forumranks_form();
break;
case 'addmembers':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-special-ranks-add-form.php');
spa_components_sr_add_members_form($_GET['id']);
break;
case 'delmembers':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-special-ranks-del-form.php');
spa_components_sr_del_members_form($_GET['id']);
break;
case 'messages':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-messages-form.php');
spa_components_messages_form();
break;
case 'policies':
include_once(SF_PLUGIN_DIR.'/admin/panel-components/forms/spa-components-policies-form.php');
spa_components_policies_form();
break;
# leave this for plugins to add to this panel
case 'plugin':
include_once(SF_PLUGIN_DIR.'/admin/panel-plugins/forms/spa-plugins-user-form.php');
$admin = (isset($_GET['admin'])) ? sp_esc_str($_GET['admin']) : '';
$save = (isset($_GET['save'])) ? sp_esc_str($_GET['save']) : '';
$form = (isset($_GET['form'])) ? sp_esc_int($_GET['form']) : '';
$reload = (isset($_GET['reload'])) ? sp_esc_str($_GET['reload']) : '';
spa_plugins_user_form($admin, $save, $form, $reload);
break;
}
}
?> | AARCprofessionals/obrs | wp-content/plugins/simple-press/admin/panel-components/spa-components-display.php | PHP | gpl-2.0 | 2,537 |
/***************************************************************************
qgsconfigcache.cpp
------------------
begin : July 24th, 2010
copyright : (C) 2010 by Marco Hugentobler
email : marco dot hugentobler at sourcepole dot ch
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
#include "qgsconfigcache.h"
#include "qgsmessagelog.h"
#include "qgsserverexception.h"
#include "qgsstorebadlayerinfo.h"
#include "qgsserverprojectutils.h"
#include <QFile>
QgsConfigCache *QgsConfigCache::instance()
{
static QgsConfigCache *sInstance = nullptr;
if ( !sInstance )
sInstance = new QgsConfigCache();
return sInstance;
}
QgsConfigCache::QgsConfigCache()
{
QObject::connect( &mFileSystemWatcher, &QFileSystemWatcher::fileChanged, this, &QgsConfigCache::removeChangedEntry );
}
const QgsProject *QgsConfigCache::project( const QString &path, QgsServerSettings *settings )
{
if ( ! mProjectCache[ path ] )
{
std::unique_ptr<QgsProject> prj( new QgsProject() );
QgsStoreBadLayerInfo *badLayerHandler = new QgsStoreBadLayerInfo();
prj->setBadLayerHandler( badLayerHandler );
QgsProject::ReadFlags readFlags = QgsProject::ReadFlag();
if ( settings )
{
// Activate trust layer metadata flag
if ( settings->trustLayerMetadata() )
{
readFlags |= QgsProject::ReadFlag::FlagTrustLayerMetadata;
}
// Activate don't load layouts flag
if ( settings->getPrintDisabled() )
{
readFlags |= QgsProject::ReadFlag::FlagDontLoadLayouts;
}
}
if ( prj->read( path, readFlags ) )
{
if ( !badLayerHandler->badLayers().isEmpty() )
{
// if bad layers are not restricted layers so service failed
QStringList unrestrictedBadLayers;
// test bad layers through restrictedlayers
const QStringList badLayerIds = badLayerHandler->badLayers();
const QMap<QString, QString> badLayerNames = badLayerHandler->badLayerNames();
const QStringList resctrictedLayers = QgsServerProjectUtils::wmsRestrictedLayers( *prj );
for ( const QString &badLayerId : badLayerIds )
{
// if this bad layer is in restricted layers
// it doesn't need to be added to unrestricted bad layers
if ( badLayerNames.contains( badLayerId ) &&
resctrictedLayers.contains( badLayerNames.value( badLayerId ) ) )
{
continue;
}
unrestrictedBadLayers.append( badLayerId );
}
if ( !unrestrictedBadLayers.isEmpty() )
{
// This is a critical error unless QGIS_SERVER_IGNORE_BAD_LAYERS is set to TRUE
if ( ! settings || ! settings->ignoreBadLayers() )
{
QgsMessageLog::logMessage(
QStringLiteral( "Error, Layer(s) %1 not valid in project %2" ).arg( unrestrictedBadLayers.join( QLatin1String( ", " ) ), path ),
QStringLiteral( "Server" ), Qgis::Critical );
throw QgsServerException( QStringLiteral( "Layer(s) not valid" ) );
}
else
{
QgsMessageLog::logMessage(
QStringLiteral( "Warning, Layer(s) %1 not valid in project %2" ).arg( unrestrictedBadLayers.join( QLatin1String( ", " ) ), path ),
QStringLiteral( "Server" ), Qgis::Warning );
}
}
}
mProjectCache.insert( path, prj.release() );
mFileSystemWatcher.addPath( path );
}
else
{
QgsMessageLog::logMessage(
QStringLiteral( "Error when loading project file '%1': %2 " ).arg( path, prj->error() ),
QStringLiteral( "Server" ), Qgis::Critical );
}
}
return mProjectCache[ path ];
}
QDomDocument *QgsConfigCache::xmlDocument( const QString &filePath )
{
//first open file
QFile configFile( filePath );
if ( !configFile.exists() )
{
QgsMessageLog::logMessage( "Error, configuration file '" + filePath + "' does not exist", QStringLiteral( "Server" ), Qgis::Critical );
return nullptr;
}
if ( !configFile.open( QIODevice::ReadOnly ) )
{
QgsMessageLog::logMessage( "Error, cannot open configuration file '" + filePath + "'", QStringLiteral( "Server" ), Qgis::Critical );
return nullptr;
}
// first get cache
QDomDocument *xmlDoc = mXmlDocumentCache.object( filePath );
if ( !xmlDoc )
{
//then create xml document
xmlDoc = new QDomDocument();
QString errorMsg;
int line, column;
if ( !xmlDoc->setContent( &configFile, true, &errorMsg, &line, &column ) )
{
QgsMessageLog::logMessage( "Error parsing file '" + filePath +
QStringLiteral( "': parse error %1 at row %2, column %3" ).arg( errorMsg ).arg( line ).arg( column ), QStringLiteral( "Server" ), Qgis::Critical );
delete xmlDoc;
return nullptr;
}
mXmlDocumentCache.insert( filePath, xmlDoc );
mFileSystemWatcher.addPath( filePath );
xmlDoc = mXmlDocumentCache.object( filePath );
Q_ASSERT( xmlDoc );
}
return xmlDoc;
}
void QgsConfigCache::removeChangedEntry( const QString &path )
{
mProjectCache.remove( path );
//xml document must be removed last, as other config cache destructors may require it
mXmlDocumentCache.remove( path );
mFileSystemWatcher.removePath( path );
}
void QgsConfigCache::removeEntry( const QString &path )
{
removeChangedEntry( path );
}
| rldhont/Quantum-GIS | src/server/qgsconfigcache.cpp | C++ | gpl-2.0 | 6,131 |
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Struct template regex_id_filter_predicate</title>
<link rel="stylesheet" href="../../boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.73.2">
<link rel="start" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset">
<link rel="up" href="../../xpressive/reference.html#header.boost.xpressive.match_results_hpp" title="Header <boost/xpressive/match_results.hpp>">
<link rel="prev" href="match_results.html" title="Struct template match_results">
<link rel="next" href="op/push.html" title="Struct push">
</head>
<body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF">
<table cellpadding="2" width="100%"><tr>
<td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td>
<td align="center"><a href="../../../../index.html">Home</a></td>
<td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td>
<td align="center"><a href="http://www.boost.org/users/people.html">People</a></td>
<td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td>
<td align="center"><a href="../../../../more/index.htm">More</a></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="match_results.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../xpressive/reference.html#header.boost.xpressive.match_results_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="op/push.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a>
</div>
<div class="refentry" lang="en">
<a name="boost.xpressive.regex_id_filter_predicate"></a><div class="titlepage"></div>
<div class="refnamediv">
<h2><span class="refentrytitle">Struct template regex_id_filter_predicate</span></h2>
<p>boost::xpressive::regex_id_filter_predicate</p>
</div>
<h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2>
<div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="emphasis"><em>// In header: <<a class="link" href="../../xpressive/reference.html#header.boost.xpressive.match_results_hpp" title="Header <boost/xpressive/match_results.hpp>">boost/xpressive/match_results.hpp</a>>
</em></span><span class="bold"><strong>template</strong></span><<span class="bold"><strong>typename</strong></span> BidiIter>
<span class="bold"><strong>struct</strong></span> <a class="link" href="regex_id_filter_predicate.html" title="Struct template regex_id_filter_predicate">regex_id_filter_predicate</a> {
<span class="emphasis"><em>// <a class="link" href="regex_id_filter_predicate.html#boost.xpressive.regex_id_filter_predicateconstruct-copy-destruct">construct/copy/destruct</a></em></span>
<a class="link" href="regex_id_filter_predicate.html#id3880415-bb">regex_id_filter_predicate</a>(regex_id_type);
<span class="emphasis"><em>// <a class="link" href="regex_id_filter_predicate.html#id3880395-bb">public member functions</a></em></span>
<span class="type"><span class="bold"><strong>bool</strong></span></span> <a class="link" href="regex_id_filter_predicate.html#id3880398-bb"><span class="bold"><strong>operator</strong></span>()</a>(<a class="link" href="match_results.html" title="Struct template match_results">match_results</a>< BidiIter > <span class="bold"><strong>const</strong></span> &) <span class="bold"><strong>const</strong></span>;
};</pre></div>
<div class="refsect1" lang="en">
<a name="id4368276"></a><h2>Description</h2>
<div class="refsect2" lang="en">
<a name="id4368280"></a><h3>
<a name="boost.xpressive.regex_id_filter_predicateconstruct-copy-destruct"></a><code class="computeroutput">regex_id_filter_predicate</code>
public
construct/copy/destruct</h3>
<div class="orderedlist"><ol type="1"><li><pre class="literallayout"><a name="id3880415-bb"></a>regex_id_filter_predicate(regex_id_type regex_id);</pre></li></ol></div>
</div>
<div class="refsect2" lang="en">
<a name="id4368316"></a><h3>
<a name="id3880395-bb"></a><code class="computeroutput">regex_id_filter_predicate</code> public member functions</h3>
<div class="orderedlist"><ol type="1"><li><pre class="literallayout"><span class="type"><span class="bold"><strong>bool</strong></span></span> <a name="id3880398-bb"></a><span class="bold"><strong>operator</strong></span>()(<a class="link" href="match_results.html" title="Struct template match_results">match_results</a>< BidiIter > <span class="bold"><strong>const</strong></span> & res) <span class="bold"><strong>const</strong></span>;</pre></li></ol></div>
</div>
</div>
</div>
<table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr>
<td align="left"></td>
<td align="right"><div class="copyright-footer">Copyright © 2007 Eric Niebler<p>
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>)
</p>
</div></td>
</tr></table>
<hr>
<div class="spirit-nav">
<a accesskey="p" href="match_results.html"><img src="../../../../doc/html/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../xpressive/reference.html#header.boost.xpressive.match_results_hpp"><img src="../../../../doc/html/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/html/images/home.png" alt="Home"></a><a accesskey="n" href="op/push.html"><img src="../../../../doc/html/images/next.png" alt="Next"></a>
</div>
</body>
</html>
| scs/uclinux | lib/boost/boost_1_38_0/doc/html/boost/xpressive/regex_id_filter_predicate.html | HTML | gpl-2.0 | 5,931 |
<?php
/**
* @copyright Copyright (C) eZ Systems AS. All rights reserved.
* @license For full copyright and license information view LICENSE file distributed with this source code.
*/
declare(strict_types=1);
namespace eZ\Publish\API\Repository\Events\Role;
use eZ\Publish\API\Repository\Values\User\RoleCopyStruct;
use eZ\Publish\API\Repository\Values\User\Role;
use eZ\Publish\SPI\Repository\Event\BeforeEvent;
use UnexpectedValueException;
final class BeforeCopyRoleEvent extends BeforeEvent
{
/** @var \eZ\Publish\API\Repository\Values\User\Role */
private $role;
/** @var \eZ\Publish\API\Repository\Values\User\RoleCopyStruct */
private $roleCopyStruct;
/** @var \eZ\Publish\API\Repository\Values\User\Role|null */
private $copiedRole;
public function __construct(Role $role, RoleCopyStruct $roleCopyStruct)
{
$this->role = $role;
$this->roleCopyStruct = $roleCopyStruct;
}
public function getRole(): Role
{
return $this->role;
}
public function getRoleCopyStruct(): RoleCopyStruct
{
return $this->roleCopyStruct;
}
/**
* @throws \eZ\Publish\API\Repository\Exceptions\BadStateException
*/
public function getCopiedRole(): Role
{
if (!$this->hasCopiedRole()) {
throw new UnexpectedValueException(sprintf('Return value is not set or not of type %s. Check hasCopiedRole() or set it using setCopiedRole() before you call the getter.', Role::class));
}
return $this->copiedRole;
}
public function setCopiedRole(?Role $copiedRole): void
{
$this->copiedRole = $copiedRole;
}
public function hasCopiedRole(): bool
{
return $this->copiedRole instanceof Role;
}
}
| gggeek/ezpublish-kernel | eZ/Publish/API/Repository/Events/Role/BeforeCopyRoleEvent.php | PHP | gpl-2.0 | 1,768 |
/* TYPOGRAPHY OPTION 2 */
@font-face {
font-family: 'ChunkFiveRegular';
src: url('fonts/Chunkfive-webfont.eot');
src: local('?'), url('fonts/Chunkfive-webfont.woff') format('woff'), url('fonts/Chunkfive-webfont.ttf') format('truetype'), url('fonts/Chunkfive-webfont.svg#webfontb5K2fJwj') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'CartoGothic';
src: url('fonts/CartoGothicStd-Book-webfont.eot');
src: local('?'), url('fonts/CartoGothicStd-Book-webfont.woff') format('woff'), url('fonts/CartoGothicStd-Book-webfont.ttf') format('truetype'), url('fonts/CartoGothicStd-Book-webfont.svg#webfontiSSvHuvy') format('svg');
font-weight: normal;
font-style: normal;
}
@font-face {
font-family: 'CartoGothic';
src: url('fonts/CartoGothicStd-Italic-webfont.eot');
src: local('?'), url('fonts/CartoGothicStd-Italic-webfont.woff') format('woff'), url('fonts/CartoGothicStd-Italic-webfont.ttf') format('truetype'), url('fonts/CartoGothicStd-Italic-webfont.svg#webfontVz7NhMTG') format('svg');
font-weight: normal;
font-style: italic;
}
@font-face {
font-family: 'CartoGothic';
src: url('fonts/CartoGothicStd-Bold-webfont.eot');
src: local('?'), url('fonts/CartoGothicStd-Bold-webfont.woff') format('woff'), url('fonts/CartoGothicStd-Bold-webfont.ttf') format('truetype'), url('fonts/CartoGothicStd-Bold-webfont.svg#webfontXG7opWym') format('svg');
font-weight: bold;
font-style: normal;
}
/* Elements */
body, td, p, p a, input, span { font-family: 'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif}
strong { font-weight: bold }
a { text-decoration: none }
h1, h2, h3, h4, .logo, #top-nav, #super-header .menu>ul a,#slideshow .video .play-video { font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; font-weight: normal; }
.btn, #main-nav, #header .menu>ul {font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif;}
#main-nav li a, #header .menu>ul li a { line-height: 32px }
#main-nav .active a, #header .menu>ul .active a { line-height: 38px}
#header .menu>ul .sub-menu li a, #main-nav .sub-menu li a {
font-family:'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif;
}
h1 { font-size: 40px;margin-bottom: 30px }
h2 { font-size: 36px; line-height: 1.1 }
h2.updates { font-size: 36px; font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; }
h3 { font-size: 32px }
h4 { font-size: 26px }
h5 { font-size: 18px; font-weight: bold }
h6 { font-size: 16px; font-weight: normal }
.btn { font-size: 18px; letter-spacing: 0 }
#blog-nav a { font-size: 18px }
#homepage-widgets h3 a, #homepage-widgets h3 { font-family:'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; font-size: 24px; letter-spacing: 0 }
#homepage-widgets .widget p { font-size: 14px}
#homepage-widgets .widget .btn { font-size: 14px}
#contact-us .blurb { font-size: 18px; font-family: 'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif; }
#contact-us .contact-us { line-height: 1.3; font-size: 22px; font-family:'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; font-weight: normal }
#contact-us .contact-us em { font-family: 'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif; letter-spacing: 0 }
#sidebar .widget h4, #sidebar .widget h4 a { font-size: 22px; font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; line-height: 30px}
#sidebar .widget, #sidebar .widget p { font-size: 12px; line-height: 1.8}
#sidebar ul li a { font-size: 12px; line-height: 2.3; padding-left: 5px}
/* Specific */
#top-nav, #super-header .menu>ul { font-size: 15px }
#top-nav a, #super-header .menu>ul a {font-family: 'CartoGothic'; font-weight: normal}
.logo { font-size: 34px; font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; line-height: 60px }
#slideshow h2 a { font-size: 30px; font-family:'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; font-weight: normal }
#slideshow p { font-size: 16px; line-height: 1.5 }
#slideshow .btn { line-height: 1.2}
#main-nav a, #header .menu>ul a { font-size: 18px }
#footer p { font-family: 'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif; line-height: 1.8; font-size: 16px}
#footer .widget h3 { font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; font-size: 16px; letter-spacing: 0; margin-bottom: 10px}
#footer .widget, #footer .widget p { font-family: 'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif; font-size: 12px; line-height: 2 }
#blog-nav .btn a {font-family: 'CartoGothic', 'Lucida Grande', Verdana, Tahoma, Arial, sans-serif; font-size: 12px; font-weight: bold }
/* Posts */
.post h3 { font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif; font-size: 28px; line-height: 1.1; margin-top: 5px }
.post .date {font-family: 'ChunkFive', 'ChunkFiveRegular', Georgia, Serif ;line-height: 1.2}
.post-content .info { font-size: 12px }
.post .keep-reading .btn { font-size: 14px; } | 3DayStartup/360DS-frontend | assets/css/typography3.css | CSS | gpl-2.0 | 4,908 |
#include "I2C_Driver.h"
/********************************************************/
void I2C_delay(void)
{
uint8_t i=20;
while(i)
{
i--;
}
}
static void Delay_N_mS(uint16_t n_milisecond) /* n mS delay */
{
uint8_t i;
while (n_milisecond--)
{
i=37;
while (i--);
}
}
bool I2C_Start(void)
{
SDA_H;
SCL_H;
I2C_delay();
if(!SDA_read)
return FALSE; //SDAÏßΪµÍµçƽÔò×ÜÏßæ,Í˳ö
SDA_L;
I2C_delay();
if(SDA_read)
return FALSE; //SDAÏßΪ¸ßµçƽÔò×ÜÏß³ö´í,Í˳ö
SDA_L;
I2C_delay();
return TRUE;
}
void I2C_Stop(void)
{
SCL_L;
I2C_delay();
SDA_L;
I2C_delay();
SCL_H;
I2C_delay();
SDA_H;
I2C_delay();
}
void I2C_Ack(void)
{
SCL_L;
I2C_delay();
SDA_L;
I2C_delay();
SCL_H;
I2C_delay();
SCL_L;
I2C_delay();
}
void I2C_NoAck(void)
{
SCL_L;
I2C_delay();
SDA_H;
I2C_delay();
SCL_H;
I2C_delay();
SCL_L;
I2C_delay();
}
bool I2C_WaitAck(void) //·µ»ØÎª:=1ÓÐACK,=0ÎÞACK
{
SCL_L;
I2C_delay();
SDA_H;
I2C_delay();
SCL_H;
I2C_delay();
if(SDA_read)
{
SCL_L;
return FALSE;
}
SCL_L;
return TRUE;
}
void I2C_SendByte(uint8_t SendByte) //Êý¾Ý´Ó¸ßλµ½µÍλ//
{
uint8_t i=8;
while(i--)
{
SCL_L;
I2C_delay();
if(SendByte&0x80)
SDA_H;
else
SDA_L;
SendByte<<=1;
I2C_delay();
SCL_H;
I2C_delay();
}
SCL_L;
}
uint8_t I2C_ReceiveByte(void) //Êý¾Ý´Ó¸ßλµ½µÍλ//
{
uint8_t i=8;
uint8_t ReceiveByte=0;
SDA_H;
while(i--)
{
ReceiveByte<<=1;
SCL_L;
I2C_delay();
SCL_H;
I2C_delay();
if(SDA_read)
{
ReceiveByte|=0x01;
}
}
SCL_L;
return ReceiveByte;
}
//дÈë1×Ö½ÚÊý¾Ý ´ýдÈëÊý¾Ý ´ýдÈëµØÖ·
bool I2C_WriteByte(uint8_t WriteAddress, uint8_t SendByte)
{
if(!I2C_Start())
return FALSE;
I2C_SendByte(Write_Pcf8563_address);//ÉèÖÃÆ÷¼þµØÖ·
if(!I2C_WaitAck())
{
I2C_Stop();
return FALSE;
}
I2C_SendByte(WriteAddress); //ÉèÖõØÖ·
I2C_WaitAck();
I2C_SendByte(SendByte);
I2C_WaitAck();
I2C_Stop();
//×¢Ò⣺ÒòΪÕâÀïÒªµÈ´ýEEPROMдÍ꣬¿ÉÒÔ²ÉÓòéѯ»òÑÓʱ·½Ê½
Delay_N_mS(200);
return TRUE;
}
//¶Á³ö1´®Êý¾Ý ´æ·Å¶Á³öÊý¾Ý ´ý¶Á³ö³¤¶È
uint8_t I2C_ReadByte(uint8_t ReadAddress)
{
uint8_t temp;
if(!I2C_Start())
return FALSE;
I2C_SendByte(Write_Pcf8563_address); //ÉèÖÃÆ÷¼þдµØÖ·
if(!I2C_WaitAck())
{
I2C_Stop();
return FALSE;
}
I2C_SendByte(ReadAddress); //ÉèÖõØÖ·
I2C_WaitAck();
if(!I2C_Start())
return FALSE;
I2C_SendByte(Read_Pcf8563_address); //ÉèÖÃÆ÷¼þ¶ÁµØÖ·
if(!I2C_WaitAck())
{
I2C_Stop();
return FALSE;
}
temp = I2C_ReceiveByte();
I2C_Stop();
return temp;
}
void rtc_SetTime(unsigned char year, unsigned char month, unsigned char day, unsigned char hour, unsigned char mint, unsigned char second)
{
I2C_WriteByte(0x00, 0x20); //Í£Ö¹RTC
I2C_WriteByte(0x01, 0x00);
I2C_WriteByte(Addr_second, second);
I2C_WriteByte(Addr_mint, mint);
I2C_WriteByte(Addr_hour, hour);
I2C_WriteByte(Addr_day, day);
I2C_WriteByte(Addr_month, month);
I2C_WriteByte(Addr_year, year);
I2C_WriteByte(0x00, 0x00); //Æô¶¯RTC
return;
}
uint8_t tmp;
TIME rtc_GetTimer(void)
{
TIME getTIME;
tmp = I2C_ReadByte(Addr_second);
tmp &= 0x7f;
tmp =(tmp/16)*10+tmp%16;
getTIME.second = tmp;
tmp = I2C_ReadByte(Addr_mint)&0x7f;
tmp =(tmp/16)*10+tmp%16;
getTIME.mint = tmp;
tmp = I2C_ReadByte(Addr_hour)&0x3f;
tmp =(tmp/16)*10+tmp%16;
getTIME.hour = tmp;
tmp = I2C_ReadByte(Addr_day)&0x3f;
tmp =(tmp/16)*10+tmp%16;
getTIME.day = tmp;
tmp = I2C_ReadByte(Addr_month)&0x1f;
tmp =(tmp/16)*10+tmp%16;
getTIME.month = tmp;
tmp = I2C_ReadByte(Addr_year)&0x1f;
tmp =(tmp/16)*10+tmp%16;
getTIME.year = tmp;
return getTIME;
}
| yangwc/EDC2000_V0.3 | bsp/drivers/I2C_Driver.c | C | gpl-2.0 | 3,974 |
foodcoop.pl localhost build
================================
* Make sure you have [`sculpin`](https://sculpin.io/download/) and [`Node.js package manager - npm`](http://ndever.net/articles/linux/installing-sass-and-compass-ubuntu-1210-1304) (with Grunt, Sass) installed.
* `cd` to your working dir and and then `git clone git@github.com:FoodCoopSystem/foodcoop-sculpin.git`.
* `npm install` manager will install all dependencies.
* To install necessery dependencies go back to root dir and run `sculpin install`.
* `grunt watch -v` - and grunt will run `sculpin` generate, `compass` for css and `uglify` for js
* `grunt sculpin-serve` if you want to run lightweight PHP on `localhost:8000`.
[terminator](http://gnometerminator.blogspot.com/p/introduction.html) (linux only)
* Congrats!
Install Node.js package manager to run grunt.
=====================
sudo apt-get install npm
Below is the oficial sculpin instructions
- - -
Sculpin Blog Skeleton
=====================
A skeleton for a Sculpin based blog.
Powered by [Sculpin](http://sculpin.io). =)
Features
--------
A very basic Sculpin based blog supporting the following features:
* Very minimal Bootstrap based theme.
* A handful of existing posts in `source/_posts/` to get you started. Feel
free to remove these when you are ready.
* An about page at `/about`.
* An index page at `/`. It displays all posts and paginates them.
* A blog archive page at `/blog`. It displays post titles broken down by
month and is paginated.
* A blog categories page at `/blog/categories`.
* A blog category index at `/blog/categories/$category`. Similar to the blog
archive except broken down by each category.
* A blog tags page at `/blog/tags`.
* A blog tag index at `/blog/tags/$tag`. Similar to the blog archive
except broken down by each tag.
Build
-----
### If You Already Have Sculpin
sculpin install
sculpin generate --watch --server
Your newly generated clone of sculpin-blog-skeleton is now
accessible at `http://localhost:8000/`.
## Download the Phar
Downloading sculpin.phar is the best way to get up and running with Sculpin since it is a ready to run self-contained archive. You can download it like this:
curl -O https://download.sculpin.io/sculpin.phar
You can execute Sculpin by running php sculpin.phar but if you want to skip the php part, you can make sculpin.phar executable like this:
chmod +x sculpin.phar
To make things even easier, sculpin.phar can be renamed to sculpin like this:
mv sculpin.phar sculpin
Finally, if you move sculpin to your path it can be run from anywhere. For example, assuming ~/bin is in your $PATH, you can do the following:
mv sculpin ~/bin/
That's it! You're all set to run Sculpin. :)
You can also download stable releases of Sculpin at the following URLs:
v2.0.0 - https://download.sculpin.io/release/v2.0.0/sculpin.phar
Previewing Development Builds
-----------------------------
By default the site will be generated in `output_dev/`. This is the location
of your development build.
To preview it with Sculpin's built in webserver, run either of the following
commands. This will start a simple webserver listening at `localhost:8000`.
### Using Sculpin's Internal Webserver
#### Generate Command
To serve files right after generating them, use the `generate` command with
the `--server` option:
sculpin generate --server
To listen on a different port, specify the `--port` option:
sculpin generate --server --port=9999
Combine with `--watch` to have Sculpin pick up changes as you make them:
sculpin generate --server --watch
##### Server Command
To serve files that have already been generated, use the `serve` command:
sculpin serve
To listen on a different port, specify the `--port` option:
sculpin serve --port=9999
### Using a Standard Webserver
The only special consideration that needs to be taken into account for standard
webservers **in development** is the fact that the URLs generated may not match
the path at which the site is installed.
This can be solved by overriding the `site.url` configuration option when
generating the site.
sculpin generate --url=http://my.dev.host/blog-skeleton/output_dev
With this option passed, `{{ site.url }}/about` will now be generated as
`http://my.dev.host/blog-skelton/output_dev/about` instead of `/about`.
Publishing Production Builds
----------------------------
When `--env=prod` is specified, the site will be generated in `output_prod/`. This
is the location of your production build.
sculpin generate --env=prod
These files are suitable to be transferred directly to a production host. For example:
sculpin generate --env=prod
rsync -avze 'ssh -p 999' output_prod/ user@yoursculpinsite.com:public_html
In fact, `publish.sh` is provided to get you started. If you plan on deploying to an
Amazon S3 bucket, you can use `s3-publish.sh` alongside the `s3cmd` utility (must be
installed separately).
| FoodCoopSystem/foodcoop-sculpin | README.md | Markdown | gpl-2.0 | 5,013 |
/*
Theme Name: Bookmarks
Layout: Sidebar-Content
*/
.content-area {
float: right;
margin: 0 0 0 -25%;
width: 100%;
}
.site-main {
margin: 0 0 0 25%;
}
.site-content .widget-area {
float: left;
overflow: hidden;
width: 25%;
}
.site-footer {
clear: both;
width: 100%;
} | MichaelArestad/Bookmarks | layouts/sidebar-content.css | CSS | gpl-2.0 | 277 |
<?php
/*
* This file is part of PHPExifTool.
*
* (c) 2012 Romain Neutron <imprec@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace PHPExiftool\Driver\Tag\Matroska;
use PHPExiftool\Driver\AbstractTag;
class TagAttachmentUID extends AbstractTag
{
protected $Id = 9158;
protected $Name = 'TagAttachmentUID';
protected $FullName = 'Matroska::Main';
protected $GroupName = 'Matroska';
protected $g0 = 'Matroska';
protected $g1 = 'Matroska';
protected $g2 = 'Video';
protected $Type = 'unsigned';
protected $Writable = false;
protected $Description = 'Tag Attachment UID';
}
| Droces/casabio | vendor/phpexiftool/phpexiftool/lib/PHPExiftool/Driver/Tag/Matroska/TagAttachmentUID.php | PHP | gpl-2.0 | 732 |
var searchData=
[
['operator_21_3d',['operator!=',['../struct_a_c_t_k_1_1_color.html#a7c06f24e8d2e0f88a5c4c63e2639d6f0',1,'ACTK::Color::operator!=()'],['../struct_a_c_t_k_1_1_color_mask.html#aee46d6e92b1005a9ec6f4a1204fefd69',1,'ACTK::ColorMask::operator!=()'],['../struct_a_c_t_k_1_1_clear_state.html#ab13fc63ba272b07bbdb857d5454754e9',1,'ACTK::ClearState::operator!=()']]],
['operator_3d_3d',['operator==',['../struct_a_c_t_k_1_1_color.html#aaac7011cd91c620dc46db571ebcf5ab9',1,'ACTK::Color::operator==()'],['../struct_a_c_t_k_1_1_color_mask.html#ae54cad63b6f88acf789e3a3ab48b621c',1,'ACTK::ColorMask::operator==()'],['../struct_a_c_t_k_1_1_clear_state.html#a4798de8ee59fb8d0d91b867760c77fb8',1,'ACTK::ClearState::operator==()']]]
];
| Acagamics/Acagamic-Toolkit | doc/html/search/functions_6f.js | JavaScript | gpl-2.0 | 740 |
<?php
/**
* @package Joomla.Platform
* @subpackage Image
*
* @copyright Copyright (C) 2005 - 2014 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('_JEXEC') or die(__FILE__);
/**
* Image Filter class adjust the contrast of an image.
*
* @package Joomla.Platform
* @subpackage Image
* @since 11.3
*/
class JImageFilterContrast extends JImageFilter
{
/**
* Method to apply a filter to an image resource.
*
* @param array $options An array of options for the filter.
*
* @return void
*
* @since 11.3
* @throws InvalidArgumentException
*/
public function execute(array $options = array())
{
// Validate that the contrast value exists and is an integer.
if (!isset($options[IMG_FILTER_CONTRAST]) || !is_int($options[IMG_FILTER_CONTRAST]))
{
throw new InvalidArgumentException('No valid contrast value was given. Expected integer.');
}
// Perform the contrast filter.
imagefilter($this->handle, IMG_FILTER_CONTRAST, $options[IMG_FILTER_CONTRAST]);
}
}
| cuongnd/test_pro | libraries/joomla/image/filter/contrast.php | PHP | gpl-2.0 | 1,108 |
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<h1 class="entry-title"><a href="<?php the_permalink(); ?>" title="<?php printf( esc_attr__( 'Permalink to %s', 'diginews' ), the_title_attribute( 'echo=0' ) ); ?>" rel="bookmark"><?php the_title(); ?></a></h1>
<div class="entry-meta">
<?php diginews_posted_on(); ?>
</div><!-- .entry-meta -->
</header><!-- .entry-header -->
<?php if ( is_search() ) : // Only display Excerpts for search pages ?>
<div class="entry-summary post_content">
<?php if ( has_post_thumbnail()) : ?>
<div class="imgthumb"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title_attribute(); ?>"><?php the_post_thumbnail( array(100, 85) ); ?></a></div>
<?php endif; ?>
<?php the_excerpt(); ?>
</div><!-- .entry-summary -->
<?php else : ?>
<div class="entry-content post_content">
<?php if ( post_password_required() ) : ?>
<?php the_content( __( 'Continue reading <span class="meta-nav">→</span>', 'diginews' ) ); ?>
<?php else : ?>
<?php
$images = get_children( array( 'post_parent' => $post->ID, 'post_type' => 'attachment', 'post_mime_type' => 'image', 'orderby' => 'menu_order', 'order' => 'ASC' ) );
if ( $images ) :
$total_images = count( $images );
$image = array_shift( $images );
$image_img_tag = wp_get_attachment_image( $image->ID, 'thumbnail' );
?>
<figure class="gallery-thumb">
<a href="<?php the_permalink(); ?>"><?php echo $image_img_tag; ?></a>
</figure><!-- .gallery-thumb -->
<p><em><?php printf( _n( 'This gallery contains <a %1$s>%2$s photo</a>.', 'This gallery contains <a %1$s>%2$s photos</a>.', $total_images, 'diginews' ),
'href="' . get_permalink() . '" title="' . sprintf( esc_attr__( 'Permalink to %s', 'diginews' ), the_title_attribute( 'echo=0' ) ) . '" rel="bookmark"',
number_format_i18n( $total_images )
); ?></em></p>
<?php endif; ?>
<?php the_excerpt(); ?>
<?php endif; ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'diginews' ), 'after' => '</div>' ) ); ?>
</div><!-- .entry-content -->
<?php endif; ?>
<footer class="entry-meta">
<?php if ( 'post' == get_post_type() ) : // Hide category and tag text for pages on Search ?>
<?php
/* translators: used between list items, there is a space after the comma */
$categories_list = get_the_category_list( __( ', ', 'diginews' ) );
if ( $categories_list && diginews_categorized_blog() ) :
?>
<span class="cat-links">
<?php printf( __( 'Posted in %1$s', 'diginews' ), $categories_list ); ?>
</span>
<span class="sep"> | </span>
<?php endif; // End if categories ?>
<?php
/* translators: used between list items, there is a space after the comma */
$tags_list = get_the_tag_list( '', __( ', ', 'diginews' ) );
if ( $tags_list ) :
?>
<span class="tag-links">
<?php printf( __( 'Tagged %1$s', 'diginews' ), $tags_list ); ?>
</span>
<span class="sep"> | </span>
<?php endif; // End if $tags_list ?>
<?php endif; // End if 'post' == get_post_type() ?>
<?php if ( comments_open() || ( '0' != get_comments_number() && ! comments_open() ) ) : ?>
<span class="comments-link"><?php comments_popup_link( __( 'Leave a comment', 'diginews' ), __( '1 Comment', 'diginews' ), __( '% Comments', 'diginews' ) ); ?></span>
<span class="sep"> | </span>
<?php endif; ?>
<?php edit_post_link( __( 'Edit', 'diginews' ), '<span class="edit-link">', '</span>' ); ?>
</footer><!-- #entry-meta -->
</article><!-- #post-<?php the_ID(); ?> -->
| RobinWu/wordpress-zh-3.4.2 | wp-content/themes/diginews/content-gallery.php | PHP | gpl-2.0 | 3,680 |
/**
* Class for active record connection to postgres database
* @file include/postgre_adapter.hpp
* @author Vladimir <Rain_Weezy> Zyablitskiy
* @date 24/08/2013
*/
#ifndef _RAINLABS_ACTIVE_RECORD_POSTGRE_DRIVER_H
#define _RAINLABS_ACTIVE_RECORD_POSTGRE_DRIVER_H
#include <iostream>
#include <string>
#include <map>
#include <pqxx/pqxx>
#include "adapter.hpp"
namespace ActiveRecord
{
class PostgreAdapter : public Adapter
{
public:
PostgreAdapter(const char *, const char *, const char *, const char *);
~PostgreAdapter();
std::map<std::string, std::string> getColumns(std::string);
std::string quote(std::string);
std::vector< std::map<std::string, std::string> > get(std::string, std::map<std::string, std::string>);
bool update(std::string, std::map<std::string, std::string>, std::map<std::string, std::string>);
bool destroy(std::string, std::map<std::string, std::string>);
bool insert(std::string, std::map<std::string, std::string>);
void commit();
void rollback();
bool connect();
void disconnect();
protected:
pqxx::work * mWorker; // transaction
bool tryQuery(std::string);
// TODO
std::string makeWhere(std::map<std::string, std::string>);
std::vector< std::map<std::string, std::string> > parseResponse(pqxx::result);
};
}
#endif /* _RAINLABS_ACTIVE_RECORD_POSTGRE_DRIVER_H */
| rainlabs/cpp-everyday | active_record/postgre_adapter.hpp | C++ | gpl-2.0 | 1,512 |
<?php
/*******************************************************************************
Copyright 2013 Whole Foods Co-op
This file is part of IT CORE.
IT CORE is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
IT CORE 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
in the file license.txt along with IT CORE; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*********************************************************************************/
include(dirname(__FILE__).'/../../../../config.php');
if (!class_exists('FannieAPI')) {
include_once($FANNIE_ROOT.'classlib2.0/FannieAPI.php');
}
/**
*/
class GumPeopleReport extends FannieReportPage
{
public $discoverable = false; // access is very restricted; no need to list
// as an available report
protected $must_authenticate = true;
protected $auth_classes = array('GiveUsMoney');
protected $required_fields = array();
protected $report_headers = array('Mem#', 'First Name', 'Last Name', 'Loan Date', 'Principal', 'Interest Rate', 'Term (Months)',
'Maturity Date', 'MaturityAmount', 'C Shares');
public function preprocess()
{
$this->header = 'Active Loan Report';
$this->title = 'Active Loan Report';
return parent::preprocess();
}
public function fetch_report_data()
{
global $FANNIE_PLUGIN_SETTINGS, $FANNIE_OP_DB;
$dbc = FannieDB::get($FANNIE_PLUGIN_SETTINGS['GiveUsMoneyDB']);
// compound interest calculation is MySQL-specific
$query = 'SELECT c.CardNo AS card_no,
c.FirstName,
c.LastName,
l.loanDate,
CASE WHEN l.principal IS NULL THEN 0 ELSE l.principal END as principal,
CASE WHEN l.termInMonths IS NULL THEN 0 ELSE l.termInMonths END as termInMonths,
CASE WHEN l.termInMonths IS NULL THEN \'\' ELSE DATE_ADD(loanDate, INTERVAL termInMonths MONTH) END as maturityDate,
CASE WHEN l.interestRate IS NULL THEN 0 ELSE l.interestRate END as interestRate,
CASE WHEN e.shares IS NULL THEN 0 ELSE e.shares END as shares,
CASE WHEN l.principal IS NULL THEN 0
ELSE principal * POW(1+interestRate, DATEDIFF(DATE_ADD(loanDate, INTERVAL termInMonths MONTH), loanDate)/365.25)
END as maturityAmount
FROM ' . $FANNIE_OP_DB . $dbc->sep() . 'custdata AS c
LEFT JOIN GumLoanAccounts AS l
ON l.card_no=c.CardNo AND c.personNum=1
LEFT JOIN (
SELECT card_no, SUM(shares) as shares
FROM GumEquityShares
GROUP BY card_no
) AS e ON c.cardNo=e.card_no AND c.personNum=1
WHERE l.card_no IS NOT NULL OR e.card_no IS NOT NULL
ORDER BY l.card_no, l.loanDate';
$result = $dbc->query($query);
$data = array();
while($row = $dbc->fetch_row($result)) {
$record = array(
$row['card_no'],
$row['LastName'],
$row['FirstName'],
($row['loanDate'] == '' ? 'n/a' : date('Y-m-d', strtotime($row['loanDate']))),
sprintf('%.2f', $row['principal']),
sprintf('%.2f', $row['interestRate'] * 100),
$row['termInMonths'],
($row['maturityDate'] == '' ? 'n/a' : date('Y-m-d', strtotime($row['maturityDate']))),
sprintf('%.2f', $row['maturityAmount']),
$row['shares'],
);
$data[] = $record;
}
return $data;
}
public function calculate_footers($data)
{
$sum = 0.0;
$c = 0.0;
$mat = 0.0;
foreach($data as $row) {
$sum += $row[4];
$mat += $row[8];
$c += $row[9];
}
return array('Total', '', '', '', sprintf('%.2f', $sum), '', '', '', sprintf('%.2f', $mat), sprintf('%.2f', $c));
}
}
FannieDispatch::conditionalExec();
| joelbrock/HARVEST_CORE | fannie/modules/plugins2.0/GiveUsMoneyPlugin/reports/GumPeopleReport.php | PHP | gpl-2.0 | 4,739 |
package com.gp.noname;
import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;
/**
* Unit test for simple App.
*/
public class AppTest
extends TestCase
{
/**
* Create the test case
*
* @param testName name of the test case
*/
public AppTest( String testName )
{
super( testName );
}
/**
* @return the suite of tests being tested
*/
public static Test suite()
{
return new TestSuite( AppTest.class );
}
/**
* Rigourous Test :-)
*/
public void testApp()
{
assertTrue( true );
}
}
| yellowforblack/NoName | src/test/java/com/gp/noname/AppTest.java | Java | gpl-2.0 | 641 |
/**********
This library is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the
Free Software Foundation; either version 2.1 of the License, or (at your
option) any later version. (See <http://www.gnu.org/copyleft/lesser.html>.)
This library is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for
more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation, Inc.,
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
**********/
// "liveMedia"
// Copyright (c) 1996-2007 Live Networks, Inc. All rights reserved.
// RTP sink for a common kind of payload format: Those which pack multiple,
// complete codec frames (as many as possible) into each RTP packet.
// Implementation
#include "MultiFramedRTPSink.hh"
#include "GroupsockHelper.hh"
////////// MultiFramedRTPSink //////////
void MultiFramedRTPSink::setPacketSizes(unsigned preferredPacketSize,
unsigned maxPacketSize) {
if (preferredPacketSize > maxPacketSize || preferredPacketSize == 0) return;
// sanity check
delete fOutBuf;
fOutBuf = new OutPacketBuffer(preferredPacketSize, maxPacketSize);
fOurMaxPacketSize = maxPacketSize; // save value, in case subclasses need it
}
MultiFramedRTPSink::MultiFramedRTPSink(UsageEnvironment& env,
Groupsock* rtpGS,
unsigned char rtpPayloadType,
unsigned rtpTimestampFrequency,
char const* rtpPayloadFormatName,
unsigned numChannels)
: RTPSink(env, rtpGS, rtpPayloadType, rtpTimestampFrequency,
rtpPayloadFormatName, numChannels),
fOutBuf(NULL), fCurFragmentationOffset(0), fPreviousFrameEndedFragmentation(False) {
setPacketSizes(1000, 1448);
// Default max packet size (1500, minus allowance for IP, UDP, UMTP headers)
// (Also, make it a multiple of 4 bytes, just in case that matters.)
}
MultiFramedRTPSink::~MultiFramedRTPSink() {
delete fOutBuf;
}
void MultiFramedRTPSink
::doSpecialFrameHandling(unsigned /*fragmentationOffset*/,
unsigned char* /*frameStart*/,
unsigned /*numBytesInFrame*/,
struct timeval frameTimestamp,
unsigned /*numRemainingBytes*/) {
// default implementation: If this is the first frame in the packet,
// use its timestamp for the RTP timestamp:
if (isFirstFrameInPacket()) {
setTimestamp(frameTimestamp);
}
}
Boolean MultiFramedRTPSink::allowFragmentationAfterStart() const {
return False; // by default
}
Boolean MultiFramedRTPSink::allowOtherFramesAfterLastFragment() const {
return False; // by default
}
Boolean MultiFramedRTPSink
::frameCanAppearAfterPacketStart(unsigned char const* /*frameStart*/,
unsigned /*numBytesInFrame*/) const {
return True; // by default
}
unsigned MultiFramedRTPSink::specialHeaderSize() const {
// default implementation: Assume no special header:
return 0;
}
unsigned MultiFramedRTPSink::frameSpecificHeaderSize() const {
// default implementation: Assume no frame-specific header:
return 0;
}
void MultiFramedRTPSink::setMarkerBit() {
unsigned rtpHdr = fOutBuf->extractWord(0);
rtpHdr |= 0x00800000;
fOutBuf->insertWord(rtpHdr, 0);
}
void MultiFramedRTPSink::setTimestamp(struct timeval timestamp) {
// First, convert the timestamp to a 32-bit RTP timestamp:
fCurrentTimestamp = convertToRTPTimestamp(timestamp);
// Then, insert it into the RTP packet:
fOutBuf->insertWord(fCurrentTimestamp, fTimestampPosition);
}
void MultiFramedRTPSink::setSpecialHeaderWord(unsigned word,
unsigned wordPosition) {
fOutBuf->insertWord(word, fSpecialHeaderPosition + 4*wordPosition);
}
void MultiFramedRTPSink::setSpecialHeaderBytes(unsigned char const* bytes,
unsigned numBytes,
unsigned bytePosition) {
fOutBuf->insert(bytes, numBytes, fSpecialHeaderPosition + bytePosition);
}
void MultiFramedRTPSink::setFrameSpecificHeaderWord(unsigned word,
unsigned wordPosition) {
fOutBuf->insertWord(word, fCurFrameSpecificHeaderPosition + 4*wordPosition);
}
void MultiFramedRTPSink::setFrameSpecificHeaderBytes(unsigned char const* bytes,
unsigned numBytes,
unsigned bytePosition) {
fOutBuf->insert(bytes, numBytes, fCurFrameSpecificHeaderPosition + bytePosition);
}
void MultiFramedRTPSink::setFramePadding(unsigned numPaddingBytes) {
if (numPaddingBytes > 0) {
// Add the padding bytes (with the last one being the padding size):
unsigned char paddingBuffer[255]; //max padding
memset(paddingBuffer, 0, numPaddingBytes);
paddingBuffer[numPaddingBytes-1] = numPaddingBytes;
fOutBuf->enqueue(paddingBuffer, numPaddingBytes);
// Set the RTP padding bit:
unsigned rtpHdr = fOutBuf->extractWord(0);
rtpHdr |= 0x20000000;
fOutBuf->insertWord(rtpHdr, 0);
}
}
Boolean MultiFramedRTPSink::continuePlaying() {
// Send the first packet.
// (This will also schedule any future sends.)
buildAndSendPacket(True);
return True;
}
void MultiFramedRTPSink::stopPlaying() {
fOutBuf->resetPacketStart();
fOutBuf->resetOffset();
fOutBuf->resetOverflowData();
// Then call the default "stopPlaying()" function:
MediaSink::stopPlaying();
}
void MultiFramedRTPSink::buildAndSendPacket(Boolean isFirstPacket) {
fIsFirstPacket = isFirstPacket;
// Set up the RTP header:
unsigned rtpHdr = 0x80000000; // RTP version 2
rtpHdr |= (fRTPPayloadType<<16);
rtpHdr |= fSeqNo; // sequence number
fOutBuf->enqueueWord(rtpHdr);
// Note where the RTP timestamp will go.
// (We can't fill this in until we start packing payload frames.)
fTimestampPosition = fOutBuf->curPacketSize();
fOutBuf->skipBytes(4); // leave a hole for the timestamp
fOutBuf->enqueueWord(SSRC());
// Allow for a special, payload-format-specific header following the
// RTP header:
fSpecialHeaderPosition = fOutBuf->curPacketSize();
fSpecialHeaderSize = specialHeaderSize();
fOutBuf->skipBytes(fSpecialHeaderSize);
// Begin packing as many (complete) frames into the packet as we can:
fTotalFrameSpecificHeaderSizes = 0;
fNoFramesLeft = False;
fNumFramesUsedSoFar = 0;
packFrame();
}
void MultiFramedRTPSink::packFrame() {
// Get the next frame.
// First, see if we have an overflow frame that was too big for the last pkt
if (fOutBuf->haveOverflowData()) {
// Use this frame before reading a new one from the source
unsigned frameSize = fOutBuf->overflowDataSize();
struct timeval presentationTime = fOutBuf->overflowPresentationTime();
unsigned durationInMicroseconds = fOutBuf->overflowDurationInMicroseconds();
fOutBuf->useOverflowData();
afterGettingFrame1(frameSize, 0, presentationTime, durationInMicroseconds);
} else {
// Normal case: we need to read a new frame from the source
if (fSource == NULL) return;
fCurFrameSpecificHeaderPosition = fOutBuf->curPacketSize();
fCurFrameSpecificHeaderSize = frameSpecificHeaderSize();
fOutBuf->skipBytes(fCurFrameSpecificHeaderSize);
fTotalFrameSpecificHeaderSizes += fCurFrameSpecificHeaderSize;
fSource->getNextFrame(fOutBuf->curPtr(), fOutBuf->totalBytesAvailable(),
afterGettingFrame, this, ourHandleClosure, this);
}
}
void MultiFramedRTPSink
::afterGettingFrame(void* clientData, unsigned numBytesRead,
unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds) {
MultiFramedRTPSink* sink = (MultiFramedRTPSink*)clientData;
sink->afterGettingFrame1(numBytesRead, numTruncatedBytes,
presentationTime, durationInMicroseconds);
}
void MultiFramedRTPSink
::afterGettingFrame1(unsigned frameSize, unsigned numTruncatedBytes,
struct timeval presentationTime,
unsigned durationInMicroseconds) {
if (fIsFirstPacket) {
// Record the fact that we're starting to play now:
gettimeofday(&fNextSendTime, NULL);
}
if (numTruncatedBytes > 0) {
unsigned const bufferSize = fOutBuf->totalBytesAvailable();
unsigned newMaxSize = frameSize + numTruncatedBytes;
envir() << "MultiFramedRTPSink::afterGettingFrame1(): The input frame data was too large for our buffer size ("
<< bufferSize << "). "
<< numTruncatedBytes << " bytes of trailing data was dropped! Correct this by increasing \"OutPacketBuffer::maxSize\" to at least "
<< newMaxSize << ", *before* creating this 'RTPSink'. (Current value is "
<< OutPacketBuffer::maxSize << ".)\n";
}
unsigned curFragmentationOffset = fCurFragmentationOffset;
unsigned numFrameBytesToUse = frameSize;
unsigned overflowBytes = 0;
// If we have already packed one or more frames into this packet,
// check whether this new frame is eligible to be packed after them.
// (This is independent of whether the packet has enough room for this
// new frame; that check comes later.)
if (fNumFramesUsedSoFar > 0) {
if ((fPreviousFrameEndedFragmentation
&& !allowOtherFramesAfterLastFragment())
|| !frameCanAppearAfterPacketStart(fOutBuf->curPtr(), frameSize)) {
// Save away this frame for next time:
numFrameBytesToUse = 0;
fOutBuf->setOverflowData(fOutBuf->curPacketSize(), frameSize,
presentationTime, durationInMicroseconds);
}
}
fPreviousFrameEndedFragmentation = False;
if (numFrameBytesToUse > 0) {
// Check whether this frame overflows the packet
if (fOutBuf->wouldOverflow(frameSize)) {
// Don't use this frame now; instead, save it as overflow data, and
// send it in the next packet instead. However, if the frame is too
// big to fit in a packet by itself, then we need to fragment it (and
// use some of it in this packet, if the payload format permits this.)
if (isTooBigForAPacket(frameSize)
&& (fNumFramesUsedSoFar == 0 || allowFragmentationAfterStart())) {
// We need to fragment this frame, and use some of it now:
overflowBytes = fOutBuf->numOverflowBytes(frameSize);
numFrameBytesToUse -= overflowBytes;
fCurFragmentationOffset += numFrameBytesToUse;
} else {
// We don't use any of this frame now:
overflowBytes = frameSize;
numFrameBytesToUse = 0;
}
fOutBuf->setOverflowData(fOutBuf->curPacketSize() + numFrameBytesToUse,
overflowBytes, presentationTime,
durationInMicroseconds);
} else if (fCurFragmentationOffset > 0) {
// This is the last fragment of a frame that was fragmented over
// more than one packet. Do any special handling for this case:
fCurFragmentationOffset = 0;
fPreviousFrameEndedFragmentation = True;
}
}
if (numFrameBytesToUse == 0) {
// Send our packet now, because we have filled it up:
sendPacketIfNecessary();
} else {
// Use this frame in our outgoing packet:
unsigned char * frameStart = fOutBuf->curPtr();
fOutBuf->increment(numFrameBytesToUse);
// do this now, in case "doSpecialFrameHandling()" calls "setFramePadding()" to append padding bytes
// Here's where any payload format specific processing gets done:
doSpecialFrameHandling(curFragmentationOffset, frameStart,
numFrameBytesToUse, presentationTime,
overflowBytes);
++fNumFramesUsedSoFar;
// Update the time at which the next packet should be sent, based
// on the duration of the frame that we just packed into it.
// However, if this frame has overflow data remaining, then don't
// count its duration yet.
if (overflowBytes == 0) {
fNextSendTime.tv_usec += durationInMicroseconds;
fNextSendTime.tv_sec += fNextSendTime.tv_usec/1000000;
fNextSendTime.tv_usec %= 1000000;
}
// Send our packet now if (i) it's already at our preferred size, or
// (ii) (heuristic) another frame of the same size as the one we just
// read would overflow the packet, or
// (iii) it contains the last fragment of a fragmented frame, and we
// don't allow anything else to follow this or
// (iv) one frame per packet is allowed:
if (fOutBuf->isPreferredSize()
|| fOutBuf->wouldOverflow(numFrameBytesToUse)
|| (fPreviousFrameEndedFragmentation &&
!allowOtherFramesAfterLastFragment())
|| !frameCanAppearAfterPacketStart(fOutBuf->curPtr() - frameSize,
frameSize) ) {
// The packet is ready to be sent now
sendPacketIfNecessary();
} else {
// There's room for more frames; try getting another:
packFrame();
}
}
}
static unsigned const rtpHeaderSize = 12;
Boolean MultiFramedRTPSink::isTooBigForAPacket(unsigned numBytes) const {
// Check whether a 'numBytes'-byte frame - together with a RTP header and
// (possible) special headers - would be too big for an output packet:
// (Later allow for RTP extension header!) #####
numBytes += rtpHeaderSize + specialHeaderSize() + frameSpecificHeaderSize();
return fOutBuf->isTooBigForAPacket(numBytes);
}
void MultiFramedRTPSink::sendPacketIfNecessary() {
if (fNumFramesUsedSoFar > 0) {
// Send the packet:
#ifdef TEST_LOSS
if ((our_random()%10) != 0) // simulate 10% packet loss #####
#endif
fRTPInterface.sendPacket(fOutBuf->packet(), fOutBuf->curPacketSize());
++fPacketCount;
fTotalOctetCount += fOutBuf->curPacketSize();
fOctetCount += fOutBuf->curPacketSize()
- rtpHeaderSize - fSpecialHeaderSize - fTotalFrameSpecificHeaderSizes;
++fSeqNo; // for next time
}
if (fOutBuf->haveOverflowData()
&& fOutBuf->totalBytesAvailable() > fOutBuf->totalBufferSize()/2) {
// Efficiency hack: Reset the packet start pointer to just in front of
// the overflow data (allowing for the RTP header and special headers),
// so that we probably don't have to "memmove()" the overflow data
// into place when building the next packet:
unsigned newPacketStart = fOutBuf->curPacketSize()
- (rtpHeaderSize + fSpecialHeaderSize + frameSpecificHeaderSize());
fOutBuf->adjustPacketStart(newPacketStart);
} else {
// Normal case: Reset the packet start pointer back to the start:
fOutBuf->resetPacketStart();
}
fOutBuf->resetOffset();
fNumFramesUsedSoFar = 0;
if (fNoFramesLeft) {
// We're done:
onSourceClosure(this);
} else {
// We have more frames left to send. Figure out when the next frame
// is due to start playing, then make sure that we wait this long before
// sending the next packet.
struct timeval timeNow;
gettimeofday(&timeNow, NULL);
int uSecondsToGo;
if (fNextSendTime.tv_sec < timeNow.tv_sec) {
uSecondsToGo = 0; // prevents integer underflow if too far behind
} else {
uSecondsToGo = (fNextSendTime.tv_sec - timeNow.tv_sec)*1000000
+ (fNextSendTime.tv_usec - timeNow.tv_usec);
}
// Delay this amount of time:
nextTask() = envir().taskScheduler().scheduleDelayedTask(uSecondsToGo,
(TaskFunc*)sendNext, this);
}
}
// The following is called after each delay between packet sends:
void MultiFramedRTPSink::sendNext(void* firstArg) {
MultiFramedRTPSink* sink = (MultiFramedRTPSink*)firstArg;
sink->buildAndSendPacket(False);
}
void MultiFramedRTPSink::ourHandleClosure(void* clientData) {
MultiFramedRTPSink* sink = (MultiFramedRTPSink*)clientData;
// There are no frames left, but we may have a partially built packet
// to send
sink->fNoFramesLeft = True;
sink->sendPacketIfNecessary();
}
| pilt/stream-server | live-media/liveMedia/MultiFramedRTPSink.cpp | C++ | gpl-2.0 | 15,638 |
#!/bin/sh
# $Id: VirtualBoxStartup.sh 54676 2015-03-07 00:16:35Z vboxsync $
## @file
# Startup service for loading the kernel extensions and select the set of VBox
# binaries that matches the kernel architecture.
#
#
# Copyright (C) 2007-2015 Oracle Corporation
#
# This file is part of VirtualBox Open Source Edition (OSE), as
# available from http://www.virtualbox.org. This file is free software;
# you can redistribute it and/or modify it under the terms of the GNU
# General Public License (GPL) as published by the Free Software
# Foundation, in version 2 as it comes in the "COPYING" file of the
# VirtualBox OSE distribution. VirtualBox OSE is distributed in the
# hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
#
if false; then
. /etc/rc.common
else
# Fake the startup item functions we're using.
ConsoleMessage()
{
if [ "$1" != "-f" ]; then
echo "$@"
else
shift
echo "Fatal error: $@"
exit 1;
fi
}
RunService()
{
case "$1" in
"start")
StartService
exit $?;
;;
"stop")
StopService
exit $?;
;;
"restart")
RestartService
exit $?;
;;
"launchd")
if RestartService; then
while true;
do
sleep 3600
done
fi
exit $?;
;;
**)
echo "Error: Unknown action '$1'"
exit 1;
esac
}
fi
StartService()
{
VBOX_RC=0
VBOXDRV="VBoxDrv"
VBOXUSB="VBoxUSB"
#
# Check that all the directories exist first.
#
if [ ! -d "/Library/Application Support/VirtualBox/${VBOXDRV}.kext" ]; then
ConsoleMessage "Error: /Library/Application Support/VirtualBox/${VBOXDRV}.kext is missing"
VBOX_RC=1
fi
if [ ! -d "/Library/Application Support/VirtualBox/${VBOXUSB}.kext" ]; then
ConsoleMessage "Error: /Library/Application Support/VirtualBox/${VBOXUSB}.kext is missing"
VBOX_RC=1
fi
if [ ! -d "/Library/Application Support/VirtualBox/VBoxNetFlt.kext" ]; then
ConsoleMessage "Error: /Library/Application Support/VirtualBox/VBoxNetFlt.kext is missing"
VBOX_RC=1
fi
if [ ! -d "/Library/Application Support/VirtualBox/VBoxNetAdp.kext" ]; then
ConsoleMessage "Error: /Library/Application Support/VirtualBox/VBoxNetAdp.kext is missing"
VBOX_RC=1
fi
#
# Check that no drivers are currently running.
# (Try stop the service if this is the case.)
#
if [ $VBOX_RC -eq 0 ]; then
if kextstat -lb org.virtualbox.kext.VBoxDrv 2>&1 | grep -q org.virtualbox.kext.VBoxDrv; then
ConsoleMessage "Error: ${VBOXDRV}.kext is already loaded"
VBOX_RC=1
fi
if kextstat -lb org.virtualbox.kext.VBoxUSB 2>&1 | grep -q org.virtualbox.kext.VBoxUSB; then
ConsoleMessage "Error: ${VBOXUSB}.kext is already loaded"
VBOX_RC=1
fi
if kextstat -lb org.virtualbox.kext.VBoxNetFlt 2>&1 | grep -q org.virtualbox.kext.VBoxNetFlt; then
ConsoleMessage "Error: VBoxNetFlt.kext is already loaded"
VBOX_RC=1
fi
if kextstat -lb org.virtualbox.kext.VBoxNetAdp 2>&1 | grep -q org.virtualbox.kext.VBoxNetAdp; then
ConsoleMessage "Error: VBoxNetAdp.kext is already loaded"
VBOX_RC=1
fi
fi
#
# Load the drivers.
#
if [ $VBOX_RC -eq 0 ]; then
ConsoleMessage "Loading ${VBOXDRV}.kext"
if ! kextload "/Library/Application Support/VirtualBox/${VBOXDRV}.kext"; then
ConsoleMessage "Error: Failed to load /Library/Application Support/VirtualBox/${VBOXDRV}.kext"
VBOX_RC=1
fi
ConsoleMessage "Loading ${VBOXUSB}.kext"
if ! kextload -d "/Library/Application Support/VirtualBox/${VBOXDRV}.kext" "/Library/Application Support/VirtualBox/${VBOXUSB}.kext"; then
ConsoleMessage "Error: Failed to load /Library/Application Support/VirtualBox/${VBOXUSB}.kext"
VBOX_RC=1
fi
ConsoleMessage "Loading VBoxNetFlt.kext"
if ! kextload -d "/Library/Application Support/VirtualBox/${VBOXDRV}.kext" "/Library/Application Support/VirtualBox/VBoxNetFlt.kext"; then
ConsoleMessage "Error: Failed to load /Library/Application Support/VirtualBox/VBoxNetFlt.kext"
VBOX_RC=1
fi
ConsoleMessage "Loading VBoxNetAdp.kext"
if ! kextload -d "/Library/Application Support/VirtualBox/${VBOXDRV}.kext" "/Library/Application Support/VirtualBox/VBoxNetAdp.kext"; then
ConsoleMessage "Error: Failed to load /Library/Application Support/VirtualBox/VBoxNetAdp.kext"
VBOX_RC=1
fi
if [ $VBOX_RC -ne 0 ]; then
# unload the drivers (ignoring failures)
kextunload -b org.virtualbox.kext.VBoxNetAdp
kextunload -b org.virtualbox.kext.VBoxNetFlt
kextunload -b org.virtualbox.kext.VBoxUSB
kextunload -b org.virtualbox.kext.VBoxDrv
fi
fi
#
# Set the error on failure.
#
if [ "$VBOX_RC" -ne "0" ]; then
ConsoleMessage -f VirtualBox
exit $VBOX_RC
fi
}
StopService()
{
VBOX_RC=0
VBOXDRV="VBoxDrv"
VBOXUSB="VBoxUSB"
if kextstat -lb org.virtualbox.kext.VBoxUSB 2>&1 | grep -q org.virtualbox.kext.VBoxUSB; then
ConsoleMessage "Unloading ${VBOXUSB}.kext"
if ! kextunload -m org.virtualbox.kext.VBoxUSB; then
ConsoleMessage "Error: Failed to unload VBoxUSB.kext"
VBOX_RC=1
fi
fi
if kextstat -lb org.virtualbox.kext.VBoxNetFlt 2>&1 | grep -q org.virtualbox.kext.VBoxNetFlt; then
ConsoleMessage "Unloading VBoxNetFlt.kext"
if ! kextunload -m org.virtualbox.kext.VBoxNetFlt; then
ConsoleMessage "Error: Failed to unload VBoxNetFlt.kext"
VBOX_RC=1
fi
fi
if kextstat -lb org.virtualbox.kext.VBoxNetAdp 2>&1 | grep -q org.virtualbox.kext.VBoxNetAdp; then
ConsoleMessage "Unloading VBoxNetAdp.kext"
if ! kextunload -m org.virtualbox.kext.VBoxNetAdp; then
ConsoleMessage "Error: Failed to unload VBoxNetAdp.kext"
VBOX_RC=1
fi
fi
# This must come last because of dependencies.
if kextstat -lb org.virtualbox.kext.VBoxDrv 2>&1 | grep -q org.virtualbox.kext.VBoxDrv; then
ConsoleMessage "Unloading ${VBOXDRV}.kext"
if ! kextunload -m org.virtualbox.kext.VBoxDrv; then
ConsoleMessage "Error: Failed to unload VBoxDrv.kext"
VBOX_RC=1
fi
fi
# Set the error on failure.
if [ "$VBOX_RC" -ne "0" ]; then
ConsoleMessage -f VirtualBox
exit $VBOX_RC
fi
}
RestartService()
{
StopService
StartService
}
RunService "$1"
| carmark/vbox | src/VBox/Installer/darwin/VBoxKEXTs/VirtualBoxStartup.sh | Shell | gpl-2.0 | 7,104 |
// FPClient.cpp : Defines the entry point for the application.
//
#include "stdafx.h"
#include "FPClient.h"
#define MAX_LOADSTRING 64
// Global Variables:
HINSTANCE hInst; // Current instance
HWND hMainWnd; // Main window handle
HMODULE hRcModule; // FPModule DLL
TCHAR szTitle[MAX_LOADSTRING]; // The title bar text
TCHAR szWindowClass[MAX_LOADSTRING]; // The main window class name
BOOL fWindowed = FALSE; // Flag of whether the game is in window mode
BOOL fActive = FALSE; // Flag of whether the game window is actived
RECT rcWindow; // Rect of the game window
RECT rcViewport; // Rect of the game viewport
DWORD dwLastTick; // Time of last logical frame displayed
IGameEnv *gameEnv = NULL; // Main game resource interface
IGameGraphics *gameGraphics = NULL; // Main game graphics interface
// Define game resource interface
typedef HRESULT(WINAPI *ICreateEnv)(IGameEnv **IEnv);
typedef HRESULT(WINAPI *IDestroyEnv)();
typedef HRESULT(WINAPI *ICreateGraphics)(IGameGraphics **IGraphics);
typedef HRESULT(WINAPI *IDestroyGraphics)();
// Forward declarations of functions included in this code module:
BOOL InitWindow(int, HACCEL*);
LRESULT CALLBACK MainProc(HWND, UINT, WPARAM, LPARAM);
HRESULT GameLoop();
HRESULT GameInit();
HRESULT GameExit();
int APIENTRY _tWinMain(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
UNREFERENCED_PARAMETER(hPrevInstance);
UNREFERENCED_PARAMETER(lpCmdLine);
WNDCLASSEX wcex;
MSG msg;
DWORD dwRet;
HACCEL hAccel;
BOOL fExit = FALSE;
// Initialize global strings
LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING);
LoadString(hInstance, IDS_CLS_NAME, szWindowClass, MAX_LOADSTRING);
// Register the window class
hInst = hInstance; // Store instance handle in our global variable
ZeroMemory(&wcex, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
wcex.style = CS_OWNDC | CS_DBLCLKS;
wcex.lpfnWndProc = MainProc;
wcex.cbClsExtra = 0;
wcex.cbWndExtra = 0;
wcex.hInstance = hInstance;
wcex.hIcon = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_ICON));
wcex.hCursor = LoadCursor(NULL, IDC_ARROW);
wcex.hbrBackground = (HBRUSH)GetStockObject(GRAY_BRUSH);
wcex.lpszMenuName = MAKEINTRESOURCE(IDS_APP_TITLE);
wcex.lpszClassName = szWindowClass;
wcex.hIconSm = NULL;
if (!RegisterClassEx(&wcex))
{
return -1;
}
// Perform application initialization:
fWindowed = TRUE;
if (!InitWindow(nCmdShow, &hAccel))
{
return -2;
}
// Start game logic
FP_DEBUG_MSG(_T("Game starting now...\n"));
if (FAILED(GameInit()))
{
MessageBox(hMainWnd, _T("Game starting failed!"), _T("Error"), MB_ICONERROR | MB_OK);
return -3;
}
// Main message loop:
HANDLE hMainTimer = CreateWaitableTimer(NULL, FALSE, NULL);
if (!hMainTimer)
{
FP_DEBUG_MSG(_T("CreateWaitableTimer failed (%d)\n"), GetLastError());
return -4;
}
LARGE_INTEGER liDueTime;
liDueTime.QuadPart = -1i64;
LONG lTimeout = 1000 / GAME_FRAME_RATE * 2;
SetWaitableTimer(hMainTimer, &liDueTime, lTimeout, NULL, NULL, 0);
while (!fExit)
{
dwRet = MsgWaitForMultipleObjects(1, &hMainTimer, FALSE, INFINITE, QS_ALLINPUT);
switch (dwRet)
{
case GAME_LOOP_TIMER:
//³¡¾°±ä»»ÓëäÖȾ
GameLoop();
break;
case GAME_LOOP_SYSMSG:
while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
if (WM_QUIT == msg.message)
{
fExit = TRUE;
// Release game logic
GameExit();
break;
}
if (0 == TranslateAccelerator(hMainWnd, hAccel, &msg))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
break;
default:
WaitMessage();
break;
}
}
CloseHandle(hMainTimer);
FreeLibrary(hRcModule);
#ifdef FP_PROJECT_DEBUG
system("PAUSE");
#endif
return (int)msg.wParam;
}
BOOL InitWindow(int nCmdShow, HACCEL *phAccel)
{
// Initialization of window instance
HACCEL hAccel = LoadAccelerators(hInst, MAKEINTRESOURCE(IDR_MAIN_ACCEL));
*phAccel = hAccel; // Store accelerate keys
hMainWnd = CreateWindowEx(NULL, szWindowClass, szTitle, WS_POPUP, 0, 0, 0, 0, NULL, NULL, hInst, NULL);
//hMainWnd = CreateWindow(szWindowClass, szTitle, WS_POPUP, 0, 0, 0, 0, NULL, NULL, hInst, NULL);
if (!hMainWnd)
{
return FALSE;
}
ShowWindow(hMainWnd, nCmdShow);
UpdateWindow(hMainWnd);
return TRUE;
}
HRESULT GameLoop()
{
gameGraphics->LoopIORequest(GetTickCount());
// for test
FPImage *pImage = NULL;
gameGraphics->GetImage(10912, &pImage);
if (pImage != NULL)
{
GameDisplayLoop(hMainWnd, pImage, 192, 32);
}
return S_OK;
}
HRESULT GameInit()
{
// Load dependent lib(s)
FP_DEBUG_MSG(_T("Loading FP DLL module...\n"));
hRcModule = LoadLibrary(GAME_RESOURCE_DLL);
if (NULL == hRcModule)
{
MessageBox(hMainWnd, _T("Can not find file \"FPModule.dll\"!"), _T("Error"), MB_ICONERROR | MB_OK);
return E_NOINTERFACE;
}
// Init game resources
if (NULL == gameEnv)
{
// Game Env
ICreateEnv CreateEnv = (ICreateEnv)GetProcAddress(hRcModule, "InitGameEnv");
if (FAILED(CreateEnv(&gameEnv)))
{
FP_DEBUG_MSG(_T("Failed to open Game Env!\n"));
return E_FAIL;
}
FP_DEBUG_MSG(_T("Game Env has been initialized:\n\t@ %s\n"), gameEnv->GetRootPath());
// Game graphics
ICreateGraphics CreateGraphics = (ICreateGraphics)GetProcAddress(hRcModule, "InitGraphics");
if (FAILED(CreateGraphics(&gameGraphics)))
{
FP_DEBUG_MSG(_T("Failed to initialize Game Graphics!\n"));
return E_FAIL;
}
}
// Init DirectDraw & prepare for game display
if (NULL == lpdd)
{
if (FAILED(DirectDrawCreateEx(NULL, (VOID**)&lpdd, IID_IDirectDraw7, NULL)))
{
return E_FAIL;
}
FP_DEBUG_MSG(_T("DirectDraw has been created.\n"));
if (FAILED(InitGameDisplay(fWindowed)))
{
FP_DEBUG_MSG(_T("Failed to start display mode!\n"));
return E_FAIL;
}
}
FP_DEBUG_MSG(_T("Game Started!\n"));
return S_OK;
}
HRESULT GameExit()
{
// Destroy game display
if (lpdd)
{
lpdd->SetCooperativeLevel(hMainWnd, DDSCL_NORMAL);
}
SAFE_RELEASE(lpdd);
FP_DEBUG_MSG(_T("DirectDraw has been destroyed.\n"));
// Release game resources
if (NULL != gameEnv)
{
// Game graphics
IDestroyGraphics DestroyGraphics = (IDestroyGraphics)GetProcAddress(hRcModule, "ReleaseGraphics");
if (FAILED(DestroyGraphics()))
{
FP_DEBUG_MSG(_T("Failed to release Game Graphics!\n"));
return E_FAIL;
}
// Game Env
gameEnv = NULL;
FP_DEBUG_MSG(_T("Game Env has been released.\n"));
IDestroyEnv DestroyEnv = (IDestroyEnv)GetProcAddress(hRcModule, "ReleaseGameEnv");
if (FAILED(DestroyEnv()))
{
FP_DEBUG_MSG(_T("Failed to close Game Env!\n"));
return E_FAIL;
}
}
// Unload dependent lib(s)
FP_DEBUG_MSG(_T("Unloading FP DLL module...\n"));
FreeLibrary(hRcModule);
// Do other cleanup
FP_DEBUG_MSG(_T("Game Shutdown!\n"));
return S_OK;
}
| FP-GAME-DEV-TEAM/FP_Game | FPClient/FPClient.cpp | C++ | gpl-2.0 | 6,815 |
<?php
// Include widgets/*.php
include_files_in_dir("/widgets/");
// Setup widgets output, wrapping HTML code
function dt_widgets_init() {
global $left_block_args;
register_sidebar( $left_block_args=array(
'name' => __( 'Widget area', LANGUAGE_ZONE ),
'id' => 'primary-widget-area',
'description' => __( 'Left block', LANGUAGE_ZONE ),
'before_widget' => '<div class="widget">',
'after_widget' => '</div><div class="widget_b"></div>',
'before_title' => '<div class="header">',
'after_title' => '</div>',
) );
}
add_action( 'widgets_init', 'dt_widgets_init' );
?>
| sharpmachine/foreverviewlodge.com | wp-content/themes/dt-chocolate/functions/03_setup_widgets.php | PHP | gpl-2.0 | 639 |
<!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_45) on Sun Jul 26 12:35:47 GMT+02:00 2015 -->
<title>InvoicingApp</title>
<meta name="date" content="2015-07-26">
<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="InvoicingApp";
}
}
catch(err) {
}
//-->
var methods = {"i0":9,"i1":9};
var tabs = {65535:["t0","All Methods"],1:["t1","Static Methods"],8:["t4","Concrete Methods"]};
var altColor = "altColor";
var rowColor = "rowColor";
var tableTab = "tableTab";
var activeTableTab = "activeTableTab";
</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="navBarCell1Rev">Class</li>
<li><a href="class-use/InvoicingApp.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>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/iproduct/invoicing/InvoicingApp.html" target="_top">Frames</a></li>
<li><a href="InvoicingApp.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><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></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.iproduct.invoicing</div>
<h2 title="Class InvoicingApp" class="title">Class InvoicingApp</h2>
</div>
<div class="contentContainer">
<ul class="inheritance">
<li>java.lang.Object</li>
<li>
<ul class="inheritance">
<li>org.iproduct.invoicing.InvoicingApp</li>
</ul>
</li>
</ul>
<div class="description">
<ul class="blockList">
<li class="blockList">
<hr>
<br>
<pre>public class <span class="typeNameLabel">InvoicingApp</span>
extends java.lang.Object</pre>
<div class="block">Top level invoicing application class.</div>
<dl>
<dt><span class="simpleTagLabel">Since:</span></dt>
<dd>1.0</dd>
<dt><span class="simpleTagLabel">Version:</span></dt>
<dd>1.0</dd>
<dt><span class="simpleTagLabel">Author:</span></dt>
<dd>Trayan Iliev</dd>
<dt><span class="seeLabel">See Also:</span></dt>
<dd><a href="../../../org/iproduct/invoicing/model/Invoice.html" title="class in org.iproduct.invoicing.model"><code>Invoice</code></a></dd>
</dl>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.summary">
<!-- -->
</a>
<h3>Constructor Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Constructor Summary table, listing constructors, and an explanation">
<caption><span>Constructors</span><span class="tabEnd"> </span></caption>
<tr>
<th class="colOne" scope="col">Constructor and Description</th>
</tr>
<tr class="altColor">
<td class="colOne"><code><span class="memberNameLink"><a href="../../../org/iproduct/invoicing/InvoicingApp.html#InvoicingApp--">InvoicingApp</a></span>()</code> </td>
</tr>
</table>
</li>
</ul>
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method.summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="memberSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span id="t0" class="activeTableTab"><span>All Methods</span><span class="tabEnd"> </span></span><span id="t1" class="tableTab"><span><a href="javascript:show(1);">Static Methods</a></span><span class="tabEnd"> </span></span><span id="t4" class="tableTab"><span><a href="javascript:show(8);">Concrete Methods</a></span><span class="tabEnd"> </span></span></caption>
<tr>
<th class="colFirst" scope="col">Modifier and Type</th>
<th class="colLast" scope="col">Method and Description</th>
</tr>
<tr id="i0" class="altColor">
<td class="colFirst"><code>static java.lang.String</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/iproduct/invoicing/InvoicingApp.html#formatInvoice-org.iproduct.invoicing.model.Invoice-">formatInvoice</a></span>(<a href="../../../org/iproduct/invoicing/model/Invoice.html" title="class in org.iproduct.invoicing.model">Invoice</a> inv)</code>
<div class="block">This method prints the invoice as text.</div>
</td>
</tr>
<tr id="i1" class="rowColor">
<td class="colFirst"><code>static void</code></td>
<td class="colLast"><code><span class="memberNameLink"><a href="../../../org/iproduct/invoicing/InvoicingApp.html#main-java.lang.String:A-">main</a></span>(java.lang.String[] args)</code> </td>
</tr>
</table>
<ul class="blockList">
<li class="blockList"><a name="methods.inherited.from.class.java.lang.Object">
<!-- -->
</a>
<h3>Methods inherited from class java.lang.Object</h3>
<code>clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait</code></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<ul class="blockList">
<li class="blockList"><a name="constructor.detail">
<!-- -->
</a>
<h3>Constructor Detail</h3>
<a name="InvoicingApp--">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>InvoicingApp</h4>
<pre>public InvoicingApp()</pre>
</li>
</ul>
</li>
</ul>
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method.detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="formatInvoice-org.iproduct.invoicing.model.Invoice-">
<!-- -->
</a>
<ul class="blockList">
<li class="blockList">
<h4>formatInvoice</h4>
<pre>public static java.lang.String formatInvoice(<a href="../../../org/iproduct/invoicing/model/Invoice.html" title="class in org.iproduct.invoicing.model">Invoice</a> inv)</pre>
<div class="block">This method prints the invoice as text.</div>
<dl>
<dt><span class="paramLabel">Parameters:</span></dt>
<dd><code>inv</code> - invoice to be printed</dd>
<dt><span class="returnLabel">Returns:</span></dt>
<dd>formatted text layout of the inoce</dd>
</dl>
</li>
</ul>
<a name="main-java.lang.String:A-">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>main</h4>
<pre>public static void main(java.lang.String[] args)</pre>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= 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="navBarCell1Rev">Class</li>
<li><a href="class-use/InvoicingApp.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>Prev Class</li>
<li>Next Class</li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?org/iproduct/invoicing/InvoicingApp.html" target="_top">Frames</a></li>
<li><a href="InvoicingApp.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><a href="#constructor.summary">Constr</a> | </li>
<li><a href="#method.summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li><a href="#constructor.detail">Constr</a> | </li>
<li><a href="#method.detail">Method</a></li>
</ul>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| iproduct/IPT-Course-Java-8 | IPT-Course-Java-31ed/Invoicing/doc/org/iproduct/invoicing/InvoicingApp.html | HTML | gpl-2.0 | 10,158 |
// Copyright 2010 wkhtmltopdf authors
//
// This file is part of wkhtmltopdf.
//
// wkhtmltopdf 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.
//
// wkhtmltopdf 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 Lesser General Public License
// along with wkhtmltopdf. If not, see <http://www.gnu.org/licenses/>.
#ifndef __MULTIPAGELOADER_HH__
#define __MULTIPAGELOADER_HH__
#ifdef __WKHTMLTOX_UNDEF_QT_DLL__
#ifdef QT_DLL
#undef QT_DLL
#endif
#endif
#include <QFile>
#include <QObject>
#include <QUrl>
#include <QWebPage>
#include <wkhtmltox/loadsettings.hh>
#include <wkhtmltox/dllbegin.inc>
namespace wkhtmltopdf {
class DLL_LOCAL MyQWebPage;
class DLL_LOCAL LoaderObject {
public:
QWebPage & page;
bool skip;
LoaderObject(QWebPage & page);
};
class DLL_LOCAL MultiPageLoaderPrivate;
class DLL_LOCAL MultiPageLoader: public QObject {
Q_OBJECT
public:
MultiPageLoader(settings::LoadGlobal & s);
~MultiPageLoader();
LoaderObject * addResource(const QString & url, const settings::LoadPage & settings, const QString * data=NULL);
LoaderObject * addResource(const QUrl & url, const settings::LoadPage & settings);
static QUrl guessUrlFromString(const QString &string);
int httpErrorCode();
static bool copyFile(QFile & src, QFile & dst);
public slots:
void load();
void clearResources();
void cancel();
signals:
void loadFinished(bool ok);
void loadProgress(int progress);
void loadStarted();
void warning(QString text);
void error(QString text);
private:
MultiPageLoaderPrivate * d;
friend class MultiPageLoaderPrivate;
friend class MyQWebPage;
friend class ResourceObject;
};
}
#include <wkhtmltox/dllend.inc>
#endif //__MULTIPAGELOADER_HH__
| artefactual-labs/trac | sites/all/libraries/libwkhtmltox-0.11.0_rc1/include/wkhtmltox/multipageloader.hh | C++ | gpl-2.0 | 2,174 |
/*
* Copyright (C) 2011-2021 Project SkyFire <https://www.projectskyfire.org/>
* Copyright (C) 2008-2021 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2005-2021 MaNGOS <https://www.getmangos.eu/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 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 SKYFIRESERVER_ERRORS_H
#define SKYFIRESERVER_ERRORS_H
#include "Define.h"
namespace Skyfire
{
DECLSPEC_NORETURN void Assert(char const* file, int line, char const* function, char const* message) ATTR_NORETURN;
DECLSPEC_NORETURN void Fatal(char const* file, int line, char const* function, char const* message) ATTR_NORETURN;
DECLSPEC_NORETURN void Error(char const* file, int line, char const* function, char const* message) ATTR_NORETURN;
void Warning(char const* file, int line, char const* function, char const* message);
} // namespace Skyfire
#define WPAssert(cond) do { if (!(cond)) Skyfire::Assert(__FILE__, __LINE__, __FUNCTION__, #cond); } while (0)
#define WPFatal(cond, msg) do { if (!(cond)) Skyfire::Fatal(__FILE__, __LINE__, __FUNCTION__, (msg)); } while (0)
#define WPError(cond, msg) do { if (!(cond)) Skyfire::Error(__FILE__, __LINE__, __FUNCTION__, (msg)); } while (0)
#define WPWarning(cond, msg) do { if (!(cond)) Skyfire::Warning(__FILE__, __LINE__, __FUNCTION__, (msg)); } while (0)
#define ASSERT WPAssert
#endif
| ProjectSkyfire/SkyFire.548 | src/server/shared/Debugging/Errors.h | C | gpl-2.0 | 1,933 |
<?php
/**
* @author Dan Redman <dredman@higherlogic.com>
* @copyright 2009-2021 Higher Logic LLC.
* @license GPL-2.0-only
*/
namespace Vanilla\Layout\Providers;
use Garden\Web\Exception\NotFoundException;
use Vanilla\FileUtils;
/**
* Provider for default layouts for a layout view type defined as a YAML file and registered during bootstrapping.
*/
class FileBasedLayoutProvider implements LayoutProviderInterface {
//region Properties
/** @var string $cacheBasePath */
private $cacheBasePath;
/** @var array{string, string} $layoutPaths */
private $layoutPaths;
/** @var ?string $requestedLayoutPath */
private $requestedLayoutPath;
/** @var \UserModel */
private $userModel;
//endregion
//region Constructor
/**
* Instantiate a file based layout provider
*
* @param string $cacheBasePath Base path used to cache parsed static layout definitions
*/
public function __construct(string $cacheBasePath, \UserModel $userModel) {
$this->cacheBasePath = $cacheBasePath;
$this->userModel = $userModel;
$this->layoutPaths = [];
}
//endregion
//region Public Methods
/**
* @inheritdoc
*/
public function isIDFormatSupported($layoutID): bool {
return is_string($layoutID) && !is_numeric($layoutID);
}
/**
* @inheritdoc
*/
public function getByID($layoutID): array {
if (!isset($this->layoutPaths[$layoutID])) {
throw new NotFoundException('Layout');
}
$cachePath = "{$this->cacheBasePath}/{$layoutID}.php";
$this->requestedLayoutPath = $this->layoutPaths[$layoutID];
$layout = (array)FileUtils::getCached($cachePath, [$this, 'parseRequestedLayoutFile']);
$this->requestedLayoutPath = null;
return $layout;
}
/**
* @inheritDoc
*/
public function getAll(): array {
return array_map(
function ($layoutID) {
return $this->getByID($layoutID);
},
array_keys($this->layoutPaths)
);
}
/**
* Register a static layout with the provider and is typically invoked as part of container initialization.
*
* @param string $layoutID Layout view type for the static layout
* @param string $layoutFilePath Path to the file where the static layout is defined.
*/
public function registerStaticLayout(string $layoutID, string $layoutFilePath): void {
if (file_exists($layoutFilePath)) {
$this->layoutPaths[$layoutID] = $layoutFilePath;
}
}
/**
* Specify cache path for layouts generated from a layout definition file.
*
* @param string $cacheBasePath
*/
public function setCacheBasePath(string $cacheBasePath): void {
$this->cacheBasePath = $cacheBasePath;
}
/**
* Specify cache path for layouts generated from a layout definition file.
*
* @return string
*/
public function getCacheBasePath(): string {
return $this->cacheBasePath;
}
/**
* Parse the static layout definition.
*
* @return array
* @throws NotFoundException Requested layout file not found.
*/
public function parseRequestedLayoutFile(): array {
try {
if (!isset($this->requestedLayoutPath)) {
throw new NotFoundException('Layout');
}
$contents = FileUtils::getArray($this->requestedLayoutPath);
$contents['insertUserID'] = $this->userModel->getSystemUserID();
return $contents;
} catch (\Exception $e) {
throw new NotFoundException('Layout');
}
}
//endregion
//region Non-Public Methods
//endregion
}
| vanilla/vanilla | library/Vanilla/Layout/Providers/FileBasedLayoutProvider.php | PHP | gpl-2.0 | 3,788 |
--TEST--
Bug#44806 (rename() function is not portable to Windows)
--SKIPIF--
<?php
if (substr(PHP_OS, 0, 3) != 'WIN') {
die('skip.. only for Windows');
}
?>
--FILE--
<?php
$dirname = dirname(__FILE__);
$file1 = $dirname . DIRECTORY_SEPARATOR . "file1.txt";
$file2 = $dirname . DIRECTORY_SEPARATOR . "file2.txt";
file_put_contents($file1, "this is file 1");
file_put_contents($file2, "this is file 2");
rename($file1, $file2);
echo "reading file 2: ";
readfile($file2);
if (file_exists($file1)) {
unlink($file1);
}
if (file_exists($file1)) {
unlink($file2);
}
?>
--EXPECT--
reading file 2: this is file 1
| ssanglee/capstone | php-5.4.6/ext/standard/tests/file/bug44805.phpt | PHP | gpl-2.0 | 613 |
/*
* Copyright (C) 2013-2015 DeathCore <http://www.noffearrdeathproject.net/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _FIELD_H
#define _FIELD_H
#include "Common.h"
#include "Log.h"
#include <mysql.h>
class Field
{
friend class ResultSet;
friend class PreparedResultSet;
public:
bool GetBool() const // Wrapper, actually gets integer
{
return GetUInt8() == 1 ? true : false;
}
uint8 GetUInt8() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_TINY))
{
TC_LOG_WARN("sql.sql", "Warning: GetUInt8() on non-tinyint field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<uint8*>(data.value);
return static_cast<uint8>(strtoul((char*)data.value, nullptr, 10));
}
int8 GetInt8() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_TINY))
{
TC_LOG_WARN("sql.sql", "Warning: GetInt8() on non-tinyint field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<int8*>(data.value);
return static_cast<int8>(strtol((char*)data.value, NULL, 10));
}
uint16 GetUInt16() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_SHORT) && !IsType(MYSQL_TYPE_YEAR))
{
TC_LOG_WARN("sql.sql", "Warning: GetUInt16() on non-smallint field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<uint16*>(data.value);
return static_cast<uint16>(strtoul((char*)data.value, nullptr, 10));
}
int16 GetInt16() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_SHORT) && !IsType(MYSQL_TYPE_YEAR))
{
TC_LOG_WARN("sql.sql", "Warning: GetInt16() on non-smallint field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<int16*>(data.value);
return static_cast<int16>(strtol((char*)data.value, NULL, 10));
}
uint32 GetUInt32() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_INT24) && !IsType(MYSQL_TYPE_LONG))
{
TC_LOG_WARN("sql.sql", "Warning: GetUInt32() on non-(medium)int field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<uint32*>(data.value);
return static_cast<uint32>(strtoul((char*)data.value, nullptr, 10));
}
int32 GetInt32() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_INT24) && !IsType(MYSQL_TYPE_LONG))
{
TC_LOG_WARN("sql.sql", "Warning: GetInt32() on non-(medium)int field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<int32*>(data.value);
return static_cast<int32>(strtol((char*)data.value, NULL, 10));
}
uint64 GetUInt64() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_LONGLONG) && !IsType(MYSQL_TYPE_BIT))
{
TC_LOG_WARN("sql.sql", "Warning: GetUInt64() on non-bigint field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<uint64*>(data.value);
return static_cast<uint64>(strtoull((char*)data.value, nullptr, 10));
}
int64 GetInt64() const
{
if (!data.value)
return 0;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_LONGLONG) && !IsType(MYSQL_TYPE_BIT))
{
TC_LOG_WARN("sql.sql", "Warning: GetInt64() on non-bigint field. Using type: %s.", FieldTypeToString(data.type));
return 0;
}
#endif
if (data.raw)
return *reinterpret_cast<int64*>(data.value);
return static_cast<int64>(strtoll((char*)data.value, NULL, 10));
}
float GetFloat() const
{
if (!data.value)
return 0.0f;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_FLOAT))
{
TC_LOG_WARN("sql.sql", "Warning: GetFloat() on non-float field. Using type: %s.", FieldTypeToString(data.type));
return 0.0f;
}
#endif
if (data.raw)
return *reinterpret_cast<float*>(data.value);
return static_cast<float>(atof((char*)data.value));
}
double GetDouble() const
{
if (!data.value)
return 0.0f;
#ifdef TRINITY_DEBUG
if (!IsType(MYSQL_TYPE_DOUBLE))
{
TC_LOG_WARN("sql.sql", "Warning: GetDouble() on non-double field. Using type: %s.", FieldTypeToString(data.type));
return 0.0f;
}
#endif
if (data.raw)
return *reinterpret_cast<double*>(data.value);
return static_cast<double>(atof((char*)data.value));
}
char const* GetCString() const
{
if (!data.value)
return NULL;
#ifdef TRINITY_DEBUG
if (IsNumeric())
{
TC_LOG_WARN("sql.sql", "Error: GetCString() on numeric field. Using type: %s.", FieldTypeToString(data.type));
return NULL;
}
#endif
return static_cast<char const*>(data.value);
}
std::string GetString() const
{
if (!data.value)
return "";
if (data.raw)
{
char const* string = GetCString();
if (!string)
string = "";
return std::string(string, data.length);
}
return std::string((char*)data.value);
}
bool IsNull() const
{
return data.value == NULL;
}
protected:
Field();
~Field();
#pragma pack(push, 1)
struct
{
uint32 length; // Length (prepared strings only)
void* value; // Actual data in memory
enum_field_types type; // Field type
bool raw; // Raw bytes? (Prepared statement or ad hoc)
} data;
#pragma pack(pop)
void SetByteValue(void const* newValue, size_t const newSize, enum_field_types newType, uint32 length);
void SetStructuredValue(char* newValue, enum_field_types newType);
void CleanUp()
{
delete[] ((char*)data.value);
data.value = NULL;
}
static size_t SizeForType(MYSQL_FIELD* field)
{
switch (field->type)
{
case MYSQL_TYPE_NULL:
return 0;
case MYSQL_TYPE_TINY:
return 1;
case MYSQL_TYPE_YEAR:
case MYSQL_TYPE_SHORT:
return 2;
case MYSQL_TYPE_INT24:
case MYSQL_TYPE_LONG:
case MYSQL_TYPE_FLOAT:
return 4;
case MYSQL_TYPE_DOUBLE:
case MYSQL_TYPE_LONGLONG:
case MYSQL_TYPE_BIT:
return 8;
case MYSQL_TYPE_TIMESTAMP:
case MYSQL_TYPE_DATE:
case MYSQL_TYPE_TIME:
case MYSQL_TYPE_DATETIME:
return sizeof(MYSQL_TIME);
case MYSQL_TYPE_TINY_BLOB:
case MYSQL_TYPE_MEDIUM_BLOB:
case MYSQL_TYPE_LONG_BLOB:
case MYSQL_TYPE_BLOB:
case MYSQL_TYPE_STRING:
case MYSQL_TYPE_VAR_STRING:
return field->max_length + 1;
case MYSQL_TYPE_DECIMAL:
case MYSQL_TYPE_NEWDECIMAL:
return 64;
case MYSQL_TYPE_GEOMETRY:
/*
Following types are not sent over the wire:
MYSQL_TYPE_ENUM:
MYSQL_TYPE_SET:
*/
default:
TC_LOG_WARN("sql.sql", "SQL::SizeForType(): invalid field type %u", uint32(field->type));
return 0;
}
}
bool IsType(enum_field_types type) const
{
return data.type == type;
}
bool IsNumeric() const
{
return (data.type == MYSQL_TYPE_TINY ||
data.type == MYSQL_TYPE_SHORT ||
data.type == MYSQL_TYPE_INT24 ||
data.type == MYSQL_TYPE_LONG ||
data.type == MYSQL_TYPE_FLOAT ||
data.type == MYSQL_TYPE_DOUBLE ||
data.type == MYSQL_TYPE_LONGLONG );
}
private:
#ifdef TRINITY_DEBUG
static char const* FieldTypeToString(enum_field_types type)
{
switch (type)
{
case MYSQL_TYPE_BIT: return "BIT";
case MYSQL_TYPE_BLOB: return "BLOB";
case MYSQL_TYPE_DATE: return "DATE";
case MYSQL_TYPE_DATETIME: return "DATETIME";
case MYSQL_TYPE_NEWDECIMAL: return "NEWDECIMAL";
case MYSQL_TYPE_DECIMAL: return "DECIMAL";
case MYSQL_TYPE_DOUBLE: return "DOUBLE";
case MYSQL_TYPE_ENUM: return "ENUM";
case MYSQL_TYPE_FLOAT: return "FLOAT";
case MYSQL_TYPE_GEOMETRY: return "GEOMETRY";
case MYSQL_TYPE_INT24: return "INT24";
case MYSQL_TYPE_LONG: return "LONG";
case MYSQL_TYPE_LONGLONG: return "LONGLONG";
case MYSQL_TYPE_LONG_BLOB: return "LONG_BLOB";
case MYSQL_TYPE_MEDIUM_BLOB: return "MEDIUM_BLOB";
case MYSQL_TYPE_NEWDATE: return "NEWDATE";
case MYSQL_TYPE_NULL: return "NULL";
case MYSQL_TYPE_SET: return "SET";
case MYSQL_TYPE_SHORT: return "SHORT";
case MYSQL_TYPE_STRING: return "STRING";
case MYSQL_TYPE_TIME: return "TIME";
case MYSQL_TYPE_TIMESTAMP: return "TIMESTAMP";
case MYSQL_TYPE_TINY: return "TINY";
case MYSQL_TYPE_TINY_BLOB: return "TINY_BLOB";
case MYSQL_TYPE_VAR_STRING: return "VAR_STRING";
case MYSQL_TYPE_YEAR: return "YEAR";
default: return "-Unknown-";
}
}
#endif
};
#endif
| HevdavDEV/DeathCore_3.3.5a | src/server/shared/Database/Field.h | C | gpl-2.0 | 12,517 |
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>ldap setup | Glody's Notes</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="description" content="title: ldapdate: 2017-11-22 20:51:16 tags: Markdown地址: 172.20.197.44 端口:389 基准检索DN: dc=mevoco,dc=com 加密方式: TLS/普通 LDAP用户DN: cn=Manager,dc=mevoco,dc=com 密码: password 用户: ldapuser1 ; ldapuser2 密码: 12">
<meta name="keywords" content="Markdown">
<meta property="og:type" content="article">
<meta property="og:title" content="ldap setup">
<meta property="og:url" content="http://glody.net/2017/11/22/Markdown/ldap/index.html">
<meta property="og:site_name" content="Glody's Notes">
<meta property="og:description" content="title: ldapdate: 2017-11-22 20:51:16 tags: Markdown地址: 172.20.197.44 端口:389 基准检索DN: dc=mevoco,dc=com 加密方式: TLS/普通 LDAP用户DN: cn=Manager,dc=mevoco,dc=com 密码: password 用户: ldapuser1 ; ldapuser2 密码: 12">
<meta property="og:updated_time" content="2017-11-22T12:51:25.781Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="ldap setup">
<meta name="twitter:description" content="title: ldapdate: 2017-11-22 20:51:16 tags: Markdown地址: 172.20.197.44 端口:389 基准检索DN: dc=mevoco,dc=com 加密方式: TLS/普通 LDAP用户DN: cn=Manager,dc=mevoco,dc=com 密码: password 用户: ldapuser1 ; ldapuser2 密码: 12">
<link rel="icon" href="https://avatars3.githubusercontent.com/u/1768868?v=3&s=460">
<link rel="stylesheet" href="/css/style.css">
<link rel="stylesheet" href="/css/highlight.css">
<link href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet">
<link href="//cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/highlight.js/9.9.0/highlight.min.js"></script>
<script>
hljs.initHighlightingOnLoad();
</script>
</head>
<div style="display: none">
<input class="theme_disqus_on" value="false">
<input class="theme_preload_comment" value="false">
</div>
<body>
<aside class="nav">
<div class="nav-left">
<a href="/" class="avatar" style="background-image:url(https://avatars3.githubusercontent.com/u/1768868?v=3&s=460)"></a>
<div class="author">
<span>Glody Guo</span>
</div>
<div class="icon">
<a class="github" title="github" href="https://github.com/glody" target="_blank"></a>
<a class="linkedin" title="linkedin" href="https://www.linkedin.com/in/glody" target="_blank"></a>
<a class="mail" title="mail" href="mailto:glody.guo@gmail.com"></a>
</div>
<ul>
<li class="all active">全部文章</li>
</ul>
</div>
<div class="nav-right">
<form onkeydown="if(event.keyCode==13){return false;}">
<input class="search" type="text" placeholder="Search..." autocomplete="off">
<span>
<label for="tagswitch">Tags:</label>
<input id="tagswitch" type="checkbox">
</span>
</form>
<ul class="tags-list">
<li class="article-tag-list-item">
<a href="javascript:" class="color4">MarkDown</a>
</li>
<li class="article-tag-list-item">
<a href="javascript:" class="color4">Markdown</a>
</li>
<div class="clearfix"></div>
</ul>
<nav>
<a class="" href="/2017/11/22/Markdown/AddSecurityGroupRule/" data-tag="Markdown">
<span class="post-title" title="AddSecurityGroupRule">AddSecurityGroupRule</span>
<span class="post-date" title="2017-11-22 20:51:23">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/ad/" data-tag="Markdown">
<span class="post-title" title="AD DC setup">AD DC setup</span>
<span class="post-date" title="2017-11-22 20:51:16">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/cannot_sariablize_None/" data-tag="Markdown">
<span class="post-title" title="auto test analysis">auto test analysis</span>
<span class="post-date" title="2017-11-22 20:51:25">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/hwinfo/" data-tag="Markdown">
<span class="post-title" title="get linux hardware info">get linux hardware info</span>
<span class="post-date" title="2017-11-22 20:51:17">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/iostat/" data-tag="Markdown">
<span class="post-title" title="iostat">iostat</span>
<span class="post-date" title="2017-11-22 20:51:20">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/gist/" data-tag="Markdown">
<span class="post-title" title="gist">gist</span>
<span class="post-date" title="2017-11-22 20:51:13">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/eth0/" data-tag="Markdown">
<span class="post-title" title="解决vm联网问题">解决vm联网问题</span>
<span class="post-date" title="2017-11-22 20:51:21">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/iotop/" data-tag="Markdown">
<span class="post-title" title="iotop">iotop</span>
<span class="post-date" title="2017-11-22 20:51:18">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/ldap/" data-tag="Markdown">
<span class="post-title" title="ldap setup">ldap setup</span>
<span class="post-date" title="2017-11-22 20:51:25">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/network/" data-tag="Markdown">
<span class="post-title" title="网络命令">网络命令</span>
<span class="post-date" title="2017-11-22 20:51:24">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/remount/" data-tag="Markdown">
<span class="post-title" title="remount">remount</span>
<span class="post-date" title="2017-11-22 20:51:15">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/sar/" data-tag="Markdown">
<span class="post-title" title="sar">sar</span>
<span class="post-date" title="2017-11-22 20:51:17">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/shadowsocks/" data-tag="Markdown">
<span class="post-title" title="ssserver -c /etc/shadowsocks.json -d start">ssserver -c /etc/shadowsocks.json -d start</span>
<span class="post-date" title="2017-11-22 20:51:15">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/sysstat/" data-tag="Markdown">
<span class="post-title" title="sysstat">sysstat</span>
<span class="post-date" title="2017-11-22 20:51:18">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/top/" data-tag="Markdown">
<span class="post-title" title="top">top</span>
<span class="post-date" title="2017-11-22 20:51:20">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/tui_setup/" data-tag="Markdown">
<span class="post-title" title="tui_setup">tui_setup</span>
<span class="post-date" title="2017-11-22 20:51:23">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/unzip/" data-tag="Markdown">
<span class="post-title" title="Linux解压">Linux解压</span>
<span class="post-date" title="2017-11-22 20:51:14">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/uptime/" data-tag="Markdown">
<span class="post-title" title="uptime">uptime</span>
<span class="post-date" title="2017-11-22 20:51:21">2017/11/22</span>
</a>
<a class="" href="/2017/11/10/Markdown/virsh/" data-tag="">
<span class="post-title" title=""></span>
<span class="post-date" title="2017-11-10 15:42:53">2017/11/10</span>
</a>
<a class="" href="/2017/11/22/Markdown/ad_test/" data-tag="Markdown">
<span class="post-title" title="adtest">adtest</span>
<span class="post-date" title="2017-11-22 20:51:12">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/ldap.tmp/" data-tag="Markdown">
<span class="post-title" title=""></span>
<span class="post-date" title="2017-11-22 20:51:10">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/note/" data-tag="Markdown">
<span class="post-title" title=""></span>
<span class="post-date" title="2017-11-22 20:51:11">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/project/" data-tag="Markdown">
<span class="post-title" title="project">project</span>
<span class="post-date" title="2017-11-22 20:51:12">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/timeout/" data-tag="Markdown">
<span class="post-title" title=""></span>
<span class="post-date" title="2017-11-22 20:51:12">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/win_cloudbase/" data-tag="Markdown">
<span class="post-title" title=""></span>
<span class="post-date" title="2017-11-22 20:51:11">2017/11/22</span>
</a>
<a class="" href="/2017/11/22/Markdown/同步时间/" data-tag="Markdown">
<span class="post-title" title="同步时间">同步时间</span>
<span class="post-date" title="2017-11-22 20:51:25">2017/11/22</span>
</a>
</nav>
</div>
</aside>
<div class="post">
<div class="pjax">
<article id="post-Markdown/ldap" class="article article-type-post" itemscope itemprop="blogPost">
<div class="article-meta">
<time class="date" title="2017-11-22 20:51:25">2017 November 22</time>
<span class="tag">
<a href="javascript:" class="color4">Markdown</a>
</span>
</div>
<h1 class="article-title">ldap setup</h1>
<div class="toc-ref">
<ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#tags-Markdown"><span class="toc-text">tags: Markdown</span></a></li></ol>
<style>
.left-col .switch-btn,
.left-col .switch-area {
display: none;
}
.toc-level-3 i,
.toc-level-3 ol {
display: none !important;
}
</style>
</div>
<div class="article-entry" itemprop="articleBody">
<hr>
<p>title: ldap<br>date: 2017-11-22 20:51:16</p>
<h2 id="tags-Markdown"><a href="#tags-Markdown" class="headerlink" title="tags: Markdown"></a>tags: Markdown</h2><pre><code class="lang:shell">地址: 172.20.197.44
端口:389
基准检索DN: dc=mevoco,dc=com
加密方式: TLS/普通
LDAP用户DN: cn=Manager,dc=mevoco,dc=com
密码: password
用户: ldapuser1 ; ldapuser2
密码: 123456
用户:ldapuser3 ; ldapuser4 ;
密码:password
用户: ldapuser5
密码: zstack.org
uid=ldapuser4,ou=people,dc=mevoco,dc=com
</code></pre>
</div>
</article>
</div>
</div>
<div class="full-toc">
<button class="full"><span class="min"></span></button>
<button class="post-toc-menu"><span class="post-toc-menu-icons"></span></button>
<div class="post-toc"><span class="post-toc-title">目录</span>
<div class="post-toc-content">
</div>
</div>
</div>
</body>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.pjax/1.9.6/jquery.pjax.min.js"></script>
<script src="/js/script.js"></script>
</html>
| glody/glody.github.io | 2017/11/22/Markdown/ldap/index.html | HTML | gpl-2.0 | 11,663 |
# os
chrisOS Repo
| VBWizard/os | README.md | Markdown | gpl-2.0 | 22 |
/*
* fm-dir-list-job.c
*
* Copyright 2009 PCMan <pcman.tw@gmail.com>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "fm-dir-list-job.h"
#include <glib/gi18n-lib.h>
#include <gio/gio.h>
#include <string.h>
#include <glib/gstdio.h>
#include "fm-mime-type.h"
#include "fm-file-info-job.h"
#include <menu-cache.h>
extern const char gfile_info_query_attribs[]; /* defined in fm-file-info-job.c */
static void fm_dir_list_job_finalize (GObject *object);
G_DEFINE_TYPE(FmDirListJob, fm_dir_list_job, FM_TYPE_JOB);
static gboolean fm_dir_list_job_run(FmDirListJob *job);
static void fm_dir_list_job_class_init(FmDirListJobClass *klass)
{
GObjectClass *g_object_class;
FmJobClass* job_class = FM_JOB_CLASS(klass);
g_object_class = G_OBJECT_CLASS(klass);
g_object_class->finalize = fm_dir_list_job_finalize;
job_class->run = fm_dir_list_job_run;
}
static void fm_dir_list_job_init(FmDirListJob *self)
{
}
FmJob* fm_dir_list_job_new(FmPath* path)
{
/* FIXME: should we cache this with hash table? Or, the cache
* should be done at the level of FmFolder instead? */
FmDirListJob* job = (FmJob*)g_object_new(FM_TYPE_DIR_LIST_JOB, NULL);
job->dir_path = fm_path_ref(path);
job->files = fm_file_info_list_new();
return (FmJob*)job;
}
FmJob* fm_dir_list_job_new_for_gfile(GFile* gf)
{
/* FIXME: should we cache this with hash table? Or, the cache
* should be done at the level of FmFolder instead? */
FmDirListJob* job = (FmJob*)g_object_new(FM_TYPE_DIR_LIST_JOB, NULL);
job->dir_path = fm_path_new_for_gfile(gf);
return (FmJob*)job;
}
static void fm_dir_list_job_finalize(GObject *object)
{
FmDirListJob *self;
g_return_if_fail(object != NULL);
g_return_if_fail(FM_IS_DIR_LIST_JOB(object));
self = FM_DIR_LIST_JOB(object);
if(self->dir_path)
fm_path_unref(self->dir_path);
if(self->dir_fi)
fm_file_info_unref(self->dir_fi);
if(self->files)
fm_list_unref(self->files);
if (G_OBJECT_CLASS(fm_dir_list_job_parent_class)->finalize)
(* G_OBJECT_CLASS(fm_dir_list_job_parent_class)->finalize)(object);
}
/* defined in fm-file-info.c */
FmFileInfo* _fm_file_info_new_from_menu_cache_item(FmPath* path, MenuCacheItem* item);
static gpointer list_menu_items(FmJob* fmjob, gpointer user_data)
{
FmDirListJob* job = (FmDirListJob*)fmjob;
FmFileInfo* fi;
MenuCache* mc;
MenuCacheDir* dir;
GList* l;
char* path_str, *p, ch;
char* menu_name;
const char* dir_path;
guint32 de_flag;
const char* de_name;
/* example: menu://applications.menu/DesktopSettings */
path_str = fm_path_to_str(job->dir_path);
p = path_str + 5; /* skip menu: */
while(*p == '/')
++p;
menu_name = p;
while(*p && *p != '/')
++p;
ch = *p;
*p = '\0';
menu_name = g_strconcat(menu_name, ".menu", NULL);
mc = menu_cache_lookup_sync(menu_name);
/* ensure that the menu cache is loaded */
if(!mc) /* if it's not loaded */
{
/* try to set $XDG_MENU_PREFIX to "lxde-" for lxmenu-data */
const char* menu_prefix = g_getenv("XDG_MENU_PREFIX");
if(g_strcmp0(menu_prefix, "lxde-")) /* if current value is not lxde- */
{
char* old_prefix = g_strdup(menu_prefix);
g_setenv("XDG_MENU_PREFIX", "lxde-", TRUE);
mc = menu_cache_lookup_sync(menu_name);
/* restore original environment variable */
if(old_prefix)
{
g_setenv("XDG_MENU_PREFIX", old_prefix, TRUE);
g_free(old_prefix);
}
else
g_unsetenv("XDG_MENU_PREFIX");
if(!mc)
{
g_free(menu_name);
return NULL;
}
}
else
{
g_free(menu_name);
return NULL;
}
}
g_free(menu_name);
*p = ch;
dir_path = p; /* path of menu dir, such as: /Internet */
de_name = g_getenv("XDG_CURRENT_DESKTOP");
if(de_name)
de_flag = menu_cache_get_desktop_env_flag(mc, de_name);
else
de_flag = (guint32)-1;
/* the menu should be loaded now */
if(*dir_path && !(*dir_path == '/' && dir_path[1]=='\0') )
{
char* tmp = g_strconcat("/", menu_cache_item_get_id(MENU_CACHE_ITEM(menu_cache_get_root_dir(mc))), dir_path, NULL);
dir = menu_cache_get_dir_from_path(mc, tmp);
g_free(tmp);
}
else
dir = menu_cache_get_root_dir(mc);
if(dir)
{
job->dir_fi = _fm_file_info_new_from_menu_cache_item(job->dir_path, dir);
for(l=menu_cache_dir_get_children(dir);l;l=l->next)
{
MenuCacheItem* item = MENU_CACHE_ITEM(l->data);
FmPath* item_path;
GIcon* gicon;
/* also hide menu items which should be hidden in current DE. */
if(!item || menu_cache_item_get_type(item) == MENU_CACHE_TYPE_SEP)
continue;
if(menu_cache_item_get_type(item) == MENU_CACHE_TYPE_APP && !menu_cache_app_get_is_visible(item, de_flag))
continue;
item_path = fm_path_new_child(job->dir_path, menu_cache_item_get_id(item));
fi = _fm_file_info_new_from_menu_cache_item(item_path, item);
fm_path_unref(item_path);
fm_list_push_tail_noref(job->files, fi);
}
}
menu_cache_unref(mc);
g_free(path_str);
return NULL;
}
gboolean fm_dir_list_job_list_xdg_menu(FmDirListJob* job)
{
/* Calling libmenu-cache is only allowed in main thread. */
fm_job_call_main_thread(FM_JOB(job), list_menu_items, NULL);
return TRUE;
}
gboolean fm_dir_list_job_run(FmDirListJob* job)
{
GFileEnumerator *enu;
GFileInfo *inf;
FmFileInfo* fi;
GError *err = NULL;
if(fm_path_is_native(job->dir_path)) /* if this is a native file on real file system */
{
char* dir_path;
GDir* dir;
dir_path = fm_path_to_str(job->dir_path);
fi = fm_file_info_new();
fi->path = fm_path_ref(job->dir_path);
if( fm_file_info_job_get_info_for_native_file(FM_JOB(job), fi, dir_path) )
{
job->dir_fi = fi;
if(! fm_file_info_is_dir(fi))
{
fm_file_info_unref(fi);
return FALSE;
}
}
else
{
fm_file_info_unref(fi);
return FALSE;
}
dir = g_dir_open(dir_path, 0, NULL);
if( dir )
{
char* name;
GString* fpath = g_string_sized_new(4096);
int dir_len = strlen(dir_path);
g_string_append_len(fpath, dir_path, dir_len);
if(fpath->str[dir_len-1] != '/')
{
g_string_append_c(fpath, '/');
++dir_len;
}
while( ! FM_JOB(job)->cancel && (name = g_dir_read_name(dir)) )
{
g_string_truncate(fpath, dir_len);
g_string_append(fpath, name);
fi = fm_file_info_new();
fi->path = fm_path_new_child(job->dir_path, name);
if( fm_file_info_job_get_info_for_native_file(FM_JOB(job), fi, fpath->str) )
fm_list_push_tail_noref(job->files, fi);
else /* failed! */
fm_file_info_unref(fi);
}
g_string_free(fpath, TRUE);
g_dir_close(dir);
}
g_free(dir_path);
}
else /* this is a virtual path or remote file system path */
{
FmJob* fmjob = FM_JOB(job);
GFile* gf;
/* handle some built-in virtual dirs */
if( fm_path_is_xdg_menu(job->dir_path) ) /* xdg menu:// */
return fm_dir_list_job_list_xdg_menu(job);
if(!fm_job_init_cancellable(fmjob))
return FALSE;
gf = fm_path_to_gfile(job->dir_path);
_retry:
inf = g_file_query_info(gf, gfile_info_query_attribs, 0, fmjob->cancellable, &err);
if(!inf )
{
if( fm_job_emit_error(fmjob, err, TRUE) )
{
g_error_free(err);
err = NULL;
goto _retry;
}
else
{
g_object_unref(gf);
g_error_free(err);
return FALSE;
}
}
if( g_file_info_get_file_type(inf) != G_FILE_TYPE_DIRECTORY)
{
err = g_error_new(G_IO_ERROR, G_IO_ERROR_NOT_DIRECTORY, _("The specified directory is not valid"));
fm_job_emit_error(fmjob, err, FALSE);
g_error_free(err);
g_object_unref(gf);
g_object_unref(inf);
return FALSE;
}
/* FIXME: should we use fm_file_info_new + fm_file_info_set_from_gfileinfo? */
job->dir_fi = fm_file_info_new_from_gfileinfo(job->dir_path, inf);
g_object_unref(inf);
enu = g_file_enumerate_children (gf, gfile_info_query_attribs, 0, fmjob->cancellable, &err);
g_object_unref(gf);
if(enu)
{
while( ! FM_JOB(job)->cancel )
{
inf = g_file_enumerator_next_file(enu, fmjob->cancellable, &err);
if(inf)
{
FmPath* sub = fm_path_new_child(job->dir_path, g_file_info_get_name(inf));
fi = fm_file_info_new_from_gfileinfo(sub, inf);
fm_path_unref(sub);
fm_list_push_tail_noref(job->files, fi);
}
else
{
if(err)
{
fm_job_emit_error(fmjob, err, FALSE);
g_error_free(err);
}
break; /* FIXME: error handling */
}
g_object_unref(inf);
}
g_file_enumerator_close(enu, NULL, &err);
g_object_unref(enu);
}
else
{
fm_job_emit_error(fmjob, err, FALSE);
g_error_free(err);
return FALSE;
}
}
return TRUE;
}
FmFileInfoList* fm_dir_dist_job_get_files(FmDirListJob* job)
{
return job->files;
}
| gilir/libfm-debian | src/job/fm-dir-list-job.c | C | gpl-2.0 | 10,659 |
from os import path
try:
from lib.settings_build import Configure
except ImportError:
import sys
from os.path import expanduser, join
sys.path.append(join(expanduser("~"), 'workspace/automation/launchy'))
from lib.settings_build import Configure
class Default(Configure):
def __init__(self):
self.beta = False
self.local = False
self.project = 'nedcompost'
self.php = True
self.database_name = self.project
self.database_user = self.project
self.path_project_root = path.join('/mnt', self.project)
self.setDefaults()
if getattr(self, 'host', False):
self.setHost()
class Local(Default):
def __init__(self):
self.beta = True
self.local = True
self.database_root_password = 'password'
super(Local, self).__init__()
class Production(Default):
def __init__(self):
self.host = ['aws-php-3', ]
self.domain = 'nedcompost.org'
self.database_root_password = 'password'
# self.database_password = 'iNcJ%kx87[M>L:!6pkY$fXZIu'
self.database_password = 'zHR-mp)@ZZydJ=s9R}*S+4,!a'
super(Production, self).__init__()
class Beta(Default):
def __init__(self):
self.beta = True
self.host = ['aws-php-3', ]
self.domain = 'nedcompost.mitesdesign.com'
self.database_root_password = 'password'
self.database_password = 'zHR-mp)@ZZydJ=s9R}*S+4,!a'
super(Beta, self).__init__()
try:
from local_settings import *
except ImportError:
pass | amites/nedcompost_wordpress | fabsettings.py | Python | gpl-2.0 | 1,613 |
/*
*sp0a19 - This code emulates a real video device with v4l2 api
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the BSD Licence, GNU General Public License
* as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version
*/
#include <linux/sizes.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/fs.h>
#include <linux/kernel.h>
#include <linux/wait.h>
#include <linux/slab.h>
#include <linux/mm.h>
#include <linux/ioport.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/pci.h>
#include <linux/random.h>
#include <linux/version.h>
#include <linux/mutex.h>
#include <linux/videodev2.h>
#include <linux/dma-mapping.h>
#include <linux/interrupt.h>
#include <linux/kthread.h>
#include <linux/highmem.h>
#include <linux/freezer.h>
#include <media/videobuf-vmalloc.h>
#include <media/v4l2-device.h>
#include <media/v4l2-ioctl.h>
#include <linux/wakelock.h>
#include <linux/i2c.h>
#include <media/v4l2-chip-ident.h>
#include <linux/amlogic/camera/aml_cam_info.h>
#include <linux/amlogic/vmapi.h>
#include <mach/am_regs.h>
#include <mach/pinmux.h>
#include <mach/gpio.h>
//#include <mach/gpio_data.h>
#include "common/plat_ctrl.h"
#if MESON_CPU_TYPE >= MESON_CPU_TYPE_MESON6
#include <mach/mod_gate.h>
#endif
#define SP0A19_CAMERA_MODULE_NAME "sp0a19"
/* Wake up at about 30 fps */
#define WAKE_NUMERATOR 30
#define WAKE_DENOMINATOR 1001
#define BUFFER_TIMEOUT msecs_to_jiffies(500) /* 0.5 seconds */
#define SP0A19_CAMERA_MAJOR_VERSION 0
#define SP0A19_CAMERA_MINOR_VERSION 7
#define SP0A19_CAMERA_RELEASE 0
#define SP0A19_CAMERA_VERSION \
KERNEL_VERSION(SP0A19_CAMERA_MAJOR_VERSION, SP0A19_CAMERA_MINOR_VERSION, SP0A19_CAMERA_RELEASE)
MODULE_DESCRIPTION("sp0a19 On Board");
MODULE_AUTHOR("amlogic-sh");
MODULE_LICENSE("GPL v2");
static unsigned video_nr = -1; /* videoX start number, -1 is autodetect. */
static unsigned debug;
//module_param(debug, uint, 0644);
//MODULE_PARM_DESC(debug, "activates debug info");
static unsigned int vid_limit = 16;
//module_param(vid_limit, uint, 0644);
//MODULE_PARM_DESC(vid_limit, "capture memory limit in megabytes");
static int sp0a19_have_open=0;
static int sp0a19_h_active=320;
static int sp0a19_v_active=240;
static struct v4l2_fract sp0a19_frmintervals_active = {
.numerator = 1,
.denominator = 15,
};
static struct vdin_v4l2_ops_s *vops;
/* supported controls */
static struct v4l2_queryctrl sp0a19_qctrl[] = {
{
.id = V4L2_CID_DO_WHITE_BALANCE,
.type = V4L2_CTRL_TYPE_MENU,
.name = "white balance",
.minimum = 0,
.maximum = 6,
.step = 0x1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_EXPOSURE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "exposure",
.minimum = 0,
.maximum = 8,
.step = 0x1,
.default_value = 4,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_COLORFX,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "effect",
.minimum = 0,
.maximum = 6,
.step = 0x1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_WHITENESS,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "banding",
.minimum = 0,
.maximum = 1,
.step = 0x1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_BLUE_BALANCE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "scene mode",
.minimum = 0,
.maximum = 1,
.step = 0x1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_HFLIP,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "flip on horizontal",
.minimum = 0,
.maximum = 1,
.step = 0x1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_VFLIP,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "flip on vertical",
.minimum = 0,
.maximum = 1,
.step = 0x1,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_ZOOM_ABSOLUTE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Zoom, Absolute",
.minimum = 100,
.maximum = 300,
.step = 20,
.default_value = 100,
.flags = V4L2_CTRL_FLAG_SLIDER,
},{
.id = V4L2_CID_ROTATE,
.type = V4L2_CTRL_TYPE_INTEGER,
.name = "Rotate",
.minimum = 0,
.maximum = 270,
.step = 90,
.default_value = 0,
.flags = V4L2_CTRL_FLAG_SLIDER,
}
};
static struct v4l2_frmivalenum sp0a19_frmivalenum[]={
{
.index = 0,
.pixel_format = V4L2_PIX_FMT_NV21,
.width = 640,
.height = 480,
.type = V4L2_FRMIVAL_TYPE_DISCRETE,
{
.discrete ={
.numerator = 1,
.denominator = 15,
}
}
},{
.index = 1,
.pixel_format = V4L2_PIX_FMT_NV21,
.width = 1600,
.height = 1200,
.type = V4L2_FRMIVAL_TYPE_DISCRETE,
{
.discrete ={
.numerator = 1,
.denominator = 5,
}
}
},
};
struct v4l2_querymenu sp0a19_qmenu_wbmode[] = {
{
.id = V4L2_CID_DO_WHITE_BALANCE,
.index = CAM_WB_AUTO,
.name = "auto",
.reserved = 0,
},{
.id = V4L2_CID_DO_WHITE_BALANCE,
.index = CAM_WB_CLOUD,
.name = "cloudy-daylight",
.reserved = 0,
},{
.id = V4L2_CID_DO_WHITE_BALANCE,
.index = CAM_WB_INCANDESCENCE,
.name = "incandescent",
.reserved = 0,
},{
.id = V4L2_CID_DO_WHITE_BALANCE,
.index = CAM_WB_DAYLIGHT,
.name = "daylight",
.reserved = 0,
},{
.id = V4L2_CID_DO_WHITE_BALANCE,
.index = CAM_WB_FLUORESCENT,
.name = "fluorescent",
.reserved = 0,
},{
.id = V4L2_CID_DO_WHITE_BALANCE,
.index = CAM_WB_FLUORESCENT,
.name = "warm-fluorescent",
.reserved = 0,
},
};
struct v4l2_querymenu sp0a19_qmenu_anti_banding_mode[] = {
{
.id = V4L2_CID_POWER_LINE_FREQUENCY,
.index = CAM_BANDING_50HZ,
.name = "50hz",
.reserved = 0,
},{
.id = V4L2_CID_POWER_LINE_FREQUENCY,
.index = CAM_BANDING_60HZ,
.name = "60hz",
.reserved = 0,
},
};
typedef struct {
__u32 id;
int num;
struct v4l2_querymenu* sp0a19_qmenu;
}sp0a19_qmenu_set_t;
sp0a19_qmenu_set_t sp0a19_qmenu_set[] = {
{
.id = V4L2_CID_DO_WHITE_BALANCE,
.num = ARRAY_SIZE(sp0a19_qmenu_wbmode),
.sp0a19_qmenu = sp0a19_qmenu_wbmode,
},{
.id = V4L2_CID_POWER_LINE_FREQUENCY,
.num = ARRAY_SIZE(sp0a19_qmenu_anti_banding_mode),
.sp0a19_qmenu = sp0a19_qmenu_anti_banding_mode,
},
};
static int vidioc_querymenu(struct file *file, void *priv,
struct v4l2_querymenu *a)
{
int i, j;
for (i = 0; i < ARRAY_SIZE(sp0a19_qmenu_set); i++)
if (a->id && a->id == sp0a19_qmenu_set[i].id) {
for(j = 0; j < sp0a19_qmenu_set[i].num; j++)
if (a->index == sp0a19_qmenu_set[i].sp0a19_qmenu[j].index) {
memcpy(a, &( sp0a19_qmenu_set[i].sp0a19_qmenu[j]),
sizeof(*a));
return (0);
}
}
return -EINVAL;
}
#define dprintk(dev, level, fmt, arg...) \
v4l2_dbg(level, debug, &dev->v4l2_dev, fmt, ## arg)
/* ------------------------------------------------------------------
Basic structures
------------------------------------------------------------------*/
struct sp0a19_fmt {
char *name;
u32 fourcc; /* v4l2 format id */
int depth;
};
static struct sp0a19_fmt formats[] = {
{
.name = "RGB565 (BE)",
.fourcc = V4L2_PIX_FMT_RGB565X, /* rrrrrggg gggbbbbb */
.depth = 16,
},
{
.name = "RGB888 (24)",
.fourcc = V4L2_PIX_FMT_RGB24, /* 24 RGB-8-8-8 */
.depth = 24,
},
{
.name = "BGR888 (24)",
.fourcc = V4L2_PIX_FMT_BGR24, /* 24 BGR-8-8-8 */
.depth = 24,
},
{
.name = "12 Y/CbCr 4:2:0",
.fourcc = V4L2_PIX_FMT_NV12,
.depth = 12,
},
{
.name = "12 Y/CbCr 4:2:0",
.fourcc = V4L2_PIX_FMT_NV21,
.depth = 12,
},
{
.name = "YUV420P",
.fourcc = V4L2_PIX_FMT_YUV420,
.depth = 12,
},
{
.name = "YVU420P",
.fourcc = V4L2_PIX_FMT_YVU420,
.depth = 12,
}
};
static struct sp0a19_fmt *get_format(struct v4l2_format *f){
struct sp0a19_fmt *fmt;
unsigned int k;
for (k = 0; k < ARRAY_SIZE(formats); k++) {
fmt = &formats[k];
if (fmt->fourcc == f->fmt.pix.pixelformat)
break;
}
if (k == ARRAY_SIZE(formats))
return NULL;
return &formats[k];
}
struct sg_to_addr {
int pos;
struct scatterlist *sg;
};
/* buffer for one video frame */
struct sp0a19_buffer {
/* common v4l buffer stuff -- must be first */
struct videobuf_buffer vb;
struct sp0a19_fmt *fmt;
};
struct sp0a19_dmaqueue {
struct list_head active;
/* thread for generating video stream*/
struct task_struct *kthread;
wait_queue_head_t wq;
/* Counters to control fps rate */
int frame;
int ini_jiffies;
};
static LIST_HEAD(sp0a19_devicelist);
struct sp0a19_device {
struct list_head sp0a19_devicelist;
struct v4l2_subdev sd;
struct v4l2_device v4l2_dev;
spinlock_t slock;
struct mutex mutex;
int users;
/* various device info */
struct video_device *vdev;
struct sp0a19_dmaqueue vidq;
/* Several counters */
unsigned long jiffies;
/* Input Number */
int input;
/* platform device data from board initting. */
aml_cam_info_t cam_info;
/* wake lock */
struct wake_lock wake_lock;
/* Control 'registers' */
int qctl_regs[ARRAY_SIZE(sp0a19_qctrl)];
};
static inline struct sp0a19_device *to_dev(struct v4l2_subdev *sd)
{
return container_of(sd, struct sp0a19_device, sd);
}
struct sp0a19_fh {
struct sp0a19_device *dev;
/* video capture */
struct sp0a19_fmt *fmt;
unsigned int width, height;
struct videobuf_queue vb_vidq;
enum v4l2_buf_type type;
int input; /* Input Number on bars */
int stream_on;
unsigned int f_flags;
};
static inline struct sp0a19_fh *to_fh(struct sp0a19_device *dev)
{
return container_of(dev, struct sp0a19_fh, dev);
}
static struct v4l2_frmsize_discrete sp0a19_prev_resolution[3]= //should include 320x240 and 640x480, those two size are used for recording
{
{320,240},
//{352,288},
{640,480},
};
static struct v4l2_frmsize_discrete sp0a19_pic_resolution[1]=
{
{640,480},
};
/* ------------------------------------------------------------------
reg spec of SP0A19
------------------------------------------------------------------*/
struct aml_camera_i2c_fig1_s SP0A19_script[] = {
//SP0A19 ini
{0xfd,0x00},
{0x1C,0x28},
{0x32,0x00},
{0x0f,0x2f},
{0x10,0x2e},
{0x11,0x00},
{0x12,0x18},
{0x13,0x2f},
{0x14,0x00},
{0x15,0x3f},
{0x16,0x00},
{0x17,0x18},
{0x25,0x40},
{0x1a,0x0b},
{0x1b,0xc },
{0x1e,0xb },
{0x20,0x3f}, // add
{0x21,0x13}, // 0x0c 24
{0x22,0x19},
{0x26,0x1a},
{0x27,0xab},
{0x28,0xfd},
{0x30,0x00},
{0x31,0x00},//0x00 0x20¸ÄÉãÏñÍ·ÒÆ¶¯·½Ïò
{0xfb,0x33},
{0x1f,0x08},
//Blacklevel
{0xfd,0x00},
{0x65,0x00},//06
{0x66,0x00},//06
{0x67,0x00},//06
{0x68,0x00},//06
{0x45,0x00},//add wxc
{0x46,0x0f},//add wxc
#if 1 //PZT 2013-7-11
//ae setting
{0xfd,0x00},
{0x03,0x01},
{0x04,0x32},
{0x06,0x00},
{0x09,0x01},
{0x0a,0x46},
{0xf0,0x66},
{0xf1,0x00},
{0xfd,0x01},
{0x90,0x10},
{0x92,0x01},
{0x98,0x66},
{0x99,0x00},
{0x9a,0x01},
{0x9b,0x00},
{0xfd,0x01},
{0xce,0x60},
{0xcf,0x06},
{0xd0,0x60},
{0xd1,0x06},
#endif
#if 0 //PZT 2013-7-11
{0xfd,0x00},
{0x03,0x01},
{0x04,0x32},
{0x06,0x00},
{0x09,0x01},
{0x0a,0x46},
{0xf0,0x66},
{0xf1,0x00},
{0xfd,0x01},
{0x90,0x0c},
{0x92,0x01},
{0x98,0x66},
{0x99,0x00},
{0x9a,0x01},
{0x9b,0x00},
//Status
{0xfd,0x01},
{0xce,0xc8},
{0xcf,0x04},
{0xd0,0xc8},
{0xd1,0x04},
#endif
{0xfd,0x01},
{0xc4,0x56},
{0xc5,0x8f},
{0xca,0x30},
{0xcb,0x45},
{0xcc,0xb0},
{0xcd,0x48},
{0xfd,0x00},
//lsc for st
{0xfd,0x01},
{0x35,0x15},
{0x36,0x15}, //20
{0x37,0x15},
{0x38,0x15},
{0x39,0x15},
{0x3a,0x15}, //15
{0x3b,0x13},
{0x3c,0x15},
{0x3d,0x15},
{0x3e,0x15}, //12
{0x3f,0x15},
{0x40,0x18},
{0x41,0x00},
{0x42,0x04},
{0x43,0x04},
{0x44,0x00},
{0x45,0x00},
{0x46,0x00},
{0x47,0x00},
{0x48,0x00},
{0x49,0xfd},
{0x4a,0x00},
{0x4b,0x00},
{0x4c,0xfd},
{0xfd,0x00},
//awb 1
{0xfd,0x01},
{0x28,0xc5},
{0x29,0x9b},
//{0x10,0x08},
//{0x11,0x14},
//{0x12,0x14},
{0x2e,0x02},
{0x2f,0x16},
{0x17,0x17},
{0x18,0x19}, //0x29 0813
{0x19,0x45},
//{0x1a,0x9e},//a1;a5
//{0x1b,0xae},//b0;9a
//{0x33,0xef},
{0x2a,0xef},
{0x2b,0x15},
//awb2
{0xfd,0x01},
{0x73,0x80},
{0x1a,0x80},
{0x1b,0x80},
//d65
{0x65,0xd5}, //d6
{0x66,0xfa}, //f0
{0x67,0x72}, //7a
{0x68,0x8a}, //9a
//indoor
{0x69,0xc6}, //ab
{0x6a,0xee}, //ca
{0x6b,0x94}, //a3
{0x6c,0xab}, //c1
//f
{0x61,0x7a}, //82
{0x62,0x98}, //a5
{0x63,0xc5}, //d6
{0x64,0xe6}, //ec
//cwf
{0x6d,0xb9}, //a5
{0x6e,0xde}, //c2
{0x6f,0xb2}, //a7
{0x70,0xd5}, //c5
//skin detect
{0xfd,0x01},
{0x08,0x15},
{0x09,0x04},
{0x0a,0x20},
{0x0b,0x12},
{0x0c,0x27},
{0x0d,0x06},
{0x0f,0x63},//0x5f 0813
//BPC_grad
{0xfd,0x00},
{0x79,0xf0},
{0x7a,0x80}, //f0
{0x7b,0x80}, //f0
{0x7c,0x20},//f0
#if 0
//smooth
{0xfd,0x00},
//
{0x57,0x06}, //raw_dif_thr_outdoor
{0x58,0x0d}, //raw_dif_thr_normal
{0x56,0x10}, //raw_dif_thr_dummy
{0x59,0x10}, //raw_dif_thr_lowlight
//GrGb
{0x89,0x06}, //raw_grgb_thr_outdoor
{0x8a,0x0d}, //raw_grgb_thr_normal
{0x9c,0x10}, //raw_grgb_thr_dummy
{0x9d,0x10}, //raw_grgb_thr_lowlight
//Gr\Gb
{0x81,0xe0}, //raw_gflt_fac_outdoor
{0x82,0xe0}, //raw_gflt_fac_normal
{0x83,0x80}, //raw_gflt_fac_dummy
{0x84,0x40}, //raw_gflt_fac_lowlight
//GrGb
{0x85,0xe0}, //raw_gf_fac_outdoor
{0x86,0xc0}, //raw_gf_fac_normal
{0x87,0x80}, //raw_gf_fac_dummy
{0x88,0x40}, //raw_gf_fac_lowlight
//
{0x5a,0xff}, //raw_rb_fac_outdoor
{0x5b,0xe0}, //raw_rb_fac_normal
{0x5c,0x80}, //raw_rb_fac_dummy
{0x5d,0x00}, //raw_rb_fac_lowlight
//sharpen
{0xfd,0x01},
{0xe2,0x30}, //sharpen_y_base
{0xe4,0xa0}, //sharpen_y_max
{0xe5,0x04}, //rangek_neg_outdoor //0x08
{0xd3,0x04}, //rangek_pos_outdoor //0x08
{0xd7,0x04}, //range_base_outdoor //0x08
{0xe6,0x06}, //rangek_neg_normal
{0xd4,0x06}, //rangek_pos_normal
{0xd8,0x06}, //range_base_normal
{0xe7,0x08}, //rangek_neg_dummy // 0x10
{0xd5,0x08}, //rangek_pos_dummy // 0x10
{0xd9,0x08}, //range_base_dummy // 0x10
{0xd2,0x10}, //rangek_neg_lowlight
{0xd6,0x10}, //rangek_pos_lowlight
{0xda,0x10}, //range_base_lowlight
{0xe8,0x20}, //sharp_fac_pos_outdoor // 0x35
{0xec,0x35}, //sharp_fac_neg_outdoor
{0xe9,0x20}, //sharp_fac_pos_nr // 0x35
{0xed,0x25},//sharp_fac_neg_nr
{0xea,0x20},//sharp_fac_pos_dummy
{0xef,0x25},//sharp_fac_neg_dummy
{0xeb,0x15},//sharp_fac_pos_low
{0xf0,0x20},//sharp_fac_neg_low
#else //PZT 2013-7-11
{0xfd,0x00},
{0x57,0x06}, //raw_dif_thr_outdoor
{0x58,0x10}, //raw_dif_thr_normal
{0x56,0x18}, //raw_dif_thr_dummy
{0x59,0x10}, //raw_dif_thr_lowlight
{0x89,0x06}, //raw_grgb_thr_outdoor
{0x8a,0x10}, //raw_grgb_thr_normal
{0x9c,0x18}, //raw_grgb_thr_dummy
{0x9d,0x10}, //raw_grgb_thr_lowlight
{0x81,0xe0}, //raw_gflt_fac_outdoor
{0x82,0xd8}, //raw_gflt_fac_normal
{0x83,0x78}, //raw_gflt_fac_dummy
{0x84,0x40}, //raw_gflt_fac_lowlight
{0x85,0xe0}, //raw_gf_fac_outdoor
{0x86,0xb8}, //raw_gf_fac_normal
{0x87,0x78}, //raw_gf_fac_dummy
{0x88,0x40}, //raw_gf_fac_lowlight
{0x5a,0xff}, //raw_rb_fac_outdoor
{0x5b,0xd8}, //raw_rb_fac_normal
{0x5c,0x78}, //raw_rb_fac_dummy
{0x5d,0x00}, //raw_rb_fac_lowlight
{0xfd,0x01},
{0xe2,0x30}, //sharpen_y_base
{0xe4,0xa0}, //sharpen_y_max
{0xe5,0x04}, //rangek_neg_outdoor //0x08
{0xd3,0x04}, //rangek_pos_outdoor //0x08
{0xd7,0x04}, //range_base_outdoor //0x08
{0xe6,0x06}, //rangek_neg_normal
{0xd4,0x06}, //rangek_pos_normal
{0xd8,0x06}, //range_base_normal
{0xe7,0x08}, //rangek_neg_dummy // 0x10
{0xd5,0x08}, //rangek_pos_dummy // 0x10
{0xd9,0x08}, //range_base_dummy // 0x10
{0xd2,0x10}, //rangek_neg_lowlight
{0xd6,0x10}, //rangek_pos_lowlight
{0xda,0x10}, //range_base_lowlight
{0xe8,0x20}, //sharp_fac_pos_outdoor // 0x35
{0xec,0x30}, //sharp_fac_neg_outdoor
{0xe9,0x20}, //sharp_fac_pos_nr // 0x35
{0xed,0x28},//sharp_fac_neg_nr
{0xea,0x20},//sharp_fac_pos_dummy
{0xef,0x28},//sharp_fac_neg_dummy
{0xeb,0x10},//sharp_fac_pos_low
{0xf0,0x20},//sharp_fac_neg_low
#endif
//CCM
{0xfd,0x01},
{0xa0,0x80},
{0xa1,0x00},
{0xa2,0x00},
{0xa3,0xf3}, // 0xf6
{0xa4,0x8e}, // 0x99
{0xa5,0x00}, // 0xf2
{0xa6,0x00}, // 0x0d
{0xa7,0xe6}, // 0xda
{0xa8,0x9a},//0xa0 0813 // 0x98
{0xa9,0x00},
{0xaa,0x03}, // 0x33
{0xab,0x0c},
{0xfd,0x00},
//gamma
{0xfd,0x00},
{0x8b,0x0 }, // 00;0 ;0
{0x8c,0xC }, // 0f;C ;11
{0x8d,0x19}, // 1e;19;19
{0x8e,0x2C}, // 3d;2C;28
{0x8f,0x49}, // 6c;49;46
{0x90,0x61}, // 92;61;61
{0x91,0x77}, // aa;77;78
{0x92,0x8A}, // b9;8A;8A
{0x93,0x9B}, // c4;9B;9B
{0x94,0xA9}, // cf;A9;A9
{0x95,0xB5}, // d4;B5;B5
{0x96,0xC0}, // da;C0;C0
{0x97,0xCA}, // e0;CA;CA
{0x98,0xD4}, // e4;D4;D4
{0x99,0xDD}, // e8;DD;DD
{0x9a,0xE6}, // ec;E6;E6
{0x9b,0xEF}, // f1;EF;EF
{0xfd,0x01}, // 01;01;01
{0x8d,0xF7}, // f7;F7;F7
{0x8e,0xFF}, // ff;FF;FF
{0xfd,0x00}, //
//rpc
{0xfd,0x00},
{0xe0,0x4c}, // 4c;44;4c;3e;3c;3a;38;rpc_1base_max
{0xe1,0x3c}, // 3c;36;3c;30;2e;2c;2a;rpc_2base_max
{0xe2,0x34}, // 34;2e;34;2a;28;26;26;rpc_3base_max
{0xe3,0x2e}, // 2e;2a;2e;26;24;22;rpc_4base_max
{0xe4,0x2e}, // 2e;2a;2e;26;24;22;rpc_5base_max
{0xe5,0x2c}, // 2c;28;2c;24;22;20;rpc_6base_max
{0xe6,0x2c}, // 2c;28;2c;24;22;20;rpc_7base_max
{0xe8,0x2a}, // 2a;26;2a;22;20;20;1e;rpc_8base_max
{0xe9,0x2a}, // 2a;26;2a;22;20;20;1e;rpc_9base_max
{0xea,0x2a}, // 2a;26;2a;22;20;20;1e;rpc_10base_max
{0xeb,0x28}, // 28;24;28;20;1f;1e;1d;rpc_11base_max
{0xf5,0x28}, // 28;24;28;20;1f;1e;1d;rpc_12base_max
{0xf6,0x28}, // 28;24;28;20;1f;1e;1d;rpc_13base_max
//ae min gain
{0xfd,0x01},
{0x94,0x80},//rpc_max_indr //0xb0
{0x95,0x28},//1e//rpc_min_indr
{0x9c,0xa0},//rpc_max_outdr
{0x9d,0x28},//rpc_min_outdr
//ae target
{0xfd,0x00},
{0xed,0x8c}, //80
{0xf7,0x88}, //7c
{0xf8,0x80}, //70
{0xec,0x7c}, //6c
{0xef,0x74}, //99
{0xf9,0x70}, //90
{0xfa,0x68}, //80
{0xee,0x64}, //78
//gray detect
{0xfd,0x01},
{0x30,0x40},
//add 0813
{0x31,0x70},
{0x32,0x40},
{0x33,0xef},
{0x34,0x05},
{0x4d,0x2f},
{0x4e,0x20},
{0x4f,0x16},
//lowlight lum
{0xfd,0x00}, //
{0xb2,0x20}, //lum_limit // 0x10
{0xb3,0x1f}, //lum_set
{0xb4,0x30}, //black_vt // 0x20
{0xb5,0x45}, //white_vt
//saturation
{0xfd,0x00},
{0xbe,0xff},
{0xbf,0x01},
{0xc0,0xff},
{0xc1,0xd8},
{0xd3,0x88}, //0x78
{0xd4,0x78}, //0x78
{0xd6,0x70}, //0x78 (0xd7,0x60}, //0x78
{0xd7,0x60},
//HEQ
{0xfd,0x00},
{0xdc,0x00},
{0xdd,0x78}, //0x80 0813 // 0x80
{0xde,0xa8}, //80 0x88 0813
{0xdf,0x80},
//func enable
{0xfd,0x00},
{0x32,0x15}, //0x0d
{0x34,0x76}, //16
{0x35,0x41},
{0x33,0xef},
{0x5f,0x51},
{0xff,0xff},
};
//load GT2005 parameters
void SP0A19_init_regs(struct sp0a19_device *dev)
{
int i=0;//,j;
unsigned char buf[2];
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
while (1) {
buf[0] = SP0A19_script[i].addr;
buf[1] = SP0A19_script[i].val;
if(SP0A19_script[i].val==0xff&&SP0A19_script[i].addr==0xff){
printk("SP0A19_write_regs success in initial SP0A19.\n");
break;
}
if((i2c_put_byte_add8(client,buf, 2)) < 0){
printk("fail in initial SP0A19. \n");
return;
}
i++;
}
return;
}
static struct aml_camera_i2c_fig1_s resolution_320x240_script[] = {
{0xfd, 0x00},
{0x47, 0x00},
{0x48, 0x78},
{0x49, 0x00},
{0x4a, 0xf0},
{0x4b, 0x00},
{0x4c, 0xa0},
{0x4d, 0x01},
{0x4e, 0x40},
{0xff, 0xff}
};
static struct aml_camera_i2c_fig1_s resolution_640x480_script[] = {
{0xfd, 0x00},
{0x47, 0x00},
{0x48, 0x00},
{0x49, 0x01},
{0x4a, 0xe0},
{0x4b, 0x00},
{0x4c, 0x00},
{0x4d, 0x02},
{0x4e, 0x80},
{0xff, 0xff}
};
static int set_flip(struct sp0a19_device *dev)
{
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char temp;
unsigned char buf[2];
temp = i2c_get_byte_add8(client, 0x31);
temp &= 0xf3;
temp |= dev->cam_info.m_flip << 5;
temp |= dev->cam_info.v_flip << 6;
buf[0] = 0x31;
buf[1] = temp;
if((i2c_put_byte_add8(client,buf, 2)) < 0) {
printk("fail in setting sensor orientation\n");
return -1;
}
return 0;
}
static void sp0a19_set_resolution(struct sp0a19_device *dev,int height,int width)
{
int i=0;
unsigned char buf[2];
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
struct aml_camera_i2c_fig1_s* resolution_script;
if (width*height >= 640*480) {
printk("set resolution 640X480\n");
resolution_script = resolution_640x480_script;
sp0a19_h_active = 640;
sp0a19_v_active = 478; //480
sp0a19_frmintervals_active.denominator = 15;
sp0a19_frmintervals_active.numerator = 1;
//SP0A19_init_regs(dev);
//return;
} else {
printk("set resolution 320X240\n");
sp0a19_h_active = 320;
sp0a19_v_active = 238;
sp0a19_frmintervals_active.denominator = 15;
sp0a19_frmintervals_active.numerator = 1;
resolution_script = resolution_320x240_script;
}
while(1) {
buf[0] = resolution_script[i].addr;
buf[1] = resolution_script[i].val;
if(resolution_script[i].val==0xff&&resolution_script[i].addr==0xff) {
break;
}
if((i2c_put_byte_add8(client,buf, 2)) < 0) {
printk("fail in setting resolution \n");
return;
}
i++;
}
set_flip(dev);
}
/*************************************************************************
* FUNCTION
* set_SP0A19_param_wb
*
* DESCRIPTION
* SP0A19 wb setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED °×ƽºâ²ÎÊý
*
*************************************************************************/
void set_SP0A19_param_wb(struct sp0a19_device *dev,enum camera_wb_flip_e para)
{
// kal_uint16 rgain=0x80, ggain=0x80, bgain=0x80;
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char buf[4];
unsigned char temp_reg;
//temp_reg=sp0a19_read_byte(0x22);
//buf[0]=0x22; //SP0A19 enable auto wb
buf[0]=0x32;
temp_reg=i2c_get_byte_add8(client,buf);
printk(" camera set_SP0A19_param_wb=%d. \n ",para);
switch (para)
{
case CAM_WB_AUTO:
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x28;
buf[1]=0xc4;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x29;
buf[1]=0x9e;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x32;
buf[1]=0x15; //temp_reg|0x10; // SP0A19 AWB enable bit[1] ie. 0x02;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_WB_CLOUD:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x32;
buf[1]=0x05;//temp_reg&~0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x28;
buf[1]=0xe0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x29;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_WB_DAYLIGHT: // tai yang guang
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x32;
buf[1]=0x05;//temp_reg&~0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x28;
buf[1]=0xb0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x29;
buf[1]=0x70;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_WB_INCANDESCENCE: // bai re guang
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x32;
buf[1]=0x05;//temp_reg&~0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x28;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x29;
buf[1]=0xe0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_WB_FLUORESCENT: //ri guang deng
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x32;
buf[1]=0x05;//temp_reg&~0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x28;
buf[1]=0x98;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x29;
buf[1]=0xc0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_WB_TUNGSTEN: // wu si deng
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x32;
buf[1]=0x05;//temp_reg&~0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x28;
buf[1]=0xaf;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x29;
buf[1]=0x99;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_WB_MANUAL:
// TODO
break;
default:
break;
}
// kal_sleep_task(20);
}
/*************************************************************************
* FUNCTION
* SP0A19_night_mode
*
* DESCRIPTION
* This function night mode of SP0A19.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void SP0A19_night_mode(struct sp0a19_device *dev,enum camera_night_mode_flip_e enable)
{
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char buf[4];
unsigned char temp_reg;
//temp_reg=sp0a19_read_byte(0x22);
//buf[0]=0x20;
temp_reg=i2c_get_byte_add8(client,buf);
temp_reg=0xff;
if(enable)
{
#if 0
//caprure preview night 24M 50hz 20-6FPS maxgain:0x78
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x05;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x06;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x09;
buf[1]=0x1 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0a;
buf[1]=0x76;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf0;
buf[1]=0x62;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf1;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf2;
buf[1]=0x5f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf5;
buf[1]=0x78;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x00;
buf[1]=0xc0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0f;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x16;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x17;
buf[1]=0xa8;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x18;
buf[1]=0xb0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x1b;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x1c;
buf[1]=0xb0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb4;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb5;
buf[1]=0x3a;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb6;
buf[1]=0x5e;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb9;
buf[1]=0x40;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xba;
buf[1]=0x4f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbb;
buf[1]=0x47;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbc;
buf[1]=0x45;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbd;
buf[1]=0x43;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbe;
buf[1]=0x42;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbf;
buf[1]=0x42;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc0;
buf[1]=0x42;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc1;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc2;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc3;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc4;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc5;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc6;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xca;
buf[1]=0x78;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xcb;
buf[1]=0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x14;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x15;
buf[1]=0x1f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
#endif
}
else
{
#if 0
//caprure preview daylight 24M 50hz 20-8FPS maxgain:0x70
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x05;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x06;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x09;
buf[1]=0x1 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0a;
buf[1]=0x76;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf0;
buf[1]=0x62;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf1;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf2;
buf[1]=0x5f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf5;
buf[1]=0x78;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x00;
buf[1]=0xb2;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0f;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x16;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x17;
buf[1]=0xa2;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x18;
buf[1]=0xaa;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x1b;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x1c;
buf[1]=0xaa;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb4;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb5;
buf[1]=0x3a;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb6;
buf[1]=0x5e;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xb9;
buf[1]=0x40;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xba;
buf[1]=0x4f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbb;
buf[1]=0x47;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbc;
buf[1]=0x45;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbd;
buf[1]=0x43;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbe;
buf[1]=0x42;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xbf;
buf[1]=0x42;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc0;
buf[1]=0x42;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc1;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc2;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc3;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc4;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc5;
buf[1]=0x70;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xc6;
buf[1]=0x41;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xca;
buf[1]=0x70;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xcb;
buf[1]=0x0c;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x14;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x15;
buf[1]=0x0f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
#endif
}
}
/*************************************************************************
* FUNCTION
* SP0A19_night_mode
*
* DESCRIPTION
* This function night mode of SP0A19.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED
*
*************************************************************************/
void SP0A19_set_param_banding(struct sp0a19_device *dev,enum camera_night_mode_flip_e banding)
{
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char buf[4];
switch(banding){
case CAM_BANDING_60HZ:
#if 1
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x03;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x04;
buf[1]=0xff;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x06;
buf[1]=0x00 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x09;
buf[1]=0x1 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0a;
buf[1]=0x46;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf0;
buf[1]=0x55;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf1;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x90;
buf[1]=0x14;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x92;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x98;
buf[1]=0x55;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x99;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9a;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9b;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xce;
buf[1]=0xa4;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xcf;
buf[1]=0x06;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd0;
buf[1]=0xa4;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd1;
buf[1]=0x06;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
#else
//caprure preview daylight 24M 60hz 20-8FPS maxgain:0x70
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x03;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x04;
buf[1]=0xff;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x06;
buf[1]=0x31 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x09;
buf[1]=0x1 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0a;
buf[1]=0x46;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf0;
buf[1]=0x55;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf1;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x90;
buf[1]=0x0f;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x92;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x98;
buf[1]=0x55;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x99;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9a;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9b;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xce;
buf[1]=0xfb;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xcf;
buf[1]=0x04;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd0;
buf[1]=0xfb;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd1;
buf[1]=0x04;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
#endif
break;
case CAM_BANDING_50HZ:
#if 1
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x03;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x04;
buf[1]=0x32;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x06;
buf[1]=0x00 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x09;
buf[1]=0x1 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0a;
buf[1]=0x46;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf0;
buf[1]=0x66;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf1;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x90;
buf[1]=0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x92;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x98;
buf[1]=0x66;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x99;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9a;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9b;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xce;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xcf;
buf[1]=0x06;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd0;
buf[1]=0x60;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd1;
buf[1]=0x06;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
#else
//caprure preview daylight 24M 50hz 20-8FPS maxgain:0x70
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x03;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x04;
buf[1]=0x32;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x06;
buf[1]=0x31 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x09;
buf[1]=0x1 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x0a;
buf[1]=0x46;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf0;
buf[1]=0x66;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xf1;
buf[1]=0x0 ;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x90;
buf[1]=0x0c;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x92;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x98;
buf[1]=0x66;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x99;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9a;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x9b;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x01;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xce;
buf[1]=0xc8;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xcf;
buf[1]=0x04;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd0;
buf[1]=0xc8;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xd1;
buf[1]=0x04;
i2c_put_byte_add8(client,buf,2);
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
#endif
break;
}
}
/*************************************************************************
* FUNCTION
* set_SP0A19_param_exposure
*
* DESCRIPTION
* SP0A19 exposure setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED ÁÁ¶ÈµÈ¼¶ µ÷½Ú²ÎÊý
*
*************************************************************************/
void set_SP0A19_param_exposure(struct sp0a19_device *dev,enum camera_exposure_e para)//ÆØ¹âµ÷½Ú
{
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char buf1[2];
unsigned char buf2[2];
switch (para)
{
case EXPOSURE_N4_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0xc0;
break;
case EXPOSURE_N3_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0xd0;
break;
case EXPOSURE_N2_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0xe0;
break;
case EXPOSURE_N1_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0xf0;
break;
case EXPOSURE_0_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0x00;//6a
break;
case EXPOSURE_P1_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0x10;
break;
case EXPOSURE_P2_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0x20;
break;
case EXPOSURE_P3_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0x30;
break;
case EXPOSURE_P4_STEP:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0x40;
break;
default:
buf1[0]=0xfd;
buf1[1]=0x00;
buf2[0]=0xdc;
buf2[1]=0x00;
break;
}
//msleep(300);
i2c_put_byte_add8(client,buf1,2);
i2c_put_byte_add8(client,buf2,2);
}
/*************************************************************************
* FUNCTION
* set_SP0A19_param_effect
*
* DESCRIPTION
* SP0A19 effect setting.
*
* PARAMETERS
* none
*
* RETURNS
* None
*
* GLOBALS AFFECTED ÌØÐ§²ÎÊý
*
*************************************************************************/
void set_SP0A19_param_effect(struct sp0a19_device *dev,enum camera_effect_flip_e para)//ÌØÐ§ÉèÖÃ
{
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char buf[4];
switch (para)
{
case CAM_EFFECT_ENC_NORMAL:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x62;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x63;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x64;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_EFFECT_ENC_GRAYSCALE:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x62;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x63;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x64;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_EFFECT_ENC_SEPIA:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x62;
buf[1]=0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x63;
buf[1]=0xc0;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x64;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_EFFECT_ENC_COLORINV:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x62;
buf[1]=0x04;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x63;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x64;
buf[1]=0x80;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_EFFECT_ENC_SEPIAGREEN:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x62;
buf[1]=0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x63;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x64;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
break;
case CAM_EFFECT_ENC_SEPIABLUE:
buf[0]=0xfd;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x62;
buf[1]=0x10;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x63;
buf[1]=0x20;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x64;
buf[1]=0xf0;
i2c_put_byte_add8(client,buf,2);
break;
default:
break;
}
}
unsigned char v4l_2_sp0a19(int val)
{
int ret=val/0x20;
if(ret<4) return ret*0x20+0x80;
else if(ret<8) return ret*0x20+0x20;
else return 0;
}
static int sp0a19_setting(struct sp0a19_device *dev,int PROP_ID,int value )
{
int ret=0;
unsigned char cur_val;
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
switch(PROP_ID) {
case V4L2_CID_DO_WHITE_BALANCE:
if(sp0a19_qctrl[0].default_value!=value){
sp0a19_qctrl[0].default_value=value;
set_SP0A19_param_wb(dev,value);
printk(KERN_INFO " set camera white_balance=%d. \n ",value);
}
break;
case V4L2_CID_EXPOSURE:
if(sp0a19_qctrl[1].default_value!=value){
sp0a19_qctrl[1].default_value=value;
set_SP0A19_param_exposure(dev,value);
printk(KERN_INFO " set camera exposure=%d. \n ",value);
}
break;
case V4L2_CID_COLORFX:
if(sp0a19_qctrl[2].default_value!=value){
sp0a19_qctrl[2].default_value=value;
set_SP0A19_param_effect(dev,value);
printk(KERN_INFO " set camera effect=%d. \n ",value);
}
break;
case V4L2_CID_WHITENESS:
if(sp0a19_qctrl[3].default_value!=value){
sp0a19_qctrl[3].default_value=value;
SP0A19_set_param_banding(dev,value);
printk(KERN_INFO " set camera banding=%d. \n ",value);
}
break;
case V4L2_CID_BLUE_BALANCE:
if(sp0a19_qctrl[4].default_value!=value){
sp0a19_qctrl[4].default_value=value;
SP0A19_night_mode(dev,value);
printk(KERN_INFO " set camera scene mode=%d. \n ",value);
}
break;
case V4L2_CID_HFLIP: /* set flip on H. */
value = value & 0x3;
if(sp0a19_qctrl[5].default_value!=value){
sp0a19_qctrl[5].default_value=value;
printk(" set camera h filp =%d. \n ",value);
}
break;
case V4L2_CID_VFLIP: /* set flip on V. */
break;
case V4L2_CID_ZOOM_ABSOLUTE:
if(sp0a19_qctrl[7].default_value!=value){
sp0a19_qctrl[7].default_value=value;
//printk(KERN_INFO " set camera zoom mode=%d. \n ",value);
}
break;
case V4L2_CID_ROTATE:
if(sp0a19_qctrl[8].default_value!=value){
sp0a19_qctrl[8].default_value=value;
printk(" set camera rotate =%d. \n ",value);
}
break;
default:
ret=-1;
break;
}
return ret;
}
static void power_down_sp0a19(struct sp0a19_device *dev)
{
struct i2c_client *client = v4l2_get_subdevdata(&dev->sd);
unsigned char buf[4];
buf[0]=0x1a;
buf[1]=0x17;
i2c_put_byte_add8(client,buf,2);
buf[0]=0x25;
buf[1]=0x00;
i2c_put_byte_add8(client,buf,2);
msleep(5);
return;
}
/* ------------------------------------------------------------------
DMA and thread functions
------------------------------------------------------------------*/
#define TSTAMP_MIN_Y 24
#define TSTAMP_MAX_Y (TSTAMP_MIN_Y + 15)
#define TSTAMP_INPUT_X 10
#define TSTAMP_MIN_X (54 + TSTAMP_INPUT_X)
static void sp0a19_fillbuff(struct sp0a19_fh *fh, struct sp0a19_buffer *buf)
{
struct sp0a19_device *dev = fh->dev;
void *vbuf = videobuf_to_vmalloc(&buf->vb);
vm_output_para_t para = {0};
dprintk(dev,1,"%s\n", __func__);
if (!vbuf)
return;
/* 0x18221223 indicate the memory type is MAGIC_VMAL_MEM*/
//para.mirror = sp0a19_qctrl[5].default_value&3;;// not set
para.v4l2_format = fh->fmt->fourcc;
para.v4l2_memory = 0x18221223;
para.zoom = sp0a19_qctrl[7].default_value;
para.vaddr = (unsigned)vbuf;
para.angle =sp0a19_qctrl[8].default_value;
vm_fill_buffer(&buf->vb,¶);
buf->vb.state = VIDEOBUF_DONE;
}
static void sp0a19_thread_tick(struct sp0a19_fh *fh)
{
struct sp0a19_buffer *buf;
struct sp0a19_device *dev = fh->dev;
struct sp0a19_dmaqueue *dma_q = &dev->vidq;
unsigned long flags = 0;
dprintk(dev, 1, "Thread tick\n");
if(!fh->stream_on){
dprintk(dev, 1, "sensor doesn't stream on\n");
return ;
}
spin_lock_irqsave(&dev->slock, flags);
if (list_empty(&dma_q->active)) {
dprintk(dev, 1, "No active queue to serve\n");
goto unlock;
}
buf = list_entry(dma_q->active.next,
struct sp0a19_buffer, vb.queue);
dprintk(dev, 1, "%s\n", __func__);
dprintk(dev, 1, "list entry get buf is %x\n",(unsigned)buf);
if(!(fh->f_flags & O_NONBLOCK)){
/* Nobody is waiting on this buffer, return */
if (!waitqueue_active(&buf->vb.done))
goto unlock;
}
buf->vb.state = VIDEOBUF_ACTIVE;
list_del(&buf->vb.queue);
do_gettimeofday(&buf->vb.ts);
/* Fill buffer */
spin_unlock_irqrestore(&dev->slock, flags);
sp0a19_fillbuff(fh, buf);
dprintk(dev, 1, "filled buffer %p\n", buf);
wake_up(&buf->vb.done);
dprintk(dev, 2, "[%p/%d] wakeup\n", buf, buf->vb. i);
return;
unlock:
spin_unlock_irqrestore(&dev->slock, flags);
return;
}
#define frames_to_ms(frames) \
((frames * WAKE_NUMERATOR * 1000) / WAKE_DENOMINATOR)
static void sp0a19_sleep(struct sp0a19_fh *fh)
{
struct sp0a19_device *dev = fh->dev;
struct sp0a19_dmaqueue *dma_q = &dev->vidq;
DECLARE_WAITQUEUE(wait, current);
dprintk(dev, 1, "%s dma_q=0x%08lx\n", __func__,
(unsigned long)dma_q);
add_wait_queue(&dma_q->wq, &wait);
if (kthread_should_stop())
goto stop_task;
/* Calculate time to wake up */
//timeout = msecs_to_jiffies(frames_to_ms(1));
sp0a19_thread_tick(fh);
schedule_timeout_interruptible(2);
stop_task:
remove_wait_queue(&dma_q->wq, &wait);
try_to_freeze();
}
static int sp0a19_thread(void *data)
{
struct sp0a19_fh *fh = data;
struct sp0a19_device *dev = fh->dev;
dprintk(dev, 1, "thread started\n");
set_freezable();
for (;;) {
sp0a19_sleep(fh);
if (kthread_should_stop())
break;
}
dprintk(dev, 1, "thread: exit\n");
return 0;
}
static int sp0a19_start_thread(struct sp0a19_fh *fh)
{
struct sp0a19_device *dev = fh->dev;
struct sp0a19_dmaqueue *dma_q = &dev->vidq;
dma_q->frame = 0;
dma_q->ini_jiffies = jiffies;
dprintk(dev, 1, "%s\n", __func__);
dma_q->kthread = kthread_run(sp0a19_thread, fh, "sp0a19");
if (IS_ERR(dma_q->kthread)) {
v4l2_err(&dev->v4l2_dev, "kernel_thread() failed\n");
return PTR_ERR(dma_q->kthread);
}
/* Wakes thread */
wake_up_interruptible(&dma_q->wq);
dprintk(dev, 1, "returning from %s\n", __func__);
return 0;
}
static void sp0a19_stop_thread(struct sp0a19_dmaqueue *dma_q)
{
struct sp0a19_device *dev = container_of(dma_q, struct sp0a19_device, vidq);
dprintk(dev, 1, "%s\n", __func__);
/* shutdown control thread */
if (dma_q->kthread) {
kthread_stop(dma_q->kthread);
dma_q->kthread = NULL;
}
}
/* ------------------------------------------------------------------
Videobuf operations
------------------------------------------------------------------*/
static int
buffer_setup(struct videobuf_queue *vq, unsigned int *count, unsigned int *size)
{
struct sp0a19_fh *fh = vq->priv_data;
struct sp0a19_device *dev = fh->dev;
//int bytes = fh->fmt->depth >> 3 ;
*size = fh->width*fh->height*fh->fmt->depth >> 3;
if (0 == *count)
*count = 32;
while (*size * *count > vid_limit * 1024 * 1024)
(*count)--;
dprintk(dev, 1, "%s, count=%d, size=%d\n", __func__,
*count, *size);
return 0;
}
static void free_buffer(struct videobuf_queue *vq, struct sp0a19_buffer *buf)
{
struct sp0a19_fh *fh = vq->priv_data;
struct sp0a19_device *dev = fh->dev;
dprintk(dev, 1, "%s, state: %i\n", __func__, buf->vb.state);
videobuf_waiton(vq, &buf->vb, 0, 0);
if (in_interrupt())
BUG();
videobuf_vmalloc_free(&buf->vb);
dprintk(dev, 1, "free_buffer: freed\n");
buf->vb.state = VIDEOBUF_NEEDS_INIT;
}
#define norm_maxw() 1024
#define norm_maxh() 768
static int
buffer_prepare(struct videobuf_queue *vq, struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct sp0a19_fh *fh = vq->priv_data;
struct sp0a19_device *dev = fh->dev;
struct sp0a19_buffer *buf = container_of(vb, struct sp0a19_buffer, vb);
int rc;
//int bytes = fh->fmt->depth >> 3 ;
dprintk(dev, 1, "%s, field=%d\n", __func__, field);
BUG_ON(NULL == fh->fmt);
if (fh->width < 48 || fh->width > norm_maxw() ||
fh->height < 32 || fh->height > norm_maxh())
return -EINVAL;
buf->vb.size = fh->width*fh->height*fh->fmt->depth >> 3;
if (0 != buf->vb.baddr && buf->vb.bsize < buf->vb.size)
return -EINVAL;
/* These properties only change when queue is idle, see s_fmt */
buf->fmt = fh->fmt;
buf->vb.width = fh->width;
buf->vb.height = fh->height;
buf->vb.field = field;
//precalculate_bars(fh);
if (VIDEOBUF_NEEDS_INIT == buf->vb.state) {
rc = videobuf_iolock(vq, &buf->vb, NULL);
if (rc < 0)
goto fail;
}
buf->vb.state = VIDEOBUF_PREPARED;
return 0;
fail:
free_buffer(vq, buf);
return rc;
}
static void
buffer_queue(struct videobuf_queue *vq, struct videobuf_buffer *vb)
{
struct sp0a19_buffer *buf = container_of(vb, struct sp0a19_buffer, vb);
struct sp0a19_fh *fh = vq->priv_data;
struct sp0a19_device *dev = fh->dev;
struct sp0a19_dmaqueue *vidq = &dev->vidq;
dprintk(dev, 1, "%s\n", __func__);
buf->vb.state = VIDEOBUF_QUEUED;
list_add_tail(&buf->vb.queue, &vidq->active);
}
static void buffer_release(struct videobuf_queue *vq,
struct videobuf_buffer *vb)
{
struct sp0a19_buffer *buf = container_of(vb, struct sp0a19_buffer, vb);
struct sp0a19_fh *fh = vq->priv_data;
struct sp0a19_device *dev = (struct sp0a19_device *)fh->dev;
dprintk(dev, 1, "%s\n", __func__);
free_buffer(vq, buf);
}
static struct videobuf_queue_ops sp0a19_video_qops = {
.buf_setup = buffer_setup,
.buf_prepare = buffer_prepare,
.buf_queue = buffer_queue,
.buf_release = buffer_release,
};
/* ------------------------------------------------------------------
IOCTL vidioc handling
------------------------------------------------------------------*/
static int vidioc_querycap(struct file *file, void *priv,
struct v4l2_capability *cap)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
strcpy(cap->driver, "sp0a19");
strcpy(cap->card, "sp0a19");
strlcpy(cap->bus_info, dev->v4l2_dev.name, sizeof(cap->bus_info));
cap->version = SP0A19_CAMERA_VERSION;
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_STREAMING |
V4L2_CAP_READWRITE;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_fmtdesc *f)
{
struct sp0a19_fmt *fmt;
if (f->index >= ARRAY_SIZE(formats))
return -EINVAL;
fmt = &formats[f->index];
strlcpy(f->description, fmt->name, sizeof(f->description));
f->pixelformat = fmt->fourcc;
return 0;
}
static int vidioc_enum_frameintervals(struct file *file, void *priv,
struct v4l2_frmivalenum *fival)
{
unsigned int k;
if(fival->index > ARRAY_SIZE(sp0a19_frmivalenum))
return -EINVAL;
for(k =0; k< ARRAY_SIZE(sp0a19_frmivalenum); k++)
{
if( (fival->index==sp0a19_frmivalenum[k].index)&&
(fival->pixel_format ==sp0a19_frmivalenum[k].pixel_format )&&
(fival->width=sp0a19_frmivalenum[k].width)&&
(fival->height==sp0a19_frmivalenum[k].height)){
memcpy( fival, &sp0a19_frmivalenum[k], sizeof(struct v4l2_frmivalenum));
return 0;
}
}
return -EINVAL;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct sp0a19_fh *fh = priv;
f->fmt.pix.width = fh->width;
f->fmt.pix.height = fh->height;
f->fmt.pix.field = fh->vb_vidq.field;
f->fmt.pix.pixelformat = fh->fmt->fourcc;
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fh->fmt->depth) >> 3;
f->fmt.pix.sizeimage =
f->fmt.pix.height * f->fmt.pix.bytesperline;
return (0);
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
struct sp0a19_fmt *fmt;
enum v4l2_field field;
unsigned int maxw, maxh;
fmt = get_format(f);
if (!fmt) {
dprintk(dev, 1, "Fourcc format (0x%08x) invalid.\n",
f->fmt.pix.pixelformat);
return -EINVAL;
}
field = f->fmt.pix.field;
if (field == V4L2_FIELD_ANY) {
field = V4L2_FIELD_INTERLACED;
} else if (V4L2_FIELD_INTERLACED != field) {
dprintk(dev, 1, "Field type invalid.\n");
return -EINVAL;
}
maxw = norm_maxw();
maxh = norm_maxh();
f->fmt.pix.field = field;
v4l_bound_align_image(&f->fmt.pix.width, 48, maxw, 2,
&f->fmt.pix.height, 32, maxh, 0, 0);
f->fmt.pix.bytesperline =
(f->fmt.pix.width * fmt->depth) >> 3;
f->fmt.pix.sizeimage =
f->fmt.pix.height * f->fmt.pix.bytesperline;
return 0;
}
/*FIXME: This seems to be generic enough to be at videodev2 */
static int vidioc_s_fmt_vid_cap(struct file *file, void *priv,
struct v4l2_format *f)
{
struct sp0a19_fh *fh = priv;
struct videobuf_queue *q = &fh->vb_vidq;
int ret = vidioc_try_fmt_vid_cap(file, fh, f);
if (ret < 0)
return ret;
mutex_lock(&q->vb_lock);
if (videobuf_queue_is_busy(&fh->vb_vidq)) {
dprintk(fh->dev, 1, "%s queue busy\n", __func__);
ret = -EBUSY;
goto out;
}
fh->fmt = get_format(f);
fh->width = f->fmt.pix.width;
fh->height = f->fmt.pix.height;
fh->vb_vidq.field = f->fmt.pix.field;
fh->type = f->type;
#if 1
if(f->fmt.pix.pixelformat==V4L2_PIX_FMT_RGB24){
sp0a19_set_resolution(fh->dev,fh->height,fh->width);
} else {
sp0a19_set_resolution(fh->dev,fh->height,fh->width);
}
#endif
ret = 0;
out:
mutex_unlock(&q->vb_lock);
return ret;
}
static int vidioc_g_parm(struct file *file, void *priv,
struct v4l2_streamparm *parms)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
struct v4l2_captureparm *cp = &parms->parm.capture;
dprintk(dev,3,"vidioc_g_parm\n");
if (parms->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
memset(cp, 0, sizeof(struct v4l2_captureparm));
cp->capability = V4L2_CAP_TIMEPERFRAME;
cp->timeperframe = sp0a19_frmintervals_active;
printk("g_parm,deno=%d, numerator=%d\n", cp->timeperframe.denominator,
cp->timeperframe.numerator );
return 0;
}
static int vidioc_reqbufs(struct file *file, void *priv,
struct v4l2_requestbuffers *p)
{
struct sp0a19_fh *fh = priv;
return (videobuf_reqbufs(&fh->vb_vidq, p));
}
static int vidioc_querybuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct sp0a19_fh *fh = priv;
return (videobuf_querybuf(&fh->vb_vidq, p));
}
static int vidioc_qbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct sp0a19_fh *fh = priv;
return (videobuf_qbuf(&fh->vb_vidq, p));
}
static int vidioc_dqbuf(struct file *file, void *priv, struct v4l2_buffer *p)
{
struct sp0a19_fh *fh = priv;
return (videobuf_dqbuf(&fh->vb_vidq, p,
file->f_flags & O_NONBLOCK));
}
#ifdef CONFIG_VIDEO_V4L1_COMPAT
static int vidiocgmbuf(struct file *file, void *priv, struct video_mbuf *mbuf)
{
struct sp0a19_fh *fh = priv;
return videobuf_cgmbuf(&fh->vb_vidq, mbuf, 8);
}
#endif
static int vidioc_streamon(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct sp0a19_fh *fh = priv;
vdin_parm_t para;
int ret = 0 ;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (i != fh->type)
return -EINVAL;
memset( ¶, 0, sizeof( para ));
para.port = TVIN_PORT_CAMERA;
para.fmt = TVIN_SIG_FMT_MAX;
para.frame_rate = sp0a19_frmintervals_active.denominator;
para.h_active = sp0a19_h_active;
para.v_active = sp0a19_v_active;
para.hsync_phase = 0;
para.vsync_phase = 1;
para.hs_bp = 0;
para.vs_bp = 2;
para.cfmt = TVIN_YUV422;
para.scan_mode = TVIN_SCAN_MODE_PROGRESSIVE;
para.skip_count = 2; //skip_num
printk("0a19,h=%d, v=%d, frame_rate=%d\n", sp0a19_h_active, sp0a19_v_active, sp0a19_frmintervals_active.denominator);
ret = videobuf_streamon(&fh->vb_vidq);
if(ret == 0){
vops->start_tvin_service(0,¶);
fh->stream_on = 1;
}
return ret;
}
static int vidioc_streamoff(struct file *file, void *priv, enum v4l2_buf_type i)
{
struct sp0a19_fh *fh = priv;
int ret = 0 ;
if (fh->type != V4L2_BUF_TYPE_VIDEO_CAPTURE)
return -EINVAL;
if (i != fh->type)
return -EINVAL;
ret = videobuf_streamoff(&fh->vb_vidq);
if(ret == 0 ){
vops->stop_tvin_service(0);
fh->stream_on = 0;
}
return ret;
}
static int vidioc_enum_framesizes(struct file *file, void *fh,struct v4l2_frmsizeenum *fsize)
{
int ret = 0,i=0;
struct sp0a19_fmt *fmt = NULL;
struct v4l2_frmsize_discrete *frmsize = NULL;
for (i = 0; i < ARRAY_SIZE(formats); i++) {
if (formats[i].fourcc == fsize->pixel_format){
fmt = &formats[i];
break;
}
}
if (fmt == NULL)
return -EINVAL;
if ((fmt->fourcc == V4L2_PIX_FMT_NV21)
||(fmt->fourcc == V4L2_PIX_FMT_NV12)
||(fmt->fourcc == V4L2_PIX_FMT_YUV420)
||(fmt->fourcc == V4L2_PIX_FMT_YVU420)
){
if (fsize->index >= ARRAY_SIZE(sp0a19_prev_resolution))
return -EINVAL;
frmsize = &sp0a19_prev_resolution[fsize->index];
fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
fsize->discrete.width = frmsize->width;
fsize->discrete.height = frmsize->height;
}
else if(fmt->fourcc == V4L2_PIX_FMT_RGB24){
if (fsize->index >= ARRAY_SIZE(sp0a19_pic_resolution))
return -EINVAL;
frmsize = &sp0a19_pic_resolution[fsize->index];
fsize->type = V4L2_FRMSIZE_TYPE_DISCRETE;
fsize->discrete.width = frmsize->width;
fsize->discrete.height = frmsize->height;
}
return ret;
}
static int vidioc_s_std(struct file *file, void *priv, v4l2_std_id *i)
{
return 0;
}
/* only one input in this sample driver */
static int vidioc_enum_input(struct file *file, void *priv,
struct v4l2_input *inp)
{
//if (inp->index >= NUM_INPUTS)
//return -EINVAL;
inp->type = V4L2_INPUT_TYPE_CAMERA;
inp->std = V4L2_STD_525_60;
sprintf(inp->name, "Camera %u", inp->index);
return (0);
}
static int vidioc_g_input(struct file *file, void *priv, unsigned int *i)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
*i = dev->input;
return (0);
}
static int vidioc_s_input(struct file *file, void *priv, unsigned int i)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
//if (i >= NUM_INPUTS)
//return -EINVAL;
dev->input = i;
//precalculate_bars(fh);
return (0);
}
/* --- controls ---------------------------------------------- */
static int vidioc_queryctrl(struct file *file, void *priv,
struct v4l2_queryctrl *qc)
{
int i;
for (i = 0; i < ARRAY_SIZE(sp0a19_qctrl); i++)
if (qc->id && qc->id == sp0a19_qctrl[i].id) {
memcpy(qc, &(sp0a19_qctrl[i]),
sizeof(*qc));
return (0);
}
return -EINVAL;
}
static int vidioc_g_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
int i;
for (i = 0; i < ARRAY_SIZE(sp0a19_qctrl); i++)
if (ctrl->id == sp0a19_qctrl[i].id) {
ctrl->value = dev->qctl_regs[i];
return 0;
}
return -EINVAL;
}
static int vidioc_s_ctrl(struct file *file, void *priv,
struct v4l2_control *ctrl)
{
struct sp0a19_fh *fh = priv;
struct sp0a19_device *dev = fh->dev;
int i;
for (i = 0; i < ARRAY_SIZE(sp0a19_qctrl); i++)
if (ctrl->id == sp0a19_qctrl[i].id) {
if (ctrl->value < sp0a19_qctrl[i].minimum ||
ctrl->value > sp0a19_qctrl[i].maximum ||
sp0a19_setting(dev,ctrl->id,ctrl->value)<0) {
return -ERANGE;
}
dev->qctl_regs[i] = ctrl->value;
return 0;
}
return -EINVAL;
}
/* ------------------------------------------------------------------
File operations for the device
------------------------------------------------------------------*/
static int sp0a19_open(struct file *file)
{
struct sp0a19_device *dev = video_drvdata(file);
struct sp0a19_fh *fh = NULL;
int retval = 0;
#if CONFIG_CMA
retval = vm_init_buf(16*SZ_1M);
if(retval <0)
return -1;
#endif
#if MESON_CPU_TYPE >= MESON_CPU_TYPE_MESON6
switch_mod_gate_by_name("ge2d", 1);
#endif
aml_cam_init(&dev->cam_info);
SP0A19_init_regs(dev);
msleep(100);//40
mutex_lock(&dev->mutex);
dev->users++;
if (dev->users > 1) {
dev->users--;
mutex_unlock(&dev->mutex);
return -EBUSY;
}
dprintk(dev, 1, "open %s type=%s users=%d\n",
video_device_node_name(dev->vdev),
v4l2_type_names[V4L2_BUF_TYPE_VIDEO_CAPTURE], dev->users);
/* init video dma queues */
INIT_LIST_HEAD(&dev->vidq.active);
init_waitqueue_head(&dev->vidq.wq);
spin_lock_init(&dev->slock);
/* allocate + initialize per filehandle data */
fh = kzalloc(sizeof(*fh), GFP_KERNEL);
if (NULL == fh) {
dev->users--;
retval = -ENOMEM;
}
mutex_unlock(&dev->mutex);
if (retval)
return retval;
wake_lock(&(dev->wake_lock));
file->private_data = fh;
fh->dev = dev;
fh->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fh->fmt = &formats[0];
fh->width = 640;
fh->height = 480;
fh->stream_on = 0 ;
fh->f_flags = file->f_flags;
/* Resets frame counters */
dev->jiffies = jiffies;
// TVIN_SIG_FMT_CAMERA_640X480P_30Hz,
// TVIN_SIG_FMT_CAMERA_800X600P_30Hz,
// TVIN_SIG_FMT_CAMERA_1024X768P_30Hz, // 190
// TVIN_SIG_FMT_CAMERA_1920X1080P_30Hz,
// TVIN_SIG_FMT_CAMERA_1280X720P_30Hz,
videobuf_queue_vmalloc_init(&fh->vb_vidq, &sp0a19_video_qops,
NULL, &dev->slock, fh->type, V4L2_FIELD_INTERLACED,
sizeof(struct sp0a19_buffer), fh,NULL);
sp0a19_start_thread(fh);
return 0;
}
static ssize_t
sp0a19_read(struct file *file, char __user *data, size_t count, loff_t *ppos)
{
struct sp0a19_fh *fh = file->private_data;
if (fh->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
return videobuf_read_stream(&fh->vb_vidq, data, count, ppos, 0,
file->f_flags & O_NONBLOCK);
}
return 0;
}
static unsigned int
sp0a19_poll(struct file *file, struct poll_table_struct *wait)
{
struct sp0a19_fh *fh = file->private_data;
struct sp0a19_device *dev = fh->dev;
struct videobuf_queue *q = &fh->vb_vidq;
dprintk(dev, 1, "%s\n", __func__);
if (V4L2_BUF_TYPE_VIDEO_CAPTURE != fh->type)
return POLLERR;
return videobuf_poll_stream(file, q, wait);
}
static int sp0a19_close(struct file *file)
{
struct sp0a19_fh *fh = file->private_data;
struct sp0a19_device *dev = fh->dev;
struct sp0a19_dmaqueue *vidq = &dev->vidq;
struct video_device *vdev = video_devdata(file);
sp0a19_have_open=0;
sp0a19_stop_thread(vidq);
videobuf_stop(&fh->vb_vidq);
if(fh->stream_on){
vops->stop_tvin_service(0);
}
videobuf_mmap_free(&fh->vb_vidq);
kfree(fh);
mutex_lock(&dev->mutex);
dev->users--;
mutex_unlock(&dev->mutex);
dprintk(dev, 1, "close called (dev=%s, users=%d)\n",
video_device_node_name(vdev), dev->users);
#if 1
sp0a19_qctrl[0].default_value=0;
sp0a19_qctrl[1].default_value=4;
sp0a19_qctrl[2].default_value=0;
sp0a19_qctrl[3].default_value=0;
sp0a19_qctrl[4].default_value=0;
sp0a19_frmintervals_active.numerator = 1;
sp0a19_frmintervals_active.denominator = 15;
//power_down_sp0a19(dev);
#endif
aml_cam_uninit(&dev->cam_info);
#if MESON_CPU_TYPE >= MESON_CPU_TYPE_MESON6
switch_mod_gate_by_name("ge2d", 0);
#endif
wake_unlock(&(dev->wake_lock));
#ifdef CONFIG_CMA
vm_deinit_buf();
#endif
return 0;
}
static int sp0a19_mmap(struct file *file, struct vm_area_struct *vma)
{
struct sp0a19_fh *fh = file->private_data;
struct sp0a19_device *dev = fh->dev;
int ret;
dprintk(dev, 1, "mmap called, vma=0x%08lx\n", (unsigned long)vma);
ret = videobuf_mmap_mapper(&fh->vb_vidq, vma);
dprintk(dev, 1, "vma start=0x%08lx, size=%ld, ret=%d\n",
(unsigned long)vma->vm_start,
(unsigned long)vma->vm_end-(unsigned long)vma->vm_start,
ret);
return ret;
}
static const struct v4l2_file_operations sp0a19_fops = {
.owner = THIS_MODULE,
.open = sp0a19_open,
.release = sp0a19_close,
.read = sp0a19_read,
.poll = sp0a19_poll,
.ioctl = video_ioctl2, /* V4L2 ioctl handler */
.mmap = sp0a19_mmap,
};
static const struct v4l2_ioctl_ops sp0a19_ioctl_ops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_s_std = vidioc_s_std,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_querymenu = vidioc_querymenu,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_enum_framesizes = vidioc_enum_framesizes,
.vidioc_g_parm = vidioc_g_parm,
.vidioc_enum_frameintervals = vidioc_enum_frameintervals,
#ifdef CONFIG_VIDEO_V4L1_COMPAT
.vidiocgmbuf = vidiocgmbuf,
#endif
};
static struct video_device sp0a19_template = {
.name = "sp0a19_v4l",
.fops = &sp0a19_fops,
.ioctl_ops = &sp0a19_ioctl_ops,
.release = video_device_release,
.tvnorms = V4L2_STD_525_60,
.current_norm = V4L2_STD_NTSC_M,
};
static int sp0a19_g_chip_ident(struct v4l2_subdev *sd, struct v4l2_dbg_chip_ident *chip)
{
struct i2c_client *client = v4l2_get_subdevdata(sd);
return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_SP0A19, 0);
//return v4l2_chip_ident_i2c_client(client, chip, V4L2_IDENT_GT2005, 0);
}
static const struct v4l2_subdev_core_ops sp0a19_core_ops = {
.g_chip_ident = sp0a19_g_chip_ident,
};
static const struct v4l2_subdev_ops sp0a19_ops = {
.core = &sp0a19_core_ops,
};
static int sp0a19_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
aml_cam_info_t* plat_dat;
int err;
struct sp0a19_device *t;
struct v4l2_subdev *sd;
vops = get_vdin_v4l2_ops();
v4l_info(client, "chip found @ 0x%x (%s)\n",
client->addr << 1, client->adapter->name);
t = kzalloc(sizeof(*t), GFP_KERNEL);
if (t == NULL)
return -ENOMEM;
sd = &t->sd;
v4l2_i2c_subdev_init(sd, client, &sp0a19_ops);
plat_dat = (aml_cam_info_t*)client->dev.platform_data;
/* Now create a video4linux device */
mutex_init(&t->mutex);
/* Now create a video4linux device */
t->vdev = video_device_alloc();
if (t->vdev == NULL) {
kfree(t);
kfree(client);
return -ENOMEM;
}
memcpy(t->vdev, &sp0a19_template, sizeof(*t->vdev));
video_set_drvdata(t->vdev, t);
wake_lock_init(&(t->wake_lock),WAKE_LOCK_SUSPEND, "sp0a19");
/* Register it */
if (plat_dat) {
memcpy(&t->cam_info, plat_dat, sizeof(aml_cam_info_t));
if (plat_dat->front_back >=0)
video_nr = plat_dat->front_back;
} else {
printk("camera sp0a19: have no platform data\n");
kfree(t);
kfree(client);
return -1;
}
err = video_register_device(t->vdev, VFL_TYPE_GRABBER, video_nr);
if (err < 0) {
video_device_release(t->vdev);
kfree(t);
return err;
}
return 0;
}
static int sp0a19_remove(struct i2c_client *client)
{
struct v4l2_subdev *sd = i2c_get_clientdata(client);
struct sp0a19_device *t = to_dev(sd);
video_unregister_device(t->vdev);
v4l2_device_unregister_subdev(sd);
wake_lock_destroy(&(t->wake_lock));
kfree(t);
return 0;
}
static const struct i2c_device_id sp0a19_id[] = {
{ "sp0a19", 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, sp0a19_id);
static struct i2c_driver sp0a19_i2c_driver = {
.driver = {
.name = "sp0a19",
},
.probe = sp0a19_probe,
.remove = sp0a19_remove,
.id_table = sp0a19_id,
};
module_i2c_driver(sp0a19_i2c_driver);
| jjm2473/AMLOGIC_M8 | drivers/amlogic/camera/sp0a19.c | C | gpl-2.0 | 70,820 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<title>LibOFX: ofx_container_security.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<link href="navtree.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="navtree.js"></script>
<script type="text/javascript" src="resize.js"></script>
<script type="text/javascript">
$(document).ready(initResizable);
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<!-- Generated by Doxygen 1.7.3 -->
<div id="top">
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td style="padding-left: 0.5em;">
<div id="projectname">LibOFX</div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="navrow1" class="tabs">
<ul class="tablist">
<li><a href="index.html"><span>Main Page</span></a></li>
<li><a href="namespaces.html"><span>Namespaces</span></a></li>
<li><a href="annotated.html"><span>Data Structures</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
</ul>
</div>
<div id="navrow2" class="tabs2">
<ul class="tablist">
<li><a href="files.html"><span>File List</span></a></li>
<li><a href="globals.html"><span>Globals</span></a></li>
</ul>
</div>
</div>
<div id="side-nav" class="ui-resizable side-nav-resizable">
<div id="nav-tree">
<div id="nav-tree-contents">
</div>
</div>
<div id="splitbar" style="-moz-user-select:none;"
class="ui-resizable-handle">
</div>
</div>
<script type="text/javascript">
initNavTree('fx-0_89_84_2lib_2ofx__container__security_8cpp.html','');
</script>
<div id="doc-content">
<div class="header">
<div class="summary">
<a href="#var-members">Variables</a> </div>
<div class="headertitle">
<h1>ofx_container_security.cpp File Reference</h1> </div>
</div>
<div class="contents">
<p>Implementation of <a class="el" href="classOfxSecurityContainer.html" title="Represents a security, such as a stock or bond.">OfxSecurityContainer</a> for stocks, bonds, mutual funds, etc.
<a href="#_details">More...</a></p>
<p><a href="fx-0_89_84_2lib_2ofx__container__security_8cpp_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr><td colspan="2"><h2><a name="var-members"></a>
Variables</h2></td></tr>
<tr><td class="memItemLeft" align="right" valign="top"><a class="anchor" id="a759a7d80c051f4f1adc2abae56002100"></a><!-- doxytag: member="fx-0.9.4/lib/ofx_container_security.cpp::MainContainer" ref="a759a7d80c051f4f1adc2abae56002100" args="" -->
<a class="el" href="classOfxMainContainer.html">OfxMainContainer</a> * </td><td class="memItemRight" valign="bottom"><b>MainContainer</b></td></tr>
</table>
<hr/><a name="_details"></a><h2>Detailed Description</h2>
<div class="textblock"><p>Implementation of <a class="el" href="classOfxSecurityContainer.html" title="Represents a security, such as a stock or bond.">OfxSecurityContainer</a> for stocks, bonds, mutual funds, etc. </p>
<p>Definition in file <a class="el" href="fx-0_89_84_2lib_2ofx__container__security_8cpp_source.html">fx-0.9.4/lib/ofx_container_security.cpp</a>.</p>
</div></div>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="fx-0_89_84_2lib_2ofx__container__security_8cpp.html">ofx_container_security.cpp</a> </li>
<li class="footer">Generated on Mon Apr 18 2011 18:09:44 for LibOFX by 
<a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </li>
</ul>
</div>
</body>
</html>
| bdonlan/libofx | doc/html/fx-0_89_84_2lib_2ofx__container__security_8cpp.html | HTML | gpl-2.0 | 3,917 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>Source code</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<div class="sourceContainer">
<pre><span class="sourceLineNo">001</span>/* ===========================================================<a name="line.1"></a>
<span class="sourceLineNo">002</span> * JFreeChart : a free chart library for the Java(tm) platform<a name="line.2"></a>
<span class="sourceLineNo">003</span> * ===========================================================<a name="line.3"></a>
<span class="sourceLineNo">004</span> *<a name="line.4"></a>
<span class="sourceLineNo">005</span> * (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.<a name="line.5"></a>
<span class="sourceLineNo">006</span> *<a name="line.6"></a>
<span class="sourceLineNo">007</span> * Project Info: http://www.jfree.org/jfreechart/index.html<a name="line.7"></a>
<span class="sourceLineNo">008</span> *<a name="line.8"></a>
<span class="sourceLineNo">009</span> * This library is free software; you can redistribute it and/or modify it<a name="line.9"></a>
<span class="sourceLineNo">010</span> * under the terms of the GNU Lesser General Public License as published by<a name="line.10"></a>
<span class="sourceLineNo">011</span> * the Free Software Foundation; either version 2.1 of the License, or<a name="line.11"></a>
<span class="sourceLineNo">012</span> * (at your option) any later version.<a name="line.12"></a>
<span class="sourceLineNo">013</span> *<a name="line.13"></a>
<span class="sourceLineNo">014</span> * This library is distributed in the hope that it will be useful, but<a name="line.14"></a>
<span class="sourceLineNo">015</span> * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY<a name="line.15"></a>
<span class="sourceLineNo">016</span> * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public<a name="line.16"></a>
<span class="sourceLineNo">017</span> * License for more details.<a name="line.17"></a>
<span class="sourceLineNo">018</span> *<a name="line.18"></a>
<span class="sourceLineNo">019</span> * You should have received a copy of the GNU Lesser General Public<a name="line.19"></a>
<span class="sourceLineNo">020</span> * License along with this library; if not, write to the Free Software<a name="line.20"></a>
<span class="sourceLineNo">021</span> * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,<a name="line.21"></a>
<span class="sourceLineNo">022</span> * USA.<a name="line.22"></a>
<span class="sourceLineNo">023</span> *<a name="line.23"></a>
<span class="sourceLineNo">024</span> * [Oracle and Java are registered trademarks of Oracle and/or its affiliates. <a name="line.24"></a>
<span class="sourceLineNo">025</span> * Other names may be trademarks of their respective owners.]<a name="line.25"></a>
<span class="sourceLineNo">026</span> *<a name="line.26"></a>
<span class="sourceLineNo">027</span> * ------------------------------<a name="line.27"></a>
<span class="sourceLineNo">028</span> * MultiValueCategoryDataset.java<a name="line.28"></a>
<span class="sourceLineNo">029</span> * ------------------------------<a name="line.29"></a>
<span class="sourceLineNo">030</span> * (C) Copyright 2007, 2008, by David Forslund and Contributors.<a name="line.30"></a>
<span class="sourceLineNo">031</span> *<a name="line.31"></a>
<span class="sourceLineNo">032</span> * Original Author: David Forslund;<a name="line.32"></a>
<span class="sourceLineNo">033</span> * Contributor(s): David Gilbert (for Object Refinery Limited);<a name="line.33"></a>
<span class="sourceLineNo">034</span> *<a name="line.34"></a>
<span class="sourceLineNo">035</span> * Changes<a name="line.35"></a>
<span class="sourceLineNo">036</span> * -------<a name="line.36"></a>
<span class="sourceLineNo">037</span> * 08-Oct-2007 : Version 1, see patch 1780779 (DG);<a name="line.37"></a>
<span class="sourceLineNo">038</span> *<a name="line.38"></a>
<span class="sourceLineNo">039</span> */<a name="line.39"></a>
<span class="sourceLineNo">040</span><a name="line.40"></a>
<span class="sourceLineNo">041</span>package org.jfree.data.statistics;<a name="line.41"></a>
<span class="sourceLineNo">042</span><a name="line.42"></a>
<span class="sourceLineNo">043</span>import java.util.List;<a name="line.43"></a>
<span class="sourceLineNo">044</span><a name="line.44"></a>
<span class="sourceLineNo">045</span>import org.jfree.data.category.CategoryDataset;<a name="line.45"></a>
<span class="sourceLineNo">046</span><a name="line.46"></a>
<span class="sourceLineNo">047</span>/**<a name="line.47"></a>
<span class="sourceLineNo">048</span> * A category dataset that defines multiple values for each item.<a name="line.48"></a>
<span class="sourceLineNo">049</span> *<a name="line.49"></a>
<span class="sourceLineNo">050</span> * @since 1.0.7<a name="line.50"></a>
<span class="sourceLineNo">051</span> */<a name="line.51"></a>
<span class="sourceLineNo">052</span>public interface MultiValueCategoryDataset extends CategoryDataset {<a name="line.52"></a>
<span class="sourceLineNo">053</span><a name="line.53"></a>
<span class="sourceLineNo">054</span> /**<a name="line.54"></a>
<span class="sourceLineNo">055</span> * Returns a list (possibly empty) of the values for the specified item.<a name="line.55"></a>
<span class="sourceLineNo">056</span> * The returned list should be unmodifiable.<a name="line.56"></a>
<span class="sourceLineNo">057</span> *<a name="line.57"></a>
<span class="sourceLineNo">058</span> * @param row the row index (zero-based).<a name="line.58"></a>
<span class="sourceLineNo">059</span> * @param column the column index (zero-based).<a name="line.59"></a>
<span class="sourceLineNo">060</span> *<a name="line.60"></a>
<span class="sourceLineNo">061</span> * @return The list of values.<a name="line.61"></a>
<span class="sourceLineNo">062</span> */<a name="line.62"></a>
<span class="sourceLineNo">063</span> public List getValues(int row, int column);<a name="line.63"></a>
<span class="sourceLineNo">064</span><a name="line.64"></a>
<span class="sourceLineNo">065</span> /**<a name="line.65"></a>
<span class="sourceLineNo">066</span> * Returns a list (possibly empty) of the values for the specified item.<a name="line.66"></a>
<span class="sourceLineNo">067</span> * The returned list should be unmodifiable.<a name="line.67"></a>
<span class="sourceLineNo">068</span> *<a name="line.68"></a>
<span class="sourceLineNo">069</span> * @param rowKey the row key (<code>null</code> not permitted).<a name="line.69"></a>
<span class="sourceLineNo">070</span> * @param columnKey the column key (<code>null</code> not permitted).<a name="line.70"></a>
<span class="sourceLineNo">071</span> *<a name="line.71"></a>
<span class="sourceLineNo">072</span> * @return The list of values.<a name="line.72"></a>
<span class="sourceLineNo">073</span> */<a name="line.73"></a>
<span class="sourceLineNo">074</span> public List getValues(Comparable rowKey, Comparable columnKey);<a name="line.74"></a>
<span class="sourceLineNo">075</span><a name="line.75"></a>
<span class="sourceLineNo">076</span>}<a name="line.76"></a>
</pre>
</div>
</body>
</html>
| jclazzarim/TrabalhoPID2013 | Trabalho PID2013/libs/jfreechart-1.0.14-javadocs/src-html/org/jfree/data/statistics/MultiValueCategoryDataset.html | HTML | gpl-2.0 | 7,485 |
/*
* Copyright (C) 2008-2014 TrinityCore <http://www.trinitycore.org/>
* Copyright (C) 2011-2015 ArkCORE <http://www.arkania.net/>
* Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_MOTIONMASTER_H
#define TRINITY_MOTIONMASTER_H
#include "Common.h"
#include <vector>
#include "SharedDefines.h"
#include "Object.h"
class MovementGenerator;
class Unit;
class PathGenerator;
// Creature Entry ID used for waypoints show, visible only for GMs
#define VISUAL_WAYPOINT 1
// values 0 ... MAX_DB_MOTION_TYPE-1 used in DB
enum MovementGeneratorType
{
IDLE_MOTION_TYPE = 0, // IdleMovementGenerator.h
RANDOM_MOTION_TYPE = 1, // RandomMovementGenerator.h
WAYPOINT_MOTION_TYPE = 2, // WaypointMovementGenerator.h
MAX_DB_MOTION_TYPE = 3, // *** this and below motion types can't be set in DB.
ANIMAL_RANDOM_MOTION_TYPE = MAX_DB_MOTION_TYPE, // AnimalRandomMovementGenerator.h
CONFUSED_MOTION_TYPE = 4, // ConfusedMovementGenerator.h
CHASE_MOTION_TYPE = 5, // TargetedMovementGenerator.h
HOME_MOTION_TYPE = 6, // HomeMovementGenerator.h
FLIGHT_MOTION_TYPE = 7, // WaypointMovementGenerator.h
POINT_MOTION_TYPE = 8, // PointMovementGenerator.h
FLEEING_MOTION_TYPE = 9, // FleeingMovementGenerator.h
DISTRACT_MOTION_TYPE = 10, // IdleMovementGenerator.h
ASSISTANCE_MOTION_TYPE= 11, // PointMovementGenerator.h (first part of flee for assistance)
ASSISTANCE_DISTRACT_MOTION_TYPE = 12, // IdleMovementGenerator.h (second part of flee for assistance)
TIMED_FLEEING_MOTION_TYPE = 13, // FleeingMovementGenerator.h (alt.second part of flee for assistance)
FOLLOW_MOTION_TYPE = 14,
ROTATE_MOTION_TYPE = 15,
EFFECT_MOTION_TYPE = 16,
NULL_MOTION_TYPE = 17
};
enum MovementSlot
{
MOTION_SLOT_IDLE,
MOTION_SLOT_ACTIVE,
MOTION_SLOT_CONTROLLED,
MAX_MOTION_SLOT
};
enum MMCleanFlag
{
MMCF_NONE = 0,
MMCF_UPDATE = 1, // Clear or Expire called from update
MMCF_RESET = 2 // Flag if need top()->Reset()
};
enum RotateDirection
{
ROTATE_DIRECTION_LEFT,
ROTATE_DIRECTION_RIGHT
};
// assume it is 25 yard per 0.6 second
#define SPEED_CHARGE 42.0f
class MotionMaster //: private std::stack<MovementGenerator *>
{
private:
//typedef std::stack<MovementGenerator *> Impl;
typedef MovementGenerator* _Ty;
void pop()
{
if (empty())
return;
Impl[_top] = NULL;
while (!empty() && !top())
--_top;
}
void push(_Ty _Val) { ++_top; Impl[_top] = _Val; }
bool needInitTop() const
{
if (empty())
return false;
return _needInit[_top];
}
void InitTop();
public:
explicit MotionMaster(Unit* unit) : _expList(NULL), _top(-1), _owner(unit), _cleanFlag(MMCF_NONE)
{
for (uint8 i = 0; i < MAX_MOTION_SLOT; ++i)
{
Impl[i] = NULL;
_needInit[i] = true;
}
}
~MotionMaster();
void Initialize();
void InitDefault();
bool empty() const { return (_top < 0); }
int size() const { return _top + 1; }
_Ty top() const
{
ASSERT(!empty());
return Impl[_top];
}
_Ty GetMotionSlot(int slot) const
{
ASSERT(slot >= 0);
return Impl[slot];
}
void DirectDelete(_Ty curr);
void DelayedDelete(_Ty curr);
void UpdateMotion(uint32 diff);
void Clear(bool reset = true)
{
if (_cleanFlag & MMCF_UPDATE)
{
if (reset)
_cleanFlag |= MMCF_RESET;
else
_cleanFlag &= ~MMCF_RESET;
DelayedClean();
}
else
DirectClean(reset);
}
void MovementExpired(bool reset = true)
{
if (_cleanFlag & MMCF_UPDATE)
{
if (reset)
_cleanFlag |= MMCF_RESET;
else
_cleanFlag &= ~MMCF_RESET;
DelayedExpire();
}
else
DirectExpire(reset);
}
void MoveIdle();
void MoveTargetedHome();
void MoveRandom(float spawndist = 0.0f);
void MoveFollow(Unit* target, float dist, float angle, MovementSlot slot = MOTION_SLOT_ACTIVE);
void MoveChase(Unit* target, float dist = 0.0f, float angle = 0.0f);
void MoveConfused();
void MoveFleeing(Unit* enemy, uint32 time = 0);
void MovePoint(uint32 id, Position const& pos, bool generatePath = true)
{ MovePoint(id, pos.m_positionX, pos.m_positionY, pos.m_positionZ, generatePath); }
void MovePoint(uint32 id, float x, float y, float z, bool generatePath = true);
// These two movement types should only be used with creatures having landing/takeoff animations
void MoveLand(uint32 id, Position const& pos);
void MoveTakeoff(uint32 id, Position const& pos);
void MoveCharge(float x, float y, float z, float speed = SPEED_CHARGE, uint32 id = EVENT_CHARGE, bool generatePath = false);
void MoveCharge(PathGenerator const& path);
void MoveKnockbackFrom(float srcX, float srcY, float speedXY, float speedZ);
void MoveJumpTo(float angle, float speedXY, float speedZ);
void MoveJump(Position const& pos, float speedXY, float speedZ, uint32 id = EVENT_JUMP)
{ MoveJump(pos.m_positionX, pos.m_positionY, pos.m_positionZ, speedXY, speedZ, id); };
void MoveJump(float x, float y, float z, float speedXY, float speedZ, uint32 id = EVENT_JUMP);
void MoveFall(uint32 id = 0);
void MoveSeekAssistance(float x, float y, float z);
void MoveSeekAssistanceDistract(uint32 timer);
void MoveTaxiFlight(uint32 path, uint32 pathnode);
void MoveDistract(uint32 time);
void MovePath(uint32 path_id, bool repeatable);
void MoveRotate(uint32 time, RotateDirection direction);
MovementGeneratorType GetCurrentMovementGeneratorType() const;
MovementGeneratorType GetMotionSlotType(int slot) const;
void propagateSpeedChange();
bool GetDestination(float &x, float &y, float &z);
private:
void Mutate(MovementGenerator *m, MovementSlot slot); // use Move* functions instead
void DirectClean(bool reset);
void DelayedClean();
void DirectExpire(bool reset);
void DelayedExpire();
typedef std::vector<_Ty> ExpireList;
ExpireList* _expList;
_Ty Impl[MAX_MOTION_SLOT];
int _top;
Unit* _owner;
bool _needInit[MAX_MOTION_SLOT];
uint8 _cleanFlag;
};
#endif
| sunshitwowsucks/ArkCORE-NG | src/server/game/Movement/MotionMaster.h | C | gpl-2.0 | 7,972 |
#####################################################################
#
# OpenBib::Authenticator::Backend::LDAP
#
# Dieses File ist (C) 2019 Oliver Flimm <flimm@openbib.org>
#
# Dieses Programm ist freie Software. Sie koennen es unter
# den Bedingungen der GNU General Public License, wie von der
# Free Software Foundation herausgegeben, weitergeben und/oder
# modifizieren, entweder unter Version 2 der Lizenz oder (wenn
# Sie es wuenschen) jeder spaeteren Version.
#
# Die Veroeffentlichung dieses Programms erfolgt in der
# Hoffnung, dass es Ihnen von Nutzen sein wird, aber OHNE JEDE
# GEWAEHRLEISTUNG - sogar ohne die implizite Gewaehrleistung
# der MARKTREIFE oder der EIGNUNG FUER EINEN BESTIMMTEN ZWECK.
# Details finden Sie in der GNU General Public License.
#
# Sie sollten eine Kopie der GNU General Public License zusammen
# mit diesem Programm erhalten haben. Falls nicht, schreiben Sie
# an die Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
# MA 02139, USA.
#
#####################################################################
package OpenBib::Authenticator::Backend::LDAP;
use strict;
use warnings;
no warnings 'redefine';
use utf8;
use base qw(OpenBib::Authenticator);
use Cache::Memcached::Fast;
use Encode qw(decode_utf8 encode_utf8);
use Log::Log4perl qw(get_logger :levels);
use MLDBM qw(DB_File Storable);
use Net::LDAPS;
use SOAP::Lite;
use Storable ();
use YAML::Syck;
use OpenBib::Config;
use OpenBib::Config::File;
sub authenticate {
my ($self,$arg_ref) = @_;
# Set defaults
my $viewname = exists $arg_ref->{viewname}
? $arg_ref->{viewname} : undef;
my $username = exists $arg_ref->{username}
? $arg_ref->{username} : undef;
my $password = exists $arg_ref->{password}
? $arg_ref->{password} : undef;
# Log4perl logger erzeugen
my $logger = get_logger();
my ($userid,$viewid) = (0,0);
my $config = $self->get_config;
eval {
$viewid = $config->get_viewinfo->single({ viewname => $viewname })->id;
};
if ($@){
$logger->error("No Viewid found: ".$@);
return $userid;
}
my $authenticator_config;
eval {
$authenticator_config = $config->{authenticator}{ldap}{$self->get('name')};
};
if ($logger->is_debug){
$logger->debug("No config found for ".$self->get('name'));
}
return 0 unless ($authenticator_config);
my @ldap_parameters = ($authenticator_config->{hostname});
foreach my $parameter ('scheme','port','verify','timeout','onerror','cafile'){
push @ldap_parameters, ($parameter,$authenticator_config->{$parameter}) if ($authenticator_config->{$parameter});
}
if ($logger->is_debug){
$logger->debug("Using Parameters ".YAML::Dump(\@ldap_parameters));
}
my $ldaps ;
eval {
$ldaps = Net::LDAPS->new(@ldap_parameters);
};
if ($@){
$logger->error("LDAP-Fehler: ".$@);
return 0;
}
my $success = 0;
if (defined $ldaps) {
my $admindn = $authenticator_config->{admindn};
my $adminpw = $authenticator_config->{adminpw};
my $mesg = $ldaps->bind(
$admindn,
password => "$adminpw"
);
if ($mesg && $mesg->code() == 0){
if ($logger->is_debug){
$logger->debug("Authenticator LDAP: OK");
$logger->debug("Returned: ".YAML::Dump($mesg));
}
my $result = $ldaps->search(
base => "",
filter => "(dn=$userdn)",
);
if ($result && $result->code){
$logger->error("Error searching userdn $userdn: ".$result->error );
}
if ($result){
foreach my $entry ($result->entries) {
$logger->debug(YAML::Dump($entry));
}
}
$success = 1;
}
else {
$logger->debug("Received error ".$mesg->code().": ".$mesg->error());
}
}
else {
$logger->error("LDAPS object NOT created");
return 0;
}
$logger->debug("Authentication via LDAP done");
if (!$success) {
return -2;
}
# Gegebenenfalls Benutzer lokal eintragen
$logger->debug("Get/Save new user");
my $user = new OpenBib::User;
# Eintragen, wenn noch nicht existent
# OLWS-Kennungen werden NICHT an einen View gebunden, damit mit der gleichen Kennung verschiedene lokale Bibliothekssysteme genutzt werden koennen - spezifisch fuer die Universitaet zu Koeln
if (!$user->user_exists_in_view({ username => $username, authenticatorid => $self->get('id'), viewid => $viewid })) {
# Neuen Satz eintragen
$userid = $user->add({
username => $username,
hashed_password => undef,
authenticatorid => $self->get('id'),
viewid => $viewid,
});
$logger->debug("User added with new id $userid");
}
else {
my $local_user = $config->get_schema->resultset('Userinfo')->search_rs(
{
username => $username,
viewid => $viewid,
authenticatorid => $self->get('id'),
},
{
select => ['id'],
as => ['thisid'],
}
)->first;
if ($local_user){
$userid = $local_user->get_column('thisid');
}
}
return $userid;
}
1;
__END__
=head1 NAME
OpenBib::Authenticator::Backend::LDAP - Backend zur Authentifizierung an der Eigenen Nutzerdatenbank nach Selbstregistrierung
=head1 DESCRIPTION
Dieses Backend stellt die Methode authenticate zur Authentifizierung eines Nutzer an der lokalen Nutzerdatenbank bereit
=head1 SYNOPSIS
use OpenBib::Authenticator::Factory;
my $authenticator = OpenBib::Authenticator::Factory->create_authenticator(1);
my $userid = $authenticator->authenticate({ viewname => 'kug', username => 'abc', password => '123' });
if ($userid > 0){
# Erfolgreich authentifiziert und Userid in $userid gespeichert
}
else {
# $userid ist Fehlercode
}
=head1 METHODS
=over 4
=item new
Erzeugung des Objektes
=back
=head1 EXPORT
Es werden keine Funktionen exportiert. Alle Funktionen muessen
vollqualifiziert verwendet werden. Der Verzicht auf den Exporter
bedeutet weniger Speicherverbrauch und mehr Performance auf
Kosten von etwas mehr Schreibarbeit.
=head1 AUTHOR
Oliver Flimm <flimm@openbib.org>
=cut
| oflimm/openbib | portal/perl/modules/OpenBib/Authenticator/Backend/ADLDAP.pm | Perl | gpl-2.0 | 6,133 |
<!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_07) on Fri Dec 14 19:29:55 GMT 2012 -->
<title>Uses of Class calculator.CalcController.RadioListener</title>
<meta name="date" content="2012-12-14">
<link rel="stylesheet" type="text/css" href="../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class calculator.CalcController.RadioListener";
}
//-->
</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="../../calculator/CalcController.RadioListener.html" title="class in calculator">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?calculator/class-use/CalcController.RadioListener.html" target="_top">Frames</a></li>
<li><a href="CalcController.RadioListener.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 calculator.CalcController.RadioListener" class="title">Uses of Class<br>calculator.CalcController.RadioListener</h2>
</div>
<div class="classUseContainer">No usage of calculator.CalcController.RadioListener</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="../../calculator/CalcController.RadioListener.html" title="class in calculator">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../index-files/index-1.html">Index</a></li>
<li><a href="../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../index.html?calculator/class-use/CalcController.RadioListener.html" target="_top">Frames</a></li>
<li><a href="CalcController.RadioListener.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>
| fated/calculator | doc/calculator/class-use/CalcController.RadioListener.html | HTML | gpl-2.0 | 4,154 |
/*
* Nividic development code
*
* This code may be freely distributed and modified under the
* terms of the GNU Lesser General Public Licence. This should
* be distributed with the code. If you do not have a copy,
* see:
*
* http://www.gnu.org/copyleft/lesser.html
*
* Copyright for this code is held jointly by the microarray platform
* of the École Normale Supérieure and the individual authors.
* These should be listed in @author doc comments.
*
* For more information on the Nividic project and its aims,
* or to join the Nividic mailing list, visit the home page
* at:
*
* http://www.transcriptome.ens.fr/nividic
*
*/
package fr.ens.transcriptome.nividic.platform.data;
import java.io.File;
import org.apache.log4j.Logger;
import fr.ens.transcriptome.nividic.platform.PlatformException;
import fr.ens.transcriptome.nividic.platform.module.AboutModule;
import fr.ens.transcriptome.nividic.platform.module.Module;
import fr.ens.transcriptome.nividic.platform.module.ModuleDescription;
import fr.ens.transcriptome.nividic.util.SystemUtils;
/**
* Wrapper for gpr files.
*
* @author Laurent Jourdren
*/
public final class BioAssayFileData extends Data implements Module {
// For logging system
private static Logger log = Logger.getLogger(BioAssayFileData.class);
/**
* Get the name of the data.
* @return The name of the data
*/
public String getName() {
return SystemUtils.getClassNameWithoutPackage(BioAssayFileData.class);
}
/**
* Get the format of the data.
* @return The name of the format of the data
*/
public String getFormat() {
return DataDefaults.FILE_FORMAT;
}
/**
* Get the type of the data.
* @return The type of the data.
*/
public String getType() {
return DataDefaults.BIOASSAY_TYPE;
}
/**
* Get the class of the data.
* @return The class of the data.
*/
public Class getDataClass() {
return File.class;
}
/**
* Get the description of the module.
* @return The description of the module
*/
public AboutModule aboutModule() {
ModuleDescription md = null;
try {
md = new ModuleDescription("BioAssayFileData", "BioAssay GPR data type");
} catch (PlatformException e) {
log.error("Unable to create module description");
}
return md;
}
/**
* Set the data.
* @param f File to set
* @throws PlatformException if data type is bad or if data is null
*/
public void setData(final File f) throws PlatformException {
super.setData(f);
}
//
// Constructor
//
/**
* Constructor.
* @param f File to set
* @throws PlatformException if data type is bad or if data is null
*/
public BioAssayFileData(final File f) throws PlatformException {
setData(f);
}
}
| GenomicParisCentre/doelan | src/main/java/fr/ens/transcriptome/nividic/platform/data/BioAssayFileData.java | Java | gpl-2.0 | 2,811 |
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">
<html>
<head>
<title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: init_userfields_js()</title>
<link rel="stylesheet" href="../sample.css" type="text/css">
<link rel="stylesheet" href="../sample-print.css" type="text/css" media="print">
<style id="hilight" type="text/css"></style>
<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">
</head>
<body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff">
<table class="pagetitle" width="100%">
<tr>
<td valign="top" class="pagetitle">
[ <a href="../index.html">Index</a> ]
</td>
<td align="right" class="pagetitle">
<h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2>
</td>
</tr>
</table>
<!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 -->
<!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net -->
<!-- http://phpxref.sourceforge.net/ -->
<script src="../phpxref.js" type="text/javascript"></script>
<script language="JavaScript" type="text/javascript">
<!--
ext='.html';
relbase='../';
subdir='_functions';
filename='index.html';
cookiekey='phpxref';
handleNavFrame(relbase, subdir, filename);
logFunction('init_userfields_js');
// -->
</script>
<script language="JavaScript" type="text/javascript">
if (gwGetCookie('xrefnav')=='off')
document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>');
else
document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>');
</script>
<noscript>
<p class="navlinks">
[ <a href="../nav.html" target="_top">Show Explorer</a> ]
[ <a href="index.html" target="_top">Hide Navbar</a> ]
</p>
</noscript>
[<a href="../index.html">Top level directory</a>]<br>
<script language="JavaScript" type="text/javascript">
<!--
document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>');
document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">');
document.writeln('<tr><td class="searchbox-title">');
document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>');
document.writeln('<\/td><\/tr>');
document.writeln('<tr><td class="searchbox-body" id="searchbox-body">');
document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>');
document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="classname"><br>');
document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="funcname"><br>');
document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="varname"><br>');
document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="constname"><br>');
document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: ');
document.writeln('<input type="text" size=10 value="" name="tablename"><br>');
document.writeln('<input type="submit" class="searchbox-button" value="Search">');
document.writeln('<\/form>');
document.writeln('<\/td><\/tr><\/table>');
document.writeln('<\/td><\/tr><\/table>');
// -->
</script>
<div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div>
<h3>Function and Method Cross Reference</h3>
<h2><a href="index.html#init_userfields_js">init_userfields_js()</a></h2>
<b>Defined at:</b><ul>
<li><a href="../inc/_core/_template.funcs.php.html#init_userfields_js">/inc/_core/_template.funcs.php</a> -> <a onClick="logFunction('init_userfields_js', '/inc/_core/_template.funcs.php.source.html#l1400')" href="../inc/_core/_template.funcs.php.source.html#l1400"> line 1400</a></li>
</ul>
<b>Referenced 2 times:</b><ul>
<li><a href="../inc/skins/model/_skin.class.php.html">/inc/skins/model/_skin.class.php</a> -> <a href="../inc/skins/model/_skin.class.php.source.html#l1047"> line 1047</a></li>
<li><a href="../inc/users/user.ctrl.php.html">/inc/users/user.ctrl.php</a> -> <a href="../inc/users/user.ctrl.php.source.html#l756"> line 756</a></li>
</ul>
<!-- A link to the phpxref site in your customized footer file is appreciated ;-) -->
<br><hr>
<table width="100%">
<tr><td>Generated: Sat Nov 21 22:13:19 2015</td>
<td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td>
</tr>
</table>
</body></html>
| mgsolipa/b2evolution_phpxref | _functions/init_userfields_js.html | HTML | gpl-2.0 | 5,055 |
#include "quakedef.h"
#include "prvm_cmds.h"
#include "jpeg.h"
//============================================================================
// Server
const char *vm_sv_extensions =
"BX_WAL_SUPPORT "
"DP_BUTTONCHAT "
"DP_BUTTONUSE "
"DP_CL_LOADSKY "
"DP_CON_ALIASPARAMETERS "
"DP_CON_BESTWEAPON "
"DP_CON_EXPANDCVAR "
"DP_CON_SET "
"DP_CON_SETA "
"DP_CON_STARTMAP "
"DP_COVERAGE "
"DP_CRYPTO "
"DP_CSQC_BINDMAPS "
"DP_CSQC_ENTITYWORLDOBJECT "
"DP_CSQC_ENTITYMODELLIGHT "
"DP_CSQC_ENTITYTRANSPARENTSORTING_OFFSET "
"DP_CSQC_MAINVIEW "
"DP_CSQC_MINFPS_QUALITY "
"DP_CSQC_MULTIFRAME_INTERPOLATION "
"DP_CSQC_BOXPARTICLES "
"DP_CSQC_SPAWNPARTICLE "
"DP_CSQC_QUERYRENDERENTITY "
"DP_CSQC_ROTATEMOVES "
"DP_CSQC_SETPAUSE "
"DP_CSQC_V_CALCREFDEF_WIP1 "
"DP_CSQC_V_CALCREFDEF_WIP2 "
"DP_EF_ADDITIVE "
"DP_EF_BLUE "
"DP_EF_DOUBLESIDED "
"DP_EF_DYNAMICMODELLIGHT "
"DP_EF_FLAME "
"DP_EF_FULLBRIGHT "
"DP_EF_NODEPTHTEST "
"DP_EF_NODRAW "
"DP_EF_NOGUNBOB "
"DP_EF_NOSELFSHADOW "
"DP_EF_NOSHADOW "
"DP_EF_RED "
"DP_EF_RESTARTANIM_BIT "
"DP_EF_STARDUST "
"DP_EF_TELEPORT_BIT "
"DP_ENT_ALPHA "
"DP_ENT_COLORMOD "
"DP_ENT_CUSTOMCOLORMAP "
"DP_ENT_EXTERIORMODELTOCLIENT "
"DP_ENT_GLOW "
"DP_ENT_GLOWMOD "
"DP_ENT_LOWPRECISION "
"DP_ENT_SCALE "
"DP_ENT_TRAILEFFECTNUM "
"DP_ENT_VIEWMODEL "
"DP_GFX_EXTERNALTEXTURES "
"DP_GFX_EXTERNALTEXTURES_PERMAP "
"DP_GFX_FOG "
"DP_GFX_MODEL_INTERPOLATION "
"DP_GFX_QUAKE3MODELTAGS "
"DP_GFX_SKINFILES "
"DP_GFX_SKYBOX "
"DP_GFX_FONTS "
"DP_GFX_FONTS_FREETYPE "
"DP_UTF8 "
"DP_FONT_VARIABLEWIDTH "
"DP_HALFLIFE_MAP "
"DP_HALFLIFE_MAP_CVAR "
"DP_HALFLIFE_SPRITE "
"DP_INPUTBUTTONS "
"DP_LIGHTSTYLE_STATICVALUE "
"DP_LITSPRITES "
"DP_LITSUPPORT "
"DP_MONSTERWALK "
"DP_MOVETYPEBOUNCEMISSILE "
"DP_MOVETYPEFLYWORLDONLY "
"DP_MOVETYPEFOLLOW "
"DP_NULL_MODEL "
"DP_QC_ASINACOSATANATAN2TAN "
"DP_QC_AUTOCVARS "
"DP_QC_CHANGEPITCH "
"DP_QC_CMD "
"DP_QC_COPYENTITY "
"DP_QC_CRC16 "
"DP_QC_CVAR_DEFSTRING "
"DP_QC_CVAR_DESCRIPTION "
"DP_QC_CVAR_STRING "
"DP_QC_CVAR_TYPE "
"DP_QC_DIGEST "
"DP_QC_DIGEST_SHA256 "
"DP_QC_EDICT_NUM "
"DP_QC_ENTITYDATA "
"DP_QC_ENTITYSTRING "
"DP_QC_ETOS "
"DP_QC_EXTRESPONSEPACKET "
"DP_QC_FINDCHAIN "
"DP_QC_FINDCHAINFLAGS "
"DP_QC_FINDCHAINFLOAT "
"DP_QC_FINDCHAIN_TOFIELD "
"DP_QC_FINDFLAGS "
"DP_QC_FINDFLOAT "
"DP_QC_FS_SEARCH "
"DP_QC_GETLIGHT "
"DP_QC_GETSURFACE "
"DP_QC_GETSURFACETRIANGLE "
"DP_QC_GETSURFACEPOINTATTRIBUTE "
"DP_QC_GETTAGINFO "
"DP_QC_GETTAGINFO_BONEPROPERTIES "
"DP_QC_GETTIME "
"DP_QC_GETTIME_CDTRACK "
"DP_QC_I18N "
"DP_QC_LOG "
"DP_QC_MINMAXBOUND "
"DP_QC_MULTIPLETEMPSTRINGS "
"DP_QC_NUM_FOR_EDICT "
"DP_QC_RANDOMVEC "
"DP_QC_SINCOSSQRTPOW "
"DP_QC_SPRINTF "
"DP_QC_STRFTIME "
"DP_QC_STRINGBUFFERS "
"DP_QC_STRINGBUFFERS_CVARLIST "
"DP_QC_STRINGBUFFERS_EXT_WIP "
"DP_QC_STRINGCOLORFUNCTIONS "
"DP_QC_STRING_CASE_FUNCTIONS "
"DP_QC_STRREPLACE "
"DP_QC_TOKENIZEBYSEPARATOR "
"DP_QC_TOKENIZE_CONSOLE "
"DP_QC_TRACEBOX "
"DP_QC_TRACETOSS "
"DP_QC_TRACE_MOVETYPE_HITMODEL "
"DP_QC_TRACE_MOVETYPE_WORLDONLY "
"DP_QC_UNLIMITEDTEMPSTRINGS "
"DP_QC_URI_ESCAPE "
"DP_QC_URI_GET "
"DP_QC_URI_POST "
"DP_QC_VECTOANGLES_WITH_ROLL "
"DP_QC_VECTORVECTORS "
"DP_QC_WHICHPACK "
"DP_QUAKE2_MODEL "
"DP_QUAKE2_SPRITE "
"DP_QUAKE3_MAP "
"DP_QUAKE3_MODEL "
"DP_REGISTERCVAR "
"DP_SKELETONOBJECTS "
"DP_SND_DIRECTIONLESSATTNNONE "
"DP_SND_FAKETRACKS "
"DP_SND_SOUND7_WIP1 "
"DP_SND_SOUND7_WIP2 "
"DP_SND_OGGVORBIS "
"DP_SND_SETPARAMS "
"DP_SND_STEREOWAV "
"DP_SND_GETSOUNDTIME "
"DP_VIDEO_DPV "
"DP_VIDEO_SUBTITLES "
"DP_SOLIDCORPSE "
"DP_SPRITE32 "
"DP_SV_BOTCLIENT "
"DP_SV_BOUNCEFACTOR "
"DP_SV_CLIENTCAMERA "
"DP_SV_CLIENTCOLORS "
"DP_SV_CLIENTNAME "
"DP_SV_CMD "
"DP_SV_CUSTOMIZEENTITYFORCLIENT "
"DP_SV_DISABLECLIENTPREDICTION "
"DP_SV_DISCARDABLEDEMO "
"DP_SV_DRAWONLYTOCLIENT "
"DP_SV_DROPCLIENT "
"DP_SV_EFFECT "
"DP_SV_ENTITYCONTENTSTRANSITION "
"DP_SV_MODELFLAGS_AS_EFFECTS "
"DP_SV_MOVETYPESTEP_LANDEVENT "
"DP_SV_NETADDRESS "
"DP_SV_NODRAWTOCLIENT "
"DP_SV_ONENTITYNOSPAWNFUNCTION "
"DP_SV_ONENTITYPREPOSTSPAWNFUNCTION "
"DP_SV_PING "
"DP_SV_PING_PACKETLOSS "
"DP_SV_PLAYERPHYSICS "
"DP_PHYSICS_ODE "
"DP_SV_POINTPARTICLES "
"DP_SV_POINTSOUND "
"DP_SV_PRECACHEANYTIME "
"DP_SV_PRINT "
"DP_SV_PUNCHVECTOR "
"DP_SV_QCSTATUS "
"DP_SV_ROTATINGBMODEL "
"DP_SV_SETCOLOR "
"DP_SV_SHUTDOWN "
"DP_SV_SLOWMO "
"DP_SV_SPAWNFUNC_PREFIX "
"DP_SV_WRITEPICTURE "
"DP_SV_WRITEUNTERMINATEDSTRING "
"DP_TE_BLOOD "
"DP_TE_BLOODSHOWER "
"DP_TE_CUSTOMFLASH "
"DP_TE_EXPLOSIONRGB "
"DP_TE_FLAMEJET "
"DP_TE_PARTICLECUBE "
"DP_TE_PARTICLERAIN "
"DP_TE_PARTICLESNOW "
"DP_TE_PLASMABURN "
"DP_TE_QUADEFFECTS1 "
"DP_TE_SMALLFLASH "
"DP_TE_SPARK "
"DP_TE_STANDARDEFFECTBUILTINS "
"DP_TRACE_HITCONTENTSMASK_SURFACEINFO "
"DP_USERMOVETYPES "
"DP_VIEWZOOM "
"EXT_BITSHIFT "
"FRIK_FILE "
"FTE_CSQC_SKELETONOBJECTS "
"FTE_QC_CHECKPVS "
"FTE_STRINGS "
"KRIMZON_SV_PARSECLIENTCOMMAND "
"NEH_CMD_PLAY2 "
"NEH_RESTOREGAME "
"NEXUIZ_PLAYERMODEL "
"NXQ_GFX_LETTERBOX "
"PRYDON_CLIENTCURSOR "
"TENEBRAE_GFX_DLIGHTS "
"TW_SV_STEPCONTROL "
"ZQ_PAUSE "
#ifndef __ANDROID__
"DP_RM_IRC "
#endif
"DP_RM_CALLFUNCTIONEX "
"DP_RM_GLOBALACCESS "
"DP_RM_ALTCSPROGS "
"DP_RM_CVAR_ALTERTYPE "
"DP_RM_CVAR_WATCHED "
"DP_RM_REGEX2 "
"DP_RM_CLIENTDATAENT "
"DP_RM_CLIPGROUP "
"DP_RM_QCSENDPACKET "
"DP_RM_GEOIP "
"DP_RM_SETRENDERENTITY "
"DP_RM_CULLTRACEMODE "
//"EXT_CSQC " // not ready yet
;
/*
=================
VM_SV_setorigin
This is the only valid way to move an object without using the physics of the world (setting velocity and waiting). Directly changing origin will not set internal links correctly, so clipping would be messed up. This should be called when an object is spawned, and then only if it is teleported.
setorigin (entity, origin)
=================
*/
static void VM_SV_setorigin(prvm_prog_t *prog)
{
prvm_edict_t *e;
VM_SAFEPARMCOUNT(2, VM_setorigin);
e = PRVM_G_EDICT(OFS_PARM0);
if (e == prog->edicts)
{
VM_Warning(prog, "setorigin: can not modify world entity\n");
return;
}
if (e->priv.server->free)
{
VM_Warning(prog, "setorigin: can not modify free entity\n");
return;
}
VectorCopy(PRVM_G_VECTOR(OFS_PARM1), PRVM_serveredictvector(e, origin));
if(e->priv.required->mark == PRVM_EDICT_MARK_WAIT_FOR_SETORIGIN)
e->priv.required->mark = PRVM_EDICT_MARK_SETORIGIN_CAUGHT;
SV_LinkEdict(e);
}
// TODO: rotate param isnt used.. could be a bug. please check this and remove it if possible [1/10/2008 Black]
static void SetMinMaxSize (prvm_prog_t *prog, prvm_edict_t *e, float *min, float *max, qboolean rotate)
{
int i;
for (i=0 ; i<3 ; i++)
if (min[i] > max[i])
prog->error_cmd("SetMinMaxSize: backwards mins/maxs");
// set derived values
VectorCopy (min, PRVM_serveredictvector(e, mins));
VectorCopy (max, PRVM_serveredictvector(e, maxs));
VectorSubtract (max, min, PRVM_serveredictvector(e, size));
SV_LinkEdict(e);
}
/*
=================
VM_SV_setsize
the size box is rotated by the current angle
LordHavoc: no it isn't...
setsize (entity, minvector, maxvector)
=================
*/
static void VM_SV_setsize(prvm_prog_t *prog)
{
prvm_edict_t *e;
vec3_t mins, maxs;
VM_SAFEPARMCOUNT(3, VM_setsize);
e = PRVM_G_EDICT(OFS_PARM0);
if (e == prog->edicts)
{
VM_Warning(prog, "setsize: can not modify world entity\n");
return;
}
if (e->priv.server->free)
{
VM_Warning(prog, "setsize: can not modify free entity\n");
return;
}
VectorCopy(PRVM_G_VECTOR(OFS_PARM1), mins);
VectorCopy(PRVM_G_VECTOR(OFS_PARM2), maxs);
SetMinMaxSize(prog, e, mins, maxs, false);
}
/*
=================
VM_SV_setmodel
setmodel(entity, model)
=================
*/
static vec3_t quakemins = {-16, -16, -16}, quakemaxs = {16, 16, 16};
static void VM_SV_setmodel(prvm_prog_t *prog)
{
prvm_edict_t *e;
dp_model_t *mod;
int i;
VM_SAFEPARMCOUNT(2, VM_setmodel);
e = PRVM_G_EDICT(OFS_PARM0);
if (e == prog->edicts)
{
VM_Warning(prog, "setmodel: can not modify world entity\n");
return;
}
if (e->priv.server->free)
{
VM_Warning(prog, "setmodel: can not modify free entity\n");
return;
}
i = SV_ModelIndex(PRVM_G_STRING(OFS_PARM1), 1);
PRVM_serveredictstring(e, model) = PRVM_SetEngineString(prog, sv.model_precache[i]);
PRVM_serveredictfloat(e, modelindex) = i;
mod = SV_GetModelByIndex(i);
if (mod)
{
if (mod->type != mod_alias || sv_gameplayfix_setmodelrealbox.integer)
SetMinMaxSize(prog, e, mod->normalmins, mod->normalmaxs, true);
else
SetMinMaxSize(prog, e, quakemins, quakemaxs, true);
}
else
SetMinMaxSize(prog, e, vec3_origin, vec3_origin, true);
}
/*
=================
VM_SV_sprint
single print to a specific client
sprint(clientent, value)
=================
*/
static void VM_SV_sprint(prvm_prog_t *prog)
{
client_t *client;
int entnum;
char string[VM_STRINGTEMP_LENGTH];
VM_SAFEPARMCOUNTRANGE(2, 8, VM_SV_sprint);
if (kex_compat.integer)
VM_VarString2(prog, 1, string, sizeof(string));
else
VM_VarString(prog, 1, string, sizeof(string));
entnum = PRVM_G_EDICTNUM(OFS_PARM0);
// LordHavoc: div0 requested that sprintto world operate like print
if (entnum == 0)
{
Con_Print(string);
return;
}
if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
{
VM_Warning(prog, "tried to centerprint to a non-client\n");
return;
}
client = svs.clients + entnum-1;
if (!client->netconnection)
return;
MSG_WriteChar(&client->netconnection->message,svc_print);
MSG_WriteString(&client->netconnection->message, string);
}
/*
=================
VM_SV_centerprint
single print to a specific client
centerprint(clientent, value)
=================
*/
static void VM_SV_centerprint(prvm_prog_t *prog)
{
client_t *client;
int entnum;
char string[VM_STRINGTEMP_LENGTH];
VM_SAFEPARMCOUNTRANGE(2, 8, VM_SV_centerprint);
entnum = PRVM_G_EDICTNUM(OFS_PARM0);
if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
{
VM_Warning(prog, "tried to centerprint to a non-client\n");
return;
}
client = svs.clients + entnum-1;
if (!client->netconnection)
return;
if (gamegroup == GAME_NORMAL)
VM_VarString2(prog, 1, string, sizeof(string));
else
VM_VarString(prog, 1, string, sizeof(string));
MSG_WriteChar(&client->netconnection->message,svc_centerprint);
MSG_WriteString(&client->netconnection->message, string);
}
/*
=================
VM_SV_particle
particle(origin, color, count)
=================
*/
static void VM_SV_particle(prvm_prog_t *prog)
{
vec3_t org, dir;
int color;
int count;
VM_SAFEPARMCOUNT(4, VM_SV_particle);
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), org);
VectorCopy(PRVM_G_VECTOR(OFS_PARM1), dir);
color = (int)PRVM_G_FLOAT(OFS_PARM2);
count = (int)PRVM_G_FLOAT(OFS_PARM3);
SV_StartParticle (org, dir, color, count);
}
/*
=================
VM_SV_ambientsound
=================
*/
static void VM_SV_ambientsound(prvm_prog_t *prog)
{
const char *samp;
vec3_t pos;
prvm_vec_t vol, attenuation;
int soundnum, large;
VM_SAFEPARMCOUNT(4, VM_SV_ambientsound);
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), pos);
samp = PRVM_G_STRING(OFS_PARM1);
vol = PRVM_G_FLOAT(OFS_PARM2);
attenuation = PRVM_G_FLOAT(OFS_PARM3);
// check to see if samp was properly precached
soundnum = SV_SoundIndex(samp, 1);
if (!soundnum)
return;
large = false;
if (soundnum >= 256)
large = true;
// add an svc_spawnambient command to the level signon packet
if (large)
MSG_WriteByte (&sv.signon, svc_spawnstaticsound2);
else
MSG_WriteByte (&sv.signon, svc_spawnstaticsound);
MSG_WriteVector(&sv.signon, pos, sv.protocol);
if (large)
MSG_WriteShort (&sv.signon, soundnum);
else
MSG_WriteByte (&sv.signon, soundnum);
MSG_WriteByte (&sv.signon, (int)(vol*255));
MSG_WriteByte (&sv.signon, (int)(attenuation*64));
}
/*
=================
VM_SV_sound
Each entity can have eight independant sound sources, like voice,
weapon, feet, etc.
Channel 0 is an auto-allocate channel, the others override anything
already running on that entity/channel pair.
An attenuation of 0 will play full volume everywhere in the level.
Larger attenuations will drop off.
=================
*/
static void VM_SV_sound(prvm_prog_t *prog)
{
const char *sample;
int channel;
prvm_edict_t *entity;
int nvolume;
int flags;
float attenuation;
float pitchchange;
VM_SAFEPARMCOUNTRANGE(4, 7, VM_SV_sound);
entity = PRVM_G_EDICT(OFS_PARM0);
channel = (int)PRVM_G_FLOAT(OFS_PARM1);
sample = PRVM_G_STRING(OFS_PARM2);
nvolume = (int)(PRVM_G_FLOAT(OFS_PARM3) * 255);
if (prog->argc < 5)
{
Con_DPrintf("VM_SV_sound: given only 4 parameters, expected 5, assuming attenuation = ATTN_NORMAL\n");
attenuation = 1;
}
else
attenuation = PRVM_G_FLOAT(OFS_PARM4);
if (prog->argc < 6)
pitchchange = 0;
else
pitchchange = PRVM_G_FLOAT(OFS_PARM5) * 0.01f;
if (prog->argc < 7)
{
flags = 0;
if(channel >= 8 && channel <= 15) // weird QW feature
{
flags |= CHANNELFLAG_RELIABLE;
channel -= 8;
}
}
else
{
// LordHavoc: we only let the qc set certain flags, others are off-limits
flags = (int)PRVM_G_FLOAT(OFS_PARM6) & (CHANNELFLAG_RELIABLE | CHANNELFLAG_FORCELOOP | CHANNELFLAG_PAUSED);
}
if (nvolume < 0 || nvolume > 255)
{
VM_Warning(prog, "SV_StartSound: volume must be in range 0-1\n");
return;
}
if (attenuation < 0 || attenuation > 4)
{
VM_Warning(prog, "SV_StartSound: attenuation must be in range 0-4\n");
return;
}
channel = CHAN_USER2ENGINE(channel);
if (!IS_CHAN(channel))
{
VM_Warning(prog, "SV_StartSound: channel must be in range 0-127\n");
return;
}
SV_StartSound (entity, channel, sample, nvolume, attenuation, flags & CHANNELFLAG_RELIABLE, pitchchange);
}
/*
=================
VM_SV_pointsound
Follows the same logic as VM_SV_sound, except instead of
an entity, an origin for the sound is provided, and channel
is omitted (since no entity is being tracked).
=================
*/
static void VM_SV_pointsound(prvm_prog_t *prog)
{
const char *sample;
int nvolume;
float attenuation;
float pitchchange;
vec3_t org;
VM_SAFEPARMCOUNTRANGE(4, 5, VM_SV_pointsound);
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), org);
sample = PRVM_G_STRING(OFS_PARM1);
nvolume = (int)(PRVM_G_FLOAT(OFS_PARM2) * 255);
attenuation = PRVM_G_FLOAT(OFS_PARM3);
pitchchange = prog->argc < 5 ? 0 : PRVM_G_FLOAT(OFS_PARM4) * 0.01f;
if (nvolume < 0 || nvolume > 255)
{
VM_Warning(prog, "SV_StartPointSound: volume must be in range 0-1\n");
return;
}
if (attenuation < 0 || attenuation > 4)
{
VM_Warning(prog, "SV_StartPointSound: attenuation must be in range 0-4\n");
return;
}
SV_StartPointSound (org, sample, nvolume, attenuation, pitchchange);
}
/*
=================
VM_SV_traceline
Used for use tracing and shot targeting
Traces are blocked by bbox and exact bsp entityes, and also slide box entities
if the tryents flag is set.
traceline (vector1, vector2, movetype, ignore)
=================
*/
static void VM_SV_traceline(prvm_prog_t *prog)
{
vec3_t v1, v2;
trace_t trace;
int move;
prvm_edict_t *ent;
VM_SAFEPARMCOUNTRANGE(4, 8, VM_SV_traceline); // allow more parameters for future expansion
prog->xfunction->builtinsprofile += 30;
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), v1);
VectorCopy(PRVM_G_VECTOR(OFS_PARM1), v2);
move = (int)PRVM_G_FLOAT(OFS_PARM2);
ent = PRVM_G_EDICT(OFS_PARM3);
if (VEC_IS_NAN(v1[0]) || VEC_IS_NAN(v1[1]) || VEC_IS_NAN(v1[2]) || VEC_IS_NAN(v2[0]) || VEC_IS_NAN(v2[1]) || VEC_IS_NAN(v2[2]))
prog->error_cmd("%s: NAN errors detected in traceline('%f %f %f', '%f %f %f', %i, entity %i)\n", prog->name, v1[0], v1[1], v1[2], v2[0], v2[1], v2[2], move, PRVM_EDICT_TO_PROG(ent));
trace = SV_TraceLine(v1, v2, move, ent, SV_GenericHitSuperContentsMask(ent), 0, collision_extendtracelinelength.value);
VM_SetTraceGlobals(prog, &trace);
}
/*
=================
VM_SV_tracebox
Used for use tracing and shot targeting
Traces are blocked by bbox and exact bsp entityes, and also slide box entities
if the tryents flag is set.
tracebox (vector1, vector mins, vector maxs, vector2, tryents)
=================
*/
// LordHavoc: added this for my own use, VERY useful, similar to traceline
static void VM_SV_tracebox(prvm_prog_t *prog)
{
vec3_t v1, v2, m1, m2;
trace_t trace;
int move;
prvm_edict_t *ent;
VM_SAFEPARMCOUNTRANGE(6, 8, VM_SV_tracebox); // allow more parameters for future expansion
prog->xfunction->builtinsprofile += 30;
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), v1);
VectorCopy(PRVM_G_VECTOR(OFS_PARM1), m1);
VectorCopy(PRVM_G_VECTOR(OFS_PARM2), m2);
VectorCopy(PRVM_G_VECTOR(OFS_PARM3), v2);
move = (int)PRVM_G_FLOAT(OFS_PARM4);
ent = PRVM_G_EDICT(OFS_PARM5);
if (VEC_IS_NAN(v1[0]) || VEC_IS_NAN(v1[1]) || VEC_IS_NAN(v1[2]) || VEC_IS_NAN(v2[0]) || VEC_IS_NAN(v2[1]) || VEC_IS_NAN(v2[2]))
prog->error_cmd("%s: NAN errors detected in tracebox('%f %f %f', '%f %f %f', '%f %f %f', '%f %f %f', %i, entity %i)\n", prog->name, v1[0], v1[1], v1[2], m1[0], m1[1], m1[2], m2[0], m2[1], m2[2], v2[0], v2[1], v2[2], move, PRVM_EDICT_TO_PROG(ent));
trace = SV_TraceBox(v1, m1, m2, v2, move, ent, SV_GenericHitSuperContentsMask(ent), 0, collision_extendtraceboxlength.value);
VM_SetTraceGlobals(prog, &trace);
}
static trace_t SV_Trace_Toss(prvm_prog_t *prog, prvm_edict_t *tossent, prvm_edict_t *ignore)
{
int i;
float gravity;
vec3_t move, end, tossentorigin, tossentmins, tossentmaxs;
vec3_t original_origin;
vec3_t original_velocity;
vec3_t original_angles;
vec3_t original_avelocity;
trace_t trace;
VectorCopy(PRVM_serveredictvector(tossent, origin) , original_origin );
VectorCopy(PRVM_serveredictvector(tossent, velocity) , original_velocity );
VectorCopy(PRVM_serveredictvector(tossent, angles) , original_angles );
VectorCopy(PRVM_serveredictvector(tossent, avelocity), original_avelocity);
gravity = PRVM_serveredictfloat(tossent, gravity);
if (!gravity)
gravity = 1.0f;
gravity *= sv_gravity.value * 0.025;
for (i = 0;i < 200;i++) // LordHavoc: sanity check; never trace more than 10 seconds
{
SV_CheckVelocity (tossent);
PRVM_serveredictvector(tossent, velocity)[2] -= gravity;
VectorMA (PRVM_serveredictvector(tossent, angles), 0.05, PRVM_serveredictvector(tossent, avelocity), PRVM_serveredictvector(tossent, angles));
VectorScale (PRVM_serveredictvector(tossent, velocity), 0.05, move);
VectorAdd (PRVM_serveredictvector(tossent, origin), move, end);
VectorCopy(PRVM_serveredictvector(tossent, origin), tossentorigin);
VectorCopy(PRVM_serveredictvector(tossent, mins), tossentmins);
VectorCopy(PRVM_serveredictvector(tossent, maxs), tossentmaxs);
trace = SV_TraceBox(tossentorigin, tossentmins, tossentmaxs, end, MOVE_NORMAL, tossent, SV_GenericHitSuperContentsMask(tossent), 0, collision_extendmovelength.value);
VectorCopy (trace.endpos, PRVM_serveredictvector(tossent, origin));
PRVM_serveredictvector(tossent, velocity)[2] -= gravity;
if (trace.fraction < 1)
break;
}
VectorCopy(original_origin , PRVM_serveredictvector(tossent, origin) );
VectorCopy(original_velocity , PRVM_serveredictvector(tossent, velocity) );
VectorCopy(original_angles , PRVM_serveredictvector(tossent, angles) );
VectorCopy(original_avelocity, PRVM_serveredictvector(tossent, avelocity));
return trace;
}
static void VM_SV_tracetoss(prvm_prog_t *prog)
{
trace_t trace;
prvm_edict_t *ent;
prvm_edict_t *ignore;
VM_SAFEPARMCOUNT(2, VM_SV_tracetoss);
prog->xfunction->builtinsprofile += 600;
ent = PRVM_G_EDICT(OFS_PARM0);
if (ent == prog->edicts)
{
VM_Warning(prog, "tracetoss: can not use world entity\n");
return;
}
ignore = PRVM_G_EDICT(OFS_PARM1);
trace = SV_Trace_Toss(prog, ent, ignore);
VM_SetTraceGlobals(prog, &trace);
}
//============================================================================
static int checkpvsbytes;
static unsigned char checkpvs[MAX_MAP_LEAFS/8];
static int VM_SV_newcheckclient(prvm_prog_t *prog, int check)
{
int i;
prvm_edict_t *ent;
vec3_t org;
// cycle to the next one
check = bound(1, check, svs.maxclients);
if (check == svs.maxclients)
i = 1;
else
i = check + 1;
for ( ; ; i++)
{
// count the cost
prog->xfunction->builtinsprofile++;
// wrap around
if (i == svs.maxclients+1)
i = 1;
// look up the client's edict
ent = PRVM_EDICT_NUM(i);
// check if it is to be ignored, but never ignore the one we started on (prevent infinite loop)
if (i != check && (ent->priv.server->free || PRVM_serveredictfloat(ent, health) <= 0 || ((int)PRVM_serveredictfloat(ent, flags) & FL_NOTARGET)))
continue;
// found a valid client (possibly the same one again)
break;
}
// get the PVS for the entity
VectorAdd(PRVM_serveredictvector(ent, origin), PRVM_serveredictvector(ent, view_ofs), org);
checkpvsbytes = 0;
if (sv.worldmodel && sv.worldmodel->brush.FatPVS)
checkpvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, org, 0, checkpvs, sizeof(checkpvs), false);
return i;
}
/*
=================
VM_SV_checkclient
Returns a client (or object that has a client enemy) that would be a
valid target.
If there is more than one valid option, they are cycled each frame
If (self.origin + self.viewofs) is not in the PVS of the current target,
it is not returned at all.
name checkclient ()
=================
*/
int c_invis, c_notvis;
static void VM_SV_checkclient(prvm_prog_t *prog)
{
prvm_edict_t *ent, *self;
vec3_t view;
VM_SAFEPARMCOUNT(0, VM_SV_checkclient);
// find a new check if on a new frame
if (sv.time - sv.lastchecktime >= 0.1)
{
sv.lastcheck = VM_SV_newcheckclient(prog, sv.lastcheck);
sv.lastchecktime = sv.time;
}
// return check if it might be visible
ent = PRVM_EDICT_NUM(sv.lastcheck);
if (ent->priv.server->free || PRVM_serveredictfloat(ent, health) <= 0)
{
VM_RETURN_EDICT(prog->edicts);
return;
}
// if current entity can't possibly see the check entity, return 0
self = PRVM_PROG_TO_EDICT(PRVM_serverglobaledict(self));
VectorAdd(PRVM_serveredictvector(self, origin), PRVM_serveredictvector(self, view_ofs), view);
if (sv.worldmodel && checkpvsbytes && !sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, checkpvs, view, view))
{
c_notvis++;
VM_RETURN_EDICT(prog->edicts);
return;
}
// might be able to see it
c_invis++;
VM_RETURN_EDICT(ent);
}
//============================================================================
/*
=================
VM_SV_checkpvs
Checks if an entity is in a point's PVS.
Should be fast but can be inexact.
float checkpvs(vector viewpos, entity viewee) = #240;
=================
*/
static void VM_SV_checkpvs(prvm_prog_t *prog)
{
vec3_t viewpos, absmin, absmax;
prvm_edict_t *viewee;
#if 1
unsigned char *pvs;
#else
int fatpvsbytes;
unsigned char fatpvs[MAX_MAP_LEAFS/8];
#endif
VM_SAFEPARMCOUNT(2, VM_SV_checkpvs);
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), viewpos);
viewee = PRVM_G_EDICT(OFS_PARM1);
if(viewee->priv.server->free)
{
VM_Warning(prog, "checkpvs: can not check free entity\n");
PRVM_G_FLOAT(OFS_RETURN) = 4;
return;
}
#if 1
if(!sv.worldmodel || !sv.worldmodel->brush.GetPVS || !sv.worldmodel->brush.BoxTouchingPVS)
{
// no PVS support on this worldmodel... darn
PRVM_G_FLOAT(OFS_RETURN) = 3;
return;
}
pvs = sv.worldmodel->brush.GetPVS(sv.worldmodel, viewpos);
if(!pvs)
{
// viewpos isn't in any PVS... darn
PRVM_G_FLOAT(OFS_RETURN) = 2;
return;
}
VectorCopy(PRVM_serveredictvector(viewee, absmin), absmin);
VectorCopy(PRVM_serveredictvector(viewee, absmax), absmax);
PRVM_G_FLOAT(OFS_RETURN) = sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, pvs, absmin, absmax);
#else
// using fat PVS like FTEQW does (slow)
if(!sv.worldmodel || !sv.worldmodel->brush.FatPVS || !sv.worldmodel->brush.BoxTouchingPVS)
{
// no PVS support on this worldmodel... darn
PRVM_G_FLOAT(OFS_RETURN) = 3;
return;
}
fatpvsbytes = sv.worldmodel->brush.FatPVS(sv.worldmodel, viewpos, 8, fatpvs, sizeof(fatpvs), false);
if(!fatpvsbytes)
{
// viewpos isn't in any PVS... darn
PRVM_G_FLOAT(OFS_RETURN) = 2;
return;
}
VectorCopy(PRVM_serveredictvector(viewee, absmin), absmin);
VectorCopy(PRVM_serveredictvector(viewee, absmax), absmax);
PRVM_G_FLOAT(OFS_RETURN) = sv.worldmodel->brush.BoxTouchingPVS(sv.worldmodel, fatpvs, absmin, absmax);
#endif
}
/*
=================
VM_SV_stuffcmd
Sends text over to the client's execution buffer
stuffcmd (clientent, value, ...)
=================
*/
static void VM_SV_stuffcmd(prvm_prog_t *prog)
{
int entnum;
client_t *old;
char string[VM_STRINGTEMP_LENGTH];
VM_SAFEPARMCOUNTRANGE(2, 8, VM_SV_stuffcmd);
entnum = PRVM_G_EDICTNUM(OFS_PARM0);
if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
{
VM_Warning(prog, "Can't stuffcmd to a non-client\n");
return;
}
VM_VarString(prog, 1, string, sizeof(string));
old = host_client;
host_client = svs.clients + entnum-1;
Host_ClientCommands ("%s", string);
host_client = old;
}
/*
=================
VM_SV_findradius
Returns a chain of entities that have origins within a spherical area
findradius (origin, radius)
=================
*/
static void VM_SV_findradius(prvm_prog_t *prog)
{
prvm_edict_t *ent, *chain;
vec_t radius, radius2;
vec3_t org, eorg, mins, maxs;
int i;
int numtouchedicts;
static prvm_edict_t *touchedicts[MAX_EDICTS];
int chainfield;
VM_SAFEPARMCOUNTRANGE(2, 3, VM_SV_findradius);
if(prog->argc == 3)
chainfield = PRVM_G_INT(OFS_PARM2);
else
chainfield = prog->fieldoffsets.chain;
if (chainfield < 0)
prog->error_cmd("VM_findchain: %s doesnt have the specified chain field !", prog->name);
chain = (prvm_edict_t *)prog->edicts;
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), org);
radius = PRVM_G_FLOAT(OFS_PARM1);
radius2 = radius * radius;
mins[0] = org[0] - (radius + 1);
mins[1] = org[1] - (radius + 1);
mins[2] = org[2] - (radius + 1);
maxs[0] = org[0] + (radius + 1);
maxs[1] = org[1] + (radius + 1);
maxs[2] = org[2] + (radius + 1);
numtouchedicts = SV_EntitiesInBox(mins, maxs, MAX_EDICTS, touchedicts);
if (numtouchedicts > MAX_EDICTS)
{
// this never happens
Con_Printf("SV_EntitiesInBox returned %i edicts, max was %i\n", numtouchedicts, MAX_EDICTS);
numtouchedicts = MAX_EDICTS;
}
for (i = 0;i < numtouchedicts;i++)
{
ent = touchedicts[i];
prog->xfunction->builtinsprofile++;
// Quake did not return non-solid entities but darkplaces does
// (note: this is the reason you can't blow up fallen zombies)
if (PRVM_serveredictfloat(ent, solid) == SOLID_NOT && !sv_gameplayfix_blowupfallenzombies.integer)
continue;
// LordHavoc: compare against bounding box rather than center so it
// doesn't miss large objects, and use DotProduct instead of Length
// for a major speedup
VectorSubtract(org, PRVM_serveredictvector(ent, origin), eorg);
if (sv_gameplayfix_findradiusdistancetobox.integer)
{
eorg[0] -= bound(PRVM_serveredictvector(ent, mins)[0], eorg[0], PRVM_serveredictvector(ent, maxs)[0]);
eorg[1] -= bound(PRVM_serveredictvector(ent, mins)[1], eorg[1], PRVM_serveredictvector(ent, maxs)[1]);
eorg[2] -= bound(PRVM_serveredictvector(ent, mins)[2], eorg[2], PRVM_serveredictvector(ent, maxs)[2]);
}
else
VectorMAMAM(1, eorg, -0.5f, PRVM_serveredictvector(ent, mins), -0.5f, PRVM_serveredictvector(ent, maxs), eorg);
if (DotProduct(eorg, eorg) < radius2)
{
PRVM_EDICTFIELDEDICT(ent,chainfield) = PRVM_EDICT_TO_PROG(chain);
chain = ent;
}
}
VM_RETURN_EDICT(chain);
}
static void VM_SV_precache_sound(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_precache_sound);
PRVM_G_FLOAT(OFS_RETURN) = SV_SoundIndex(PRVM_G_STRING(OFS_PARM0), 2);
}
static void VM_SV_precache_model(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_precache_model);
SV_ModelIndex(PRVM_G_STRING(OFS_PARM0), 2);
PRVM_G_INT(OFS_RETURN) = PRVM_G_INT(OFS_PARM0);
}
/*
===============
VM_SV_walkmove
float(float yaw, float dist[, settrace]) walkmove
===============
*/
static void VM_SV_walkmove(prvm_prog_t *prog)
{
prvm_edict_t *ent;
float yaw, dist;
vec3_t move;
mfunction_t *oldf;
int oldself;
qboolean settrace;
VM_SAFEPARMCOUNTRANGE(2, 3, VM_SV_walkmove);
// assume failure if it returns early
PRVM_G_FLOAT(OFS_RETURN) = 0;
ent = PRVM_PROG_TO_EDICT(PRVM_serverglobaledict(self));
if (ent == prog->edicts)
{
VM_Warning(prog, "walkmove: can not modify world entity\n");
return;
}
if (ent->priv.server->free)
{
VM_Warning(prog, "walkmove: can not modify free entity\n");
return;
}
yaw = PRVM_G_FLOAT(OFS_PARM0);
dist = PRVM_G_FLOAT(OFS_PARM1);
settrace = prog->argc >= 3 && PRVM_G_FLOAT(OFS_PARM2);
if ( !( (int)PRVM_serveredictfloat(ent, flags) & (FL_ONGROUND|FL_FLY|FL_SWIM) ) )
return;
yaw = yaw*M_PI*2 / 360;
move[0] = cos(yaw)*dist;
move[1] = sin(yaw)*dist;
move[2] = 0;
// save program state, because SV_movestep may call other progs
oldf = prog->xfunction;
oldself = PRVM_serverglobaledict(self);
PRVM_G_FLOAT(OFS_RETURN) = SV_movestep(ent, move, true, false, settrace);
// restore program state
prog->xfunction = oldf;
PRVM_serverglobaledict(self) = oldself;
}
/*
===============
VM_SV_droptofloor
void() droptofloor
===============
*/
static void VM_SV_droptofloor(prvm_prog_t *prog)
{
prvm_edict_t *ent;
vec3_t end, entorigin, entmins, entmaxs;
trace_t trace;
VM_SAFEPARMCOUNTRANGE(0, 2, VM_SV_droptofloor); // allow 2 parameters because the id1 defs.qc had an incorrect prototype
// assume failure if it returns early
PRVM_G_FLOAT(OFS_RETURN) = 0;
ent = PRVM_PROG_TO_EDICT(PRVM_serverglobaledict(self));
if (ent == prog->edicts)
{
VM_Warning(prog, "droptofloor: can not modify world entity\n");
return;
}
if (ent->priv.server->free)
{
VM_Warning(prog, "droptofloor: can not modify free entity\n");
return;
}
VectorCopy (PRVM_serveredictvector(ent, origin), end);
end[2] -= 256;
if (sv_gameplayfix_droptofloorstartsolid_nudgetocorrect.integer)
SV_NudgeOutOfSolid(ent);
VectorCopy(PRVM_serveredictvector(ent, origin), entorigin);
VectorCopy(PRVM_serveredictvector(ent, mins), entmins);
VectorCopy(PRVM_serveredictvector(ent, maxs), entmaxs);
trace = SV_TraceBox(entorigin, entmins, entmaxs, end, MOVE_NORMAL, ent, SV_GenericHitSuperContentsMask(ent), 0, collision_extendmovelength.value);
if (trace.startsolid && sv_gameplayfix_droptofloorstartsolid.integer)
{
vec3_t offset, org;
VectorSet(offset, 0.5f * (PRVM_serveredictvector(ent, mins)[0] + PRVM_serveredictvector(ent, maxs)[0]), 0.5f * (PRVM_serveredictvector(ent, mins)[1] + PRVM_serveredictvector(ent, maxs)[1]), PRVM_serveredictvector(ent, mins)[2]);
VectorAdd(PRVM_serveredictvector(ent, origin), offset, org);
trace = SV_TraceLine(org, end, MOVE_NORMAL, ent, SV_GenericHitSuperContentsMask(ent), 0, collision_extendmovelength.value);
VectorSubtract(trace.endpos, offset, trace.endpos);
if (trace.startsolid)
{
Con_DPrintf("droptofloor at %f %f %f - COULD NOT FIX BADLY PLACED ENTITY\n", PRVM_serveredictvector(ent, origin)[0], PRVM_serveredictvector(ent, origin)[1], PRVM_serveredictvector(ent, origin)[2]);
SV_LinkEdict(ent);
PRVM_serveredictfloat(ent, flags) = (int)PRVM_serveredictfloat(ent, flags) | FL_ONGROUND;
PRVM_serveredictedict(ent, groundentity) = 0;
PRVM_G_FLOAT(OFS_RETURN) = 1;
}
else if (trace.fraction < 1)
{
Con_DPrintf("droptofloor at %f %f %f - FIXED BADLY PLACED ENTITY\n", PRVM_serveredictvector(ent, origin)[0], PRVM_serveredictvector(ent, origin)[1], PRVM_serveredictvector(ent, origin)[2]);
VectorCopy (trace.endpos, PRVM_serveredictvector(ent, origin));
if (sv_gameplayfix_droptofloorstartsolid_nudgetocorrect.integer)
SV_NudgeOutOfSolid(ent);
SV_LinkEdict(ent);
PRVM_serveredictfloat(ent, flags) = (int)PRVM_serveredictfloat(ent, flags) | FL_ONGROUND;
PRVM_serveredictedict(ent, groundentity) = PRVM_EDICT_TO_PROG(trace.ent);
PRVM_G_FLOAT(OFS_RETURN) = 1;
// if support is destroyed, keep suspended (gross hack for floating items in various maps)
ent->priv.server->suspendedinairflag = true;
}
}
else
{
if (!trace.allsolid && trace.fraction < 1)
{
VectorCopy (trace.endpos, PRVM_serveredictvector(ent, origin));
SV_LinkEdict(ent);
PRVM_serveredictfloat(ent, flags) = (int)PRVM_serveredictfloat(ent, flags) | FL_ONGROUND;
PRVM_serveredictedict(ent, groundentity) = PRVM_EDICT_TO_PROG(trace.ent);
PRVM_G_FLOAT(OFS_RETURN) = 1;
// if support is destroyed, keep suspended (gross hack for floating items in various maps)
ent->priv.server->suspendedinairflag = true;
}
}
}
/*
===============
VM_SV_lightstyle
void(float style, string value) lightstyle
===============
*/
static void VM_SV_lightstyle(prvm_prog_t *prog)
{
int style;
const char *val;
client_t *client;
int j;
VM_SAFEPARMCOUNT(2, VM_SV_lightstyle);
style = (int)PRVM_G_FLOAT(OFS_PARM0);
val = PRVM_G_STRING(OFS_PARM1);
if( (unsigned) style >= MAX_LIGHTSTYLES ) {
prog->error_cmd( "PF_lightstyle: style: %i >= 64", style );
}
// change the string in sv
strlcpy(sv.lightstyles[style], val, sizeof(sv.lightstyles[style]));
// send message to all clients on this server
if (sv.state != ss_active)
return;
for (j = 0, client = svs.clients;j < svs.maxclients;j++, client++)
{
if (client->active && client->netconnection)
{
MSG_WriteChar (&client->netconnection->message, svc_lightstyle);
MSG_WriteChar (&client->netconnection->message,style);
MSG_WriteString (&client->netconnection->message, val);
}
}
}
/*
=============
VM_SV_checkbottom
=============
*/
static void VM_SV_checkbottom(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_checkbottom);
PRVM_G_FLOAT(OFS_RETURN) = SV_CheckBottom (PRVM_G_EDICT(OFS_PARM0));
}
/*
=============
VM_SV_pointcontents
=============
*/
static void VM_SV_pointcontents(prvm_prog_t *prog)
{
vec3_t point;
VM_SAFEPARMCOUNT(1, VM_SV_pointcontents);
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), point);
PRVM_G_FLOAT(OFS_RETURN) = Mod_Q1BSP_NativeContentsFromSuperContents(NULL, SV_PointSuperContents(point));
}
/*
=============
VM_SV_aim
Pick a vector for the player to shoot along
vector aim(entity, missilespeed)
=============
*/
static void VM_SV_aim(prvm_prog_t *prog)
{
prvm_edict_t *ent, *check, *bestent;
vec3_t start, dir, end, bestdir;
int i, j;
trace_t tr;
float dist, bestdist;
//float speed;
VM_SAFEPARMCOUNT(2, VM_SV_aim);
// assume failure if it returns early
VectorCopy(PRVM_serverglobalvector(v_forward), PRVM_G_VECTOR(OFS_RETURN));
// if sv_aim is so high it can't possibly accept anything, skip out early
if (sv_aim.value >= 1)
return;
ent = PRVM_G_EDICT(OFS_PARM0);
if (ent == prog->edicts)
{
VM_Warning(prog, "aim: can not use world entity\n");
return;
}
if (ent->priv.server->free)
{
VM_Warning(prog, "aim: can not use free entity\n");
return;
}
//speed = PRVM_G_FLOAT(OFS_PARM1);
VectorCopy (PRVM_serveredictvector(ent, origin), start);
start[2] += 20;
// try sending a trace straight
VectorCopy (PRVM_serverglobalvector(v_forward), dir);
VectorMA (start, 2048, dir, end);
tr = SV_TraceLine(start, end, MOVE_NORMAL, ent, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY, 0, collision_extendmovelength.value);
if (tr.ent && PRVM_serveredictfloat(((prvm_edict_t *)tr.ent), takedamage) == DAMAGE_AIM
&& (!teamplay.integer || PRVM_serveredictfloat(ent, team) <=0 || PRVM_serveredictfloat(ent, team) != PRVM_serveredictfloat(((prvm_edict_t *)tr.ent), team)) )
{
VectorCopy (PRVM_serverglobalvector(v_forward), PRVM_G_VECTOR(OFS_RETURN));
return;
}
// try all possible entities
VectorCopy (dir, bestdir);
bestdist = sv_aim.value;
bestent = NULL;
check = PRVM_NEXT_EDICT(prog->edicts);
for (i=1 ; i<prog->num_edicts ; i++, check = PRVM_NEXT_EDICT(check) )
{
prog->xfunction->builtinsprofile++;
if (PRVM_serveredictfloat(check, takedamage) != DAMAGE_AIM)
continue;
if (check == ent)
continue;
if (teamplay.integer && PRVM_serveredictfloat(ent, team) > 0 && PRVM_serveredictfloat(ent, team) == PRVM_serveredictfloat(check, team))
continue; // don't aim at teammate
for (j=0 ; j<3 ; j++)
end[j] = PRVM_serveredictvector(check, origin)[j]
+ 0.5*(PRVM_serveredictvector(check, mins)[j] + PRVM_serveredictvector(check, maxs)[j]);
VectorSubtract (end, start, dir);
VectorNormalize (dir);
dist = DotProduct (dir, PRVM_serverglobalvector(v_forward));
if (dist < bestdist)
continue; // to far to turn
tr = SV_TraceLine(start, end, MOVE_NORMAL, ent, SUPERCONTENTS_SOLID | SUPERCONTENTS_BODY, 0, collision_extendmovelength.value);
if (tr.ent == check)
{ // can shoot at this one
bestdist = dist;
bestent = check;
}
}
if (bestent)
{
VectorSubtract (PRVM_serveredictvector(bestent, origin), PRVM_serveredictvector(ent, origin), dir);
dist = DotProduct (dir, PRVM_serverglobalvector(v_forward));
VectorScale (PRVM_serverglobalvector(v_forward), dist, end);
end[2] = dir[2];
VectorNormalize (end);
VectorCopy (end, PRVM_G_VECTOR(OFS_RETURN));
}
else
{
VectorCopy (bestdir, PRVM_G_VECTOR(OFS_RETURN));
}
}
/*
===============================================================================
MESSAGE WRITING
===============================================================================
*/
#define MSG_BROADCAST 0 // unreliable to all
#define MSG_ONE 1 // reliable to one (msg_entity)
#define MSG_ALL 2 // reliable to all
#define MSG_INIT 3 // write to the init string
#define MSG_ENTITY 5
static sizebuf_t *WriteDest(prvm_prog_t *prog)
{
int entnum;
int dest;
prvm_edict_t *ent;
dest = (int)PRVM_G_FLOAT(OFS_PARM0);
switch (dest)
{
case MSG_BROADCAST:
return &sv.datagram;
case MSG_ONE:
ent = PRVM_PROG_TO_EDICT(PRVM_serverglobaledict(msg_entity));
entnum = PRVM_NUM_FOR_EDICT(ent);
if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active || !svs.clients[entnum-1].netconnection)
{
VM_Warning(prog, "WriteDest: tried to write to non-client\n");
return &sv.reliable_datagram;
}
else
return &svs.clients[entnum-1].netconnection->message;
default:
VM_Warning(prog, "WriteDest: bad destination\n");
case MSG_ALL:
return &sv.reliable_datagram;
case MSG_INIT:
return &sv.signon;
case MSG_ENTITY:
return sv.writeentitiestoclient_msg;
}
//return NULL;
}
static void VM_SV_WriteByte(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteByte);
MSG_WriteByte (WriteDest(prog), (int)PRVM_G_FLOAT(OFS_PARM1));
}
static void VM_SV_WriteChar(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteChar);
MSG_WriteChar (WriteDest(prog), (int)PRVM_G_FLOAT(OFS_PARM1));
}
static void VM_SV_WriteShort(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteShort);
MSG_WriteShort (WriteDest(prog), (int)PRVM_G_FLOAT(OFS_PARM1));
}
static void VM_SV_WriteLong(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteLong);
MSG_WriteLong (WriteDest(prog), (int)PRVM_G_FLOAT(OFS_PARM1));
}
static void VM_SV_WriteAngle(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteAngle);
MSG_WriteAngle (WriteDest(prog), PRVM_G_FLOAT(OFS_PARM1), sv.protocol);
}
static void VM_SV_WriteCoord(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteCoord);
MSG_WriteCoord (WriteDest(prog), PRVM_G_FLOAT(OFS_PARM1), sv.protocol);
}
static void VM_SV_WriteString(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteString);
MSG_WriteString (WriteDest(prog), PRVM_G_STRING(OFS_PARM1));
}
static void VM_SV_WriteUnterminatedString(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteUnterminatedString);
MSG_WriteUnterminatedString (WriteDest(prog), PRVM_G_STRING(OFS_PARM1));
}
static void VM_SV_WriteEntity(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_WriteEntity);
MSG_WriteShort (WriteDest(prog), PRVM_G_EDICTNUM(OFS_PARM1));
}
// writes a picture as at most size bytes of data
// message:
// IMGNAME \0 SIZE(short) IMGDATA
// if failed to read/compress:
// IMGNAME \0 \0 \0
//#501 void(float dest, string name, float maxsize) WritePicture (DP_SV_WRITEPICTURE))
static void VM_SV_WritePicture(prvm_prog_t *prog)
{
const char *imgname;
void *buf;
size_t size;
VM_SAFEPARMCOUNT(3, VM_SV_WritePicture);
imgname = PRVM_G_STRING(OFS_PARM1);
size = (size_t) PRVM_G_FLOAT(OFS_PARM2);
if(size > 65535)
size = 65535;
MSG_WriteString(WriteDest(prog), imgname);
if(Image_Compress(imgname, size, &buf, &size))
{
// actual picture
MSG_WriteShort(WriteDest(prog), (int)size);
SZ_Write(WriteDest(prog), (unsigned char *) buf, (int)size);
}
else
{
// placeholder
MSG_WriteShort(WriteDest(prog), 0);
}
}
//////////////////////////////////////////////////////////
static void VM_SV_makestatic(prvm_prog_t *prog)
{
prvm_edict_t *ent;
int i, large;
// allow 0 parameters due to an id1 qc bug in which this function is used
// with no parameters (but directly after setmodel with self in OFS_PARM0)
VM_SAFEPARMCOUNTRANGE(0, 1, VM_SV_makestatic);
if (prog->argc >= 1)
ent = PRVM_G_EDICT(OFS_PARM0);
else
ent = PRVM_PROG_TO_EDICT(PRVM_serverglobaledict(self));
if (ent == prog->edicts)
{
VM_Warning(prog, "makestatic: can not modify world entity\n");
return;
}
if (ent->priv.server->free)
{
VM_Warning(prog, "makestatic: can not modify free entity\n");
return;
}
large = false;
if (PRVM_serveredictfloat(ent, modelindex) >= 256 || PRVM_serveredictfloat(ent, frame) >= 256)
large = true;
if (large)
{
MSG_WriteByte (&sv.signon,svc_spawnstatic2);
MSG_WriteShort (&sv.signon, (int)PRVM_serveredictfloat(ent, modelindex));
MSG_WriteShort (&sv.signon, (int)PRVM_serveredictfloat(ent, frame));
}
else
{
MSG_WriteByte (&sv.signon,svc_spawnstatic);
MSG_WriteByte (&sv.signon, (int)PRVM_serveredictfloat(ent, modelindex));
MSG_WriteByte (&sv.signon, (int)PRVM_serveredictfloat(ent, frame));
}
MSG_WriteByte (&sv.signon, (int)PRVM_serveredictfloat(ent, colormap));
MSG_WriteByte (&sv.signon, (int)PRVM_serveredictfloat(ent, skin));
for (i=0 ; i<3 ; i++)
{
MSG_WriteCoord(&sv.signon, PRVM_serveredictvector(ent, origin)[i], sv.protocol);
MSG_WriteAngle(&sv.signon, PRVM_serveredictvector(ent, angles)[i], sv.protocol);
}
// throw the entity away now
PRVM_ED_Free(prog, ent);
}
//=============================================================================
/*
==============
VM_SV_setspawnparms
==============
*/
static void VM_SV_setspawnparms(prvm_prog_t *prog)
{
prvm_edict_t *ent;
int i;
client_t *client;
VM_SAFEPARMCOUNT(1, VM_SV_setspawnparms);
ent = PRVM_G_EDICT(OFS_PARM0);
i = PRVM_NUM_FOR_EDICT(ent);
if (i < 1 || i > svs.maxclients || !svs.clients[i-1].active)
{
Con_Print("tried to setspawnparms on a non-client\n");
return;
}
// copy spawn parms out of the client_t
client = svs.clients + i-1;
for (i=0 ; i< NUM_SPAWN_PARMS ; i++)
(&PRVM_serverglobalfloat(parm1))[i] = client->spawn_parms[i];
}
/*
=================
VM_SV_getlight
Returns a color vector indicating the lighting at the requested point.
(Internal Operation note: actually measures the light beneath the point, just like
the model lighting on the client)
getlight(vector)
=================
*/
static void VM_SV_getlight(prvm_prog_t *prog)
{
vec3_t ambientcolor, diffusecolor, diffusenormal;
vec3_t p;
VM_SAFEPARMCOUNT(1, VM_SV_getlight);
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), p);
VectorClear(ambientcolor);
VectorClear(diffusecolor);
VectorClear(diffusenormal);
if (sv.worldmodel && sv.worldmodel->brush.LightPoint)
sv.worldmodel->brush.LightPoint(sv.worldmodel, p, ambientcolor, diffusecolor, diffusenormal);
VectorMA(ambientcolor, 0.5, diffusecolor, PRVM_G_VECTOR(OFS_RETURN));
}
typedef struct
{
unsigned char type; // 1/2/8 or other value if isn't used
int fieldoffset;
}customstat_t;
static customstat_t *vm_customstats = NULL; //[515]: it starts from 0, not 32
static int vm_customstats_last;
void VM_CustomStats_Clear (void)
{
if(vm_customstats)
{
Z_Free(vm_customstats);
vm_customstats = NULL;
vm_customstats_last = -1;
}
}
void VM_SV_UpdateCustomStats (client_t *client, prvm_edict_t *ent, sizebuf_t *msg, int *stats)
{
prvm_prog_t *prog = SVVM_prog;
int i;
char s[17];
if(!vm_customstats)
return;
for(i=0; i<vm_customstats_last+1 ;i++)
{
if(!vm_customstats[i].type)
continue;
switch(vm_customstats[i].type)
{
//string as 16 bytes
case 1:
memset(s, 0, 17);
strlcpy(s, PRVM_E_STRING(ent, vm_customstats[i].fieldoffset), 16);
stats[i+32] = s[ 0] + s[ 1] * 256 + s[ 2] * 65536 + s[ 3] * 16777216;
stats[i+33] = s[ 4] + s[ 5] * 256 + s[ 6] * 65536 + s[ 7] * 16777216;
stats[i+34] = s[ 8] + s[ 9] * 256 + s[10] * 65536 + s[11] * 16777216;
stats[i+35] = s[12] + s[13] * 256 + s[14] * 65536 + s[15] * 16777216;
break;
//float field sent as-is
case 8:
stats[i+32] = PRVM_E_INT(ent, vm_customstats[i].fieldoffset);
break;
//integer value of float field
case 2:
stats[i+32] = (int)PRVM_E_FLOAT(ent, vm_customstats[i].fieldoffset);
break;
default:
break;
}
}
}
// void(float index, float type, .void field) SV_AddStat = #232;
// Set up an auto-sent player stat.
// Client's get thier own fields sent to them. Index may not be less than 32.
// Type is a value equating to the ev_ values found in qcc to dictate types. Valid ones are:
// 1: string (4 stats carrying a total of 16 charactures)
// 2: float (one stat, float converted to an integer for transportation)
// 8: integer (one stat, not converted to an int, so this can be used to transport floats as floats - what a unique idea!)
static void VM_SV_AddStat(prvm_prog_t *prog)
{
int off, i;
unsigned char type;
VM_SAFEPARMCOUNT(3, VM_SV_AddStat);
if(!vm_customstats)
{
vm_customstats = (customstat_t *)Z_Malloc((MAX_CL_STATS-32) * sizeof(customstat_t));
if(!vm_customstats)
{
VM_Warning(prog, "PF_SV_AddStat: not enough memory\n");
return;
}
}
i = (int)PRVM_G_FLOAT(OFS_PARM0);
type = (int)PRVM_G_FLOAT(OFS_PARM1);
off = PRVM_G_INT (OFS_PARM2);
i -= 32;
if(i < 0)
{
VM_Warning(prog, "PF_SV_AddStat: index may not be less than 32\n");
return;
}
if(i >= (MAX_CL_STATS-32))
{
VM_Warning(prog, "PF_SV_AddStat: index >= MAX_CL_STATS\n");
return;
}
if(i > (MAX_CL_STATS-32-4) && type == 1)
{
VM_Warning(prog, "PF_SV_AddStat: index > (MAX_CL_STATS-4) with string\n");
return;
}
vm_customstats[i].type = type;
vm_customstats[i].fieldoffset = off;
if(vm_customstats_last < i)
vm_customstats_last = i;
}
/*
=================
VM_SV_copyentity
copies data from one entity to another
copyentity(src, dst)
=================
*/
static void VM_SV_copyentity(prvm_prog_t *prog)
{
prvm_edict_t *in, *out;
VM_SAFEPARMCOUNT(2, VM_SV_copyentity);
in = PRVM_G_EDICT(OFS_PARM0);
if (in == prog->edicts)
{
VM_Warning(prog, "copyentity: can not read world entity\n");
return;
}
if (in->priv.server->free)
{
VM_Warning(prog, "copyentity: can not read free entity\n");
return;
}
out = PRVM_G_EDICT(OFS_PARM1);
if (out == prog->edicts)
{
VM_Warning(prog, "copyentity: can not modify world entity\n");
return;
}
if (out->priv.server->free)
{
VM_Warning(prog, "copyentity: can not modify free entity\n");
return;
}
memcpy(out->fields.fp, in->fields.fp, prog->entityfields * sizeof(prvm_vec_t));
SV_LinkEdict(out);
}
/*
=================
VM_SV_setcolor
sets the color of a client and broadcasts the update to all connected clients
setcolor(clientent, value)
=================
*/
static void VM_SV_setcolor(prvm_prog_t *prog)
{
client_t *client;
int entnum, i;
VM_SAFEPARMCOUNT(2, VM_SV_setcolor);
entnum = PRVM_G_EDICTNUM(OFS_PARM0);
i = (int)PRVM_G_FLOAT(OFS_PARM1);
if (entnum < 1 || entnum > svs.maxclients || !svs.clients[entnum-1].active)
{
Con_Print("tried to setcolor a non-client\n");
return;
}
client = svs.clients + entnum-1;
if (client->edict)
{
PRVM_serveredictfloat(client->edict, clientcolors) = i;
PRVM_serveredictfloat(client->edict, team) = (i & 15) + 1;
}
client->colors = i;
if (client->old_colors != client->colors)
{
client->old_colors = client->colors;
// send notification to all clients
MSG_WriteByte (&sv.reliable_datagram, svc_updatecolors);
MSG_WriteByte (&sv.reliable_datagram, client - svs.clients);
MSG_WriteByte (&sv.reliable_datagram, client->colors);
}
}
/*
=================
VM_SV_effect
effect(origin, modelname, startframe, framecount, framerate)
=================
*/
static void VM_SV_effect(prvm_prog_t *prog)
{
int i;
const char *s;
vec3_t org;
VM_SAFEPARMCOUNT(5, VM_SV_effect);
s = PRVM_G_STRING(OFS_PARM1);
if (!s[0])
{
VM_Warning(prog, "effect: no model specified\n");
return;
}
i = SV_ModelIndex(s, 1);
if (!i)
{
VM_Warning(prog, "effect: model not precached\n");
return;
}
if (PRVM_G_FLOAT(OFS_PARM3) < 1)
{
VM_Warning(prog, "effect: framecount < 1\n");
return;
}
if (PRVM_G_FLOAT(OFS_PARM4) < 1)
{
VM_Warning(prog, "effect: framerate < 1\n");
return;
}
VectorCopy(PRVM_G_VECTOR(OFS_PARM0), org);
SV_StartEffect(org, i, (int)PRVM_G_FLOAT(OFS_PARM2), (int)PRVM_G_FLOAT(OFS_PARM3), (int)PRVM_G_FLOAT(OFS_PARM4));
}
static void VM_SV_te_blood(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_blood);
if (PRVM_G_FLOAT(OFS_PARM2) < 1)
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_BLOOD);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// velocity
MSG_WriteChar(&sv.datagram, bound(-128, (int) PRVM_G_VECTOR(OFS_PARM1)[0], 127));
MSG_WriteChar(&sv.datagram, bound(-128, (int) PRVM_G_VECTOR(OFS_PARM1)[1], 127));
MSG_WriteChar(&sv.datagram, bound(-128, (int) PRVM_G_VECTOR(OFS_PARM1)[2], 127));
// count
MSG_WriteByte(&sv.datagram, bound(0, (int) PRVM_G_FLOAT(OFS_PARM2), 255));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_bloodshower(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(4, VM_SV_te_bloodshower);
if (PRVM_G_FLOAT(OFS_PARM3) < 1)
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_BLOODSHOWER);
// min
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// max
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// speed
MSG_WriteCoord(&sv.datagram, PRVM_G_FLOAT(OFS_PARM2), sv.protocol);
// count
MSG_WriteShort(&sv.datagram, (int)bound(0, PRVM_G_FLOAT(OFS_PARM3), 65535));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_explosionrgb(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(2, VM_SV_te_explosionrgb);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_EXPLOSIONRGB);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// color
MSG_WriteByte(&sv.datagram, bound(0, (int) (PRVM_G_VECTOR(OFS_PARM1)[0] * 255), 255));
MSG_WriteByte(&sv.datagram, bound(0, (int) (PRVM_G_VECTOR(OFS_PARM1)[1] * 255), 255));
MSG_WriteByte(&sv.datagram, bound(0, (int) (PRVM_G_VECTOR(OFS_PARM1)[2] * 255), 255));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_particlecube(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(7, VM_SV_te_particlecube);
if (PRVM_G_FLOAT(OFS_PARM3) < 1)
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_PARTICLECUBE);
// min
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// max
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// velocity
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
// count
MSG_WriteShort(&sv.datagram, (int)bound(0, PRVM_G_FLOAT(OFS_PARM3), 65535));
// color
MSG_WriteByte(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM4));
// gravity true/false
MSG_WriteByte(&sv.datagram, ((int) PRVM_G_FLOAT(OFS_PARM5)) != 0);
// randomvel
MSG_WriteCoord(&sv.datagram, PRVM_G_FLOAT(OFS_PARM6), sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_particlerain(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(5, VM_SV_te_particlerain);
if (PRVM_G_FLOAT(OFS_PARM3) < 1)
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_PARTICLERAIN);
// min
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// max
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// velocity
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
// count
MSG_WriteShort(&sv.datagram, (int)bound(0, PRVM_G_FLOAT(OFS_PARM3), 65535));
// color
MSG_WriteByte(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM4));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_particlesnow(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(5, VM_SV_te_particlesnow);
if (PRVM_G_FLOAT(OFS_PARM3) < 1)
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_PARTICLESNOW);
// min
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// max
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// velocity
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
// count
MSG_WriteShort(&sv.datagram, (int)bound(0, PRVM_G_FLOAT(OFS_PARM3), 65535));
// color
MSG_WriteByte(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM4));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_spark(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_spark);
if (PRVM_G_FLOAT(OFS_PARM2) < 1)
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_SPARK);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// velocity
MSG_WriteChar(&sv.datagram, bound(-128, (int) PRVM_G_VECTOR(OFS_PARM1)[0], 127));
MSG_WriteChar(&sv.datagram, bound(-128, (int) PRVM_G_VECTOR(OFS_PARM1)[1], 127));
MSG_WriteChar(&sv.datagram, bound(-128, (int) PRVM_G_VECTOR(OFS_PARM1)[2], 127));
// count
MSG_WriteByte(&sv.datagram, bound(0, (int) PRVM_G_FLOAT(OFS_PARM2), 255));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_gunshotquad(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_gunshotquad);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_GUNSHOTQUAD);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_spikequad(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_spikequad);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_SPIKEQUAD);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_superspikequad(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_superspikequad);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_SUPERSPIKEQUAD);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_explosionquad(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_explosionquad);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_EXPLOSIONQUAD);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_smallflash(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_smallflash);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_SMALLFLASH);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_customflash(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(4, VM_SV_te_customflash);
if (PRVM_G_FLOAT(OFS_PARM1) < 8 || PRVM_G_FLOAT(OFS_PARM2) < (1.0 / 256.0))
return;
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_CUSTOMFLASH);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// radius
MSG_WriteByte(&sv.datagram, (int)bound(0, PRVM_G_FLOAT(OFS_PARM1) / 8 - 1, 255));
// lifetime
MSG_WriteByte(&sv.datagram, (int)bound(0, PRVM_G_FLOAT(OFS_PARM2) * 256 - 1, 255));
// color
MSG_WriteByte(&sv.datagram, (int)bound(0, PRVM_G_VECTOR(OFS_PARM3)[0] * 255, 255));
MSG_WriteByte(&sv.datagram, (int)bound(0, PRVM_G_VECTOR(OFS_PARM3)[1] * 255, 255));
MSG_WriteByte(&sv.datagram, (int)bound(0, PRVM_G_VECTOR(OFS_PARM3)[2] * 255, 255));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_gunshot(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_gunshot);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_GUNSHOT);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_spike(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_spike);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_SPIKE);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_superspike(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_superspike);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_SUPERSPIKE);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_explosion(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_explosion);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_EXPLOSION);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_tarexplosion(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_tarexplosion);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_TAREXPLOSION);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_wizspike(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_wizspike);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_WIZSPIKE);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_knightspike(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_knightspike);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_KNIGHTSPIKE);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_lavasplash(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_lavasplash);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_LAVASPLASH);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_teleport(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_teleport);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_TELEPORT);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_explosion2(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_explosion2);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_EXPLOSION2);
// origin
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// color
MSG_WriteByte(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM1));
MSG_WriteByte(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM2));
SV_FlushBroadcastMessages();
}
static void VM_SV_te_lightning1(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_lightning1);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_LIGHTNING1);
// owner entity
MSG_WriteShort(&sv.datagram, PRVM_G_EDICTNUM(OFS_PARM0));
// start
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// end
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_lightning2(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_lightning2);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_LIGHTNING2);
// owner entity
MSG_WriteShort(&sv.datagram, PRVM_G_EDICTNUM(OFS_PARM0));
// start
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// end
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_lightning3(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_lightning3);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_LIGHTNING3);
// owner entity
MSG_WriteShort(&sv.datagram, PRVM_G_EDICTNUM(OFS_PARM0));
// start
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// end
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_beam(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_beam);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_BEAM);
// owner entity
MSG_WriteShort(&sv.datagram, PRVM_G_EDICTNUM(OFS_PARM0));
// start
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// end
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM2)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_plasmaburn(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(1, VM_SV_te_plasmaburn);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_PLASMABURN);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
SV_FlushBroadcastMessages();
}
static void VM_SV_te_flamejet(prvm_prog_t *prog)
{
VM_SAFEPARMCOUNT(3, VM_SV_te_flamejet);
MSG_WriteByte(&sv.datagram, svc_temp_entity);
MSG_WriteByte(&sv.datagram, TE_FLAMEJET);
// org
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM0)[2], sv.protocol);
// vel
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[0], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[1], sv.protocol);
MSG_WriteCoord(&sv.datagram, PRVM_G_VECTOR(OFS_PARM1)[2], sv.protocol);
// count
MSG_WriteByte(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM2));
SV_FlushBroadcastMessages();
}
//void(entity e, string s) clientcommand = #440; // executes a command string as if it came from the specified client
//this function originally written by KrimZon, made shorter by LordHavoc
static void VM_SV_clientcommand(prvm_prog_t *prog)
{
client_t *temp_client;
int i;
VM_SAFEPARMCOUNT(2, VM_SV_clientcommand);
//find client for this entity
i = (PRVM_NUM_FOR_EDICT(PRVM_G_EDICT(OFS_PARM0)) - 1);
if (i < 0 || i >= svs.maxclients || !svs.clients[i].active)
{
Con_Print("PF_clientcommand: entity is not a client\n");
return;
}
temp_client = host_client;
host_client = svs.clients + i;
Cmd_ExecuteString (PRVM_G_STRING(OFS_PARM1), src_client, true);
host_client = temp_client;
}
//void(entity e, entity tagentity, string tagname) setattachment = #443; // attachs e to a tag on tagentity (note: use "" to attach to entity origin/angles instead of a tag)
static void VM_SV_setattachment(prvm_prog_t *prog)
{
prvm_edict_t *e = PRVM_G_EDICT(OFS_PARM0);
prvm_edict_t *tagentity = PRVM_G_EDICT(OFS_PARM1);
const char *tagname = PRVM_G_STRING(OFS_PARM2);
dp_model_t *model;
int tagindex;
VM_SAFEPARMCOUNT(3, VM_SV_setattachment);
if (e == prog->edicts)
{
VM_Warning(prog, "setattachment: can not modify world entity\n");
return;
}
if (e->priv.server->free)
{
VM_Warning(prog, "setattachment: can not modify free entity\n");
return;
}
if (tagentity == NULL)
tagentity = prog->edicts;
tagindex = 0;
if (tagentity != NULL && tagentity != prog->edicts && tagname && tagname[0])
{
model = SV_GetModelFromEdict(tagentity);
if (model)
{
tagindex = Mod_Alias_GetTagIndexForName(model, (int)PRVM_serveredictfloat(tagentity, skin), tagname);
if (tagindex == 0)
Con_DPrintf("setattachment(edict %i, edict %i, string \"%s\"): tried to find tag named \"%s\" on entity %i (model \"%s\") but could not find it\n", PRVM_NUM_FOR_EDICT(e), PRVM_NUM_FOR_EDICT(tagentity), tagname, tagname, PRVM_NUM_FOR_EDICT(tagentity), model->name);
}
else
Con_DPrintf("setattachment(edict %i, edict %i, string \"%s\"): tried to find tag named \"%s\" on entity %i but it has no model\n", PRVM_NUM_FOR_EDICT(e), PRVM_NUM_FOR_EDICT(tagentity), tagname, tagname, PRVM_NUM_FOR_EDICT(tagentity));
}
PRVM_serveredictedict(e, tag_entity) = PRVM_EDICT_TO_PROG(tagentity);
PRVM_serveredictfloat(e, tag_index) = tagindex;
}
/////////////////////////////////////////
// DP_MD3_TAGINFO extension coded by VorteX
static int SV_GetTagIndex (prvm_prog_t *prog, prvm_edict_t *e, const char *tagname)
{
int i;
i = (int)PRVM_serveredictfloat(e, modelindex);
if (i < 1 || i >= MAX_MODELS)
return -1;
return Mod_Alias_GetTagIndexForName(SV_GetModelByIndex(i), (int)PRVM_serveredictfloat(e, skin), tagname);
}
static int SV_GetExtendedTagInfo (prvm_prog_t *prog, prvm_edict_t *e, int tagindex, int *parentindex, const char **tagname, matrix4x4_t *tag_localmatrix)
{
int r;
dp_model_t *model;
*tagname = NULL;
*parentindex = 0;
Matrix4x4_CreateIdentity(tag_localmatrix);
if (tagindex >= 0 && (model = SV_GetModelFromEdict(e)) && model->num_bones)
{
r = Mod_Alias_GetExtendedTagInfoForIndex(model, (int)PRVM_serveredictfloat(e, skin), e->priv.server->frameblend, &e->priv.server->skeleton, tagindex - 1, parentindex, tagname, tag_localmatrix);
if(!r) // success?
*parentindex += 1;
return r;
}
return 1;
}
void SV_GetEntityMatrix (prvm_prog_t *prog, prvm_edict_t *ent, matrix4x4_t *out, qboolean viewmatrix)
{
float scale;
float pitchsign = 1;
scale = PRVM_serveredictfloat(ent, scale);
if (!scale)
scale = 1.0f;
if (viewmatrix)
Matrix4x4_CreateFromQuakeEntity(out, PRVM_serveredictvector(ent, origin)[0], PRVM_serveredictvector(ent, origin)[1], PRVM_serveredictvector(ent, origin)[2] + PRVM_serveredictvector(ent, view_ofs)[2], PRVM_serveredictvector(ent, v_angle)[0], PRVM_serveredictvector(ent, v_angle)[1], PRVM_serveredictvector(ent, v_angle)[2], scale * cl_viewmodel_scale.value);
else
{
pitchsign = SV_GetPitchSign(prog, ent);
Matrix4x4_CreateFromQuakeEntity(out, PRVM_serveredictvector(ent, origin)[0], PRVM_serveredictvector(ent, origin)[1], PRVM_serveredictvector(ent, origin)[2], pitchsign * PRVM_serveredictvector(ent, angles)[0], PRVM_serveredictvector(ent, angles)[1], PRVM_serveredictvector(ent, angles)[2], scale);
}
}
static int SV_GetEntityLocalTagMatrix(prvm_prog_t *prog, prvm_edict_t *ent, int tagindex, matrix4x4_t *out)
{
dp_model_t *model;
if (tagindex >= 0 && (model = SV_GetModelFromEdict(ent)) && model->animscenes)
{
VM_GenerateFrameGroupBlend(prog, ent->priv.server->framegroupblend, ent);
VM_FrameBlendFromFrameGroupBlend(ent->priv.server->frameblend, ent->priv.server->framegroupblend, model, sv.time);
VM_UpdateEdictSkeleton(prog, ent, model, ent->priv.server->frameblend);
return Mod_Alias_GetTagMatrix(model, ent->priv.server->frameblend, &ent->priv.server->skeleton, tagindex, out);
}
*out = identitymatrix;
return 0;
}
// Warnings/errors code:
// 0 - normal (everything all-right)
// 1 - world entity
// 2 - free entity
// 3 - null or non-precached model
// 4 - no tags with requested index
// 5 - runaway loop at attachment chain
extern cvar_t cl_bob;
extern cvar_t cl_bobcycle;
extern cvar_t cl_bobup;
static int SV_GetTagMatrix (prvm_prog_t *prog, matrix4x4_t *out, prvm_edict_t *ent, int tagindex)
{
int ret;
int modelindex, attachloop;
matrix4x4_t entitymatrix, tagmatrix, attachmatrix;
dp_model_t *model;
*out = identitymatrix; // warnings and errors return identical matrix
if (ent == prog->edicts)
return 1;
if (ent->priv.server->free)
return 2;
modelindex = (int)PRVM_serveredictfloat(ent, modelindex);
if (modelindex <= 0 || modelindex >= MAX_MODELS)
return 3;
model = SV_GetModelByIndex(modelindex);
VM_GenerateFrameGroupBlend(prog, ent->priv.server->framegroupblend, ent);
VM_FrameBlendFromFrameGroupBlend(ent->priv.server->frameblend, ent->priv.server->framegroupblend, model, sv.time);
VM_UpdateEdictSkeleton(prog, ent, model, ent->priv.server->frameblend);
tagmatrix = identitymatrix;
// DP_GFX_QUAKE3MODELTAGS, scan all chain and stop on unattached entity
attachloop = 0;
for (;;)
{
if (attachloop >= 256) // prevent runaway looping
return 5;
// apply transformation by child's tagindex on parent entity and then
// by parent entity itself
ret = SV_GetEntityLocalTagMatrix(prog, ent, tagindex - 1, &attachmatrix);
if (ret && attachloop == 0)
return ret;
SV_GetEntityMatrix(prog, ent, &entitymatrix, false);
Matrix4x4_Concat(&tagmatrix, &attachmatrix, out);
Matrix4x4_Concat(out, &entitymatrix, &tagmatrix);
// next iteration we process the parent entity
if (PRVM_serveredictedict(ent, tag_entity))
{
tagindex = (int)PRVM_serveredictfloat(ent, tag_index);
ent = PRVM_EDICT_NUM(PRVM_serveredictedict(ent, tag_entity));
}
else
break;
attachloop++;
}
// RENDER_VIEWMODEL magic
if (PRVM_serveredictedict(ent, viewmodelforclient))
{
Matrix4x4_Copy(&tagmatrix, out);
ent = PRVM_EDICT_NUM(PRVM_serveredictedict(ent, viewmodelforclient));
SV_GetEntityMatrix(prog, ent, &entitymatrix, true);
Matrix4x4_Concat(out, &entitymatrix, &tagmatrix);
/*
// Cl_bob, ported from rendering code
if (PRVM_serveredictfloat(ent, health) > 0 && cl_bob.value && cl_bobcycle.value)
{
double bob, cycle;
// LordHavoc: this code is *weird*, but not replacable (I think it
// should be done in QC on the server, but oh well, quake is quake)
// LordHavoc: figured out bobup: the time at which the sin is at 180
// degrees (which allows lengthening or squishing the peak or valley)
cycle = sv.time/cl_bobcycle.value;
cycle -= (int)cycle;
if (cycle < cl_bobup.value)
cycle = sin(M_PI * cycle / cl_bobup.value);
else
cycle = sin(M_PI + M_PI * (cycle-cl_bobup.value)/(1.0 - cl_bobup.value));
// bob is proportional to velocity in the xy plane
// (don't count Z, or jumping messes it up)
bob = sqrt(PRVM_serveredictvector(ent, velocity)[0]*PRVM_serveredictvector(ent, velocity)[0] + PRVM_serveredictvector(ent, velocity)[1]*PRVM_serveredictvector(ent, velocity)[1])*cl_bob.value;
bob = bob*0.3 + bob*0.7*cycle;
Matrix4x4_AdjustOrigin(out, 0, 0, bound(-7, bob, 4));
}
*/
}
return 0;
}
//float(entity ent, string tagname) gettagindex;
static void VM_SV_gettagindex(prvm_prog_t *prog)
{
prvm_edict_t *ent;
const char *tag_name;
int tag_index;
VM_SAFEPARMCOUNT(2, VM_SV_gettagindex);
ent = PRVM_G_EDICT(OFS_PARM0);
tag_name = PRVM_G_STRING(OFS_PARM1);
if (ent == prog->edicts)
{
VM_Warning(prog, "VM_SV_gettagindex(entity #%i): can't affect world entity\n", PRVM_NUM_FOR_EDICT(ent));
return;
}
if (ent->priv.server->free)
{
VM_Warning(prog, "VM_SV_gettagindex(entity #%i): can't affect free entity\n", PRVM_NUM_FOR_EDICT(ent));
return;
}
tag_index = 0;
if (!SV_GetModelFromEdict(ent))
Con_DPrintf("VM_SV_gettagindex(entity #%i): null or non-precached model\n", PRVM_NUM_FOR_EDICT(ent));
else
{
tag_index = SV_GetTagIndex(prog, ent, tag_name);
if (tag_index == 0)
if(developer_extra.integer)
Con_DPrintf("VM_SV_gettagindex(entity #%i): tag \"%s\" not found\n", PRVM_NUM_FOR_EDICT(ent), tag_name);
}
PRVM_G_FLOAT(OFS_RETURN) = tag_index;
}
//vector(entity ent, float tagindex) gettaginfo;
static void VM_SV_gettaginfo(prvm_prog_t *prog)
{
prvm_edict_t *e;
int tagindex;
matrix4x4_t tag_matrix;
matrix4x4_t tag_localmatrix;
int parentindex;
const char *tagname;
int returncode;
vec3_t forward, left, up, origin;
const dp_model_t *model;
VM_SAFEPARMCOUNT(2, VM_SV_gettaginfo);
e = PRVM_G_EDICT(OFS_PARM0);
tagindex = (int)PRVM_G_FLOAT(OFS_PARM1);
returncode = SV_GetTagMatrix(prog, &tag_matrix, e, tagindex);
Matrix4x4_ToVectors(&tag_matrix, forward, left, up, origin);
VectorCopy(forward, PRVM_serverglobalvector(v_forward));
VectorNegate(left, PRVM_serverglobalvector(v_right));
VectorCopy(up, PRVM_serverglobalvector(v_up));
VectorCopy(origin, PRVM_G_VECTOR(OFS_RETURN));
model = SV_GetModelFromEdict(e);
VM_GenerateFrameGroupBlend(prog, e->priv.server->framegroupblend, e);
VM_FrameBlendFromFrameGroupBlend(e->priv.server->frameblend, e->priv.server->framegroupblend, model, sv.time);
VM_UpdateEdictSkeleton(prog, e, model, e->priv.server->frameblend);
SV_GetExtendedTagInfo(prog, e, tagindex, &parentindex, &tagname, &tag_localmatrix);
Matrix4x4_ToVectors(&tag_localmatrix, forward, left, up, origin);
PRVM_serverglobalfloat(gettaginfo_parent) = parentindex;
PRVM_serverglobalstring(gettaginfo_name) = tagname ? PRVM_SetTempString(prog, tagname) : 0;
VectorCopy(forward, PRVM_serverglobalvector(gettaginfo_forward));
VectorNegate(left, PRVM_serverglobalvector(gettaginfo_right));
VectorCopy(up, PRVM_serverglobalvector(gettaginfo_up));
VectorCopy(origin, PRVM_serverglobalvector(gettaginfo_offset));
switch(returncode)
{
case 1:
VM_Warning(prog, "gettagindex: can't affect world entity\n");
break;
case 2:
VM_Warning(prog, "gettagindex: can't affect free entity\n");
break;
case 3:
Con_DPrintf("SV_GetTagMatrix(entity #%i): null or non-precached model\n", PRVM_NUM_FOR_EDICT(e));
break;
case 4:
Con_DPrintf("SV_GetTagMatrix(entity #%i): model has no tag with requested index %i\n", PRVM_NUM_FOR_EDICT(e), tagindex);
break;
case 5:
Con_DPrintf("SV_GetTagMatrix(entity #%i): runaway loop at attachment chain\n", PRVM_NUM_FOR_EDICT(e));
break;
}
}
//void(entity clent) dropclient (DP_SV_DROPCLIENT)
static void VM_SV_dropclient(prvm_prog_t *prog)
{
int clientnum;
client_t *oldhostclient;
VM_SAFEPARMCOUNT(1, VM_SV_dropclient);
clientnum = PRVM_G_EDICTNUM(OFS_PARM0) - 1;
if (clientnum < 0 || clientnum >= svs.maxclients)
{
VM_Warning(prog, "dropclient: not a client\n");
return;
}
if (!svs.clients[clientnum].active)
{
VM_Warning(prog, "dropclient: that client slot is not connected\n");
return;
}
oldhostclient = host_client;
host_client = svs.clients + clientnum;
SV_DropClient(false);
host_client = oldhostclient;
}
//entity() spawnclient (DP_SV_BOTCLIENT)
static void VM_SV_spawnclient(prvm_prog_t *prog)
{
int i;
prvm_edict_t *ed;
VM_SAFEPARMCOUNT(0, VM_SV_spawnclient);
prog->xfunction->builtinsprofile += 2;
ed = prog->edicts;
for (i = 0;i < svs.maxclients;i++)
{
if (!svs.clients[i].active)
{
prog->xfunction->builtinsprofile += 100;
SV_ConnectClient (i, NULL);
// this has to be set or else ClientDisconnect won't be called
// we assume the qc will call ClientConnect...
svs.clients[i].clientconnectcalled = true;
ed = PRVM_EDICT_NUM(i + 1);
break;
}
}
VM_RETURN_EDICT(ed);
}
//float(entity clent) clienttype (DP_SV_BOTCLIENT)
static void VM_SV_clienttype(prvm_prog_t *prog)
{
int clientnum;
VM_SAFEPARMCOUNT(1, VM_SV_clienttype);
clientnum = PRVM_G_EDICTNUM(OFS_PARM0) - 1;
if (clientnum < 0 || clientnum >= svs.maxclients)
PRVM_G_FLOAT(OFS_RETURN) = 3;
else if (!svs.clients[clientnum].active)
PRVM_G_FLOAT(OFS_RETURN) = 0;
else if (svs.clients[clientnum].netconnection)
PRVM_G_FLOAT(OFS_RETURN) = 1;
else
PRVM_G_FLOAT(OFS_RETURN) = 2;
}
/*
===============
VM_SV_serverkey
string(string key) serverkey
===============
*/
static void VM_SV_serverkey(prvm_prog_t *prog)
{
char string[VM_STRINGTEMP_LENGTH];
VM_SAFEPARMCOUNT(1, VM_SV_serverkey);
InfoString_GetValue(svs.serverinfo, PRVM_G_STRING(OFS_PARM0), string, sizeof(string));
PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, string);
}
//#333 void(entity e, float mdlindex) setmodelindex (EXT_CSQC)
static void VM_SV_setmodelindex(prvm_prog_t *prog)
{
prvm_edict_t *e;
dp_model_t *mod;
int i;
VM_SAFEPARMCOUNT(2, VM_SV_setmodelindex);
e = PRVM_G_EDICT(OFS_PARM0);
if (e == prog->edicts)
{
VM_Warning(prog, "setmodelindex: can not modify world entity\n");
return;
}
if (e->priv.server->free)
{
VM_Warning(prog, "setmodelindex: can not modify free entity\n");
return;
}
i = (int)PRVM_G_FLOAT(OFS_PARM1);
if (i <= 0 || i >= MAX_MODELS)
{
VM_Warning(prog, "setmodelindex: invalid modelindex\n");
return;
}
if (!sv.model_precache[i][0])
{
VM_Warning(prog, "setmodelindex: model not precached\n");
return;
}
PRVM_serveredictstring(e, model) = PRVM_SetEngineString(prog, sv.model_precache[i]);
PRVM_serveredictfloat(e, modelindex) = i;
mod = SV_GetModelByIndex(i);
if (mod)
{
if (mod->type != mod_alias || sv_gameplayfix_setmodelrealbox.integer)
SetMinMaxSize(prog, e, mod->normalmins, mod->normalmaxs, true);
else
SetMinMaxSize(prog, e, quakemins, quakemaxs, true);
}
else
SetMinMaxSize(prog, e, vec3_origin, vec3_origin, true);
}
//#334 string(float mdlindex) modelnameforindex (EXT_CSQC)
static void VM_SV_modelnameforindex(prvm_prog_t *prog)
{
int i;
VM_SAFEPARMCOUNT(1, VM_SV_modelnameforindex);
PRVM_G_INT(OFS_RETURN) = OFS_NULL;
i = (int)PRVM_G_FLOAT(OFS_PARM0);
if (i <= 0 || i >= MAX_MODELS)
{
VM_Warning(prog, "modelnameforindex: invalid modelindex\n");
return;
}
if (!sv.model_precache[i][0])
{
VM_Warning(prog, "modelnameforindex: model not precached\n");
return;
}
PRVM_G_INT(OFS_RETURN) = PRVM_SetEngineString(prog, sv.model_precache[i]);
}
//#335 float(string effectname) particleeffectnum (EXT_CSQC)
static void VM_SV_particleeffectnum(prvm_prog_t *prog)
{
int i;
VM_SAFEPARMCOUNT(1, VM_SV_particleeffectnum);
i = SV_ParticleEffectIndex(PRVM_G_STRING(OFS_PARM0));
if (i == 0)
i = -1;
PRVM_G_FLOAT(OFS_RETURN) = i;
}
// #336 void(entity ent, float effectnum, vector start, vector end) trailparticles (EXT_CSQC)
static void VM_SV_trailparticles(prvm_prog_t *prog)
{
vec3_t start, end;
VM_SAFEPARMCOUNT(4, VM_SV_trailparticles);
if ((int)PRVM_G_FLOAT(OFS_PARM0) < 0)
return;
MSG_WriteByte(&sv.datagram, svc_trailparticles);
MSG_WriteShort(&sv.datagram, PRVM_G_EDICTNUM(OFS_PARM0));
MSG_WriteShort(&sv.datagram, (int)PRVM_G_FLOAT(OFS_PARM1));
VectorCopy(PRVM_G_VECTOR(OFS_PARM2), start);
VectorCopy(PRVM_G_VECTOR(OFS_PARM3), end);
MSG_WriteVector(&sv.datagram, start, sv.protocol);
MSG_WriteVector(&sv.datagram, end, sv.protocol);
SV_FlushBroadcastMessages();
}
//#337 void(float effectnum, vector origin, vector dir, float count) pointparticles (EXT_CSQC)
static void VM_SV_pointparticles(prvm_prog_t *prog)
{
int effectnum, count;
vec3_t org, vel;
VM_SAFEPARMCOUNTRANGE(4, 8, VM_SV_pointparticles);
if ((int)PRVM_G_FLOAT(OFS_PARM0) < 0)
return;
effectnum = (int)PRVM_G_FLOAT(OFS_PARM0);
VectorCopy(PRVM_G_VECTOR(OFS_PARM1), org);
VectorCopy(PRVM_G_VECTOR(OFS_PARM2), vel);
count = bound(0, (int)PRVM_G_FLOAT(OFS_PARM3), 65535);
if (count == 1 && !VectorLength2(vel))
{
// 1+2+12=15 bytes
MSG_WriteByte(&sv.datagram, svc_pointparticles1);
MSG_WriteShort(&sv.datagram, effectnum);
MSG_WriteVector(&sv.datagram, org, sv.protocol);
}
else
{
// 1+2+12+12+2=29 bytes
MSG_WriteByte(&sv.datagram, svc_pointparticles);
MSG_WriteShort(&sv.datagram, effectnum);
MSG_WriteVector(&sv.datagram, org, sv.protocol);
MSG_WriteVector(&sv.datagram, vel, sv.protocol);
MSG_WriteShort(&sv.datagram, count);
}
SV_FlushBroadcastMessages();
}
//PF_setpause, // void(float pause) setpause = #531;
static void VM_SV_setpause(prvm_prog_t *prog) {
int pauseValue;
pauseValue = (int)PRVM_G_FLOAT(OFS_PARM0);
if (pauseValue != 0) { //pause the game
sv.paused = 1;
sv.pausedstart = realtime;
} else { //disable pause, in case it was enabled
if (sv.paused != 0) {
sv.paused = 0;
sv.pausedstart = 0;
}
}
// send notification to all clients
MSG_WriteByte(&sv.reliable_datagram, svc_setpause);
MSG_WriteByte(&sv.reliable_datagram, sv.paused);
}
// #263 float(float modlindex) skel_create = #263; // (FTE_CSQC_SKELETONOBJECTS) create a skeleton (be sure to assign this value into .skeletonindex for use), returns skeleton index (1 or higher) on success, returns 0 on failure (for example if the modelindex is not skeletal), it is recommended that you create a new skeleton if you change modelindex.
static void VM_SV_skel_create(prvm_prog_t *prog)
{
int modelindex = (int)PRVM_G_FLOAT(OFS_PARM0);
dp_model_t *model = SV_GetModelByIndex(modelindex);
skeleton_t *skeleton;
int i;
PRVM_G_FLOAT(OFS_RETURN) = 0;
if (!model || !model->num_bones)
return;
for (i = 0;i < MAX_EDICTS;i++)
if (!prog->skeletons[i])
break;
if (i == MAX_EDICTS)
return;
prog->skeletons[i] = skeleton = (skeleton_t *)Mem_Alloc(prog->progs_mempool, sizeof(skeleton_t) + model->num_bones * sizeof(matrix4x4_t));
PRVM_G_FLOAT(OFS_RETURN) = i + 1;
skeleton->model = model;
skeleton->relativetransforms = (matrix4x4_t *)(skeleton+1);
// initialize to identity matrices
for (i = 0;i < skeleton->model->num_bones;i++)
skeleton->relativetransforms[i] = identitymatrix;
}
// #264 float(float skel, entity ent, float modlindex, float retainfrac, float firstbone, float lastbone) skel_build = #264; // (FTE_CSQC_SKELETONOBJECTS) blend in a percentage of standard animation, 0 replaces entirely, 1 does nothing, 0.5 blends half, etc, and this only alters the bones in the specified range for which out of bounds values like 0,100000 are safe (uses .frame, .frame2, .frame3, .frame4, .lerpfrac, .lerpfrac3, .lerpfrac4, .frame1time, .frame2time, .frame3time, .frame4time), returns skel on success, 0 on failure
static void VM_SV_skel_build(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
skeleton_t *skeleton;
prvm_edict_t *ed = PRVM_G_EDICT(OFS_PARM1);
int modelindex = (int)PRVM_G_FLOAT(OFS_PARM2);
float retainfrac = PRVM_G_FLOAT(OFS_PARM3);
int firstbone = PRVM_G_FLOAT(OFS_PARM4) - 1;
int lastbone = PRVM_G_FLOAT(OFS_PARM5) - 1;
dp_model_t *model = SV_GetModelByIndex(modelindex);
int numblends;
int bonenum;
int blendindex;
framegroupblend_t framegroupblend[MAX_FRAMEGROUPBLENDS];
frameblend_t frameblend[MAX_FRAMEBLENDS];
matrix4x4_t bonematrix;
matrix4x4_t matrix;
PRVM_G_FLOAT(OFS_RETURN) = 0;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
firstbone = max(0, firstbone);
lastbone = min(lastbone, model->num_bones - 1);
lastbone = min(lastbone, skeleton->model->num_bones - 1);
VM_GenerateFrameGroupBlend(prog, framegroupblend, ed);
VM_FrameBlendFromFrameGroupBlend(frameblend, framegroupblend, model, sv.time);
for (numblends = 0;numblends < MAX_FRAMEBLENDS && frameblend[numblends].lerp;numblends++)
;
for (bonenum = firstbone;bonenum <= lastbone;bonenum++)
{
memset(&bonematrix, 0, sizeof(bonematrix));
for (blendindex = 0;blendindex < numblends;blendindex++)
{
Matrix4x4_FromBonePose7s(&matrix, model->num_posescale, model->data_poses7s + 7 * (frameblend[blendindex].subframe * model->num_bones + bonenum));
Matrix4x4_Accumulate(&bonematrix, &matrix, frameblend[blendindex].lerp);
}
Matrix4x4_Normalize3(&bonematrix, &bonematrix);
Matrix4x4_Interpolate(&skeleton->relativetransforms[bonenum], &bonematrix, &skeleton->relativetransforms[bonenum], retainfrac);
}
PRVM_G_FLOAT(OFS_RETURN) = skeletonindex + 1;
}
// #265 float(float skel) skel_get_numbones = #265; // (FTE_CSQC_SKELETONOBJECTS) returns how many bones exist in the created skeleton
static void VM_SV_skel_get_numbones(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
skeleton_t *skeleton;
PRVM_G_FLOAT(OFS_RETURN) = 0;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
PRVM_G_FLOAT(OFS_RETURN) = skeleton->model->num_bones;
}
// #266 string(float skel, float bonenum) skel_get_bonename = #266; // (FTE_CSQC_SKELETONOBJECTS) returns name of bone (as a tempstring)
static void VM_SV_skel_get_bonename(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int bonenum = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
skeleton_t *skeleton;
PRVM_G_INT(OFS_RETURN) = 0;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
if (bonenum < 0 || bonenum >= skeleton->model->num_bones)
return;
PRVM_G_INT(OFS_RETURN) = PRVM_SetTempString(prog, skeleton->model->data_bones[bonenum].name);
}
// #267 float(float skel, float bonenum) skel_get_boneparent = #267; // (FTE_CSQC_SKELETONOBJECTS) returns parent num for supplied bonenum, 0 if bonenum has no parent or bone does not exist (returned value is always less than bonenum, you can loop on this)
static void VM_SV_skel_get_boneparent(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int bonenum = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
skeleton_t *skeleton;
PRVM_G_FLOAT(OFS_RETURN) = 0;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
if (bonenum < 0 || bonenum >= skeleton->model->num_bones)
return;
PRVM_G_FLOAT(OFS_RETURN) = skeleton->model->data_bones[bonenum].parent + 1;
}
// #268 float(float skel, string tagname) skel_find_bone = #268; // (FTE_CSQC_SKELETONOBJECTS) get number of bone with specified name, 0 on failure, tagindex (bonenum+1) on success, same as using gettagindex on the modelindex
static void VM_SV_skel_find_bone(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
const char *tagname = PRVM_G_STRING(OFS_PARM1);
skeleton_t *skeleton;
PRVM_G_FLOAT(OFS_RETURN) = 0;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
PRVM_G_FLOAT(OFS_RETURN) = Mod_Alias_GetTagIndexForName(skeleton->model, 0, tagname) + 1;
}
// #269 vector(float skel, float bonenum) skel_get_bonerel = #269; // (FTE_CSQC_SKELETONOBJECTS) get matrix of bone in skeleton relative to its parent - sets v_forward, v_right, v_up, returns origin (relative to parent bone)
static void VM_SV_skel_get_bonerel(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int bonenum = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
skeleton_t *skeleton;
matrix4x4_t matrix;
vec3_t forward, left, up, origin;
VectorClear(PRVM_G_VECTOR(OFS_RETURN));
VectorClear(PRVM_clientglobalvector(v_forward));
VectorClear(PRVM_clientglobalvector(v_right));
VectorClear(PRVM_clientglobalvector(v_up));
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
if (bonenum < 0 || bonenum >= skeleton->model->num_bones)
return;
matrix = skeleton->relativetransforms[bonenum];
Matrix4x4_ToVectors(&matrix, forward, left, up, origin);
VectorCopy(forward, PRVM_clientglobalvector(v_forward));
VectorNegate(left, PRVM_clientglobalvector(v_right));
VectorCopy(up, PRVM_clientglobalvector(v_up));
VectorCopy(origin, PRVM_G_VECTOR(OFS_RETURN));
}
// #270 vector(float skel, float bonenum) skel_get_boneabs = #270; // (FTE_CSQC_SKELETONOBJECTS) get matrix of bone in skeleton in model space - sets v_forward, v_right, v_up, returns origin (relative to entity)
static void VM_SV_skel_get_boneabs(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int bonenum = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
skeleton_t *skeleton;
matrix4x4_t matrix;
matrix4x4_t temp;
vec3_t forward, left, up, origin;
VectorClear(PRVM_G_VECTOR(OFS_RETURN));
VectorClear(PRVM_clientglobalvector(v_forward));
VectorClear(PRVM_clientglobalvector(v_right));
VectorClear(PRVM_clientglobalvector(v_up));
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
if (bonenum < 0 || bonenum >= skeleton->model->num_bones)
return;
matrix = skeleton->relativetransforms[bonenum];
// convert to absolute
while ((bonenum = skeleton->model->data_bones[bonenum].parent) >= 0)
{
temp = matrix;
Matrix4x4_Concat(&matrix, &skeleton->relativetransforms[bonenum], &temp);
}
Matrix4x4_ToVectors(&matrix, forward, left, up, origin);
VectorCopy(forward, PRVM_clientglobalvector(v_forward));
VectorNegate(left, PRVM_clientglobalvector(v_right));
VectorCopy(up, PRVM_clientglobalvector(v_up));
VectorCopy(origin, PRVM_G_VECTOR(OFS_RETURN));
}
// #271 void(float skel, float bonenum, vector org) skel_set_bone = #271; // (FTE_CSQC_SKELETONOBJECTS) set matrix of bone relative to its parent, reads v_forward, v_right, v_up, takes origin as parameter (relative to parent bone)
static void VM_SV_skel_set_bone(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int bonenum = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
vec3_t forward, left, up, origin;
skeleton_t *skeleton;
matrix4x4_t matrix;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
if (bonenum < 0 || bonenum >= skeleton->model->num_bones)
return;
VectorCopy(PRVM_clientglobalvector(v_forward), forward);
VectorNegate(PRVM_clientglobalvector(v_right), left);
VectorCopy(PRVM_clientglobalvector(v_up), up);
VectorCopy(PRVM_G_VECTOR(OFS_PARM2), origin);
Matrix4x4_FromVectors(&matrix, forward, left, up, origin);
skeleton->relativetransforms[bonenum] = matrix;
}
// #272 void(float skel, float bonenum, vector org) skel_mul_bone = #272; // (FTE_CSQC_SKELETONOBJECTS) transform bone matrix (relative to its parent) by the supplied matrix in v_forward, v_right, v_up, takes origin as parameter (relative to parent bone)
static void VM_SV_skel_mul_bone(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int bonenum = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
vec3_t forward, left, up, origin;
skeleton_t *skeleton;
matrix4x4_t matrix;
matrix4x4_t temp;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
if (bonenum < 0 || bonenum >= skeleton->model->num_bones)
return;
VectorCopy(PRVM_G_VECTOR(OFS_PARM2), origin);
VectorCopy(PRVM_clientglobalvector(v_forward), forward);
VectorNegate(PRVM_clientglobalvector(v_right), left);
VectorCopy(PRVM_clientglobalvector(v_up), up);
Matrix4x4_FromVectors(&matrix, forward, left, up, origin);
temp = skeleton->relativetransforms[bonenum];
Matrix4x4_Concat(&skeleton->relativetransforms[bonenum], &matrix, &temp);
}
// #273 void(float skel, float startbone, float endbone, vector org) skel_mul_bones = #273; // (FTE_CSQC_SKELETONOBJECTS) transform bone matrices (relative to their parents) by the supplied matrix in v_forward, v_right, v_up, takes origin as parameter (relative to parent bones)
static void VM_SV_skel_mul_bones(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int firstbone = PRVM_G_FLOAT(OFS_PARM1) - 1;
int lastbone = PRVM_G_FLOAT(OFS_PARM2) - 1;
int bonenum;
vec3_t forward, left, up, origin;
skeleton_t *skeleton;
matrix4x4_t matrix;
matrix4x4_t temp;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
VectorCopy(PRVM_G_VECTOR(OFS_PARM3), origin);
VectorCopy(PRVM_clientglobalvector(v_forward), forward);
VectorNegate(PRVM_clientglobalvector(v_right), left);
VectorCopy(PRVM_clientglobalvector(v_up), up);
Matrix4x4_FromVectors(&matrix, forward, left, up, origin);
firstbone = max(0, firstbone);
lastbone = min(lastbone, skeleton->model->num_bones - 1);
for (bonenum = firstbone;bonenum <= lastbone;bonenum++)
{
temp = skeleton->relativetransforms[bonenum];
Matrix4x4_Concat(&skeleton->relativetransforms[bonenum], &matrix, &temp);
}
}
// #274 void(float skeldst, float skelsrc, float startbone, float endbone) skel_copybones = #274; // (FTE_CSQC_SKELETONOBJECTS) copy bone matrices (relative to their parents) from one skeleton to another, useful for copying a skeleton to a corpse
static void VM_SV_skel_copybones(prvm_prog_t *prog)
{
int skeletonindexdst = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
int skeletonindexsrc = (int)PRVM_G_FLOAT(OFS_PARM1) - 1;
int firstbone = PRVM_G_FLOAT(OFS_PARM2) - 1;
int lastbone = PRVM_G_FLOAT(OFS_PARM3) - 1;
int bonenum;
skeleton_t *skeletondst;
skeleton_t *skeletonsrc;
if (skeletonindexdst < 0 || skeletonindexdst >= MAX_EDICTS || !(skeletondst = prog->skeletons[skeletonindexdst]))
return;
if (skeletonindexsrc < 0 || skeletonindexsrc >= MAX_EDICTS || !(skeletonsrc = prog->skeletons[skeletonindexsrc]))
return;
firstbone = max(0, firstbone);
lastbone = min(lastbone, skeletondst->model->num_bones - 1);
lastbone = min(lastbone, skeletonsrc->model->num_bones - 1);
for (bonenum = firstbone;bonenum <= lastbone;bonenum++)
skeletondst->relativetransforms[bonenum] = skeletonsrc->relativetransforms[bonenum];
}
// #275 void(float skel) skel_delete = #275; // (FTE_CSQC_SKELETONOBJECTS) deletes skeleton at the beginning of the next frame (you can add the entity, delete the skeleton, renderscene, and it will still work)
static void VM_SV_skel_delete(prvm_prog_t *prog)
{
int skeletonindex = (int)PRVM_G_FLOAT(OFS_PARM0) - 1;
skeleton_t *skeleton;
if (skeletonindex < 0 || skeletonindex >= MAX_EDICTS || !(skeleton = prog->skeletons[skeletonindex]))
return;
Mem_Free(skeleton);
prog->skeletons[skeletonindex] = NULL;
}
// #276 float(float modlindex, string framename) frameforname = #276; // (FTE_CSQC_SKELETONOBJECTS) finds number of a specified frame in the animation, returns -1 if no match found
static void VM_SV_frameforname(prvm_prog_t *prog)
{
int modelindex = (int)PRVM_G_FLOAT(OFS_PARM0);
dp_model_t *model = SV_GetModelByIndex(modelindex);
const char *name = PRVM_G_STRING(OFS_PARM1);
int i;
PRVM_G_FLOAT(OFS_RETURN) = -1;
if (!model || !model->animscenes)
return;
for (i = 0;i < model->numframes;i++)
{
if (!strcasecmp(model->animscenes[i].name, name))
{
PRVM_G_FLOAT(OFS_RETURN) = i;
break;
}
}
}
// #277 float(float modlindex, float framenum) frameduration = #277; // (FTE_CSQC_SKELETONOBJECTS) returns the intended play time (in seconds) of the specified framegroup, if it does not exist the result is 0, if it is a single frame it may be a small value around 0.1 or 0.
static void VM_SV_frameduration(prvm_prog_t *prog)
{
int modelindex = (int)PRVM_G_FLOAT(OFS_PARM0);
dp_model_t *model = SV_GetModelByIndex(modelindex);
int framenum = (int)PRVM_G_FLOAT(OFS_PARM1);
PRVM_G_FLOAT(OFS_RETURN) = 0;
if (!model || !model->animscenes || framenum < 0 || framenum >= model->numframes)
return;
if (model->animscenes[framenum].framerate)
PRVM_G_FLOAT(OFS_RETURN) = model->animscenes[framenum].framecount / model->animscenes[framenum].framerate;
}
prvm_builtin_t vm_sv_builtins[] = {
NULL, // #0 NULL function (not callable) (QUAKE)
VM_makevectors, // #1 void(vector ang) makevectors (QUAKE)
VM_SV_setorigin, // #2 void(entity e, vector o) setorigin (QUAKE)
VM_SV_setmodel, // #3 void(entity e, string m) setmodel (QUAKE)
VM_SV_setsize, // #4 void(entity e, vector min, vector max) setsize (QUAKE)
NULL, // #5 void(entity e, vector min, vector max) setabssize (QUAKE)
VM_break, // #6 void() break (QUAKE)
VM_random, // #7 float() random (QUAKE)
VM_SV_sound, // #8 void(entity e, float chan, string samp) sound (QUAKE)
VM_normalize, // #9 vector(vector v) normalize (QUAKE)
VM_error, // #10 void(string e) error (QUAKE)
VM_objerror, // #11 void(string e) objerror (QUAKE)
VM_vlen, // #12 float(vector v) vlen (QUAKE)
VM_vectoyaw, // #13 float(vector v) vectoyaw (QUAKE)
VM_spawn, // #14 entity() spawn (QUAKE)
VM_remove, // #15 void(entity e) remove (QUAKE)
VM_SV_traceline, // #16 void(vector v1, vector v2, float tryents) traceline (QUAKE)
VM_SV_checkclient, // #17 entity() checkclient (QUAKE)
VM_find, // #18 entity(entity start, .string fld, string match) find (QUAKE)
VM_SV_precache_sound, // #19 void(string s) precache_sound (QUAKE)
VM_SV_precache_model, // #20 void(string s) precache_model (QUAKE)
VM_SV_stuffcmd, // #21 void(entity client, string s, ...) stuffcmd (QUAKE)
VM_SV_findradius, // #22 entity(vector org, float rad) findradius (QUAKE)
VM_bprint, // #23 void(string s, ...) bprint (QUAKE)
VM_SV_sprint, // #24 void(entity client, string s, ...) sprint (QUAKE)
VM_dprint, // #25 void(string s, ...) dprint (QUAKE)
VM_ftos, // #26 string(float f) ftos (QUAKE)
VM_vtos, // #27 string(vector v) vtos (QUAKE)
VM_coredump, // #28 void() coredump (QUAKE)
VM_traceon, // #29 void() traceon (QUAKE)
VM_traceoff, // #30 void() traceoff (QUAKE)
VM_eprint, // #31 void(entity e) eprint (QUAKE)
VM_SV_walkmove, // #32 float(float yaw, float dist) walkmove (QUAKE)
NULL, // #33 (QUAKE)
VM_SV_droptofloor, // #34 float() droptofloor (QUAKE)
VM_SV_lightstyle, // #35 void(float style, string value) lightstyle (QUAKE)
VM_rint, // #36 float(float v) rint (QUAKE)
VM_floor, // #37 float(float v) floor (QUAKE)
VM_ceil, // #38 float(float v) ceil (QUAKE)
NULL, // #39 (QUAKE)
VM_SV_checkbottom, // #40 float(entity e) checkbottom (QUAKE)
VM_SV_pointcontents, // #41 float(vector v) pointcontents (QUAKE)
NULL, // #42 (QUAKE)
VM_fabs, // #43 float(float f) fabs (QUAKE)
VM_SV_aim, // #44 vector(entity e, float speed) aim (QUAKE)
VM_cvar, // #45 float(string s) cvar (QUAKE)
VM_localcmd, // #46 void(string s) localcmd (QUAKE)
VM_nextent, // #47 entity(entity e) nextent (QUAKE)
VM_SV_particle, // #48 void(vector o, vector d, float color, float count) particle (QUAKE)
VM_changeyaw, // #49 void() ChangeYaw (QUAKE)
NULL, // #50 (QUAKE)
VM_vectoangles, // #51 vector(vector v) vectoangles (QUAKE)
VM_SV_WriteByte, // #52 void(float to, float f) WriteByte (QUAKE)
VM_SV_WriteChar, // #53 void(float to, float f) WriteChar (QUAKE)
VM_SV_WriteShort, // #54 void(float to, float f) WriteShort (QUAKE)
VM_SV_WriteLong, // #55 void(float to, float f) WriteLong (QUAKE)
VM_SV_WriteCoord, // #56 void(float to, float f) WriteCoord (QUAKE)
VM_SV_WriteAngle, // #57 void(float to, float f) WriteAngle (QUAKE)
VM_SV_WriteString, // #58 void(float to, string s) WriteString (QUAKE)
VM_SV_WriteEntity, // #59 void(float to, entity e) WriteEntity (QUAKE)
VM_sin, // #60 float(float f) sin (DP_QC_SINCOSSQRTPOW) (QUAKE)
VM_cos, // #61 float(float f) cos (DP_QC_SINCOSSQRTPOW) (QUAKE)
VM_sqrt, // #62 float(float f) sqrt (DP_QC_SINCOSSQRTPOW) (QUAKE)
VM_changepitch, // #63 void(entity ent) changepitch (DP_QC_CHANGEPITCH) (QUAKE)
VM_SV_tracetoss, // #64 void(entity e, entity ignore) tracetoss (DP_QC_TRACETOSS) (QUAKE)
VM_etos, // #65 string(entity ent) etos (DP_QC_ETOS) (QUAKE)
NULL, // #66 (QUAKE)
VM_SV_MoveToGoal, // #67 void(float step) movetogoal (QUAKE)
VM_precache_file, // #68 string(string s) precache_file (QUAKE)
VM_SV_makestatic, // #69 void(entity e) makestatic (QUAKE)
VM_changelevel, // #70 void(string s) changelevel (QUAKE)
NULL, // #71 (QUAKE)
VM_cvar_set, // #72 void(string var, string val) cvar_set (QUAKE)
VM_SV_centerprint, // #73 void(entity client, strings) centerprint (QUAKE)
VM_SV_ambientsound, // #74 void(vector pos, string samp, float vol, float atten) ambientsound (QUAKE)
VM_SV_precache_model, // #75 string(string s) precache_model2 (QUAKE)
VM_SV_precache_sound, // #76 string(string s) precache_sound2 (QUAKE)
VM_precache_file, // #77 string(string s) precache_file2 (QUAKE)
VM_SV_setspawnparms, // #78 void(entity e) setspawnparms (QUAKE)
NULL, // #79 void(entity killer, entity killee) logfrag (QUAKEWORLD)
NULL, // #80 string(entity e, string keyname) infokey (QUAKEWORLD)
VM_stof, // #81 float(string s) stof (FRIK_FILE)
NULL, // #82 void(vector where, float set) multicast (QUAKEWORLD)
NULL, // #83 (QUAKE)
NULL, // #84 (QUAKE)
NULL, // #85 (QUAKE)
NULL, // #86 (QUAKE)
NULL, // #87 (QUAKE)
NULL, // #88 (QUAKE)
NULL, // #89 (QUAKE)
VM_SV_tracebox, // #90 void(vector v1, vector min, vector max, vector v2, float nomonsters, entity forent) tracebox (DP_QC_TRACEBOX)
VM_randomvec, // #91 vector() randomvec (DP_QC_RANDOMVEC)
VM_SV_getlight, // #92 vector(vector org) getlight (DP_QC_GETLIGHT)
VM_registercvar, // #93 float(string name, string value) registercvar (DP_REGISTERCVAR)
VM_min, // #94 float(float a, floats) min (DP_QC_MINMAXBOUND)
VM_max, // #95 float(float a, floats) max (DP_QC_MINMAXBOUND)
VM_bound, // #96 float(float minimum, float val, float maximum) bound (DP_QC_MINMAXBOUND)
VM_pow, // #97 float(float f, float f) pow (DP_QC_SINCOSSQRTPOW)
VM_findfloat, // #98 entity(entity start, .float fld, float match) findfloat (DP_QC_FINDFLOAT)
VM_checkextension, // #99 float(string s) checkextension (the basis of the extension system)
// FrikaC and Telejano range #100-#199
NULL, // #100
NULL, // #101
NULL, // #102
NULL, // #103
NULL, // #104
NULL, // #105
NULL, // #106
NULL, // #107
NULL, // #108
NULL, // #109
VM_fopen, // #110 float(string filename, float mode) fopen (FRIK_FILE)
VM_fclose, // #111 void(float fhandle) fclose (FRIK_FILE)
VM_fgets, // #112 string(float fhandle) fgets (FRIK_FILE)
VM_fputs, // #113 void(float fhandle, string s) fputs (FRIK_FILE)
VM_strlen, // #114 float(string s) strlen (FRIK_FILE)
VM_strcat, // #115 string(string s1, string s2, ...) strcat (FRIK_FILE)
VM_substring, // #116 string(string s, float start, float length) substring (FRIK_FILE)
VM_stov, // #117 vector(string) stov (FRIK_FILE)
VM_strzone, // #118 string(string s) strzone (FRIK_FILE)
VM_strunzone, // #119 void(string s) strunzone (FRIK_FILE)
NULL, // #120
NULL, // #121
NULL, // #122
NULL, // #123
NULL, // #124
NULL, // #125
NULL, // #126
NULL, // #127
NULL, // #128
NULL, // #129
NULL, // #130
NULL, // #131
NULL, // #132
NULL, // #133
NULL, // #134
NULL, // #135
NULL, // #136
NULL, // #137
NULL, // #138
NULL, // #139
NULL, // #140
NULL, // #141
NULL, // #142
NULL, // #143
NULL, // #144
NULL, // #145
NULL, // #146
NULL, // #147
NULL, // #148
NULL, // #149
VM_CallFunctionEx_SetArgFloat, // #150 void(float idx, float val) CallFunctionEx_SetArgFloat = #150; (DP_RM_CALLFUNCTIONEX)
VM_CallFunctionEx_SetArgIntFromFloat, // #151 void(float idx, float val) CallFunctionEx_SetArgInt = #151; (DP_RM_CALLFUNCTIONEX)
VM_CallFunctionEx_SetArgVector, // #152 void(float idx, vector val) CallFunctionEx_SetArgVector = #152; (DP_RM_CALLFUNCTIONEX)
VM_CallFunctionEx_SetArgInt, // #153 use this for strings/ents/fields/etc. (DP_RM_CALLFUNCTIONEX)
VM_CallFunctionEx, // #154 void(string fname, float castretval) CallFunctionEx = #154; (DP_RM_CALLFUNCTIONEX)
NULL, // #155
NULL, // #156
NULL, // #157
NULL, // #158
NULL, // #159
NULL, // #160
NULL, // #161
NULL, // #162
NULL, // #163
NULL, // #164
NULL, // #165
NULL, // #166
NULL, // #167
NULL, // #168
NULL, // #169
VM_GlobalOfs, // #170 float(string) GlobalOfs = #170; (DP_RM_GLOBALACCESS)
VM_GlobalType, // #171 float(string) GlobalType = #171; (DP_RM_GLOBALACCESS)
VM_GlobalInt, // #172 float(float) GlobalInt = #172; (DP_RM_GLOBALACCESS)
VM_GlobalFloat, // #173 float(float) GlobalFloat = #173; (DP_RM_GLOBALACCESS)
VM_GlobalSetInt, // #174 void(float, float) GlobalSetInt = #174; (DP_RM_GLOBALACCESS)
VM_GlobalSetFloat, // #175 void(float, float) GlobalSetFloat = #175; (DP_RM_GLOBALACCESS)
VM_GlobalGet, // #176 string(string) GlobalGet = #176; (DP_RM_GLOBALACCESS)
VM_GlobalSet, // #177 float(string, string) GlobalSet = #177; (DP_RM_GLOBALACCESS)
NULL, // #178
NULL, // #179
NULL, // #180
NULL, // #181
NULL, // #182
NULL, // #183
NULL, // #184
NULL, // #185
NULL, // #186
NULL, // #187
NULL, // #188
NULL, // #189
NULL, // #190
NULL, // #191
NULL, // #192
NULL, // #193
NULL, // #194
NULL, // #195
NULL, // #196
NULL, // #197
NULL, // #198
NULL, // #199
// FTEQW range #200-#299
NULL, // #200
NULL, // #201
NULL, // #202
NULL, // #203
NULL, // #204
NULL, // #205
NULL, // #206
NULL, // #207
NULL, // #208
NULL, // #209
NULL, // #210
NULL, // #211
NULL, // #212
NULL, // #213
NULL, // #214
NULL, // #215
NULL, // #216
NULL, // #217
VM_bitshift, // #218 float(float number, float quantity) bitshift (EXT_BITSHIFT)
NULL, // #219
NULL, // #220
VM_strstrofs, // #221 float(string str, string sub[, float startpos]) strstrofs (FTE_STRINGS)
VM_str2chr, // #222 float(string str, float ofs) str2chr (FTE_STRINGS)
VM_chr2str, // #223 string(float c, ...) chr2str (FTE_STRINGS)
VM_strconv, // #224 string(float ccase, float calpha, float cnum, string s, ...) strconv (FTE_STRINGS)
VM_strpad, // #225 string(float chars, string s, ...) strpad (FTE_STRINGS)
VM_infoadd, // #226 string(string info, string key, string value, ...) infoadd (FTE_STRINGS)
VM_infoget, // #227 string(string info, string key) infoget (FTE_STRINGS)
VM_strncmp, // #228 float(string s1, string s2, float len) strncmp (FTE_STRINGS)
VM_strncasecmp, // #229 float(string s1, string s2) strcasecmp (FTE_STRINGS)
VM_strncasecmp, // #230 float(string s1, string s2, float len) strncasecmp (FTE_STRINGS)
NULL, // #231
VM_SV_AddStat, // #232 void(float index, float type, .void field) SV_AddStat (EXT_CSQC)
NULL, // #233
NULL, // #234
NULL, // #235
NULL, // #236
NULL, // #237
NULL, // #238
NULL, // #239
VM_SV_checkpvs, // #240 float(vector viewpos, entity viewee) checkpvs;
NULL, // #241
NULL, // #242
NULL, // #243
NULL, // #244
NULL, // #245
NULL, // #246
NULL, // #247
NULL, // #248
NULL, // #249
NULL, // #250
NULL, // #251
NULL, // #252
NULL, // #253
NULL, // #254
NULL, // #255
NULL, // #256
NULL, // #257
NULL, // #258
NULL, // #259
NULL, // #260
NULL, // #261
NULL, // #262
VM_SV_skel_create, // #263 float(float modlindex) skel_create = #263; // (DP_SKELETONOBJECTS) create a skeleton (be sure to assign this value into .skeletonindex for use), returns skeleton index (1 or higher) on success, returns 0 on failure (for example if the modelindex is not skeletal), it is recommended that you create a new skeleton if you change modelindex.
VM_SV_skel_build, // #264 float(float skel, entity ent, float modlindex, float retainfrac, float firstbone, float lastbone) skel_build = #264; // (DP_SKELETONOBJECTS) blend in a percentage of standard animation, 0 replaces entirely, 1 does nothing, 0.5 blends half, etc, and this only alters the bones in the specified range for which out of bounds values like 0,100000 are safe (uses .frame, .frame2, .frame3, .frame4, .lerpfrac, .lerpfrac3, .lerpfrac4, .frame1time, .frame2time, .frame3time, .frame4time), returns skel on success, 0 on failure
VM_SV_skel_get_numbones, // #265 float(float skel) skel_get_numbones = #265; // (DP_SKELETONOBJECTS) returns how many bones exist in the created skeleton
VM_SV_skel_get_bonename, // #266 string(float skel, float bonenum) skel_get_bonename = #266; // (DP_SKELETONOBJECTS) returns name of bone (as a tempstring)
VM_SV_skel_get_boneparent, // #267 float(float skel, float bonenum) skel_get_boneparent = #267; // (DP_SKELETONOBJECTS) returns parent num for supplied bonenum, -1 if bonenum has no parent or bone does not exist (returned value is always less than bonenum, you can loop on this)
VM_SV_skel_find_bone, // #268 float(float skel, string tagname) skel_find_bone = #268; // (DP_SKELETONOBJECTS) get number of bone with specified name, 0 on failure, tagindex (bonenum+1) on success, same as using gettagindex on the modelindex
VM_SV_skel_get_bonerel, // #269 vector(float skel, float bonenum) skel_get_bonerel = #269; // (DP_SKELETONOBJECTS) get matrix of bone in skeleton relative to its parent - sets v_forward, v_right, v_up, returns origin (relative to parent bone)
VM_SV_skel_get_boneabs, // #270 vector(float skel, float bonenum) skel_get_boneabs = #270; // (DP_SKELETONOBJECTS) get matrix of bone in skeleton in model space - sets v_forward, v_right, v_up, returns origin (relative to entity)
VM_SV_skel_set_bone, // #271 void(float skel, float bonenum, vector org) skel_set_bone = #271; // (DP_SKELETONOBJECTS) set matrix of bone relative to its parent, reads v_forward, v_right, v_up, takes origin as parameter (relative to parent bone)
VM_SV_skel_mul_bone, // #272 void(float skel, float bonenum, vector org) skel_mul_bone = #272; // (DP_SKELETONOBJECTS) transform bone matrix (relative to its parent) by the supplied matrix in v_forward, v_right, v_up, takes origin as parameter (relative to parent bone)
VM_SV_skel_mul_bones, // #273 void(float skel, float startbone, float endbone, vector org) skel_mul_bones = #273; // (DP_SKELETONOBJECTS) transform bone matrices (relative to their parents) by the supplied matrix in v_forward, v_right, v_up, takes origin as parameter (relative to parent bones)
VM_SV_skel_copybones, // #274 void(float skeldst, float skelsrc, float startbone, float endbone) skel_copybones = #274; // (DP_SKELETONOBJECTS) copy bone matrices (relative to their parents) from one skeleton to another, useful for copying a skeleton to a corpse
VM_SV_skel_delete, // #275 void(float skel) skel_delete = #275; // (DP_SKELETONOBJECTS) deletes skeleton at the beginning of the next frame (you can add the entity, delete the skeleton, renderscene, and it will still work)
VM_SV_frameforname, // #276 float(float modlindex, string framename) frameforname = #276; // (DP_SKELETONOBJECTS) finds number of a specified frame in the animation, returns -1 if no match found
VM_SV_frameduration, // #277 float(float modlindex, float framenum) frameduration = #277; // (DP_SKELETONOBJECTS) returns the intended play time (in seconds) of the specified framegroup, if it does not exist the result is 0, if it is a single frame it may be a small value around 0.1 or 0.
NULL, // #278
NULL, // #279
NULL, // #280
NULL, // #281
NULL, // #282
NULL, // #283
NULL, // #284
NULL, // #285
NULL, // #286
NULL, // #287
NULL, // #288
NULL, // #289
NULL, // #290
NULL, // #291
NULL, // #292
NULL, // #293
NULL, // #294
NULL, // #295
NULL, // #296
NULL, // #297
NULL, // #298
NULL, // #299
// CSQC range #300-#399
NULL, // #300 void() clearscene (EXT_CSQC)
NULL, // #301 void(float mask) addentities (EXT_CSQC)
NULL, // #302 void(entity ent) addentity (EXT_CSQC)
NULL, // #303 float(float property, ...) setproperty (EXT_CSQC)
NULL, // #304 void() renderscene (EXT_CSQC)
NULL, // #305 void(vector org, float radius, vector lightcolours) adddynamiclight (EXT_CSQC)
NULL, // #306 void(string texturename, float flag[, float is2d, float lines]) R_BeginPolygon
NULL, // #307 void(vector org, vector texcoords, vector rgb, float alpha) R_PolygonVertex
NULL, // #308 void() R_EndPolygon
NULL, // #309
NULL, // #310 vector (vector v) cs_unproject (EXT_CSQC)
NULL, // #311 vector (vector v) cs_project (EXT_CSQC)
NULL, // #312
NULL, // #313
NULL, // #314
NULL, // #315 void(float width, vector pos1, vector pos2, float flag) drawline (EXT_CSQC)
NULL, // #316 float(string name) iscachedpic (EXT_CSQC)
NULL, // #317 string(string name, float trywad) precache_pic (EXT_CSQC)
NULL, // #318 vector(string picname) draw_getimagesize (EXT_CSQC)
NULL, // #319 void(string name) freepic (EXT_CSQC)
NULL, // #320 float(vector position, float character, vector scale, vector rgb, float alpha, float flag) drawcharacter (EXT_CSQC)
NULL, // #321 float(vector position, string text, vector scale, vector rgb, float alpha, float flag) drawstring (EXT_CSQC)
NULL, // #322 float(vector position, string pic, vector size, vector rgb, float alpha, float flag) drawpic (EXT_CSQC)
NULL, // #323 float(vector position, vector size, vector rgb, float alpha, float flag) drawfill (EXT_CSQC)
NULL, // #324 void(float x, float y, float width, float height) drawsetcliparea
NULL, // #325 void(void) drawresetcliparea
NULL, // #326
NULL, // #327
NULL, // #328
NULL, // #329
NULL, // #330 float(float stnum) getstatf (EXT_CSQC)
NULL, // #331 float(float stnum) getstati (EXT_CSQC)
NULL, // #332 string(float firststnum) getstats (EXT_CSQC)
VM_SV_setmodelindex, // #333 void(entity e, float mdlindex) setmodelindex (EXT_CSQC)
VM_SV_modelnameforindex, // #334 string(float mdlindex) modelnameforindex (EXT_CSQC)
VM_SV_particleeffectnum, // #335 float(string effectname) particleeffectnum (EXT_CSQC)
VM_SV_trailparticles, // #336 void(entity ent, float effectnum, vector start, vector end) trailparticles (EXT_CSQC)
VM_SV_pointparticles, // #337 void(float effectnum, vector origin [, vector dir, float count]) pointparticles (EXT_CSQC)
NULL, // #338 void(string s, ...) centerprint (EXT_CSQC)
VM_print, // #339 void(string s, ...) print (EXT_CSQC, DP_SV_PRINT)
NULL, // #340 string(float keynum) keynumtostring (EXT_CSQC)
NULL, // #341 float(string keyname) stringtokeynum (EXT_CSQC)
NULL, // #342 string(float keynum) getkeybind (EXT_CSQC)
NULL, // #343 void(float usecursor) setcursormode (EXT_CSQC)
NULL, // #344 vector() getmousepos (EXT_CSQC)
NULL, // #345 float(float framenum) getinputstate (EXT_CSQC)
NULL, // #346 void(float sens) setsensitivityscaler (EXT_CSQC)
NULL, // #347 void() runstandardplayerphysics (EXT_CSQC)
NULL, // #348 string(float playernum, string keyname) getplayerkeyvalue (EXT_CSQC)
NULL, // #349 float() isdemo (EXT_CSQC)
VM_isserver, // #350 float() isserver (EXT_CSQC)
NULL, // #351 void(vector origin, vector forward, vector right, vector up) SetListener (EXT_CSQC)
NULL, // #352 void(string cmdname) registercommand (EXT_CSQC)
VM_wasfreed, // #353 float(entity ent) wasfreed (EXT_CSQC) (should be availabe on server too)
VM_SV_serverkey, // #354 string(string key) serverkey (EXT_CSQC)
NULL, // #355
NULL, // #356
NULL, // #357
NULL, // #358
NULL, // #359
NULL, // #360 float() readbyte (EXT_CSQC)
NULL, // #361 float() readchar (EXT_CSQC)
NULL, // #362 float() readshort (EXT_CSQC)
NULL, // #363 float() readlong (EXT_CSQC)
NULL, // #364 float() readcoord (EXT_CSQC)
NULL, // #365 float() readangle (EXT_CSQC)
NULL, // #366 string() readstring (EXT_CSQC)
NULL, // #367 float() readfloat (EXT_CSQC)
NULL, // #368
NULL, // #369
NULL, // #370
NULL, // #371
NULL, // #372
NULL, // #373
NULL, // #374
NULL, // #375
NULL, // #376
NULL, // #377
NULL, // #378
NULL, // #379
NULL, // #380
NULL, // #381
NULL, // #382
NULL, // #383
NULL, // #384
NULL, // #385
NULL, // #386
NULL, // #387
NULL, // #388
NULL, // #389
NULL, // #390
NULL, // #391
NULL, // #392
NULL, // #393
NULL, // #394
NULL, // #395
NULL, // #396
NULL, // #397
NULL, // #398
NULL, // #399
// LordHavoc's range #400-#499
VM_SV_copyentity, // #400 void(entity from, entity to) copyentity (DP_QC_COPYENTITY)
VM_SV_setcolor, // #401 void(entity ent, float colors) setcolor (DP_QC_SETCOLOR)
VM_findchain, // #402 entity(.string fld, string match) findchain (DP_QC_FINDCHAIN)
VM_findchainfloat, // #403 entity(.float fld, float match) findchainfloat (DP_QC_FINDCHAINFLOAT)
VM_SV_effect, // #404 void(vector org, string modelname, float startframe, float endframe, float framerate) effect (DP_SV_EFFECT)
VM_SV_te_blood, // #405 void(vector org, vector velocity, float howmany) te_blood (DP_TE_BLOOD)
VM_SV_te_bloodshower, // #406 void(vector mincorner, vector maxcorner, float explosionspeed, float howmany) te_bloodshower (DP_TE_BLOODSHOWER)
VM_SV_te_explosionrgb, // #407 void(vector org, vector color) te_explosionrgb (DP_TE_EXPLOSIONRGB)
VM_SV_te_particlecube, // #408 void(vector mincorner, vector maxcorner, vector vel, float howmany, float color, float gravityflag, float randomveljitter) te_particlecube (DP_TE_PARTICLECUBE)
VM_SV_te_particlerain, // #409 void(vector mincorner, vector maxcorner, vector vel, float howmany, float color) te_particlerain (DP_TE_PARTICLERAIN)
VM_SV_te_particlesnow, // #410 void(vector mincorner, vector maxcorner, vector vel, float howmany, float color) te_particlesnow (DP_TE_PARTICLESNOW)
VM_SV_te_spark, // #411 void(vector org, vector vel, float howmany) te_spark (DP_TE_SPARK)
VM_SV_te_gunshotquad, // #412 void(vector org) te_gunshotquad (DP_QUADEFFECTS1)
VM_SV_te_spikequad, // #413 void(vector org) te_spikequad (DP_QUADEFFECTS1)
VM_SV_te_superspikequad, // #414 void(vector org) te_superspikequad (DP_QUADEFFECTS1)
VM_SV_te_explosionquad, // #415 void(vector org) te_explosionquad (DP_QUADEFFECTS1)
VM_SV_te_smallflash, // #416 void(vector org) te_smallflash (DP_TE_SMALLFLASH)
VM_SV_te_customflash, // #417 void(vector org, float radius, float lifetime, vector color) te_customflash (DP_TE_CUSTOMFLASH)
VM_SV_te_gunshot, // #418 void(vector org) te_gunshot (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_spike, // #419 void(vector org) te_spike (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_superspike, // #420 void(vector org) te_superspike (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_explosion, // #421 void(vector org) te_explosion (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_tarexplosion, // #422 void(vector org) te_tarexplosion (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_wizspike, // #423 void(vector org) te_wizspike (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_knightspike, // #424 void(vector org) te_knightspike (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_lavasplash, // #425 void(vector org) te_lavasplash (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_teleport, // #426 void(vector org) te_teleport (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_explosion2, // #427 void(vector org, float colorstart, float colorlength) te_explosion2 (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_lightning1, // #428 void(entity own, vector start, vector end) te_lightning1 (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_lightning2, // #429 void(entity own, vector start, vector end) te_lightning2 (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_lightning3, // #430 void(entity own, vector start, vector end) te_lightning3 (DP_TE_STANDARDEFFECTBUILTINS)
VM_SV_te_beam, // #431 void(entity own, vector start, vector end) te_beam (DP_TE_STANDARDEFFECTBUILTINS)
VM_vectorvectors, // #432 void(vector dir) vectorvectors (DP_QC_VECTORVECTORS)
VM_SV_te_plasmaburn, // #433 void(vector org) te_plasmaburn (DP_TE_PLASMABURN)
VM_getsurfacenumpoints, // #434 float(entity e, float s) getsurfacenumpoints (DP_QC_GETSURFACE)
VM_getsurfacepoint, // #435 vector(entity e, float s, float n) getsurfacepoint (DP_QC_GETSURFACE)
VM_getsurfacenormal, // #436 vector(entity e, float s) getsurfacenormal (DP_QC_GETSURFACE)
VM_getsurfacetexture, // #437 string(entity e, float s) getsurfacetexture (DP_QC_GETSURFACE)
VM_getsurfacenearpoint, // #438 float(entity e, vector p) getsurfacenearpoint (DP_QC_GETSURFACE)
VM_getsurfaceclippedpoint, // #439 vector(entity e, float s, vector p) getsurfaceclippedpoint (DP_QC_GETSURFACE)
VM_SV_clientcommand, // #440 void(entity e, string s) clientcommand (KRIMZON_SV_PARSECLIENTCOMMAND)
VM_tokenize, // #441 float(string s) tokenize (KRIMZON_SV_PARSECLIENTCOMMAND)
VM_argv, // #442 string(float n) argv (KRIMZON_SV_PARSECLIENTCOMMAND)
VM_SV_setattachment, // #443 void(entity e, entity tagentity, string tagname) setattachment (DP_GFX_QUAKE3MODELTAGS)
VM_search_begin, // #444 float(string pattern, float caseinsensitive, float quiet) search_begin (DP_QC_FS_SEARCH)
VM_search_end, // #445 void(float handle) search_end (DP_QC_FS_SEARCH)
VM_search_getsize, // #446 float(float handle) search_getsize (DP_QC_FS_SEARCH)
VM_search_getfilename, // #447 string(float handle, float num) search_getfilename (DP_QC_FS_SEARCH)
VM_cvar_string, // #448 string(string s) cvar_string (DP_QC_CVAR_STRING)
VM_findflags, // #449 entity(entity start, .float fld, float match) findflags (DP_QC_FINDFLAGS)
VM_findchainflags, // #450 entity(.float fld, float match) findchainflags (DP_QC_FINDCHAINFLAGS)
VM_SV_gettagindex, // #451 float(entity ent, string tagname) gettagindex (DP_QC_GETTAGINFO)
VM_SV_gettaginfo, // #452 vector(entity ent, float tagindex) gettaginfo (DP_QC_GETTAGINFO)
VM_SV_dropclient, // #453 void(entity clent) dropclient (DP_SV_DROPCLIENT)
VM_SV_spawnclient, // #454 entity() spawnclient (DP_SV_BOTCLIENT)
VM_SV_clienttype, // #455 float(entity clent) clienttype (DP_SV_BOTCLIENT)
VM_SV_WriteUnterminatedString, // #456 void(float to, string s) WriteUnterminatedString (DP_SV_WRITEUNTERMINATEDSTRING)
VM_SV_te_flamejet, // #457 void(vector org, vector vel, float howmany) te_flamejet = #457 (DP_TE_FLAMEJET)
NULL, // #458
VM_ftoe, // #459 entity(float num) entitybyindex (DP_QC_EDICT_NUM)
VM_buf_create, // #460 float() buf_create (DP_QC_STRINGBUFFERS)
VM_buf_del, // #461 void(float bufhandle) buf_del (DP_QC_STRINGBUFFERS)
VM_buf_getsize, // #462 float(float bufhandle) buf_getsize (DP_QC_STRINGBUFFERS)
VM_buf_copy, // #463 void(float bufhandle_from, float bufhandle_to) buf_copy (DP_QC_STRINGBUFFERS)
VM_buf_sort, // #464 void(float bufhandle, float sortpower, float backward) buf_sort (DP_QC_STRINGBUFFERS)
VM_buf_implode, // #465 string(float bufhandle, string glue) buf_implode (DP_QC_STRINGBUFFERS)
VM_bufstr_get, // #466 string(float bufhandle, float string_index) bufstr_get (DP_QC_STRINGBUFFERS)
VM_bufstr_set, // #467 void(float bufhandle, float string_index, string str) bufstr_set (DP_QC_STRINGBUFFERS)
VM_bufstr_add, // #468 float(float bufhandle, string str, float order) bufstr_add (DP_QC_STRINGBUFFERS)
VM_bufstr_free, // #469 void(float bufhandle, float string_index) bufstr_free (DP_QC_STRINGBUFFERS)
NULL, // #470
VM_asin, // #471 float(float s) VM_asin (DP_QC_ASINACOSATANATAN2TAN)
VM_acos, // #472 float(float c) VM_acos (DP_QC_ASINACOSATANATAN2TAN)
VM_atan, // #473 float(float t) VM_atan (DP_QC_ASINACOSATANATAN2TAN)
VM_atan2, // #474 float(float c, float s) VM_atan2 (DP_QC_ASINACOSATANATAN2TAN)
VM_tan, // #475 float(float a) VM_tan (DP_QC_ASINACOSATANATAN2TAN)
VM_strlennocol, // #476 float(string s) : DRESK - String Length (not counting color codes) (DP_QC_STRINGCOLORFUNCTIONS)
VM_strdecolorize, // #477 string(string s) : DRESK - Decolorized String (DP_SV_STRINGCOLORFUNCTIONS)
VM_strftime, // #478 string(float uselocaltime, string format, ...) (DP_QC_STRFTIME)
VM_tokenizebyseparator, // #479 float(string s) tokenizebyseparator (DP_QC_TOKENIZEBYSEPARATOR)
VM_strtolower, // #480 string(string s) VM_strtolower (DP_QC_STRING_CASE_FUNCTIONS)
VM_strtoupper, // #481 string(string s) VM_strtoupper (DP_QC_STRING_CASE_FUNCTIONS)
VM_cvar_defstring, // #482 string(string s) cvar_defstring (DP_QC_CVAR_DEFSTRING)
VM_SV_pointsound, // #483 void(vector origin, string sample, float volume, float attenuation) (DP_SV_POINTSOUND)
VM_strreplace, // #484 string(string search, string replace, string subject) strreplace (DP_QC_STRREPLACE)
VM_strireplace, // #485 string(string search, string replace, string subject) strireplace (DP_QC_STRREPLACE)
VM_getsurfacepointattribute,// #486 vector(entity e, float s, float n, float a) getsurfacepointattribute = #486;
NULL, // #487
NULL, // #488
NULL, // #489
NULL, // #490
NULL, // #491
NULL, // #492
NULL, // #493
VM_crc16, // #494 float(float caseinsensitive, string s, ...) crc16 = #494 (DP_QC_CRC16)
VM_cvar_type, // #495 float(string name) cvar_type = #495; (DP_QC_CVAR_TYPE)
VM_numentityfields, // #496 float() numentityfields = #496; (DP_QC_ENTITYDATA)
VM_entityfieldname, // #497 string(float fieldnum) entityfieldname = #497; (DP_QC_ENTITYDATA)
VM_entityfieldtype, // #498 float(float fieldnum) entityfieldtype = #498; (DP_QC_ENTITYDATA)
VM_getentityfieldstring, // #499 string(float fieldnum, entity ent) getentityfieldstring = #499; (DP_QC_ENTITYDATA)
VM_putentityfieldstring, // #500 float(float fieldnum, entity ent, string s) putentityfieldstring = #500; (DP_QC_ENTITYDATA)
VM_SV_WritePicture, // #501
NULL, // #502
VM_whichpack, // #503 string(string) whichpack = #503;
NULL, // #504
VM_cvar_altertype, // #505 float(string varname, float setflags, float unsetflags) cvar_altertype = #505;
NULL, // #506
NULL, // #507
NULL, // #508
NULL, // #509
VM_uri_escape, // #510 string(string in) uri_escape = #510;
VM_uri_unescape, // #511 string(string in) uri_unescape = #511;
VM_etof, // #512 float(entity ent) num_for_edict = #512 (DP_QC_NUM_FOR_EDICT)
VM_uri_get, // #513 float(string uri, float id, [string post_contenttype, string post_delim, [float buf]]) uri_get = #513; (DP_QC_URI_GET, DP_QC_URI_POST)
VM_tokenize_console, // #514 float(string str) tokenize_console = #514; (DP_QC_TOKENIZE_CONSOLE)
VM_argv_start_index, // #515 float(float idx) argv_start_index = #515; (DP_QC_TOKENIZE_CONSOLE)
VM_argv_end_index, // #516 float(float idx) argv_end_index = #516; (DP_QC_TOKENIZE_CONSOLE)
VM_buf_cvarlist, // #517 void(float buf, string prefix, string antiprefix) buf_cvarlist = #517; (DP_QC_STRINGBUFFERS_CVARLIST)
VM_cvar_description, // #518 float(string name) cvar_description = #518; (DP_QC_CVAR_DESCRIPTION)
VM_gettime, // #519 float(float timer) gettime = #519; (DP_QC_GETTIME)
NULL, // #520
NULL, // #521
NULL, // #522
NULL, // #523
NULL, // #524
NULL, // #525
NULL, // #526
NULL, // #527
NULL, // #528
VM_loadfromdata, // #529
VM_loadfromfile, // #530
VM_SV_setpause, // #531 void(float pause) setpause = #531;
VM_log, // #532
VM_getsoundtime, // #533 float(entity e, float channel) getsoundtime = #533; (DP_SND_GETSOUNDTIME)
VM_soundlength, // #534 float(string sample) soundlength = #534; (DP_SND_GETSOUNDTIME)
VM_buf_loadfile, // #535 float(string filename, float bufhandle) buf_loadfile (DP_QC_STRINGBUFFERS_EXT_WIP)
VM_buf_writefile, // #536 float(float filehandle, float bufhandle, float startpos, float numstrings) buf_writefile (DP_QC_STRINGBUFFERS_EXT_WIP)
VM_bufstr_find, // #537 float(float bufhandle, string match, float matchrule, float startpos) bufstr_find (DP_QC_STRINGBUFFERS_EXT_WIP)
VM_matchpattern, // #538 float(string s, string pattern, float matchrule) matchpattern (DP_QC_STRINGBUFFERS_EXT_WIP)
NULL, // #539
VM_physics_enable, // #540 void(entity e, float physics_enabled) physics_enable = #540; (DP_PHYSICS_ODE)
VM_physics_addforce, // #541 void(entity e, vector force, vector relative_ofs) physics_addforce = #541; (DP_PHYSICS_ODE)
VM_physics_addtorque, // #542 void(entity e, vector torque) physics_addtorque = #542; (DP_PHYSICS_ODE)
NULL, // #543
NULL, // #544
NULL, // #545
NULL, // #546
NULL, // #547
NULL, // #548
NULL, // #549
#ifndef __ANDROID__
VM_IRC_CreateSession, // #550 float(void) IRC_CreateSession = #550; (DP_RM_IRC)
VM_IRC_ConnectSession, // #551 float(float handle, string server, float port, string password, string nick, string username, string realname) IRC_ConnectSession = #551; (DP_RM_IRC)
VM_IRC_SessionExists, // #552 float(float handle) IRC_SessionExists = #552; (DP_RM_IRC)
VM_IRC_SessionIsConnected, // #553 float(float handle) IRC_SessionIsConnected = #553; (DP_RM_IRC)
VM_IRC_SendRaw, // #554 float(float handle, string command) IRC_SendRaw = #554; (DP_RM_IRC)
VM_IRC_StrError, // #555 string(float errno) IRC_StrError = #555; (DP_RM_IRC)
VM_IRC_JoinChannel, // #556 float(float handle, string channel) IRC_JoinChannel = #556; (DP_RM_IRC)
VM_IRC_PartChannel, // #557 float(float handle, string channel) IRC_PartChannel = #557; (DP_RM_IRC)
VM_IRC_Topic, // #558 float(float handle, string channel, string topic) IRC_Topic = #558; (DP_RM_IRC)
VM_IRC_CurrentNick, // #559 string(float handle) IRC_CurrentNick = #559; (DP_RM_IRC)
VM_IRC_Privmsg, // #560 float(float handle, string targ, string msg) IRC_Privmsg = #560; (DP_RM_IRC)
VM_IRC_Notice, // #561 float(float handle, string targ, string msg) IRC_Notice = #561; (DP_RM_IRC)
VM_IRC_Quit, // #562 float(float handle, string reason) IRC_Quit = #562; (DP_RM_IRC)
VM_IRC_TerminateSession, // #563 float(float handle) IRC_TerminateSession = #563; (DP_RM_IRC)
VM_IRC_DP2IRC, // #564 string(string str) IRC_DP2IRC = #564; (DP_RM_IRC)
VM_IRC_IRC2DP, // #565 string(string str) IRC_IRC2DP = #565; (DP_RM_IRC)
VM_IRC_ChangeNick, // #566 float(float handle, string nick) IRC_ChangeNick = #566; (DP_RM_IRC)
VM_IRC_ChannelMode, // #567 float(float handle, string channel, string mode) IRC_ChannelMode = #567; (DP_RM_IRC)
VM_IRC_UserMode, // #568 float(float handle, string mode) IRC_UserMode = #568; (DP_RM_IRC)
VM_IRC_MaskMatches, // #569 float(string mask, string pattern) IRC_MaskMatches = #569; (DP_RM_IRC)
VM_IRC_CTCPRequest, // #570 float(float handle, string targ, string msg) IRC_CTCPRequest = #570; (DP_RM_IRC)
VM_IRC_CTCPReply, // #571 float(float handle, string targ, string msg) IRC_CTCPReply = #571; (DP_RM_IRC)
#else
NULL, // #550
NULL, // #551
NULL, // #552
NULL, // #553
NULL, // #554
NULL, // #555
NULL, // #556
NULL, // #557
NULL, // #558
NULL, // #559
NULL, // #560
NULL, // #561
NULL, // #562
NULL, // #563
NULL, // #564
NULL, // #565
NULL, // #566
NULL, // #567
NULL, // #568
NULL, // #569
NULL, // #570
NULL, // #571
#endif
NULL, // #572
NULL, // #573
NULL, // #574
NULL, // #575
NULL, // #576
NULL, // #577
NULL, // #578
NULL, // #579
NULL, // #580
NULL, // #581
NULL, // #582
NULL, // #583
NULL, // #584
NULL, // #585
NULL, // #586
NULL, // #587
NULL, // #588
NULL, // #589
NULL, // #590
NULL, // #591
NULL, // #592
NULL, // #593
NULL, // #594
NULL, // #595
NULL, // #596
NULL, // #597
NULL, // #598
NULL, // #599
NULL, // #600
NULL, // #601
NULL, // #602
NULL, // #603
NULL, // #604
VM_callfunction, // #605
VM_writetofile, // #606
VM_isfunction, // #607
NULL, // #608
NULL, // #609
NULL, // #610
NULL, // #611
NULL, // #612
VM_parseentitydata, // #613
NULL, // #614
NULL, // #615
NULL, // #616
NULL, // #617
NULL, // #618
NULL, // #619
NULL, // #620
NULL, // #621
NULL, // #622
NULL, // #623
VM_SV_getextresponse, // #624 string getextresponse(void)
NULL, // #625
NULL, // #626
VM_sprintf, // #627 string sprintf(string format, ...)
VM_getsurfacenumtriangles, // #628 float(entity e, float s) getsurfacenumpoints (DP_QC_GETSURFACETRIANGLE)
VM_getsurfacetriangle, // #629 vector(entity e, float s, float n) getsurfacepoint (DP_QC_GETSURFACETRIANGLE)
NULL, // #630
NULL, // #631
NULL, // #632
NULL, // #633
NULL, // #634
NULL, // #635
NULL, // #636
NULL, // #637
NULL, // #638
VM_digest_hex, // #639
NULL, // #640
NULL, // #641
VM_coverage, // #642
NULL, // #643
NULL, // #644
NULL, // #645
NULL, // #646
NULL, // #647
NULL, // #648
NULL, // #649
NULL, // #650
NULL, // #651
NULL, // #652
NULL, // #653
NULL, // #654
NULL, // #655
NULL, // #656
NULL, // #657
NULL, // #658
NULL, // #659
NULL, // #660
NULL, // #661
NULL, // #662
NULL, // #663
NULL, // #664
NULL, // #665
NULL, // #666
NULL, // #667
NULL, // #668
NULL, // #669
NULL, // #670
NULL, // #671
NULL, // #672
NULL, // #673
NULL, // #674
NULL, // #675
NULL, // #676
NULL, // #677
NULL, // #678
NULL, // #679
NULL, // #680
NULL, // #681
NULL, // #682
NULL, // #683
NULL, // #684
NULL, // #685
NULL, // #686
NULL, // #687
NULL, // #688
NULL, // #689
NULL, // #690
NULL, // #691
NULL, // #692
NULL, // #693
NULL, // #694
NULL, // #695
NULL, // #696
NULL, // #697
NULL, // #698
NULL, // #699
NULL, // #700
NULL, // #701
NULL, // #702
NULL, // #703
NULL, // #704
NULL, // #705
NULL, // #706
NULL, // #707
NULL, // #708
NULL, // #709
NULL, // #710
NULL, // #711
NULL, // #712
NULL, // #713
NULL, // #714
NULL, // #715
NULL, // #716
NULL, // #717
NULL, // #718
NULL, // #719
NULL, // #720
NULL, // #721
NULL, // #722
NULL, // #723
NULL, // #724
NULL, // #725
NULL, // #726
NULL, // #727
NULL, // #728
NULL, // #729
NULL, // #730
NULL, // #731
NULL, // #732
NULL, // #733
NULL, // #734
NULL, // #735
NULL, // #736
NULL, // #737
NULL, // #738
NULL, // #739
NULL, // #740
NULL, // #741
NULL, // #742
NULL, // #743
NULL, // #744
NULL, // #745
NULL, // #746
NULL, // #747
NULL, // #748
NULL, // #749
NULL, // #750
NULL, // #751
NULL, // #752
NULL, // #753
NULL, // #754
NULL, // #755
NULL, // #756
NULL, // #757
NULL, // #758
NULL, // #759
NULL, // #760
NULL, // #761
NULL, // #762
NULL, // #763
NULL, // #764
NULL, // #765
NULL, // #766
NULL, // #767
NULL, // #768
NULL, // #769
NULL, // #770
NULL, // #771
NULL, // #772
NULL, // #773
NULL, // #774
NULL, // #775
NULL, // #776
NULL, // #777
NULL, // #778
NULL, // #779
NULL, // #780
NULL, // #781
NULL, // #782
NULL, // #783
NULL, // #784
NULL, // #785
NULL, // #786
NULL, // #787
NULL, // #788
NULL, // #789
NULL, // #790
NULL, // #791
NULL, // #792
NULL, // #793
NULL, // #794
NULL, // #795
NULL, // #796
NULL, // #797
NULL, // #798
NULL, // #799
VM_regex_match, // #800 float(string regex, string input, float offset, float size, float flags) regex_match = #800; (DP_RM_REGEX2)
VM_net_sendpacket, // #801 float(string addr, string data) net_sendpacket = #801; (DP_RM_QCSENDPACKET)
VM_GeoIP_LookUp, // #802 string(string addr) GeoIP_LookUp = #802; (DP_RM_GEOIP)
NULL
};
const int vm_sv_numbuiltins = sizeof(vm_sv_builtins) / sizeof(prvm_builtin_t);
void SVVM_init_cmd(prvm_prog_t *prog)
{
VM_Cmd_Init(prog);
}
void SVVM_reset_cmd(prvm_prog_t *prog)
{
World_End(&sv.world);
if(prog->loaded && PRVM_serverfunction(SV_Shutdown))
{
func_t s = PRVM_serverfunction(SV_Shutdown);
PRVM_serverglobalfloat(time) = sv.time;
PRVM_serverfunction(SV_Shutdown) = 0; // prevent it from getting called again
prog->ExecuteProgram(prog, s,"SV_Shutdown() required");
}
VM_Cmd_Reset(prog);
}
| nexAkari/DarkPlacesRM | svvm_cmds.c | C | gpl-2.0 | 145,404 |
// Tonokip RepRap firmware rewrite based off of Hydra-mmm firmware.
// License: GPL
#ifndef MARLIN_H
#define MARLIN_H
#define FORCE_INLINE __attribute__((always_inline)) inline
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#ifdef ARDUINO_ARCH_AVR
#include <util/delay.h>
#include <avr/eeprom.h>
#endif
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include "HAL.h"
#include "fastio.h"
#include "Configuration.h"
#include "pins.h"
#ifdef ARDUINO_ARCH_AVR
#ifndef AT90USB
#define HardwareSerial_h // trick to disable the standard HWserial
#endif
#endif
#if (ARDUINO >= 100)
# include "Arduino.h"
#else
# include "WProgram.h"
//Arduino < 1.0.0 does not define this, so we need to do it ourselves
# define analogInputToDigitalPin(p) ((p) + A0)
#endif
#ifdef AT90USB
#include "HardwareSerial.h"
#endif
#ifdef ARDUINO_ARCH_AVR
#include "MarlinSerial.h"
#endif
#ifndef cbi
#define cbi(sfr, bit) (_SFR_BYTE(sfr) &= ~_BV(bit))
#endif
#ifndef sbi
#define sbi(sfr, bit) (_SFR_BYTE(sfr) |= _BV(bit))
#endif
#include "WString.h"
#ifdef AT90USB
#ifdef BTENABLED
#define MYSERIAL bt
#else
#define MYSERIAL Serial
#endif // BTENABLED
#else
#ifdef ARDUINO_ARCH_AVR
#define MYSERIAL MSerial
#elif defined (ARDUINO_ARCH_SAM)
#define MYSERIAL Serial
#endif
#endif
#define SERIAL_PROTOCOL(x) (MYSERIAL.print(x))
#define SERIAL_PROTOCOL_F(x,y) (MYSERIAL.print(x,y))
#define SERIAL_PROTOCOLPGM(x) (serialprintPGM(PSTR(x)))
#define SERIAL_PROTOCOLLN(x) (MYSERIAL.print(x),MYSERIAL.write('\n'))
#define SERIAL_PROTOCOLLNPGM(x) (serialprintPGM(PSTR(x)),MYSERIAL.write('\n'))
const char errormagic[] PROGMEM ="Error:";
const char echomagic[] PROGMEM ="echo:";
#define SERIAL_ERROR_START (serialprintPGM(errormagic))
#define SERIAL_ERROR(x) SERIAL_PROTOCOL(x)
#define SERIAL_ERRORPGM(x) SERIAL_PROTOCOLPGM(x)
#define SERIAL_ERRORLN(x) SERIAL_PROTOCOLLN(x)
#define SERIAL_ERRORLNPGM(x) SERIAL_PROTOCOLLNPGM(x)
#define SERIAL_ECHO_START (serialprintPGM(echomagic))
#define SERIAL_ECHO(x) SERIAL_PROTOCOL(x)
#define SERIAL_ECHOPGM(x) SERIAL_PROTOCOLPGM(x)
#define SERIAL_ECHOLN(x) SERIAL_PROTOCOLLN(x)
#define SERIAL_ECHOLNPGM(x) SERIAL_PROTOCOLLNPGM(x)
#define SERIAL_ECHOPAIR(name,value) (serial_echopair_P(PSTR(name),(value)))
void serial_echopair_P(const char *s_P, float v);
void serial_echopair_P(const char *s_P, double v);
void serial_echopair_P(const char *s_P, unsigned long v);
//Things to write to serial from Program memory. Saves 400 to 2k of RAM.
FORCE_INLINE void serialprintPGM(const char *str)
{
char ch=pgm_read_byte(str);
while(ch)
{
MYSERIAL.write(ch);
ch=pgm_read_byte(++str);
}
}
void get_command();
void process_commands();
void manage_inactivity();
#if defined(DUAL_X_CARRIAGE) && defined(X_ENABLE_PIN) && X_ENABLE_PIN > -1 \
&& defined(X2_ENABLE_PIN) && X2_ENABLE_PIN > -1
#define enable_x() do { WRITE(X_ENABLE_PIN, X_ENABLE_ON); WRITE(X2_ENABLE_PIN, X_ENABLE_ON); } while (0)
#define disable_x() do { WRITE(X_ENABLE_PIN,!X_ENABLE_ON); WRITE(X2_ENABLE_PIN,!X_ENABLE_ON); axis_known_position[X_AXIS] = false; } while (0)
#elif defined(X_ENABLE_PIN) && X_ENABLE_PIN > -1
#define enable_x() WRITE(X_ENABLE_PIN, X_ENABLE_ON)
#define disable_x() { WRITE(X_ENABLE_PIN,!X_ENABLE_ON); axis_known_position[X_AXIS] = false; }
#else
#define enable_x() ;
#define disable_x() ;
#endif
#if defined(Y_ENABLE_PIN) && Y_ENABLE_PIN > -1
#ifdef Y_DUAL_STEPPER_DRIVERS
#define enable_y() { WRITE(Y_ENABLE_PIN, Y_ENABLE_ON); WRITE(Y2_ENABLE_PIN, Y_ENABLE_ON); }
#define disable_y() { WRITE(Y_ENABLE_PIN,!Y_ENABLE_ON); WRITE(Y2_ENABLE_PIN, !Y_ENABLE_ON); axis_known_position[Y_AXIS] = false; }
#else
#define enable_y() WRITE(Y_ENABLE_PIN, Y_ENABLE_ON)
#define disable_y() { WRITE(Y_ENABLE_PIN,!Y_ENABLE_ON); axis_known_position[Y_AXIS] = false; }
#endif
#else
#define enable_y() ;
#define disable_y() ;
#endif
#if defined(Z_ENABLE_PIN) && Z_ENABLE_PIN > -1
#ifdef Z_DUAL_STEPPER_DRIVERS
#define enable_z() { WRITE(Z_ENABLE_PIN, Z_ENABLE_ON); WRITE(Z2_ENABLE_PIN, Z_ENABLE_ON); }
#define disable_z() { WRITE(Z_ENABLE_PIN,!Z_ENABLE_ON); WRITE(Z2_ENABLE_PIN,!Z_ENABLE_ON); axis_known_position[Z_AXIS] = false; }
#else
#define enable_z() WRITE(Z_ENABLE_PIN, Z_ENABLE_ON)
#define disable_z() { WRITE(Z_ENABLE_PIN,!Z_ENABLE_ON); axis_known_position[Z_AXIS] = false; }
#endif
#else
#define enable_z() ;
#define disable_z() ;
#endif
#if defined(E0_ENABLE_PIN) && (E0_ENABLE_PIN > -1)
#ifdef LASER
#define laser_on() enable_e0()
#define laser_off() disable_e0()
#define enable_e0() WRITE(E0_ENABLE_PIN, !E_ENABLE_ON)
#define disable_e0() WRITE(E0_ENABLE_PIN,E_ENABLE_ON)
#define WRITE_DAC0(X) dacc_write_conversion_data(DACC, (char)X << 4);
#define WRITE_DAC1(X) dacc_write_conversion_data(DACC, 0x1 << 12 | (char)X << 4);
#else
#define enable_e0() WRITE(E0_ENABLE_PIN, E_ENABLE_ON)
#define disable_e0() WRITE(E0_ENABLE_PIN,!E_ENABLE_ON)
#endif // LASER
#else
#define enable_e0() /* nothing */
#define disable_e0() /* nothing */
#endif
#if (EXTRUDERS > 1) && defined(E1_ENABLE_PIN) && (E1_ENABLE_PIN > -1)
#define enable_e1() WRITE(E1_ENABLE_PIN, E_ENABLE_ON)
#define disable_e1() WRITE(E1_ENABLE_PIN,!E_ENABLE_ON)
#else
#define enable_e1() /* nothing */
#define disable_e1() /* nothing */
#endif
#if (EXTRUDERS > 2) && defined(E2_ENABLE_PIN) && (E2_ENABLE_PIN > -1)
#define enable_e2() WRITE(E2_ENABLE_PIN, E_ENABLE_ON)
#define disable_e2() WRITE(E2_ENABLE_PIN,!E_ENABLE_ON)
#else
#define enable_e2() /* nothing */
#define disable_e2() /* nothing */
#endif
#if defined(RED_DOT_LASER) && (RED_DOT_LASER > -1)
#define enable_red_dot() WRITE(RED_DOT_LASER, HIGH)
#define disable_red_dot() WRITE(RED_DOT_LASER, LOW)
#endif
#if defined(RED_CROSS_LASER) && (RED_CROSS_LASER > -1)
#define enable_red_cross() WRITE(RED_CROSS_LASER, HIGH)
#define disable_red_cross() WRITE(RED_CROSS_LASER, LOW)
#endif
enum AxisEnum {X_AXIS=0, Y_AXIS=1, Z_AXIS=2, E_AXIS=3};
void FlushSerialRequestResend();
void ClearToSend();
void get_coordinates();
#ifdef DELTA
void calculate_delta(float cartesian[3]);
extern float delta[3];
#endif
void prepare_move();
void kill();
void Stop();
bool IsStopped();
void enquecommand(const char *cmd); //put an ASCII command at the end of the current buffer.
void enquecommand_P(const char *cmd); //put an ASCII command at the end of the current buffer, read from flash
void prepare_arc_move(char isclockwise);
void clamp_to_software_endstops(float target[3]);
void refresh_cmd_timeout(void);
#ifdef FAST_PWM_FAN
void setPwmFrequency(uint8_t pin, int val);
#endif
extern float homing_feedrate[];
extern bool axis_relative_modes[];
extern int feedmultiply;
extern int extrudemultiply; // Sets extrude multiply factor (in percent) for all extruders
extern int extruder_multiply[EXTRUDERS]; // sets extrude multiply factor (in percent) for each extruder individually
extern float volumetric_multiplier[EXTRUDERS]; // reciprocal of cross-sectional area of filament (in square millimeters), stored this way to reduce computational burden in planner
extern float current_position[NUM_AXIS] ;
extern float add_homeing[3];
#ifdef LASER
typedef enum {CONTINUOUS = 0, PULSED = 1, RASTER = 2} laser_e;
extern bool laserArmed;
extern laser_e laserMode;
extern float laserIntensity;
#endif
#ifdef DELTA
extern float endstop_adj[3];
extern float delta_radius;
extern float delta_diagonal_rod;
extern float delta_segments_per_second;
void recalc_delta_settings(float radius, float diagonal_rod);
#endif
extern float min_pos[3];
extern float max_pos[3];
extern bool axis_known_position[3];
extern float zprobe_zoffset;
extern int fanSpeed;
#ifdef BARICUDA
extern int ValvePressure;
extern int EtoPPressure;
#endif
#ifdef FAN_SOFT_PWM
extern unsigned char fanSpeedSoftPwm;
#endif
#ifdef FWRETRACT
extern bool autoretract_enabled;
extern bool retracted;
extern float retract_length, retract_feedrate, retract_zlift;
extern float retract_recover_length, retract_recover_feedrate;
#endif
extern unsigned long starttime;
extern unsigned long stoptime;
// Handling multiple extruders pins
extern uint8_t active_extruder;
#ifdef DIGIPOT_I2C
extern void digipot_i2c_set_current( int channel, float current );
extern void digipot_i2c_init();
#endif
#endif
| PostTenebrasLab/Laser_Cutter_upgrade | Marlin/Marlin.h | C | gpl-2.0 | 8,402 |
#! /bin/sh
# Copyright (C) 2003-2017 Free Software Foundation, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, 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 <https://www.gnu.org/licenses/>.
# Test to make sure a sensible default source for libraries is used.
required='cc libtool'
. test-init.sh
cat >> configure.ac << 'END'
AC_PROG_CC
AM_PROG_AR
AC_PROG_LIBTOOL
AC_OUTPUT
END
mkdir zoo.d
cat > Makefile.am << 'END'
AM_LDFLAGS = -module
pkglib_LTLIBRARIES = zoo.d/bar.la old.la
noinst_LTLIBRARIES = foo.la zoo.d/old2.la
$(srcdir)/zoo_d_old2_la.c: $(srcdir)/old_la.c
cp $(srcdir)/old_la.c $@
AUTOMAKE_OPTIONS = -Wno-unsupported
END
cat > foo.c << 'END'
int foo (void)
{
return 0;
}
END
cp foo.c zoo.d/bar.c
cp foo.c old_la.c
libtoolize
$ACLOCAL
$AUTOCONF
AUTOMAKE_fails -a
grep '^Makefile\.am:2:.*old_la\.c' stderr
grep '^Makefile\.am:2:.*old\.c' stderr
grep '^Makefile\.am:3:.*zoo_d_old2_la\.c' stderr
grep '^Makefile\.am:3:.*zoo\.d/old2\.c' stderr
$AUTOMAKE -Wno-obsolete
mkdir sub
cd sub
../configure
$MAKE
test -f foo.la
test -f zoo.d/bar.la
test -f old.la
test -f zoo.d/old2.la
$MAKE distcheck
:
| pylam/automake | t/ltlibsrc.sh | Shell | gpl-2.0 | 1,619 |
@extends('layouts.admin')
@section('title', 'Crear Categoria')
@section('content')
<h1 class="page-header">Crear Categoria</h1>
{!! Form::open(array(
'url' => route('admin.categories.store'),
'class' => 'form-horizontal',
'role' => 'form'
)) !!}
{{-- Name --}}
<div class="form-group{{ $errors->has('name') ? ' has-error' : '' }}">
{!! Form::label('name', 'Nombre', ['class' => 'col-sm-3 control-label']) !!}
<div class="col-sm-9 col-md-6">
{!! Form::text('name', old('name'), array(
'class' => 'form-control',
'aria-describedby' => 'helpBlock1'
)) !!}
@if($errors->has('name'))
<span id="helpBlock1" class="help-block">
<strong>{{ $errors->first('name') }}</strong>
</span>
@endif
</div>
</div>
{{-- Submit --}}
<div class="form-group">
<div class="col-sm-9 col-md-6 col-sm-offset-3">
{!! Form::button('Crear', array(
'type' => 'submit',
'class' => 'btn btn-success'
)) !!}
</div>
</div>
{!! Form::close() !!}
@endsection | JManuelMtz/TecnoComputadoras | resources/views/admin/categories/create.blade.php | PHP | gpl-2.0 | 1,046 |
/* SCCS %W%---%G%--%U% */
// Copyright: Copyright (c) 1997 University of Southern California Brain Project.
// Copyright: This software may be freely copied provided the toplevel
// Copyright: COPYRIGHT file is included with each such copy.
// Copyright: Email nsl@java.usc.edu.
package nslj.src.lang;
import nslj.src.nsls.struct.Executive;
import nslj.src.system.NslSystem;
import java.io.*;
public class NslOut extends PrintStream {
NslSystem system;
public NslOut(OutputStream out) {
super(out);
system = Executive.system;
}
public boolean checkError() { return false; }
public void close() {}
public void flush() {}
protected void setError() {}
public void write(byte[] buf, int off, int len) {}
public void write(int b) {}
public synchronized void print(boolean b) {
system.nslPrint(""+b);
}
public synchronized void print(char c) {
system.nslPrint(""+c);
}
public synchronized void print(char[] s) {
system.nslPrint(new String(s));
}
public synchronized void print(double d) {
system.nslPrint(""+d);
}
public synchronized void print(float f) {
system.nslPrint(""+f);
}
public synchronized void print(int i) {
system.nslPrint(""+i);
}
public synchronized void print(long l) {
system.nslPrint(""+l);
}
public synchronized void print(Object obj) {
Object temp = transform(obj);
system.nslPrint(temp.toString());
}
public synchronized void print(String s) {
system.nslPrint(s);
}
public synchronized void println(boolean b) {
system.nslPrintln(""+b);
}
public synchronized void println(char c) {
system.nslPrintln(""+c);
}
public synchronized void println(char[] s) {
system.nslPrintln(new String(s));
}
public synchronized void println(double d) {
system.nslPrintln(""+d);
}
public synchronized void println(float f) {
system.nslPrintln(""+f);
}
public synchronized void println(int i) {
system.nslPrintln(""+i);
}
public synchronized void println(long l) {
system.nslPrintln(""+l);
}
public synchronized void println(Object obj) {
system.nslPrintln(obj.toString());
}
public synchronized void println(String s) {
system.nslPrintln(s);
}
public synchronized NslData transform(Object obj) {
Object temp=obj;
if (obj instanceof double[]) {
return new NslDouble1((double[])obj);
} else if (obj instanceof double[][]) {
return new NslDouble2((double[][])obj);
} else if (obj instanceof double[][][]) {
return new NslDouble3((double[][][])obj);
} else if (obj instanceof double[][][][]) {
return new NslDouble4((double[][][][])obj);
} else if (obj instanceof float[]) {
return new NslFloat1((float[])obj);
} else if (obj instanceof float[][]) {
return new NslFloat2((float[][])obj);
} else if (obj instanceof float[][][]) {
return new NslFloat3((float[][][])obj);
} else if (obj instanceof float[][][][]) {
return new NslFloat4((float[][][][])obj);
} else if (obj instanceof boolean[]) {
return new NslBoolean1((boolean[])obj);
} else if (obj instanceof boolean[][]) {
return new NslBoolean2((boolean[][])obj);
} else if (obj instanceof int[]) {
return new NslInt1((int[])obj);
} else if (obj instanceof int[][]) {
return new NslInt2((int[][])obj);
} else if (obj instanceof int[][][]) {
return new NslInt3((int[][][])obj);
} else if (obj instanceof int[][][][]) {
return new NslInt4((int[][][][])obj);
}
return (NslData)obj;
}
}
| salvadormarmol/NSL_3_0_S | nslj/src/lang/NslOut.java | Java | gpl-2.0 | 3,988 |
/*************************************************************************
> File Name: hash.c
> Author: likeyi
> Mail: likeyi@sina.com
> Created Time: Tue 17 Jun 2014 04:36:47 PM CST
************************************************************************/
#include "includes.h"
extern int global_trace;
static int next_prime(int x)
{
long i, j;
int f;
x = (x==0)?1:x;
i = x;
while (i++)
{
f=1;
for (j=2; j<i; j++)
{
if (i%j == 0)
{
f=0;
break;
}
}
if (f)
{
return (int)i;
}
}
return 0;
}
struct blist * find_list(struct list_head * head,
void * item,
compare * compare_handler)
{
struct list_head * p;
struct blist * node;
list_for_each(p,head)
{
node = list_entry(p,struct blist,listhead);
if(compare_handler(node->item, item) == 0)
{
return node->item;
}
}
return NULL;
}
/*
* 1. 创建
* */
hash_table * hash_create(int num,ht_ops_t * ops)
{
exit_if_ptr_is_null(ops,"ht ops is null");
hash_table * result;
bucket_t * b;
int bytes;
int i;
result = malloc(sizeof(hash_table));
exit_if_ptr_is_null(result,"Initizial hash table Error");
num = next_prime(num);
bytes = num * sizeof(bucket_t);
result->buckets = b = malloc(bytes);
exit_if_ptr_is_null(result->buckets,"hash table buckets alloc error");
result->ops = malloc(sizeof(ht_ops_t));
exit_if_ptr_is_null(result->ops,"hash ops alloc error");
memcpy(result->ops,ops,sizeof(ht_ops_t));
result->num_buckets = num;
i = num;
while(--i >= 0)
{
INIT_LIST_HEAD(&b->list);
pthread_mutex_init(&b->lock, NULL);
b->count = 0;
b++;
}
return result;
}
/*
* 2. 查找
* 查找的本质是,给出一组特性
* hash_lookup把特性编程key,然后再把比较特性。
* */
void * hash_lookup_item(hash_table * ht,
uint32_t key,
void * value)
{
struct list_head * ll;
bucket_t * bucket = &ht -> buckets[key % ht->num_buckets];
ll = &bucket->list;
compare * compare_handler = ht->ops->compare_handler;
if(compare_handler == NULL)
{
TRACE(LOG_FAULT,"compare_handler can not be NULL\n");
exit(0);
}
return (void *) find_list(ll,value,compare_handler);
}
/*
* 3. 插入
* 严格说来,blist 完全没有任何问题。
* */
int hash_add_item(hash_table ** htp, uint32_t key, void * value )
{
struct list_head * ll;
struct blist * blist;
struct blist * new_blist;
hash_table * ht = *htp;
void * item = (void *)value;
//manager_t * manager = list_entry(htp,manager_t,ht);
/*
*
* */
bucket_t * bucket = &ht -> buckets[key % ht->num_buckets];
pthread_mutex_lock(&bucket->lock);
ll = &bucket->list;
compare * compare_handler = ht->ops->compare_handler;
if(compare_handler == NULL)
{
TRACE(LOG_FAULT,"compare_handler can not be NULL\n");
exit(0);
}
blist = find_list(ll,item,compare_handler);
/*
* 假如不存在于链表中。
* */
if(!blist)
{
/*
* 初始化,并且添加到新建的列表里。
* */
if(ht->ops->new_handler)
{
ht->ops->new_handler(&new_blist,value);
INIT_LIST_HEAD(&new_blist->listhead);
list_add_tail(&new_blist->listhead,ll);
++bucket->count;
}
else
{
TRACE(LOG_WARN,"make_new should not be NULL");
}
}
/*
* Found it, and memcpy it.
* 主要是这一段无法公共化,其他的hash函数可能找到后,并不会copy
* */
else
{
TRACE(LOG_INFO,"existed_handler:%p\n",ht->ops->existed_handler);
if(ht->ops->existed_handler)
{
ht->ops->existed_handler(blist,value);
}
}
pthread_mutex_unlock(&bucket->lock);
return 0;
}
/*
* 4. 遍历
* */
void hash_travel_delete(hash_table * ht)
{
register int i = 0;
register bucket_t * bucket;
delete * delete_item = ht->ops->delete_handler;
bucket = ht->buckets;
while(i++ < ht->num_buckets)
{
pthread_mutex_lock(&bucket->lock);
if(delete_item == NULL)
{
TRACE(LOG_WARN,"delete_item is null\n");
}
else
{
delete_item(bucket);
}
pthread_mutex_unlock(&bucket->lock);
bucket++;
}
}
void hash_travel_viewer(hash_table * ht)
{
register int i = 0;
register bucket_t * bucket;
viewer * viewer_handler = ht->ops->viewer_handler;
bucket = ht->buckets;
while(i++ < ht->num_buckets)
{
pthread_mutex_lock(&bucket->lock);
if(viewer_handler == NULL)
{
TRACE(LOG_WARN,"viewer handler is null\n");
}
else
{
viewer_handler(bucket);
}
pthread_mutex_unlock(&bucket->lock);
bucket++;
}
}
/*
* unsigned int hash_count(hash_table *ht)
*
* Return total number of elements contained in hash table.
*/
uint32_t hash_count(hash_table * ht)
{
register int i = 0;
register int cnt = 0;
register bucket_t *bucket;
bucket = ht->buckets;
while (i++ < ht->num_buckets)
{
cnt += bucket->count;
bucket++;
}
return cnt;
}
| likeyiyy/hash | hash.c | C | gpl-2.0 | 5,698 |
/***************************************************************************
* Copyright (C) 2007 - 2021 by Volker Schroer, DL1KSV *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#define VERSION "LinLogBook 0.6.0"
#include "linlogbook.h"
#include "setup.h"
#include "operatorsetup.h"
#include "createdatabasefields.h"
#include "qsotablemodel.h"
#include "linlogbookserver.h"
#include "statisticstotal.h"
#include "setupqslcard.h"
#include "qslcardinfo.h"
#include <QSettings>
#include <QFileDialog>
#include <QMessageBox>
#include <QFile>
#include <QSqlQuery>
#include <QSqlError>
#include <QDir>
#include <QStatusBar>
#include <QTextStream>
#include <QSqlRecord>
#include <QHeaderView>
#include <QDate>
#include <QTime>
#include <QSqlRecord>
#include <QProgressDialog>
#include <QProgressBar>
#include <QPrinter>
#include <QPainter>
#include <math.h>
#include <QPrintDialog>
QString dateFormat = QLatin1String("dd.MM.yyyy");
LinLogBook::LinLogBook(QWidget* parent)
: QMainWindow(parent)
{
setupUi(this);
setWindowTitle(QLatin1String(VERSION));
setWindowIcon(QIcon(":/images/linlogbook.png"));
readSettings();
dbStatus = -1;
editQso = nullptr;
qsoTable = nullptr;
qsoServer = nullptr;
opCallsignView=new QTableView();
bool ok = false;
qsosLogged.setText(tr("No qsos logged"));
if (reopenDb && !dbName.isEmpty())
ok = openSelectedDb(dbName);
if (opId <0)
OpCall.setText("No callsign set");
if (!ok)
{
dbNameMessage.setText(tr("No Database"));
}
else
enableMenuEntries();
statusBar()->addWidget(&dbNameMessage);
statusBar()->addWidget(&OpCall);
statusBar()->addWidget(&qsosLogged);
if(serverAutoStart)
startServer();
else
serverStatus.setText(tr("Server is not running"));
statusBar()->addPermanentWidget(&serverStatus);
/** File **/
connect(actionNewDatabase, SIGNAL(triggered()), this, SLOT(newDB()));
connect(actionOpenDatabase, SIGNAL(triggered()), this, SLOT(openDB()));
connect(actionSaveDatabaseDefinition, SIGNAL(triggered()), this, SLOT(saveDatabaseDefinion()));
connect(actionSaveViews, SIGNAL(triggered()), this, SLOT(saveViews()));
connect(actionImportCtyDat, SIGNAL(triggered()), this, SLOT(importCtyDat()));
connect(actionImportAdifFile, SIGNAL(triggered()), this, SLOT(importAdifFile()));
connect(actionExportAdifFile, SIGNAL(triggered()), this, SLOT(exportAdifFile()));
connect(actionExportforEQSLUpload, SIGNAL(triggered()), this, SLOT(exportForEQSLUpload()));
connect(actionExportforLotWUpload, SIGNAL(triggered()), this, SLOT(exportForLotWUpload()));
connect(actionPrintQSLCard, SIGNAL(triggered()), this, SLOT(printQSLCard()));
// Preferences
connect(actionGeneralSettings, SIGNAL(triggered()), this, SLOT(setup()));
connect(actionEditOperatorData,SIGNAL(triggered()), this, SLOT(editOperatorData()));
connect(actionQuit, SIGNAL(triggered()), this, SLOT(close()));
/** Statistic **/
connect(menuStatistics, SIGNAL(triggered(QAction *)), this, SLOT(showStatistic(QAction *)));
/**Edit **/
connect(actionDefineDatabaseFields, SIGNAL(triggered()), this, SLOT(defineQsoTableFields()));
connect(actionCreateBaseTables, SIGNAL(triggered()), this, SLOT(createBaseTables()));
connect(actionCreateQSOTable, SIGNAL(triggered()), this, SLOT(createQSOTable()));
connect(actionUpdateBaseTables, SIGNAL(triggered()), this, SLOT(updateBaseTables()));
connect(actionQSLCardSetup, SIGNAL(triggered()), this, SLOT(qslCardSetup()));
/** Server **/
connect(actionStartServer, SIGNAL(triggered()), this, SLOT(startServer()));
connect(actionStopServer, SIGNAL(triggered()), this, SLOT(stopServer()));
/** About **/
connect(actionAboutLinLogBook, SIGNAL(triggered()), this, SLOT(aboutLinLogBook()));
connect(actionAboutctydat, SIGNAL(triggered()), this, SLOT(aboutCtydat()));
connect(actionAboutQT, SIGNAL(triggered()), this, SLOT(aboutQT()));
/** Callsign search **/
connect(findCallsign, SIGNAL(returnPressed()), this, SLOT(searchCallsign()));
/** Buttons **/
connect(clearRecord, SIGNAL(clicked()), this, SLOT(clearInput()));
connect(saveRecord, SIGNAL(clicked()), this, SLOT(saveInput()));
connect(deleteRecord, SIGNAL(clicked()), this, SLOT(deleteEntry()));
connect(deleteAll, SIGNAL(clicked()), this, SLOT(deleteAllEntries()));
/** qsoList **/
connect(qsoList, SIGNAL(clicked(QModelIndex)), this, SLOT(takeEntry(QModelIndex)));
/** Default Settings for Loging **/
connect(defaultBand, SIGNAL(activated(int)), this, SLOT(setDefaultBand(int)));
connect(defaultMode, SIGNAL(activated(int)), this, SLOT(setDefaultMode(int)));
/** For detailview selection **/
connect(differentViews, SIGNAL(currentChanged(int)), this, SLOT(viewChanged(int)));
connect(editQsoRecord, SIGNAL(clicked(QModelIndex)), this, SLOT(saveIndex(QModelIndex)));
connect(opCallsign,SIGNAL(currentIndexChanged(int)),this,SLOT(setOpCallsign(int)));
connect(showAllQsos,SIGNAL(clicked(bool)),this,SLOT(setOpFilter(bool)));
//Adif fields, eqsl interprets
restrictEqslExport << "QSO_DATE" << "TIME_ON" <<"CALL" <<"MODE" <<"BAND" << "FREQ" <<"PROP_MODE" <<"QSLMSG" << "RST_SENT";
}
LinLogBook::~LinLogBook()
{
}
void LinLogBook::setup()
{
Setup *s = new Setup();
s->setReopen(reopenDb);
s->setAutoStart(serverAutoStart);
s->setDateFormat(dateFormat);
s->setPortNumber(portNumber);
if (!myLinLogBookDirectory.isNull())
s->setDBDirectory(myLinLogBookDirectory);
if (s->exec() == QDialog::Accepted)
{
myLinLogBookDirectory = s->getDBDirectory();
reopenDb = s->reopenLastDB();
serverAutoStart=s->autoStart();
dateFormat = s->getDateFormat();
//hostName=s->getHostName();
portNumber = s->getPortNumber();
saveSettings();
}
delete s;
}
void LinLogBook::editOperatorData()
{
opId=opCallsign->currentIndex();
operatorTable->setReadOnly(false);
OperatorSetup *ed = new OperatorSetup(operatorTable);
if( ed->exec() == QDialog::Accepted)
{
opCallsign->clear();
operatorTable->select();
opCallsign->setCurrentIndex(opId);
}
delete ed;
operatorTable->setReadOnly(true);
}
void LinLogBook::readSettings()
{
QSettings settings(QLatin1String("DL1KSV"), QLatin1String("LinLogBook"));
opId= settings.value(QLatin1String("opId"),-1).toInt();
myLinLogBookDirectory = settings.value(QLatin1String("LinLogBookDirectory")).toString();
detailView->setLastDirectory(settings.value(QLatin1String("LastCardDirectory"),QVariant(QLatin1String("."))).toString());
reopenDb = settings.value(QLatin1String("reopenDb"), QVariant(false)).toBool();
dbName = settings.value(QLatin1String("lastUsedDb")).toString();
serverAutoStart=settings.value(QLatin1String("serverAutoStart"),QVariant(false)).toBool();
dateFormat = settings.value(QLatin1String("dateFormat")).toString();
if (dateFormat.isEmpty())
dateFormat = QLatin1String("dd.MM.yyyy");
portNumber = settings.value(QLatin1String("portNumber"), 8080).toInt();
splitter->restoreState(settings.value(QLatin1String("splitterSizes")).toByteArray());
}
void LinLogBook::saveSettings()
{
QSettings settings(QLatin1String("DL1KSV"), QLatin1String("LinLogBook"));
//settings.setValue(QLatin1String("myCall"), myCall);
//settings.setValue(QLatin1String("myName"), myName);
//settings.setValue(QLatin1String("myCity"), myCity);
//settings.setValue(QLatin1String("myLocator"), myLocator);
settings.setValue(QLatin1String("opId"),opId);
settings.setValue(QLatin1String("LinLogBookDirectory"), myLinLogBookDirectory);
settings.setValue(QLatin1String("LastCardDirectory"),detailView->getLastDirectory());
settings.setValue(QLatin1String("reopenDb"), reopenDb);
settings.setValue(QLatin1String("serverAutoStart"),serverAutoStart);
settings.setValue(QLatin1String("lastUsedDb"), dbName);
settings.setValue(QLatin1String("dateFormat"), dateFormat);
settings.setValue(QLatin1String("portNumer"), portNumber);
settings.setValue(QLatin1String("splitterSizes"), splitter->saveState());
}
void LinLogBook::newDB()
{
QString dbname;
// bool ok;
QDir dir(myLinLogBookDirectory);
QString s = QDir::homePath();
// ok = dir.cd(s);
dir.cd(s);
if (!dir.exists())
// ok = dir.mkpath(myLinLogBookDirectory);
dir.mkpath(myLinLogBookDirectory);
// ok = dir.cd(myLinLogBookDirectory);
// ok = dir.makeAbsolute();
dir.cd(myLinLogBookDirectory);
dir.makeAbsolute();
s = dir.path();
QFileDialog dbOpenDialog(this, tr("Create a new Database"), s, tr("DB files (*.dblog)"));
if (dbOpenDialog.exec() == QDialog::Accepted)
{
dbname = dbOpenDialog.selectedFiles().at(0);
if (QFile(dbname).exists())
{
if (QMessageBox::question(0, tr("Delete Database"), tr("Database %1 already exits.\nRecreate this database ?").arg(dbname), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Ok)
QFile::remove(dbname);
else
return;
}
else if (!dbname.endsWith(QLatin1String(".dblog"), Qt::CaseInsensitive))
dbname.append(QLatin1String(".dblog"));
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"));
db.setDatabaseName(dbname);
if (!db.open())
QMessageBox::warning(0, tr("New Database"), tr("Could not create Database %1 \n").arg(dbname) + db.lastError().text(), QMessageBox::Ok);
else
{
dbNameMessage.setText(tr("Database %1").arg(dbname));
QSqlQuery qy;
bool ok = qy.exec(QLatin1String("create table dbStatus (status int UNIQUE )"));
if (!ok)
{
QMessageBox::critical(0, tr("New Database"), tr("Could not create Statustable for Database: %1").arg(dbname), QMessageBox::Ok);
return;
}
ok = qy.exec(QLatin1String("insert into dbStatus values(0)"));
if (!ok)
QMessageBox::critical(0, tr("New Database"), tr("Could not insert Statusvalue into dbStatus. Database: %1").arg(dbname), QMessageBox::Ok);
else
{
dbStatus = 0;
QMessageBox::warning(0, tr("New Database"), tr("Successfully created Database %1").arg(dbname), QMessageBox::Ok);
}
}
enableMenuEntries();
}
}
void LinLogBook::openDB()
{
QDir dir(myLinLogBookDirectory);
QString s = QDir::homePath();
dir.cd(s);
if (!dir.exists())
dir.mkpath(myLinLogBookDirectory);
dir.cd(myLinLogBookDirectory);
dir.makeAbsolute();
s = dir.path();
QFileDialog dbOpenDialog(this, tr("Open an existing Database"), s, tr("DB files (*.dblog)"));
dbOpenDialog.setAcceptMode(QFileDialog::AcceptOpen);
if (dbOpenDialog.exec() == QDialog::Accepted)
{
dbName = dbOpenDialog.selectedFiles().at(0);
if (!openSelectedDb(dbName))
dbName.clear();
else
enableMenuEntries();
}
}
void LinLogBook::defineQsoTableFields()
{
CreateDatabaseFields *cr = new CreateDatabaseFields();
if (cr->exec() == QDialog::Accepted)
{
QSqlQuery qy;
qy.exec(QLatin1String("update dbStatus set status= 2"));
dbStatus = 2;
actionCreateQSOTable->setEnabled(true);
QMessageBox::information(0, tr("Define Database Fields"), tr(" Databasefields successfully defined "));
enableMenuEntries();
}
delete cr;
}
bool LinLogBook::execFile(QFile *ExecFile, QProgressBar *Bar)
{
QSqlQuery qy;
int count = 0;
int errorcount = 0;
QTextStream line(ExecFile);
// s will get the complete sql- statement, to be executed
if (Bar != 0)
Bar->show();
while (!line.atEnd())
{
QString s;
QString actLine = line.readLine();
while (!actLine.isEmpty())
{
int pos = actLine.indexOf(QLatin1Char(';'));
if (pos > 0)
{
count++;
s = actLine.left(pos);
actLine = actLine.mid(pos);
if (!s.isEmpty())
{
qy.exec(s);
if (!qy.isActive())
{
QMessageBox::information(0, tr("Execute SQL- Statements"), tr("Couldn't execute SQL- Statement from file %1\nStatement was\n %2").arg(ExecFile->fileName()).arg(s));
errorcount++;
}
s.clear();
}
}
else
{
s += actLine;
actLine.clear();
}
}
qApp->processEvents();
}
if (Bar != 0)
Bar->hide();
qy.clear();
QMessageBox::information(0, tr("Execute SQL- Statements"), tr("%1 SQL- Statements processed\n %2 without errors \n %3 with errors") .arg(count).arg(count - errorcount).arg(errorcount));
if ((count - errorcount) > 0)
return true;
else
return false;
}
void LinLogBook::closeEvent(QCloseEvent *)
{
if (qsoTable != 0)
delete qsoTable;
if (editQso != 0)
delete editQso;
QSqlDatabase db = QSqlDatabase::database();
db.close();
saveSettings();
}
void LinLogBook::createQSOTable()
{
QSqlQuery qy;
qy.setForwardOnly(true);
qy.exec(QLatin1String("select * from LinLogFields"));
QString statement(QLatin1String("CREATE TABLE qsos ( Id INTEGER PRIMARY KEY AUTOINCREMENT,"));
bool first;
first = true;
while (qy.next())
{
qDebug("** %s",qPrintable(qy.value(0).toString()));
databaseFields << qy.value(0).toString();
fieldsTypes << qy.value(1).toString();
linlogFields << qy.value(2).toString();
if (!first)
statement.append(QLatin1String(","));
first = false;
statement.append(qy.value(0).toString());
if ((qy.value(1).toString() == QLatin1String("E")) || (qy.value(1).toString() == QLatin1String("N"))) // Default values for foreign keys
{
if (qy.value(3).isValid())
statement.append(QString(QLatin1String(" INTEGER DEFAULT %1 ")).arg(qy.value(3).toInt()));
else
statement.append(QLatin1String(" INTEGER "));
}
}
statement.append(QLatin1String(");"));
bool ok = qy.exec(statement);
if (ok)
{
// Now setup the view for sorting
statement = QLatin1String("create view orderedqsos as select * from qsos");
if (databaseFields.contains(QLatin1String("QSO_DATE"), Qt::CaseInsensitive))
{
statement.append(QLatin1String(" order by QSO_DATE DESC"));
if (databaseFields.contains(QLatin1String("TIME_ON"), Qt::CaseInsensitive))
statement.append(QLatin1String(",TIME_ON DESC"));
else
if (databaseFields.contains(QLatin1String("TIME_OFF"), Qt::CaseInsensitive))
statement.append(QLatin1String(",TIME_OFF DESC"));
}
if (!qy.exec(statement))
{
QMessageBox::warning(0, tr("Create View for ordering"), tr("Error, Could not create View orderedqsos for odering the qso table\n ") + statement, QMessageBox::Ok);
return;
}
else
if (qy.exec(QLatin1String("update dbStatus set status=3")))
{
dbStatus = 3;
QMessageBox::information(0, tr("Create QSO table"), tr(" QSO Table successfully created "), QMessageBox::Ok);
}
prepareViews();
enableMenuEntries();
}
else
QMessageBox::warning(0, tr("Create QSO table"), tr("Error, Could not create QSO Table\n ") + statement, QMessageBox::Ok);
}
void LinLogBook::importAdifFile()
{
// bool ok;
State Status;
int pos, valueLength;
if (dbStatus < 3)
{
QMessageBox::critical(0, tr("Import Adif File"), tr("No open Database or no qso table defined.\nPlease open Database first and/or define qso table!"));
return;
}
QString dbname;
QDir dir;
QString adifFileName;
QString s = QDir::homePath();
// ok = dir.cd(s);
dir.cd(s);
// ok = dir.makeAbsolute();
dir.makeAbsolute();
s = dir.path();
pos=0;
valueLength=0;
QFileDialog AdifOpenDialog(this, tr("Import Adif File"), s, tr("Adif files (*.adi)"));
if (AdifOpenDialog.exec() == QDialog::Accepted)
{
adifFileName = AdifOpenDialog.selectedFiles().at(0);
QFile importFile(adifFileName);
if (!importFile.open(QIODevice::ReadOnly | QIODevice::Text))
QMessageBox::information(0, tr("Import Adif File"), tr("Could not open file: ") + adifFileName);
else
{
QProgressDialog progress(this);
progress.setLabelText(tr("Importing Adif file %1").arg(adifFileName));
progress.setRange(0, importFile.size());
int bytesRead = 0;
int count = 0;
QTextStream line(&importFile);
Status = undef;
QString paramNameList, paramValueList, paramName, paramValue;
paramNameList.clear();
paramValueList.clear();
while (!line.atEnd())
{
QString actLine = line.readLine();
bytesRead += actLine.length();
while (!actLine.isEmpty())
{
switch (Status)
{
case undef:
if (!actLine.startsWith(QLatin1Char('<')))
Status = Header;
else
Status = Record;
break;
case Header: // Read until EOH
pos = actLine.indexOf(QLatin1String("<EOH>"), Qt::CaseInsensitive);
if (pos < 0)
actLine.clear();
else
{
pos += 5;
actLine = actLine.mid(pos);
Status = Record;
}
break;
case Record:
pos = actLine.indexOf(QLatin1Char('<'));
if (pos < 0)
actLine.clear();
else
{
pos++;
actLine = actLine.mid(pos);
Status = adifName;
}
break;
case adifName:
pos = actLine.indexOf(QRegExp(QLatin1String(":|>")));
paramName = actLine.left(pos);
if (paramName.toUpper() == QLatin1String("EOR"))
Status = insertRecord;
else
{
if (pos < 0)
qDebug("Falscher Aufbau");
pos++;
actLine = actLine.mid(pos);
pos = actLine.indexOf(QRegExp(QLatin1String(":|>")));
valueLength = actLine.left(pos).toInt();
actLine = actLine.mid(pos);
pos = actLine.indexOf(QLatin1Char('>'));
pos++;
actLine = actLine.mid(pos);
Status = readValue;
}
break;
case readValue:
paramValue = actLine.left(valueLength);
pos = valueLength + 1;
actLine = actLine.mid(pos);
// Check , if supported by LinLogBook
if (databaseFields.contains(paramName))
{
if (!paramNameList.isEmpty())
{
paramNameList.append(QLatin1Char(','));
paramValueList.append(QLatin1Char(','));
}
paramNameList.append(paramName);
paramValueList.append(QLatin1Char('\''));
// Check, if there is foreign key
if (foreignKey(paramName))
paramValueList.append(getKey(paramName, paramValue));
else if (dateType(paramName))
{
// Make ISO Date
paramValue.insert(4, QLatin1Char('-'));
paramValue.insert(7, QLatin1Char('-'));
paramValueList.append(paramValue);
}
else
paramValueList.append(paramValue);
paramValueList.append(QLatin1Char('\''));
}
Status = adifName;
break;
case insertRecord:
{
QString statement(QLatin1String("insert into qsos ("));
statement.append(paramNameList);
statement.append(QLatin1String(") values("));
statement.append(paramValueList);
statement.append(QLatin1String(");"));
QSqlQuery qy(statement);
if (qy.isActive())
count++;
else
qDebug("Error in insert");
}
pos++;
actLine = actLine.mid(pos);
paramNameList.clear();
paramValueList.clear();
Status = Record;
break;
default:
actLine.clear();
break;
}
}
progress.setValue(bytesRead);
qApp->processEvents();
if (progress.wasCanceled())
break;
}
QString s1;
s1.setNum(count);
s1.append(tr(" records imported"));
importFile.close();
QMessageBox::information(0, tr("Import Adif File"), s1);
prepareViews();
qsoList->showRow(count);
}
}
}
void LinLogBook::exportAdifFile()
{
QDir dir;
QFile exportFile;
QString adifFileName;
QString s = QDir::homePath();
// bool ok = dir.cd(s);
dir.cd(s);
// ok = dir.makeAbsolute();
dir.makeAbsolute();
s = dir.path();
QFileDialog fileOpenDialog(this, tr("Export Data to Adif File"), s, tr("Adif Files (*.adi)"));
if (fileOpenDialog.exec() == QDialog::Accepted)
{
adifFileName = fileOpenDialog.selectedFiles().at(0);
exportFile.setFileName(adifFileName);
if (exportFile.exists())
{
if (QMessageBox::question(0, tr("Export Data to Adif File"), tr("File ") + adifFileName + tr(" already exits.\nOverwrite ?"), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
return;
}
else
{
adifFileName.append(QLatin1String(".adi"));
exportFile.setFileName(adifFileName);
}
}
else
return;
if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
QMessageBox::critical(0, tr("Export Data to Adif File"), tr("Could not open file: ") + adifFileName);
return;
}
s = QLatin1String("select ") + databaseFields.join(QLatin1String(",")) + QLatin1String(" from qsos");
if (databaseFields.contains(QLatin1String("QSO_DATE"), Qt::CaseInsensitive))
{
s.append(QLatin1String(" order by QSO_DATE ASC"));
if (databaseFields.contains(QLatin1String("TIME_ON"), Qt::CaseInsensitive))
s.append(QLatin1String(",TIME_ON ASC"));
else
if (databaseFields.contains(QLatin1String("TIME_OFF"), Qt::CaseInsensitive))
s.append(QLatin1String(",TIME_OFF ASC"));
}
QSqlQuery qy(s);
int count = writeAdif(qy, &exportFile);
exportFile.close();
QMessageBox::information(0, tr("Export in dataADIF Format "), tr(" %1 records written to file %2").arg(count).arg(exportFile.fileName()));
}
void LinLogBook::clearInput()
{
int cind, col;
QString s;
editQso->setFilter(QLatin1String("CALL like '-1'"));
editQso->select();
editQso->insertRow(0);
cind = defaultBand->currentIndex();
if (cind >= 0)
{
s = defaultBand->currentText();
col = databaseFields.indexOf(QRegExp(QLatin1String("BAND"))) + 1;
if (col > 0)
{
QModelIndex I = editQso->index(0, col);
editQso->setData(I, QVariant(defaultBand->itemData(cind).toInt()), Qt::EditRole);
editQso->setData(I, QVariant(s), Qt::DisplayRole);
}
}
cind = defaultMode->currentIndex();
if (cind >= 0)
{
s = defaultMode->currentText();
col = databaseFields.indexOf(QRegExp(QLatin1String("MODE"))) + 1;
if (col > 0)
{
QModelIndex I = editQso->index(0, col);
editQso->setData(I, QVariant(defaultMode->itemData(cind).toInt()), Qt::EditRole);
editQso->setData(I, QVariant(s), Qt::DisplayRole);
}
}
if (opId >= 0)
{
s = opCallsign->currentText();
col = databaseFields.indexOf(QRegExp(QLatin1String("OPERATOR"))) + 1;
if (col > 0)
{
QModelIndex I = editQso->index(0, col);
//QComboBox index may be different from database index.
editQso->setData(I, QVariant(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt()), Qt::EditRole);
editQso->setData(I, QVariant(s), Qt::DisplayRole);
}
}
QModelIndex i = editQsoRecord->model()->index(0, 1);
editQsoRecord->scrollTo(i, QAbstractItemView::EnsureVisible);
(editQsoRecord->selectionModel())->setCurrentIndex(i, QItemSelectionModel::NoUpdate);
editQsoRecord->setFocus();
}
void LinLogBook::searchCallsign()
{
int column;
if (editQso == nullptr)
return;
QString s = QLatin1String("CALL like '") + findCallsign->text() + QLatin1String("%'");
editQso->setFilter(s);
bool ok = editQso->select();
if (!ok)
return;
int rows = editQso->rowCount();
QSqlRecord r = editQso->record(0);
if (rows == 0)
{
s.clear();
editQso->insertRow(0);
column = r.indexOf(QLatin1String("CALL"));
if (column > 0)
editQso->setData(editQso->index(0, column), findCallsign->text().toUpper());
column = r.indexOf(QLatin1String("QSO_DATE"));
if (column > 0)
editQso->setData(editQso->index(0, column), QDate::currentDate().toString(dateFormat));
column = r.indexOf(QLatin1String("TIME_ON"));
if (column > 0)
editQso->setData(editQso->index(0, column), QDateTime::currentDateTime().toUTC().time().toString(QLatin1String("HH:mm")));
}
else if (rows == 1)
{
column = r.indexOf(QLatin1String("GRIDSQUARE"));
if (column > 0)
s = r.value(column).toString();
else
s.clear();
}
else
s.clear();
editQsoRecord->show();
displayCallSignInfo(findCallsign->text().toUpper(), s);
}
void LinLogBook::saveInput()
{
bool ok;
if (editQso == nullptr)
return;
int rows = editQso->rowCount();
if (rows == 0)
return;
else
{
QModelIndex i = editQsoRecord->model()->index(0, 1);
editQsoRecord->scrollTo(i, QAbstractItemView::EnsureVisible);
(editQsoRecord->selectionModel())->setCurrentIndex(i, QItemSelectionModel::NoUpdate);
editQsoRecord->setFocus(); // To avoid segfault if enter was not pressed before
//Check if QSO_DATE is set
int col = databaseFields.indexOf(QRegExp(QLatin1String("QSO_DATE"))) + 1;
if (col >= 1)
{
QModelIndex I = editQso->index(0, col);
if (editQso->data(I, Qt::DisplayRole).toString().isEmpty())
editQso->setData(I, QVariant(QDate::currentDate().toString(dateFormat)), Qt::EditRole);
}
//Check if TIME_* is set
col = databaseFields.indexOf(QRegExp(QLatin1String("TIME_.+"))) + 1;
if (col >= 1)
{
QModelIndex I = editQso->index(0, col);
if (editQso->data(I, Qt::DisplayRole).toString().isEmpty())
// editQso->setData(I, QVariant(QTime::currentTime().toString(QLatin1String("HHmm"))), Qt::EditRole);
editQso->setData(I, QVariant(QDateTime::currentDateTime().toUTC().time().toString(QLatin1String("HH:mm"))), Qt::EditRole);
}
if ((ok = editQso->submitAll()))
{
qsoTable->select();
clearInput();
int count = qsoTable->rowCount(); //There should be at least one record in the table, but if just the first record was inserted
//this record will not be shown ( Error in qt ?? )
//After reasigning the table the record is now foundqsoTable->setTable(QLatin1String("orderedqsos"));
// But we have to define the whole table again
if (count == 0)
{
qsoTable->setTable(QLatin1String("orderedqsos"));
qsoTable->setDependency(databaseFields, fieldsTypes);
for (int k = 0; k < linlogFields.size(); k++)
qsoTable->setHeaderData(k + 1, Qt::Horizontal, linlogFields[k]);
qsoTable->select();
count = qsoTable->rowCount();
}
}
else
{
QSqlDatabase db = QSqlDatabase::database();
QMessageBox::warning(0, tr("Save Record"), tr("Could not save the record\nReason : ") + db.lastError().text(), QMessageBox::Ok);
}
}
}
bool LinLogBook::foreignKey(QString s)
{
int key = databaseFields.indexOf(QRegExp(s));
if (key < 0)
return false;
if (fieldsTypes[key] == QLatin1String("E"))
return true;
else
return false;
}
QString LinLogBook::getKey(QString table, QString value)
{
QSqlQuery qy;
QString s = QLatin1String("select Id from ") + table + QLatin1String(" where lower(") + table + QLatin1String("value) = '") + value.toLower() + QLatin1String("'");
bool ok = qy.exec(s);
ok = qy.first();
if (ok)
return qy.value(0).toString();
else
return QLatin1String("");
}
void LinLogBook::takeEntry(QModelIndex i)
{
int col;
int selectedRow = i.row();
QString s = QString(QLatin1String("qsos.Id = '%1")).arg(qsoTable->data(qsoTable->index(selectedRow, 0), Qt::DisplayRole).toInt()) + QLatin1String("'");
editQso->setFilter(s);
if (editQso->select())
editQsoRecord->show();
selectedRecord = qsoTable->record(selectedRow);
col = qsoTable->record().indexOf(QLatin1String("GRIDSQUARE"));
s.clear();
if (col >= 0)
s = qsoTable->data(qsoTable->index(selectedRow, col), Qt::DisplayRole).toString();
col = qsoTable->record().indexOf(QLatin1String("CALL"));
if (col >= 0)
displayCallSignInfo(qsoTable->data(qsoTable->index(selectedRow, col), Qt::DisplayRole).toString(), s);
}
void LinLogBook::deleteEntry()
{
int i = editQsoRecord->currentIndex().row();
if (i >= 0)
{
// bool ok = editQso->removeRow(editQsoRecord->currentIndex().row());
editQso->removeRow(editQsoRecord->currentIndex().row());
// ok = editQso->submitAll();
editQso->submitAll();
qsoTable->select();
clearInput();
}
else
QMessageBox::warning(0, tr("Delete"), tr("No entry selected\n"), QMessageBox::Ok);
}
void LinLogBook::deleteAllEntries()
{
QSqlQuery qy;
if (editQso == nullptr)
return;
int rows = editQso->rowCount();
if (rows <= 0)
return;
if (rows > 1)
{
if (QMessageBox::question(0, tr("Delete QSO Entry"), tr("Delete all %1 entries ?").arg(rows), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
return;
}
// bool ok;
for (int i = 0; i < rows; i++)
// ok = editQso->removeRow(i);
editQso->removeRow(i);
// ok = editQso->submitAll();
editQso->submitAll();
qsoTable->select();
clearInput();
}
bool LinLogBook::dateType(QString s)
{
int key = databaseFields.indexOf(QRegExp(s));
if (key < 0)
return false;
if (fieldsTypes[key] == QLatin1String("D"))
return true;
else
return false;
}
void LinLogBook::prepareViews()
{
QSqlQuery qy;
int defaultBandSet, defaultModeSet, i, j;
// Look for Header,Type, and ADIF Field
defaultBandSet = 0;
defaultModeSet = 0;
databaseFields.clear();
fieldsTypes.clear();
linlogFields.clear();
qy.setForwardOnly(true);
qy.exec(QLatin1String("select * from LinLogFields"));
while (qy.next())
{
databaseFields << qy.value(0).toString();
if (qy.value(0).toString() == QLatin1String("BAND"))
defaultBandSet = qy.value(3).toInt();
if (qy.value(0).toString() == QLatin1String("MODE"))
defaultModeSet = qy.value(3).toInt();
fieldsTypes << qy.value(1).toString();
linlogFields << qy.value(2).toString();
}
// qy.clear();
//Prepare default Combo boxes
j = defaultBand->count();
if (j > 0)
for (i = j - 1; i >= 0; i--)
defaultBand->removeItem(i);
j = defaultMode->count();
if (j > 0)
for (i = j - 1; i >= 0; i--)
defaultMode->removeItem(i);
qy.exec(QLatin1String("select Id,BANDValue from BAND"));
while (qy.next())
defaultBand->insertItem(qy.value(0).toInt(), qy.value(1).toString(), QVariant(qy.value(0).toInt()));
// qy.clear();
if (defaultBandSet > 0)
defaultBand->setCurrentIndex(defaultBandSet);
qy.exec(QLatin1String("select Id,MODEValue from MODE"));
while (qy.next())
defaultMode->insertItem(qy.value(0).toInt(), qy.value(1).toString(), QVariant(qy.value(0).toInt()));
// qy.clear();
if (defaultModeSet > 0)
defaultMode->setCurrentIndex(defaultModeSet);
qsoTable->clear();
qsoTable->setReadOnly(true);
qsoTable->setTable(QLatin1String("orderedqsos"));
qsoTable->setQsoFieldTypes(fieldsTypes);
qsoTable->setDependency(databaseFields, fieldsTypes);
editQso->setTable(QLatin1String("qsos"));
for (int i = 0; i < linlogFields.size(); i++)
{
editQso->setHeaderData(i + 1, Qt::Horizontal, linlogFields[i]);
qsoTable->setHeaderData(i + 1, Qt::Horizontal, linlogFields[i]);
}
//qsoTable->setSort(1, Qt::DescendingOrder);
qsoTable->select();
// qsosLogged.setText(tr("%1 qsos logged").arg(qsoTable->rowCount()));
qy.clear();
if(showAllQsos->isChecked())
qy.exec(QString("select count(*) from orderedqsos where operator = %1").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt()));
else
qy.exec(QLatin1String("select count(*) from orderedqsos"));
if( qy.next())
qsosLogged.setText(tr("%1 qsos logged").arg(qy.value(0).toString()));
//qDebug ( "Selectstatement view qso %s", qPrintable ( qsoTable->showSelectStatement() ) );
//qDebug ("Selectstatement1 %s", qPrintable ( editQso->showSelectStatement() ));
qsoList->setModel(qsoTable);
qsoList->setSelectionBehavior(QAbstractItemView::SelectRows);
qsoList->verticalHeader()->hide();
qsoList->resizeColumnsToContents();
qsoList->hideColumn(0); // Don't show the index column
qsoList->show();
editQso->setQsoFieldTypes(fieldsTypes);
editQso->setDependency(databaseFields, fieldsTypes);
editQso->setEditStrategy(QSqlTableModel::OnManualSubmit);
editQsoRecord->setModel(editQso);
editQsoRecord->setNumberOfColumns(databaseFields.size());
connect(editQsoRecord, SIGNAL(qsoDataComplete()), this, SLOT(saveInput()));
editQsoRecord->setQsoFieldTypes(fieldsTypes);
editQsoRecord->verticalHeader()->hide();
editQsoRecord->setHorizontalScrollMode(QAbstractItemView::ScrollPerItem);
editQsoRecord->setSelectionMode(QAbstractItemView::NoSelection);
editQsoRecord->hideColumn(0);
editQsoRecord->show();
qsoList->show();
clearInput();
// qy.clear();
}
void LinLogBook::startServer()
{
if (qsoServer == nullptr)
{
qsoServer = new LinLogBookServer;
connect(qsoServer, SIGNAL(qsoElement(QString)), this, SLOT(setDataFromServer(QString)));
}
if (qsoServer->listen(QHostAddress::Any, portNumber))
{
serverStatus.setText(tr("Server is running on port %1").arg(portNumber));
actionStartServer->setEnabled(false);
actionStopServer->setEnabled(true);
}
else
QMessageBox::warning(0, tr("Start LinLogBook Server"), tr("Could not start Server on port %1\n").arg(portNumber), QMessageBox::Ok);
}
void LinLogBook::stopServer()
{
if (qsoServer != nullptr)
{
qsoServer->close();
serverStatus.setText(tr("Server is not running"));
actionStartServer->setEnabled(true);
actionStopServer->setEnabled(false);
}
}
void LinLogBook::setDataFromServer(QString s)
{
QString dateformat = dateFormat;
dateFormat = QLatin1String("yyyyMMdd");
int column;
QString s1, s2;
column = prepareItem(s, &s1, &s2);
if (column > 0)
{
QModelIndex I = editQso->index(0, column);
editQso->setData(I, QVariant(s1), Qt::DisplayRole);
editQso->setData(I, QVariant(s2), Qt::EditRole);
}
dateFormat = dateformat;
}
int LinLogBook::prepareItem(QString s, QString *s1, QString *s2)
{
int pos, valueLength;
QString paramName;
QString paramValue;
QString actLine = s;
if (!actLine.startsWith(QLatin1Char('<')))
return -1;
actLine = actLine.mid(1);
pos = actLine.indexOf(QRegExp(QLatin1String(":|>")));
paramName = actLine.left(pos);
if (pos < 0)
{
qDebug("Falscher Aufbau");
return -1;
}
pos++;
actLine = actLine.mid(pos);
pos = actLine.indexOf(QRegExp(QLatin1String(":|>")));
valueLength = actLine.left(pos).toInt();
actLine = actLine.mid(pos);
pos = actLine.indexOf(QLatin1Char('>'));
pos++;
actLine = actLine.mid(pos);
paramValue = actLine.left(valueLength);
pos = valueLength + 1;
actLine = actLine.mid(pos);
// Check , if supported by LinLogBook
if(paramName.toUpper() == QLatin1String("SOR")) //Start of record
clearInput();
else if (paramName.toUpper() == QLatin1String("EOR"))
{
saveInput();
return -1;
}
if (databaseFields.contains(paramName))
{
int col = databaseFields.indexOf(QRegExp(paramName));
if (col >= 0)
col++;
*s1 = paramValue;
if (foreignKey(paramName))
*s2 = getKey(paramName, paramValue);
else
*s2 = paramValue;
return col;
}
else
return -1;
}
bool LinLogBook::openSelectedDb(QString dbname)
{
QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"));
db.setDatabaseName(dbname);
QString s = QFileInfo(dbname).fileName();
if (db.open())
{
dbNameMessage.setText(tr("Database ") + s);
actionImportCtyDat->setEnabled(true);
}
else
{
QMessageBox::warning(0, tr("Open Database"), tr("Could not open Database %1\n").arg(dbname) + db.lastError().text(), QMessageBox::Ok);
return false;
}
operatorTable = new QsoTableModel();
operatorTable->setReadOnly(true);
operatorTable->setQsoFieldTypes(QStringList() << "S" << "S" << "G" << "S" << "D" << "D");
if(db.tables().contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive))
configureOpHandling();
return readTables();
}
void LinLogBook::exportForEQSLUpload()
{
QDir dir;
QFile exportFile;
QString adifFileName;
QString s = QDir::homePath();
dir.cd(s);
dir.makeAbsolute();
s = dir.path();
QFileDialog fileOpenDialog(this, tr("Export Data to Adif File"), s, tr("Adif Files (*.adi)"));
if (fileOpenDialog.exec() == QDialog::Accepted)
{
adifFileName = fileOpenDialog.selectedFiles().at(0);
exportFile.setFileName(adifFileName);
if (exportFile.exists())
{
if (QMessageBox::question(0, tr("Export Data to Adif File"), tr("File %1 already exits.\nOverwrite ?").arg(adifFileName), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
return;
}
else
{
adifFileName.append(QLatin1String(".adi"));
exportFile.setFileName(adifFileName);
}
}
else
return;
if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
QMessageBox::critical(0, tr("Export Data to Adif File"), tr("Could not open file: ") + adifFileName);
return;
}
// Menu is only visible if EQSL_QSL_SENT field is present
QString selectString=QLatin1String("select ") + databaseFields.join(QLatin1String(",")) + QLatin1String(" from qsos where EQSL_QSL_SENT= (select id from EQSL_QSL_SENT where EQSL_QSL_SENTvalue='R') ");
if(databaseFields.contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive) ) // Restrict to operator !!!
selectString = selectString + QString(" and OPERATOR=%1").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt());
QSqlQuery qy(selectString);
int count = writeAdif(qy, &exportFile);
exportFile.close();
s = QLatin1String("update qsos set EQSL_QSL_SENT=(select Id from EQSL_QSL_SENT where EQSL_QSL_SENTvalue='Y') ");
if (databaseFields.contains(QLatin1String("EQSL_QSLSDATE"),Qt::CaseInsensitive))
{
s.append(",EQSL_QSLSDATE='");
s.append(QDate::currentDate().toString(QLatin1String("yyyy-MM-dd")));
s.append("' ");
}
s.append(" where eqsl_qsl_sent=(select id from eqsl_qsl_sent where eqsl_qsl_sentvalue='R'");
if(databaseFields.contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive) )
s.append(QString(" and OPERATOR=%1)").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt()));
else
s.append(')');
//qDebug("Query String %s", qPrintable(s));
qy.exec(s);
QMessageBox::information(0, tr("Export for Eqsl Upload"), tr(" %1 Qso records writen to file %2 for eQsl upload").arg(count).arg(exportFile.fileName()));
qsoTable->select();
}
int LinLogBook::writeAdif(QSqlQuery qy, QFile *exportFile)
{
QTextStream out(exportFile);
QString s;
out << "ADIF v2.0 export from " << VERSION << Qt::endl;
out << "Generated on " << QDateTime::currentDateTime().toUTC().toString() << " UTC" << Qt::endl;
out << "<PROGRAMID:10>LinLogBook" << Qt::endl;
out << "<ADIF_Ver:1>2" << Qt::endl;
out << "<EOH>" << Qt::endl;
qy.exec();
int count = 0;
while (qy.next())
{
for (int i = 0; i < databaseFields.size(); i++)
{
if(restrictEqslExport.contains(databaseFields[i],Qt::CaseInsensitive))
{
if (fieldsTypes[i] == QLatin1String("E"))
{
QSqlQuery qydepend;
QString s1 = QString(QLatin1String("select %1value from %1 where Id = %2")).arg(databaseFields[i]).arg(qy.value(i).toString());
qydepend.exec(s1);
if (qydepend.next())
s = qydepend.value(0).toString();
else s.clear();
}
else
s = qy.value(i).toString();
if (fieldsTypes[i] == QLatin1String("D"))
s.remove(QLatin1Char('-'));
if((fieldsTypes[i] == QLatin1String("T")) && (s.size() == 3) ) // time in adif requires four digits
s.prepend(QLatin1String("0"));
if (!s.isEmpty())
out << "<" << databaseFields[i] << ":" << s.size() << ">" << s;
}
}
out << "<EOR>" << Qt::endl;
count++;
}
return count;
}
void LinLogBook::saveDatabaseDefinion()
{
int i;
QString s, value;
QFile exportFile;
QDir dir(myLinLogBookDirectory);
s = QDir::homePath();
// bool ok = dir.cd(s);
dir.cd(s);
if (!dir.exists())
// ok = dir.mkpath(myLinLogBookDirectory);
dir.mkpath(myLinLogBookDirectory);
// ok = dir.cd(myLinLogBookDirectory);
dir.cd(myLinLogBookDirectory);
// ok = dir.makeAbsolute();
dir.makeAbsolute();
s = dir.path();
QFileDialog fileOpenDialog(this, tr("Save Databasedefinitons"), s, tr("Databasedefinitions (*.sql)"));
if (fileOpenDialog.exec() == QDialog::Accepted)
{
QString fileName = fileOpenDialog.selectedFiles().at(0);
if (!fileName.endsWith(QLatin1String(".sql"), Qt::CaseInsensitive))
fileName.append(QLatin1String(".sql"));
exportFile.setFileName(fileName);
if (exportFile.exists())
{
if (QMessageBox::question(0, tr("Save Databasedefinitons"), tr("File ") + fileName + tr(" already exits.\nOverwrite ?"), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
return;
}
}
else
return;
QSqlQuery qy;
if (dbStatus < 1)
{
QMessageBox::warning(0, tr("Save Databasedefinition"), tr("Database %1 is empty, no Definitions available").arg(dbName), QMessageBox::Ok);
return;
}
if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
QMessageBox::critical(0, tr("Save Databasedefinition"), tr("Could not open file %1: to store Databasedefinition").arg(exportFile.fileName()));
return;
}
QTextStream out(&exportFile);
QSqlDatabase db = QSqlDatabase::database();
QStringList tables = db.tables(QSql::Tables);
/** This part is probably sqlite specific **/
for (i = 0; i < tables.size(); i++)
{
s = tables.at(i);
qy.exec(QLatin1String("select sql from sqlite_master where type='table' and name='") + s + QLatin1String("'"));
if ((s != QLatin1String("qsos")) && (s != QLatin1String("dbStatus")) && (s != QLatin1String("sqlite_sequence")))
{
if (qy.next())
{
// out << "BEGIN TRANSACTION;" << endl;
out << qy.value(0).toString() << QLatin1Char(';') << Qt::endl;
qy.exec(QLatin1String("select * from ") + s);
if ((s != QLatin1String("qslcards") && (s != QLatin1String("countrylist")) && (s != QLatin1String("prefixlist")))) // Only create content for definition tables
{
while (qy.next())
{
int count = qy.record().count();
out << "INSERT INTO " << s << " VALUES(";
int col;
for (col = 0; col < (count - 1); col++)
{
value = qy.value(col).toString();
value.replace(QLatin1Char('\''), QLatin1String("''"));
out << "'" << value << "',";
}
value = qy.value(col).toString();
value.replace(QLatin1Char('\''), QLatin1String("''"));
out << "'" << value << "');" << Qt::endl;
}
}
// out << "COMMIT;" << endl;
}
}
}
out << "UPDATE dbStatus set status= ";
if (dbStatus < 3)
out << dbStatus;
else
out << "2";
out << ";" << Qt::endl;
exportFile.close();
QMessageBox::information(0, tr("Save Databasedefinition"), tr("Definitions of database %1 successfully saved to file %2").arg(dbName).arg(exportFile.fileName()));
}
bool LinLogBook::readTables()
{
/** The tables depending on the database state are read
and the correct menu items will be activated **/
int i, j;
QSqlQuery qy;
if (!qy.exec(QLatin1String("select status from dbStatus")))
{
QMessageBox::critical(0, tr("Open Database"), tr("Could not ascertain status of database: %1 \nPerhaps database destroyed.\n Recreate Databse").arg(dbName), QMessageBox::Ok);
return false;
}
if (!qy.next())
{
QMessageBox::critical(0, tr("Open Database"), tr("Could not select status of database: %1 \nPerhaps database destroyed.\n Recreate Databse").arg(dbName), QMessageBox::Ok);
return false;
}
dbStatus = qy.value(0).toInt();
qy.clear(); // Sometimes database remains locked afterwards; so release lock by clear;
// In some situations readTables might be calle repeatedly
if (qsoTable == 0)
qsoTable = new QsoTableModel();
if (editQso == 0)
editQso = new QsoTableModel();
if ((dbStatus > 0) && (dbStatus < 3))
{
databaseFields.clear();
fieldsTypes.clear();
linlogFields.clear();
j = defaultBand->count();
if (j > 0)
for (i = j - 1; i >= 0; i--)
defaultBand->removeItem(i);
j = defaultMode->count();
if (j > 0)
for (i = j - 1; i >= 0; i--)
defaultMode->removeItem(i);
qy.exec(QLatin1String("select Id,BANDValue from BAND"));
while (qy.next())
defaultBand->insertItem(qy.value(0).toInt(), qy.value(1).toString(), QVariant(qy.value(0).toInt()));
qy.exec(QLatin1String("select Id,MODEValue from MODE"));
while (qy.next())
defaultMode->insertItem(qy.value(0).toInt(), qy.value(1).toString(), QVariant(qy.value(0).toInt()));
}
if (dbStatus == 3)
prepareViews();
// qy.exec(QLatin1String("commit")); // Sometimes database remains locked afterwards; so release lock by unneeded commit to release lock
return true;
}
void LinLogBook::setDefaultBand(int cind)
{
if (cind >= 0)
{
QString s = defaultBand->currentText();
int col = databaseFields.indexOf(QRegExp(QLatin1String("BAND"))) + 1;
QModelIndex I = editQso->index(0, col);
editQso->setData(I, QVariant(defaultBand->itemData(cind).toInt()), Qt::EditRole);
editQso->setData(I, QVariant(s), Qt::DisplayRole);
}
}
void LinLogBook::setDefaultMode(int cind)
{
if (cind >= 0)
{
QString s = defaultMode->currentText();
int col = databaseFields.indexOf(QRegExp(QLatin1String("MODE"))) + 1;
QModelIndex I = editQso->index(0, col);
editQso->setData(I, QVariant(defaultMode->itemData(cind).toInt()), Qt::EditRole);
editQso->setData(I, QVariant(s), Qt::DisplayRole);
}
}
void LinLogBook::updateBaseTables()
{
QSqlQuery qy;
bool ok;
QString dbname;
QDir dir(myLinLogBookDirectory);
QString s = QDir::homePath();
ok = dir.cd(s);
ok = dir.cd(myLinLogBookDirectory);
ok = dir.makeAbsolute();
s = dir.path();
QSqlDatabase db = QSqlDatabase::database();
bool opTableChange=!db.tables(QSql::Tables).contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive);
QFileDialog basetableOpenDialog(this, tr("Opens an existing File with sql commands"), s, tr("Command files (*.sql)"));
if (basetableOpenDialog.exec() == QDialog::Accepted)
{
s = basetableOpenDialog.selectedFiles().at(0);
QFile ExecFile(s);
if (!ExecFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::information(0, tr("Update Basetables"), tr("Unable to open File %1 ").arg(s));
return;
}
else
{
ok = db.transaction();
if (!ok)
qDebug("Transaction Error %s", qPrintable(db.lastError().text()));
if (execFile(&ExecFile, 0))
{
QMessageBox::information(0, tr("Update Basetables"), tr("Basetables updated "));
ok = db.commit();
if (!ok)
qDebug("Commit Error %s", qPrintable(db.lastError().text()));
}
else
ok = db.rollback();
}
readTables();
opTableChange = opTableChange && db.tables(QSql::Tables).contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive);
if(opTableChange)
{
configureOpHandling();
QMessageBox::information(0, tr("Update Basetables"), tr("Please restart LinLogbook to make changes take place.\n"));
}
enableMenuEntries();
}
}
void LinLogBook::createBaseTables()
{
QSqlQuery qy;
bool ok;
QString dbname;
QProgressBar progress(this);
progress.setMinimum(0);
progress.setMaximum(0);
progress.setGeometry(width() / 2, height() / 4, 200, 20);
QDir dir(myLinLogBookDirectory);
QString s = QDir::homePath();
ok = dir.cd(s);
ok = dir.cd(myLinLogBookDirectory);
ok = dir.makeAbsolute();
s = dir.path();
QFileDialog basetableOpenDialog(this, tr("Opens an existing File with sql commands"), s, tr("Command files (*.sql)"));
if (basetableOpenDialog.exec() == QDialog::Accepted)
{
s = basetableOpenDialog.selectedFiles().at(0);
QFile ExecFile(s);
if (!ExecFile.open(QIODevice::ReadOnly | QIODevice::Text))
{
QMessageBox::information(0, tr("Create Basetables"), tr("Unable to open File ") + s);
return;
}
else
{
ok = execFile(&ExecFile, &progress);
if (ok)
{
if (!qy.exec(QLatin1String("update dbStatus set status=1")))
{
QMessageBox::critical(0, tr("Create Basetables"), tr("Could not update dbStatus: "), QMessageBox::Ok);
actionUpdateBaseTables->setEnabled(true);
return;
}
else
dbStatus = 1;
}
}
}
readTables();
enableMenuEntries();
}
void LinLogBook::importCtyDat()
{
QString ctyFileName;
bool ok;
QDir dir(myLinLogBookDirectory);
QString s = QDir::homePath();
ok = dir.cd(s);
if (!dir.exists())
ok = dir.mkpath(myLinLogBookDirectory);
ok = dir.cd(myLinLogBookDirectory);
ok = dir.makeAbsolute();
s = dir.path();
QFileDialog ctyDat(this, tr("Import cty.dat"), s, tr("Cty.dat File (*.dat)"));
ctyDat.setAcceptMode(QFileDialog::AcceptOpen);
if (ctyDat.exec() == QDialog::Accepted)
ctyFileName = ctyDat.selectedFiles().at(0);
else
return;
QFile importFile(ctyFileName);
if (!importFile.open(QIODevice::ReadOnly | QIODevice::Text))
QMessageBox::information(0, tr("Import cty.dat"), tr("Could not open file: ") + ctyFileName);
else
{
// QProgressDialog progress(this);
// progress.setLabelText(tr("Importing file %1").arg(ctyFileName));
// progress.setRange(0, importFile.size());
int bytesRead = 0;
int count = 0;
QProgressDialog progress(tr("Importing file %1").arg(ctyFileName),tr("Cancel Import\nImport will be incomplete"),0,importFile.size(),this);
progress.setValue(0);
qApp->processEvents();
QSqlQuery qy;
// First we drop both required tables
ok=qy.exec(QLatin1String("drop table if exists countrylist"));
if(!ok)
{
qsoTable->query().finish();
ok=qy.exec(QLatin1String("drop table if exists countrylist"));
}
if(!ok)
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Could not drop table countrylist.\nReason: ")+qy.lastError().text(), QMessageBox::Ok);
return;
}
ok=qy.exec(QLatin1String("drop table if exists prefixlist"));
if(!ok)
{
qsoTable->query().finish();
ok=qy.exec(QLatin1String("drop table if exists prefixlist"));
}
if(!ok)
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Could not drop table prefixlist.\nReason: ")+qy.lastError().text(), QMessageBox::Ok);
return;
}
// Now we recrate the tables
ok = qy.exec(QLatin1String("create table countrylist(mainPrefix PRIMARY KEY not null,countryName not null,continent not null)"));
if (!ok)
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Could not create table countrylist: "), QMessageBox::Ok);
return;
}
ok = qy.exec(QLatin1String("create table prefixlist(prefix PRIMARY KEY not null,mainPrefix,WAZ,ITU)")); //mainPrefix should be a foreign key constraint, but sqlite does not support this
if (!ok)
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Could not create table prefixlist: "), QMessageBox::Ok);
return;
}
qsoTable->select();
QTextStream line(&importFile);
QString countryName, mainPrefix, WAZ, ITU, continent;
while (!line.atEnd())
{
QString actLine = line.readLine();
count++;
bytesRead += actLine.length();
countryName = actLine.section(QLatin1Char(':'), 0, 0);
if (countryName.contains(QLatin1Char('\'')))
countryName.replace(QLatin1Char('\''), QLatin1String("''"));
WAZ = actLine.section(QLatin1Char(':'), 1, 1);
WAZ.remove(QLatin1Char(' '));
ITU = actLine.section(QLatin1Char(':'), 2, 2);
ITU.remove(QLatin1Char(' '));
continent = actLine.section(QLatin1Char(':'), 3, 3);
continent.remove(QLatin1Char(' '));
mainPrefix = actLine.section(QLatin1Char(':'), 7, 7);
mainPrefix.remove(QLatin1Char(' '));
ok = qy.exec(QString(QLatin1String("insert into countrylist values('%1','%2','%3')")).arg(mainPrefix).arg(countryName).arg(continent));
if (!ok)
{
QMessageBox::critical(0, tr("Insert into countrylist"), tr("Could not insert entry\nline was ") + actLine, QMessageBox::Ok);
return;
}
do
{
actLine = line.readLine();
bytesRead += actLine.length();
count++;
if (actLine.isEmpty())
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("cty.dat, line %1 was empty").arg(count), QMessageBox::Ok);
return;
}
QString s;
QStringList list = actLine.split(QLatin1Char(','));
for (int i = 0; i < list.size(); i++)
{
QString prefix, subWAZ, subITU;
s = list[i];
if(s.contains(QLatin1Char('='))) // Remove VERSION String or "=" sign
{
if(s.contains(QLatin1String("VER"),Qt::CaseInsensitive))
s="";
else
s.remove(QLatin1Char('='));
}
if (!s.isEmpty())
{
int len;
int pos1 = s.indexOf(QLatin1Char('('));
int pos2 = s.indexOf(QLatin1Char('['));
if ((pos1 < 0) && (pos2 < 0))
{
prefix = s;
subWAZ = WAZ;
subITU = ITU;
}
else if (pos2 < 0) // pos1 > 0
{
prefix = s.left(pos1);
pos1++;
len = s.indexOf(QLatin1Char(')'));
if ((len < 0) || ((len - pos1) < 1))
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Error in prefix\nline was ") + actLine, QMessageBox::Ok);
return;
}
subWAZ = s.mid(pos1, len - pos1);
subITU = ITU;
}
else if (pos1 < 0) //pos2 > 0
{
prefix = s.left(pos2);
pos2++;
len = s.indexOf(QLatin1Char(']'));
if ((len < 0) || ((len - pos2) < 1))
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Error in prefix\nline was ") + actLine, QMessageBox::Ok);
return;
}
subWAZ = WAZ;
subITU = s.mid(pos2, len - pos2);
}
else // pos1 > 0 and pos2 > 0)
{
prefix = s.left(pos1);
len = s.indexOf(QLatin1Char(')'));
pos1++;
pos2++;
if ((len < 0) || ((len - pos1) < 1))
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Error in prefix\nline was ") + actLine, QMessageBox::Ok);
return;
}
subWAZ = s.mid(pos1, len - pos1);
len = s.indexOf(QLatin1Char(']'));
if ((len < 0) || ((len - pos2) < 1))
{
QMessageBox::critical(0, tr("Import cty.dat"), tr("Error in prefix\nline was ") + actLine, QMessageBox::Ok);
return;
}
subITU = s.mid(pos2, len - pos2);
}
prefix.remove(QLatin1Char(';'));
prefix.remove(QLatin1Char(' '));
prefix.remove(QLatin1Char('/'));
ok = qy.exec(QString(QLatin1String("insert into prefixlist values('%1','%2','%3','%4')")).arg(prefix).arg(mainPrefix).arg(subWAZ).arg(subITU));
if (!ok)
{
//test, if prefix is already in prefixlist
ok = qy.exec(QString(QLatin1String("select mainPrefix from prefixlist where prefix='%1'")).arg(prefix));
if (!ok)
{
QMessageBox::critical(0, tr("Insert into prefixlist"), tr("Could not insert entry\nline was ") + actLine, QMessageBox::Ok);
return;
}
else
{
if (qy.next())
QMessageBox::critical(0, tr("Insert into prefixlist"), tr("Prefix ") + prefix + tr(" already in Prefix list for country ") + mainPrefix + tr("\n now it should be inserted for ") + qy.value(0).toString(), QMessageBox::Ok);
else
{
QMessageBox::critical(0, tr("Insert into prefixlist"), tr("Could not insert entry, reason unknown\nline was ") + actLine, QMessageBox::Ok);
return;
}
}
}
}
}
ok = !s.contains(QLatin1Char(';'));
progress.setValue(bytesRead);
qApp->processEvents(QEventLoop::AllEvents,100);
}
while (ok);
if (progress.wasCanceled())
break;
}
}
}
void LinLogBook::displayCallSignInfo(QString callSign, QString hisLocator)
{
//Delete previous entries
mainPrefix->setText(tr("Main Prefix: "));
wazZone->setText(tr("WAZ Zone: "));
ituZone->setText(tr("ITU Zone: "));
countryName->setText(tr("Country Name: "));
continent->setText(tr("Continent: "));
CallSignInfo s = getCallSignInfo(callSign);
mainPrefix->setText(tr("Main Prefix: ") + s.mainPrefix);
wazZone->setText(tr("WAZ Zone: ") + s.wazZone);
ituZone->setText(tr("ITU Zone: ") + s.ituZone);
countryName->setText(tr("Country Name: ") + s.countryName);
continent->setText(tr("Continent: ") + s.continent);
distanceValue->setText(calculateDistance(myLocator, hisLocator));
detailView->setCallsignInfo(s, distanceValue->text());
}
CallSignInfo LinLogBook::getCallSignInfo(QString callSign)
{
QString s;
bool ok;
QSqlQuery qy;
CallSignInfo info;
info.mainPrefix.clear();
info.wazZone.clear();
info.ituZone.clear();
info.countryName.clear();
info.continent.clear();
info.workingLocator.clear();
info.worked = false;
if (callSign.isEmpty())
return info;
int pos = callSign.indexOf(QLatin1Char('/'));
if (pos > 0)
s = callSign.left(pos).toUpper();
else
s = callSign.toUpper();
// Check, if already worked
ok = qy.exec(QString(QLatin1String("select operator from qsos where CALL='%1'")).arg(s));
if (!ok)
qDebug("Error in qsosearch %s", qPrintable(s));
info.worked = qy.next();
if(info.worked)
{
ok= qy.exec(QString(QLatin1String("select MY_GRIDSQUARE from OPERATOR where ID=%1")).arg(qy.value(0).toInt()));
if (ok)
qy.next();
info.workingLocator=qy.value(0).toString();
myLocator = info.workingLocator;
}
ok = qy.exec(QString(QLatin1String("select mainPrefix,WAZ,ITU from prefixlist where prefix='%1'")).arg(s));
if (!ok)
qDebug("Error in prefixsearch");
ok = qy.next();
if (!ok)
{
pos = s.indexOf(QRegExp(QLatin1String("[0-9]")), 1);
s = s.left(pos + 1);
ok = qy.exec(QString(QLatin1String("select mainPrefix,WAZ,ITU from prefixlist where prefix='%1'")).arg(s));
if (!ok)
qDebug("Error in prefixsearch 2");
ok = qy.next();
if (!ok)
{
s = s.left(pos);
ok = qy.exec(QString(QLatin1String("select mainPrefix,WAZ,ITU from prefixlist where prefix='%1'")).arg(s));
if (!ok)
qDebug("Error in prefixsearch 2");
ok = qy.next();
if (!ok && pos > 1)
{
s = s.left(pos - 1);
ok = qy.exec(QString(QLatin1String("select mainPrefix,WAZ,ITU from prefixlist where prefix='%1'")).arg(s));
if (!ok)
qDebug("Error in prefixsearch 3");
ok = qy.next();
if (!ok)
return info; // No Match
}
}
}
info.mainPrefix = qy.value(0).toString();
info.wazZone = qy.value(1).toString();
info.ituZone = qy.value(2).toString();
s = qy.value(0).toString();
ok = qy.exec(QString(QLatin1String("select countryName,continent from countrylist where mainPrefix='%1'")).arg(s));
if (!ok)
qDebug("Error in countrylist, mainPrefix: %s", qPrintable(s));
if (qy.next())
{
info.countryName = qy.value(0).toString();
info.continent = qy.value(1).toString();
}
return info;
}
void LinLogBook::showStatistic(QAction *a)
{
StatisticsTotal *s = new StatisticsTotal(a->text());
s->exec();
delete s;
}
void LinLogBook::aboutQT()
{
QMessageBox::aboutQt(this);
}
void LinLogBook::aboutLinLogBook()
{
QMessageBox::about(this, QString(tr("About QLinLogBook")), QString(tr("<h3>About LinLogBook</h3><p><a href=\"http://linlogbook.sf.net/\">LinLogBook</a> is a highly user configurable LoogBook program for Linux and Mac OSX by Volker Schroer, DL1KSV. It is developed under GPL( Read the file COPYING contained in the distribution for more information)</p><p>LinLogBook uses <a href=\"http://www.sqlite.org/\">sqlite </a> as sql database to store the data.</p>")));
}
void LinLogBook::aboutCtydat()
{
QMessageBox::about(this, QString(tr("About cty.dat")), QString(tr("<h3>About cty.dat</h3><p>The cty.dat file contains DXCC entities</p><p> and is maintained by Jim Reisert, AD1C </p><p>See <a href=\"http://country-files.com/\">country-files-com</a> for more information and download</p>")));
}
void LinLogBook::saveViews()
{
QString s;
QSqlQuery qy;
QFile exportFile;
QDir dir(myLinLogBookDirectory);
s = QDir::homePath();
// bool ok = dir.cd(s);
dir.cd(s);
if (!dir.exists())
// ok = dir.mkpath(myLinLogBookDirectory);
dir.mkpath(myLinLogBookDirectory);
// ok = dir.cd(myLinLogBookDirectory);
dir.cd(myLinLogBookDirectory);
// ok = dir.makeAbsolute();
dir.makeAbsolute();
s = dir.path();
QFileDialog fileOpenDialog(this, tr("Save Views"), s, tr("Views (*.sql)"));
if (fileOpenDialog.exec() == QDialog::Accepted)
{
QString fileName = fileOpenDialog.selectedFiles().at(0);
if (!fileName.endsWith(QLatin1String(".sql"), Qt::CaseInsensitive))
fileName.append(QLatin1String(".sql"));
exportFile.setFileName(fileName);
if (exportFile.exists())
{
if (QMessageBox::question(0, tr("Save Views"), tr("File ") + fileName + tr(" already exits.\nOverwrite ?"), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
return;
}
}
else
return;
// And now save the view definition
if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
QMessageBox::critical(0, tr("Save Views"), tr("Could not open file %1: to store Views").arg(exportFile.fileName()));
return;
}
QTextStream out(&exportFile);
QSqlDatabase db = QSqlDatabase::database();
QStringList tables = db.tables(QSql::Views);
if (tables.size() > 1) // There should exist at least the View orderedqsos,
// but this view will be created together with the table qsos
// so we should not save this view
{
for (int i = 0; i < tables.size(); i++)
{
s = tables.at(i);
if (s != QLatin1String("orderedqsos"))
{
qy.exec(QLatin1String("select sql from sqlite_master where type='view' and name='") + s + QLatin1String("'"));
if (qy.next())
out << qy.value(0).toString() << QLatin1Char(';') << Qt::endl;
}
}
}
exportFile.close();
QMessageBox::information(0, tr("Save Views"), tr("Views of database %1 successfully saved to file %2").arg(dbName).arg(exportFile.fileName()));
}
void LinLogBook::qslCardSetup()
{
SetupQslCard *setupQslCard = new SetupQslCard();
if (setupQslCard->exec())
actionPrintQSLCard->setEnabled(true);
delete setupQslCard;
}
void LinLogBook::printQSLCard()
{
QString s(QLatin1String("select "));
QString whereClause(QLatin1String(" where qsl_sent=(select id from qsl_sent where qsl_sentvalue='R')"));
QStringList fromClause;
fromClause << QLatin1String("qsos");
QStringList *fields;
QStringList types;
int entries, i, extraEntries;
QSqlQuery qy;
bool firstPage;
// Build sql statement
QSLCardInfo *info = new QSLCardInfo();
if ((entries = info->numEntries()) == 0)
{
QMessageBox::warning(0, tr("Print QSl Card"), tr("Card Definition is missing.\nUnable to print"), QMessageBox::Ok);
return;
}
extraEntries = info->numExtraEntries();
fields = info->fieldList();
for (i = 0; i < entries; i++)
{
QString param = fields->at(i);
if (i > 0)
s.append(QLatin1Char(','));
s.append(param);
int pos = databaseFields.indexOf(param);
types << fieldsTypes.at(pos);
if (fieldsTypes.at(pos) == QLatin1String("E"))
{
s.append(QLatin1String("value"));
if (!fromClause.contains(param, Qt::CaseInsensitive))
fromClause << param;
whereClause.append(QLatin1String(" and qsos."));
whereClause.append(param);
whereClause.append(QLatin1String("="));
whereClause.append(param);
whereClause.append(QLatin1String(".id"));
}
}
if(databaseFields.contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive) )
whereClause.append(QString(" and OPERATOR=%1").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt()));
s.append(QLatin1String(" from "));
s.append(fromClause.join(QLatin1String(",")));
s.append(whereClause);
qDebug("%s", qPrintable(s));
bool ok = qy.exec(s);
if (!ok)
qDebug("%s", qPrintable(s));
if (!ok)
return;
QPrinter printer;
QPrintDialog printDialog(&printer);
firstPage = true;
if (printDialog.exec())
{
// Qpainter now takes the resolution of the printer, not 72 dpi as written in the ddocumentation
float convert = ((float) printer.resolution()) / 25.4; // Factor to convert mm to pixel
QPainter painter(&printer);
int fontsize = painter.font().pointSize();
QStringList *Conditions = info->printConditions();
QStringList *Values = info->printValues();
QList<QPoint>* coordinates = info->fieldCoordinates();
QStringList* extraList = info->extraTextList();
QList<int> *fontSizeText = info->fontSize();
QList<int> *fontSizeExtraText = info->fontSizeExtra();
QPoint p;
QList<QPoint>* extraListCoordinates = info->extraTextListCoordinates();
while (qy.next())
{
if (!firstPage)
printer.newPage();
firstPage = false;
painter.save();
QFont f = painter.font();
for (i = 0; i < entries; i++)
{
if (fontSizeText->at(i) > 0)
f.setPointSize(fontSizeText->at(i));
else
f.setPointSize(fontsize);
painter.setFont(f);
p = coordinates->at(i);
p *= convert;
if (!(Conditions->at(i).isEmpty()))
{
if (qy.value(i).toString() == Conditions->at(i))
painter.drawText(p.x(), p.y(), Values->at(i));
}
else
{
if (types.at(i) == QLatin1String("D"))
s = qy.value(i).toDate().toString(dateFormat);
else if (types.at(i) == QLatin1String("T"))
{
// The following statement does not work any longer
// s = qy.value ( i ).toTime().toString ( QLatin1String ( "HH:mm" ) ); //so
s = qy.value(i).toString();
s.insert(2, QLatin1Char(':'));
}
else
s = qy.value(i).toString();
painter.drawText(p.x(), p.y(), s);
}
}
for (i = 0; i < extraEntries; i++)
{
if (fontSizeExtraText->at(i) > 0)
f.setPointSize(fontSizeExtraText->at(i));
else
f.setPointSize(fontsize);
painter.setFont(f);
p = extraListCoordinates->at(i);
p *= convert;
painter.drawText(p.x(), p.y(), extraList->at(i));
}
painter.restore();
}
if (firstPage) // Hack, as sqlite does report the size of query, so we check if at least one record was processed
{
QMessageBox::question(this, tr("QSL Card Print"), tr("There was nothing to print"));
return;
}
}
else
return;
if (QMessageBox::question(this, tr("QSL Card Print"), tr("Were all cards well printed ?"), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes)
{
s = QLatin1String("update qsos set qsl_sent=(select id from qsl_sent where qsl_sentvalue='Y') ");
if (databaseFields.contains(QLatin1String("QSLSDATE")))
{
s.append(",QSLSDATE='");
s.append(QDate::currentDate().toString(QLatin1String("yyyy-MM-dd")));
s.append("' ");
}
s.append(" where qsl_sent=(select id from qsl_sent where qsl_sentvalue='R')");
if(databaseFields.contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive) )
s.append(QString(" and OPERATOR=%1").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt()));
// qDebug("Query String %s",qPrintable(s));
ok = qy.exec(s);
if (ok)
qsoTable->select();
else qDebug("Could not update qso table");
}
}
void LinLogBook::enableMenuEntries()
{
QSqlDatabase db = QSqlDatabase::database();
bool hasOpTable=db.tables(QSql::Tables).contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive);
if (dbStatus == 0)
{
actionNewDatabase->setEnabled(false);
actionOpenDatabase->setEnabled(false);
actionEditOperatorData->setEnabled(false);
actionImportCtyDat->setEnabled(true);
actionUpdateBaseTables->setEnabled(true);
actionCreateBaseTables->setEnabled(true);
}
// Preparing Menu entries depending on Database Status
if (dbStatus == 1)
{
actionNewDatabase->setEnabled(false);
actionOpenDatabase->setEnabled(false);
actionDefineDatabaseFields->setEnabled(true);
actionCreateBaseTables->setEnabled(false);
actionUpdateBaseTables->setEnabled(true);
if(hasOpTable)
actionEditOperatorData->setEnabled(true);
}
if (dbStatus == 2)
{
actionNewDatabase->setEnabled(false);
actionOpenDatabase->setEnabled(false);
actionCreateBaseTables->setEnabled(false);
actionDefineDatabaseFields->setEnabled(true);
actionCreateQSOTable->setEnabled(true);
actionUpdateBaseTables->setEnabled(true);
if(hasOpTable)
actionEditOperatorData->setEnabled(true);
}
if (dbStatus == 3)
{
actionNewDatabase->setEnabled(false);
actionOpenDatabase->setEnabled(false);
actionCreateBaseTables->setEnabled(false);
actionDefineDatabaseFields->setEnabled(false);
actionCreateQSOTable->setEnabled(false);
actionUpdateBaseTables->setEnabled(true);
if(hasOpTable)
actionEditOperatorData->setEnabled(true);
clearRecord->setEnabled(true);
saveRecord->setEnabled(true);
deleteRecord->setEnabled(true);
deleteAll->setEnabled(true);
actionSaveDatabaseDefinition->setEnabled(true);
actionImportAdifFile->setEnabled(true);
actionExportAdifFile->setEnabled(true);
menuServer->setEnabled(true);
//Prepare Menu entries depending on database fields
QSqlQuery qy;
if (databaseFields.contains(QLatin1String("QSL_SENT")))
{
actionQSLCardSetup->setEnabled(true);
if (qy.exec(QLatin1String(" select count(*) from cardfields")))
{
actionPrintQSLCard->setEnabled(true);
actionPrintQSLCard->setVisible(true);
}
}
if (databaseFields.contains(QLatin1String("EQSL_QSL_SENT")))
{
actionExportforEQSLUpload->setEnabled(true);
actionExportforEQSLUpload->setVisible(true);
}
if (databaseFields.contains(QLatin1String("LOTW_QSL_SENT")))
{
actionExportforLotWUpload->setEnabled(true);
actionExportforLotWUpload->setVisible(true);
}
bool ok = qy.exec(QLatin1String("select * from statistics"));
if (ok)
{
menuStatistics->setEnabled(true); // Adopt Menu
menuStatistics->clear();
while (qy.next())
menuStatistics->addAction(qy.value(0).toString());
}
//QSqlDatabase db = QSqlDatabase::database();
if (db.tables(QSql::Views).size() > 1)
actionSaveViews->setEnabled(true);
}
if( (dbStatus > 0) && hasOpTable)
{
opCallsign->setEnabled(true);
showAllQsos->setEnabled(true);
}
else
{
opCallsign->setEnabled(false);
showAllQsos->setEnabled(false);
}
}
void LinLogBook::exportForLotWUpload()
{
QDir dir;
QFile exportFile;
QString adifFileName;
QString s = QDir::homePath();
// bool ok = dir.cd(s);
dir.cd(s);
// ok = dir.makeAbsolute();
dir.makeAbsolute();
s = dir.path();
QFileDialog fileOpenDialog(this, tr("Export Data to Adif File for LotW"), s, tr("Adif Files (*.adi)"));
if (fileOpenDialog.exec() == QDialog::Accepted)
{
adifFileName = fileOpenDialog.selectedFiles().at(0);
exportFile.setFileName(adifFileName);
if (exportFile.exists())
{
if (QMessageBox::question(0, tr("Export Data to Adif File for LotW"), tr("File %1 already exits.\nOverwrite ?").arg(adifFileName), QMessageBox::Ok | QMessageBox::Cancel, QMessageBox::Cancel) == QMessageBox::Cancel)
return;
}
else
{
adifFileName.append(QLatin1String(".adi"));
exportFile.setFileName(adifFileName);
}
}
else
return;
if (!exportFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate))
{
QMessageBox::critical(0, tr("Export Data to Adif File for LotW"), tr("Could not open file: ") + adifFileName);
return;
}
// Menu is only visible if EQSL_QSL_SENT field is present
QString selectString=QLatin1String("select ") + databaseFields.join(QLatin1String(",")) + QLatin1String(" from qsos where LOTW_QSL_SENT= (select id from LOTW_QSL_SENT where LOTW_QSL_SENTvalue='R') ");
if(databaseFields.contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive) ) // Restrict to operator !!!
selectString = selectString + QString(" and OPERATOR=%1").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt());
//qDebug("Query String %s", qPrintable(selectString));
QSqlQuery qy(selectString);
int count = writeAdif(qy, &exportFile);
exportFile.close();
s = QLatin1String("update qsos set LOTW_QSL_SENT=(select Id from LOTW_QSL_SENT where LOTW_QSL_SENTvalue='Y') ");
if (databaseFields.contains(QLatin1String("LOTW_QSLSDATE")))
{
s.append(",LOTW_QSLSDATE='");
s.append(QDate::currentDate().toString(QLatin1String("yyyy-MM-dd")));
s.append("' ");
}
s.append(" where lotw_qsl_sent=(select id from lotw_qsl_sent where lotw_qsl_sentvalue='R'");
if(databaseFields.contains(QLatin1String("OPERATOR"),Qt::CaseInsensitive) )
s.append(QString(" and OPERATOR=%1)").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt()));
else
s.append(')');
//qDebug("Query String %s", qPrintable(s));
qy.exec(s);
QMessageBox::information(0, tr("Export for LotW Upload"), tr(" %1 Qso records writen to file %2 for LotW upload").arg(count).arg(exportFile.fileName()));
qsoTable->select();
}
QString LinLogBook::calculateDistance(QString myLocator, QString hisLocator)
{
coordinates mine, his;
double dist;
if (myLocator.isEmpty() || hisLocator.isEmpty())
return QLatin1String("Distance:");
if (myLocator.length() != 6)
return QLatin1String("Distance:");
QString s("Distance: %1 km");
mine = loc2coordinates(myLocator.constData());
his = loc2coordinates(hisLocator.constData());
dist = 6371. * acos(sin(mine.breite) * sin(his.breite) + cos(mine.breite) * cos(his.breite) * cos(mine.laenge - his.laenge));
return s.arg((int) dist, 6);
}
LinLogBook::coordinates LinLogBook::loc2coordinates(const QChar *l)
{
coordinates c;
c.laenge = (20. * (l[0].toLatin1() - 'A') + 2. * (l[2].toLatin1() - '0') + (1. / 12.) * (l[4].toLatin1() - 'A') + 1. / 24.);
c.laenge *= M_PI / 180.;
c.breite = 90. - (10. * (l[1].toLatin1() - 'A') + 1. * (l[3].toLatin1() - '0') + (1. / 24.) * (l[5].toLatin1() - 'A') + 1. / 48.);
c.breite *= M_PI / 180.;
return c;
}
void LinLogBook::viewChanged(int i)
{
if (i == 0)
return;
//Find selection
if (selectedRecord.isEmpty())
return;
detailView->showDetail(selectedRecord, fieldsTypes, linlogFields);
}
void LinLogBook::saveIndex(QModelIndex i)
{
selectedRecord = editQso->record(i.row());
QString call=selectedRecord.value(QLatin1String("CALL")).toString();
QString locator=selectedRecord.value(QLatin1String("GRIDSQUARE")).toString();
displayCallSignInfo(call,locator);
if (differentViews->currentIndex() == 1)
viewChanged(1);
}
void LinLogBook::setOpCallsign(int id)
{
opId=id;
OpCall.setText(tr("Operator: ")+operatorTable->data(operatorTable->index(opId,1),Qt::DisplayRole).toString());
myLocator=operatorTable->data(operatorTable->index(opId,3),Qt::DisplayRole).toString();
setOpFilter(showAllQsos->isChecked());
}
void LinLogBook::setOpFilter(bool pressed)
{
QSqlQuery qy;
QString s;
if( dbStatus <=0)
return;
if(pressed)
{
s=QString("OPERATOR=%1").arg(operatorTable->data(operatorTable->index(opId,0),Qt::DisplayRole).toInt());
qsoTable->setFilter(s);
qsoTable->select();
//qDebug ( "SelectstatementN %s", qPrintable ( qsoTable->showSelectStatement() ) );
qy.exec(QString("select count(*) from orderedqsos where ") + s);
if( qy.next())
qsosLogged.setText(tr("%1 qsos logged for operator").arg(qy.value(0).toString()));
}
else
{
qsoTable->setFilter(QLatin1String(""));
qsoTable->select();
qy.exec(QString("select count(*) from orderedqsos"));
if(qy.next())
qsosLogged.setText(tr("%1 qsos logged").arg(qy.value(0).toString()));
//qDebug ( "SelectstatementO %s", qPrintable ( qsoTable->showSelectStatement() ) );
}
}
void LinLogBook::configureOpHandling()
{
operatorTable->setTable(QLatin1String("OPERATOR"));
operatorTable->setHeaderData(1,Qt::Horizontal,tr("Operators call"));
operatorTable->setHeaderData(2,Qt::Horizontal,tr("Operators name"));
operatorTable->setHeaderData(3,Qt::Horizontal,tr("Locator"));
operatorTable->setHeaderData(4,Qt::Horizontal,tr("City"));
operatorTable->setHeaderData(5,Qt::Horizontal,tr("Valid from"));
operatorTable->setHeaderData(6,Qt::Horizontal,tr("Valid to"));
operatorTable->select();
opCallsign->clear();
if(opId <0)
opId=0;
int saveOpId= opId; // Set Model will change the current Index and that changes opId
// so we have to restore it afterwards
opCallsign->setModel(operatorTable);
opCallsign->setModelColumn(1);
opCallsignView->setModel(operatorTable);
opCallsignView->hideColumn(0);
opCallsignView->verticalHeader()->hide();
opCallsign->setView(opCallsignView);
opCallsign->setCurrentIndex(saveOpId);
opCallsign->show();
OpCall.setText(tr("Operator: ")+operatorTable->data(operatorTable->index(opId,1),Qt::DisplayRole).toString());
/**
if(operatorTable->select()) {
qDebug("Selection was OK");
qDebug("Table contains %d rows",operatorTable->rowCount());
}
else {
qDebug("Selection was not OK");
qDebug("Error was: %s", qPrintable(operatorTable->lastError().text()));
}
**/
}
| dl1ksv/linlogbook | src/linlogbook.cpp | C++ | gpl-2.0 | 80,721 |
#for GDP3.3:
MYLIB=../lib
#for GDP3.4:
#MYLIB=../lib/$(MACHTYPE)
install clean: ALWAYS
$(MAKE) -f makefile.dynamo INSTALL=$(MYLIB) $@
ALWAYS:
| erwincoumans/dynamo | Src/Cpp/Makefile | Makefile | gpl-2.0 | 147 |
package me.lorenzop.webauctionplus;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.SortedSet;
import java.util.TreeSet;
import org.bukkit.enchantments.Enchantment;
import org.bukkit.entity.Player;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.meta.EnchantmentStorageMeta;
import org.bukkit.inventory.meta.ItemMeta;
public class WebItemMeta {
@Override
public Object clone() throws CloneNotSupportedException {
throw new CloneNotSupportedException();
}
private WebItemMeta() {}
// encode enchantments for database storage
public static String encodeEnchants(final ItemStack stack, final Player player) {
if(stack == null) throw new NullPointerException();
final Map<Enchantment, Integer> enchants = getItemEnchants(stack, player);
final boolean hasEnchants = !enchants.isEmpty();
final StringBuilder str = new StringBuilder();
if(hasEnchants) {
// convert enchantments to int id for sorting
final Map<Integer, Integer> intMap = new HashMap<Integer, Integer>();
for(final Entry<Enchantment, Integer> entry : enchants.entrySet()) {
intMap.put(
getEnchId(entry.getKey()),
entry.getValue()
);
}
// sort by enchantment id
final SortedSet<Integer> sorted = new TreeSet<Integer>(intMap.keySet());
// append enchantments to string
for(final Integer id : sorted) {
final int level = intMap.get(id);
if(str.length() > 0)
str.append(",");
str.append(Integer.toString(id));
str.append(":");
str.append(Integer.toString(level));
}
}
if(stack.hasItemMeta()) {
final ItemMeta meta = stack.getItemMeta();
// append display name to string
if(meta.hasDisplayName()) {
if(str.length() > 0)
str.append(",");
str.append("<NAME>:");
str.append( meta.getDisplayName().replace(":", "").replace(",", "").trim() );
}
// append lore to string
if(meta.hasLore()) {
str.append("<LORE>:");
final String[] lore = meta.getLore().toArray(new String[0]);
for(final String line : lore) {
if(line == null) continue;
if(str.length() > 0)
str.append("\\n");
str.append( line.replace(":", "").replace(",", "").replace("\\n", "").trim() );
}
}
}
if(str.length() == 0)
return null;
return str.toString();
}
// decode enchantments from string
public static void decodeEnchants(final ItemStack stack, final Player player, final String str) {
if(str == null || str.isEmpty()) return;
final Map<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>();
// parse string
for(String part : str.split(",")) {
if(part==null || part.isEmpty()) continue;
String[] split = part.split(":");
if(split.length != 2) {
WebAuctionPlus.getLog().warning("Invalid enchantment data: "+part);
continue;
}
// custom name
if(split[0].equals("<NAME>")) {
final ItemMeta meta = stack.getItemMeta();
meta.setDisplayName(split[1].trim());
stack.setItemMeta(meta);
continue;
}
// lore
if(split[0].equals("<LORE>")) {
final ItemMeta meta = stack.getItemMeta();
List<String> lore = meta.getLore();
if(lore == null) lore = new ArrayList<String>();
for(final String s : split[1].split("\\n"))
lore.add(s.trim());
meta.setLore(lore);
stack.setItemMeta(meta);
continue;
}
// enchantment
int enchId = -1;
int level = -1;
try {
enchId = Integer.valueOf(split[0]);
level = Integer.valueOf(split[1]);
} catch(Exception ignore) {}
if(enchId < 0 || level < 1) {
WebAuctionPlus.getLog().warning("Invalid enchantment data: "+part);
continue;
}
final Enchantment enchantment = getEnchById(enchId);
if(enchantment == null) {
WebAuctionPlus.getLog().warning("Invalid enchantment id: "+part);
continue;
}
// add enchantment to map
enchants.put(enchantment, level);
}
// apply enchantments to item
if(enchants != null && !enchants.isEmpty())
applyItemEnchants(stack, player, enchants);
}
// safely get enchantments from an item
private static Map<Enchantment, Integer> getItemEnchants(final ItemStack stack, final Player player) {
if(stack == null) return null;
final Map<Enchantment, Integer> enchants = new HashMap<Enchantment, Integer>();
Map<Enchantment, Integer> tmpEnchants = null;
// item meta
if(stack.hasItemMeta()) {
final ItemMeta meta = stack.getItemMeta();
// enchanted book
if(meta instanceof EnchantmentStorageMeta) {
EnchantmentStorageMeta bookMeta = (EnchantmentStorageMeta) meta;
tmpEnchants = bookMeta.getStoredEnchants();
}
}
// normal item
if(tmpEnchants == null)
tmpEnchants = stack.getEnchantments();
// check safe enchantments
boolean removedUnsafe = false;
for(Entry<Enchantment, Integer> entry : tmpEnchants.entrySet()) {
final Enchantment ench = entry.getKey();
final int level = checkSafeEnchantment(stack, ench, entry.getValue());
if(level < 1) {
removedUnsafe = true;
continue;
}
enchants.put(ench, level);
}
if(removedUnsafe && player != null)
player.sendMessage(WebAuctionPlus.chatPrefix+WebAuctionPlus.Lang.getString("removed_enchantments"));
return enchants;
}
// safely apply enchantments to a stack
private static void applyItemEnchants(final ItemStack stack, final Player player,
Map<Enchantment, Integer> enchants) {
if(stack == null || enchants == null || enchants.isEmpty()) return;
boolean removedUnsafe = false;
for(Entry<Enchantment, Integer> entry : enchants.entrySet()) {
final Enchantment ench = entry.getKey();
final int level = checkSafeEnchantment(stack, ench, entry.getValue());
if(level < 1) {
removedUnsafe = true;
continue;
}
// item meta
final ItemMeta meta = stack.getItemMeta();
// enchanted book
if(meta instanceof EnchantmentStorageMeta) {
EnchantmentStorageMeta bookMeta = (EnchantmentStorageMeta) meta;
bookMeta.addStoredEnchant(ench, level, WebAuctionPlus.timEnabled());
stack.setItemMeta(bookMeta);
continue;
}
// normal item
if(WebAuctionPlus.timEnabled())
stack.addUnsafeEnchantment(ench, level);
else
stack.addEnchantment(ench, level);
}
if(removedUnsafe && player != null)
player.sendMessage(WebAuctionPlus.chatPrefix+WebAuctionPlus.Lang.getString("removed_enchantments"));
}
// check natural enchantment
private static int checkSafeEnchantment(final ItemStack stack, final Enchantment ench, int level) {
final int FAIL_VALUE = -1;
// enchanted book
final boolean isContainer = (stack.getItemMeta() instanceof EnchantmentStorageMeta);
if(stack == null || ench == null) return FAIL_VALUE;
if(level < 1) return FAIL_VALUE;
// can enchant item
if(!isContainer) {
if(!ench.canEnchantItem(stack)) {
WebAuctionPlus.getLog().warning("Removed unsafe enchantment: "+stack.toString()+" "+ench.toString());
return FAIL_VALUE;
}
}
if(WebAuctionPlus.timEnabled()) {
if(level > 127) level = 127;
} else {
// level too low
if(level < ench.getStartLevel()) {
WebAuctionPlus.getLog().warning("Raised unsafe enchantment: "+Integer.toString(level)+" "+
stack.toString()+" "+ench.toString()+" to level: "+ench.getStartLevel() );
level = ench.getStartLevel();
}
// level too high
if(level > ench.getMaxLevel()) {
WebAuctionPlus.getLog().warning("Lowered unsafe enchantment: "+Integer.toString(level)+" "+
stack.toString()+" "+ench.toString()+" to level: "+ench.getMaxLevel() );
level = ench.getMaxLevel();
}
}
return level;
}
@SuppressWarnings("deprecation")
private static Integer getEnchId(Enchantment ench) {
if(ench == null)
return null;
return ench.getId();
}
@SuppressWarnings("deprecation")
private static Enchantment getEnchById(Integer value) {
if(value == null)
return null;
return Enchantment.getById(value);
}
}
| pablo67340/WebAuctionPlus | java/src/me/lorenzop/webauctionplus/WebItemMeta.java | Java | gpl-2.0 | 7,957 |
/**
* Overall styles
*/
.filefield-icon img {
display: inline;
}
/**
* Clear the filefield-icon float, or any other floats
* that custom widgets might have inserted but not cleared.
* Stolen from "How To Clear Floats Without Structural Markup",
* http://www.positioniseverything.net/easyclearing.html
*/
.filefield-item:after, .filefield-file-edit:after {
content: "";
display: block;
height: 0;
clear: both;
visibility: hidden;
}
/* Hides from IE-mac \*/
* html .filefield-item, .filefield-file-edit {height: 1%;}
/* End hide from IE-mac */
/* End overall styles */
/**
* Formatter styles
*/
.filefield-item .filefield-icon {
float: left;
margin-right: 0.4em;
}
/* End formatter styles */
/**
* General widget form styles (applicable to all widgets)
*/
.filefield-file-edit-flags {
float: right;
text-align: right;
margin-bottom: -4px; /* The "List" checkbox has too much bottom margin */
}
.filefield-file-edit-widget {
width: 90%;
}
/* Only applies to single-value fields, for which we provide our own table. */
.filefield-file-container-table {
width: 90%;
margin-top: 3px;
margin-bottom: 2px;
}
.filefield-file-upload {
margin-bottom: 5px;
}
.filefield-js-error {
/* For some reason, the JS error message doesn't wrap by default. */
white-space: normal;
}
/* End general widget form styles */
/**
* Generic file edit widget styles. Not applicable to other widgets that
* might hook into filefield (say, a widget with an image preview).
*/
.filefield-generic-edit .filefield-icon {
float: left;
margin-right: 0.7em;
margin-top: 0.3em;
}
.filefield-generic-edit-description {
margin-right: 6em;
}
/* The text field is made unnecessarily long by node.css - shorten it */
.filefield-generic-edit .form-text {
width: 100%;
}
.filefield-generic-edit .description {
white-space: normal;
margin-bottom: 0;
overflow: auto; /* indent on line wraps, don't float around the icon */
}
/* End widget form styles */
| product31/headshots | sites/all/modules/filefield/filefield.css | CSS | gpl-2.0 | 2,000 |
<?xml version="1.0" encoding="ascii"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>schrodinger.trajectory.ffstructure._FFAngleProperty</title>
<link rel="stylesheet" href="epydoc.css" type="text/css" />
<script type="text/javascript" src="epydoc.js"></script>
</head>
<body bgcolor="white" text="black" link="blue" vlink="#204080"
alink="#204080">
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>2015-2Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table width="100%" cellpadding="0" cellspacing="0">
<tr valign="top">
<td width="100%">
<span class="breadcrumbs">
<a href="schrodinger-module.html">Package schrodinger</a> ::
<a href="schrodinger.trajectory-module.html">Package trajectory</a> ::
<a href="schrodinger.trajectory.ffstructure-module.html">Module ffstructure</a> ::
Class _FFAngleProperty
</span>
</td>
<td>
<table cellpadding="0" cellspacing="0">
<!-- hide/show private -->
<tr><td align="right"><span class="options">[<a href="javascript:void(0);" class="privatelink"
onclick="toggle_private();">hide private</a>]</span></td></tr>
<tr><td align="right"><span class="options"
>[<a href="frames.html" target="_top">frames</a
>] | <a href="schrodinger.trajectory.ffstructure._FFAngleProperty-class.html"
target="_top">no frames</a>]</span></td></tr>
</table>
</td>
</tr>
</table>
<!-- ==================== CLASS DESCRIPTION ==================== -->
<h1 class="epydoc">Class _FFAngleProperty</h1><p class="nomargin-top"></p>
<pre class="base-tree">
UserDict.DictMixin --+
|
<strong class="uidshort">_FFAngleProperty</strong>
</pre>
<hr />
<p>A dictionary to hold angle force field parameters.</p>
<!-- ==================== INSTANCE METHODS ==================== -->
<a name="section-InstanceMethods"></a>
<table class="summary" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Instance Methods</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-InstanceMethods"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="__init__"></a><span class="summary-sig-name">__init__</span>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">ffangle</span>,
<span class="summary-sig-arg">ffhandle</span>,
<span class="summary-sig-arg">_index</span>)</span></td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.trajectory.ffstructure._FFAngleProperty-class.html#__getitem__" class="summary-sig-name">__getitem__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">item</span>)</span><br />
Return the given item if it is a valid force field parameter for this
angle, None if not.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a href="schrodinger.trajectory.ffstructure._FFAngleProperty-class.html#__setitem__" class="summary-sig-name">__setitem__</a>(<span class="summary-sig-arg">self</span>,
<span class="summary-sig-arg">item</span>,
<span class="summary-sig-arg">value</span>)</span><br />
Set a force field parameter for the angle.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td width="15%" align="right" valign="top" class="summary">
<span class="summary-type"> </span>
</td><td class="summary">
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td><span class="summary-sig"><a name="keys"></a><span class="summary-sig-name">keys</span>(<span class="summary-sig-arg">self</span>)</span><br />
Returns a list of the property names for this angle.</td>
<td align="right" valign="top">
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td colspan="2" class="summary">
<p class="indent-wrapped-lines"><b>Inherited from <code>UserDict.DictMixin</code></b>:
<code>__cmp__</code>,
<code>__contains__</code>,
<code>__iter__</code>,
<code>__len__</code>,
<code>__repr__</code>,
<code>clear</code>,
<code>get</code>,
<code>has_key</code>,
<code>items</code>,
<code>iteritems</code>,
<code>iterkeys</code>,
<code>itervalues</code>,
<code>pop</code>,
<code>popitem</code>,
<code>setdefault</code>,
<code>update</code>,
<code>values</code>
</p>
</td>
</tr>
</table>
<!-- ==================== METHOD DETAILS ==================== -->
<a name="section-MethodDetails"></a>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr bgcolor="#70b0f0" class="table-header">
<td colspan="2" class="table-header">
<table border="0" cellpadding="0" cellspacing="0" width="100%">
<tr valign="top">
<td align="left"><span class="table-header">Method Details</span></td>
<td align="right" valign="top"
><span class="options">[<a href="#section-MethodDetails"
class="privatelink" onclick="toggle_private();"
>hide private</a>]</span></td>
</tr>
</table>
</td>
</tr>
</table>
<a name="__getitem__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__getitem__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">item</span>)</span>
<br /><em class="fname">(Indexing operator)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Return the given item if it is a valid force field parameter for this
angle, None if not.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>item</code></strong> (string) - The property name.</li>
</ul></dd>
</dl>
</td></tr></table>
</div>
<a name="__setitem__"></a>
<div>
<table class="details" border="1" cellpadding="3"
cellspacing="0" width="100%" bgcolor="white">
<tr><td>
<table width="100%" cellpadding="0" cellspacing="0" border="0">
<tr valign="top"><td>
<h3 class="epydoc"><span class="sig"><span class="sig-name">__setitem__</span>(<span class="sig-arg">self</span>,
<span class="sig-arg">item</span>,
<span class="sig-arg">value</span>)</span>
<br /><em class="fname">(Index assignment operator)</em>
</h3>
</td><td align="right" valign="top"
>
</td>
</tr></table>
<p>Set a force field parameter for the angle.</p>
<dl class="fields">
<dt>Parameters:</dt>
<dd><ul class="nomargin-top">
<li><strong class="pname"><code>item</code></strong> (string) - The property name.</li>
<li><strong class="pname"><code>value</code></strong> - The value to be set.</li>
</ul></dd>
</dl>
</td></tr></table>
</div>
<br />
<!-- ==================== NAVIGATION BAR ==================== -->
<table class="navbar" border="0" width="100%" cellpadding="0"
bgcolor="#a0c0ff" cellspacing="0">
<tr valign="middle">
<!-- Tree link -->
<th> <a
href="module-tree.html">Trees</a> </th>
<!-- Index link -->
<th> <a
href="identifier-index.html">Indices</a> </th>
<!-- Help link -->
<th> <a
href="help.html">Help</a> </th>
<!-- Project homepage -->
<th class="navbar" align="right" width="100%">
<table border="0" cellpadding="0" cellspacing="0">
<tr><th class="navbar" align="center"
>2015-2Schrodinger Python API</th>
</tr></table></th>
</tr>
</table>
<table border="0" cellpadding="0" cellspacing="0" width="100%%">
<tr>
<td align="left" class="footer">
Generated by Epydoc 3.0.1 on Sat May 9 06:31:27 2015
</td>
<td align="right" class="footer">
<a target="mainFrame" href="http://epydoc.sourceforge.net"
>http://epydoc.sourceforge.net</a>
</td>
</tr>
</table>
<script type="text/javascript">
<!--
// Private objects are initially displayed (because if
// javascript is turned off then we want them to be
// visible); but by default, we want to hide them. So hide
// them unless we have a cookie that says to show them.
checkCookie();
// -->
</script>
</body>
</html>
| platinhom/ManualHom | Schrodinger/Schrodinger_2015-2_docs/python_api/api/schrodinger.trajectory.ffstructure._FFAngleProperty-class.html | HTML | gpl-2.0 | 10,901 |
/*****************************************************************
* $Id: sail_symbol.cpp 1983 2013-09-02 18:10:02Z rutger $
* Created: Jul 26, 2012 14:24:25 AM - rutger
*
* Copyright (C) 2012 Red-Bag. All rights reserved.
* This file is part of the Biluna SAIL project.
*
* See http://www.red-bag.com for further details.
*****************************************************************/
#include "sail_symbol.h"
SAIL_Symbol::SAIL_Symbol (const RB_String& id, RB_ObjectBase* p,
const RB_String& n, RB_ObjectFactory* f)
: RB_ObjectAtomic (id, p, n, f) {
createMembers();
}
SAIL_Symbol::SAIL_Symbol(SAIL_Symbol* obj) : RB_ObjectAtomic(obj) {
createMembers();
*this = *obj;
}
SAIL_Symbol::~SAIL_Symbol() {
// clean up children done in RB_ObjectBase and RB_ObjectContainer
}
/**
Create members:
\li description, description of the symbol
\li svg, the SVG data of the symbol image
*/
void SAIL_Symbol::createMembers() {
addMember("mname", "-", "<New>", RB2::MemberChar125);
addMember("svg", "-", "", RB2::MemberString);
addMember("icon", "-", "", RB2::MemberByteArray);
}
| biluna/biluna | sail/src/model/sail_symbol.cpp | C++ | gpl-2.0 | 1,159 |
#ifndef _LINUX_FS_H
#define _LINUX_FS_H
#include <linux/linkage.h>
#include <linux/wait.h>
#include <linux/kdev_t.h>
#include <linux/dcache.h>
#include <linux/path.h>
#include <linux/stat.h>
#include <linux/cache.h>
#include <linux/list.h>
#include <linux/radix-tree.h>
#include <linux/rbtree.h>
#include <linux/init.h>
#include <linux/pid.h>
#include <linux/bug.h>
#include <linux/mutex.h>
#include <linux/capability.h>
#include <linux/semaphore.h>
#include <linux/fiemap.h>
#include <linux/rculist_bl.h>
#include <linux/atomic.h>
#include <linux/shrinker.h>
#include <linux/migrate_mode.h>
#include <linux/uidgid.h>
#include <linux/lockdep.h>
#include <linux/percpu-rwsem.h>
#include <linux/blk_types.h>
#include <asm/byteorder.h>
#include <uapi/linux/fs.h>
struct export_operations;
struct hd_geometry;
struct iovec;
struct nameidata;
struct kiocb;
struct kobject;
struct pipe_inode_info;
struct poll_table_struct;
struct kstatfs;
struct vm_area_struct;
struct vfsmount;
struct cred;
struct swap_info_struct;
struct seq_file;
struct fscrypt_info;
struct fscrypt_operations;
extern void __init inode_init(void);
extern void __init inode_init_early(void);
extern void __init files_init(unsigned long);
extern struct files_stat_struct files_stat;
extern unsigned long get_max_files(void);
extern int sysctl_nr_open;
extern struct inodes_stat_t inodes_stat;
extern int leases_enable, lease_break_time;
extern int sysctl_protected_symlinks;
extern int sysctl_protected_hardlinks;
struct buffer_head;
typedef int (get_block_t)(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create);
typedef void (dio_iodone_t)(struct kiocb *iocb, loff_t offset,
ssize_t bytes, void *private, int ret,
bool is_async);
#define MAY_EXEC 0x00000001
#define MAY_WRITE 0x00000002
#define MAY_READ 0x00000004
#define MAY_APPEND 0x00000008
#define MAY_ACCESS 0x00000010
#define MAY_OPEN 0x00000020
#define MAY_CHDIR 0x00000040
/* called from RCU mode, don't block */
#define MAY_NOT_BLOCK 0x00000080
/*
* flags in file.f_mode. Note that FMODE_READ and FMODE_WRITE must correspond
* to O_WRONLY and O_RDWR via the strange trick in __dentry_open()
*/
/* file is open for reading */
#define FMODE_READ ((__force fmode_t)0x1)
/* file is open for writing */
#define FMODE_WRITE ((__force fmode_t)0x2)
/* file is seekable */
#define FMODE_LSEEK ((__force fmode_t)0x4)
/* file can be accessed using pread */
#define FMODE_PREAD ((__force fmode_t)0x8)
/* file can be accessed using pwrite */
#define FMODE_PWRITE ((__force fmode_t)0x10)
/* File is opened for execution with sys_execve / sys_uselib */
#define FMODE_EXEC ((__force fmode_t)0x20)
/* File is opened with O_NDELAY (only set for block devices) */
#define FMODE_NDELAY ((__force fmode_t)0x40)
/* File is opened with O_EXCL (only set for block devices) */
#define FMODE_EXCL ((__force fmode_t)0x80)
/* File is opened using open(.., 3, ..) and is writeable only for ioctls
(specialy hack for floppy.c) */
#define FMODE_WRITE_IOCTL ((__force fmode_t)0x100)
/* 32bit hashes as llseek() offset (for directories) */
#define FMODE_32BITHASH ((__force fmode_t)0x200)
/* 64bit hashes as llseek() offset (for directories) */
#define FMODE_64BITHASH ((__force fmode_t)0x400)
/*
* Don't update ctime and mtime.
*
* Currently a special hack for the XFS open_by_handle ioctl, but we'll
* hopefully graduate it to a proper O_CMTIME flag supported by open(2) soon.
*/
#define FMODE_NOCMTIME ((__force fmode_t)0x800)
/* Expect random access pattern */
#define FMODE_RANDOM ((__force fmode_t)0x1000)
/* File is huge (eg. /dev/kmem): treat loff_t as unsigned */
#define FMODE_UNSIGNED_OFFSET ((__force fmode_t)0x2000)
/* File is opened with O_PATH; almost nothing can be done with it */
#define FMODE_PATH ((__force fmode_t)0x4000)
/* File was opened by fanotify and shouldn't generate fanotify events */
#define FMODE_NONOTIFY ((__force fmode_t)0x1000000)
/*
* Flag for rw_copy_check_uvector and compat_rw_copy_check_uvector
* that indicates that they should check the contents of the iovec are
* valid, but not check the memory that the iovec elements
* points too.
*/
#define CHECK_IOVEC_ONLY -1
/*
* The below are the various read and write types that we support. Some of
* them include behavioral modifiers that send information down to the
* block layer and IO scheduler. Terminology:
*
* The block layer uses device plugging to defer IO a little bit, in
* the hope that we will see more IO very shortly. This increases
* coalescing of adjacent IO and thus reduces the number of IOs we
* have to send to the device. It also allows for better queuing,
* if the IO isn't mergeable. If the caller is going to be waiting
* for the IO, then he must ensure that the device is unplugged so
* that the IO is dispatched to the driver.
*
* All IO is handled async in Linux. This is fine for background
* writes, but for reads or writes that someone waits for completion
* on, we want to notify the block layer and IO scheduler so that they
* know about it. That allows them to make better scheduling
* decisions. So when the below references 'sync' and 'async', it
* is referencing this priority hint.
*
* With that in mind, the available types are:
*
* READ A normal read operation. Device will be plugged.
* READ_SYNC A synchronous read. Device is not plugged, caller can
* immediately wait on this read without caring about
* unplugging.
* READA Used for read-ahead operations. Lower priority, and the
* block layer could (in theory) choose to ignore this
* request if it runs into resource problems.
* WRITE A normal async write. Device will be plugged.
* WRITE_SYNC Synchronous write. Identical to WRITE, but passes down
* the hint that someone will be waiting on this IO
* shortly. The write equivalent of READ_SYNC.
* WRITE_ODIRECT Special case write for O_DIRECT only.
* WRITE_FLUSH Like WRITE_SYNC but with preceding cache flush.
* WRITE_FUA Like WRITE_SYNC but data is guaranteed to be on
* non-volatile media on completion.
* WRITE_FLUSH_FUA Combination of WRITE_FLUSH and FUA. The IO is preceded
* by a cache flush and data is guaranteed to be on
* non-volatile media on completion.
*
*/
#define RW_MASK REQ_WRITE
#define RWA_MASK REQ_RAHEAD
#define READ 0
#define WRITE RW_MASK
#define READA RWA_MASK
#define KERNEL_READ (READ|REQ_KERNEL)
#define KERNEL_WRITE (WRITE|REQ_KERNEL)
#define READ_SYNC (READ | REQ_SYNC)
#define WRITE_SYNC (WRITE | REQ_SYNC | REQ_NOIDLE)
#define WRITE_ODIRECT (WRITE | REQ_SYNC)
#define WRITE_FLUSH (WRITE | REQ_SYNC | REQ_NOIDLE | REQ_FLUSH)
#define WRITE_FUA (WRITE | REQ_SYNC | REQ_NOIDLE | REQ_FUA)
#define WRITE_FLUSH_FUA (WRITE | REQ_SYNC | REQ_NOIDLE | REQ_FLUSH | REQ_FUA)
/*
* Attribute flags. These should be or-ed together to figure out what
* has been changed!
*/
#define ATTR_MODE (1 << 0)
#define ATTR_UID (1 << 1)
#define ATTR_GID (1 << 2)
#define ATTR_SIZE (1 << 3)
#define ATTR_ATIME (1 << 4)
#define ATTR_MTIME (1 << 5)
#define ATTR_CTIME (1 << 6)
#define ATTR_ATIME_SET (1 << 7)
#define ATTR_MTIME_SET (1 << 8)
#define ATTR_FORCE (1 << 9) /* Not a change, but a change it */
#define ATTR_ATTR_FLAG (1 << 10)
#define ATTR_KILL_SUID (1 << 11)
#define ATTR_KILL_SGID (1 << 12)
#define ATTR_FILE (1 << 13)
#define ATTR_KILL_PRIV (1 << 14)
#define ATTR_OPEN (1 << 15) /* Truncating from open(O_TRUNC) */
#define ATTR_TIMES_SET (1 << 16)
/*
* This is the Inode Attributes structure, used for notify_change(). It
* uses the above definitions as flags, to know which values have changed.
* Also, in this manner, a Filesystem can look at only the values it cares
* about. Basically, these are the attributes that the VFS layer can
* request to change from the FS layer.
*
* Derek Atkins <warlord@MIT.EDU> 94-10-20
*/
struct iattr {
unsigned int ia_valid;
umode_t ia_mode;
kuid_t ia_uid;
kgid_t ia_gid;
loff_t ia_size;
struct timespec ia_atime;
struct timespec ia_mtime;
struct timespec ia_ctime;
/*
* Not an attribute, but an auxiliary info for filesystems wanting to
* implement an ftruncate() like method. NOTE: filesystem should
* check for (ia_valid & ATTR_FILE), and not for (ia_file != NULL).
*/
struct file *ia_file;
};
/*
* Includes for diskquotas.
*/
#include <linux/quota.h>
/**
* enum positive_aop_returns - aop return codes with specific semantics
*
* @AOP_WRITEPAGE_ACTIVATE: Informs the caller that page writeback has
* completed, that the page is still locked, and
* should be considered active. The VM uses this hint
* to return the page to the active list -- it won't
* be a candidate for writeback again in the near
* future. Other callers must be careful to unlock
* the page if they get this return. Returned by
* writepage();
*
* @AOP_TRUNCATED_PAGE: The AOP method that was handed a locked page has
* unlocked it and the page might have been truncated.
* The caller should back up to acquiring a new page and
* trying again. The aop will be taking reasonable
* precautions not to livelock. If the caller held a page
* reference, it should drop it before retrying. Returned
* by readpage().
*
* address_space_operation functions return these large constants to indicate
* special semantics to the caller. These are much larger than the bytes in a
* page to allow for functions that return the number of bytes operated on in a
* given page.
*/
enum positive_aop_returns {
AOP_WRITEPAGE_ACTIVATE = 0x80000,
AOP_TRUNCATED_PAGE = 0x80001,
};
#define AOP_FLAG_UNINTERRUPTIBLE 0x0001 /* will not do a short write */
#define AOP_FLAG_CONT_EXPAND 0x0002 /* called from cont_expand */
#define AOP_FLAG_NOFS 0x0004 /* used by filesystem to direct
* helper code (eg buffer layer)
* to clear GFP_FS from alloc */
/*
* oh the beauties of C type declarations.
*/
struct page;
struct address_space;
struct writeback_control;
struct iov_iter {
const struct iovec *iov;
unsigned long nr_segs;
size_t iov_offset;
size_t count;
};
size_t iov_iter_copy_from_user_atomic(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes);
size_t iov_iter_copy_from_user(struct page *page,
struct iov_iter *i, unsigned long offset, size_t bytes);
void iov_iter_advance(struct iov_iter *i, size_t bytes);
int iov_iter_fault_in_readable(struct iov_iter *i, size_t bytes);
size_t iov_iter_single_seg_count(const struct iov_iter *i);
static inline void iov_iter_init(struct iov_iter *i,
const struct iovec *iov, unsigned long nr_segs,
size_t count, size_t written)
{
i->iov = iov;
i->nr_segs = nr_segs;
i->iov_offset = 0;
i->count = count + written;
iov_iter_advance(i, written);
}
static inline size_t iov_iter_count(struct iov_iter *i)
{
return i->count;
}
/*
* "descriptor" for what we're up to with a read.
* This allows us to use the same read code yet
* have multiple different users of the data that
* we read from a file.
*
* The simplest case just copies the data to user
* mode.
*/
typedef struct {
size_t written;
size_t count;
union {
char __user *buf;
void *data;
} arg;
int error;
} read_descriptor_t;
typedef int (*read_actor_t)(read_descriptor_t *, struct page *,
unsigned long, unsigned long);
struct address_space_operations {
int (*writepage)(struct page *page, struct writeback_control *wbc);
int (*readpage)(struct file *, struct page *);
/* Write back some dirty pages from this mapping. */
int (*writepages)(struct address_space *, struct writeback_control *);
/* Set a page dirty. Return true if this dirtied it */
int (*set_page_dirty)(struct page *page);
int (*readpages)(struct file *filp, struct address_space *mapping,
struct list_head *pages, unsigned nr_pages);
int (*write_begin)(struct file *, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata);
int (*write_end)(struct file *, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata);
/* Unfortunately this kludge is needed for FIBMAP. Don't use it */
sector_t (*bmap)(struct address_space *, sector_t);
void (*invalidatepage) (struct page *, unsigned long);
int (*releasepage) (struct page *, gfp_t);
void (*freepage)(struct page *);
ssize_t (*direct_IO)(int, struct kiocb *, const struct iovec *iov,
loff_t offset, unsigned long nr_segs);
int (*get_xip_mem)(struct address_space *, pgoff_t, int,
void **, unsigned long *);
/*
* migrate the contents of a page to the specified target. If sync
* is false, it must not block.
*/
int (*migratepage) (struct address_space *,
struct page *, struct page *, enum migrate_mode);
int (*launder_page) (struct page *);
int (*is_partially_uptodate) (struct page *, read_descriptor_t *,
unsigned long);
void (*is_dirty_writeback) (struct page *, bool *, bool *);
int (*error_remove_page)(struct address_space *, struct page *);
/* swapfile support */
int (*swap_activate)(struct swap_info_struct *sis, struct file *file,
sector_t *span);
void (*swap_deactivate)(struct file *file);
};
extern const struct address_space_operations empty_aops;
/*
* pagecache_write_begin/pagecache_write_end must be used by general code
* to write into the pagecache.
*/
int pagecache_write_begin(struct file *, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata);
int pagecache_write_end(struct file *, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata);
struct backing_dev_info;
struct address_space {
struct inode *host; /* owner: inode, block_device */
struct radix_tree_root page_tree; /* radix tree of all pages */
spinlock_t tree_lock; /* and lock protecting it */
unsigned int i_mmap_writable;/* count VM_SHARED mappings */
struct rb_root i_mmap; /* tree of private and shared mappings */
struct list_head i_mmap_nonlinear;/*list VM_NONLINEAR mappings */
struct mutex i_mmap_mutex; /* protect tree, count, list */
/* Protected by tree_lock together with the radix tree */
unsigned long nrpages; /* number of total pages */
pgoff_t writeback_index;/* writeback starts here */
const struct address_space_operations *a_ops; /* methods */
unsigned long flags; /* error bits/gfp mask */
struct backing_dev_info *backing_dev_info; /* device readahead, etc */
spinlock_t private_lock; /* for use by the address_space */
struct list_head private_list; /* ditto */
void *private_data; /* ditto */
} __attribute__((aligned(sizeof(long))));
/*
* On most architectures that alignment is already the case; but
* must be enforced here for CRIS, to let the least significant bit
* of struct page's "mapping" pointer be used for PAGE_MAPPING_ANON.
*/
struct request_queue;
struct block_device {
dev_t bd_dev; /* not a kdev_t - it's a search key */
int bd_openers;
struct inode * bd_inode; /* will die */
struct super_block * bd_super;
struct mutex bd_mutex; /* open/close mutex */
struct list_head bd_inodes;
void * bd_claiming;
void * bd_holder;
int bd_holders;
bool bd_write_holder;
#ifdef CONFIG_SYSFS
struct list_head bd_holder_disks;
#endif
struct block_device * bd_contains;
unsigned bd_block_size;
struct hd_struct * bd_part;
/* number of times partitions within this device have been opened. */
unsigned bd_part_count;
int bd_invalidated;
struct gendisk * bd_disk;
struct request_queue * bd_queue;
struct list_head bd_list;
/*
* Private data. You must have bd_claim'ed the block_device
* to use this. NOTE: bd_claim allows an owner to claim
* the same device multiple times, the owner must take special
* care to not mess up bd_private for that case.
*/
unsigned long bd_private;
/* The counter of freeze processes */
int bd_fsfreeze_count;
/* Mutex for freeze */
struct mutex bd_fsfreeze_mutex;
};
/*
* Radix-tree tags, for tagging dirty and writeback pages within the pagecache
* radix trees
*/
#define PAGECACHE_TAG_DIRTY 0
#define PAGECACHE_TAG_WRITEBACK 1
#define PAGECACHE_TAG_TOWRITE 2
int mapping_tagged(struct address_space *mapping, int tag);
/*
* Might pages of this file be mapped into userspace?
*/
static inline int mapping_mapped(struct address_space *mapping)
{
return !RB_EMPTY_ROOT(&mapping->i_mmap) ||
!list_empty(&mapping->i_mmap_nonlinear);
}
/*
* Might pages of this file have been modified in userspace?
* Note that i_mmap_writable counts all VM_SHARED vmas: do_mmap_pgoff
* marks vma as VM_SHARED if it is shared, and the file was opened for
* writing i.e. vma may be mprotected writable even if now readonly.
*/
static inline int mapping_writably_mapped(struct address_space *mapping)
{
return mapping->i_mmap_writable != 0;
}
/*
* Use sequence counter to get consistent i_size on 32-bit processors.
*/
#if BITS_PER_LONG==32 && defined(CONFIG_SMP)
#include <linux/seqlock.h>
#define __NEED_I_SIZE_ORDERED
#define i_size_ordered_init(inode) seqcount_init(&inode->i_size_seqcount)
#else
#define i_size_ordered_init(inode) do { } while (0)
#endif
struct posix_acl;
#define ACL_NOT_CACHED ((void *)(-1))
#define IOP_FASTPERM 0x0001
#define IOP_LOOKUP 0x0002
#define IOP_NOFOLLOW 0x0004
/*
* Keep mostly read-only and often accessed (especially for
* the RCU path lookup and 'stat' data) fields at the beginning
* of the 'struct inode'
*/
struct inode {
umode_t i_mode;
unsigned short i_opflags;
kuid_t i_uid;
kgid_t i_gid;
unsigned int i_flags;
#ifdef CONFIG_FS_POSIX_ACL
struct posix_acl *i_acl;
struct posix_acl *i_default_acl;
#endif
const struct inode_operations *i_op;
struct super_block *i_sb;
struct address_space *i_mapping;
#ifdef CONFIG_SECURITY
void *i_security;
#endif
/* Stat data, not accessed from path walking */
unsigned long i_ino;
/*
* Filesystems may only read i_nlink directly. They shall use the
* following functions for modification:
*
* (set|clear|inc|drop)_nlink
* inode_(inc|dec)_link_count
*/
union {
const unsigned int i_nlink;
unsigned int __i_nlink;
};
dev_t i_rdev;
loff_t i_size;
struct timespec i_atime;
struct timespec i_mtime;
struct timespec i_ctime;
spinlock_t i_lock; /* i_blocks, i_bytes, maybe i_size */
unsigned short i_bytes;
unsigned int i_blkbits;
blkcnt_t i_blocks;
#ifdef __NEED_I_SIZE_ORDERED
seqcount_t i_size_seqcount;
#endif
/* Misc */
unsigned long i_state;
struct mutex i_mutex;
unsigned long dirtied_when; /* jiffies of first dirtying */
struct hlist_node i_hash;
struct list_head i_wb_list; /* backing dev IO list */
struct list_head i_lru; /* inode LRU list */
struct list_head i_sb_list;
union {
struct hlist_head i_dentry;
struct rcu_head i_rcu;
};
u64 i_version;
atomic_t i_count;
atomic_t i_dio_count;
atomic_t i_writecount;
const struct file_operations *i_fop; /* former ->i_op->default_file_ops */
struct file_lock *i_flock;
struct address_space i_data;
#ifdef CONFIG_QUOTA
struct dquot *i_dquot[MAXQUOTAS];
#endif
struct list_head i_devices;
union {
struct pipe_inode_info *i_pipe;
struct block_device *i_bdev;
struct cdev *i_cdev;
};
__u32 i_generation;
#ifdef CONFIG_FSNOTIFY
__u32 i_fsnotify_mask; /* all events this inode cares about */
struct hlist_head i_fsnotify_marks;
#endif
#ifdef CONFIG_IMA
atomic_t i_readcount; /* struct files open RO */
#endif
#if IS_ENABLED(CONFIG_FS_ENCRYPTION)
struct fscrypt_info *i_crypt_info;
#endif
void *i_private; /* fs or device private pointer */
};
static inline int inode_unhashed(struct inode *inode)
{
return hlist_unhashed(&inode->i_hash);
}
/*
* inode->i_mutex nesting subclasses for the lock validator:
*
* 0: the object of the current VFS operation
* 1: parent
* 2: child/target
* 3: quota file
*
* The locking order between these classes is
* parent -> child -> normal -> xattr -> quota
*/
enum inode_i_mutex_lock_class
{
I_MUTEX_NORMAL,
I_MUTEX_PARENT,
I_MUTEX_CHILD,
I_MUTEX_XATTR,
I_MUTEX_QUOTA
};
/*
* NOTE: in a 32bit arch with a preemptable kernel and
* an UP compile the i_size_read/write must be atomic
* with respect to the local cpu (unlike with preempt disabled),
* but they don't need to be atomic with respect to other cpus like in
* true SMP (so they need either to either locally disable irq around
* the read or for example on x86 they can be still implemented as a
* cmpxchg8b without the need of the lock prefix). For SMP compiles
* and 64bit archs it makes no difference if preempt is enabled or not.
*/
static inline loff_t i_size_read(const struct inode *inode)
{
#if BITS_PER_LONG==32 && defined(CONFIG_SMP)
loff_t i_size;
unsigned int seq;
do {
seq = read_seqcount_begin(&inode->i_size_seqcount);
i_size = inode->i_size;
} while (read_seqcount_retry(&inode->i_size_seqcount, seq));
return i_size;
#elif BITS_PER_LONG==32 && defined(CONFIG_PREEMPT)
loff_t i_size;
preempt_disable();
i_size = inode->i_size;
preempt_enable();
return i_size;
#else
return inode->i_size;
#endif
}
/*
* NOTE: unlike i_size_read(), i_size_write() does need locking around it
* (normally i_mutex), otherwise on 32bit/SMP an update of i_size_seqcount
* can be lost, resulting in subsequent i_size_read() calls spinning forever.
*/
static inline void i_size_write(struct inode *inode, loff_t i_size)
{
#if BITS_PER_LONG==32 && defined(CONFIG_SMP)
preempt_disable();
write_seqcount_begin(&inode->i_size_seqcount);
inode->i_size = i_size;
write_seqcount_end(&inode->i_size_seqcount);
preempt_enable();
#elif BITS_PER_LONG==32 && defined(CONFIG_PREEMPT)
preempt_disable();
inode->i_size = i_size;
preempt_enable();
#else
inode->i_size = i_size;
#endif
}
/* Helper functions so that in most cases filesystems will
* not need to deal directly with kuid_t and kgid_t and can
* instead deal with the raw numeric values that are stored
* in the filesystem.
*/
static inline uid_t i_uid_read(const struct inode *inode)
{
return from_kuid(&init_user_ns, inode->i_uid);
}
static inline gid_t i_gid_read(const struct inode *inode)
{
return from_kgid(&init_user_ns, inode->i_gid);
}
static inline void i_uid_write(struct inode *inode, uid_t uid)
{
inode->i_uid = make_kuid(&init_user_ns, uid);
}
static inline void i_gid_write(struct inode *inode, gid_t gid)
{
inode->i_gid = make_kgid(&init_user_ns, gid);
}
static inline unsigned iminor(const struct inode *inode)
{
return MINOR(inode->i_rdev);
}
static inline unsigned imajor(const struct inode *inode)
{
return MAJOR(inode->i_rdev);
}
extern struct block_device *I_BDEV(struct inode *inode);
struct fown_struct {
rwlock_t lock; /* protects pid, uid, euid fields */
struct pid *pid; /* pid or -pgrp where SIGIO should be sent */
enum pid_type pid_type; /* Kind of process group SIGIO should be sent to */
kuid_t uid, euid; /* uid/euid of process setting the owner */
int signum; /* posix.1b rt signal to be delivered on IO */
};
/*
* Track a single file's readahead state
*/
struct file_ra_state {
pgoff_t start; /* where readahead started */
unsigned int size; /* # of readahead pages */
unsigned int async_size; /* do asynchronous readahead when
there are only # of pages ahead */
unsigned int ra_pages; /* Maximum readahead window */
unsigned int mmap_miss; /* Cache miss stat for mmap accesses */
loff_t prev_pos; /* Cache last read() position */
};
/*
* Check if @index falls in the readahead windows.
*/
static inline int ra_has_index(struct file_ra_state *ra, pgoff_t index)
{
return (index >= ra->start &&
index < ra->start + ra->size);
}
#define FILE_MNT_WRITE_TAKEN 1
#define FILE_MNT_WRITE_RELEASED 2
struct file {
/*
* fu_list becomes invalid after file_free is called and queued via
* fu_rcuhead for RCU freeing
*/
union {
struct list_head fu_list;
struct rcu_head fu_rcuhead;
} f_u;
struct path f_path;
#define f_dentry f_path.dentry
struct inode *f_inode; /* cached value */
const struct file_operations *f_op;
/*
* Protects f_ep_links, f_flags, f_pos vs i_size in lseek SEEK_CUR.
* Must not be taken from IRQ context.
*/
spinlock_t f_lock;
#ifdef CONFIG_SMP
int f_sb_list_cpu;
#endif
atomic_long_t f_count;
unsigned int f_flags;
fmode_t f_mode;
loff_t f_pos;
struct fown_struct f_owner;
const struct cred *f_cred;
struct file_ra_state f_ra;
u64 f_version;
#ifdef CONFIG_SECURITY
void *f_security;
#endif
/* needed for tty driver, and maybe others */
void *private_data;
#ifdef CONFIG_EPOLL
/* Used by fs/eventpoll.c to link all the hooks to this file */
struct list_head f_ep_links;
struct list_head f_tfile_llink;
#endif /* #ifdef CONFIG_EPOLL */
struct address_space *f_mapping;
#ifdef CONFIG_DEBUG_WRITECOUNT
unsigned long f_mnt_write_state;
#endif
};
struct file_handle {
__u32 handle_bytes;
int handle_type;
/* file identifier */
unsigned char f_handle[0];
};
static inline struct file *get_file(struct file *f)
{
atomic_long_inc(&f->f_count);
return f;
}
#define fput_atomic(x) atomic_long_add_unless(&(x)->f_count, -1, 1)
#define file_count(x) atomic_long_read(&(x)->f_count)
#ifdef CONFIG_DEBUG_WRITECOUNT
static inline void file_take_write(struct file *f)
{
WARN_ON(f->f_mnt_write_state != 0);
f->f_mnt_write_state = FILE_MNT_WRITE_TAKEN;
}
static inline void file_release_write(struct file *f)
{
f->f_mnt_write_state |= FILE_MNT_WRITE_RELEASED;
}
static inline void file_reset_write(struct file *f)
{
f->f_mnt_write_state = 0;
}
static inline void file_check_state(struct file *f)
{
/*
* At this point, either both or neither of these bits
* should be set.
*/
WARN_ON(f->f_mnt_write_state == FILE_MNT_WRITE_TAKEN);
WARN_ON(f->f_mnt_write_state == FILE_MNT_WRITE_RELEASED);
}
static inline int file_check_writeable(struct file *f)
{
if (f->f_mnt_write_state == FILE_MNT_WRITE_TAKEN)
return 0;
printk(KERN_WARNING "writeable file with no "
"mnt_want_write()\n");
WARN_ON(1);
return -EINVAL;
}
#else /* !CONFIG_DEBUG_WRITECOUNT */
static inline void file_take_write(struct file *filp) {}
static inline void file_release_write(struct file *filp) {}
static inline void file_reset_write(struct file *filp) {}
static inline void file_check_state(struct file *filp) {}
static inline int file_check_writeable(struct file *filp)
{
return 0;
}
#endif /* CONFIG_DEBUG_WRITECOUNT */
#define MAX_NON_LFS ((1UL<<31) - 1)
/* Page cache limit. The filesystems should put that into their s_maxbytes
limits, otherwise bad things can happen in VM. */
#if BITS_PER_LONG==32
#define MAX_LFS_FILESIZE (((loff_t)PAGE_CACHE_SIZE << (BITS_PER_LONG-1))-1)
#elif BITS_PER_LONG==64
#define MAX_LFS_FILESIZE ((loff_t)0x7fffffffffffffffLL)
#endif
#define FL_POSIX 1
#define FL_FLOCK 2
#define FL_ACCESS 8 /* not trying to lock, just looking */
#define FL_EXISTS 16 /* when unlocking, test for existence */
#define FL_LEASE 32 /* lease held on this file */
#define FL_CLOSE 64 /* unlock on close */
#define FL_SLEEP 128 /* A blocking lock */
#define FL_DOWNGRADE_PENDING 256 /* Lease is being downgraded */
#define FL_UNLOCK_PENDING 512 /* Lease is being broken */
/*
* Special return value from posix_lock_file() and vfs_lock_file() for
* asynchronous locking.
*/
#define FILE_LOCK_DEFERRED 1
/*
* The POSIX file lock owner is determined by
* the "struct files_struct" in the thread group
* (or NULL for no owner - BSD locks).
*
* Lockd stuffs a "host" pointer into this.
*/
typedef struct files_struct *fl_owner_t;
struct file_lock_operations {
void (*fl_copy_lock)(struct file_lock *, struct file_lock *);
void (*fl_release_private)(struct file_lock *);
};
struct lock_manager_operations {
int (*lm_compare_owner)(struct file_lock *, struct file_lock *);
void (*lm_notify)(struct file_lock *); /* unblock callback */
int (*lm_grant)(struct file_lock *, struct file_lock *, int);
void (*lm_break)(struct file_lock *);
int (*lm_change)(struct file_lock **, int);
};
struct lock_manager {
struct list_head list;
};
struct net;
void locks_start_grace(struct net *, struct lock_manager *);
void locks_end_grace(struct lock_manager *);
int locks_in_grace(struct net *);
/* that will die - we need it for nfs_lock_info */
#include <linux/nfs_fs_i.h>
struct file_lock {
struct file_lock *fl_next; /* singly linked list for this inode */
struct list_head fl_link; /* doubly linked list of all locks */
struct list_head fl_block; /* circular list of blocked processes */
fl_owner_t fl_owner;
unsigned int fl_flags;
unsigned char fl_type;
unsigned int fl_pid;
struct pid *fl_nspid;
wait_queue_head_t fl_wait;
struct file *fl_file;
loff_t fl_start;
loff_t fl_end;
struct fasync_struct * fl_fasync; /* for lease break notifications */
/* for lease breaks: */
unsigned long fl_break_time;
unsigned long fl_downgrade_time;
const struct file_lock_operations *fl_ops; /* Callbacks for filesystems */
const struct lock_manager_operations *fl_lmops; /* Callbacks for lockmanagers */
union {
struct nfs_lock_info nfs_fl;
struct nfs4_lock_info nfs4_fl;
struct {
struct list_head link; /* link in AFS vnode's pending_locks list */
int state; /* state of grant or error if -ve */
} afs;
} fl_u;
};
/* The following constant reflects the upper bound of the file/locking space */
#ifndef OFFSET_MAX
#define INT_LIMIT(x) (~((x)1 << (sizeof(x)*8 - 1)))
#define OFFSET_MAX INT_LIMIT(loff_t)
#define OFFT_OFFSET_MAX INT_LIMIT(off_t)
#endif
#include <linux/fcntl.h>
extern void send_sigio(struct fown_struct *fown, int fd, int band);
#ifdef CONFIG_FILE_LOCKING
extern int fcntl_getlk(struct file *, struct flock __user *);
extern int fcntl_setlk(unsigned int, struct file *, unsigned int,
struct flock __user *);
#if BITS_PER_LONG == 32
extern int fcntl_getlk64(struct file *, struct flock64 __user *);
extern int fcntl_setlk64(unsigned int, struct file *, unsigned int,
struct flock64 __user *);
#endif
extern int fcntl_setlease(unsigned int fd, struct file *filp, long arg);
extern int fcntl_getlease(struct file *filp);
/* fs/locks.c */
void locks_free_lock(struct file_lock *fl);
extern void locks_init_lock(struct file_lock *);
extern struct file_lock * locks_alloc_lock(void);
extern void locks_copy_lock(struct file_lock *, struct file_lock *);
extern void __locks_copy_lock(struct file_lock *, const struct file_lock *);
extern void locks_remove_posix(struct file *, fl_owner_t);
extern void locks_remove_flock(struct file *);
extern void locks_release_private(struct file_lock *);
extern void posix_test_lock(struct file *, struct file_lock *);
extern int posix_lock_file(struct file *, struct file_lock *, struct file_lock *);
extern int posix_lock_file_wait(struct file *, struct file_lock *);
extern int posix_unblock_lock(struct file *, struct file_lock *);
extern int vfs_test_lock(struct file *, struct file_lock *);
extern int vfs_lock_file(struct file *, unsigned int, struct file_lock *, struct file_lock *);
extern int vfs_cancel_lock(struct file *filp, struct file_lock *fl);
extern int flock_lock_file_wait(struct file *filp, struct file_lock *fl);
extern int __break_lease(struct inode *inode, unsigned int flags);
extern void lease_get_mtime(struct inode *, struct timespec *time);
extern int generic_setlease(struct file *, long, struct file_lock **);
extern int vfs_setlease(struct file *, long, struct file_lock **);
extern int lease_modify(struct file_lock **, int);
extern int lock_may_read(struct inode *, loff_t start, unsigned long count);
extern int lock_may_write(struct inode *, loff_t start, unsigned long count);
extern void locks_delete_block(struct file_lock *waiter);
extern void lock_flocks(void);
extern void unlock_flocks(void);
#else /* !CONFIG_FILE_LOCKING */
static inline int fcntl_getlk(struct file *file, struct flock __user *user)
{
return -EINVAL;
}
static inline int fcntl_setlk(unsigned int fd, struct file *file,
unsigned int cmd, struct flock __user *user)
{
return -EACCES;
}
#if BITS_PER_LONG == 32
static inline int fcntl_getlk64(struct file *file, struct flock64 __user *user)
{
return -EINVAL;
}
static inline int fcntl_setlk64(unsigned int fd, struct file *file,
unsigned int cmd, struct flock64 __user *user)
{
return -EACCES;
}
#endif
static inline int fcntl_setlease(unsigned int fd, struct file *filp, long arg)
{
return 0;
}
static inline int fcntl_getlease(struct file *filp)
{
return 0;
}
static inline void locks_init_lock(struct file_lock *fl)
{
return;
}
static inline void __locks_copy_lock(struct file_lock *new, struct file_lock *fl)
{
return;
}
static inline void locks_copy_lock(struct file_lock *new, struct file_lock *fl)
{
return;
}
static inline void locks_remove_posix(struct file *filp, fl_owner_t owner)
{
return;
}
static inline void locks_remove_flock(struct file *filp)
{
return;
}
static inline void posix_test_lock(struct file *filp, struct file_lock *fl)
{
return;
}
static inline int posix_lock_file(struct file *filp, struct file_lock *fl,
struct file_lock *conflock)
{
return -ENOLCK;
}
static inline int posix_lock_file_wait(struct file *filp, struct file_lock *fl)
{
return -ENOLCK;
}
static inline int posix_unblock_lock(struct file *filp,
struct file_lock *waiter)
{
return -ENOENT;
}
static inline int vfs_test_lock(struct file *filp, struct file_lock *fl)
{
return 0;
}
static inline int vfs_lock_file(struct file *filp, unsigned int cmd,
struct file_lock *fl, struct file_lock *conf)
{
return -ENOLCK;
}
static inline int vfs_cancel_lock(struct file *filp, struct file_lock *fl)
{
return 0;
}
static inline int flock_lock_file_wait(struct file *filp,
struct file_lock *request)
{
return -ENOLCK;
}
static inline int __break_lease(struct inode *inode, unsigned int mode)
{
return 0;
}
static inline void lease_get_mtime(struct inode *inode, struct timespec *time)
{
return;
}
static inline int generic_setlease(struct file *filp, long arg,
struct file_lock **flp)
{
return -EINVAL;
}
static inline int vfs_setlease(struct file *filp, long arg,
struct file_lock **lease)
{
return -EINVAL;
}
static inline int lease_modify(struct file_lock **before, int arg)
{
return -EINVAL;
}
static inline int lock_may_read(struct inode *inode, loff_t start,
unsigned long len)
{
return 1;
}
static inline int lock_may_write(struct inode *inode, loff_t start,
unsigned long len)
{
return 1;
}
static inline void locks_delete_block(struct file_lock *waiter)
{
}
static inline void lock_flocks(void)
{
}
static inline void unlock_flocks(void)
{
}
#endif /* !CONFIG_FILE_LOCKING */
struct fasync_struct {
spinlock_t fa_lock;
int magic;
int fa_fd;
struct fasync_struct *fa_next; /* singly linked list */
struct file *fa_file;
struct rcu_head fa_rcu;
};
#define FASYNC_MAGIC 0x4601
/* SMP safe fasync helpers: */
extern int fasync_helper(int, struct file *, int, struct fasync_struct **);
extern struct fasync_struct *fasync_insert_entry(int, struct file *, struct fasync_struct **, struct fasync_struct *);
extern int fasync_remove_entry(struct file *, struct fasync_struct **);
extern struct fasync_struct *fasync_alloc(void);
extern void fasync_free(struct fasync_struct *);
/* can be called from interrupts */
extern void kill_fasync(struct fasync_struct **, int, int);
extern int __f_setown(struct file *filp, struct pid *, enum pid_type, int force);
extern int f_setown(struct file *filp, unsigned long arg, int force);
extern void f_delown(struct file *filp);
extern pid_t f_getown(struct file *filp);
extern int send_sigurg(struct fown_struct *fown);
struct mm_struct;
/*
* Umount options
*/
#define MNT_FORCE 0x00000001 /* Attempt to forcibily umount */
#define MNT_DETACH 0x00000002 /* Just detach from the tree */
#define MNT_EXPIRE 0x00000004 /* Mark for expiry */
#define UMOUNT_NOFOLLOW 0x00000008 /* Don't follow symlink on umount */
#define UMOUNT_UNUSED 0x80000000 /* Flag guaranteed to be unused */
extern struct list_head super_blocks;
extern spinlock_t sb_lock;
/* Possible states of 'frozen' field */
enum {
SB_UNFROZEN = 0, /* FS is unfrozen */
SB_FREEZE_WRITE = 1, /* Writes, dir ops, ioctls frozen */
SB_FREEZE_PAGEFAULT = 2, /* Page faults stopped as well */
SB_FREEZE_FS = 3, /* For internal FS use (e.g. to stop
* internal threads if needed) */
SB_FREEZE_COMPLETE = 4, /* ->freeze_fs finished successfully */
};
#define SB_FREEZE_LEVELS (SB_FREEZE_COMPLETE - 1)
struct sb_writers {
/* Counters for counting writers at each level */
struct percpu_counter counter[SB_FREEZE_LEVELS];
wait_queue_head_t wait; /* queue for waiting for
writers / faults to finish */
int frozen; /* Is sb frozen? */
wait_queue_head_t wait_unfrozen; /* queue for waiting for
sb to be thawed */
#ifdef CONFIG_DEBUG_LOCK_ALLOC
struct lockdep_map lock_map[SB_FREEZE_LEVELS];
#endif
};
struct super_block {
struct list_head s_list; /* Keep this first */
dev_t s_dev; /* search index; _not_ kdev_t */
unsigned char s_blocksize_bits;
unsigned long s_blocksize;
loff_t s_maxbytes; /* Max file size */
struct file_system_type *s_type;
const struct super_operations *s_op;
const struct dquot_operations *dq_op;
const struct quotactl_ops *s_qcop;
const struct export_operations *s_export_op;
unsigned long s_flags;
unsigned long s_magic;
struct dentry *s_root;
struct rw_semaphore s_umount;
int s_count;
atomic_t s_active;
#ifdef CONFIG_SECURITY
void *s_security;
#endif
const struct xattr_handler **s_xattr;
struct list_head s_inodes; /* all inodes */
const struct fscrypt_operations *s_cop;
struct hlist_bl_head s_anon; /* anonymous dentries for (nfs) exporting */
#ifdef CONFIG_SMP
struct list_head __percpu *s_files;
#else
struct list_head s_files;
#endif
struct list_head s_mounts; /* list of mounts; _not_ for fs use */
/* s_dentry_lru, s_nr_dentry_unused protected by dcache.c lru locks */
struct list_head s_dentry_lru; /* unused dentry lru */
int s_nr_dentry_unused; /* # of dentry on lru */
/* s_inode_lru_lock protects s_inode_lru and s_nr_inodes_unused */
spinlock_t s_inode_lru_lock ____cacheline_aligned_in_smp;
struct list_head s_inode_lru; /* unused inode lru */
int s_nr_inodes_unused; /* # of inodes on lru */
struct block_device *s_bdev;
struct backing_dev_info *s_bdi;
struct mtd_info *s_mtd;
struct hlist_node s_instances;
struct quota_info s_dquot; /* Diskquota specific options */
struct sb_writers s_writers;
char s_id[32]; /* Informational name */
u8 s_uuid[16]; /* UUID */
void *s_fs_info; /* Filesystem private info */
unsigned int s_max_links;
fmode_t s_mode;
/* Granularity of c/m/atime in ns.
Cannot be worse than a second */
u32 s_time_gran;
/*
* The next field is for VFS *only*. No filesystems have any business
* even looking at it. You had been warned.
*/
struct mutex s_vfs_rename_mutex; /* Kludge */
/*
* Filesystem subtype. If non-empty the filesystem type field
* in /proc/mounts will be "type.subtype"
*/
char *s_subtype;
/*
* Saved mount options for lazy filesystems using
* generic_show_options()
*/
char __rcu *s_options;
const struct dentry_operations *s_d_op; /* default d_op for dentries */
/*
* Saved pool identifier for cleancache (-1 means none)
*/
int cleancache_poolid;
struct shrinker s_shrink; /* per-sb shrinker handle */
/* Number of inodes with nlink == 0 but still referenced */
atomic_long_t s_remove_count;
/* Being remounted read-only */
int s_readonly_remount;
};
/* superblock cache pruning functions */
extern void prune_icache_sb(struct super_block *sb, int nr_to_scan);
extern void prune_dcache_sb(struct super_block *sb, int nr_to_scan);
extern struct timespec current_fs_time(struct super_block *sb);
/*
* Snapshotting support.
*/
void __sb_end_write(struct super_block *sb, int level);
int __sb_start_write(struct super_block *sb, int level, bool wait);
/**
* sb_end_write - drop write access to a superblock
* @sb: the super we wrote to
*
* Decrement number of writers to the filesystem. Wake up possible waiters
* wanting to freeze the filesystem.
*/
static inline void sb_end_write(struct super_block *sb)
{
__sb_end_write(sb, SB_FREEZE_WRITE);
}
/**
* sb_end_pagefault - drop write access to a superblock from a page fault
* @sb: the super we wrote to
*
* Decrement number of processes handling write page fault to the filesystem.
* Wake up possible waiters wanting to freeze the filesystem.
*/
static inline void sb_end_pagefault(struct super_block *sb)
{
__sb_end_write(sb, SB_FREEZE_PAGEFAULT);
}
/**
* sb_end_intwrite - drop write access to a superblock for internal fs purposes
* @sb: the super we wrote to
*
* Decrement fs-internal number of writers to the filesystem. Wake up possible
* waiters wanting to freeze the filesystem.
*/
static inline void sb_end_intwrite(struct super_block *sb)
{
__sb_end_write(sb, SB_FREEZE_FS);
}
/**
* sb_start_write - get write access to a superblock
* @sb: the super we write to
*
* When a process wants to write data or metadata to a file system (i.e. dirty
* a page or an inode), it should embed the operation in a sb_start_write() -
* sb_end_write() pair to get exclusion against file system freezing. This
* function increments number of writers preventing freezing. If the file
* system is already frozen, the function waits until the file system is
* thawed.
*
* Since freeze protection behaves as a lock, users have to preserve
* ordering of freeze protection and other filesystem locks. Generally,
* freeze protection should be the outermost lock. In particular, we have:
*
* sb_start_write
* -> i_mutex (write path, truncate, directory ops, ...)
* -> s_umount (freeze_super, thaw_super)
*/
static inline void sb_start_write(struct super_block *sb)
{
__sb_start_write(sb, SB_FREEZE_WRITE, true);
}
static inline int sb_start_write_trylock(struct super_block *sb)
{
return __sb_start_write(sb, SB_FREEZE_WRITE, false);
}
/**
* sb_start_pagefault - get write access to a superblock from a page fault
* @sb: the super we write to
*
* When a process starts handling write page fault, it should embed the
* operation into sb_start_pagefault() - sb_end_pagefault() pair to get
* exclusion against file system freezing. This is needed since the page fault
* is going to dirty a page. This function increments number of running page
* faults preventing freezing. If the file system is already frozen, the
* function waits until the file system is thawed.
*
* Since page fault freeze protection behaves as a lock, users have to preserve
* ordering of freeze protection and other filesystem locks. It is advised to
* put sb_start_pagefault() close to mmap_sem in lock ordering. Page fault
* handling code implies lock dependency:
*
* mmap_sem
* -> sb_start_pagefault
*/
static inline void sb_start_pagefault(struct super_block *sb)
{
__sb_start_write(sb, SB_FREEZE_PAGEFAULT, true);
}
/*
* sb_start_intwrite - get write access to a superblock for internal fs purposes
* @sb: the super we write to
*
* This is the third level of protection against filesystem freezing. It is
* free for use by a filesystem. The only requirement is that it must rank
* below sb_start_pagefault.
*
* For example filesystem can call sb_start_intwrite() when starting a
* transaction which somewhat eases handling of freezing for internal sources
* of filesystem changes (internal fs threads, discarding preallocation on file
* close, etc.).
*/
static inline void sb_start_intwrite(struct super_block *sb)
{
__sb_start_write(sb, SB_FREEZE_FS, true);
}
extern bool inode_owner_or_capable(const struct inode *inode);
/*
* VFS helper functions..
*/
extern int vfs_create(struct inode *, struct dentry *, umode_t, bool);
extern int vfs_mkdir(struct inode *, struct dentry *, umode_t);
extern int vfs_mknod(struct inode *, struct dentry *, umode_t, dev_t);
extern int vfs_symlink(struct inode *, struct dentry *, const char *);
extern int vfs_link(struct dentry *, struct inode *, struct dentry *);
extern int vfs_rmdir(struct inode *, struct dentry *);
extern int vfs_unlink(struct inode *, struct dentry *);
extern int vfs_rename(struct inode *, struct dentry *, struct inode *, struct dentry *);
/*
* VFS dentry helper functions.
*/
extern void dentry_unhash(struct dentry *dentry);
/*
* VFS file helper functions.
*/
extern void inode_init_owner(struct inode *inode, const struct inode *dir,
umode_t mode);
/*
* VFS FS_IOC_FIEMAP helper definitions.
*/
struct fiemap_extent_info {
unsigned int fi_flags; /* Flags as passed from user */
unsigned int fi_extents_mapped; /* Number of mapped extents */
unsigned int fi_extents_max; /* Size of fiemap_extent array */
struct fiemap_extent __user *fi_extents_start; /* Start of
fiemap_extent array */
};
int fiemap_fill_next_extent(struct fiemap_extent_info *info, u64 logical,
u64 phys, u64 len, u32 flags);
int fiemap_check_flags(struct fiemap_extent_info *fieinfo, u32 fs_flags);
/*
* File types
*
* NOTE! These match bits 12..15 of stat.st_mode
* (ie "(i_mode >> 12) & 15").
*/
#define DT_UNKNOWN 0
#define DT_FIFO 1
#define DT_CHR 2
#define DT_DIR 4
#define DT_BLK 6
#define DT_REG 8
#define DT_LNK 10
#define DT_SOCK 12
#define DT_WHT 14
/*
* This is the "filldir" function type, used by readdir() to let
* the kernel specify what kind of dirent layout it wants to have.
* This allows the kernel to read directories into kernel space or
* to have different dirent layouts depending on the binary type.
*/
typedef int (*filldir_t)(void *, const char *, int, loff_t, u64, unsigned);
struct block_device_operations;
/* These macros are for out of kernel modules to test that
* the kernel supports the unlocked_ioctl and compat_ioctl
* fields in struct file_operations. */
#define HAVE_COMPAT_IOCTL 1
#define HAVE_UNLOCKED_IOCTL 1
struct file_operations {
struct module *owner;
loff_t (*llseek) (struct file *, loff_t, int);
ssize_t (*read) (struct file *, char __user *, size_t, loff_t *);
ssize_t (*write) (struct file *, const char __user *, size_t, loff_t *);
ssize_t (*aio_read) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
ssize_t (*aio_write) (struct kiocb *, const struct iovec *, unsigned long, loff_t);
int (*readdir) (struct file *, void *, filldir_t);
unsigned int (*poll) (struct file *, struct poll_table_struct *);
long (*unlocked_ioctl) (struct file *, unsigned int, unsigned long);
long (*compat_ioctl) (struct file *, unsigned int, unsigned long);
int (*mmap) (struct file *, struct vm_area_struct *);
int (*open) (struct inode *, struct file *);
int (*flush) (struct file *, fl_owner_t id);
int (*release) (struct inode *, struct file *);
int (*fsync) (struct file *, loff_t, loff_t, int datasync);
int (*aio_fsync) (struct kiocb *, int datasync);
int (*fasync) (int, struct file *, int);
int (*lock) (struct file *, int, struct file_lock *);
ssize_t (*sendpage) (struct file *, struct page *, int, size_t, loff_t *, int);
unsigned long (*get_unmapped_area)(struct file *, unsigned long, unsigned long, unsigned long, unsigned long);
int (*check_flags)(int);
int (*flock) (struct file *, int, struct file_lock *);
ssize_t (*splice_write)(struct pipe_inode_info *, struct file *, loff_t *, size_t, unsigned int);
ssize_t (*splice_read)(struct file *, loff_t *, struct pipe_inode_info *, size_t, unsigned int);
int (*setlease)(struct file *, long, struct file_lock **);
long (*fallocate)(struct file *file, int mode, loff_t offset,
loff_t len);
int (*show_fdinfo)(struct seq_file *m, struct file *f);
};
struct inode_operations {
struct dentry * (*lookup) (struct inode *,struct dentry *, unsigned int);
void * (*follow_link) (struct dentry *, struct nameidata *);
int (*permission) (struct inode *, int);
struct posix_acl * (*get_acl)(struct inode *, int);
int (*readlink) (struct dentry *, char __user *,int);
void (*put_link) (struct dentry *, struct nameidata *, void *);
int (*create) (struct inode *,struct dentry *, umode_t, bool);
int (*link) (struct dentry *,struct inode *,struct dentry *);
int (*unlink) (struct inode *,struct dentry *);
int (*symlink) (struct inode *,struct dentry *,const char *);
int (*mkdir) (struct inode *,struct dentry *,umode_t);
int (*rmdir) (struct inode *,struct dentry *);
int (*mknod) (struct inode *,struct dentry *,umode_t,dev_t);
int (*rename) (struct inode *, struct dentry *,
struct inode *, struct dentry *);
int (*setattr) (struct dentry *, struct iattr *);
int (*getattr) (struct vfsmount *mnt, struct dentry *, struct kstat *);
int (*setxattr) (struct dentry *, const char *,const void *,size_t,int);
ssize_t (*getxattr) (struct dentry *, const char *, void *, size_t);
ssize_t (*listxattr) (struct dentry *, char *, size_t);
int (*removexattr) (struct dentry *, const char *);
int (*fiemap)(struct inode *, struct fiemap_extent_info *, u64 start,
u64 len);
int (*update_time)(struct inode *, struct timespec *, int);
int (*atomic_open)(struct inode *, struct dentry *,
struct file *, unsigned open_flag,
umode_t create_mode, int *opened);
} ____cacheline_aligned;
ssize_t rw_copy_check_uvector(int type, const struct iovec __user * uvector,
unsigned long nr_segs, unsigned long fast_segs,
struct iovec *fast_pointer,
struct iovec **ret_pointer);
extern ssize_t vfs_read(struct file *, char __user *, size_t, loff_t *);
extern ssize_t vfs_write(struct file *, const char __user *, size_t, loff_t *);
extern ssize_t vfs_readv(struct file *, const struct iovec __user *,
unsigned long, loff_t *);
extern ssize_t vfs_writev(struct file *, const struct iovec __user *,
unsigned long, loff_t *);
struct super_operations {
struct inode *(*alloc_inode)(struct super_block *sb);
void (*destroy_inode)(struct inode *);
void (*dirty_inode) (struct inode *, int flags);
int (*write_inode) (struct inode *, struct writeback_control *wbc);
int (*drop_inode) (struct inode *);
void (*evict_inode) (struct inode *);
void (*put_super) (struct super_block *);
int (*sync_fs)(struct super_block *sb, int wait);
int (*freeze_fs) (struct super_block *);
int (*unfreeze_fs) (struct super_block *);
int (*statfs) (struct dentry *, struct kstatfs *);
int (*remount_fs) (struct super_block *, int *, char *);
void (*umount_begin) (struct super_block *);
int (*show_options)(struct seq_file *, struct dentry *);
int (*show_devname)(struct seq_file *, struct dentry *);
int (*show_path)(struct seq_file *, struct dentry *);
int (*show_stats)(struct seq_file *, struct dentry *);
#ifdef CONFIG_QUOTA
ssize_t (*quota_read)(struct super_block *, int, char *, size_t, loff_t);
ssize_t (*quota_write)(struct super_block *, int, const char *, size_t, loff_t);
#endif
int (*bdev_try_to_free_page)(struct super_block*, struct page*, gfp_t);
int (*nr_cached_objects)(struct super_block *);
void (*free_cached_objects)(struct super_block *, int);
};
/*
* Inode flags - they have no relation to superblock flags now
*/
#define S_SYNC 1 /* Writes are synced at once */
#define S_NOATIME 2 /* Do not update access times */
#define S_APPEND 4 /* Append-only file */
#define S_IMMUTABLE 8 /* Immutable file */
#define S_DEAD 16 /* removed, but still open directory */
#define S_NOQUOTA 32 /* Inode is not counted to quota */
#define S_DIRSYNC 64 /* Directory modifications are synchronous */
#define S_NOCMTIME 128 /* Do not update file c/mtime */
#define S_SWAPFILE 256 /* Do not truncate: swapon got its bmaps */
#define S_PRIVATE 512 /* Inode is fs-internal */
#define S_IMA 1024 /* Inode has an associated IMA struct */
#define S_AUTOMOUNT 2048 /* Automount/referral quasi-directory */
#define S_NOSEC 4096 /* no suid or xattr security attributes */
/*
* Note that nosuid etc flags are inode-specific: setting some file-system
* flags just means all the inodes inherit those flags by default. It might be
* possible to override it selectively if you really wanted to with some
* ioctl() that is not currently implemented.
*
* Exception: MS_RDONLY is always applied to the entire file system.
*
* Unfortunately, it is possible to change a filesystems flags with it mounted
* with files in use. This means that all of the inodes will not have their
* i_flags updated. Hence, i_flags no longer inherit the superblock mount
* flags, so these have to be checked separately. -- rmk@arm.uk.linux.org
*/
#define __IS_FLG(inode, flg) ((inode)->i_sb->s_flags & (flg))
#define IS_RDONLY(inode) ((inode)->i_sb->s_flags & MS_RDONLY)
#define IS_SYNC(inode) (__IS_FLG(inode, MS_SYNCHRONOUS) || \
((inode)->i_flags & S_SYNC))
#define IS_DIRSYNC(inode) (__IS_FLG(inode, MS_SYNCHRONOUS|MS_DIRSYNC) || \
((inode)->i_flags & (S_SYNC|S_DIRSYNC)))
#define IS_MANDLOCK(inode) __IS_FLG(inode, MS_MANDLOCK)
#define IS_NOATIME(inode) __IS_FLG(inode, MS_RDONLY|MS_NOATIME)
#define IS_I_VERSION(inode) __IS_FLG(inode, MS_I_VERSION)
#define IS_NOQUOTA(inode) ((inode)->i_flags & S_NOQUOTA)
#define IS_APPEND(inode) ((inode)->i_flags & S_APPEND)
#define IS_IMMUTABLE(inode) ((inode)->i_flags & S_IMMUTABLE)
#define IS_POSIXACL(inode) __IS_FLG(inode, MS_POSIXACL)
#define IS_DEADDIR(inode) ((inode)->i_flags & S_DEAD)
#define IS_NOCMTIME(inode) ((inode)->i_flags & S_NOCMTIME)
#define IS_SWAPFILE(inode) ((inode)->i_flags & S_SWAPFILE)
#define IS_PRIVATE(inode) ((inode)->i_flags & S_PRIVATE)
#define IS_IMA(inode) ((inode)->i_flags & S_IMA)
#define IS_AUTOMOUNT(inode) ((inode)->i_flags & S_AUTOMOUNT)
#define IS_NOSEC(inode) ((inode)->i_flags & S_NOSEC)
/*
* Inode state bits. Protected by inode->i_lock
*
* Three bits determine the dirty state of the inode, I_DIRTY_SYNC,
* I_DIRTY_DATASYNC and I_DIRTY_PAGES.
*
* Four bits define the lifetime of an inode. Initially, inodes are I_NEW,
* until that flag is cleared. I_WILL_FREE, I_FREEING and I_CLEAR are set at
* various stages of removing an inode.
*
* Two bits are used for locking and completion notification, I_NEW and I_SYNC.
*
* I_DIRTY_SYNC Inode is dirty, but doesn't have to be written on
* fdatasync(). i_atime is the usual cause.
* I_DIRTY_DATASYNC Data-related inode changes pending. We keep track of
* these changes separately from I_DIRTY_SYNC so that we
* don't have to write inode on fdatasync() when only
* mtime has changed in it.
* I_DIRTY_PAGES Inode has dirty pages. Inode itself may be clean.
* I_NEW Serves as both a mutex and completion notification.
* New inodes set I_NEW. If two processes both create
* the same inode, one of them will release its inode and
* wait for I_NEW to be released before returning.
* Inodes in I_WILL_FREE, I_FREEING or I_CLEAR state can
* also cause waiting on I_NEW, without I_NEW actually
* being set. find_inode() uses this to prevent returning
* nearly-dead inodes.
* I_WILL_FREE Must be set when calling write_inode_now() if i_count
* is zero. I_FREEING must be set when I_WILL_FREE is
* cleared.
* I_FREEING Set when inode is about to be freed but still has dirty
* pages or buffers attached or the inode itself is still
* dirty.
* I_CLEAR Added by clear_inode(). In this state the inode is
* clean and can be destroyed. Inode keeps I_FREEING.
*
* Inodes that are I_WILL_FREE, I_FREEING or I_CLEAR are
* prohibited for many purposes. iget() must wait for
* the inode to be completely released, then create it
* anew. Other functions will just ignore such inodes,
* if appropriate. I_NEW is used for waiting.
*
* I_SYNC Writeback of inode is running. The bit is set during
* data writeback, and cleared with a wakeup on the bit
* address once it is done. The bit is also used to pin
* the inode in memory for flusher thread.
*
* I_REFERENCED Marks the inode as recently references on the LRU list.
*
* I_DIO_WAKEUP Never set. Only used as a key for wait_on_bit().
*
* Q: What is the difference between I_WILL_FREE and I_FREEING?
*/
#define I_DIRTY_SYNC (1 << 0)
#define I_DIRTY_DATASYNC (1 << 1)
#define I_DIRTY_PAGES (1 << 2)
#define __I_NEW 3
#define I_NEW (1 << __I_NEW)
#define I_WILL_FREE (1 << 4)
#define I_FREEING (1 << 5)
#define I_CLEAR (1 << 6)
#define __I_SYNC 7
#define I_SYNC (1 << __I_SYNC)
#define I_REFERENCED (1 << 8)
#define __I_DIO_WAKEUP 9
#define I_DIO_WAKEUP (1 << I_DIO_WAKEUP)
#define I_DIRTY (I_DIRTY_SYNC | I_DIRTY_DATASYNC | I_DIRTY_PAGES)
extern void __mark_inode_dirty(struct inode *, int);
static inline void mark_inode_dirty(struct inode *inode)
{
__mark_inode_dirty(inode, I_DIRTY);
}
static inline void mark_inode_dirty_sync(struct inode *inode)
{
__mark_inode_dirty(inode, I_DIRTY_SYNC);
}
extern void inc_nlink(struct inode *inode);
extern void drop_nlink(struct inode *inode);
extern void clear_nlink(struct inode *inode);
extern void set_nlink(struct inode *inode, unsigned int nlink);
static inline void inode_inc_link_count(struct inode *inode)
{
inc_nlink(inode);
mark_inode_dirty(inode);
}
static inline void inode_dec_link_count(struct inode *inode)
{
drop_nlink(inode);
mark_inode_dirty(inode);
}
/**
* inode_inc_iversion - increments i_version
* @inode: inode that need to be updated
*
* Every time the inode is modified, the i_version field will be incremented.
* The filesystem has to be mounted with i_version flag
*/
static inline void inode_inc_iversion(struct inode *inode)
{
spin_lock(&inode->i_lock);
inode->i_version++;
spin_unlock(&inode->i_lock);
}
enum file_time_flags {
S_ATIME = 1,
S_MTIME = 2,
S_CTIME = 4,
S_VERSION = 8,
};
extern void touch_atime(struct path *);
static inline void file_accessed(struct file *file)
{
if (!(file->f_flags & O_NOATIME))
touch_atime(&file->f_path);
}
int sync_inode(struct inode *inode, struct writeback_control *wbc);
int sync_inode_metadata(struct inode *inode, int wait);
struct file_system_type {
const char *name;
int fs_flags;
#define FS_REQUIRES_DEV 1
#define FS_BINARY_MOUNTDATA 2
#define FS_HAS_SUBTYPE 4
#define FS_USERNS_MOUNT 8 /* Can be mounted by userns root */
#define FS_USERNS_DEV_MOUNT 16 /* A userns mount does not imply MNT_NODEV */
#define FS_RENAME_DOES_D_MOVE 32768 /* FS will handle d_move() during rename() internally. */
struct dentry *(*mount) (struct file_system_type *, int,
const char *, void *);
void (*kill_sb) (struct super_block *);
struct module *owner;
struct file_system_type * next;
struct hlist_head fs_supers;
struct lock_class_key s_lock_key;
struct lock_class_key s_umount_key;
struct lock_class_key s_vfs_rename_key;
struct lock_class_key s_writers_key[SB_FREEZE_LEVELS];
struct lock_class_key i_lock_key;
struct lock_class_key i_mutex_key;
struct lock_class_key i_mutex_dir_key;
};
#define MODULE_ALIAS_FS(NAME) MODULE_ALIAS("fs-" NAME)
extern struct dentry *mount_ns(struct file_system_type *fs_type, int flags,
void *data, int (*fill_super)(struct super_block *, void *, int));
extern struct dentry *mount_bdev(struct file_system_type *fs_type,
int flags, const char *dev_name, void *data,
int (*fill_super)(struct super_block *, void *, int));
extern struct dentry *mount_single(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int));
extern struct dentry *mount_nodev(struct file_system_type *fs_type,
int flags, void *data,
int (*fill_super)(struct super_block *, void *, int));
extern struct dentry *mount_subtree(struct vfsmount *mnt, const char *path);
void generic_shutdown_super(struct super_block *sb);
void kill_block_super(struct super_block *sb);
void kill_anon_super(struct super_block *sb);
void kill_litter_super(struct super_block *sb);
void deactivate_super(struct super_block *sb);
void deactivate_locked_super(struct super_block *sb);
int set_anon_super(struct super_block *s, void *data);
int get_anon_bdev(dev_t *);
void free_anon_bdev(dev_t);
struct super_block *sget(struct file_system_type *type,
int (*test)(struct super_block *,void *),
int (*set)(struct super_block *,void *),
int flags, void *data);
extern struct dentry *mount_pseudo(struct file_system_type *, char *,
const struct super_operations *ops,
const struct dentry_operations *dops,
unsigned long);
/* Alas, no aliases. Too much hassle with bringing module.h everywhere */
#define fops_get(fops) \
(((fops) && try_module_get((fops)->owner) ? (fops) : NULL))
#define fops_put(fops) \
do { if (fops) module_put((fops)->owner); } while(0)
extern int register_filesystem(struct file_system_type *);
extern int unregister_filesystem(struct file_system_type *);
extern struct vfsmount *kern_mount_data(struct file_system_type *, void *data);
#define kern_mount(type) kern_mount_data(type, NULL)
extern void kern_unmount(struct vfsmount *mnt);
extern int may_umount_tree(struct vfsmount *);
extern int may_umount(struct vfsmount *);
extern long do_mount(const char *, const char *, const char *, unsigned long, void *);
extern struct vfsmount *collect_mounts(struct path *);
extern void drop_collected_mounts(struct vfsmount *);
extern int iterate_mounts(int (*)(struct vfsmount *, void *), void *,
struct vfsmount *);
extern int vfs_statfs(struct path *, struct kstatfs *);
extern int user_statfs(const char __user *, struct kstatfs *);
extern int fd_statfs(int, struct kstatfs *);
extern int vfs_ustat(dev_t, struct kstatfs *);
extern int freeze_super(struct super_block *super);
extern int thaw_super(struct super_block *super);
extern bool our_mnt(struct vfsmount *mnt);
extern int current_umask(void);
/* /sys/fs */
extern struct kobject *fs_kobj;
#define MAX_RW_COUNT (INT_MAX & PAGE_CACHE_MASK)
extern int rw_verify_area(int, struct file *, loff_t *, size_t);
#define FLOCK_VERIFY_READ 1
#define FLOCK_VERIFY_WRITE 2
#ifdef CONFIG_FILE_LOCKING
extern int locks_mandatory_locked(struct inode *);
extern int locks_mandatory_area(int, struct inode *, struct file *, loff_t, size_t);
/*
* Candidates for mandatory locking have the setgid bit set
* but no group execute bit - an otherwise meaningless combination.
*/
static inline int __mandatory_lock(struct inode *ino)
{
return (ino->i_mode & (S_ISGID | S_IXGRP)) == S_ISGID;
}
/*
* ... and these candidates should be on MS_MANDLOCK mounted fs,
* otherwise these will be advisory locks
*/
static inline int mandatory_lock(struct inode *ino)
{
return IS_MANDLOCK(ino) && __mandatory_lock(ino);
}
static inline int locks_verify_locked(struct inode *inode)
{
if (mandatory_lock(inode))
return locks_mandatory_locked(inode);
return 0;
}
static inline int locks_verify_truncate(struct inode *inode,
struct file *filp,
loff_t size)
{
if (inode->i_flock && mandatory_lock(inode))
return locks_mandatory_area(
FLOCK_VERIFY_WRITE, inode, filp,
size < inode->i_size ? size : inode->i_size,
(size < inode->i_size ? inode->i_size - size
: size - inode->i_size)
);
return 0;
}
static inline int break_lease(struct inode *inode, unsigned int mode)
{
if (inode->i_flock)
return __break_lease(inode, mode);
return 0;
}
#else /* !CONFIG_FILE_LOCKING */
static inline int locks_mandatory_locked(struct inode *inode)
{
return 0;
}
static inline int locks_mandatory_area(int rw, struct inode *inode,
struct file *filp, loff_t offset,
size_t count)
{
return 0;
}
static inline int __mandatory_lock(struct inode *inode)
{
return 0;
}
static inline int mandatory_lock(struct inode *inode)
{
return 0;
}
static inline int locks_verify_locked(struct inode *inode)
{
return 0;
}
static inline int locks_verify_truncate(struct inode *inode, struct file *filp,
size_t size)
{
return 0;
}
static inline int break_lease(struct inode *inode, unsigned int mode)
{
return 0;
}
#endif /* CONFIG_FILE_LOCKING */
/* fs/open.c */
struct audit_names;
struct filename {
const char *name; /* pointer to actual string */
const __user char *uptr; /* original userland pointer */
struct audit_names *aname;
bool separate; /* should "name" be freed? */
};
extern long vfs_truncate(struct path *, loff_t);
extern int do_truncate(struct dentry *, loff_t start, unsigned int time_attrs,
struct file *filp);
extern int do_fallocate(struct file *file, int mode, loff_t offset,
loff_t len);
extern long do_sys_open(int dfd, const char __user *filename, int flags,
umode_t mode);
extern struct file *file_open_name(struct filename *, int, umode_t);
extern struct file *filp_open(const char *, int, umode_t);
extern struct file *file_open_root(struct dentry *, struct vfsmount *,
const char *, int);
extern struct file * dentry_open(const struct path *, int, const struct cred *);
extern int filp_close(struct file *, fl_owner_t id);
extern struct filename *getname(const char __user *);
enum {
FILE_CREATED = 1,
FILE_OPENED = 2
};
extern int finish_open(struct file *file, struct dentry *dentry,
int (*open)(struct inode *, struct file *),
int *opened);
extern int finish_no_open(struct file *file, struct dentry *dentry);
/* fs/ioctl.c */
extern int ioctl_preallocate(struct file *filp, void __user *argp);
/* fs/dcache.c */
extern void __init vfs_caches_init_early(void);
extern void __init vfs_caches_init(unsigned long);
extern struct kmem_cache *names_cachep;
extern void final_putname(struct filename *name);
#define __getname() kmem_cache_alloc(names_cachep, GFP_KERNEL)
#define __putname(name) kmem_cache_free(names_cachep, (void *)(name))
#ifndef CONFIG_AUDITSYSCALL
#define putname(name) final_putname(name)
#else
extern void putname(struct filename *name);
#endif
#ifdef CONFIG_BLOCK
extern int register_blkdev(unsigned int, const char *);
extern void unregister_blkdev(unsigned int, const char *);
extern struct block_device *bdget(dev_t);
extern struct block_device *bdgrab(struct block_device *bdev);
extern void bd_set_size(struct block_device *, loff_t size);
extern void bd_forget(struct inode *inode);
extern void bdput(struct block_device *);
extern void invalidate_bdev(struct block_device *);
extern void iterate_bdevs(void (*)(struct block_device *, void *), void *);
extern int sync_blockdev(struct block_device *bdev);
extern void kill_bdev(struct block_device *);
extern struct super_block *freeze_bdev(struct block_device *);
extern void emergency_thaw_all(void);
extern int thaw_bdev(struct block_device *bdev, struct super_block *sb);
extern int fsync_bdev(struct block_device *);
#else
static inline void bd_forget(struct inode *inode) {}
static inline int sync_blockdev(struct block_device *bdev) { return 0; }
static inline void kill_bdev(struct block_device *bdev) {}
static inline void invalidate_bdev(struct block_device *bdev) {}
static inline struct super_block *freeze_bdev(struct block_device *sb)
{
return NULL;
}
static inline int thaw_bdev(struct block_device *bdev, struct super_block *sb)
{
return 0;
}
static inline void iterate_bdevs(void (*f)(struct block_device *, void *), void *arg)
{
}
#endif
extern int sync_filesystem(struct super_block *);
extern const struct file_operations def_blk_fops;
extern void sync_filesystems(int wait);
extern const struct file_operations def_chr_fops;
extern const struct file_operations bad_sock_fops;
#ifdef CONFIG_BLOCK
extern int ioctl_by_bdev(struct block_device *, unsigned, unsigned long);
extern int blkdev_ioctl(struct block_device *, fmode_t, unsigned, unsigned long);
extern long compat_blkdev_ioctl(struct file *, unsigned, unsigned long);
extern int blkdev_get(struct block_device *bdev, fmode_t mode, void *holder);
extern struct block_device *blkdev_get_by_path(const char *path, fmode_t mode,
void *holder);
extern struct block_device *blkdev_get_by_dev(dev_t dev, fmode_t mode,
void *holder);
extern void blkdev_put(struct block_device *bdev, fmode_t mode);
#ifdef CONFIG_SYSFS
extern int bd_link_disk_holder(struct block_device *bdev, struct gendisk *disk);
extern void bd_unlink_disk_holder(struct block_device *bdev,
struct gendisk *disk);
#else
static inline int bd_link_disk_holder(struct block_device *bdev,
struct gendisk *disk)
{
return 0;
}
static inline void bd_unlink_disk_holder(struct block_device *bdev,
struct gendisk *disk)
{
}
#endif
#endif
/* fs/char_dev.c */
#define CHRDEV_MAJOR_HASH_SIZE 255
extern int alloc_chrdev_region(dev_t *, unsigned, unsigned, const char *);
extern int register_chrdev_region(dev_t, unsigned, const char *);
extern int __register_chrdev(unsigned int major, unsigned int baseminor,
unsigned int count, const char *name,
const struct file_operations *fops);
extern void __unregister_chrdev(unsigned int major, unsigned int baseminor,
unsigned int count, const char *name);
extern void unregister_chrdev_region(dev_t, unsigned);
extern void chrdev_show(struct seq_file *,off_t);
static inline int register_chrdev(unsigned int major, const char *name,
const struct file_operations *fops)
{
return __register_chrdev(major, 0, 256, name, fops);
}
static inline void unregister_chrdev(unsigned int major, const char *name)
{
__unregister_chrdev(major, 0, 256, name);
}
/* fs/block_dev.c */
#define BDEVNAME_SIZE 32 /* Largest string for a blockdev identifier */
#define BDEVT_SIZE 10 /* Largest string for MAJ:MIN for blkdev */
#ifdef CONFIG_BLOCK
#define BLKDEV_MAJOR_HASH_SIZE 255
extern const char *__bdevname(dev_t, char *buffer);
extern const char *bdevname(struct block_device *bdev, char *buffer);
extern struct block_device *lookup_bdev(const char *);
extern void blkdev_show(struct seq_file *,off_t);
#else
#define BLKDEV_MAJOR_HASH_SIZE 0
#endif
extern void init_special_inode(struct inode *, umode_t, dev_t);
/* Invalid inode operations -- fs/bad_inode.c */
extern void make_bad_inode(struct inode *);
extern int is_bad_inode(struct inode *);
#ifdef CONFIG_BLOCK
/*
* return READ, READA, or WRITE
*/
#define bio_rw(bio) ((bio)->bi_rw & (RW_MASK | RWA_MASK))
/*
* return data direction, READ or WRITE
*/
#define bio_data_dir(bio) ((bio)->bi_rw & 1)
extern void check_disk_size_change(struct gendisk *disk,
struct block_device *bdev);
extern int revalidate_disk(struct gendisk *);
extern int check_disk_change(struct block_device *);
extern int __invalidate_device(struct block_device *, bool);
extern int invalidate_partition(struct gendisk *, int);
#endif
unsigned long invalidate_mapping_pages(struct address_space *mapping,
pgoff_t start, pgoff_t end);
static inline void invalidate_remote_inode(struct inode *inode)
{
if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
S_ISLNK(inode->i_mode))
invalidate_mapping_pages(inode->i_mapping, 0, -1);
}
extern int invalidate_inode_pages2(struct address_space *mapping);
extern int invalidate_inode_pages2_range(struct address_space *mapping,
pgoff_t start, pgoff_t end);
extern int write_inode_now(struct inode *, int);
extern int filemap_fdatawrite(struct address_space *);
extern int filemap_flush(struct address_space *);
extern int filemap_fdatawait(struct address_space *);
extern int filemap_fdatawait_range(struct address_space *, loff_t lstart,
loff_t lend);
extern int filemap_write_and_wait(struct address_space *mapping);
extern int filemap_write_and_wait_range(struct address_space *mapping,
loff_t lstart, loff_t lend);
extern int __filemap_fdatawrite_range(struct address_space *mapping,
loff_t start, loff_t end, int sync_mode);
extern int filemap_fdatawrite_range(struct address_space *mapping,
loff_t start, loff_t end);
extern int vfs_fsync_range(struct file *file, loff_t start, loff_t end,
int datasync);
extern int vfs_fsync(struct file *file, int datasync);
extern int generic_write_sync(struct file *file, loff_t pos, loff_t count);
extern void emergency_sync(void);
extern void emergency_remount(void);
#ifdef CONFIG_BLOCK
extern sector_t bmap(struct inode *, sector_t);
#endif
extern int notify_change(struct dentry *, struct iattr *);
extern int inode_permission(struct inode *, int);
extern int generic_permission(struct inode *, int);
static inline bool execute_ok(struct inode *inode)
{
return (inode->i_mode & S_IXUGO) || S_ISDIR(inode->i_mode);
}
static inline struct inode *file_inode(struct file *f)
{
return f->f_inode;
}
static inline void file_start_write(struct file *file)
{
if (!S_ISREG(file_inode(file)->i_mode))
return;
__sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, true);
}
static inline bool file_start_write_trylock(struct file *file)
{
if (!S_ISREG(file_inode(file)->i_mode))
return true;
return __sb_start_write(file_inode(file)->i_sb, SB_FREEZE_WRITE, false);
}
static inline void file_end_write(struct file *file)
{
if (!S_ISREG(file_inode(file)->i_mode))
return;
__sb_end_write(file_inode(file)->i_sb, SB_FREEZE_WRITE);
}
/*
* get_write_access() gets write permission for a file.
* put_write_access() releases this write permission.
* This is used for regular files.
* We cannot support write (and maybe mmap read-write shared) accesses and
* MAP_DENYWRITE mmappings simultaneously. The i_writecount field of an inode
* can have the following values:
* 0: no writers, no VM_DENYWRITE mappings
* < 0: (-i_writecount) vm_area_structs with VM_DENYWRITE set exist
* > 0: (i_writecount) users are writing to the file.
*
* Normally we operate on that counter with atomic_{inc,dec} and it's safe
* except for the cases where we don't hold i_writecount yet. Then we need to
* use {get,deny}_write_access() - these functions check the sign and refuse
* to do the change if sign is wrong.
*/
static inline int get_write_access(struct inode *inode)
{
return atomic_inc_unless_negative(&inode->i_writecount) ? 0 : -ETXTBSY;
}
static inline int deny_write_access(struct file *file)
{
struct inode *inode = file_inode(file);
return atomic_dec_unless_positive(&inode->i_writecount) ? 0 : -ETXTBSY;
}
static inline void put_write_access(struct inode * inode)
{
atomic_dec(&inode->i_writecount);
}
static inline void allow_write_access(struct file *file)
{
if (file)
atomic_inc(&file_inode(file)->i_writecount);
}
#ifdef CONFIG_IMA
static inline void i_readcount_dec(struct inode *inode)
{
BUG_ON(!atomic_read(&inode->i_readcount));
atomic_dec(&inode->i_readcount);
}
static inline void i_readcount_inc(struct inode *inode)
{
atomic_inc(&inode->i_readcount);
}
#else
static inline void i_readcount_dec(struct inode *inode)
{
return;
}
static inline void i_readcount_inc(struct inode *inode)
{
return;
}
#endif
extern int do_pipe_flags(int *, int);
extern int kernel_read(struct file *, loff_t, char *, unsigned long);
extern ssize_t kernel_write(struct file *, const char *, size_t, loff_t);
extern struct file * open_exec(const char *);
/* fs/dcache.c -- generic fs support functions */
extern int is_subdir(struct dentry *, struct dentry *);
extern int path_is_under(struct path *, struct path *);
extern ino_t find_inode_number(struct dentry *, struct qstr *);
#include <linux/err.h>
/* needed for stackable file system support */
extern loff_t default_llseek(struct file *file, loff_t offset, int whence);
extern loff_t vfs_llseek(struct file *file, loff_t offset, int whence);
extern int inode_init_always(struct super_block *, struct inode *);
extern void inode_init_once(struct inode *);
extern void address_space_init_once(struct address_space *mapping);
extern void ihold(struct inode * inode);
extern void iput(struct inode *);
extern struct inode * igrab(struct inode *);
extern ino_t iunique(struct super_block *, ino_t);
extern int inode_needs_sync(struct inode *inode);
extern int generic_delete_inode(struct inode *inode);
static inline int generic_drop_inode(struct inode *inode)
{
return !inode->i_nlink || inode_unhashed(inode);
}
extern struct inode *ilookup5_nowait(struct super_block *sb,
unsigned long hashval, int (*test)(struct inode *, void *),
void *data);
extern struct inode *ilookup5(struct super_block *sb, unsigned long hashval,
int (*test)(struct inode *, void *), void *data);
extern struct inode *ilookup(struct super_block *sb, unsigned long ino);
extern struct inode * iget5_locked(struct super_block *, unsigned long, int (*test)(struct inode *, void *), int (*set)(struct inode *, void *), void *);
extern struct inode * iget_locked(struct super_block *, unsigned long);
extern int insert_inode_locked4(struct inode *, unsigned long, int (*test)(struct inode *, void *), void *);
extern int insert_inode_locked(struct inode *);
#ifdef CONFIG_DEBUG_LOCK_ALLOC
extern void lockdep_annotate_inode_mutex_key(struct inode *inode);
#else
static inline void lockdep_annotate_inode_mutex_key(struct inode *inode) { };
#endif
extern void unlock_new_inode(struct inode *);
extern unsigned int get_next_ino(void);
extern void __iget(struct inode * inode);
extern void iget_failed(struct inode *);
extern void clear_inode(struct inode *);
extern void __destroy_inode(struct inode *);
extern struct inode *new_inode_pseudo(struct super_block *sb);
extern struct inode *new_inode(struct super_block *sb);
extern void free_inode_nonrcu(struct inode *inode);
extern int should_remove_suid(struct dentry *);
extern int file_remove_suid(struct file *);
extern void __insert_inode_hash(struct inode *, unsigned long hashval);
static inline void insert_inode_hash(struct inode *inode)
{
__insert_inode_hash(inode, inode->i_ino);
}
extern void __remove_inode_hash(struct inode *);
static inline void remove_inode_hash(struct inode *inode)
{
if (!inode_unhashed(inode))
__remove_inode_hash(inode);
}
extern void inode_sb_list_add(struct inode *inode);
#ifdef CONFIG_BLOCK
extern void submit_bio(int, struct bio *);
extern int bdev_read_only(struct block_device *);
#endif
extern int set_blocksize(struct block_device *, int);
extern int sb_set_blocksize(struct super_block *, int);
extern int sb_min_blocksize(struct super_block *, int);
extern int generic_file_mmap(struct file *, struct vm_area_struct *);
extern int generic_file_readonly_mmap(struct file *, struct vm_area_struct *);
extern int generic_file_remap_pages(struct vm_area_struct *, unsigned long addr,
unsigned long size, pgoff_t pgoff);
extern int file_read_actor(read_descriptor_t * desc, struct page *page, unsigned long offset, unsigned long size);
int generic_write_checks(struct file *file, loff_t *pos, size_t *count, int isblk);
extern ssize_t generic_file_aio_read(struct kiocb *, const struct iovec *, unsigned long, loff_t);
extern ssize_t __generic_file_aio_write(struct kiocb *, const struct iovec *, unsigned long,
loff_t *);
extern ssize_t generic_file_aio_write(struct kiocb *, const struct iovec *, unsigned long, loff_t);
extern ssize_t generic_file_direct_write(struct kiocb *, const struct iovec *,
unsigned long *, loff_t, loff_t *, size_t, size_t);
extern ssize_t generic_file_buffered_write(struct kiocb *, const struct iovec *,
unsigned long, loff_t, loff_t *, size_t, ssize_t);
extern ssize_t do_sync_read(struct file *filp, char __user *buf, size_t len, loff_t *ppos);
extern ssize_t do_sync_write(struct file *filp, const char __user *buf, size_t len, loff_t *ppos);
extern int generic_segment_checks(const struct iovec *iov,
unsigned long *nr_segs, size_t *count, int access_flags);
/* fs/block_dev.c */
extern ssize_t blkdev_aio_write(struct kiocb *iocb, const struct iovec *iov,
unsigned long nr_segs, loff_t pos);
extern int blkdev_fsync(struct file *filp, loff_t start, loff_t end,
int datasync);
extern void block_sync_page(struct page *page);
/* fs/splice.c */
extern ssize_t generic_file_splice_read(struct file *, loff_t *,
struct pipe_inode_info *, size_t, unsigned int);
extern ssize_t default_file_splice_read(struct file *, loff_t *,
struct pipe_inode_info *, size_t, unsigned int);
extern ssize_t generic_file_splice_write(struct pipe_inode_info *,
struct file *, loff_t *, size_t, unsigned int);
extern ssize_t generic_splice_sendpage(struct pipe_inode_info *pipe,
struct file *out, loff_t *, size_t len, unsigned int flags);
extern void
file_ra_state_init(struct file_ra_state *ra, struct address_space *mapping);
extern loff_t noop_llseek(struct file *file, loff_t offset, int whence);
extern loff_t no_llseek(struct file *file, loff_t offset, int whence);
extern loff_t generic_file_llseek(struct file *file, loff_t offset, int whence);
extern loff_t generic_file_llseek_size(struct file *file, loff_t offset,
int whence, loff_t maxsize, loff_t eof);
extern loff_t fixed_size_llseek(struct file *file, loff_t offset,
int whence, loff_t size);
extern int generic_file_open(struct inode * inode, struct file * filp);
extern int nonseekable_open(struct inode * inode, struct file * filp);
#ifdef CONFIG_FS_XIP
extern ssize_t xip_file_read(struct file *filp, char __user *buf, size_t len,
loff_t *ppos);
extern int xip_file_mmap(struct file * file, struct vm_area_struct * vma);
extern ssize_t xip_file_write(struct file *filp, const char __user *buf,
size_t len, loff_t *ppos);
extern int xip_truncate_page(struct address_space *mapping, loff_t from);
#else
static inline int xip_truncate_page(struct address_space *mapping, loff_t from)
{
return 0;
}
#endif
#ifdef CONFIG_BLOCK
typedef void (dio_submit_t)(int rw, struct bio *bio, struct inode *inode,
loff_t file_offset);
enum {
/* need locking between buffered and direct access */
DIO_LOCKING = 0x01,
/* filesystem does not support filling holes */
DIO_SKIP_HOLES = 0x02,
};
void dio_end_io(struct bio *bio, int error);
ssize_t __blockdev_direct_IO(int rw, struct kiocb *iocb, struct inode *inode,
struct block_device *bdev, const struct iovec *iov, loff_t offset,
unsigned long nr_segs, get_block_t get_block, dio_iodone_t end_io,
dio_submit_t submit_io, int flags);
static inline ssize_t blockdev_direct_IO(int rw, struct kiocb *iocb,
struct inode *inode, const struct iovec *iov, loff_t offset,
unsigned long nr_segs, get_block_t get_block)
{
return __blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
offset, nr_segs, get_block, NULL, NULL,
DIO_LOCKING | DIO_SKIP_HOLES);
}
#endif
void inode_dio_wait(struct inode *inode);
void inode_dio_done(struct inode *inode);
struct inode *dio_bio_get_inode(struct bio *bio);
extern const struct file_operations generic_ro_fops;
#define special_file(m) (S_ISCHR(m)||S_ISBLK(m)||S_ISFIFO(m)||S_ISSOCK(m))
extern int vfs_readlink(struct dentry *, char __user *, int, const char *);
extern int vfs_follow_link(struct nameidata *, const char *);
extern int page_readlink(struct dentry *, char __user *, int);
extern void *page_follow_link_light(struct dentry *, struct nameidata *);
extern void page_put_link(struct dentry *, struct nameidata *, void *);
extern int __page_symlink(struct inode *inode, const char *symname, int len,
int nofs);
extern int page_symlink(struct inode *inode, const char *symname, int len);
extern const struct inode_operations page_symlink_inode_operations;
extern int generic_readlink(struct dentry *, char __user *, int);
extern void generic_fillattr(struct inode *, struct kstat *);
extern int vfs_getattr(struct path *, struct kstat *);
void __inode_add_bytes(struct inode *inode, loff_t bytes);
void inode_add_bytes(struct inode *inode, loff_t bytes);
void __inode_sub_bytes(struct inode *inode, loff_t bytes);
void inode_sub_bytes(struct inode *inode, loff_t bytes);
loff_t inode_get_bytes(struct inode *inode);
void inode_set_bytes(struct inode *inode, loff_t bytes);
extern int vfs_readdir(struct file *, filldir_t, void *);
extern int vfs_stat(const char __user *, struct kstat *);
extern int vfs_lstat(const char __user *, struct kstat *);
extern int vfs_fstat(unsigned int, struct kstat *);
extern int vfs_fstatat(int , const char __user *, struct kstat *, int);
extern int do_vfs_ioctl(struct file *filp, unsigned int fd, unsigned int cmd,
unsigned long arg);
extern int __generic_block_fiemap(struct inode *inode,
struct fiemap_extent_info *fieinfo,
loff_t start, loff_t len,
get_block_t *get_block);
extern int generic_block_fiemap(struct inode *inode,
struct fiemap_extent_info *fieinfo, u64 start,
u64 len, get_block_t *get_block);
extern void get_filesystem(struct file_system_type *fs);
extern void put_filesystem(struct file_system_type *fs);
extern struct file_system_type *get_fs_type(const char *name);
extern struct super_block *get_super(struct block_device *);
extern struct super_block *get_super_thawed(struct block_device *);
extern struct super_block *get_active_super(struct block_device *bdev);
extern void drop_super(struct super_block *sb);
extern void iterate_supers(void (*)(struct super_block *, void *), void *);
extern void iterate_supers_type(struct file_system_type *,
void (*)(struct super_block *, void *), void *);
extern int dcache_dir_open(struct inode *, struct file *);
extern int dcache_dir_close(struct inode *, struct file *);
extern loff_t dcache_dir_lseek(struct file *, loff_t, int);
extern int dcache_readdir(struct file *, void *, filldir_t);
extern int simple_setattr(struct dentry *, struct iattr *);
extern int simple_getattr(struct vfsmount *, struct dentry *, struct kstat *);
extern int simple_statfs(struct dentry *, struct kstatfs *);
extern int simple_open(struct inode *inode, struct file *file);
extern int simple_link(struct dentry *, struct inode *, struct dentry *);
extern int simple_unlink(struct inode *, struct dentry *);
extern int simple_rmdir(struct inode *, struct dentry *);
extern int simple_rename(struct inode *, struct dentry *, struct inode *, struct dentry *);
extern int noop_fsync(struct file *, loff_t, loff_t, int);
extern int simple_empty(struct dentry *);
extern int simple_readpage(struct file *file, struct page *page);
extern int simple_write_begin(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned flags,
struct page **pagep, void **fsdata);
extern int simple_write_end(struct file *file, struct address_space *mapping,
loff_t pos, unsigned len, unsigned copied,
struct page *page, void *fsdata);
extern struct dentry *simple_lookup(struct inode *, struct dentry *, unsigned int flags);
extern ssize_t generic_read_dir(struct file *, char __user *, size_t, loff_t *);
extern const struct file_operations simple_dir_operations;
extern const struct inode_operations simple_dir_inode_operations;
struct tree_descr { char *name; const struct file_operations *ops; int mode; };
struct dentry *d_alloc_name(struct dentry *, const char *);
extern int simple_fill_super(struct super_block *, unsigned long, struct tree_descr *);
extern int simple_pin_fs(struct file_system_type *, struct vfsmount **mount, int *count);
extern void simple_release_fs(struct vfsmount **mount, int *count);
extern ssize_t simple_read_from_buffer(void __user *to, size_t count,
loff_t *ppos, const void *from, size_t available);
extern ssize_t simple_write_to_buffer(void *to, size_t available, loff_t *ppos,
const void __user *from, size_t count);
extern int generic_file_fsync(struct file *, loff_t, loff_t, int);
extern int generic_check_addressable(unsigned, u64);
#ifdef CONFIG_MIGRATION
extern int buffer_migrate_page(struct address_space *,
struct page *, struct page *,
enum migrate_mode);
#else
#define buffer_migrate_page NULL
#endif
extern int inode_change_ok(const struct inode *, struct iattr *);
extern int inode_newsize_ok(const struct inode *, loff_t offset);
extern void setattr_copy(struct inode *inode, const struct iattr *attr);
extern int file_update_time(struct file *file);
extern int generic_show_options(struct seq_file *m, struct dentry *root);
extern void save_mount_options(struct super_block *sb, char *options);
extern void replace_mount_options(struct super_block *sb, char *options);
static inline ino_t parent_ino(struct dentry *dentry)
{
ino_t res;
/*
* Don't strictly need d_lock here? If the parent ino could change
* then surely we'd have a deeper race in the caller?
*/
spin_lock(&dentry->d_lock);
res = dentry->d_parent->d_inode->i_ino;
spin_unlock(&dentry->d_lock);
return res;
}
/* Transaction based IO helpers */
/*
* An argresp is stored in an allocated page and holds the
* size of the argument or response, along with its content
*/
struct simple_transaction_argresp {
ssize_t size;
char data[0];
};
#define SIMPLE_TRANSACTION_LIMIT (PAGE_SIZE - sizeof(struct simple_transaction_argresp))
char *simple_transaction_get(struct file *file, const char __user *buf,
size_t size);
ssize_t simple_transaction_read(struct file *file, char __user *buf,
size_t size, loff_t *pos);
int simple_transaction_release(struct inode *inode, struct file *file);
void simple_transaction_set(struct file *file, size_t n);
/*
* simple attribute files
*
* These attributes behave similar to those in sysfs:
*
* Writing to an attribute immediately sets a value, an open file can be
* written to multiple times.
*
* Reading from an attribute creates a buffer from the value that might get
* read with multiple read calls. When the attribute has been read
* completely, no further read calls are possible until the file is opened
* again.
*
* All attributes contain a text representation of a numeric value
* that are accessed with the get() and set() functions.
*/
#define DEFINE_SIMPLE_ATTRIBUTE(__fops, __get, __set, __fmt) \
static int __fops ## _open(struct inode *inode, struct file *file) \
{ \
__simple_attr_check_format(__fmt, 0ull); \
return simple_attr_open(inode, file, __get, __set, __fmt); \
} \
static const struct file_operations __fops = { \
.owner = THIS_MODULE, \
.open = __fops ## _open, \
.release = simple_attr_release, \
.read = simple_attr_read, \
.write = simple_attr_write, \
.llseek = generic_file_llseek, \
};
static inline __printf(1, 2)
void __simple_attr_check_format(const char *fmt, ...)
{
/* don't do anything, just let the compiler check the arguments; */
}
int simple_attr_open(struct inode *inode, struct file *file,
int (*get)(void *, u64 *), int (*set)(void *, u64),
const char *fmt);
int simple_attr_release(struct inode *inode, struct file *file);
ssize_t simple_attr_read(struct file *file, char __user *buf,
size_t len, loff_t *ppos);
ssize_t simple_attr_write(struct file *file, const char __user *buf,
size_t len, loff_t *ppos);
struct ctl_table;
int proc_nr_files(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos);
int proc_nr_dentry(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos);
int proc_nr_inodes(struct ctl_table *table, int write,
void __user *buffer, size_t *lenp, loff_t *ppos);
int __init get_filesystem_list(char *buf);
#define __FMODE_EXEC ((__force int) FMODE_EXEC)
#define __FMODE_NONOTIFY ((__force int) FMODE_NONOTIFY)
#define ACC_MODE(x) ("\004\002\006\006"[(x)&O_ACCMODE])
#define OPEN_FMODE(flag) ((__force fmode_t)(((flag + 1) & O_ACCMODE) | \
(flag & __FMODE_NONOTIFY)))
static inline int is_sxid(umode_t mode)
{
return (mode & S_ISUID) || ((mode & S_ISGID) && (mode & S_IXGRP));
}
static inline void inode_has_no_xattr(struct inode *inode)
{
if (!is_sxid(inode->i_mode) && (inode->i_sb->s_flags & MS_NOSEC))
inode->i_flags |= S_NOSEC;
}
#endif /* _LINUX_FS_H */
| AndyPhoenix9879/SkyMelon-msm8939 | include/linux/fs.h | C | gpl-2.0 | 91,630 |
/*
* Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef MANGOSSERVER_MOVESPLINEINIT_H
#define MANGOSSERVER_MOVESPLINEINIT_H
#include "MoveSplineInitArgs.h"
#include "../PathFinder.h"
class Unit;
namespace Movement
{
enum AnimType
{
ToGround = 0, // 460 = ToGround, index of AnimationData.dbc
FlyToFly = 1, // 461 = FlyToFly?
ToFly = 2, // 458 = ToFly
FlyToGround = 3, // 463 = FlyToGround
};
/* Initializes and launches spline movement
*/
class MANGOS_DLL_SPEC MoveSplineInit
{
public:
explicit MoveSplineInit(Unit& m);
/* Final pass of initialization that launches spline movement.
* @return duration - estimated travel time
*/
int32 Launch();
/* Adds movement by parabolic trajectory
* @param amplitude - the maximum height of parabola, value could be negative and positive
* @param start_time - delay between movement starting time and beginning to move by parabolic trajectory
* can't be combined with final animation
*/
void SetParabolic(float amplitude, float start_time);
/* Plays animation after movement done
* can't be combined with parabolic movement
*/
void SetAnimation(AnimType anim);
/* Adds final facing animation
* sets unit's facing to specified point/angle after all path done
* you can have only one final facing: previous will be overriden
*/
void SetFacing(float angle);
void SetFacing(Vector3 const& point);
void SetFacing(const Unit* target);
/* Initializes movement by path
* @param path - array of points, shouldn't be empty
* @param pointId - Id of fisrt point of the path. Example: when third path point will be done it will notify that pointId + 3 done
*/
void MovebyPath(const PointsArray& path, int32 pointId = 0);
/* Initializes simple A to B mition, A is current unit's position, B is destination
*/
void MoveTo(const Vector3& destination, bool generatePath = false, bool forceDestination = false);
void MoveTo(float x, float y, float z, bool generatePath = false, bool forceDestination = false);
/* Sets Id of fisrt point of the path. When N-th path point will be done ILisener will notify that pointId + N done
* Needed for waypoint movement where path splitten into parts
*/
void SetFirstPointId(int32 pointId) { args.path_Idx_offset = pointId; }
/* Enables CatmullRom spline interpolation mode(makes path smooth)
* if not enabled linear spline mode will be choosen. Disabled by default
*/
void SetSmooth();
/* Enables CatmullRom spline interpolation mode, enables flying animation. Disabled by default
*/
void SetFly();
/* Enables walk mode. Disabled by default
*/
void SetWalk(bool enable);
/* Makes movement cyclic. Disabled by default
*/
void SetCyclic();
/* Enables falling mode. Disabled by default
*/
void SetFall();
/* Inverses unit model orientation. Disabled by default
*/
void SetOrientationInversed();
/* Fixes unit's model rotation. Disabled by default
*/
void SetOrientationFixed(bool enable);
/* Enables transport enter/exit modes
*/
void SetTransportEnter();
void SetTransportExit();
/* Sets the velocity (in case you want to have custom movement velocity)
* if no set, speed will be selected based on unit's speeds and current movement mode
* Has no effect if falling mode enabled
* velocity shouldn't be negative
*/
void SetVelocity(float velocity);
/* Sets BoardVehicle flag
*/
void SetBoardVehicle();
/* Sets ExitVehicle flag
*/
void SetExitVehicle();
PointsArray& Path() { return args.path; }
protected:
MoveSplineInitArgs args;
Unit& unit;
};
inline void MoveSplineInit::SetFly() { args.flags.EnableFlying();}
inline void MoveSplineInit::SetWalk(bool enable) { args.flags.walkmode = enable;}
inline void MoveSplineInit::SetSmooth() { args.flags.EnableCatmullRom();}
inline void MoveSplineInit::SetCyclic() { args.flags.cyclic = true;}
inline void MoveSplineInit::SetFall() { args.flags.EnableFalling();}
inline void MoveSplineInit::SetVelocity(float vel) { args.velocity = vel;}
inline void MoveSplineInit::SetOrientationInversed() { args.flags.orientationInversed = true;}
inline void MoveSplineInit::SetOrientationFixed(bool enable) { args.flags.orientationFixed = enable;}
inline void MoveSplineInit::SetBoardVehicle() { args.flags.EnableBoardVehicle(); }
inline void MoveSplineInit::SetExitVehicle() { args.flags.EnableExitVehicle(); }
inline void MoveSplineInit::MovebyPath(const PointsArray& controls, int32 path_offset)
{
args.path_Idx_offset = path_offset;
args.path.assign(controls.begin(), controls.end());
}
inline void MoveSplineInit::MoveTo(float x, float y, float z, bool generatePath, bool forceDestination)
{
Vector3 v(x, y, z);
MoveTo(v, generatePath, forceDestination);
}
inline void MoveSplineInit::MoveTo(const Vector3& dest, bool generatePath, bool forceDestination)
{
if (generatePath)
{
PathFinder path(&unit);
path.calculate(dest.x, dest.y, dest.z, forceDestination);
MovebyPath(path.getPath());
}
else
{
args.path_Idx_offset = 0;
args.path.resize(2);
args.path[1] = dest;
}
}
inline void MoveSplineInit::SetParabolic(float amplitude, float time_shift)
{
args.time_perc = time_shift;
args.parabolic_amplitude = amplitude;
args.flags.EnableParabolic();
}
inline void MoveSplineInit::SetAnimation(AnimType anim)
{
args.time_perc = 0.f;
args.flags.EnableAnimation((uint8)anim);
}
inline void MoveSplineInit::SetFacing(Vector3 const& spot)
{
args.facing.f.x = spot.x;
args.facing.f.y = spot.y;
args.facing.f.z = spot.z;
args.flags.EnableFacingPoint();
}
}
#endif // MANGOSSERVER_MOVESPLINEINIT_H
| wuzhupc/mangos | src/game/movement/MoveSplineInit.h | C | gpl-2.0 | 7,511 |
-- phpMyAdmin SQL Dump
-- version 4.0.2
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Erstellungszeit: 01. Jan 2014 um 14:15
-- Server Version: 5.5.31-0+wheezy1-log
-- PHP-Version: 5.4.4-14+deb7u5
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Datenbank: `bookmark2`
--
-- --------------------------------------------------------
--
-- Tabellenstruktur für Tabelle `typenDefinition`
--
CREATE TABLE IF NOT EXISTS `typenDefinition` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`reihenfolge` int(3) DEFAULT NULL,
`name` varchar(150) DEFAULT NULL,
`typ` varchar(100) DEFAULT NULL,
`spaltenbreite` varchar(100) NOT NULL DEFAULT '6,12',
`beschreibung` varchar(100) DEFAULT NULL,
`eingabeFormular` tinyint(1) DEFAULT NULL,
`ergebnisListe` tinyint(1) DEFAULT '0',
`suchwert` varchar(200) NOT NULL,
`eingabewert` varchar(200) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`),
UNIQUE KEY `name` (`name`),
KEY `reihenfolge` (`reihenfolge`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=27 ;
--
-- Daten für Tabelle `typenDefinition`
--
INSERT INTO `typenDefinition` (`id`, `reihenfolge`, `name`, `typ`, `spaltenbreite`, `beschreibung`, `eingabeFormular`, `ergebnisListe`, `suchwert`, `eingabewert`) VALUES
(1, 50, 'id', 'zahl', '', 'ID', 0, 0, '%', '4'),
(5, 99, 'editStatus', 'einstellung', '', 'Einstellungsparameter', NULL, 0, '0', ''),
(6, 99, 'startPage', 'einstellung', '', 'Startseite', NULL, 0, '0', ''),
(8, 99, 'maxEintraege', 'einstellung', '', 'Maximale Anzahl der Einträge pro Seite', NULL, 0, '10', ''),
(9, 99, 'sortierung', 'einstellung', '', 'Sortierung der Ergebnisliste', NULL, 0, 'Speicherdatum', ''),
(10, 99, 'sortierfolge', 'einstellung', '', 'Sortierung, aufsteigend ist 1, absteigend 0', NULL, 0, '0', ''),
(12, 99, 'fileupload', 'einstellung', '', 'Soll ein file upgeloaded werden?', NULL, 0, '0', '0'),
(13, 51, 'Speicherdatum', 'datum', '', 'Speicherdatum', 0, 0, '%', '05.12.2013'),
(14, 99, 'datumFormat', 'einstellung', '', 'Format des Datums [d -> Tag] [m -> Monat] [Y -> Jahr] [H -> Stunden] [i -> minuten] [s -> Sekunden]', 0, 0, 'd.m.Y', ''),
(21, 1, 'beschreibung', 'text', '10,10', 'Beschreibung', 1, 1, '%', 'Böhnse Onkelz'),
(22, 3, 'tag', 'auswahl', '9,12', 'Tag', 1, 1, '%', '2'),
(23, 0, 'url', 'url', '2,2', 'URL', 1, 1, '%', 'http://onkelz.de'),
(24, 4, 'favorit', 'auswahl', '3,12', 'Favorit', 1, 1, '%', '0'),
(25, 99, 'tabellenNameKurz', 'einstellung', '', 'Name der Tabelle der angezeigt werden soll', 0, 0, 'Bookmarks', ''),
(26, 99, 'tabellenNameLang', 'einstellung', '', 'langer Anzeigename der Tabelle', 0, 0, 'Bookmark-Verwaltung', '');
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
| ChristianSchlake/cutter | initialDatabases/typenDefinition.sql | SQL | gpl-2.0 | 3,083 |
from numpy import *
from matplotlib.pyplot import *
import scipy.constants as sc
import copy
import scipy.integrate as integ
# test sun/earth with hw5(1.989e30,5.972e24,149.6e6,0.0167,1000)
def hw5(m1, m2, a, e, tmax, tstep=0.001, tplot=0.025, method='leapfrog'):
if method != 'leapfrog' and method != 'odeint':
print("That's not a method")
return()
# initialize commonly used variables
period = sqrt((4*(pi**2)*(a**3)) / (sc.G*(m1 + m2)))
dt = period*tstep
# initialize objects at time 0
q = m1 / m2
r0 = (1-e)*a/(1+q)
v0 = (1/(1+q))*sqrt((1+e)/(1-e))*sqrt(sc.G*(m1+m2)/a)
rv = array([r0, 0, 0, v0, -q*r0, 0, 0, -q*v0])
# set up figure
figure(1)
gca().set_aspect('equal')
xlim([-2*a, 2*a])
ylim([-2*a, 2*a])
rv_list = []
if method == 'leapfrog':
timeCounter = 0
frameCounter = 0
while timeCounter < tmax:
# plot positions if tplot time has passed
if frameCounter >= tplot:
frameCounter = 0
rv_list.append(copy.deepcopy(rv))
# calc positions
rv[0] = rv[0] + rv[2]*dt
rv[1] = rv[1] + rv[3]*dt
rv[4] = rv[4] + rv[6]*dt
rv[5] = rv[5] + rv[7]*dt
# calc acceleration
r = array([rv[0] - rv[4], rv[1] - rv[5]])
force = ((sc.G*m1*m2)/(np.linalg.norm(r)**2))*(r/np.linalg.norm(r))
# calc velocity
rv[2] = rv[2] - (force[0]/m1)*dt
rv[3] = rv[3] - (force[1]/m1)*dt
rv[6] = rv[6] + (force[0]/m2)*dt
rv[7] = rv[7] + (force[1]/m2)*dt
# increment counters
timeCounter += tstep
frameCounter += tstep
# plot final position
rv_list.append(copy.deepcopy(rv))
rv_list_plot = rv_list
else:
# odeint
rv_list = integ.odeint(deriv, rv, arange(0, tmax*period, dt), (m1, m2))
# needed to calculate using tstep, but we want to plot
# using tplot,
t_interval = tplot / tstep
rv_list_plot = rv_list[::t_interval]
# plot
for i in range(len(rv_list_plot)):
plot(rv_list_plot[i][0],rv_list_plot[i][1],'bo')
plot(rv_list_plot[i][4],rv_list_plot[i][5],'go')
draw()
def deriv(rv, dt, m1, m2):
# calc position deriv
rv_copy = zeros(8)
rv_copy[0] = rv[2]
rv_copy[1] = rv[3]
rv_copy[4] = rv[6]
rv_copy[5] = rv[7]
# calc velocity deriv
r = array([rv[0] - rv[4], rv[1] - rv[5]])
force = ((sc.G*m1*m2)/(np.linalg.norm(r)**2))*(r/np.linalg.norm(r))
rv_copy[2] = - (force[0]/m1)
rv_copy[3] = - (force[1]/m1)
rv_copy[6] = + (force[0]/m2)
rv_copy[7] = + (force[1]/m2)
return rv_copy
| smorad/ast119 | hw5.py | Python | gpl-2.0 | 2,857 |
/*
* ak4678.h - ASoC codec driver for AK4678
*
* Copyright 2012, AsahiKASEI Co., Ltd.
* Copyright 2012, Insignal Co., Ltd.
* Author: Claude Youn <claude@insignal.co.kr>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
*/
#ifndef __AK4678_H__
#define __AK4678_H__
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/pcm_params.h>
#include <sound/soc.h>
#ifndef SND_SOC_DAIFMT_SFS
# define SND_SOC_DAIFMT_SFS 7
# define SND_SOC_DAIFMT_LFS 8
#endif
struct ak4678_priv {
struct snd_soc_codec *codec;
struct snd_soc_dai *codec_dai;
int num_of_dai;
struct snd_soc_codec_driver *codec_driver;
};
int ak4678_hookup_probe(struct device *dev);
#endif
| elixirflash/dm-keepfast | sound/soc/codecs/ak4678.h | C | gpl-2.0 | 1,026 |
# CMAKE generated file: DO NOT EDIT!
# Generated by "Unix Makefiles" Generator, CMake Version 2.8
# Default target executed when no arguments are given to make.
default_target: all
.PHONY : default_target
#=============================================================================
# Special targets provided by cmake.
# Disable implicit rules so canonical targets will work.
.SUFFIXES:
# Remove some rules from gmake that .SUFFIXES does not remove.
SUFFIXES =
.SUFFIXES: .hpux_make_needs_suffix_list
# Suppress display of executed commands.
$(VERBOSE).SILENT:
# A target that is always out of date.
cmake_force:
.PHONY : cmake_force
#=============================================================================
# Set environment variables for the build.
# The shell in which to execute make rules.
SHELL = /bin/sh
# The CMake executable.
CMAKE_COMMAND = /usr/bin/cmake
# The command to remove a file.
RM = /usr/bin/cmake -E remove -f
# Escaping for special characters.
EQUALS = =
# The top-level source directory on which CMake was run.
CMAKE_SOURCE_DIR = /home/akshay/PMC/plasma-mediacenter
# The top-level build directory on which CMake was run.
CMAKE_BINARY_DIR = /home/akshay/PMC/plasma-mediacenter/build
#=============================================================================
# Targets provided globally by CMake.
# Special rule for the target edit_cache
edit_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running interactive CMake command-line interface..."
/usr/bin/cmake -i .
.PHONY : edit_cache
# Special rule for the target edit_cache
edit_cache/fast: edit_cache
.PHONY : edit_cache/fast
# Special rule for the target install
install: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install
# Special rule for the target install
install/fast: preinstall/fast
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Install the project..."
/usr/bin/cmake -P cmake_install.cmake
.PHONY : install/fast
# Special rule for the target install/local
install/local: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing only the local directory..."
/usr/bin/cmake -DCMAKE_INSTALL_LOCAL_ONLY=1 -P cmake_install.cmake
.PHONY : install/local
# Special rule for the target install/local
install/local/fast: install/local
.PHONY : install/local/fast
# Special rule for the target install/strip
install/strip: preinstall
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Installing the project stripped..."
/usr/bin/cmake -DCMAKE_INSTALL_DO_STRIP=1 -P cmake_install.cmake
.PHONY : install/strip
# Special rule for the target install/strip
install/strip/fast: install/strip
.PHONY : install/strip/fast
# Special rule for the target list_install_components
list_install_components:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Available install components are: \"Devel\" \"Unspecified\""
.PHONY : list_install_components
# Special rule for the target list_install_components
list_install_components/fast: list_install_components
.PHONY : list_install_components/fast
# Special rule for the target rebuild_cache
rebuild_cache:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running CMake to regenerate build system..."
/usr/bin/cmake -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR)
.PHONY : rebuild_cache
# Special rule for the target rebuild_cache
rebuild_cache/fast: rebuild_cache
.PHONY : rebuild_cache/fast
# Special rule for the target test
test:
@$(CMAKE_COMMAND) -E cmake_echo_color --switch=$(COLOR) --cyan "Running tests..."
/usr/bin/ctest --force-new-ctest-process $(ARGS)
.PHONY : test
# Special rule for the target test
test/fast: test
.PHONY : test/fast
# The main all target
all: cmake_check_build_system
cd /home/akshay/PMC/plasma-mediacenter/build && $(CMAKE_COMMAND) -E cmake_progress_start /home/akshay/PMC/plasma-mediacenter/build/CMakeFiles /home/akshay/PMC/plasma-mediacenter/build/shells/newshell/CMakeFiles/progress.marks
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f CMakeFiles/Makefile2 shells/newshell/all
$(CMAKE_COMMAND) -E cmake_progress_start /home/akshay/PMC/plasma-mediacenter/build/CMakeFiles 0
.PHONY : all
# The main clean target
clean:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f CMakeFiles/Makefile2 shells/newshell/clean
.PHONY : clean
# The main clean target
clean/fast: clean
.PHONY : clean/fast
# Prepare targets for installation.
preinstall: all
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f CMakeFiles/Makefile2 shells/newshell/preinstall
.PHONY : preinstall
# Prepare targets for installation.
preinstall/fast:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f CMakeFiles/Makefile2 shells/newshell/preinstall
.PHONY : preinstall/fast
# clear depends
depend:
cd /home/akshay/PMC/plasma-mediacenter/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 1
.PHONY : depend
# Convenience name for target.
shells/newshell/CMakeFiles/plasma-mediacenter.dir/rule:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f CMakeFiles/Makefile2 shells/newshell/CMakeFiles/plasma-mediacenter.dir/rule
.PHONY : shells/newshell/CMakeFiles/plasma-mediacenter.dir/rule
# Convenience name for target.
plasma-mediacenter: shells/newshell/CMakeFiles/plasma-mediacenter.dir/rule
.PHONY : plasma-mediacenter
# fast build rule for target.
plasma-mediacenter/fast:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/build
.PHONY : plasma-mediacenter/fast
# Convenience name for target.
shells/newshell/CMakeFiles/plasma-mediacenter_automoc.dir/rule:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f CMakeFiles/Makefile2 shells/newshell/CMakeFiles/plasma-mediacenter_automoc.dir/rule
.PHONY : shells/newshell/CMakeFiles/plasma-mediacenter_automoc.dir/rule
# Convenience name for target.
plasma-mediacenter_automoc: shells/newshell/CMakeFiles/plasma-mediacenter_automoc.dir/rule
.PHONY : plasma-mediacenter_automoc
# fast build rule for target.
plasma-mediacenter_automoc/fast:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter_automoc.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter_automoc.dir/build
.PHONY : plasma-mediacenter_automoc/fast
# target to build an object file
main.o:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/main.o
.PHONY : main.o
# target to preprocess a source file
main.i:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/main.i
.PHONY : main.i
# target to generate assembly for a file
main.s:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/main.s
.PHONY : main.s
# target to build an object file
mainwindow.o:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/mainwindow.o
.PHONY : mainwindow.o
# target to preprocess a source file
mainwindow.i:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/mainwindow.i
.PHONY : mainwindow.i
# target to generate assembly for a file
mainwindow.s:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/mainwindow.s
.PHONY : mainwindow.s
# target to build an object file
plasma-mediacenter_automoc.o:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/plasma-mediacenter_automoc.o
.PHONY : plasma-mediacenter_automoc.o
# target to preprocess a source file
plasma-mediacenter_automoc.i:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/plasma-mediacenter_automoc.i
.PHONY : plasma-mediacenter_automoc.i
# target to generate assembly for a file
plasma-mediacenter_automoc.s:
cd /home/akshay/PMC/plasma-mediacenter/build && $(MAKE) -f shells/newshell/CMakeFiles/plasma-mediacenter.dir/build.make shells/newshell/CMakeFiles/plasma-mediacenter.dir/plasma-mediacenter_automoc.s
.PHONY : plasma-mediacenter_automoc.s
# Help Target
help:
@echo "The following are some of the valid targets for this Makefile:"
@echo "... all (the default if no target is provided)"
@echo "... clean"
@echo "... depend"
@echo "... edit_cache"
@echo "... install"
@echo "... install/local"
@echo "... install/strip"
@echo "... list_install_components"
@echo "... plasma-mediacenter"
@echo "... plasma-mediacenter_automoc"
@echo "... rebuild_cache"
@echo "... test"
@echo "... main.o"
@echo "... main.i"
@echo "... main.s"
@echo "... mainwindow.o"
@echo "... mainwindow.i"
@echo "... mainwindow.s"
@echo "... plasma-mediacenter_automoc.o"
@echo "... plasma-mediacenter_automoc.i"
@echo "... plasma-mediacenter_automoc.s"
.PHONY : help
#=============================================================================
# Special targets to cleanup operation of make.
# Special rule to run CMake to check the build system integrity.
# No rule that depends on this can have commands that come from listfiles
# because they might be regenerated.
cmake_check_build_system:
cd /home/akshay/PMC/plasma-mediacenter/build && $(CMAKE_COMMAND) -H$(CMAKE_SOURCE_DIR) -B$(CMAKE_BINARY_DIR) --check-build-system CMakeFiles/Makefile.cmake 0
.PHONY : cmake_check_build_system
| akshayratan/plasmamediacenter | build/shells/newshell/Makefile | Makefile | gpl-2.0 | 10,212 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.