code stringlengths 4 1.01M | language stringclasses 2 values |
|---|---|
package com.carpoolsophia;
import java.util.concurrent.ExecutionException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import butterknife.InjectView;
import butterknife.Views;
import com.carpoolsophia.gcloudApi.model.CarpoolSophiaUser;
import com.carpoolsophia.service.CarpoolSophiaUserService;
import com.carpoolsophia.service.ProfileService;
import com.facebook.AccessToken;
import com.facebook.AccessTokenUtils;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
public class ProfileFragment extends Fragment {
private final static String CLASSNAME = ProfileFragment.class.getSimpleName();
@InjectView(R.id.TestLoadFromFB)
Button testLoadFromFbBtn;
@InjectView(R.id.profile_firstName)
EditText profileFirstName;
@InjectView(R.id.profile_lastName)
EditText profileLastName;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.profile_fragment, container, false);
Views.inject(this, view);
return view;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
final ProfileFragment finalThis = this;
testLoadFromFbBtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.w(ProfileFragment.class.getSimpleName(), "loadFromFB");
CarpoolSophiaUser user;
try {
user = (new LoadUserFromFbTask(finalThis).execute()).get();
if (user != null) {
// Log.w(getClass().getSimpleName(),
// "user loaded: "+ModelToJSONParseAdapter.toJSONParse(user));
profileFirstName.setText(user.getFirstName());
profileLastName.setText(user.getLastName());
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void updateProfileInfo(View btn) {
Log.w(getClass().getSimpleName(), "updateProfileInfo");
}
private class LoadUserFromFbTask extends
AsyncTask<CarpoolSophiaUser, Void, CarpoolSophiaUser> {
private ProfileFragment profileFragment;
public LoadUserFromFbTask(ProfileFragment fragment) {
super();
this.profileFragment = fragment;
}
@SuppressWarnings("serial")
protected CarpoolSophiaUser doInBackground(final CarpoolSophiaUser... users) {
CarpoolSophiaUser user = CarpoolSophiaUserService.get()
.getCurrentCSuser();
AccessToken accessToken = AccessTokenUtils.deserializeToken(user
.getAccessToken());
GraphRequest request = GraphRequest.newMeRequest(accessToken,
new GraphRequest.GraphJSONObjectCallback() {
@Override
public void onCompleted(JSONObject object, GraphResponse response) {
// Log.d(CLASSNAME, "JSONobject: " + object);
// Log.d(CLASSNAME, "GraphResponse #1: " +
// response.getRawResponse());
}
});
GraphResponse response = request.executeAndWait();
Log.d(CLASSNAME, "GraphResponse #2: " + response.getRawResponse());
CarpoolSophiaUser userFromFB = new CarpoolSophiaUser();
try {
userFromFB.setFirstName(response.getJSONObject()
.getString("first_name"));
userFromFB.setLastName(response.getJSONObject().getString("last_name"));
} catch (JSONException e) {
e.printStackTrace();
}
ProfileService.get().refreshCSUser(user, userFromFB);
return user;
}
@Override
protected void onPostExecute(CarpoolSophiaUser result) {
super.onPostExecute(result);
}
}
}
| Java |
//---------------------------------------------------------------------------
// NEOPOP : Emulator as in Dreamland
//
// Copyright (c) 2001-2002 by neopop_uk
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// 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. See also the license.txt file for
// additional informations.
//---------------------------------------------------------------------------
/*
//---------------------------------------------------------------------------
//=========================================================================
TLCS900h_registers_mapCodeB0.h
//=========================================================================
//---------------------------------------------------------------------------
History of changes:
===================
20 JUL 2002 - neopop_uk
=======================================
- Cleaned and tidied up for the source release
//---------------------------------------------------------------------------
*/
((_u8*)&gprBank[0][0]) + BYTE0,((_u8*)&gprBank[0][0]) + BYTE1, //BANK 0
((_u8*)&gprBank[0][0]) + BYTE2, ((_u8*)&gprBank[0][0]) + BYTE3,
((_u8*)&gprBank[0][1]) + BYTE0,((_u8*)&gprBank[0][1]) + BYTE1,
((_u8*)&gprBank[0][1]) + BYTE2, ((_u8*)&gprBank[0][1]) + BYTE3,
((_u8*)&gprBank[0][2]) + BYTE0,((_u8*)&gprBank[0][2]) + BYTE1,
((_u8*)&gprBank[0][2]) + BYTE2, ((_u8*)&gprBank[0][2]) + BYTE3,
((_u8*)&gprBank[0][3]) + BYTE0,((_u8*)&gprBank[0][3]) + BYTE1,
((_u8*)&gprBank[0][3]) + BYTE2, ((_u8*)&gprBank[0][3]) + BYTE3,
((_u8*)&gprBank[1][0]) + BYTE0,((_u8*)&gprBank[1][0]) + BYTE1, //BANK 1
((_u8*)&gprBank[1][0]) + BYTE2, ((_u8*)&gprBank[1][0]) + BYTE3,
((_u8*)&gprBank[1][1]) + BYTE0,((_u8*)&gprBank[1][1]) + BYTE1,
((_u8*)&gprBank[1][1]) + BYTE2, ((_u8*)&gprBank[1][1]) + BYTE3,
((_u8*)&gprBank[1][2]) + BYTE0,((_u8*)&gprBank[1][2]) + BYTE1,
((_u8*)&gprBank[1][2]) + BYTE2, ((_u8*)&gprBank[1][2]) + BYTE3,
((_u8*)&gprBank[1][3]) + BYTE0,((_u8*)&gprBank[1][3]) + BYTE1,
((_u8*)&gprBank[1][3]) + BYTE2, ((_u8*)&gprBank[1][3]) + BYTE3,
((_u8*)&gprBank[2][0]) + BYTE0,((_u8*)&gprBank[2][0]) + BYTE1, //BANK 2
((_u8*)&gprBank[2][0]) + BYTE2, ((_u8*)&gprBank[2][0]) + BYTE3,
((_u8*)&gprBank[2][1]) + BYTE0,((_u8*)&gprBank[2][1]) + BYTE1,
((_u8*)&gprBank[2][1]) + BYTE2, ((_u8*)&gprBank[2][1]) + BYTE3,
((_u8*)&gprBank[2][2]) + BYTE0,((_u8*)&gprBank[2][2]) + BYTE1,
((_u8*)&gprBank[2][2]) + BYTE2, ((_u8*)&gprBank[2][2]) + BYTE3,
((_u8*)&gprBank[2][3]) + BYTE0,((_u8*)&gprBank[2][3]) + BYTE1,
((_u8*)&gprBank[2][3]) + BYTE2, ((_u8*)&gprBank[2][3]) + BYTE3,
((_u8*)&gprBank[3][0]) + BYTE0,((_u8*)&gprBank[3][0]) + BYTE1, //BANK 3
((_u8*)&gprBank[3][0]) + BYTE2, ((_u8*)&gprBank[3][0]) + BYTE3,
((_u8*)&gprBank[3][1]) + BYTE0,((_u8*)&gprBank[3][1]) + BYTE1,
((_u8*)&gprBank[3][1]) + BYTE2, ((_u8*)&gprBank[3][1]) + BYTE3,
((_u8*)&gprBank[3][2]) + BYTE0,((_u8*)&gprBank[3][2]) + BYTE1,
((_u8*)&gprBank[3][2]) + BYTE2, ((_u8*)&gprBank[3][2]) + BYTE3,
((_u8*)&gprBank[3][3]) + BYTE0,((_u8*)&gprBank[3][3]) + BYTE1,
((_u8*)&gprBank[3][3]) + BYTE2, ((_u8*)&gprBank[3][3]) + BYTE3,
(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,(_u8*)&rErr,
//Previous Bank
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
(_u8*)&rErr,(_u8*)&rErr,
//Current Bank
((_u8*)&gprBank[0][0]) + BYTE0,((_u8*)&gprBank[0][0]) + BYTE1,
((_u8*)&gprBank[0][0]) + BYTE2, ((_u8*)&gprBank[0][0]) + BYTE3,
((_u8*)&gprBank[0][1]) + BYTE0,((_u8*)&gprBank[0][1]) + BYTE1,
((_u8*)&gprBank[0][1]) + BYTE2, ((_u8*)&gprBank[0][1]) + BYTE3,
((_u8*)&gprBank[0][2]) + BYTE0,((_u8*)&gprBank[0][2]) + BYTE1,
((_u8*)&gprBank[0][2]) + BYTE2, ((_u8*)&gprBank[0][2]) + BYTE3,
((_u8*)&gprBank[0][3]) + BYTE0,((_u8*)&gprBank[0][3]) + BYTE1,
((_u8*)&gprBank[0][3]) + BYTE2, ((_u8*)&gprBank[0][3]) + BYTE3,
((_u8*)&gpr[0]) + BYTE0, ((_u8*)&gpr[0]) + BYTE1,
((_u8*)&gpr[0]) + BYTE2, ((_u8*)&gpr[0]) + BYTE3,
((_u8*)&gpr[1]) + BYTE0, ((_u8*)&gpr[1]) + BYTE1,
((_u8*)&gpr[1]) + BYTE2, ((_u8*)&gpr[1]) + BYTE3,
((_u8*)&gpr[2]) + BYTE0, ((_u8*)&gpr[2]) + BYTE1,
((_u8*)&gpr[2]) + BYTE2, ((_u8*)&gpr[2]) + BYTE3,
((_u8*)&gpr[3]) + BYTE0, ((_u8*)&gpr[3]) + BYTE1,
((_u8*)&gpr[3]) + BYTE2, ((_u8*)&gpr[3]) + BYTE3
//=============================================================================
| Java |
<!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"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.11"/>
<title>ShipCAD: ShipCADlib/subdivbase.cpp File Reference</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="dynsections.js"></script>
<link href="search/search.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="search/searchdata.js"></script>
<script type="text/javascript" src="search/search.js"></script>
<script type="text/javascript">
$(document).ready(function() { init_search(); });
</script>
<link href="doxygen.css" rel="stylesheet" type="text/css" />
</head>
<body>
<div id="top"><!-- do not remove this div, it is closed by doxygen! -->
<div id="titlearea">
<table cellspacing="0" cellpadding="0">
<tbody>
<tr style="height: 56px;">
<td id="projectalign" style="padding-left: 0.5em;">
<div id="projectname">ShipCAD
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- end header part -->
<!-- Generated by Doxygen 1.8.11 -->
<script type="text/javascript">
var searchBox = new SearchBox("searchBox", "search",false,'Search');
</script>
<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>Classes</span></a></li>
<li class="current"><a href="files.html"><span>Files</span></a></li>
<li>
<div id="MSearchBox" class="MSearchBoxInactive">
<span class="left">
<img id="MSearchSelect" src="search/mag_sel.png"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
alt=""/>
<input type="text" id="MSearchField" value="Search" accesskey="S"
onfocus="searchBox.OnSearchFieldFocus(true)"
onblur="searchBox.OnSearchFieldFocus(false)"
onkeyup="searchBox.OnSearchFieldChange(event)"/>
</span><span class="right">
<a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a>
</span>
</div>
</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>File Members</span></a></li>
</ul>
</div>
<!-- window showing the filter options -->
<div id="MSearchSelectWindow"
onmouseover="return searchBox.OnSearchSelectShow()"
onmouseout="return searchBox.OnSearchSelectHide()"
onkeydown="return searchBox.OnSearchSelectKey(event)">
</div>
<!-- iframe showing the search results (closed by default) -->
<div id="MSearchResultsWindow">
<iframe src="javascript:void(0)" frameborder="0"
name="MSearchResults" id="MSearchResults">
</iframe>
</div>
<div id="nav-path" class="navpath">
<ul>
<li class="navelem"><a class="el" href="dir_f0b6ef187c5b1483641b038f81654ac4.html">ShipCADlib</a></li> </ul>
</div>
</div><!-- top -->
<div class="header">
<div class="summary">
<a href="#func-members">Functions</a> </div>
<div class="headertitle">
<div class="title">subdivbase.cpp File Reference</div> </div>
</div><!--header-->
<div class="contents">
<div class="textblock"><code>#include <iostream></code><br />
<code>#include "<a class="el" href="subdivbase_8h_source.html">subdivbase.h</a>"</code><br />
<code>#include "<a class="el" href="subdivsurface_8h_source.html">subdivsurface.h</a>"</code><br />
</div>
<p><a href="subdivbase_8cpp_source.html">Go to the source code of this file.</a></p>
<table class="memberdecls">
<tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="func-members"></a>
Functions</h2></td></tr>
<tr class="memitem:a84a51d41cc05085431b75e5148141ca9"><td class="memItemLeft" align="right" valign="top">ostream & </td><td class="memItemRight" valign="bottom"><a class="el" href="subdivbase_8cpp.html#a84a51d41cc05085431b75e5148141ca9">operator<<</a> (ostream &os, const <a class="el" href="classShipCAD_1_1SubdivisionBase.html">ShipCAD::SubdivisionBase</a> &base)</td></tr>
<tr class="separator:a84a51d41cc05085431b75e5148141ca9"><td class="memSeparator" colspan="2"> </td></tr>
</table>
<h2 class="groupheader">Function Documentation</h2>
<a class="anchor" id="a84a51d41cc05085431b75e5148141ca9"></a>
<div class="memitem">
<div class="memproto">
<table class="memname">
<tr>
<td class="memname">ostream& operator<< </td>
<td>(</td>
<td class="paramtype">ostream & </td>
<td class="paramname"><em>os</em>, </td>
</tr>
<tr>
<td class="paramkey"></td>
<td></td>
<td class="paramtype">const <a class="el" href="classShipCAD_1_1SubdivisionBase.html">ShipCAD::SubdivisionBase</a> & </td>
<td class="paramname"><em>base</em> </td>
</tr>
<tr>
<td></td>
<td>)</td>
<td></td><td></td>
</tr>
</table>
</div><div class="memdoc">
<p>Definition at line <a class="el" href="subdivbase_8cpp_source.html#l00062">62</a> of file <a class="el" href="subdivbase_8cpp_source.html">subdivbase.cpp</a>.</p>
</div>
</div>
</div><!-- contents -->
<!-- start footer part -->
<hr class="footer"/><address class="footer"><small>
Generated on Sun Feb 25 2018 15:36:00 for ShipCAD by  <a href="http://www.doxygen.org/index.html">
<img class="footer" src="doxygen.png" alt="doxygen"/>
</a> 1.8.11
</small></address>
</body>
</html>
| Java |
/*
* fs/fs-writeback.c
*
* Copyright (C) 2002, Linus Torvalds.
*
* Contains all the functions related to writing back and waiting
* upon dirty inodes against superblocks, and writing back dirty
* pages against inodes. ie: data writeback. Writeout of the
* inode itself is not handled here.
*
* 10Apr2002 Andrew Morton
* Split out of fs/inode.c
* Additions for address_space-based writeback
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/spinlock.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/kthread.h>
#include <linux/freezer.h>
#include <linux/writeback.h>
#include <linux/blkdev.h>
#include <linux/backing-dev.h>
#include <linux/buffer_head.h>
#include <linux/tracepoint.h>
#include <trace/events/vfs.h>
#include "internal.h"
/*
* Passed into wb_writeback(), essentially a subset of writeback_control
*/
struct wb_writeback_work {
long nr_pages;
struct super_block *sb;
unsigned long *older_than_this;
enum writeback_sync_modes sync_mode;
unsigned int tagged_writepages:1;
unsigned int for_kupdate:1;
unsigned int range_cyclic:1;
unsigned int for_background:1;
enum wb_reason reason; /* why was writeback initiated? */
struct list_head list; /* pending work list */
struct completion *done; /* set if the caller waits */
};
/*
* Include the creation of the trace points after defining the
* wb_writeback_work structure so that the definition remains local to this
* file.
*/
#define CREATE_TRACE_POINTS
#include <trace/events/writeback.h>
/*
* We don't actually have pdflush, but this one is exported though /proc...
*/
int nr_pdflush_threads;
/**
* writeback_in_progress - determine whether there is writeback in progress
* @bdi: the device's backing_dev_info structure.
*
* Determine whether there is writeback waiting to be handled against a
* backing device.
*/
int writeback_in_progress(struct backing_dev_info *bdi)
{
return test_bit(BDI_writeback_running, &bdi->state);
}
static inline struct backing_dev_info *inode_to_bdi(struct inode *inode)
{
struct super_block *sb = inode->i_sb;
if (strcmp(sb->s_type->name, "bdev") == 0)
return inode->i_mapping->backing_dev_info;
return sb->s_bdi;
}
static inline struct inode *wb_inode(struct list_head *head)
{
return list_entry(head, struct inode, i_wb_list);
}
/* Wakeup flusher thread or forker thread to fork it. Requires bdi->wb_lock. */
static void bdi_wakeup_flusher(struct backing_dev_info *bdi)
{
if (bdi->wb.task) {
wake_up_process(bdi->wb.task);
} else {
/*
* The bdi thread isn't there, wake up the forker thread which
* will create and run it.
*/
wake_up_process(default_backing_dev_info.wb.task);
}
}
static void bdi_queue_work(struct backing_dev_info *bdi,
struct wb_writeback_work *work)
{
trace_writeback_queue(bdi, work);
spin_lock_bh(&bdi->wb_lock);
list_add_tail(&work->list, &bdi->work_list);
if (!bdi->wb.task)
trace_writeback_nothread(bdi, work);
bdi_wakeup_flusher(bdi);
spin_unlock_bh(&bdi->wb_lock);
}
static void
__bdi_start_writeback(struct backing_dev_info *bdi, long nr_pages,
bool range_cyclic, enum wb_reason reason)
{
struct wb_writeback_work *work;
/*
* This is WB_SYNC_NONE writeback, so if allocation fails just
* wakeup the thread for old dirty data writeback
*/
work = kzalloc(sizeof(*work), GFP_ATOMIC);
if (!work) {
if (bdi->wb.task) {
trace_writeback_nowork(bdi);
wake_up_process(bdi->wb.task);
}
return;
}
work->sync_mode = WB_SYNC_NONE;
work->nr_pages = nr_pages;
work->range_cyclic = range_cyclic;
work->reason = reason;
bdi_queue_work(bdi, work);
}
/**
* bdi_start_writeback - start writeback
* @bdi: the backing device to write from
* @nr_pages: the number of pages to write
* @reason: reason why some writeback work was initiated
*
* Description:
* This does WB_SYNC_NONE opportunistic writeback. The IO is only
* started when this function returns, we make no guarantees on
* completion. Caller need not hold sb s_umount semaphore.
*
*/
void bdi_start_writeback(struct backing_dev_info *bdi, long nr_pages,
enum wb_reason reason)
{
__bdi_start_writeback(bdi, nr_pages, true, reason);
}
/**
* bdi_start_background_writeback - start background writeback
* @bdi: the backing device to write from
*
* Description:
* This makes sure WB_SYNC_NONE background writeback happens. When
* this function returns, it is only guaranteed that for given BDI
* some IO is happening if we are over background dirty threshold.
* Caller need not hold sb s_umount semaphore.
*/
void bdi_start_background_writeback(struct backing_dev_info *bdi)
{
/*
* We just wake up the flusher thread. It will perform background
* writeback as soon as there is no other work to do.
*/
trace_writeback_wake_background(bdi);
spin_lock_bh(&bdi->wb_lock);
bdi_wakeup_flusher(bdi);
spin_unlock_bh(&bdi->wb_lock);
}
/*
* Remove the inode from the writeback list it is on.
*/
void inode_wb_list_del(struct inode *inode)
{
struct backing_dev_info *bdi = inode_to_bdi(inode);
spin_lock(&bdi->wb.list_lock);
list_del_init(&inode->i_wb_list);
spin_unlock(&bdi->wb.list_lock);
}
/*
* Redirty an inode: set its when-it-was dirtied timestamp and move it to the
* furthest end of its superblock's dirty-inode list.
*
* Before stamping the inode's ->dirtied_when, we check to see whether it is
* already the most-recently-dirtied inode on the b_dirty list. If that is
* the case then the inode must have been redirtied while it was being written
* out and we don't reset its dirtied_when.
*/
static void redirty_tail(struct inode *inode, struct bdi_writeback *wb)
{
assert_spin_locked(&wb->list_lock);
if (!list_empty(&wb->b_dirty)) {
struct inode *tail;
tail = wb_inode(wb->b_dirty.next);
if (time_before(inode->dirtied_when, tail->dirtied_when))
inode->dirtied_when = jiffies;
}
list_move(&inode->i_wb_list, &wb->b_dirty);
}
/*
* requeue inode for re-scanning after bdi->b_io list is exhausted.
*/
static void requeue_io(struct inode *inode, struct bdi_writeback *wb)
{
assert_spin_locked(&wb->list_lock);
list_move(&inode->i_wb_list, &wb->b_more_io);
}
static void inode_sync_complete(struct inode *inode)
{
/*
* Prevent speculative execution through
* spin_unlock(&wb->list_lock);
*/
smp_mb();
wake_up_bit(&inode->i_state, __I_SYNC);
}
static bool inode_dirtied_after(struct inode *inode, unsigned long t)
{
bool ret = time_after(inode->dirtied_when, t);
#ifndef CONFIG_64BIT
/*
* For inodes being constantly redirtied, dirtied_when can get stuck.
* It _appears_ to be in the future, but is actually in distant past.
* This test is necessary to prevent such wrapped-around relative times
* from permanently stopping the whole bdi writeback.
*/
ret = ret && time_before_eq(inode->dirtied_when, jiffies);
#endif
return ret;
}
/*
* Move expired dirty inodes from @delaying_queue to @dispatch_queue.
*/
static int move_expired_inodes(struct list_head *delaying_queue,
struct list_head *dispatch_queue,
struct wb_writeback_work *work)
{
LIST_HEAD(tmp);
struct list_head *pos, *node;
struct super_block *sb = NULL;
struct inode *inode;
int do_sb_sort = 0;
int moved = 0;
while (!list_empty(delaying_queue)) {
inode = wb_inode(delaying_queue->prev);
if (work->older_than_this &&
inode_dirtied_after(inode, *work->older_than_this))
break;
if (sb && sb != inode->i_sb)
do_sb_sort = 1;
sb = inode->i_sb;
list_move(&inode->i_wb_list, &tmp);
moved++;
}
/* just one sb in list, splice to dispatch_queue and we're done */
if (!do_sb_sort) {
list_splice(&tmp, dispatch_queue);
goto out;
}
/* Move inodes from one superblock together */
while (!list_empty(&tmp)) {
sb = wb_inode(tmp.prev)->i_sb;
list_for_each_prev_safe(pos, node, &tmp) {
inode = wb_inode(pos);
if (inode->i_sb == sb)
list_move(&inode->i_wb_list, dispatch_queue);
}
}
out:
return moved;
}
/*
* Queue all expired dirty inodes for io, eldest first.
* Before
* newly dirtied b_dirty b_io b_more_io
* =============> gf edc BA
* After
* newly dirtied b_dirty b_io b_more_io
* =============> g fBAedc
* |
* +--> dequeue for IO
*/
static void queue_io(struct bdi_writeback *wb, struct wb_writeback_work *work)
{
int moved;
assert_spin_locked(&wb->list_lock);
list_splice_init(&wb->b_more_io, &wb->b_io);
moved = move_expired_inodes(&wb->b_dirty, &wb->b_io, work);
trace_writeback_queue_io(wb, work, moved);
}
static int write_inode(struct inode *inode, struct writeback_control *wbc)
{
if (inode->i_sb->s_op->write_inode && !is_bad_inode(inode))
return inode->i_sb->s_op->write_inode(inode, wbc);
return 0;
}
/*
* Wait for writeback on an inode to complete.
*/
static void inode_wait_for_writeback(struct inode *inode,
struct bdi_writeback *wb)
{
DEFINE_WAIT_BIT(wq, &inode->i_state, __I_SYNC);
wait_queue_head_t *wqh;
wqh = bit_waitqueue(&inode->i_state, __I_SYNC);
while (inode->i_state & I_SYNC) {
spin_unlock(&inode->i_lock);
spin_unlock(&wb->list_lock);
__wait_on_bit(wqh, &wq, inode_wait, TASK_UNINTERRUPTIBLE);
spin_lock(&wb->list_lock);
spin_lock(&inode->i_lock);
}
}
/*
* Write out an inode's dirty pages. Called under wb->list_lock and
* inode->i_lock. Either the caller has an active reference on the inode or
* the inode has I_WILL_FREE set.
*
* If `wait' is set, wait on the writeout.
*
* The whole writeout design is quite complex and fragile. We want to avoid
* starvation of particular inodes when others are being redirtied, prevent
* livelocks, etc.
*/
static int
writeback_single_inode(struct inode *inode, struct bdi_writeback *wb,
struct writeback_control *wbc)
{
struct address_space *mapping = inode->i_mapping;
long nr_to_write = wbc->nr_to_write;
unsigned dirty;
int ret;
assert_spin_locked(&wb->list_lock);
assert_spin_locked(&inode->i_lock);
if (!atomic_read(&inode->i_count))
WARN_ON(!(inode->i_state & (I_WILL_FREE|I_FREEING)));
else
WARN_ON(inode->i_state & I_WILL_FREE);
if (inode->i_state & I_SYNC) {
/*
* If this inode is locked for writeback and we are not doing
* writeback-for-data-integrity, move it to b_more_io so that
* writeback can proceed with the other inodes on s_io.
*
* We'll have another go at writing back this inode when we
* completed a full scan of b_io.
*/
if (wbc->sync_mode != WB_SYNC_ALL) {
requeue_io(inode, wb);
trace_writeback_single_inode_requeue(inode, wbc,
nr_to_write);
return 0;
}
/*
* It's a data-integrity sync. We must wait.
*/
inode_wait_for_writeback(inode, wb);
}
BUG_ON(inode->i_state & I_SYNC);
/* Set I_SYNC, reset I_DIRTY_PAGES */
inode->i_state |= I_SYNC;
inode->i_state &= ~I_DIRTY_PAGES;
spin_unlock(&inode->i_lock);
spin_unlock(&wb->list_lock);
ret = do_writepages(mapping, wbc);
/*
* Make sure to wait on the data before writing out the metadata.
* This is important for filesystems that modify metadata on data
* I/O completion.
*/
if (wbc->sync_mode == WB_SYNC_ALL) {
int err = filemap_fdatawait(mapping);
if (ret == 0)
ret = err;
}
/*
* Some filesystems may redirty the inode during the writeback
* due to delalloc, clear dirty metadata flags right before
* write_inode()
*/
spin_lock(&inode->i_lock);
dirty = inode->i_state & I_DIRTY;
inode->i_state &= ~(I_DIRTY_SYNC | I_DIRTY_DATASYNC);
spin_unlock(&inode->i_lock);
/* Don't write the inode if only I_DIRTY_PAGES was set */
if (dirty & (I_DIRTY_SYNC | I_DIRTY_DATASYNC)) {
int err = write_inode(inode, wbc);
if (ret == 0)
ret = err;
}
spin_lock(&wb->list_lock);
spin_lock(&inode->i_lock);
inode->i_state &= ~I_SYNC;
if (!(inode->i_state & I_FREEING)) {
/*
* Sync livelock prevention. Each inode is tagged and synced in
* one shot. If still dirty, it will be redirty_tail()'ed below.
* Update the dirty time to prevent enqueue and sync it again.
*/
if ((inode->i_state & I_DIRTY) &&
(wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages))
inode->dirtied_when = jiffies;
if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY)) {
/*
* We didn't write back all the pages. nfs_writepages()
* sometimes bales out without doing anything.
*/
inode->i_state |= I_DIRTY_PAGES;
if (wbc->nr_to_write <= 0) {
/*
* slice used up: queue for next turn
*/
requeue_io(inode, wb);
} else {
/*
* Writeback blocked by something other than
* congestion. Delay the inode for some time to
* avoid spinning on the CPU (100% iowait)
* retrying writeback of the dirty page/inode
* that cannot be performed immediately.
*/
redirty_tail(inode, wb);
}
} else if (inode->i_state & I_DIRTY) {
/*
* Filesystems can dirty the inode during writeback
* operations, such as delayed allocation during
* submission or metadata updates after data IO
* completion.
*/
redirty_tail(inode, wb);
} else {
/*
* The inode is clean. At this point we either have
* a reference to the inode or it's on it's way out.
* No need to add it back to the LRU.
*/
list_del_init(&inode->i_wb_list);
}
}
inode_sync_complete(inode);
trace_writeback_single_inode(inode, wbc, nr_to_write);
return ret;
}
static long writeback_chunk_size(struct backing_dev_info *bdi,
struct wb_writeback_work *work)
{
long pages;
/*
* WB_SYNC_ALL mode does livelock avoidance by syncing dirty
* inodes/pages in one big loop. Setting wbc.nr_to_write=LONG_MAX
* here avoids calling into writeback_inodes_wb() more than once.
*
* The intended call sequence for WB_SYNC_ALL writeback is:
*
* wb_writeback()
* writeback_sb_inodes() <== called only once
* write_cache_pages() <== called once for each inode
* (quickly) tag currently dirty pages
* (maybe slowly) sync all tagged pages
*/
if (work->sync_mode == WB_SYNC_ALL || work->tagged_writepages)
pages = LONG_MAX;
else {
pages = min(bdi->avg_write_bandwidth / 2,
global_dirty_limit / DIRTY_SCOPE);
pages = min(pages, work->nr_pages);
pages = round_down(pages + MIN_WRITEBACK_PAGES,
MIN_WRITEBACK_PAGES);
}
return pages;
}
/*
* Write a portion of b_io inodes which belong to @sb.
*
* If @only_this_sb is true, then find and write all such
* inodes. Otherwise write only ones which go sequentially
* in reverse order.
*
* Return the number of pages and/or inodes written.
*/
static long writeback_sb_inodes(struct super_block *sb,
struct bdi_writeback *wb,
struct wb_writeback_work *work)
{
struct writeback_control wbc = {
.sync_mode = work->sync_mode,
.tagged_writepages = work->tagged_writepages,
.for_kupdate = work->for_kupdate,
.for_background = work->for_background,
.range_cyclic = work->range_cyclic,
.range_start = 0,
.range_end = LLONG_MAX,
};
unsigned long start_time = jiffies;
long write_chunk;
long wrote = 0; /* count both pages and inodes */
while (!list_empty(&wb->b_io)) {
struct inode *inode = wb_inode(wb->b_io.prev);
if (inode->i_sb != sb) {
if (work->sb) {
/*
* We only want to write back data for this
* superblock, move all inodes not belonging
* to it back onto the dirty list.
*/
redirty_tail(inode, wb);
continue;
}
/*
* The inode belongs to a different superblock.
* Bounce back to the caller to unpin this and
* pin the next superblock.
*/
break;
}
/*
* Don't bother with new inodes or inodes beeing freed, first
* kind does not need peridic writeout yet, and for the latter
* kind writeout is handled by the freer.
*/
spin_lock(&inode->i_lock);
if (inode->i_state & (I_NEW | I_FREEING | I_WILL_FREE)) {
spin_unlock(&inode->i_lock);
redirty_tail(inode, wb);
continue;
}
__iget(inode);
write_chunk = writeback_chunk_size(wb->bdi, work);
wbc.nr_to_write = write_chunk;
wbc.pages_skipped = 0;
writeback_single_inode(inode, wb, &wbc);
work->nr_pages -= write_chunk - wbc.nr_to_write;
wrote += write_chunk - wbc.nr_to_write;
if (!(inode->i_state & I_DIRTY))
wrote++;
if (wbc.pages_skipped) {
/*
* writeback is not making progress due to locked
* buffers. Skip this inode for now.
*/
redirty_tail(inode, wb);
}
spin_unlock(&inode->i_lock);
spin_unlock(&wb->list_lock);
iput(inode);
cond_resched();
spin_lock(&wb->list_lock);
/*
* bail out to wb_writeback() often enough to check
* background threshold and other termination conditions.
*/
if (wrote) {
if (time_is_before_jiffies(start_time + HZ / 10UL))
break;
if (work->nr_pages <= 0)
break;
}
}
return wrote;
}
static long __writeback_inodes_wb(struct bdi_writeback *wb,
struct wb_writeback_work *work)
{
unsigned long start_time = jiffies;
long wrote = 0;
while (!list_empty(&wb->b_io)) {
struct inode *inode = wb_inode(wb->b_io.prev);
struct super_block *sb = inode->i_sb;
if (!grab_super_passive(sb)) {
/*
* grab_super_passive() may fail consistently due to
* s_umount being grabbed by someone else. Don't use
* requeue_io() to avoid busy retrying the inode/sb.
*/
redirty_tail(inode, wb);
continue;
}
wrote += writeback_sb_inodes(sb, wb, work);
drop_super(sb);
/* refer to the same tests at the end of writeback_sb_inodes */
if (wrote) {
if (time_is_before_jiffies(start_time + HZ / 10UL))
break;
if (work->nr_pages <= 0)
break;
}
}
/* Leave any unwritten inodes on b_io */
return wrote;
}
long writeback_inodes_wb(struct bdi_writeback *wb, long nr_pages,
enum wb_reason reason)
{
struct wb_writeback_work work = {
.nr_pages = nr_pages,
.sync_mode = WB_SYNC_NONE,
.range_cyclic = 1,
.reason = reason,
};
spin_lock(&wb->list_lock);
if (list_empty(&wb->b_io))
queue_io(wb, &work);
__writeback_inodes_wb(wb, &work);
spin_unlock(&wb->list_lock);
return nr_pages - work.nr_pages;
}
static bool over_bground_thresh(struct backing_dev_info *bdi)
{
unsigned long background_thresh, dirty_thresh;
global_dirty_limits(&background_thresh, &dirty_thresh);
if (global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS) > background_thresh)
return true;
if (bdi_stat(bdi, BDI_RECLAIMABLE) >
bdi_dirty_limit(bdi, background_thresh))
return true;
return false;
}
/*
* Called under wb->list_lock. If there are multiple wb per bdi,
* only the flusher working on the first wb should do it.
*/
static void wb_update_bandwidth(struct bdi_writeback *wb,
unsigned long start_time)
{
__bdi_update_bandwidth(wb->bdi, 0, 0, 0, 0, 0, start_time);
}
/*
* Explicit flushing or periodic writeback of "old" data.
*
* Define "old": the first time one of an inode's pages is dirtied, we mark the
* dirtying-time in the inode's address_space. So this periodic writeback code
* just walks the superblock inode list, writing back any inodes which are
* older than a specific point in time.
*
* Try to run once per dirty_writeback_interval. But if a writeback event
* takes longer than a dirty_writeback_interval interval, then leave a
* one-second gap.
*
* older_than_this takes precedence over nr_to_write. So we'll only write back
* all dirty pages if they are all attached to "old" mappings.
*/
static long wb_writeback(struct bdi_writeback *wb,
struct wb_writeback_work *work)
{
unsigned long wb_start = jiffies;
long nr_pages = work->nr_pages;
unsigned long oldest_jif;
struct inode *inode;
long progress;
oldest_jif = jiffies;
work->older_than_this = &oldest_jif;
spin_lock(&wb->list_lock);
for (;;) {
/*
* Stop writeback when nr_pages has been consumed
*/
if (work->nr_pages <= 0)
break;
/*
* Background writeout and kupdate-style writeback may
* run forever. Stop them if there is other work to do
* so that e.g. sync can proceed. They'll be restarted
* after the other works are all done.
*/
if ((work->for_background || work->for_kupdate) &&
!list_empty(&wb->bdi->work_list))
break;
/*
* For background writeout, stop when we are below the
* background dirty threshold
*/
if (work->for_background && !over_bground_thresh(wb->bdi))
break;
if (work->for_kupdate) {
oldest_jif = jiffies -
msecs_to_jiffies(dirty_expire_interval * 10);
work->older_than_this = &oldest_jif;
}
trace_writeback_start(wb->bdi, work);
if (list_empty(&wb->b_io))
queue_io(wb, work);
if (work->sb)
progress = writeback_sb_inodes(work->sb, wb, work);
else
progress = __writeback_inodes_wb(wb, work);
trace_writeback_written(wb->bdi, work);
wb_update_bandwidth(wb, wb_start);
/*
* Did we write something? Try for more
*
* Dirty inodes are moved to b_io for writeback in batches.
* The completion of the current batch does not necessarily
* mean the overall work is done. So we keep looping as long
* as made some progress on cleaning pages or inodes.
*/
if (progress)
continue;
/*
* No more inodes for IO, bail
*/
if (list_empty(&wb->b_more_io))
break;
/*
* Nothing written. Wait for some inode to
* become available for writeback. Otherwise
* we'll just busyloop.
*/
if (!list_empty(&wb->b_more_io)) {
trace_writeback_wait(wb->bdi, work);
inode = wb_inode(wb->b_more_io.prev);
spin_lock(&inode->i_lock);
inode_wait_for_writeback(inode, wb);
spin_unlock(&inode->i_lock);
}
}
spin_unlock(&wb->list_lock);
return nr_pages - work->nr_pages;
}
/*
* Return the next wb_writeback_work struct that hasn't been processed yet.
*/
static struct wb_writeback_work *
get_next_work_item(struct backing_dev_info *bdi)
{
struct wb_writeback_work *work = NULL;
spin_lock_bh(&bdi->wb_lock);
if (!list_empty(&bdi->work_list)) {
work = list_entry(bdi->work_list.next,
struct wb_writeback_work, list);
list_del_init(&work->list);
}
spin_unlock_bh(&bdi->wb_lock);
return work;
}
/*
* Add in the number of potentially dirty inodes, because each inode
* write can dirty pagecache in the underlying blockdev.
*/
static unsigned long get_nr_dirty_pages(void)
{
return global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS) +
get_nr_dirty_inodes();
}
static long wb_check_background_flush(struct bdi_writeback *wb)
{
if (over_bground_thresh(wb->bdi)) {
struct wb_writeback_work work = {
.nr_pages = LONG_MAX,
.sync_mode = WB_SYNC_NONE,
.for_background = 1,
.range_cyclic = 1,
.reason = WB_REASON_BACKGROUND,
};
return wb_writeback(wb, &work);
}
return 0;
}
static long wb_check_old_data_flush(struct bdi_writeback *wb)
{
unsigned long expired;
long nr_pages;
/*
* When set to zero, disable periodic writeback
*/
if (!dirty_writeback_interval)
return 0;
expired = wb->last_old_flush +
msecs_to_jiffies(dirty_writeback_interval * 10);
if (time_before(jiffies, expired))
return 0;
wb->last_old_flush = jiffies;
nr_pages = get_nr_dirty_pages();
if (nr_pages) {
struct wb_writeback_work work = {
.nr_pages = nr_pages,
.sync_mode = WB_SYNC_NONE,
.for_kupdate = 1,
.range_cyclic = 1,
.reason = WB_REASON_PERIODIC,
};
return wb_writeback(wb, &work);
}
return 0;
}
/*
* Retrieve work items and do the writeback they describe
*/
long wb_do_writeback(struct bdi_writeback *wb, int force_wait)
{
struct backing_dev_info *bdi = wb->bdi;
struct wb_writeback_work *work;
long wrote = 0;
set_bit(BDI_writeback_running, &wb->bdi->state);
while ((work = get_next_work_item(bdi)) != NULL) {
/*
* Override sync mode, in case we must wait for completion
* because this thread is exiting now.
*/
if (force_wait)
work->sync_mode = WB_SYNC_ALL;
trace_writeback_exec(bdi, work);
wrote += wb_writeback(wb, work);
/*
* Notify the caller of completion if this is a synchronous
* work item, otherwise just free it.
*/
if (work->done)
complete(work->done);
else
kfree(work);
}
/*
* Check for periodic writeback, kupdated() style
*/
wrote += wb_check_old_data_flush(wb);
wrote += wb_check_background_flush(wb);
clear_bit(BDI_writeback_running, &wb->bdi->state);
return wrote;
}
/*
* Handle writeback of dirty data for the device backed by this bdi. Also
* wakes up periodically and does kupdated style flushing.
*/
int bdi_writeback_thread(void *data)
{
struct bdi_writeback *wb = data;
struct backing_dev_info *bdi = wb->bdi;
long pages_written;
current->flags |= PF_SWAPWRITE;
set_freezable();
wb->last_active = jiffies;
/*
* Our parent may run at a different priority, just set us to normal
*/
set_user_nice(current, 0);
trace_writeback_thread_start(bdi);
while (!kthread_should_stop()) {
/*
* Remove own delayed wake-up timer, since we are already awake
* and we'll take care of the preriodic write-back.
*/
del_timer(&wb->wakeup_timer);
pages_written = wb_do_writeback(wb, 0);
trace_writeback_pages_written(pages_written);
if (pages_written)
wb->last_active = jiffies;
set_current_state(TASK_INTERRUPTIBLE);
if (!list_empty(&bdi->work_list) || kthread_should_stop()) {
__set_current_state(TASK_RUNNING);
continue;
}
if (wb_has_dirty_io(wb) && dirty_writeback_interval)
schedule_timeout(msecs_to_jiffies(dirty_writeback_interval * 10));
else {
/*
* We have nothing to do, so can go sleep without any
* timeout and save power. When a work is queued or
* something is made dirty - we will be woken up.
*/
schedule();
}
try_to_freeze();
}
/* Flush any work that raced with us exiting */
if (!list_empty(&bdi->work_list))
wb_do_writeback(wb, 1);
trace_writeback_thread_stop(bdi);
return 0;
}
/*
* Start writeback of `nr_pages' pages. If `nr_pages' is zero, write back
* the whole world.
*/
void wakeup_flusher_threads(long nr_pages, enum wb_reason reason)
{
struct backing_dev_info *bdi;
if (!nr_pages) {
nr_pages = global_page_state(NR_FILE_DIRTY) +
global_page_state(NR_UNSTABLE_NFS);
}
rcu_read_lock();
list_for_each_entry_rcu(bdi, &bdi_list, bdi_list) {
if (!bdi_has_dirty_io(bdi))
continue;
__bdi_start_writeback(bdi, nr_pages, false, reason);
}
rcu_read_unlock();
}
static noinline void block_dump___mark_inode_dirty(struct inode *inode)
{
if (inode->i_ino || strcmp(inode->i_sb->s_id, "bdev")) {
struct dentry *dentry;
const char *name = "?";
dentry = d_find_alias(inode);
if (dentry) {
spin_lock(&dentry->d_lock);
name = (const char *) dentry->d_name.name;
}
printk(KERN_DEBUG
"%s(%d): dirtied inode %lu (%s) on %s\n",
current->comm, task_pid_nr(current), inode->i_ino,
name, inode->i_sb->s_id);
if (dentry) {
spin_unlock(&dentry->d_lock);
dput(dentry);
}
}
}
/**
* __mark_inode_dirty - internal function
* @inode: inode to mark
* @flags: what kind of dirty (i.e. I_DIRTY_SYNC)
* Mark an inode as dirty. Callers should use mark_inode_dirty or
* mark_inode_dirty_sync.
*
* Put the inode on the super block's dirty list.
*
* CAREFUL! We mark it dirty unconditionally, but move it onto the
* dirty list only if it is hashed or if it refers to a blockdev.
* If it was not hashed, it will never be added to the dirty list
* even if it is later hashed, as it will have been marked dirty already.
*
* In short, make sure you hash any inodes _before_ you start marking
* them dirty.
*
* Note that for blockdevs, inode->dirtied_when represents the dirtying time of
* the block-special inode (/dev/hda1) itself. And the ->dirtied_when field of
* the kernel-internal blockdev inode represents the dirtying time of the
* blockdev's pages. This is why for I_DIRTY_PAGES we always use
* page->mapping->host, so the page-dirtying time is recorded in the internal
* blockdev inode.
*/
void __mark_inode_dirty(struct inode *inode, int flags)
{
struct super_block *sb = inode->i_sb;
struct backing_dev_info *bdi = NULL;
/*
* Don't do this for I_DIRTY_PAGES - that doesn't actually
* dirty the inode itself
*/
if (flags & (I_DIRTY_SYNC | I_DIRTY_DATASYNC)) {
if (sb->s_op->dirty_inode)
sb->s_op->dirty_inode(inode, flags);
}
/*
* make sure that changes are seen by all cpus before we test i_state
* -- mikulas
*/
smp_mb();
/* avoid the locking if we can */
if ((inode->i_state & flags) == flags)
return;
trace_dirty_inode(inode, current);
if (unlikely(block_dump))
block_dump___mark_inode_dirty(inode);
spin_lock(&inode->i_lock);
if ((inode->i_state & flags) != flags) {
const int was_dirty = inode->i_state & I_DIRTY;
inode->i_state |= flags;
/*
* If the inode is being synced, just update its dirty state.
* The unlocker will place the inode on the appropriate
* superblock list, based upon its state.
*/
if (inode->i_state & I_SYNC)
goto out_unlock_inode;
/*
* Only add valid (hashed) inodes to the superblock's
* dirty list. Add blockdev inodes as well.
*/
if (!S_ISBLK(inode->i_mode)) {
if (inode_unhashed(inode))
goto out_unlock_inode;
}
if (inode->i_state & I_FREEING)
goto out_unlock_inode;
/*
* If the inode was already on b_dirty/b_io/b_more_io, don't
* reposition it (that would break b_dirty time-ordering).
*/
if (!was_dirty) {
bool wakeup_bdi = false;
bdi = inode_to_bdi(inode);
if (bdi_cap_writeback_dirty(bdi)) {
WARN(!test_bit(BDI_registered, &bdi->state),
"bdi-%s not registered\n", bdi->name);
/*
* If this is the first dirty inode for this
* bdi, we have to wake-up the corresponding
* bdi thread to make sure background
* write-back happens later.
*/
if (!wb_has_dirty_io(&bdi->wb))
wakeup_bdi = true;
}
spin_unlock(&inode->i_lock);
spin_lock(&bdi->wb.list_lock);
inode->dirtied_when = jiffies;
list_move(&inode->i_wb_list, &bdi->wb.b_dirty);
spin_unlock(&bdi->wb.list_lock);
if (wakeup_bdi)
bdi_wakeup_thread_delayed(bdi);
return;
}
}
out_unlock_inode:
spin_unlock(&inode->i_lock);
}
EXPORT_SYMBOL(__mark_inode_dirty);
/*
* Write out a superblock's list of dirty inodes. A wait will be performed
* upon no inodes, all inodes or the final one, depending upon sync_mode.
*
* If older_than_this is non-NULL, then only write out inodes which
* had their first dirtying at a time earlier than *older_than_this.
*
* If `bdi' is non-zero then we're being asked to writeback a specific queue.
* This function assumes that the blockdev superblock's inodes are backed by
* a variety of queues, so all inodes are searched. For other superblocks,
* assume that all inodes are backed by the same queue.
*
* The inodes to be written are parked on bdi->b_io. They are moved back onto
* bdi->b_dirty as they are selected for writing. This way, none can be missed
* on the writer throttling path, and we get decent balancing between many
* throttled threads: we don't want them all piling up on inode_sync_wait.
*/
static void wait_sb_inodes(struct super_block *sb)
{
struct inode *inode, *old_inode = NULL;
/*
* We need to be protected against the filesystem going from
* r/o to r/w or vice versa.
*/
WARN_ON(!rwsem_is_locked(&sb->s_umount));
spin_lock(&inode_sb_list_lock);
/*
* Data integrity sync. Must wait for all pages under writeback,
* because there may have been pages dirtied before our sync
* call, but which had writeout started before we write it out.
* In which case, the inode may not be on the dirty list, but
* we still have to wait for that writeout.
*/
list_for_each_entry(inode, &sb->s_inodes, i_sb_list) {
struct address_space *mapping = inode->i_mapping;
spin_lock(&inode->i_lock);
if ((inode->i_state & (I_FREEING|I_WILL_FREE|I_NEW)) ||
(mapping->nrpages == 0)) {
spin_unlock(&inode->i_lock);
continue;
}
__iget(inode);
spin_unlock(&inode->i_lock);
spin_unlock(&inode_sb_list_lock);
/*
* We hold a reference to 'inode' so it couldn't have been
* removed from s_inodes list while we dropped the
* inode_sb_list_lock. We cannot iput the inode now as we can
* be holding the last reference and we cannot iput it under
* inode_sb_list_lock. So we keep the reference and iput it
* later.
*/
iput(old_inode);
old_inode = inode;
filemap_fdatawait(mapping);
cond_resched();
spin_lock(&inode_sb_list_lock);
}
spin_unlock(&inode_sb_list_lock);
iput(old_inode);
}
/**
* writeback_inodes_sb_nr - writeback dirty inodes from given super_block
* @sb: the superblock
* @nr: the number of pages to write
* @reason: reason why some writeback work initiated
*
* Start writeback on some inodes on this super_block. No guarantees are made
* on how many (if any) will be written, and this function does not wait
* for IO completion of submitted IO.
*/
void writeback_inodes_sb_nr(struct super_block *sb,
unsigned long nr,
enum wb_reason reason)
{
DECLARE_COMPLETION_ONSTACK(done);
struct wb_writeback_work work = {
.sb = sb,
.sync_mode = WB_SYNC_NONE,
.tagged_writepages = 1,
.done = &done,
.nr_pages = nr,
.reason = reason,
};
WARN_ON(!rwsem_is_locked(&sb->s_umount));
bdi_queue_work(sb->s_bdi, &work);
wait_for_completion(&done);
}
EXPORT_SYMBOL(writeback_inodes_sb_nr);
/**
* writeback_inodes_sb - writeback dirty inodes from given super_block
* @sb: the superblock
* @reason: reason why some writeback work was initiated
*
* Start writeback on some inodes on this super_block. No guarantees are made
* on how many (if any) will be written, and this function does not wait
* for IO completion of submitted IO.
*/
void writeback_inodes_sb(struct super_block *sb, enum wb_reason reason)
{
return writeback_inodes_sb_nr(sb, get_nr_dirty_pages(), reason);
}
EXPORT_SYMBOL(writeback_inodes_sb);
/**
* writeback_inodes_sb_if_idle - start writeback if none underway
* @sb: the superblock
* @reason: reason why some writeback work was initiated
*
* Invoke writeback_inodes_sb if no writeback is currently underway.
* Returns 1 if writeback was started, 0 if not.
*/
int writeback_inodes_sb_if_idle(struct super_block *sb, enum wb_reason reason)
{
if (!writeback_in_progress(sb->s_bdi)) {
down_read(&sb->s_umount);
writeback_inodes_sb(sb, reason);
up_read(&sb->s_umount);
return 1;
} else
return 0;
}
EXPORT_SYMBOL(writeback_inodes_sb_if_idle);
/**
* writeback_inodes_sb_if_idle - start writeback if none underway
* @sb: the superblock
* @nr: the number of pages to write
* @reason: reason why some writeback work was initiated
*
* Invoke writeback_inodes_sb if no writeback is currently underway.
* Returns 1 if writeback was started, 0 if not.
*/
int writeback_inodes_sb_nr_if_idle(struct super_block *sb,
unsigned long nr,
enum wb_reason reason)
{
if (!writeback_in_progress(sb->s_bdi)) {
down_read(&sb->s_umount);
writeback_inodes_sb_nr(sb, nr, reason);
up_read(&sb->s_umount);
return 1;
} else
return 0;
}
EXPORT_SYMBOL(writeback_inodes_sb_nr_if_idle);
/**
* sync_inodes_sb - sync sb inode pages
* @sb: the superblock
*
* This function writes and waits on any dirty inode belonging to this
* super_block.
*/
void sync_inodes_sb(struct super_block *sb)
{
DECLARE_COMPLETION_ONSTACK(done);
struct wb_writeback_work work = {
.sb = sb,
.sync_mode = WB_SYNC_ALL,
.nr_pages = LONG_MAX,
.range_cyclic = 0,
.done = &done,
.reason = WB_REASON_SYNC,
};
WARN_ON(!rwsem_is_locked(&sb->s_umount));
bdi_queue_work(sb->s_bdi, &work);
wait_for_completion(&done);
wait_sb_inodes(sb);
}
EXPORT_SYMBOL(sync_inodes_sb);
/**
* write_inode_now - write an inode to disk
* @inode: inode to write to disk
* @sync: whether the write should be synchronous or not
*
* This function commits an inode to disk immediately if it is dirty. This is
* primarily needed by knfsd.
*
* The caller must either have a ref on the inode or must have set I_WILL_FREE.
*/
int write_inode_now(struct inode *inode, int sync)
{
struct bdi_writeback *wb = &inode_to_bdi(inode)->wb;
int ret;
struct writeback_control wbc = {
.nr_to_write = LONG_MAX,
.sync_mode = sync ? WB_SYNC_ALL : WB_SYNC_NONE,
.range_start = 0,
.range_end = LLONG_MAX,
};
if (!mapping_cap_writeback_dirty(inode->i_mapping))
wbc.nr_to_write = 0;
might_sleep();
spin_lock(&wb->list_lock);
spin_lock(&inode->i_lock);
ret = writeback_single_inode(inode, wb, &wbc);
spin_unlock(&inode->i_lock);
spin_unlock(&wb->list_lock);
if (sync)
inode_sync_wait(inode);
return ret;
}
EXPORT_SYMBOL(write_inode_now);
/**
* sync_inode - write an inode and its pages to disk.
* @inode: the inode to sync
* @wbc: controls the writeback mode
*
* sync_inode() will write an inode and its pages to disk. It will also
* correctly update the inode on its superblock's dirty inode lists and will
* update inode->i_state.
*
* The caller must have a ref on the inode.
*/
int sync_inode(struct inode *inode, struct writeback_control *wbc)
{
struct bdi_writeback *wb = &inode_to_bdi(inode)->wb;
int ret;
spin_lock(&wb->list_lock);
spin_lock(&inode->i_lock);
ret = writeback_single_inode(inode, wb, wbc);
spin_unlock(&inode->i_lock);
spin_unlock(&wb->list_lock);
return ret;
}
EXPORT_SYMBOL(sync_inode);
/**
* sync_inode_metadata - write an inode to disk
* @inode: the inode to sync
* @wait: wait for I/O to complete.
*
* Write an inode to disk and adjust its dirty state after completion.
*
* Note: only writes the actual inode, no associated data or other metadata.
*/
int sync_inode_metadata(struct inode *inode, int wait)
{
struct writeback_control wbc = {
.sync_mode = wait ? WB_SYNC_ALL : WB_SYNC_NONE,
.nr_to_write = 0, /* metadata-only */
};
return sync_inode(inode, &wbc);
}
EXPORT_SYMBOL(sync_inode_metadata);
| Java |
/*
* Copyright (C) 2011-2012 ArkCORE2 <http://www.arkania.net/>
* Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/>
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptPCH.h"
#include "ScriptedEscortAI.h"
#include "violet_hold.h"
#define GOSSIP_START_EVENT "Get your people to safety, we'll keep the Blue Dragonflight's forces at bay."
#define GOSSIP_ITEM_1 "Activate the crystals when we get in trouble, right"
#define GOSSIP_I_WANT_IN "I'm not fighting, so send me in now!"
#define SPAWN_TIME 20000
enum PortalCreatures
{
CREATURE_AZURE_INVADER_1 = 30661,
CREATURE_AZURE_INVADER_2 = 30961,
CREATURE_AZURE_SPELLBREAKER_1 = 30662,
CREATURE_AZURE_SPELLBREAKER_2 = 30962,
CREATURE_AZURE_BINDER_1 = 30663,
CREATURE_AZURE_BINDER_2 = 30918,
CREATURE_AZURE_MAGE_SLAYER_1 = 30664,
CREATURE_AZURE_MAGE_SLAYER_2 = 30963,
CREATURE_AZURE_CAPTAIN = 30666,
CREATURE_AZURE_SORCEROR = 30667,
CREATURE_AZURE_RAIDER = 30668,
CREATURE_AZURE_STALKER = 32191
};
enum AzureInvaderSpells
{
SPELL_CLEAVE = 15496,
SPELL_IMPALE = 58459,
H_SPELL_IMPALE = 59256,
SPELL_BRUTAL_STRIKE = 58460,
SPELL_SUNDER_ARMOR = 58461
};
enum AzureSellbreakerSpells
{
SPELL_ARCANE_BLAST = 58462,
H_SPELL_ARCANE_BLAST = 59257,
SPELL_SLOW = 25603,
SPELL_CHAINS_OF_ICE = 58464,
SPELL_CONE_OF_COLD = 58463,
H_SPELL_CONE_OF_COLD = 59258
};
enum AzureBinderSpells
{
SPELL_ARCANE_BARRAGE = 58456,
H_SPELL_ARCANE_BARRAGE = 59248,
SPELL_ARCANE_EXPLOSION = 58455,
H_SPELL_ARCANE_EXPLOSION = 59245,
SPELL_FROST_NOVA = 58458,
H_SPELL_FROST_NOVA = 59253,
SPELL_FROSTBOLT = 58457,
H_SPELL_FROSTBOLT = 59251,
};
enum AzureMageSlayerSpells
{
SPELL_ARCANE_EMPOWERMENT = 58469,
SPELL_SPELL_LOCK = 30849
};
enum AzureCaptainSpells
{
SPELL_MORTAL_STRIKE = 32736,
SPELL_WHIRLWIND_OF_STEEL = 41057
};
enum AzureSorcerorSpells
{
SPELL_ARCANE_STREAM = 60181,
H_SPELL_ARCANE_STREAM = 60204,
SPELL_MANA_DETONATION = 60182,
H_SPELL_MANA_DETONATION = 60205
};
enum AzureRaiderSpells
{
SPELL_CONCUSSION_BLOW = 52719,
SPELL_MAGIC_REFLECTION = 60158
};
enum AzureStalkerSpells
{
SPELL_BACKSTAB = 58471,
SPELL_TACTICAL_BLINK = 58470
};
enum AzureSaboteurSpells
{
SABOTEUR_SHIELD_DISRUPTION = 58291,
SABOTEUR_SHIELD_EFFECT = 45775
};
enum TrashDoorSpell
{
SPELL_DESTROY_DOOR_SEAL = 58040
};
enum Spells
{
SPELL_PORTAL_CHANNEL = 58012,
SPELL_CRYSTALL_ACTIVATION = 57804
};
enum eSinclari
{
SAY_SINCLARI_1 = -1608045
};
float FirstPortalWPs [6][3] =
{
{1877.670288f, 842.280273f, 43.333591f},
{1877.338867f, 834.615356f, 38.762287f},
{1872.161011f, 823.854309f, 38.645401f},
{1864.860474f, 815.787170f, 38.784843f},
{1858.953735f, 810.048950f, 44.008759f},
{1843.707153f, 805.807739f, 44.135197f}
//{1825.736084f, 807.305847f, 44.363785f}
};
float SecondPortalFirstWPs [9][3] =
{
{1902.561401f, 853.334656f, 47.106117f},
{1895.486084f, 855.376404f, 44.334591f},
{1882.805176f, 854.993286f, 43.333591f},
{1877.670288f, 842.280273f, 43.333591f},
{1877.338867f, 834.615356f, 38.762287f},
{1872.161011f, 823.854309f, 38.645401f},
{1864.860474f, 815.787170f, 38.784843f},
{1858.953735f, 810.048950f, 44.008759f},
{1843.707153f, 805.807739f, 44.135197f}
//{1825.736084f, 807.305847f, 44.363785f}
};
float SecondPortalSecondWPs [8][3] =
{
{1929.392212f, 837.614990f, 47.136166f},
{1928.290649f, 824.750427f, 45.474411f},
{1915.544922f, 826.919373f, 38.642811f},
{1900.933960f, 818.855652f, 38.801647f},
{1886.810547f, 813.536621f, 38.490490f},
{1869.079712f, 808.701538f, 38.689003f},
{1860.843384f, 806.645020f, 44.008789f},
{1843.707153f, 805.807739f, 44.135197f}
//{1825.736084f, 807.305847f, 44.363785f}
};
float ThirdPortalWPs [8][3] =
{
{1934.049438f, 815.778503f, 52.408699f},
{1928.290649f, 824.750427f, 45.474411f},
{1915.544922f, 826.919373f, 38.642811f},
{1900.933960f, 818.855652f, 38.801647f},
{1886.810547f, 813.536621f, 38.490490f},
{1869.079712f, 808.701538f, 38.689003f},
{1860.843384f, 806.645020f, 44.008789f},
{1843.707153f, 805.807739f, 44.135197f}
//{1825.736084f, 807.305847f, 44.363785f}
};
float FourthPortalWPs [9][3] =
{
{1921.658447f, 761.657043f, 50.866741f},
{1910.559814f, 755.780457f, 47.701447f},
{1896.664673f, 752.920898f, 47.667004f},
{1887.398804f, 763.633240f, 47.666851f},
{1879.020386f, 775.396973f, 38.705990f},
{1872.439087f, 782.568604f, 38.808292f},
{1863.573364f, 791.173584f, 38.743660f},
{1857.811890f, 796.765564f, 43.950329f},
{1845.577759f, 800.681152f, 44.104248f}
//{1827.100342f, 801.605957f, 44.363358f}
};
float FifthPortalWPs [6][3] =
{
{1887.398804f, 763.633240f, 47.666851f},
{1879.020386f, 775.396973f, 38.705990f},
{1872.439087f, 782.568604f, 38.808292f},
{1863.573364f, 791.173584f, 38.743660f},
{1857.811890f, 796.765564f, 43.950329f},
{1845.577759f, 800.681152f, 44.104248f}
//{1827.100342f, 801.605957f, 44.363358f}
};
float SixthPoralWPs [4][3] =
{
{1888.861084f, 805.074768f, 38.375790f},
{1869.793823f, 804.135804f, 38.647018f},
{1861.541504f, 804.149780f, 43.968292f},
{1843.567017f, 804.288208f, 44.139091f}
//{1826.889648f, 803.929993f, 44.363239f}
};
const float SaboteurFinalPos1[3][3] =
{
{1892.502319f, 777.410767f, 38.630402f},
{1891.165161f, 762.969421f, 47.666920f},
{1893.168091f, 740.919189f, 47.666920f}
};
const float SaboteurFinalPos2[3][3] =
{
{1882.242676f, 834.818726f, 38.646786f},
{1879.220825f, 842.224854f, 43.333641f},
{1873.842896f, 863.892456f, 43.333641f}
};
const float SaboteurFinalPos3[2][3] =
{
{1904.298340f, 792.400391f, 38.646782f},
{1935.716919f, 758.437073f, 30.627895f}
};
const float SaboteurFinalPos4[3] =
{
1855.006104f, 760.641724f, 38.655266f
};
const float SaboteurFinalPos5[3] =
{
1906.667358f, 841.705566f, 38.637894f
};
const float SaboteurFinalPos6[5][3] =
{
{1911.437012f, 821.289246f, 38.684128f},
{1920.734009f, 822.978027f, 41.525414f},
{1928.262939f, 830.836609f, 44.668266f},
{1929.338989f, 837.593933f, 47.137596f},
{1931.063354f, 848.468445f, 47.190434f}
};
const Position MovePosition = {1806.955566f, 803.851807f, 44.363323f, 0.0f};
const Position playerTeleportPosition = {1830.531006f, 803.939758f, 44.340508f, 6.281611f};
const Position sinclariOutsidePosition = {1817.315674f, 804.060608f, 44.363998f, 0.0f};
class npc_sinclari_vh : public CreatureScript
{
public:
npc_sinclari_vh() : CreatureScript("npc_sinclari_vh") { }
bool OnGossipSelect(Player* player, Creature* creature, uint32 /*Sender*/, uint32 action)
{
player->PlayerTalkClass->ClearMenus();
switch (action)
{
case GOSSIP_ACTION_INFO_DEF+1:
player->CLOSE_GOSSIP_MENU();
CAST_AI(npc_sinclari_vh::npc_sinclariAI, (creature->AI()))->uiPhase = 1;
if (InstanceScript* instance = creature->GetInstanceScript())
instance->SetData(DATA_MAIN_EVENT_PHASE, SPECIAL);
break;
case GOSSIP_ACTION_INFO_DEF+2:
player->SEND_GOSSIP_MENU(13854, creature->GetGUID());
break;
case GOSSIP_ACTION_INFO_DEF+3:
player->NearTeleportTo(playerTeleportPosition.GetPositionX(), playerTeleportPosition.GetPositionY(), playerTeleportPosition.GetPositionZ(), playerTeleportPosition.GetOrientation(), true);
player->CLOSE_GOSSIP_MENU();
break;
}
return true;
}
bool OnGossipHello(Player* player, Creature* creature)
{
if (InstanceScript* instance = creature->GetInstanceScript())
{
switch (instance->GetData(DATA_MAIN_EVENT_PHASE))
{
case NOT_STARTED:
case FAIL: // Allow to start event if not started or wiped
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_ITEM_1, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+2);
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_START_EVENT, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+1);
player->SEND_GOSSIP_MENU(13853, creature->GetGUID());
break;
case IN_PROGRESS: // Allow to teleport inside if event is in progress
player->ADD_GOSSIP_ITEM(GOSSIP_ICON_CHAT, GOSSIP_I_WANT_IN, GOSSIP_SENDER_MAIN, GOSSIP_ACTION_INFO_DEF+3);
player->SEND_GOSSIP_MENU(13853, creature->GetGUID());
break;
default:
player->SEND_GOSSIP_MENU(13910, creature->GetGUID());
}
}
return true;
}
CreatureAI* GetAI(Creature* creature) const
{
return new npc_sinclariAI(creature);
}
struct npc_sinclariAI : public ScriptedAI
{
npc_sinclariAI(Creature* creature) : ScriptedAI(creature)
{
instance = creature->GetInstanceScript();
}
InstanceScript* instance;
uint8 uiPhase;
uint32 uiTimer;
void Reset()
{
uiPhase = 0;
uiTimer = 0;
me->SetReactState(REACT_AGGRESSIVE);
std::list<Creature*> GuardList;
me->GetCreatureListWithEntryInGrid(GuardList, NPC_VIOLET_HOLD_GUARD, 40.0f);
if (!GuardList.empty())
{
for (std::list<Creature*>::const_iterator itr = GuardList.begin(); itr != GuardList.end(); ++itr)
{
if (Creature* pGuard = *itr)
{
pGuard->DisappearAndDie();
pGuard->Respawn();
pGuard->SetVisible(true);
pGuard->SetReactState(REACT_AGGRESSIVE);
}
}
}
}
void UpdateAI(const uint32 uiDiff)
{
ScriptedAI::UpdateAI(uiDiff);
if (uiPhase)
{
if (uiTimer <= uiDiff)
{
switch (uiPhase)
{
case 1:
DoScriptText(SAY_SINCLARI_1, me);
uiTimer = 4000;
uiPhase = 2;
break;
case 2:
{
std::list<Creature*> GuardList;
me->GetCreatureListWithEntryInGrid(GuardList, NPC_VIOLET_HOLD_GUARD, 40.0f);
if (!GuardList.empty())
for (std::list<Creature*>::const_iterator itr = GuardList.begin(); itr != GuardList.end(); ++itr)
{
if (Creature* pGuard = *itr)
{
pGuard->RemoveUnitMovementFlag(MOVEMENTFLAG_WALKING);
pGuard->GetMotionMaster()->MovePoint(0, MovePosition);
}
}
uiTimer = 6000;
uiPhase = 3;
break;
}
case 3:
{
std::list<Creature*> GuardList;
me->GetCreatureListWithEntryInGrid(GuardList, NPC_VIOLET_HOLD_GUARD, 40.0f);
if (!GuardList.empty())
for (std::list<Creature*>::const_iterator itr = GuardList.begin(); itr != GuardList.end(); ++itr)
{
if (Creature* pGuard = *itr)
{
pGuard->SetVisible(false);
pGuard->SetReactState(REACT_PASSIVE);
}
}
uiTimer = 2000;
uiPhase = 4;
break;
}
case 4:
me->GetMotionMaster()->MovePoint(0, sinclariOutsidePosition);
uiTimer = 4000;
uiPhase = 5;
break;
case 5:
if (instance)
instance->SetData(DATA_MAIN_EVENT_PHASE, IN_PROGRESS);
me->SetReactState(REACT_PASSIVE);
uiTimer = 0;
uiPhase = 0;
break;
}
}
else uiTimer -= uiDiff;
}
if (!UpdateVictim())
return;
DoMeleeAttackIfReady();
}
};
};
class mob_azure_saboteur : public CreatureScript
{
public:
mob_azure_saboteur() : CreatureScript("mob_azure_saboteur") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_saboteurAI (creature);
}
struct mob_azure_saboteurAI : public npc_escortAI
{
mob_azure_saboteurAI(Creature* c):npc_escortAI(c)
{
instance = c->GetInstanceScript();
bHasGotMovingPoints = false;
uiBoss = 0;
Reset();
}
InstanceScript* instance;
bool bHasGotMovingPoints;
uint32 uiBoss;
void Reset()
{
if (instance && !uiBoss)
uiBoss = instance->GetData(DATA_WAVE_COUNT) == 6 ? instance->GetData(DATA_FIRST_BOSS) : instance->GetData(DATA_SECOND_BOSS);
me->SetReactState(REACT_PASSIVE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_IMMUNE_TO_PC|UNIT_FLAG_NON_ATTACKABLE);
me->SetFlag(UNIT_FIELD_FLAGS, UNIT_FLAG_NOT_SELECTABLE);
}
void WaypointReached(uint32 uiWPointId)
{
switch (uiBoss)
{
case 1:
if (uiWPointId == 2)
FinishPointReached();
break;
case 2:
if (uiWPointId == 2)
FinishPointReached();
break;
case 3:
if (uiWPointId == 1)
FinishPointReached();
break;
case 4:
if (uiWPointId == 0)
FinishPointReached();
break;
case 5:
if (uiWPointId == 0)
FinishPointReached();
break;
case 6:
if (uiWPointId == 4)
FinishPointReached();
break;
}
}
void UpdateAI(const uint32 diff)
{
if (instance && instance->GetData(DATA_MAIN_EVENT_PHASE) != IN_PROGRESS)
me->CastStop();
npc_escortAI::UpdateAI(diff);
if (!bHasGotMovingPoints)
{
bHasGotMovingPoints = true;
switch (uiBoss)
{
case 1:
for (int i=0;i<3;i++)
AddWaypoint(i, SaboteurFinalPos1[i][0], SaboteurFinalPos1[i][1], SaboteurFinalPos1[i][2], 0);
me->SetHomePosition(SaboteurFinalPos1[2][0], SaboteurFinalPos1[2][1], SaboteurFinalPos1[2][2], 4.762346f);
break;
case 2:
for (int i=0;i<3;i++)
AddWaypoint(i, SaboteurFinalPos2[i][0], SaboteurFinalPos2[i][1], SaboteurFinalPos2[i][2], 0);
me->SetHomePosition(SaboteurFinalPos2[2][0], SaboteurFinalPos2[2][1], SaboteurFinalPos2[2][2], 1.862674f);
break;
case 3:
for (int i=0;i<2;i++)
AddWaypoint(i, SaboteurFinalPos3[i][0], SaboteurFinalPos3[i][1], SaboteurFinalPos3[i][2], 0);
me->SetHomePosition(SaboteurFinalPos3[1][0], SaboteurFinalPos3[1][1], SaboteurFinalPos3[1][2], 5.500638f);
break;
case 4:
AddWaypoint(0, SaboteurFinalPos4[0], SaboteurFinalPos4[1], SaboteurFinalPos4[2], 0);
me->SetHomePosition(SaboteurFinalPos4[0], SaboteurFinalPos4[1], SaboteurFinalPos4[2], 3.991108f);
break;
case 5:
AddWaypoint(0, SaboteurFinalPos5[0], SaboteurFinalPos5[1], SaboteurFinalPos5[2], 0);
me->SetHomePosition(SaboteurFinalPos5[0], SaboteurFinalPos5[1], SaboteurFinalPos5[2], 1.100841f);
break;
case 6:
for (int i=0;i<5;i++)
AddWaypoint(i, SaboteurFinalPos6[i][0], SaboteurFinalPos6[i][1], SaboteurFinalPos6[i][2], 0);
me->SetHomePosition(SaboteurFinalPos6[4][0], SaboteurFinalPos6[4][1], SaboteurFinalPos6[4][2], 0.983031f);
break;
}
SetDespawnAtEnd(false);
Start(true, true);
}
}
void FinishPointReached()
{
me->CastSpell(me, SABOTEUR_SHIELD_DISRUPTION, false);
me->DisappearAndDie();
Creature* pSaboPort = Unit::GetCreature((*me), instance->GetData64(DATA_SABOTEUR_PORTAL));
if (pSaboPort)
pSaboPort->DisappearAndDie();
instance->SetData(DATA_START_BOSS_ENCOUNTER, 1);
}
};
};
class npc_teleportation_portal_vh : public CreatureScript
{
public:
npc_teleportation_portal_vh() : CreatureScript("npc_teleportation_portal_vh") { }
CreatureAI* GetAI(Creature* creature) const
{
return new npc_teleportation_portalAI(creature);
}
struct npc_teleportation_portalAI : public ScriptedAI
{
npc_teleportation_portalAI(Creature* c) : ScriptedAI(c), listOfMobs(me)
{
instance = c->GetInstanceScript();
uiTypeOfMobsPortal = urand(0, 1); // 0 - elite mobs 1 - portal guardian or portal keeper with regular mobs
bPortalGuardianOrKeeperOrEliteSpawn = false;
}
uint32 uiSpawnTimer;
bool bPortalGuardianOrKeeperOrEliteSpawn;
uint8 uiTypeOfMobsPortal;
SummonList listOfMobs;
InstanceScript* instance;
void Reset()
{
uiSpawnTimer = 10000;
bPortalGuardianOrKeeperOrEliteSpawn = false;
}
void EnterCombat(Unit* /*who*/) {}
void MoveInLineOfSight(Unit* /*who*/) {}
void UpdateAI(const uint32 diff)
{
if (!instance) //Massive usage of instance, global check
return;
if (instance->GetData(DATA_REMOVE_NPC) == 1)
{
me->DespawnOrUnsummon();
instance->SetData(DATA_REMOVE_NPC, 0);
}
uint8 uiWaveCount = instance->GetData(DATA_WAVE_COUNT);
if ((uiWaveCount == 6) || (uiWaveCount == 12)) //Don't spawn mobs on boss encounters
return;
switch (uiTypeOfMobsPortal)
{
// spawn elite mobs and then set portals visibility to make it look like it dissapeard
case 0:
if (!bPortalGuardianOrKeeperOrEliteSpawn)
{
if (uiSpawnTimer <= diff)
{
bPortalGuardianOrKeeperOrEliteSpawn = true;
uint8 k = uiWaveCount < 12 ? 2 : 3;
for (uint8 i = 0; i < k; ++i)
{
uint32 entry = RAND(CREATURE_AZURE_CAPTAIN, CREATURE_AZURE_RAIDER, CREATURE_AZURE_STALKER, CREATURE_AZURE_SORCEROR);
DoSummon(entry, me, 2.0f, 20000, TEMPSUMMON_DEAD_DESPAWN);
}
me->SetVisible(false);
} else uiSpawnTimer -= diff;
}
else
{
// if all spawned elites have died kill portal
if (listOfMobs.empty())
{
me->Kill(me, false);
me->RemoveCorpse();
}
}
break;
// spawn portal guardian or portal keeper with regular mobs
case 1:
if (uiSpawnTimer <= diff)
{
if (bPortalGuardianOrKeeperOrEliteSpawn)
{
uint8 k = instance->GetData(DATA_WAVE_COUNT) < 12 ? 3 : 4;
for (uint8 i = 0; i < k; ++i)
{
uint32 entry = RAND(CREATURE_AZURE_INVADER_1, CREATURE_AZURE_INVADER_2, CREATURE_AZURE_SPELLBREAKER_1, CREATURE_AZURE_SPELLBREAKER_2, CREATURE_AZURE_MAGE_SLAYER_1, CREATURE_AZURE_MAGE_SLAYER_2, CREATURE_AZURE_BINDER_1, CREATURE_AZURE_BINDER_2);
DoSummon(entry, me, 2.0f, 20000, TEMPSUMMON_DEAD_DESPAWN);
}
}
else
{
bPortalGuardianOrKeeperOrEliteSpawn = true;
uint32 entry = RAND(CREATURE_PORTAL_GUARDIAN, CREATURE_PORTAL_KEEPER);
if (Creature* pPortalKeeper = DoSummon(entry, me, 2.0f, 0, TEMPSUMMON_DEAD_DESPAWN))
me->CastSpell(pPortalKeeper, SPELL_PORTAL_CHANNEL, false);
}
uiSpawnTimer = SPAWN_TIME;
} else uiSpawnTimer -= diff;
if (bPortalGuardianOrKeeperOrEliteSpawn && !me->IsNonMeleeSpellCasted(false))
{
me->Kill(me, false);
me->RemoveCorpse();
}
break;
}
}
void JustDied(Unit* /*killer*/)
{
if (instance)
instance->SetData(DATA_WAVE_COUNT, instance->GetData(DATA_WAVE_COUNT)+1);
}
void JustSummoned(Creature* summoned)
{
listOfMobs.Summon(summoned);
if (summoned)
instance->SetData64(DATA_ADD_TRASH_MOB, summoned->GetGUID());
}
void SummonedMobDied(Creature* summoned)
{
listOfMobs.Despawn(summoned);
if (summoned)
instance->SetData64(DATA_DEL_TRASH_MOB, summoned->GetGUID());
}
};
};
struct violet_hold_trashAI : public npc_escortAI
{
violet_hold_trashAI(Creature* c):npc_escortAI(c)
{
instance = c->GetInstanceScript();
bHasGotMovingPoints = false;
if (instance)
portalLocationID = instance->GetData(DATA_PORTAL_LOCATION);
Reset();
}
public:
InstanceScript* instance;
bool bHasGotMovingPoints;
uint32 portalLocationID;
uint32 secondPortalRouteID;
void WaypointReached(uint32 uiPointId)
{
switch (portalLocationID)
{
case 0:
if (uiPointId == 5)
CreatureStartAttackDoor();
break;
case 1:
if ((uiPointId == 8 && secondPortalRouteID == 0) || (uiPointId == 7 && secondPortalRouteID == 1))
CreatureStartAttackDoor();
break;
case 2:
if (uiPointId == 7)
CreatureStartAttackDoor();
break;
case 3:
if (uiPointId == 8)
CreatureStartAttackDoor();
break;
case 4:
if (uiPointId == 5)
CreatureStartAttackDoor();
break;
case 5:
if (uiPointId == 3)
CreatureStartAttackDoor();
break;
}
}
void UpdateAI(const uint32)
{
if (instance && instance->GetData(DATA_MAIN_EVENT_PHASE) != IN_PROGRESS)
me->CastStop();
if (!bHasGotMovingPoints)
{
bHasGotMovingPoints = true;
switch (portalLocationID)
{
case 0:
for (int i=0;i<6;i++)
AddWaypoint(i, FirstPortalWPs[i][0]+irand(-1, 1), FirstPortalWPs[i][1]+irand(-1, 1), FirstPortalWPs[i][2]+irand(-1, 1), 0);
me->SetHomePosition(FirstPortalWPs[5][0], FirstPortalWPs[5][1], FirstPortalWPs[5][2], 3.149439f);
break;
case 1:
secondPortalRouteID = urand(0, 1);
switch (secondPortalRouteID)
{
case 0:
for (int i=0;i<9;i++)
AddWaypoint(i, SecondPortalFirstWPs[i][0]+irand(-1, 1), SecondPortalFirstWPs[i][1]+irand(-1, 1), SecondPortalFirstWPs[i][2], 0);
me->SetHomePosition(SecondPortalFirstWPs[8][0]+irand(-1, 1), SecondPortalFirstWPs[8][1]+irand(-1, 1), SecondPortalFirstWPs[8][2]+irand(-1, 1), 3.149439f);
break;
case 1:
for (int i=0;i<8;i++)
AddWaypoint(i, SecondPortalSecondWPs[i][0]+irand(-1, 1), SecondPortalSecondWPs[i][1]+irand(-1, 1), SecondPortalSecondWPs[i][2], 0);
me->SetHomePosition(SecondPortalSecondWPs[7][0], SecondPortalSecondWPs[7][1], SecondPortalSecondWPs[7][2], 3.149439f);
break;
}
break;
case 2:
for (int i=0;i<8;i++)
AddWaypoint(i, ThirdPortalWPs[i][0]+irand(-1, 1), ThirdPortalWPs[i][1]+irand(-1, 1), ThirdPortalWPs[i][2], 0);
me->SetHomePosition(ThirdPortalWPs[7][0], ThirdPortalWPs[7][1], ThirdPortalWPs[7][2], 3.149439f);
break;
case 3:
for (int i=0;i<9;i++)
AddWaypoint(i, FourthPortalWPs[i][0]+irand(-1, 1), FourthPortalWPs[i][1]+irand(-1, 1), FourthPortalWPs[i][2], 0);
me->SetHomePosition(FourthPortalWPs[8][0], FourthPortalWPs[8][1], FourthPortalWPs[8][2], 3.149439f);
break;
case 4:
for (int i=0;i<6;i++)
AddWaypoint(i, FifthPortalWPs[i][0]+irand(-1, 1), FifthPortalWPs[i][1]+irand(-1, 1), FifthPortalWPs[i][2], 0);
me->SetHomePosition(FifthPortalWPs[5][0], FifthPortalWPs[5][1], FifthPortalWPs[5][2], 3.149439f);
break;
case 5:
for (int i=0;i<4;i++)
AddWaypoint(i, SixthPoralWPs[i][0]+irand(-1, 1), SixthPoralWPs[i][1]+irand(-1, 1), SixthPoralWPs[i][2], 0);
me->SetHomePosition(SixthPoralWPs[3][0], SixthPoralWPs[3][1], SixthPoralWPs[3][2], 3.149439f);
break;
}
SetDespawnAtEnd(false);
Start(true, true);
}
}
void JustDied(Unit* /*unit*/)
{
if (Creature* portal = Unit::GetCreature((*me), instance->GetData64(DATA_TELEPORTATION_PORTAL)))
CAST_AI(npc_teleportation_portal_vh::npc_teleportation_portalAI, portal->AI())->SummonedMobDied(me);
if (instance)
instance->SetData(DATA_NPC_PRESENCE_AT_DOOR_REMOVE, 1);
}
void CreatureStartAttackDoor()
{
me->SetReactState(REACT_PASSIVE);
DoCast(SPELL_DESTROY_DOOR_SEAL);
if (instance)
instance->SetData(DATA_NPC_PRESENCE_AT_DOOR_ADD, 1);
}
};
class mob_azure_invader : public CreatureScript
{
public:
mob_azure_invader() : CreatureScript("mob_azure_invader") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_invaderAI (creature);
}
struct mob_azure_invaderAI : public violet_hold_trashAI
{
mob_azure_invaderAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiCleaveTimer;
uint32 uiImpaleTimer;
uint32 uiBrutalStrikeTimer;
uint32 uiSunderArmorTimer;
void Reset()
{
uiCleaveTimer = 5000;
uiImpaleTimer = 4000;
uiBrutalStrikeTimer = 5000;
uiSunderArmorTimer = 4000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (me->GetEntry() == CREATURE_AZURE_INVADER_1)
{
if (uiCleaveTimer <= diff)
{
DoCast(me->getVictim(), SPELL_CLEAVE);
uiCleaveTimer = 5000;
} else uiCleaveTimer -= diff;
if (uiImpaleTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, SPELL_IMPALE);
uiImpaleTimer = 4000;
} else uiImpaleTimer -= diff;
}
if (me->GetEntry() == CREATURE_AZURE_INVADER_2)
{
if (uiBrutalStrikeTimer <= diff)
{
DoCast(me->getVictim(), SPELL_BRUTAL_STRIKE);
uiBrutalStrikeTimer = 5000;
} else uiBrutalStrikeTimer -= diff;
if (uiSunderArmorTimer <= diff)
{
DoCast(me->getVictim(), SPELL_SUNDER_ARMOR);
uiSunderArmorTimer = urand(8000, 10000);
} else uiSunderArmorTimer -= diff;
DoMeleeAttackIfReady();
}
DoMeleeAttackIfReady();
}
};
};
class mob_azure_binder : public CreatureScript
{
public:
mob_azure_binder() : CreatureScript("mob_azure_binder") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_binderAI (creature);
}
struct mob_azure_binderAI : public violet_hold_trashAI
{
mob_azure_binderAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiArcaneExplosionTimer;
uint32 uiArcainBarrageTimer;
uint32 uiFrostNovaTimer;
uint32 uiFrostboltTimer;
void Reset()
{
uiArcaneExplosionTimer = 5000;
uiArcainBarrageTimer = 4000;
uiFrostNovaTimer = 5000;
uiFrostboltTimer = 4000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (me->GetEntry() == CREATURE_AZURE_BINDER_1)
{
if (uiArcaneExplosionTimer <= diff)
{
DoCast(DUNGEON_MODE(SPELL_ARCANE_EXPLOSION, H_SPELL_ARCANE_EXPLOSION));
uiArcaneExplosionTimer = 5000;
} else uiArcaneExplosionTimer -= diff;
if (uiArcainBarrageTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, DUNGEON_MODE(SPELL_ARCANE_BARRAGE, H_SPELL_ARCANE_BARRAGE));
uiArcainBarrageTimer = 6000;
} else uiArcainBarrageTimer -= diff;
}
if (me->GetEntry() == CREATURE_AZURE_BINDER_2)
{
if (uiFrostNovaTimer <= diff)
{
DoCast(DUNGEON_MODE(SPELL_FROST_NOVA, H_SPELL_FROST_NOVA));
uiFrostNovaTimer = 5000;
} else uiFrostNovaTimer -= diff;
if (uiFrostboltTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, DUNGEON_MODE(SPELL_FROSTBOLT, H_SPELL_FROSTBOLT));
uiFrostboltTimer = 6000;
} else uiFrostboltTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
};
class mob_azure_mage_slayer : public CreatureScript
{
public:
mob_azure_mage_slayer() : CreatureScript("mob_azure_mage_slayer") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_mage_slayerAI (creature);
}
struct mob_azure_mage_slayerAI : public violet_hold_trashAI
{
mob_azure_mage_slayerAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiArcaneEmpowermentTimer;
uint32 uiSpellLockTimer;
void Reset()
{
uiArcaneEmpowermentTimer = 5000;
uiSpellLockTimer = 5000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (me->GetEntry() == CREATURE_AZURE_MAGE_SLAYER_1)
{
if (uiArcaneEmpowermentTimer <= diff)
{
DoCast(me, SPELL_ARCANE_EMPOWERMENT);
uiArcaneEmpowermentTimer = 14000;
} else uiArcaneEmpowermentTimer -= diff;
}
if (me->GetEntry() == CREATURE_AZURE_MAGE_SLAYER_2)
{
if (uiSpellLockTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, SPELL_SPELL_LOCK);
uiSpellLockTimer = 9000;
} else uiSpellLockTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
};
class mob_azure_raider : public CreatureScript
{
public:
mob_azure_raider() : CreatureScript("mob_azure_raider") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_raiderAI (creature);
}
struct mob_azure_raiderAI : public violet_hold_trashAI
{
mob_azure_raiderAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiConcussionBlowTimer;
uint32 uiMagicReflectionTimer;
void Reset()
{
uiConcussionBlowTimer = 5000;
uiMagicReflectionTimer = 8000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (uiConcussionBlowTimer <= diff)
{
DoCast(me->getVictim(), SPELL_CONCUSSION_BLOW);
uiConcussionBlowTimer = 5000;
} else uiConcussionBlowTimer -= diff;
if (uiMagicReflectionTimer <= diff)
{
DoCast(SPELL_MAGIC_REFLECTION);
uiMagicReflectionTimer = urand(10000, 15000);
} else uiMagicReflectionTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
class mob_azure_stalker : public CreatureScript
{
public:
mob_azure_stalker() : CreatureScript("mob_azure_stalker") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_stalkerAI (creature);
}
struct mob_azure_stalkerAI : public violet_hold_trashAI
{
mob_azure_stalkerAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiBackstabTimer;
uint32 uiTacticalBlinkTimer;
bool TacticalBlinkCasted;
void Reset()
{
uiBackstabTimer = 1300;
uiTacticalBlinkTimer = 8000;
TacticalBlinkCasted =false;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (!TacticalBlinkCasted)
{
if (uiTacticalBlinkTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 40, true);
if (target)
DoCast(target, SPELL_TACTICAL_BLINK);
uiTacticalBlinkTimer = 6000;
TacticalBlinkCasted = true;
} else uiTacticalBlinkTimer -= diff;
}
else
{
if (uiBackstabTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_NEAREST, 0, 10, true);
DoCast(target, SPELL_BACKSTAB);
TacticalBlinkCasted = false;
uiBackstabTimer =1300;
} else uiBackstabTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
};
class mob_azure_spellbreaker : public CreatureScript
{
public:
mob_azure_spellbreaker() : CreatureScript("mob_azure_spellbreaker") { }
struct mob_azure_spellbreakerAI : public violet_hold_trashAI
{
mob_azure_spellbreakerAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiArcaneBlastTimer;
uint32 uiSlowTimer;
uint32 uiChainsOfIceTimer;
uint32 uiConeOfColdTimer;
void Reset()
{
uiArcaneBlastTimer = 5000;
uiSlowTimer = 4000;
uiChainsOfIceTimer = 5000;
uiConeOfColdTimer = 4000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (me->GetEntry() == CREATURE_AZURE_SPELLBREAKER_1)
{
if (uiArcaneBlastTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, DUNGEON_MODE(SPELL_ARCANE_BLAST, H_SPELL_ARCANE_BLAST));
uiArcaneBlastTimer = 6000;
} else uiArcaneBlastTimer -= diff;
if (uiSlowTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, SPELL_SLOW);
uiSlowTimer = 5000;
} else uiSlowTimer -= diff;
}
if (me->GetEntry() == CREATURE_AZURE_SPELLBREAKER_2)
{
if (uiChainsOfIceTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, SPELL_CHAINS_OF_ICE);
uiChainsOfIceTimer = 7000;
} else uiChainsOfIceTimer -= diff;
if (uiConeOfColdTimer <= diff)
{
DoCast(DUNGEON_MODE(SPELL_CONE_OF_COLD, H_SPELL_CONE_OF_COLD));
uiConeOfColdTimer = 5000;
} else uiConeOfColdTimer -= diff;
}
DoMeleeAttackIfReady();
}
};
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_spellbreakerAI (creature);
}
};
class mob_azure_captain : public CreatureScript
{
public:
mob_azure_captain() : CreatureScript("mob_azure_captain") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_captainAI (creature);
}
struct mob_azure_captainAI : public violet_hold_trashAI
{
mob_azure_captainAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiMortalStrikeTimer;
uint32 uiWhirlwindTimer;
void Reset()
{
uiMortalStrikeTimer = 5000;
uiWhirlwindTimer = 8000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (uiMortalStrikeTimer <= diff)
{
DoCast(me->getVictim(), SPELL_MORTAL_STRIKE);
uiMortalStrikeTimer = 5000;
} else uiMortalStrikeTimer -= diff;
if (uiWhirlwindTimer <= diff)
{
DoCast(me, SPELL_WHIRLWIND_OF_STEEL);
uiWhirlwindTimer = 8000;
} else uiWhirlwindTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
class mob_azure_sorceror : public CreatureScript
{
public:
mob_azure_sorceror() : CreatureScript("mob_azure_sorceror") { }
CreatureAI* GetAI(Creature* creature) const
{
return new mob_azure_sorcerorAI (creature);
}
struct mob_azure_sorcerorAI : public violet_hold_trashAI
{
mob_azure_sorcerorAI(Creature* c) : violet_hold_trashAI(c)
{
instance = c->GetInstanceScript();
}
uint32 uiArcaneStreamTimer;
uint32 uiArcaneStreamTimerStartingValueHolder;
uint32 uiManaDetonationTimer;
void Reset()
{
uiArcaneStreamTimer = 4000;
uiArcaneStreamTimerStartingValueHolder = uiArcaneStreamTimer;
uiManaDetonationTimer = 5000;
}
void UpdateAI(const uint32 diff)
{
violet_hold_trashAI::UpdateAI(diff);
npc_escortAI::UpdateAI(diff);
if (!UpdateVictim())
return;
if (uiArcaneStreamTimer <= diff)
{
Unit* target = SelectTarget(SELECT_TARGET_RANDOM, 0, 100, true);
if (target)
DoCast(target, DUNGEON_MODE(SPELL_ARCANE_STREAM, H_SPELL_ARCANE_STREAM));
uiArcaneStreamTimer = urand(0, 5000)+5000;
uiArcaneStreamTimerStartingValueHolder = uiArcaneStreamTimer;
} else uiArcaneStreamTimer -= diff;
if (uiManaDetonationTimer <= diff && uiArcaneStreamTimer >=1500 && uiArcaneStreamTimer <= uiArcaneStreamTimerStartingValueHolder/2)
{
DoCast(DUNGEON_MODE(SPELL_MANA_DETONATION, H_SPELL_MANA_DETONATION));
uiManaDetonationTimer = urand(2000, 6000);
} else uiManaDetonationTimer -= diff;
DoMeleeAttackIfReady();
}
};
};
void AddSC_violet_hold()
{
new npc_sinclari_vh();
new npc_teleportation_portal_vh();
new mob_azure_invader();
new mob_azure_spellbreaker();
new mob_azure_binder();
new mob_azure_mage_slayer();
new mob_azure_captain();
new mob_azure_sorceror();
new mob_azure_raider();
new mob_azure_stalker();
new mob_azure_saboteur();
} | Java |
/* Hey EMACS -*- linux-c -*- */
/* $Id: toolbar.h 4392 2011-08-01 09:24:05Z debrouxl $ */
/* TiLP - Tilp Is a Linking Program
* Copyright (C) 1999-2006 Romain Lievin
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef GTOOLBAR_H
#define GTOOLBAR_H
void toolbar_refresh_buttons(void);
void toolbar_set_button(int sr);
#endif
| Java |
(function ($, window, document) {
"use strict";
$(document).on( 'ready', function(){
var $body = $('body'),
$topbar = $( document.getElementById('topbar') ),
$products_sliders = $('.products-slider-wrapper, .categories-slider-wrapper');
/*************************
* SHOP STYLE SWITCHER
*************************/
$('#list-or-grid').on( 'click', 'a', function(){
var trigger = $(this),
view = trigger.attr( 'class' ).replace('-view', '');
$( 'ul.products li' ).removeClass( 'list grid' ).addClass( view );
trigger.parent().find( 'a' ).removeClass( 'active' );
trigger.addClass( 'active' );
$.cookie( yit_shop_view_cookie, view );
return false;
});
/*************************
* Fix Product Name and Price
*************************/
var padding_nameprice = function () {
$('li.product .product-wrapper .info-product.slideup').each(function () {
$(this).find('h3').css( 'padding-' + ( ! yit.isRtl ? 'right' : 'left' ), $(this).find('span.price').width() + 10 );
});
};
if( $(window).width() > 1199 ){
padding_nameprice();
}
$(document).on('yith-wcan-ajax-filtered', padding_nameprice );
/*************************
* ADD TO CART
*************************/
var product, product_onsale;
var add_to_cart = function() {
$('ul.products').on('click', 'li.product .add_to_cart_button', function () {
product = $(this).parents('li.product');
product_onsale = product.find('.product-wrapper > .onsale');
if( typeof yit.load_gif != 'undefined' ) {
product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else{
product.find('.thumb-wrapper').block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
});
}
add_to_cart();
$(document).on('yith-wcan-ajax-filtered', add_to_cart );
$body.on('added_to_cart', function () {
if( typeof product_onsale === 'undefined' && typeof product === 'undefined' ) return;
$( '.products-slider.swiper .swiper-slide .opacity .swiper-product-informations span.product-add-to-cart a.added_to_cart.wc-forward')
.addClass( 'btn btn-flat' )
.prev('a').remove();
if ( product_onsale.length ) {
product_onsale.remove();
}
product.find('.thumb-wrapper').append('<div class="added_to_cart_box"><div class="added_to_cart_label">' + yit.added_to_cart + '</div></div>');
product.find('.added_to_cart_label').append(product.find('a.added_to_cart'));
product.find('.product-wrapper div:first-child').addClass('nohover');
setTimeout( function(){
product.find('.added_to_cart_box').fadeOut(2000, function(){ $(this).remove(); });
product.find('.product-wrapper div:first-child').removeClass('nohover');
}, 3000 );
if (product.find('.product-wrapper > .added_to_cart_ico').length == 0) {
setTimeout(function() {
product.find('.product-wrapper').append('<span class="added_to_cart_ico">' + yit.added_to_cart_ico + '</span>');
}, 4000);
}
product.find('.thumb-wrapper').unblock();
});
/*************************
* PRODUCTS SLIDER
*************************/
if( $.fn.owlCarousel && $.fn.imagesLoaded && $products_sliders.length ) {
var product_slider = function(t) {
t.imagesLoaded(function(){
var cols = t.data('columns') ? t.data('columns') : 4;
var autoplay = (t.attr('data-autoplay')=='true') ? 3000 : false;
var owl = t.find('.products').owlCarousel({
items : cols,
responsiveClass : true,
responsive:{
0 : {
items: 2
},
479 : {
items: 3
},
767 : {
items: 4
},
992 : {
items: cols
}
},
autoplay : autoplay,
autoplayTimeout : 2000,
autoplayHoverPause: true,
loop : true,
rtl: yit.isRtl == true
});
// Custom Navigation Events
t.on('click', '.es-nav-next', function () {
owl.trigger('next.owl.carousel');
});
t.on('click', '.es-nav-prev', function () {
owl.trigger('prev.owl.carousel');
});
});
};
// initialize slider in only visible tabs
$products_sliders.each(function(){
var t = $(this);
if( ! t.closest('.panel.group').length || t.closest('.panel.group').hasClass('showing') ){
product_slider( t );
}
});
$('.tabs-container').on( 'yit_tabopened', function( e, tab ) {
product_slider( tab.find( $products_sliders ) );
});
}
/*************************
* VARIATIONS SELECT
*************************/
var variations_select = function(){
// variations select
if( $.fn.selectbox ) {
var form = $('form.variations_form');
var select = form.find('select:not(.yith_wccl_custom)');
if( form.data('wccl') ) {
select = select.filter(function(){
return $(this).data('type') == 'select'
});
}
select.selectbox({
effect: 'fade',
onOpen: function() {
//$('.variations select').trigger('focusin');
}
});
var update_select = function(event){ // console.log(event);
select.selectbox("detach");
select.selectbox("attach");
};
// fix variations select
form.on( 'woocommerce_update_variation_values', update_select);
form.find('.reset_variations').on('click.yit', update_select);
}
};
variations_select();
/*************************
* TOPBAR INDICATORS
*************************/
$topbar.find('#lang_sel .lang_sel_sel').append('<span class="sf-sub-indicator"> +</span>');
$topbar.find('#wcml_currency_switcher > ul > li a.sbSelector').append('<span class="sf-sub-indicator"> +</span>');
/*************************
* PRODUCT TABS
*************************/
$('.single-product-tabs.vertical').on('click', 'ul.tabs li .tab_name', function () {
var tab_trigger = $(this),
panel = tab_trigger.siblings('.panel'),
container = tab_trigger.closest('.single-product-tabs');
if ( ! tab_trigger.hasClass('active') ) {
//remove opened tab
container.find('.tab_name.active').siblings('div.panel').slideToggle('slow');
container.find('.tab_name.active').removeClass('active');
//open tab
tab_trigger.addClass('active');
} else {
tab_trigger.removeClass('active');
}
panel.slideToggle('slow');
});
/*************************
* INQUIRY FORM
*************************/
var inquiry_form = function(){
if ( $('#inquiry-form .product-inquiry').length ) {
$(document).on('click', '#inquiry-form .product-inquiry', function(event){
event.stopImmediatePropagation('click');
$(this).next('form.contact-form').slideToggle('slow');
});
}
};
inquiry_form();
$(document).on('yit_quick_view_loaded', inquiry_form);
if( $( 'body').hasClass( 'single-product' ) ) {
setTimeout( function() {
if( $.trim( $( 'div.user-message').html() ) != '' || $.trim( $( '.contact-form li div.msg-error' ).text() ) != '' ) {
$('form.contact-form').slideToggle('slow');
}
}, 200 );
}
/*************************
* Wishlist
*************************/
var wishlist_share = function() {
if ( $('#wishlist-share div.share-text').length ) {
$(document).on('click', '#wishlist-share div.share-text', function(){
$(this).next('div.share-link-container').slideToggle('slow');
});
}
};
wishlist_share();
$(document).on('yit_quick_view_loaded', wishlist_share);
/*************************
* Update Calculate Shipping Select
*************************/
var wc_version = 2.2;
if (typeof yit_woocommerce != 'undefined') wc_version = parseFloat(yit_woocommerce.version);
if ( wc_version < 2.3 && $.fn.selectbox ) {
$('#calc_shipping_state').next('.sbHolder').addClass('stateHolder');
$body.on('country_to_state_changing', function(){
$('.stateHolder').remove();
$('#calc_shipping_state').show().attr('sb', '');
$('select#calc_shipping_state').selectbox({
effect: 'fade',
classHolder: 'stateHolder sbHolder'
});
});
}
/*************************
* Login Form
*************************/
// $('#login-form').on('submit', function(){
// var a = $('#reg_password').val();
// var b = $('#reg_password_retype').val();
// if(!(a==b)){
// $('#reg_password_retype').addClass('invalid');
// return false;
// }else{
// $('#reg_password_retype').removeClass('invalid');
// return true;
// }
// });
/*************************
* PRODUCT QUICK VIEW
*************************/
function quick_view_trigger() {
$('div.quick-view a.trigger').yit_quick_view({
item_container: 'li.product',
loader : 'div.single-product.woocommerce',
assets : yit_quick_view.assets,
before : function (trigger, item) {
// add loading in the button
if( typeof yit.load_gif != 'undefined' ) {
trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else{
trigger.parent().block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
item.find('.thumb-wrapper').addClass('hover');
},
openDialog : function (trigger, item) {
// remove loading from button
trigger.parent().unblock();
item.find('.thumb-wrapper').removeClass('hover');
},
completed : function (trigger, item, html, overlay) {
var data = $('<div>' + html + '</div>'),
title = data.find('h1.product_title').html(),
price = data.find('p.price').html(),
rating = data.find('div.star-rating').html(),
container = document.getElementById('wrapper'),
wrapper = $(overlay).find('.main .container');
// add main class to dialog container
$(overlay).addClass('product-quick-view');
// head
$('<p />').addClass('price').html(price).prependTo(wrapper.find('.head'));
$('<div />').addClass('star-rating').html(rating).prependTo(wrapper.find('.head'));
$('<h4 />').html(title).prependTo(wrapper.find('.head'));
//prettyPhoto
if ( typeof $.prettyPhoto != 'undefined' ) {
data.find( "a[rel^='thumbnails'], a.zoom" ).prettyPhoto({
social_tools : false,
theme : 'pp_woocommerce',
horizontal_padding: 40,
opacity : 0.9,
deeplinking : false
});
}
// quantity fields
$('div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)').addClass('buttons_added').append('<input type="button" value="+" class="plus" />').prepend('<input type="button" value="-" class="minus" />');
variations_select();
// add to cart
$('form.cart', overlay).on('submit', function (e) {
e.preventDefault();
var form = $(this),
button = form.find('button'),
product_url = item.find('a.thumb').attr('href');
if( typeof yit.load_gif != 'undefined' ) {
button.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else if (typeof( woocommerce_params.plugin_url ) != 'undefined') {
button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.plugin_url + '/assets/images/ajax-loader.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
else {
button.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
$.post(product_url, form.serialize() + '&_wp_http_referer=' + product_url, function (result) {
var message = $( '.woocommerce-message', result ),
cart_dropdown = $( '#header .yit_cart_widget', result);
if( typeof wc_cart_fragments_params != 'undefined') {
// update fragments
var $supports_html5_storage;
try {
$supports_html5_storage = ( 'sessionStorage' in window && window.sessionStorage !== null );
window.sessionStorage.setItem('wc', 'test');
window.sessionStorage.removeItem('wc');
} catch (err) {
$supports_html5_storage = false;
}
$.ajax({
url : wc_cart_fragments_params.wc_ajax_url.toString().replace('%%endpoint%%', 'get_refreshed_fragments'),
type : 'POST',
success: function (data) {
if (data && data.fragments) {
$.each(data.fragments, function (key, value) {
$(key).replaceWith(value);
});
if ($supports_html5_storage) {
sessionStorage.setItem(wc_cart_fragments_params.fragment_name, JSON.stringify(data.fragments));
sessionStorage.setItem('wc_cart_hash', data.cart_hash);
}
$(document.body).trigger('wc_fragments_refreshed');
}
}
});
}
// add message
$('div.product', overlay).before(message);
// remove loading
button.unblock();
});
});
// others
$('#wishlist-share').find('.share-link-container').hide();
$('#inquiry-form').find('form.contact-form').hide();
},
action : 'yit_load_product_quick_view'
});
}
if ($.fn.yit_quick_view && typeof yit_quick_view != 'undefined') {
quick_view_trigger();
$(document).on('yith-wcan-ajax-filtered', quick_view_trigger);
}
/*************************
* WISHLIST LABEL
*************************/
$( '.yith-wcwl-add-button .add_to_wishlist').on( 'click', function() {
var feedback = $(this).closest('.yith-wcwl-add-to-wishlist').find('.yith-wcwl-wishlistaddedbrowse span.feedback');
feedback.fadeIn();
setTimeout( function(){
feedback.fadeOut('slow');
}, 4000 );
});
/*************************
* Widget Woo Price Filter
*************************/
if( yit.price_filter_slider == 'no' || typeof yit.price_filter_slider == 'undefined' ) {
var removePriceFilterSlider = function() {
$( 'input#min_price, input#max_price' ).show();
$('form > div.price_slider_wrapper').find( 'div.price_slider, div.price_label' ).hide();
};
removePriceFilterSlider();
}
/*****************************
* TERMS AND CONDITIONS POPUP
*****************************/
if ($.fn.yit_quick_view ) {
var term_popup = function() {
$('p.terms a').yit_quick_view({
item_container: 'p.terms',
loader: '#primary .content',
loadPage: true,
before: function( trigger, item ) {
// add loading in the button
if( typeof yit.load_gif != 'undefined' ) {
item.block({message: null, overlayCSS: {background: '#fff url(' + yit.load_gif + ') no-repeat center', opacity: 0.3, cursor: 'none'}});
} else {
item.block({message: null, overlayCSS: {background: '#fff url(' + woocommerce_params.ajax_loader_url.substring(0, woocommerce_params.ajax_loader_url.length - 7) + '.gif) no-repeat center', opacity: 0.3, cursor: 'none'}});
}
},
completed: function( trigger, item, html, overlay ) {
var data = $('<div>' + html + '</div>'),
title = trigger.text(),
container = document.getElementById( 'wrapper' ),
wrapper = $(overlay).find('.main .container');
// head
$('<h4 />').html(title).prependTo( wrapper.find('.head') );
$(overlay).addClass('terms-popup');
$(overlay).find('.content').removeClass('col-sm-12 col-sm-9');
},
openDialog: function( trigger, item ) {
item.unblock();
}
});
};
$body.on('updated_checkout', term_popup);
term_popup();
}
});
})( jQuery, window, document ); | Java |
package com.yh.admin.bo;
import java.util.Date;
import com.yh.platform.core.bo.BaseBo;
public class UserAgent extends BaseBo {
private static final long serialVersionUID = 2715416587055228708L;
private Long userAgentOid;
private Long systemPositionOid;
private String userId; // 被代理人
private String agentUserId; // 指定的代理人
private Date effectiveDate; // 有效开始期
private Date expiredDt;
private String isActive;
public Long getSystemPositionOid() {
return systemPositionOid;
}
public void setSystemPositionOid(Long systemPositionOid) {
this.systemPositionOid = systemPositionOid;
}
public Long getUserAgentOid() {
return userAgentOid;
}
public void setUserAgentOid(Long userAgentOid) {
this.userAgentOid = userAgentOid;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getAgentUserId() {
return agentUserId;
}
public void setAgentUserId(String agentUserId) {
this.agentUserId = agentUserId;
}
public Date getExpiredDt() {
return expiredDt;
}
public void setExpiredDt(Date expiredDt) {
this.expiredDt = expiredDt;
}
public String getIsActive() {
return isActive;
}
public void setIsActive(String isActive) {
this.isActive = isActive;
}
public Date getEffectiveDate() {
return effectiveDate;
}
public void setEffectiveDate(Date effectiveDate) {
this.effectiveDate = effectiveDate;
}
}
| Java |
<?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\File;
use PHPExiftool\Driver\AbstractTag;
class PreviewPNG extends AbstractTag
{
protected $Id = 'PreviewPNG';
protected $Name = 'PreviewPNG';
protected $FullName = 'Extra';
protected $GroupName = 'File';
protected $g0 = 'File';
protected $g1 = 'File';
protected $g2 = 'Image';
protected $Type = '?';
protected $Writable = false;
protected $Description = 'Preview PNG';
protected $flag_Binary = true;
}
| Java |
<?php
/**
* @version $Id: blog.php 20960 2011-03-12 14:14:00Z chdemko $
* @package Chola.Site
* @subpackage com_content
* @copyright Copyright (C) 2005 - 2011 Cholalabs Software LLP. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
JHtml::addIncludePath(JPATH_COMPONENT.'/helpers');
?>
<div class="blog<?php echo $this->pageclass_sfx;?>">
<?php if ($this->params->get('show_page_heading', 1)) : ?>
<h1>
<?php echo $this->escape($this->params->get('page_heading')); ?>
</h1>
<?php endif; ?>
<?php if ($this->params->get('show_category_title', 1) OR $this->params->get('page_subheading')) : ?>
<h2>
<?php echo $this->escape($this->params->get('page_subheading')); ?>
<?php if ($this->params->get('show_category_title')) : ?>
<span class="subheading-category"><?php echo $this->category->title;?></span>
<?php endif; ?>
</h2>
<?php endif; ?>
<?php if ($this->params->get('show_description', 1) || $this->params->def('show_description_image', 1)) : ?>
<div class="category-desc">
<?php if ($this->params->get('show_description_image') && $this->category->getParams()->get('image')) : ?>
<img src="<?php echo $this->category->getParams()->get('image'); ?>"/>
<?php endif; ?>
<?php if ($this->params->get('show_description') && $this->category->description) : ?>
<?php echo JHtml::_('content.prepare', $this->category->description); ?>
<?php endif; ?>
<div class="clr"></div>
</div>
<?php endif; ?>
<?php $leadingcount=0 ; ?>
<?php if (!empty($this->lead_items)) : ?>
<div class="items-leading">
<?php foreach ($this->lead_items as &$item) : ?>
<div class="leading-<?php echo $leadingcount; ?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<?php
$leadingcount++;
?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php
$introcount=(count($this->intro_items));
$counter=0;
?>
<?php if (!empty($this->intro_items)) : ?>
<?php foreach ($this->intro_items as $key => &$item) : ?>
<?php
$key= ($key-$leadingcount)+1;
$rowcount=( ((int)$key-1) % (int) $this->columns) +1;
$row = $counter / $this->columns ;
if ($rowcount==1) : ?>
<div class="items-row cols-<?php echo (int) $this->columns;?> <?php echo 'row-'.$row ; ?>">
<?php endif; ?>
<div class="item column-<?php echo $rowcount;?><?php echo $item->state == 0 ? ' system-unpublished' : null; ?>">
<?php
$this->item = &$item;
echo $this->loadTemplate('item');
?>
</div>
<?php $counter++; ?>
<?php if (($rowcount == $this->columns) or ($counter ==$introcount)): ?>
<span class="row-separator"></span>
</div>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
<?php if (!empty($this->link_items)) : ?>
<?php echo $this->loadTemplate('links'); ?>
<?php endif; ?>
<?php if (!empty($this->children[$this->category->id])&& $this->maxLevel != 0) : ?>
<div class="cat-children">
<h3>
<?php echo JTEXT::_('JGLOBAL_SUBCATEGORIES'); ?>
</h3>
<?php echo $this->loadTemplate('children'); ?>
</div>
<?php endif; ?>
<?php if (($this->params->def('show_pagination', 1) == 1 || ($this->params->get('show_pagination') == 2)) && ($this->pagination->get('pages.total') > 1)) : ?>
<div class="pagination">
<?php if ($this->params->def('show_pagination_results', 1)) : ?>
<p class="counter">
<?php echo $this->pagination->getPagesCounter(); ?>
</p>
<?php endif; ?>
<?php echo $this->pagination->getPagesLinks(); ?>
</div>
<?php endif; ?>
</div>
| Java |
local function isBotAllowed (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
local banned = redis:get(hash)
return banned
end
local function allowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:set(hash, true)
end
local function disallowBot (userId, chatId)
local hash = 'anti-bot:allowed:'..chatId..':'..userId
redis:del(hash)
end
-- Is anti-bot enabled on chat
local function isAntiBotEnabled (chatId)
local hash = 'anti-bot:enabled:'..chatId
local enabled = redis:get(hash)
return enabled
end
local function enableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'anti-bot:enabled:'..chatId
redis:del(hash)
end
local function isABot (user)
-- Flag its a bot 0001000000000000
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function kickUser(userId, chatId)
local chat = 'chat#id'..chatId
local user = 'user#id'..userId
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
-- We wont return text if is a service msg
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
end
end
local chatId = msg.to.id
if matches[1] == 'enable' then
enableAntiBot(chatId)
return 'Anti-bot enabled on this chat'
end
if matches[1] == 'disable' then
disableAntiBot(chatId)
return 'Anti-bot disabled on this chat'
end
if matches[1] == 'allow' then
local userId = matches[2]
allowBot(userId, chatId)
return 'Bot '..userId..' allowed'
end
if matches[1] == 'disallow' then
local userId = matches[2]
disallowBot(userId, chatId)
return 'Bot '..userId..' disallowed'
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABot(user) then
print('It\'s a bot!')
if isAntiBotEnabled(chatId) then
print('Anti bot is enabled')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('This bot is allowed')
end
end
end
end
end
return {
description = 'When bot enters group kick it.',
usage = {
'[/!]antibot enable: Enable Anti-bot on current chat',
'[/!]antibot disable: Disable Anti-bot on current chat',
'[/!]antibot allow <botId>: Allow <botId> on this chat',
'[/!]antibot disallow <botId>: Disallow <botId> on this chat'
},
patterns = {
'^[/!]antibot (allow) (%d+)$',
'^[/!]antibot (disallow) (%d+)$',
'^[/!]antibot (enable)$',
'^[/!]antibot (disable)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = run
}
| Java |
/* Cabal - Legacy Game Implementations
*
* Cabal is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* 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.
*
*/
// Based on the ScummVM (GPLv2+) file of the same name
#ifdef ENABLE_HE
#include "scumm/he/floodfill_he.h"
#include "scumm/he/intern_he.h"
#include "scumm/resource.h"
#include "scumm/scumm.h"
namespace Scumm {
static bool floodFillPixelCheck(int x, int y, const FloodFillState *ffs) {
int diffColor = ffs->color1 - ffs->color2;
if (x >= 0 && x < ffs->dst_w && y >= 0 && y < ffs->dst_h) {
uint8 color = *(ffs->dst + y * ffs->dst_w + x);
diffColor = color - ffs->color1;
}
return diffColor == 0;
}
static void floodFillProcessRect(FloodFillState *ffs, const Common::Rect *r) {
Common::Rect *dr = &ffs->dstBox;
if (dr->right >= dr->left && dr->top <= dr->bottom) {
int rw = r->right - r->left + 1;
int rh = r->bottom - r->top + 1;
assert(r->top + rh <= ffs->dst_h);
assert(r->left + rw <= ffs->dst_w);
uint8 *dst = ffs->dst + r->top * ffs->dst_w + r->left;
if (rw <= 1) {
--rh;
while (rh >= 0) {
*dst = ffs->color2;
dst += ffs->dst_w;
--rh;
}
} else {
--rh;
while (rh >= 0) {
memset(dst, ffs->color2, rw);
dst += ffs->dst_w;
--rh;
}
}
dr->extend(*r);
} else {
*dr = *r;
}
}
static void floodFillAddLine(FloodFillLine **ffl, int y, int x1, int x2, int dy) {
(*ffl)->y = y;
(*ffl)->x1 = x1;
(*ffl)->x2 = x2;
(*ffl)->inc = dy;
(*ffl)++;
}
static void floodFillProcess(int x, int y, FloodFillState *ffs, FloodFillPixelCheckCallback pixelCheckCallback) {
ffs->dstBox.left = ffs->dstBox.top = 12345;
ffs->dstBox.right = ffs->dstBox.bottom = -12345;
FloodFillLine **fillLineCur = &ffs->fillLineTableCur;
FloodFillLine **fillLineEnd = &ffs->fillLineTableEnd;
assert(*fillLineCur < *fillLineEnd);
if (ffs->srcBox.top <= y + 1 && ffs->srcBox.bottom >= y + 1) {
(*fillLineCur)->y = y;
(*fillLineCur)->x1 = x;
(*fillLineCur)->x2 = x;
(*fillLineCur)->inc = 1;
(*fillLineCur)++;
}
assert(*fillLineCur < *fillLineEnd);
if (ffs->srcBox.top <= y && ffs->srcBox.bottom >= y) {
(*fillLineCur)->y = y + 1;
(*fillLineCur)->x1 = x;
(*fillLineCur)->x2 = x;
(*fillLineCur)->inc = -1;
(*fillLineCur)++;
}
assert(ffs->fillLineTable <= *fillLineCur);
FloodFillLine **fillLineStart = fillLineCur;
while (ffs->fillLineTable < *fillLineStart) {
Common::Rect r;
int x_start;
FloodFillLine *fflCur = --(*fillLineCur);
int dy = fflCur->inc;
int x_end = fflCur->x2;
int x1 = fflCur->x1;
int x2 = fflCur->x1 + 1;
r.bottom = r.top = y = fflCur->y + fflCur->inc;
r.left = x2;
r.right = x1;
x = x1;
while (ffs->srcBox.left <= x) {
if (!(*pixelCheckCallback)(x, y, ffs)) {
break;
}
r.left = x;
--x;
}
if (r.right >= r.left && r.top <= r.bottom) {
floodFillProcessRect(ffs, &r);
}
if (x >= x1) goto skip;
x_start = x + 1;
if (x1 > x_start) {
assert(*fillLineEnd > *fillLineCur);
if (ffs->srcBox.top <= y - dy && ffs->srcBox.bottom >= y - dy) {
--x1;
floodFillAddLine(fillLineCur, y, x_start, x1, -dy);
}
}
x = x2;
while (x_start <= x_end) {
r.left = x;
r.top = y;
r.right = x - 1;
r.bottom = y;
while (ffs->srcBox.right >= x) {
if (!(*pixelCheckCallback)(x, y, ffs)) {
break;
}
r.right = x;
++x;
}
if (r.right >= r.left && r.top <= r.bottom) {
floodFillProcessRect(ffs, &r);
}
assert(ffs->fillLineTableCur < ffs->fillLineTableEnd);
if (ffs->srcBox.top <= y + dy && ffs->srcBox.bottom >= y + dy) {
floodFillAddLine(&ffs->fillLineTableCur, y, x_start, x - 1, dy);
}
x_start = x_end + 1;
if (x > x_start) {
assert(ffs->fillLineTableCur < ffs->fillLineTableEnd);
if (ffs->srcBox.top <= y - dy && ffs->srcBox.bottom >= y - dy) {
floodFillAddLine(&ffs->fillLineTableCur, y, x_start, x - 1, -dy);
}
}
skip:
++x;
while (x <= x_end) {
if ((*pixelCheckCallback)(x, y, ffs)) {
break;
}
++x;
}
x_start = x;
}
}
}
void floodFill(FloodFillParameters *ffp, ScummEngine_v90he *vm) {
uint8 *dst;
VirtScreen *vs = &vm->_virtscr[kMainVirtScreen];
if (ffp->flags & 0x8000) {
dst = vs->getBackPixels(0, vs->topline);
} else {
dst = vs->getPixels(0, vs->topline);
}
uint8 color = ffp->flags & 0xFF;
Common::Rect r;
r.left = r.top = 12345;
r.right = r.bottom = -12345;
FloodFillState *ffs = new FloodFillState;
ffs->fillLineTableCount = vs->getHeight() * 2;
ffs->fillLineTable = new FloodFillLine[ffs->fillLineTableCount];
ffs->color2 = color;
ffs->dst = dst;
ffs->dst_w = vs->getWidth();
ffs->dst_h = vs->getHeight();
ffs->srcBox = ffp->box;
ffs->fillLineTableCur = &ffs->fillLineTable[0];
ffs->fillLineTableEnd = &ffs->fillLineTable[ffs->fillLineTableCount];
if (ffp->x < 0 || ffp->y < 0 || ffp->x >= vs->getWidth() || ffp->y >= vs->getHeight()) {
ffs->color1 = color;
} else {
ffs->color1 = *(dst + ffp->y * vs->getWidth() + ffp->x);
}
debug(5, "floodFill() x=%d y=%d color1=%d ffp->flags=0x%X", ffp->x, ffp->y, ffs->color1, ffp->flags);
if (ffs->color1 != color) {
floodFillProcess(ffp->x, ffp->y, ffs, floodFillPixelCheck);
r = ffs->dstBox;
}
r.debugPrint(5, "floodFill() dirty_rect");
delete[] ffs->fillLineTable;
delete ffs;
vm->VAR(119) = 1;
if (r.left <= r.right && r.top <= r.bottom) {
if (ffp->flags & 0x8000) {
vm->restoreBackgroundHE(r);
} else {
++r.bottom;
vm->markRectAsDirty(kMainVirtScreen, r);
}
}
}
void Wiz::fillWizFlood(const WizParameters *params) {
if (params->processFlags & kWPFClipBox2) {
int px = params->box2.left;
int py = params->box2.top;
uint8 *dataPtr = _vm->getResourceAddress(rtImage, params->img.resNum);
if (dataPtr) {
int state = 0;
if (params->processFlags & kWPFNewState) {
state = params->img.state;
}
uint8 *wizh = _vm->findWrappedBlock(MKTAG('W','I','Z','H'), dataPtr, state, 0);
assert(wizh);
int c = READ_LE_UINT32(wizh + 0x0);
int w = READ_LE_UINT32(wizh + 0x4);
int h = READ_LE_UINT32(wizh + 0x8);
assert(c == 0);
Common::Rect imageRect(w, h);
if (params->processFlags & kWPFClipBox) {
if (!imageRect.intersects(params->box)) {
return;
}
imageRect.clip(params->box);
}
uint8 color = _vm->VAR(93);
if (params->processFlags & kWPFFillColor) {
color = params->fillColor;
}
if (imageRect.contains(px, py)) {
uint8 *wizd = _vm->findWrappedBlock(MKTAG('W','I','Z','D'), dataPtr, state, 0);
assert(wizd);
FloodFillState *ffs = new FloodFillState;
ffs->fillLineTableCount = h * 2;
ffs->fillLineTable = new FloodFillLine[ffs->fillLineTableCount];
ffs->color2 = color;
ffs->dst = wizd;
ffs->dst_w = w;
ffs->dst_h = h;
ffs->srcBox = imageRect;
ffs->fillLineTableCur = &ffs->fillLineTable[0];
ffs->fillLineTableEnd = &ffs->fillLineTable[ffs->fillLineTableCount];
if (px < 0 || py < 0 || px >= w || py >= h) {
ffs->color1 = color;
} else {
ffs->color1 = *(wizd + py * w + px);
}
debug(0, "floodFill() x=%d y=%d color1=%d", px, py, ffs->color1);
if (ffs->color1 != color) {
floodFillProcess(px, py, ffs, floodFillPixelCheck);
}
delete[] ffs->fillLineTable;
delete ffs;
}
}
}
_vm->_res->setModified(rtImage, params->img.resNum);
}
} // End of namespace Scumm
#endif // ENABLE_HE
| Java |
/* Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
DROP PROCEDURE IF EXISTS ps_setup_show_enabled_consumers;
DELIMITER $$
CREATE DEFINER='root'@'localhost' PROCEDURE ps_setup_show_enabled_consumers ()
COMMENT '
Description
-----------
Shows all currently enabled consumers.
Parameters
-----------
None
Example
-----------
mysql> CALL sys.ps_setup_show_enabled_consumers();
+---------------------------+
| enabled_consumers |
+---------------------------+
| events_statements_current |
| global_instrumentation |
| thread_instrumentation |
| statements_digest |
+---------------------------+
4 rows in set (0.05 sec)
'
SQL SECURITY INVOKER
DETERMINISTIC
READS SQL DATA
BEGIN
SELECT name AS enabled_consumers
FROM performance_schema.setup_consumers
WHERE enabled = 'YES';
END$$
DELIMITER ;
| Java |
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="zh-CN"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><meta http-equiv="Content-Language" content="zh-CN"><link href="stylesheet.css" media="all" rel="stylesheet" type="text/css">
<title>pg_database</title>
<script>var _hmt=_hmt||[]; (function(){ var hm=document.createElement("script"); hm.src="//hm.baidu.com/hm.js?d286c55b63a3c54a1e43d10d4c203e75"; var s=document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm,s); })();</script>
</head><body class="SECT1">
<div>
<table summary="Header navigation table" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><th colspan="5" align="center" valign="bottom">PostgreSQL 8.2.3 中文文档</th></tr>
<tr><td width="10%" align="left" valign="top"><a href="catalog-pg-conversion.html" accesskey="P">后退</a></td><td width="10%" align="left" valign="top"><a href="catalogs.html">快退</a></td><td width="60%" align="center" valign="bottom">章43. 系统表</td><td width="10%" align="right" valign="top"><a href="catalogs.html">快进</a></td><td width="10%" align="right" valign="top"><a href="catalog-pg-depend.html" accesskey="N">前进</a></td></tr>
</table>
<hr align="LEFT" width="100%"></div>
<div class="SECT1"><h1 class="SECT1"><a name="CATALOG-PG-DATABASE">43.15. <tt class="STRUCTNAME">pg_database</tt></a></h1><a name="AEN63288"></a>
<p><tt class="STRUCTNAME">pg_database</tt> 表存储关于可用数据库的信息。数据库是用 <a href="sql-createdatabase.html"><i>CREATE DATABASE</i></a> 创建的。参考<a href="managing-databases.html">章19</a>获取一些参数的详细含义。</p>
<p>和大多数系统表不同,<tt class="STRUCTNAME">pg_database</tt> 是在一个集群里的所有数据库共享的:每个集群只有一份 <tt class="STRUCTNAME">pg_database</tt> 拷贝,而不是每个数据库一份。</p>
<div class="TABLE"><a name="AEN63297"></a>
<p><b>表43-15. <tt class="STRUCTNAME">pg_database</tt> 字段</b></p>
<table border="1" class="CALSTABLE"><col><col><col><col>
<thead>
<tr><th>名字</th><th>类型</th><th>引用</th><th>描述</th></tr>
</thead>
<tbody>
<tr><td><tt class="STRUCTFIELD">datname</tt></td><td><tt class="TYPE">name</tt></td><td> </td><td>数据库名字</td></tr>
<tr><td><tt class="STRUCTFIELD">datdba</tt></td><td><tt class="TYPE">oid</tt></td><td><tt class="LITERAL"><a href="catalog-pg-authid.html"><tt class="STRUCTNAME">pg_authid</tt></a>.oid</tt></td><td>数据库所有人,通常为其创建者</td></tr>
<tr><td><tt class="STRUCTFIELD">encoding</tt></td><td><tt class="TYPE">int4</tt></td><td> </td><td>数据库的字符编码方式(<code class="FUNCTION">pg_encoding_to_char()</code> 能够将这个数字转换为相应的编码名称)</td></tr>
<tr><td><tt class="STRUCTFIELD">datistemplate</tt></td><td><tt class="TYPE">bool</tt></td><td> </td><td>如果为真则此数据库可以用于 <tt class="COMMAND">CREATE DATABASE</tt> 的 <tt class="LITERAL">TEMPLATE</tt> 子句,把新数据库创建为此数据库的克隆。</td></tr>
<tr><td><tt class="STRUCTFIELD">datallowconn</tt></td><td><tt class="TYPE">bool</tt></td><td> </td><td>如果为假则没有人可以连接到这个数据库。这个字段用于保护 <tt class="LITERAL">template0</tt> 数据库不被更改。</td></tr>
<tr><td><tt class="STRUCTFIELD">datconnlimit</tt></td><td><tt class="TYPE">int4</tt></td><td> </td><td>设置该数据库上允许的最大并发连接数,-1 表示无限制。</td></tr>
<tr><td><tt class="STRUCTFIELD">datlastsysoid</tt></td><td><tt class="TYPE">oid</tt></td><td> </td><td>数据库里最后一个系统 OID ;对 <span class="APPLICATION">pg_dump</span> 特别有用。</td></tr>
<tr><td><tt class="STRUCTFIELD">datfrozenxid</tt></td><td><tt class="TYPE">xid</tt></td><td> </td><td>该数据库中中所有在这个之前的事务 ID 已经被一个固定的("frozen")事务 ID 替换。这用于跟踪该数据库是否需要为了防止事务 ID 重叠或者允许收缩 <tt class="LITERAL">pg_clog</tt> 而进行清理。它是针对每个表的 <tt class="STRUCTNAME">pg_class</tt>.<tt class="STRUCTFIELD">relfrozenxid</tt> 中的最小值。</td></tr>
<tr><td><tt class="STRUCTFIELD">dattablespace</tt></td><td><tt class="TYPE">oid</tt></td><td><tt class="LITERAL"><a href="catalog-pg-tablespace.html"><tt class="STRUCTNAME">pg_tablespace</tt></a>.oid</tt></td><td>该数据库的缺省表空间。在这个数据库里,所有 <tt class="STRUCTNAME">pg_class</tt>.<tt class="STRUCTFIELD">reltablespace</tt> 为零的表都将保存在这个表空间里;特别要指出的是,所有非共享的系统表也都存放在这里。</td></tr>
<tr><td><tt class="STRUCTFIELD">datconfig</tt></td><td><tt class="TYPE">text[]</tt></td><td> </td><td>运行时配置变量的会话缺省值</td></tr>
<tr><td><tt class="STRUCTFIELD">datacl</tt></td><td><tt class="TYPE">aclitem[]</tt></td><td> </td><td>访问权限,参阅 <a href="sql-grant.html"><i>GRANT</i></a> 和 <a href="sql-revoke.html"><i>REVOKE</i></a> 获取详细描述。</td></tr>
</tbody>
</table>
</div>
</div>
<div>
<hr align="LEFT" width="100%">
<table summary="Footer navigation table" width="100%" border="0" cellpadding="0" cellspacing="0">
<tr><td width="33%" align="left" valign="top"><a href="catalog-pg-conversion.html" accesskey="P">后退</a></td><td width="34%" align="center" valign="top"><a href="index.html" accesskey="H">首页</a></td><td width="33%" align="right" valign="top"><a href="catalog-pg-depend.html" accesskey="N">前进</a></td></tr>
<tr><td width="33%" align="left" valign="top"><tt class="STRUCTNAME">pg_conversion</tt></td><td width="34%" align="center" valign="top"><a href="catalogs.html" accesskey="U">上一级</a></td><td width="33%" align="right" valign="top"><tt class="STRUCTNAME">pg_depend</tt></td></tr>
</table>
</div>
</body></html> | Java |
if (Meteor.isServer) {
var
//// A lookup-table whose keys are generated each time an ‘you.register’ form is rendered using the `babelslug()` method.
//// The key is a babelslug, followed by hyphen, followed by a Meteor connection ID (like a session ID for anon users).
//// The value is the unix timestamp in milliseconds, which allows us to clear out old and unused babelslugs.
//// Two examples are shown here:
recentBabelslugs = { // @todo for a multi-servo project, move this functionality to a shared mongoDB collection
// 'MagentaMouse-KukNJw4d4vjGzzrQa': 1409341347912,
// 'BlueChessCat-YYJWMWTPq7RFWdKr6': 1409341399283
}
//// Clear out stale elements in the `recentBabelslugs` lookup-table.
, recentBabelslugsHousekeeping = function () {
var key
, now = Date.now()
;
for (key in recentBabelslugs) {
if (15 * 60 * 1000 < now - recentBabelslugs[key]) { // allow a user 15 minutes to fill in the registration form
delete recentBabelslugs[key];
}
}
}
//// Check how many times a given `username` exists in the user database. If all’s well, this should only ever return `0` or `1`.
, usernameCount = function (username) {
return Meteor.users.find({ 'profile.username': username }).count();
}
//// BabelSlug, from Rich Plastow’s work, 2014-02-09.
, ucs2 = [
[ // animal
{ en:'slug' ,es:'babosa' ,ru:'\u0441\u043B\u0438\u0437\u043D\u044F\u043A',fr:'limace' ,zh:'\u86DE\u8753',ar:'\u064A\u0631\u0642\u0627\u0646\u0629' }
, { en:'mouse' ,es:'rat\u00F3n',ru:'\u043C\u044B\u0448\u044C' ,fr:'souris' ,zh:'\u9F20\u6807',ar:'\u0641\u0623\u0631' }
, { en:'cow' ,es:'vaca' ,ru:'\u043A\u043E\u0440\u043E\u0432\u0430' ,fr:'vache' ,zh:'\u725B' ,ar:'\u0628\u0642\u0631\u0629' }
, { en:'cat' ,es:'gato' ,ru:'\u043A\u043E\u0448\u043A\u0430' ,fr:'chat' ,zh:'\u732B' ,ar:'\u0642\u0637' }
, { en:'rabbit',es:'conejo' ,ru:'\u043A\u0440\u043E\u043B\u0438\u043A' ,fr:'lapin' ,zh:'\u5154' ,ar:'\u0623\u0631\u0646\u0628' }
, { en:'deer' ,es:'ciervo' ,ru:'\u043E\u043B\u0435\u043D\u044C' ,fr:'cerf' ,zh:'\u9E7F' ,ar:'\u0623\u064A\u0644' }
, { en:'bear' ,es:'oso' ,ru:'\u043C\u0435\u0434\u0432\u0435\u0434\u044C',fr:'ours' ,zh:'\u718A' ,ar:'\u062F\u064F\u0628\u0651' }
, { en:'frog' ,es:'rana' ,ru:'\u043B\u044F\u0433\u0443\u0448\u043A\u0430',fr:'grenouille',zh:'\u9752\u86D9',ar:'\u0636\u0641\u062F\u0639' }
]
// , [ // texture
// { en:'-' ,es:'-' ,ru:'-' ,fr:'-' ,zh:'-' ,ar:'-' }
// , { en:'dotted' ,es:'punteado',ru:[1087,1091,1085,1082,1090,1080,1088,1085,1099,1081],fr:'pointill\u00E9',zh:[26001,28857],ar:[1605,1606,1602,1591] }
// , { en:'striped',es:'rayas' ,ru:[1087,1086,1083,1086,1089,1072,1090,1099,1081] ,fr:'ray\u00E9' ,zh:[26465,32441],ar:[1605,1602,1604,1605] }
// , { en:'chess' ,es:'ajedrez' ,ru:[1096,1072,1093,1084,1072,1090,1099] ,fr:'\u00E9checs' ,zh:[26827] ,ar:[1588,1591,1585,1606,1580] }
// ]
, [ // color1
{ en:'-' ,es:'-' ,ru:'-' ,fr:'-' ,zh:'-' ,ar:'-' }
, { en:'red' ,es:'rojo' ,ru:[1082,1088,1072,1089,1085,1099,1081] ,fr:'rouge' ,zh:[32418] ,ar:[1571,1581,1605,1585] }
, { en:'orange' ,es:'naranja' ,ru:[1086,1088,1072,1085,1078,1077,1074,1099,1081],fr:'orange' ,zh:[27225] ,ar:[1575,1604,1576,1585,1578,1602,1575,1604,1610] }
, { en:'yellow' ,es:'amarillo',ru:[1078,1077,1083,1090,1099,1081] ,fr:'jaune' ,zh:[40644] ,ar:[1571,1589,1601,1585] }
, { en:'green' ,es:'verde' ,ru:[1079,1077,1083,1077,1085,1099,1081] ,fr:'vert' ,zh:[32511] ,ar:[1571,1582,1590,1585] }
// , { en:'cyan' ,es:'cian' ,ru:[1075,1086,1083,1091,1073,1086,1081] ,fr:'cyan' ,zh:[38738] ,ar:[1587,1605,1575,1608,1610] }
, { en:'blue' ,es:'azul' ,ru:[1089,1080,1085,1080,1081] ,fr:'bleu' ,zh:[34013] ,ar:[1571,1586,1585,1602] }
, { en:'purple' ,es:'magenta' ,ru:[1087,1091,1088,1087,1091,1088,1085,1099,1081],fr:'magenta',zh:[27915,32418],ar:[1571,1585,1580,1608,1575,1606,1610] } // @todo translate purple (these are for magenta)
]
, [ // emotion @todo convert remaining languages from 2014-Work/BabelSlug/README.md
{ en:'-' ,es:'-' ,fr:'-' }
, { en:'happy' ,es:'feliz' ,fr:'heureux' }
// , { en:'sad' ,es:'triste' ,fr:'triste' }
, { en:'laughing' ,es:'risa' ,fr:'rire' }
, { en:'sleepy' ,es:'soñoliento' ,fr:'somnolent' }
, { en:'surprised',es:'sorprendido',fr:'étonné' }
// , { en:'playful' ,es:'juguetón' ,fr:'espiègle' }
, { en:'confused' ,es:'confundido' ,fr:'embrouillé' }
]
]
//// Prepare an empty cache, which may contain HTML entities converted from `ucs2`, if required.
, html = (function () {
var i, j, l, m ,html = {};
for (i=0, l=ucs2.length; i<l; i++) {
html[i] = [];
for (j=0, m=ucs2[i].length; j<m; j++) {
html[i][j] = {};
}
}
return html
} ())
// !!!! `numberToPhrase()`, then `i` becomes `num`, and then `ucs2` becomes an array, and `i` is iterator !!!!
, numberToPhrase = function (number, options) {
var key, len, rem, word
, num = ~~(number < 0 ? -number : number) // ensure `num` is a positive whole number, or zero
, opt = options || {}
, l18n = ucs2[0][0][opt.l18n] ? opt.l18n : 'en' // set to English if the localization option is invalid or unspecified
, phrase = []
;
for (key in ucs2) {
len = ucs2[key].length;
rem = num % len;
if (! opt.format || 'ucs2' === opt.format) {
word = ucs2[key][rem][l18n];
// console.log('key ' + key + ' format ' + 'ucs2' + ' word ' + word);
} else if ('html' === opt.format) {
word = html[key][rem][l18n];
if (! word) {
word = html[key][rem][l18n] = ucs2[key][rem][l18n].replace(/[\u00A0-\u2666]/g, function(c) {
return '&#' + c.charCodeAt(0) + ';';
});
// console.log('ADD TO CACHE key ' + key + ' format ' + 'html' + ' word ' + word);
} else {
// console.log('GET IN CACHE key ' + key + ' format ' + 'html' + ' word ' + word);
}
} else {
// @todo format error
}
if ('-' !== word) { phrase.unshift(word); }
num = ~~(num / len); // prepare for the next part in `ucs2`
if (0 === num) { break; } // low numbers don't need to step through every section in `ucs2`
}
return phrase.join('-');
}
;
Meteor.methods({
babelslug: function () {
var i, key, babelslug;
if (this.isSimulation) { return; } // clientside stub (return value is ignored)
//// Housekeeping on the `recentBabelslugs` lut.
recentBabelslugsHousekeeping();
//// Try, 200 times, to find a username which has not been taken. @todo this is quite brute-force ... can we come up with a more elegant solution?
for (i=200; i>0; i--) {
babelslug = numberToPhrase( Math.floor(Math.random() * 50000) );
if ( 3 === babelslug.split('-').length && ! recentBabelslugs[babelslug] && ! usernameCount(babelslug) ) { break; } // we are only using three-part usernames at present
}
if (! i) { throw new Meteor.Error(500, "Cannot generate a username! Please email " + Config.about.webmaster); } // @todo check `(! i)` can ever be truthy
recentBabelslugs[babelslug] = { // later, when the form is submitted, we will check that the babelslug value is expected
now: Date.now() // allows `recentBabelslugsHousekeeping()` to find stale babelslugs
, cid: this.connection.id
}
return babelslug + '_' + this.connection.id; // @todo is `this.connection.id` ever some unexpected value, for example `null`?
}
});
Accounts.onCreateUser(function (options, user) {
var babelslug, connectionId;
//// Housekeeping on the `recentBabelslugs` lut.
recentBabelslugsHousekeeping();
//// Validate the value of `<input id="AT_field_you-babelslug" ...>`.
babelslug = options.profile['you-babelslug'].split('_')[0];
connectionId = options.profile['you-babelslug'].split('_')[1];
if (! babelslug || ! connectionId) {
throw new Meteor.Error(500, "The ‘username’ field is invalid."); // @todo better error-code than 500?
}
if (! recentBabelslugs[babelslug]) {
throw new Meteor.Error(500, "Your registration form expired after 15 minutes. Please refresh the browser and try again."); // The ‘username’ value is unexpected, so this may actually be a hack attempt
}
if ( usernameCount(babelslug) ) {
throw new Meteor.Error(500, "The ‘username’ is already in use."); // prevent two `Meteor.user` records having the same username, which could happen on a multi-servo project, until we change `recentBabelslugs` to a shared mongoDB collection @todo
}
//// Remove the babelslug, as it’s not needed any more.
delete recentBabelslugs[babelslug];
//// Record the username (‘info@loop.coop’ gets a special username).
options.profile = options.profile || {};
options.profile.username = 'info@loop.coop' === options.email ? 'red-cat' : babelslug;
//// Record other registration data.
if (options.profile['you-age-group-code']) { options.profile.agc = options.profile['you-age-group-code']; }
if (options.profile['you-based-in-code']) { options.profile.bic = options.profile['you-based-in-code']; }
if (options.profile['you-hear-about-code']) { options.profile.hac = options.profile['you-hear-about-code']; }
if (options.profile['you-hear-about-text']) { options.profile.hat = options.profile['you-hear-about-text']; }
if (options.profile['you-newsletter-opt']) { options.profile.nlo = options.profile['you-newsletter-opt']; }
//// The registration is valid, so record it as usual. http://docs.meteor.com/#accounts_oncreateuser
user.profile = options.profile;
return user;
});
}
| Java |
#pragma once
#include <string>
class GameSettings
{
private:
int m_nFPS = 60;
std::string m_strPath = "../Settings.ini";
private:
GameSettings();
void Load();
void Save();
static GameSettings& GetInstance();
public:
static int FPS();
};
| Java |
package org.rebecalang.modeltransformer.ros.timedrebeca;
import java.util.HashMap;
import java.util.Map;
import org.rebecalang.compiler.modelcompiler.corerebeca.CoreRebecaTypeSystem;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.BinaryExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.CastExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.DotPrimary;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.Expression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.FieldDeclaration;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.Literal;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.MsgsrvDeclaration;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.NonDetExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.PlusSubExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.PrimaryExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.ReactiveClassDeclaration;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.RebecInstantiationPrimary;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.RebecaModel;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.TermPrimary;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.TernaryExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.UnaryExpression;
import org.rebecalang.compiler.modelcompiler.corerebeca.objectmodel.VariableDeclarator;
import org.rebecalang.compiler.modelcompiler.timedrebeca.TimedRebecaTypeSystem;
import org.rebecalang.compiler.utils.CodeCompilationException;
import org.rebecalang.compiler.utils.ExceptionContainer;
import org.rebecalang.compiler.utils.Pair;
import org.rebecalang.modeltransformer.StatementTransformingException;
import org.rebecalang.modeltransformer.ros.Utilities;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class TimedRebeca2ROSExpressionTransformer {
public final static String NEW_LINE = "\r\n";
public final static String TAB = "\t";
static Integer i = 0;
private String modelName;
private ReactiveClassDeclaration rc;
private RebecaModel rebecaModel;
private Map <Pair<String, String>, String> methodCalls = new HashMap<Pair<String, String>, String>();
@Autowired
TimedRebecaTypeSystem timedRebecaTypeSystem;
@Autowired
ExceptionContainer exceptionContainer;
public void prepare(String modelName, ReactiveClassDeclaration rc, RebecaModel rebecaModel) {
this.modelName = modelName;
this.rebecaModel = rebecaModel;
this.rc = rc;
}
public String translate(Expression expression) {
String retValue = "";
if (expression instanceof TernaryExpression) {
TernaryExpression tExpression = (TernaryExpression)expression;
Expression condition = tExpression.getCondition();
retValue = "(" + (translate(condition)) + ")";
retValue += " ? " + "(" + translate(tExpression.getLeft()) + ")";
retValue += " : " + "(" + translate(tExpression.getRight()) + ")";
} else if (expression instanceof BinaryExpression) {
BinaryExpression bExpression = (BinaryExpression) expression;
String op = bExpression.getOperator();
retValue = translate(bExpression.getLeft()) +
" " + op + " " + translate(bExpression.getRight());
} else if (expression instanceof UnaryExpression) {
UnaryExpression uExpression = (UnaryExpression) expression;
retValue = uExpression.getOperator() + " " + translate(uExpression.getExpression());
} else if (expression instanceof CastExpression) {
exceptionContainer.addException(new StatementTransformingException("This version of transformer does not supprt " +
"\"cast\" expression.",
expression.getLineNumber(), expression.getCharacter()));
} else if (expression instanceof NonDetExpression) {
NonDetExpression nonDetExpression = (NonDetExpression)expression;
int numberOfChoices = nonDetExpression.getChoices().size();
retValue += nonDetExpression.getType().getTypeName();
retValue += "int numberOfChoices = " + Integer.toString(numberOfChoices) + ";" + NEW_LINE;
retValue += "int choice = " + "rand() % " + Integer.toString(numberOfChoices) + ";" + NEW_LINE;
int index = numberOfChoices;
for (Expression nonDetChoice : ((NonDetExpression)expression).getChoices()) {
retValue += "if (" + "choice ==" + Integer.toString(numberOfChoices - index) + ")" + NEW_LINE;
retValue += ((NonDetExpression)nonDetChoice);
index ++;
}
} else if (expression instanceof Literal) {
Literal lExpression = (Literal) expression;
retValue = lExpression.getLiteralValue();
if (retValue.equals("null"))
retValue = "\"dummy\"";
} else if (expression instanceof PlusSubExpression) {
retValue = translate(((PlusSubExpression)expression).getValue()) +
((PlusSubExpression)expression).getOperator();
} else if (expression instanceof PrimaryExpression) {
PrimaryExpression pExpression = (PrimaryExpression) expression;
retValue = translatePrimaryExpression(pExpression);
}
else {
exceptionContainer.addException(
new StatementTransformingException("Unknown translation rule for expression type "
+ expression.getClass(), expression.getLineNumber(), expression.getCharacter()));
}
return retValue;
}
protected String translatePrimaryExpression(PrimaryExpression pExpression) {
String retValue = "";
if (pExpression instanceof DotPrimary) {
DotPrimary dotPrimary = (DotPrimary) pExpression;
retValue = translateDotPrimary(dotPrimary);
} else if (pExpression instanceof TermPrimary) {
retValue = translatePrimaryTermExpression((TermPrimary) pExpression);
} else if (pExpression instanceof RebecInstantiationPrimary) {
RebecInstantiationPrimary rip = (RebecInstantiationPrimary) pExpression;
boolean hasMoreVariable = false;
String args = "";
try {
ReactiveClassDeclaration rcd = (ReactiveClassDeclaration) timedRebecaTypeSystem.getMetaData(rip.getType());
if (!rcd.getStatevars().isEmpty()) {
args += " , ";
for (FieldDeclaration fd : rcd.getStatevars()) {
for (VariableDeclarator vd : fd.getVariableDeclarators()) {
hasMoreVariable = true;
String typeInit = fd.getType() == CoreRebecaTypeSystem.BOOLEAN_TYPE ? "false" :
fd.getType().canTypeCastTo(CoreRebecaTypeSystem.INT_TYPE) ? "0" : "\"dummy\"";
args += "(" + rcd.getName() + "-" + vd.getVariableName() + " |-> " + typeInit + ") " ;
}
}
}
if (!hasMoreVariable)
args += "emptyValuation";
} catch (CodeCompilationException e) {
e.printStackTrace();
}
args += ",";
hasMoreVariable = false;
String typeName = rip.getType().getTypeName();
for (Expression expression : rip.getBindings()) {
args += " arg(" + translate(expression) + ")";
hasMoreVariable = true;
}
for (Expression expression : rip.getArguments()) {
args += " arg(" + translate(expression) + ")";
hasMoreVariable = true;
}
if (!hasMoreVariable)
args += "noArg";
retValue = " new (" + typeName + args + ")";
} else {
exceptionContainer.addException(new StatementTransformingException("Unknown translation rule for initializer type "
+ pExpression.getClass(), pExpression.getLineNumber(), pExpression.getCharacter()));
}
return retValue;
}
private String translateDotPrimary(DotPrimary dotPrimary) {
String retValue = "";
if (!(dotPrimary.getLeft() instanceof TermPrimary) || !(dotPrimary.getRight() instanceof TermPrimary)) {
exceptionContainer.addException(new StatementTransformingException("This version of transformer does not supprt " +
"nested record access expression.",
dotPrimary.getLineNumber(), dotPrimary.getCharacter()));
} else {
// TODO: Modified by Ehsan as the return vlaue type of message servers is always set to MSGSRV_TYPE
// if(TypesUtilities.getInstance().getSuperType(dotPrimary.getRight().getType()) == TypesUtilities.MSGSRV_TYPE) {
if(dotPrimary.getRight().getType() == CoreRebecaTypeSystem.MSGSRV_TYPE) {
retValue = mapToROSPublishing(dotPrimary);
}
}
return retValue;
}
private String mapToROSPublishing(DotPrimary dotPrimary) {
String retValue = "";
/* map to ROS Publishing */
retValue = modelName + "::" + ((TermPrimary)dotPrimary.getRight()).getName()
+ " " + "pubMsg" + i.toString() + ";" + NEW_LINE;
/* fill the ROS message fields with the arguments to be published */
int argumentIndex = 0;
for (Expression expression : ((TermPrimary)dotPrimary.getRight()).getParentSuffixPrimary().getArguments()) {
ReactiveClassDeclaration toClass = null;
TermPrimary toRebec = (TermPrimary)dotPrimary.getLeft();
toClass = Utilities.findKnownReactiveClass(rc, toRebec.getName(), rebecaModel);
String toMsgsrvName = ((TermPrimary)dotPrimary.getRight()).getName();
MsgsrvDeclaration toMsgsrv = Utilities.findTheMsgsrv(toClass, toMsgsrvName);
String argumentName = toMsgsrv.getFormalParameters().get(argumentIndex).getName();
retValue += "pubMsg" + i.toString() + "." + argumentName + " = " + translate(expression) + ";" + NEW_LINE;
argumentIndex ++;
}
retValue += "pubMsg" + i.toString() + "." + "sender" + "=" + "sender" + ";" + NEW_LINE;
retValue += ((TermPrimary) dotPrimary.getLeft()).getName() + "_" + ((TermPrimary)dotPrimary.getRight()).getName() + "_pub"
+ "." + "publish(" + "pubMsg" + i.toString() + ")" + ";" + NEW_LINE;
i ++; /* to prevent from repeated names */
/* end of publishing */
/* storing the name of callee rebec and the name of called msgsrv in order to declare publishers */
Pair<String, String> methodCall = new Pair<String, String>(
((TermPrimary)dotPrimary.getLeft()).getName(), ((TermPrimary)dotPrimary.getRight()).getName() );
methodCalls.put(methodCall, "");
//ReactiveClassDeclaration rcd = (ReactiveClassDeclaration) TransformingContext.getInstance().lookupInContext("current-reactive-class");
//retValue = ((TermPrimary) dotPrimary.getLeft()).getName();
//String typeName = TypesUtilities.getTypeName(((TermPrimary) dotPrimary.getLeft()).getType());
//System.out.println(typeName);
return retValue;
}
private String translatePrimaryTermExpression(TermPrimary pExpression) {
String retValue = "";
if(pExpression.getName().equals("assertion") ||
pExpression.getName().equals("after") ||
pExpression.getName().equals("deadline")){
return retValue;
}
if(pExpression.getName().equals("delay"))
retValue += "sleep";
else if(pExpression.getName().equals("sender"))
return "thisMsg.sender";
else
retValue += pExpression.getName();
if( pExpression.getParentSuffixPrimary() != null) {
retValue += "(";
for(Expression argument: pExpression.getParentSuffixPrimary().getArguments()) {
retValue += translate(argument) + ",";
}
if(! pExpression.getParentSuffixPrimary().getArguments().isEmpty()) {
retValue = retValue.substring(0, retValue.length() - 1);
}
retValue += ")";
}
//To support movement in ROS
if (retValue.compareTo("Move(1,0)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if (retValue.compareTo("Move(0,1)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if (retValue.compareTo("Move(-1,0)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if (retValue.compareTo("Move(0,-1)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if(retValue.compareTo("Move(1,1)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if(retValue.compareTo("Move(1,-1)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if(retValue.compareTo("Move(-1,1)")==0)
{
//ROSCode to publish on CM_Vel topic
}
else if(retValue.compareTo("Move(-1,-1)")==0)
{
//ROSCode to publish on CM_Vel topic
}
/* to support arrays */
for(Expression ex: pExpression.getIndices()) {
retValue += "[" + translate(ex) + "]";
}
return retValue;
}
public Map <Pair<String, String>, String> getMethodCalls() {
return methodCalls;
}
} | Java |
/*
* Copyright (C) 2007 Red Hat, Inc. All rights reserved.
*
* This file is part of LVM2.
*
* This copyrighted material is made available to anyone wishing to use,
* modify, copy, or redistribute it subject to the terms and conditions
* of the GNU Lesser General Public License v.2.1.
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef _LVM_UTIL_H
#define _LVM_UTIL_H
#define min(a, b) ({ typeof(a) _a = (a); \
typeof(b) _b = (b); \
(void) (&_a == &_b); \
_a < _b ? _a : _b; })
#define max(a, b) ({ typeof(a) _a = (a); \
typeof(b) _b = (b); \
(void) (&_a == &_b); \
_a > _b ? _a : _b; })
#define uninitialized_var(x) x = x
#define KERNEL_VERSION(major, minor, release) (((major) << 16) + ((minor) << 8) + (release))
#endif
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Mon Jul 03 11:07:20 PDT 2000 -->
<TITLE>
: Class Ins_dup2
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" ID="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT ID="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-summary.html"><FONT ID="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" ID="NavBarCell1Rev"> <FONT ID="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-tree.html"><FONT ID="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT ID="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../index-all.html"><FONT ID="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT ID="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../ojvm/loading/instructions/Ins_dup_x2.html"><B>PREV CLASS</B></A>
<A HREF="../../../ojvm/loading/instructions/Ins_dup2_x1.html"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="Ins_dup2.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
<TR>
<TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2">
SUMMARY: INNER | <A HREF="#fields_inherited_from_class_ojvm.loading.instructions.Instruction">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<!-- ======== START OF CLASS DATA ======== -->
<H2>
<FONT SIZE="-1">
ojvm.loading.instructions</FONT>
<BR>
Class Ins_dup2</H2>
<PRE>
java.lang.Object
|
+--<A HREF="../../../ojvm/loading/instructions/Instruction.html">ojvm.loading.instructions.Instruction</A>
|
+--<B>ojvm.loading.instructions.Ins_dup2</B>
</PRE>
<HR>
<DL>
<DT>public class <B>Ins_dup2</B><DT>extends <A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></DL>
<P>
The encapsulation of a dup2 instruction.
<P>
<HR>
<P>
<!-- ======== INNER CLASS SUMMARY ======== -->
<!-- =========== FIELD SUMMARY =========== -->
<A NAME="fields_inherited_from_class_ojvm.loading.instructions.Instruction"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" ID="TableSubHeadingColor">
<TD><B>Fields inherited from class ojvm.loading.instructions.<A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></B></TD>
</TR>
<TR BGCOLOR="white" ID="TableRowColor">
<TD><CODE><A HREF="../../../ojvm/loading/instructions/Instruction.html#length">length</A>,
<A HREF="../../../ojvm/loading/instructions/Instruction.html#OPCODE">OPCODE</A>,
<A HREF="../../../ojvm/loading/instructions/Instruction.html#opcodeName">opcodeName</A></CODE></TD>
</TR>
</TABLE>
<!-- ======== CONSTRUCTOR SUMMARY ======== -->
<A NAME="constructor_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" ID="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Constructor Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" ID="TableRowColor">
<TD><CODE><B><A HREF="../../../ojvm/loading/instructions/Ins_dup2.html#Ins_dup2(ojvm.loading.instructions.InstructionInputStream)">Ins_dup2</A></B>(<A HREF="../../../ojvm/loading/instructions/InstructionInputStream.html">InstructionInputStream</A> classFile)</CODE>
<BR>
</TD>
</TR>
</TABLE>
<!-- ========== METHOD SUMMARY =========== -->
<A NAME="method_summary"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" ID="TableHeadingColor">
<TD COLSPAN=2><FONT SIZE="+2">
<B>Method Summary</B></FONT></TD>
</TR>
<TR BGCOLOR="white" ID="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> void</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../ojvm/loading/instructions/Ins_dup2.html#accept(ojvm.operations.InstructionVisitor)">accept</A></B>(<A HREF="../../../ojvm/operations/InstructionVisitor.html">InstructionVisitor</A> iv)</CODE>
<BR>
</TD>
</TR>
<TR BGCOLOR="white" ID="TableRowColor">
<TD ALIGN="right" VALIGN="top" WIDTH="1%"><FONT SIZE="-1">
<CODE> java.lang.String</CODE></FONT></TD>
<TD><CODE><B><A HREF="../../../ojvm/loading/instructions/Ins_dup2.html#toString()">toString</A></B>()</CODE>
<BR>
</TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_ojvm.loading.instructions.Instruction"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" ID="TableSubHeadingColor">
<TD><B>Methods inherited from class ojvm.loading.instructions.<A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></B></TD>
</TR>
<TR BGCOLOR="white" ID="TableRowColor">
<TD><CODE><A HREF="../../../ojvm/loading/instructions/Instruction.html#getLength()">getLength</A>,
<A HREF="../../../ojvm/loading/instructions/Instruction.html#isActualInstruction()">isActualInstruction</A></CODE></TD>
</TR>
</TABLE>
<A NAME="methods_inherited_from_class_java.lang.Object"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#EEEEFF" ID="TableSubHeadingColor">
<TD><B>Methods inherited from class java.lang.Object</B></TD>
</TR>
<TR BGCOLOR="white" ID="TableRowColor">
<TD><CODE>clone,
equals,
finalize,
getClass,
hashCode,
notify,
notifyAll,
wait,
wait,
wait</CODE></TD>
</TR>
</TABLE>
<P>
<!-- ============ FIELD DETAIL =========== -->
<!-- ========= CONSTRUCTOR DETAIL ======== -->
<A NAME="constructor_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" ID="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Constructor Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="Ins_dup2(ojvm.loading.instructions.InstructionInputStream)"><!-- --></A><H3>
Ins_dup2</H3>
<PRE>
public <B>Ins_dup2</B>(<A HREF="../../../ojvm/loading/instructions/InstructionInputStream.html">InstructionInputStream</A> classFile)</PRE>
<DL>
</DL>
<!-- ============ METHOD DETAIL ========== -->
<A NAME="method_detail"><!-- --></A>
<TABLE BORDER="1" CELLPADDING="3" CELLSPACING="0" WIDTH="100%">
<TR BGCOLOR="#CCCCFF" ID="TableHeadingColor">
<TD COLSPAN=1><FONT SIZE="+2">
<B>Method Detail</B></FONT></TD>
</TR>
</TABLE>
<A NAME="accept(ojvm.operations.InstructionVisitor)"><!-- --></A><H3>
accept</H3>
<PRE>
public void <B>accept</B>(<A HREF="../../../ojvm/operations/InstructionVisitor.html">InstructionVisitor</A> iv)
throws <A HREF="../../../ojvm/data/JavaException.html">JavaException</A></PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD><A HREF="../../../ojvm/loading/instructions/Instruction.html#accept(ojvm.operations.InstructionVisitor)">accept</A> in class <A HREF="../../../ojvm/loading/instructions/Instruction.html">Instruction</A></DL>
</DD>
</DL>
<HR>
<A NAME="toString()"><!-- --></A><H3>
toString</H3>
<PRE>
public java.lang.String <B>toString</B>()</PRE>
<DL>
<DD><DL>
<DT><B>Overrides:</B><DD>toString in class java.lang.Object</DL>
</DD>
</DL>
<!-- ========= END OF CLASS DATA ========= -->
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" ID="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../overview-summary.html"><FONT ID="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-summary.html"><FONT ID="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" ID="NavBarCell1Rev"> <FONT ID="NavBarFont1Rev"><B>Class</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="package-tree.html"><FONT ID="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../deprecated-list.html"><FONT ID="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../index-all.html"><FONT ID="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" ID="NavBarCell1"> <A HREF="../../../help-doc.html"><FONT ID="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../ojvm/loading/instructions/Ins_dup_x2.html"><B>PREV CLASS</B></A>
<A HREF="../../../ojvm/loading/instructions/Ins_dup2_x1.html"><B>NEXT CLASS</B></A></FONT></TD>
<TD BGCOLOR="white" ID="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="Ins_dup2.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
<TR>
<TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2">
SUMMARY: INNER | <A HREF="#fields_inherited_from_class_ojvm.loading.instructions.Instruction">FIELD</A> | <A HREF="#constructor_summary">CONSTR</A> | <A HREF="#method_summary">METHOD</A></FONT></TD>
<TD VALIGN="top" ID="NavBarCell3"><FONT SIZE="-2">
DETAIL: FIELD | <A HREF="#constructor_detail">CONSTR</A> | <A HREF="#method_detail">METHOD</A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
</BODY>
</HTML>
| Java |
#!/usr/bin/perl
=head1 NAME
TMI pokal_sent.pl
=head1 SYNOPSIS
TBD
=head1 AUTHOR
admin@socapro.com
=head1 CHANGELOG
2015-06-09 Thomas: Added Session Management
=head1 COPYRIGHT
Copyright (c) 2015, SocaPro Inc.
Created 2015-06-09
=cut
use lib '/tmapp/tmsrc/cgi-bin/';
use TMSession;
my $session = TMSession::getSession(tmi_login => 1);
my $trainer = $session->getUser();
my $leut = $trainer;
use CGI;
print "Content-type: text/html\n\n";
$query = new CGI;
$url = $query->param('url');
$tip[1] = $query->param('30....');
$tip[2] = $query->param('31....');
$tip[3] = $query->param('32....');
$tip[4] = $query->param('33....');
$tip[5] = $query->param('34....');
$tip[6] = $query->param('35....');
$tip[7] = $query->param('36....');
$tip[8] = $query->param('37....');
$tip[9] = $query->param('38....');
$tip[10] = $query->param('39....');
$tips = $query->param('tips');
$pokal = $query->param('pokal');
open(D7,"/tmdata/tmi/pokal/tip_status.txt");
$tip_status = <D7> ;
chomp $tip_status;
close(D7);
if ( $tip_status != 1 ) {
print "<title>Pokal Tipabgabe</title><font face=verdana size=2><br><br><br><br><br><b>Die Tipabgabefrist ist bereits abgelaufen ...\n";
exit ;
}
print "Content-type: text/html\n\n";
print "<title>Pokal Tipabgabe</title><body bgcolor=white text=black>\n";
print "<form name=Testform action=/cgi-mod/tmi/login.pl method=post></form>";
print "<script language=JavaScript>";
print" function AbGehts()";
print" {";
print" document.Testform.submit();";
print" }";
print" window.setTimeout(\"AbGehts()\",7000);";
print" </script>";
print "<p align=left><body bgcolor=white text=black link=darkred link=darkred> \n";
require "/tmapp/tmsrc/cgi-bin/tag.pl" ;
$agb = 0;
for ($x=1 ; $x<=10 ; $x++ ) {
if ( $tip[$x] ne "0&0" ) { $abg++ }
$reihe = $reihe . $tip[$x] . '.' ;
}
if ( $abg != $tips ) {
print "<font face=verdana size=2><br><br><br><br><br><b>Die Anzahl Ihrer abgegebenen Tips ist nicht korrekt ...<br>Sie haben $abg Tips anstatt der korrekten $tips Tips abgegeben .<br>Bitte kehren Sie zur Tipabgabe zurueck und korregieren Sie Ihre Tipabgabe .\n";
exit ;
}
$rf ="0";
$rx = "x" ;
my $liga = 0;
if ( $liga > 9 ) { $rf = "" }
$suche = '&'.$trainer.'&' ;
$s = 0;
open(D2,"/tmdata/tmi/history.txt");
while(<D2>) {
$s++;
if ($_ =~ /$suche/) {
@lor = split (/&/, $_);
$liga = $s ;
}
}
close(D2);
$id_verein = 0;
$y = 0;
for ( $x = 1; $x < 19; $x++ )
{
$y++;
chomp $lor[$y];
$data[$x] = $lor[$y];
$teams[$x] = $lor[$y];
$team[$x] = $lor[$y];
$y++;
chomp $lor[$y];
$datb[$x] = $lor[$y];
if ( $datb[$x] eq $trainer ) {$id = $x }
if ( $datb[$x] eq $trainer ) {$id_verein = (($liga-1)*18)+ $x }
if ( $datb[$x] eq $trainer ) {$verein = $data[$x] }
$y++;
chomp $lor[$y];
$datc[$x] = $lor[$y];
if ( $datb[$x] eq $trainer ) {$recipient = $datc[$x] }
}
$rr = 0;
$li=0;
$liga=0;
open(D2,"/tmdata/tmi/history.txt");
while(<D2>) {
$li++;
@vereine = split (/&/, $_);
$y = 0;
for ( $x = 1; $x < 19; $x++ )
{
$rr++;
$y++;
chomp $verein[$y];
$teams[$rr] = $vereine[$y];
$team[$rr] = $vereine[$y];
$y++;
chomp $verein[$y];
$datb[$rr] = $vereine[$y];
$y++;
chomp $verein[$y];
$datc[$rr] = $vereine[$y];
}
}
close(D2);
my $url = "/tmdata/tmi/pokal/tips/" ;
if ( $id_verein<10 ) { $url = $url . '0' }
if ( $id_verein<100 ) { $url = $url . '0' }
if ( $id_verein<1000 ) { $url = $url . '0' }
open(D7,"/tmdata/tmi/pokal/pokal_datum.txt");
$spielrunde_ersatz = <D7> ;
chomp $spielrunde_ersatz;
close(D7);
$runde = $spielrunde_ersatz;
$url=$url.$id_verein. '-' . $pokal . '-' . $runde . '.txt' ;
open(D2,">$url");
print D2 "$reihe\n";
close (D2) ;
print "<font face=verdana size=2><br><br><br><b> Ihre Tipabgabe wurde registriert .<br> Sie werden zu Ihrem LogIn Bereich weitergeleitet ...\n";
| Java |
/*
* The ManaPlus Client
* Copyright (C) 2013-2015 The ManaPlus Developers
*
* This file is part of The ManaPlus Client.
*
* 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
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "utils/fuzzer.h"
#ifdef USE_FUZZER
#include "client.h"
#include "logger.h"
#include "settings.h"
#include "utils/stringutils.h"
#include "debug.h"
namespace
{
Logger *fuzz = nullptr;
int fuzzRand = 50;
} // namespace
void Fuzzer::init()
{
fuzz = new Logger;
fuzz->setLogFile(settings.localDataDir + "/fuzzer.log");
unsigned int sr = time(nullptr);
fuzz->log("Srand: %u", sr);
srand(sr);
}
bool Fuzzer::conditionTerminate(const char *const name)
{
if ((rand() % 100) <= fuzzRand)
{
fuzz->log("deleted: %s", name);
return true;
}
fuzz->log("passed: %s", name);
return false;
}
#endif
| Java |
<?php
/**
* HTML attribute filters.
* Most of these functions filter the generic values from the framework found in hoot/functions/attr.php
* Attributes for non-generic structural elements (mostly theme specific) can be loaded in this file.
*
* @package hoot
* @subpackage responsive-brix
* @since responsive-brix 1.0
*/
/* Modify Original Filters from Framework */
add_filter( 'hoot_attr_content', 'hoot_theme_attr_content' );
add_filter( 'hoot_attr_sidebar', 'hoot_theme_attr_sidebar', 10, 2 );
/* New Theme Filters */
add_filter( 'hoot_attr_page_wrapper', 'hoot_theme_attr_page_wrapper' );
add_filter( 'hoot_attr_page_template_content', 'hoot_theme_page_template_content', 10, 2 );
/* Misc Filters */
add_filter( 'hoot_attr_social_icons_icon', 'hoot_theme_attr_social_icons_icon', 10, 2 );
/**
* Modify Main content container of the page attributes.
*
* @since 1.0
* @access public
* @param array $attr
* @return array
*/
function hoot_theme_attr_content( $attr ) {
$layout_class = hoot_main_layout_class( 'content' );
if ( !empty( $layout_class ) ) {
if ( isset( $attr['class'] ) )
$attr['class'] .= ' ' . $layout_class;
else
$attr['class'] = $layout_class;
}
return $attr;
}
/**
* Modify Sidebar attributes.
*
* @since 1.0
* @access public
* @param array $attr
* @param string $context
* @return array
*/
function hoot_theme_attr_sidebar( $attr, $context ) {
if ( !empty( $context ) && $context == 'primary' ) {
$layout_class = hoot_main_layout_class( 'primary-sidebar' );
if ( !empty( $layout_class ) ) {
if ( isset( $attr['class'] ) )
$attr['class'] .= ' ' . $layout_class;
else
$attr['class'] = $layout_class;
}
}
return $attr;
}
/**
* Page wrapper attributes.
*
* @since 1.0
* @access public
* @param array $attr
* @return array
*/
function hoot_theme_attr_page_wrapper( $attr ) {
$site_layout = hoot_get_mod( 'site_layout' );
$attr['class'] = ( $site_layout == 'boxed' ) ? 'grid site-boxed' : 'site-stretch';
$attr['class'] .= ' page-wrapper';
return $attr;
}
/**
* Main content container of the page attributes when a page template is being displayed
*
* @since 1.0
* @access public
* @param array $attr
* @param string $context
* @return array
*/
function hoot_theme_page_template_content( $attr, $context ) {
if ( is_page_template() && $context == 'none' ) {
$attr['id'] = 'content';
$attr['class'] = 'content sidebar-none';
$attr['role'] = 'main';
$attr['itemprop'] = 'mainContentOfPage';
$template_slug = basename( get_page_template(), '.php' );
$attr['class'] .= ' ' . sanitize_html_class( 'content-' . $template_slug );
} elseif ( function_exists( 'hoot_attr_content' ) ) {
// Get page attributes for main content container of a non-template regular page
$attr = apply_filters( "hoot_attr_content", $attr, $context );
}
return $attr;
}
/**
* Social Icons Widget - Icons
*
* @since 2.0
* @access public
* @param array $attr
* @param string $context
* @return array
*/
function hoot_theme_attr_social_icons_icon( $attr, $context ) {
$attr['class'] = 'social-icons-icon';
if ( $context != 'email' )
$attr['target'] = '_blank';
return $attr;
} | Java |
Photoshop files, icons, transparency images, anything that has been edited and is not an original photograph.
| Java |
var iconhead={
title:"Icon Heading Shortcode",
id :'oscitas-form-iconhead',
pluginName: 'iconhead',
setRowColors:false
};
(function() {
_create_tinyMCE_options(iconhead,800);
})();
function create_oscitas_iconhead(pluginObj){
if(jQuery(pluginObj.hashId).length){
jQuery(pluginObj.hashId).remove();
}
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var iconhead_fa='';
/*if(ebs.ebs_fa_inclusion==1){
iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>';
}*/
iconhead_fa='<h4>Font Awesome</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsfaicons+'</ul>';
// creates a form to be displayed everytime the button is clicked
// you should achieve this using AJAX instead of direct html code like this
var form = jQuery('<div id="'+pluginObj.id+'" class="oscitas-container" title="'+pluginObj.title+'"><table id="gallery-table" class="form-table">\
<tr>\
<th><label for="oscitas-heading-icon">Select Icon:</label></th>\
<td><div id="click_icon_list" class="oscitas-icon-div"><span id="osc_show_icon"></span><span class="show-drop"></span></div><input type="hidden" id="oscitas-iconhead-icon" value=""><input type="hidden" id="oscitas-iconhead-icontype" value="">\
<div id="osc_show_iconlist" class="oscitas-icon" style="display:none;width:100%"><h4>Glyphicons</h4><ul name="oscitas-heading-icon_servicebox" class="oscitas-heading-icon">'+ebsicons+'</ul>'+iconhead_fa+'</div>\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-iconcolor">Icon Color:</label></th>\
<td><input type="text" name="label" id="oscitas-iconhead-iconcolor" class="color" value="" /><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-headingtype">Heading Type:</label></th>\
<td><select name="oscitas-iconhead-headingtype" id="oscitas-iconhead-headingtype">\
<option value="h1">H1</option>\
<option value="h2">H2</option>\
<option value="h3">H3</option>\
<option value="h4">H4</option>\
<option value="h5">H5</option>\
<option value="h6">H6</option>\
</select><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-heading">Heading:</label></th>\
<td><input type="text" name="oscitas-iconhead-heading" id="oscitas-iconhead-heading" value="Heading"/><br />\
</td>\
</tr>\
<tr>\
<th><label for="oscitas-iconhead-class">Custom Class:</label></th>\
<td><input type="text" name="line" id="oscitas-iconhead-class" value=""/><br />\
</td>\
</tr>\
</table>\
<p class="submit">\
<input type="button" id="oscitas-iconhead-submit" class="button-primary" value="Insert Icon Heading" name="submit" />\
</p>\
</div>');
var table = form.find('table');
jQuery('.glyphicon').css('display','inline');
form.appendTo('body').hide();
form.find('.color').wpColorPicker();
table.find('#click_icon_list').click(function(){
if(!jQuery(this).hasClass('osc_icon_showing')){
jQuery(this).addClass('osc_icon_showing')
table.find('#osc_show_iconlist').show();
} else{
jQuery(this).removeClass('osc_icon_showing')
table.find('#osc_show_iconlist').hide();
}
});
table.find('.oscitas-heading-icon li').click(function(){
var val=jQuery(this).attr('data-value');
var type=jQuery(this).attr('type');
table.find('.oscitas-heading-icon li').removeClass('osc_icon_selected');
jQuery(this).addClass('osc_icon_selected');
table.find('#click_icon_list').removeClass('osc_icon_showing');
table.find('#osc_show_iconlist').hide();
table.find('#osc_show_icon').removeClass().addClass(type).addClass(val);
table.find('#oscitas-iconhead-icon').val(val);
table.find('#oscitas-iconhead-icontype').val(type);
});
// // handles the click event of the submit button
form.find('#oscitas-iconhead-submit').click(function() {
// defines the options and their default values
// again, this is not the most elegant way to do this
// but well, this gets the job done nonetheless
var type=jQuery('#oscitas-iconhead-headingtype').val();
var cusclass='',style='';
if(table.find('#oscitas-iconhead-icon').val()!=''){
style=' style="' + table.find('#oscitas-iconhead-icon').val()+'"' ;
}
if(table.find('#oscitas-iconhead-icontype').val()!=''){
style+=' icontype="' + table.find('#oscitas-iconhead-icontype').val()+'"' ;
}
if(table.find('#oscitas-iconhead-iconcolor').val()!=''){
cusclass+= ' color="'+table.find('#oscitas-iconhead-iconcolor').val()+'"';
}
if(table.find('#oscitas-iconhead-class').val()!=''){
cusclass+= ' class="'+table.find('#oscitas-iconhead-class').val()+'"';
}
var shortcode = '[iconheading type="'+type+'"';
shortcode += style+cusclass ;
shortcode += ']'+table.find('#oscitas-iconhead-heading').val()+'[/iconheading]' ;
// inserts the shortcode into the active editor
tinyMCE.activeEditor.execCommand('mceInsertContent',0 , shortcode);
// closes Dialoguebox
close_dialogue(pluginObj.hashId);
});
}
| Java |
using System;
using System.Threading.Tasks;
using System.Windows.Threading;
using Disp = System.Windows.Threading.Dispatcher;
using Op = System.Windows.Threading.DispatcherOperation;
using DO = System.Windows.Threading.DispatcherObject;
using static System.Array;
namespace AphidUI
{
public static class DispatcherObjectExtension
{
public static void Invoke(this Disp dispatcher, Action action) =>
dispatcher.Invoke(action, Empty<object>());
public static void Sync(this Disp dispatcher, Action action) =>
dispatcher.Invoke(action, Empty<object>());
public static Op BeginInvoke(this Disp dispatcher, Action action, params object[] args) =>
dispatcher.BeginInvoke(action, args);
public static Op Async(this Disp dispatcher, Action action, params object[] args) =>
dispatcher.BeginInvoke(action, args);
public static Task Run(this Disp dispatcher, Action action, params object[] args) =>
dispatcher.BeginInvoke(action, args).Task;
public static TResult Invoke<TResult>(this Disp dispatcher, Func<TResult> action) =>
(TResult)dispatcher.Invoke(action, Empty<object>());
public static TResult Sync<TResult>(this Disp dispatcher, Func<TResult> action) =>
(TResult)dispatcher.Invoke(action, Empty<object>());
public static Op BeginInvoke(this DO @do, Action action, params object[] args) =>
@do.Dispatcher.BeginInvoke(action, args);
public static Op Async(this DO @do, Action action, params object[] args) =>
@do.Dispatcher.BeginInvoke(action, args);
public static Task Run(this DO @do, Action action, params object[] args) =>
@do.BeginInvoke(action, args).Task;
public static Task Run<TArg>(this DO @do, Action<TArg> action, TArg arg0) =>
@do.Dispatcher.BeginInvoke(action, new object[] { arg0 }).Task;
public static void Invoke(this DO @do, Action action) =>
@do.Dispatcher.Invoke(action, Empty<object>());
public static void Sync(this DO @do, Action action) =>
@do.Dispatcher.Invoke(action, Empty<object>());
public static TResult Invoke<TResult>(this DO @do, Func<TResult> action) =>
(TResult)@do.Dispatcher.Invoke(action, Empty<object>());
public static TResult Sync<TResult>(this DO @do, Func<TResult> action) =>
(TResult)@do.Dispatcher.Invoke(action, Empty<object>());
public static DispatcherProcessingDisabled DisableProcessing(this DO @do) =>
@do.Dispatcher.DisableProcessing();
}
}
| Java |
<?php
/**
* @desc Modify from component Media Manager of Joomla
*
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die( 'Restricted access' );
jimport('joomla.filesystem.file');
jimport('joomla.filesystem.folder');
/**
* Weblinks Weblink Controller
*
* @package Joomla
* @subpackage Weblinks
* @since 1.5
*/
class JaextmanagerControllerFile extends JaextmanagerController
{
/**
* Upload a file
*
* @since 1.5
*/
function upload()
{
global $mainframe;
// Check for request forgeries
JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );
$file = JRequest::getVar( 'Filedata', '', 'files', 'array' );
$folder = JRequest::getVar( 'folder', '', '', 'path' );
$format = JRequest::getVar( 'format', 'html', '', 'cmd');
$return = JRequest::getVar( 'return-url', null, 'post', 'base64' );
$err = null;
// Set FTP credentials, if given
jimport('joomla.client.helper');
JClientHelper::setCredentialsFromRequest('ftp');
// Make the filename safe
jimport('joomla.filesystem.file');
$file['name'] = JFile::makeSafe($file['name']);
if (isset($file['name'])) {
$filepath = JPath::clean(JA_WORKING_DATA_FOLDER.DS.$folder.DS.strtolower($file['name']));
if (!RepoHelper::canUpload( $file, $err )) {
if ($format == 'json') {
jimport('joomla.error.log');
$log = &JLog::getInstance('upload.error.php');
$log->addEntry(array('comment' => 'Invalid: '.$filepath.': '.$err));
header('HTTP/1.0 415 Unsupported Media Type');
jexit('Error. Unsupported Media Type!');
} else {
JError::raiseNotice(100, JText::_($err));
// REDIRECT
if ($return) {
$mainframe->redirect(base64_decode($return).'&folder='.$folder);
}
return;
}
}
if (JFile::exists($filepath)) {
if ($format == 'json') {
jimport('joomla.error.log');
$log = &JLog::getInstance('upload.error.php');
$log->addEntry(array('comment' => 'File already exists: '.$filepath));
header('HTTP/1.0 409 Conflict');
jexit('Error. File already exists');
} else {
JError::raiseNotice(100, JText::_('Error. File already exists'));
// REDIRECT
if ($return) {
$mainframe->redirect(base64_decode($return).'&folder='.$folder);
}
return;
}
}
if (!JFile::upload($file['tmp_name'], $filepath)) {
if ($format == 'json') {
jimport('joomla.error.log');
$log = &JLog::getInstance('upload.error.php');
$log->addEntry(array('comment' => 'Cannot upload: '.$filepath));
header('HTTP/1.0 400 Bad Request');
jexit('Error. Unable to upload file');
} else {
JError::raiseWarning(100, JText::_('Error. Unable to upload file'));
// REDIRECT
if ($return) {
$mainframe->redirect(base64_decode($return).'&folder='.$folder);
}
return;
}
} else {
if ($format == 'json') {
jimport('joomla.error.log');
$log = &JLog::getInstance();
$log->addEntry(array('comment' => $folder));
jexit('Upload complete');
} else {
$mainframe->enqueueMessage(JText::_('Upload complete'));
// REDIRECT
if ($return) {
$mainframe->redirect(base64_decode($return).'&folder='.$folder);
}
return;
}
}
} else {
$mainframe->redirect('index.php', 'Invalid Request', 'error');
}
}
/**
* Deletes paths from the current path
*
* @param string $listFolder The image directory to delete a file from
* @since 1.5
*/
function delete()
{
global $mainframe;
JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );
// Set FTP credentials, if given
jimport('joomla.client.helper');
JClientHelper::setCredentialsFromRequest('ftp');
// Get some data from the request
$tmpl = JRequest::getCmd( 'tmpl' );
$paths = JRequest::getVar( 'rm', array(), '', 'array' );
$folder = JRequest::getVar( 'folder', '', '', 'path');
// Initialize variables
$msg = array();
$ret = true;
if (count($paths)) {
foreach ($paths as $path)
{
if ($path !== JFile::makeSafe($path)) {
JError::raiseWarning(100, JText::_('Unable to delete:').htmlspecialchars($path, ENT_COMPAT, 'UTF-8').' '.JText::_('WARNFILENAME'));
continue;
}
$fullPath = JPath::clean(JA_WORKING_DATA_FOLDER.DS.$folder.DS.$path);
if (is_file($fullPath)) {
$ret |= !JFile::delete($fullPath);
} else if (is_dir($fullPath)) {
$files = JFolder::files($fullPath, '.', true);
$canDelete = true;
foreach ($files as $file) {
if ($file != 'index.html') {
$canDelete = false;
}
}
if ($canDelete) {
$ret |= !JFolder::delete($fullPath);
} else {
//allow remove folder not empty on local repository
$ret2 = JFolder::delete($fullPath);
$ret |= !$ret2;
if($ret2 == false) {
JError::raiseWarning(100, JText::_('Unable to delete:').$fullPath);
}
}
}
}
}
if ($ret) {
JError::raiseNotice(200, JText::_('Successfully delete a seleted item(s).'));
}
if ($tmpl == 'component') {
// We are inside the iframe
$mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder.'&tmpl=component');
} else {
$mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder);
}
}
function download()
{
global $mainframe;
JRequest::checkToken( 'request' ) or jexit( 'Invalid Token' );
// Set FTP credentials, if given
jimport('joomla.client.helper');
JClientHelper::setCredentialsFromRequest('ftp');
// Get some data from the request
$tmpl = JRequest::getCmd( 'tmpl' );
$paths = JRequest::getVar( 'rm', array(), '', 'array' );
$folder = JRequest::getVar( 'folder', '', '', 'path');
// Initialize variables
$msg = array();
$ret = true;
if (count($paths)) {
foreach ($paths as $path)
{
$fullPath = JPath::clean(JA_WORKING_DATA_FOLDER.DS.$folder.DS.$path);
if(is_file($fullPath) && JFile::getExt($fullPath) == 'zip') {
// Set headers
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=$fullPath");
header("Content-Type: application/zip");
header("Content-Transfer-Encoding: binary");
// Read the file from disk
readfile($fullPath);
exit();
}
}
}
if ($tmpl == 'component') {
// We are inside the iframe
$mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder.'&tmpl=component');
} else {
$mainframe->redirect('index.php?option='.JACOMPONENT.'&view=repolist&folder='.$folder);
}
}
}
| Java |
# Rshell
A simple command shell designed by Trevor Smith and Chianh Wu.
## What it does (currently)
This shell will handle standard command line programs and their arguments. Similarly, these commands can be linked with `&&`,`||`, or `;`.
We are orking on adding precidence via parentheses. The shell itself will also handle comments starting with the `#` symbol. There is also a built
in function that will test if a file or directory exits, and can be executed via `test` with flags `-e` to check existance, `-f` to check for
a regular file, and `-d` to check if it is a directory. Also, `test` can be represented as `[]` (e.g. `test -e /home/user/` = `[ -e /home/user/ ]`);
note also that this is white space sensetive `[-e /home/user/]` will not work.
## How to Run
- `$ git clone https://github.com/tsmit019/rshell.git`
- `$ cd rshell`
- `$ git checkout hw4`
- `$ make`
- `$ bin/rshell`
## If you want to run test
- `$ git clone https://github.com/tsmit019/rshell.git`
- `$ cd rshell`
- `$ git checkout hw4`
- `$ make`
- `$ cd tests`
From here you can chose any of the `.sh` and run them. Make sure they are executable by checking using `ls -l`. If they are not executable, then type `chmod 711 *.sh` to make all the `.sh` files executable.
## Bugs
Input redirection and output redirection work most of the time except for when they are the first set of commands (e.g. `cat < test.txt` will through an out of range. I have looked
for the reason for a while and have not been able to identify why). But, if you use the redirects after a connector (e.g. `echo hhallllllllu && cat < test` or `ls -al; echo why does this not work > sad.txt`)
then it works perfectly fine. Same for piping. I don't quite know.
Nested redirects dont quite work as intended e.g. `cat < test.txt > test_clone.txt` will not write to test_clone.txt but just execute the `cat < test.txt`.
If you give a command that is parenthese, connector, then command (e.g. `(echo a && echo b) || echo c`) you get a out of range error that I was
not able to resolve. Similarly, any connector directly after a closing parenthese will cause this behavior and I am unsure why. I will try and fix
this by the next release.
Similarly, commands with connectors right after each other will through a similar out of range error. E.g `echo a && ||` will give you out of range.
| Java |
---
name: Feature request
about: Please consider reporting directly to https://github.com/magento/community-features
---
<!---
Important: This repository is intended only for Magento 2 Technical Issues. Enter Feature Requests at https://github.com/magento/community-features. Project stakeholders monitor and manage requests. Feature requests entered using this form may be moved to the forum. Fields marked with (*) are required. Please don't remove the template.
-->
### Description (*)
<!--- Describe the feature you would like to add. -->
### Expected behavior (*)
<!--- What is the expected behavior of this feature? How is it going to work? -->
### Benefits
<!--- How do you think this feature would improve Magento? -->
### Additional information
<!--- What other information can you provide about the desired feature? -->
| Java |
<!DOCTYPE html>
<html>
<h1>muppets_mug5</h1>
<p> BOLD: 2/2 correct and 0/2false</p>
<p> SIFT: 0/2 correct and 2/2false</p><br>
<img src = "../../../BVD_M01/muppets_mug/muppets_mug5.jpg" alt = "muppets_mug5.html" style= " width:320px;height:240px;"> <h1> Falsely compared to: </h1><br>
<img src = "../../../" alt = "" style= " width:320px;height:240px;"> <img src = "../../../" alt = "" style= " width:320px;height:240px;"> </html> | Java |
/**
@mainpage SOIL
Jonathan Dummer
2007-07-26-10.36
Simple OpenGL Image Library
A tiny c library for uploading images as
textures into OpenGL. Also saving and
loading of images is supported.
I'm using Sean's Tool Box image loader as a base:
http://www.nothings.org/
I'm upgrading it to load TGA and DDS files, and a direct
path for loading DDS files straight into OpenGL textures,
when applicable.
Image Formats:
- BMP load & save
- TGA load & save
- DDS load & save
- PNG load
- JPG load
OpenGL Texture Features:
- resample to power-of-two sizes
- MIPmap generation
- compressed texture S3TC formats (if supported)
- can pre-multiply alpha for you, for better compositing
- can flip image about the y-axis (except pre-compressed DDS files)
Thanks to:
* Sean Barret - for the awesome stb_image
* Dan Venkitachalam - for finding some non-compliant DDS files, and patching some explicit casts
* everybody at gamedev.net
**/
#ifndef HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY
#define HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY
#ifdef __cplusplus
extern "C" {
#endif
/**
The format of images that may be loaded (force_channels).
SOIL_LOAD_AUTO leaves the image in whatever format it was found.
SOIL_LOAD_L forces the image to load as Luminous (greyscale)
SOIL_LOAD_LA forces the image to load as Luminous with Alpha
SOIL_LOAD_RGB forces the image to load as Red Green Blue
SOIL_LOAD_RGBA forces the image to load as Red Green Blue Alpha
**/
enum
{
SOIL_LOAD_AUTO = 0,
SOIL_LOAD_L = 1,
SOIL_LOAD_LA = 2,
SOIL_LOAD_RGB = 3,
SOIL_LOAD_RGBA = 4
};
/**
Passed in as reuse_texture_ID, will cause SOIL to
register a new texture ID using glGenTextures().
If the value passed into reuse_texture_ID > 0 then
SOIL will just re-use that texture ID (great for
reloading image assets in-game!)
**/
enum
{
SOIL_CREATE_NEW_ID = 0
};
/**
flags you can pass into SOIL_load_OGL_texture()
and SOIL_create_OGL_texture().
(note that if SOIL_FLAG_DDS_LOAD_DIRECT is used
the rest of the flags with the exception of
SOIL_FLAG_TEXTURE_REPEATS will be ignored while
loading already-compressed DDS files.)
SOIL_FLAG_POWER_OF_TWO: force the image to be POT
SOIL_FLAG_MIPMAPS: generate mipmaps for the texture
SOIL_FLAG_TEXTURE_REPEATS: otherwise will clamp
SOIL_FLAG_MULTIPLY_ALPHA: for using (GL_ONE,GL_ONE_MINUS_SRC_ALPHA) blending
SOIL_FLAG_INVERT_Y: flip the image vertically
SOIL_FLAG_COMPRESS_TO_DXT: if the card can display them, will convert RGB to DXT1, RGBA to DXT5
SOIL_FLAG_DDS_LOAD_DIRECT: will load DDS files directly without _ANY_ additional processing
SOIL_FLAG_NTSC_SAFE_RGB: clamps RGB components to the range [16,235]
SOIL_FLAG_CoCg_Y: Google YCoCg; RGB=>CoYCg, RGBA=>CoCgAY
SOIL_FLAG_TEXTURE_RECTANGE: uses ARB_texture_rectangle ; pixel indexed & no repeat or MIPmaps or cubemaps
**/
enum
{
SOIL_FLAG_POWER_OF_TWO = 1,
SOIL_FLAG_MIPMAPS = 2,
SOIL_FLAG_TEXTURE_REPEATS = 4,
SOIL_FLAG_MULTIPLY_ALPHA = 8,
SOIL_FLAG_INVERT_Y = 16,
SOIL_FLAG_COMPRESS_TO_DXT = 32,
SOIL_FLAG_DDS_LOAD_DIRECT = 64,
SOIL_FLAG_NTSC_SAFE_RGB = 128,
SOIL_FLAG_CoCg_Y = 256,
SOIL_FLAG_TEXTURE_RECTANGLE = 512
};
/**
The types of images that may be saved.
(TGA supports uncompressed RGB / RGBA)
(BMP supports uncompressed RGB)
(DDS supports DXT1 and DXT5)
**/
enum
{
SOIL_SAVE_TYPE_TGA = 0,
SOIL_SAVE_TYPE_BMP = 1,
SOIL_SAVE_TYPE_DDS = 2
};
/**
Defines the order of faces in a DDS cubemap.
I recommend that you use the same order in single
image cubemap files, so they will be interchangeable
with DDS cubemaps when using SOIL.
**/
#define SOIL_DDS_CUBEMAP_FACE_ORDER "EWUDNS"
/**
The types of internal fake HDR representations
SOIL_HDR_RGBE: RGB * pow( 2.0, A - 128.0 )
SOIL_HDR_RGBdivA: RGB / A
SOIL_HDR_RGBdivA2: RGB / (A*A)
**/
enum
{
SOIL_HDR_RGBE = 0,
SOIL_HDR_RGBdivA = 1,
SOIL_HDR_RGBdivA2 = 2
};
/**
Loads an image from disk into an OpenGL texture.
\param filename the name of the file to upload as a texture
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture
(
const char *filename,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 6 images from disk into an OpenGL cubemap texture.
\param x_pos_file the name of the file to upload as the +x cube face
\param x_neg_file the name of the file to upload as the -x cube face
\param y_pos_file the name of the file to upload as the +y cube face
\param y_neg_file the name of the file to upload as the -y cube face
\param z_pos_file the name of the file to upload as the +z cube face
\param z_neg_file the name of the file to upload as the -z cube face
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_cubemap
(
const char *x_pos_file,
const char *x_neg_file,
const char *y_pos_file,
const char *y_neg_file,
const char *z_pos_file,
const char *z_neg_file,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 1 image from disk and splits it into an OpenGL cubemap texture.
\param filename the name of the file to upload as a texture
\param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_single_cubemap
(
const char *filename,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads an HDR image from disk into an OpenGL texture.
\param filename the name of the file to upload as a texture
\param fake_HDR_format SOIL_HDR_RGBE, SOIL_HDR_RGBdivA, SOIL_HDR_RGBdivA2
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_HDR_texture
(
const char *filename,
int fake_HDR_format,
int rescale_to_max,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads an image from RAM into an OpenGL texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\param width
\param height
\param channels
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture_and_info_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags,
int *width,
int *height,
int *channels
);
/**
Loads an image from RAM into an OpenGL texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_texture_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 6 images from memory into an OpenGL cubemap texture.
\param x_pos_buffer the image data in RAM to upload as the +x cube face
\param x_pos_buffer_length the size of the above buffer
\param x_neg_buffer the image data in RAM to upload as the +x cube face
\param x_neg_buffer_length the size of the above buffer
\param y_pos_buffer the image data in RAM to upload as the +x cube face
\param y_pos_buffer_length the size of the above buffer
\param y_neg_buffer the image data in RAM to upload as the +x cube face
\param y_neg_buffer_length the size of the above buffer
\param z_pos_buffer the image data in RAM to upload as the +x cube face
\param z_pos_buffer_length the size of the above buffer
\param z_neg_buffer the image data in RAM to upload as the +x cube face
\param z_neg_buffer_length the size of the above buffer
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_cubemap_from_memory
(
const unsigned char *const x_pos_buffer,
int x_pos_buffer_length,
const unsigned char *const x_neg_buffer,
int x_neg_buffer_length,
const unsigned char *const y_pos_buffer,
int y_pos_buffer_length,
const unsigned char *const y_neg_buffer,
int y_neg_buffer_length,
const unsigned char *const z_pos_buffer,
int z_pos_buffer_length,
const unsigned char *const z_neg_buffer,
int z_neg_buffer_length,
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Loads 1 image from RAM and splits it into an OpenGL cubemap texture.
\param buffer the image data in RAM just as if it were still in a file
\param buffer_length the size of the buffer in bytes
\param face_order the order of the faces in the file, any combination of NSWEUD, for North, South, Up, etc.
\param force_channels 0-image format, 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_load_OGL_single_cubemap_from_memory
(
const unsigned char *const buffer,
int buffer_length,
const char face_order[6],
int force_channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Creates a 2D OpenGL texture from raw image data. Note that the raw data is
_NOT_ freed after the upload (so the user can load various versions).
\param data the raw data to be uploaded as an OpenGL texture
\param width the width of the image in pixels
\param height the height of the image in pixels
\param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_create_OGL_texture
(
const unsigned char *const data,
int width, int height, int channels,
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Creates an OpenGL cubemap texture by splitting up 1 image into 6 parts.
\param data the raw data to be uploaded as an OpenGL texture
\param width the width of the image in pixels
\param height the height of the image in pixels
\param channels the number of channels: 1-luminous, 2-luminous/alpha, 3-RGB, 4-RGBA
\param face_order the order of the faces in the file, and combination of NSWEUD, for North, South, Up, etc.
\param reuse_texture_ID 0-generate a new texture ID, otherwise reuse the texture ID (overwriting the old texture)
\param flags can be any of SOIL_FLAG_POWER_OF_TWO | SOIL_FLAG_MIPMAPS | SOIL_FLAG_TEXTURE_REPEATS | SOIL_FLAG_MULTIPLY_ALPHA | SOIL_FLAG_INVERT_Y | SOIL_FLAG_COMPRESS_TO_DXT | SOIL_FLAG_DDS_LOAD_DIRECT
\return 0-failed, otherwise returns the OpenGL texture handle
**/
unsigned int
SOIL_create_OGL_single_cubemap
(
const unsigned char *const data,
int width, int height, int channels,
const char face_order[6],
unsigned int reuse_texture_ID,
unsigned int flags
);
/**
Captures the OpenGL window (RGB) and saves it to disk
\return 0 if it failed, otherwise returns 1
**/
int
SOIL_save_screenshot
(
const char *filename,
int image_type,
int x, int y,
int width, int height
);
/**
Loads an image from disk into an array of unsigned chars.
Note that *channels return the original channel count of the
image. If force_channels was other than SOIL_LOAD_AUTO,
the resulting image has force_channels, but *channels may be
different (if the original image had a different channel
count).
\return 0 if failed, otherwise returns 1
**/
unsigned char*
SOIL_load_image
(
const char *filename,
int *width, int *height, int *channels,
int force_channels
);
/**
Loads an image from memory into an array of unsigned chars.
Note that *channels return the original channel count of the
image. If force_channels was other than SOIL_LOAD_AUTO,
the resulting image has force_channels, but *channels may be
different (if the original image had a different channel
count).
\return 0 if failed, otherwise returns 1
**/
unsigned char*
SOIL_load_image_from_memory
(
const unsigned char *const buffer,
int buffer_length,
int *width, int *height, int *channels,
int force_channels
);
/**
Saves an image from an array of unsigned chars (RGBA) to disk
\return 0 if failed, otherwise returns 1
**/
int
SOIL_save_image
(
const char *filename,
int image_type,
int width, int height, int channels,
const unsigned char *const data
);
/**
Frees the image data (note, this is just C's "free()"...this function is
present mostly so C++ programmers don't forget to use "free()" and call
"delete []" instead [8^)
**/
void
SOIL_free_image_data
(
unsigned char *img_data
);
/**
This function resturn a pointer to a string describing the last thing
that happened inside SOIL. It can be used to determine why an image
failed to load.
**/
const char*
SOIL_last_result
(
void
);
#ifdef __cplusplus
}
#endif
#endif /* HEADER_SIMPLE_OPENGL_IMAGE_LIBRARY */
| Java |
/*
Google HTML5 slides template
Authors: Luke Mahé (code)
Marcin Wichary (code and design)
Dominic Mazzoni (browser compatibility)
Charles Chen (ChromeVox support)
URL: http://code.google.com/p/html5slides/
*/
/* Framework */
html {
height: 100%;
}
body {
margin: 0;
padding: 0;
display: block !important;
height: 100%;
min-height: 740px;
overflow-x: hidden;
overflow-y: auto;
background: rgb(215, 215, 215);
background: -o-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -moz-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -webkit-radial-gradient(rgb(240, 240, 240), rgb(190, 190, 190));
background: -webkit-gradient(radial, 50% 50%, 0, 50% 50%, 500, from(rgb(240, 240, 240)), to(rgb(190, 190, 190)));
-webkit-font-smoothing: antialiased;
}
.slides {
width: 100%;
height: 100%;
left: 0;
top: 0;
position: absolute;
-webkit-transform: translate3d(0, 0, 0);
}
.slides > article {
display: block;
position: absolute;
overflow: hidden;
width: 900px;
height: 700px;
left: 50%;
top: 50%;
margin-left: -450px;
margin-top: -350px;
padding: 40px 60px;
box-sizing: border-box;
-o-box-sizing: border-box;
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
border-radius: 10px;
-o-border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
background-color: white;
box-shadow: 0 2px 6px rgba(0, 0, 0, .1);
border: 1px solid rgba(0, 0, 0, .3);
transition: transform .3s ease-out;
-o-transition: -o-transform .3s ease-out;
-moz-transition: -moz-transform .3s ease-out;
-webkit-transition: -webkit-transform .3s ease-out;
}
.slides.layout-widescreen > article {
margin-left: -550px;
width: 1100px;
}
.slides.layout-faux-widescreen > article {
margin-left: -550px;
width: 1100px;
padding: 40px 160px;
}
.slides.template-default > article:not(.nobackground):not(.biglogo) {
background: url(images/google-logo-small.jpg) 710px 625px no-repeat;
background-color: white;
}
.slides.template-io2011 > article:not(.nobackground):not(.biglogo) {
background: url(images/colorbar.png) 0 600px repeat-x,
url(images/googleio-logo.jpg) 640px 625px no-repeat;
background-size: 100%, 225px;
background-color: white;
}
.slides.layout-widescreen > article:not(.nobackground):not(.biglogo),
.slides.layout-faux-widescreen > article:not(.nobackground):not(.biglogo) {
background-position-x: 0, 840px;
}
/* Clickable/tappable areas */
.slide-area {
z-index: 1000;
position: absolute;
left: 0;
top: 0;
width: 150px;
height: 700px;
left: 50%;
top: 50%;
cursor: pointer;
margin-top: -350px;
tap-highlight-color: transparent;
-o-tap-highlight-color: transparent;
-moz-tap-highlight-color: transparent;
-webkit-tap-highlight-color: transparent;
}
#prev-slide-area {
margin-left: -550px;
}
#next-slide-area {
margin-left: 400px;
}
.slides.layout-widescreen #prev-slide-area,
.slides.layout-faux-widescreen #prev-slide-area {
margin-left: -650px;
}
.slides.layout-widescreen #next-slide-area,
.slides.layout-faux-widescreen #next-slide-area {
margin-left: 500px;
}
/* Slide styles */
.slides.template-default article.biglogo {
background: white url(images/google-logo.jpg) 50% 50% no-repeat;
}
.slides.template-io2011 article.biglogo {
background: white url(images/googleio-logo.jpg) 50% 50% no-repeat;
background-size: 600px;
}
/* Slides */
.slides > article {
display: none;
}
.slides > article.far-past {
display: block;
transform: translate(-2040px);
-o-transform: translate(-2040px);
-moz-transform: translate(-2040px);
-webkit-transform: translate3d(-2040px, 0, 0);
}
.slides > article.past {
display: block;
transform: translate(-1020px);
-o-transform: translate(-1020px);
-moz-transform: translate(-1020px);
-webkit-transform: translate3d(-1020px, 0, 0);
}
.slides > article.current {
display: block;
transform: translate(0);
-o-transform: translate(0);
-moz-transform: translate(0);
-webkit-transform: translate3d(0, 0, 0);
}
.slides > article.next {
display: block;
transform: translate(1020px);
-o-transform: translate(1020px);
-moz-transform: translate(1020px);
-webkit-transform: translate3d(1020px, 0, 0);
}
.slides > article.far-next {
display: block;
transform: translate(2040px);
-o-transform: translate(2040px);
-moz-transform: translate(2040px);
-webkit-transform: translate3d(2040px, 0, 0);
}
.slides.layout-widescreen > article.far-past,
.slides.layout-faux-widescreen > article.far-past {
display: block;
transform: translate(-2260px);
-o-transform: translate(-2260px);
-moz-transform: translate(-2260px);
-webkit-transform: translate3d(-2260px, 0, 0);
}
.slides.layout-widescreen > article.past,
.slides.layout-faux-widescreen > article.past {
display: block;
transform: translate(-1130px);
-o-transform: translate(-1130px);
-moz-transform: translate(-1130px);
-webkit-transform: translate3d(-1130px, 0, 0);
}
.slides.layout-widescreen > article.current,
.slides.layout-faux-widescreen > article.current {
display: block;
transform: translate(0);
-o-transform: translate(0);
-moz-transform: translate(0);
-webkit-transform: translate3d(0, 0, 0);
}
.slides.layout-widescreen > article.next,
.slides.layout-faux-widescreen > article.next {
display: block;
transform: translate(1130px);
-o-transform: translate(1130px);
-moz-transform: translate(1130px);
-webkit-transform: translate3d(1130px, 0, 0);
}
.slides.layout-widescreen > article.far-next,
.slides.layout-faux-widescreen > article.far-next {
display: block;
transform: translate(2260px);
-o-transform: translate(2260px);
-moz-transform: translate(2260px);
-webkit-transform: translate3d(2260px, 0, 0);
}
/* Styles for slides */
.slides > article {
font-family: 'Open Sans', Arial, sans-serif;
color: rgb(102, 102, 102);
text-shadow: 0 1px 1px rgba(0, 0, 0, .1);
font-size: 30px;
line-height: 36px;
letter-spacing: -1px;
}
b {
font-weight: 600;
}
.blue {
color: rgb(0, 102, 204);
}
.yellow {
color: rgb(255, 211, 25);
}
.green {
color: rgb(0, 138, 53);
}
.red {
color: rgb(255, 0, 0);
}
.black {
color: black;
}
.white {
color: white;
}
a {
color: rgb(0, 102, 204);
}
a:visited {
color: rgba(0, 102, 204, .75);
}
a:hover {
color: black;
}
p {
margin: 0;
padding: 0;
margin-top: 20px;
}
p:first-child {
margin-top: 0;
}
h1 {
font-size: 60px;
line-height: 60px;
padding: 0;
margin: 0;
margin-top: 200px;
padding-right: 40px;
font-weight: 600;
letter-spacing: -3px;
color: rgb(51, 51, 51);
}
h2 {
font-size: 45px;
line-height: 45px;
position: absolute;
bottom: 150px;
padding: 0;
margin: 0;
padding-right: 40px;
font-weight: 600;
letter-spacing: -2px;
color: rgb(51, 51, 51);
}
h3 {
font-size: 30px;
line-height: 36px;
padding: 0;
margin: 0;
padding-right: 40px;
font-weight: 600;
letter-spacing: -1px;
color: rgb(51, 51, 51);
}
article.fill h3 {
background: rgba(0, 0, 0, .35);
padding-top: .2em;
padding-bottom: .3em;
margin-top: -.2em;
margin-left: -60px;
padding-left: 60px;
margin-right: -60px;
padding-right: 60px;
}
ul {
list-style: none;
margin: 0;
padding: 0;
margin-top: 40px;
margin-left: .75em;
}
ul:first-child {
margin-top: 0;
}
ul ul {
margin-top: .5em;
}
li {
padding: 0;
margin: 0;
margin-bottom: .5em;
}
li::before {
content: '·';
width: .75em;
margin-left: -.75em;
position: absolute;
}
pre {
font-family: 'Droid Sans Mono', 'Courier New', monospace;
font-size: 20px;
line-height: 28px;
padding: 5px 10px;
letter-spacing: -1px;
margin-top: 40px;
margin-bottom: 40px;
color: black;
background: rgb(240, 240, 240);
border: 1px solid rgb(224, 224, 224);
box-shadow: inset 0 2px 6px rgba(0, 0, 0, .1);
overflow: hidden;
}
code {
font-size: 95%;
font-family: 'Droid Sans Mono', 'Courier New', monospace;
color: black;
}
iframe {
width: 100%;
height: 620px;
background: white;
border: 1px solid rgb(192, 192, 192);
margin: -1px;
/*box-shadow: inset 0 2px 6px rgba(0, 0, 0, .1);*/
}
h3 + iframe {
margin-top: 40px;
height: 540px;
}
article.fill iframe {
position: absolute;
left: 0;
top: 0;
width: 100%;
height: 100%;
border: 0;
margin: 0;
border-radius: 10px;
-o-border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
z-index: -1;
}
article.fill img {
position: absolute;
left: 0;
top: 0;
min-width: 100%;
min-height: 100%;
border-radius: 10px;
-o-border-radius: 10px;
-moz-border-radius: 10px;
-webkit-border-radius: 10px;
z-index: -1;
}
img.centered {
margin: 0 auto;
display: block;
}
table {
width: 100%;
border-collapse: collapse;
margin-top: 40px;
}
th {
font-weight: 600;
text-align: left;
}
td,
th {
border: 1px solid rgb(224, 224, 224);
padding: 5px 10px;
vertical-align: top;
}
.source {
position: absolute;
left: 60px;
top: 644px;
padding-right: 175px;
font-size: 15px;
letter-spacing: 0;
line-height: 18px;
}
q {
display: block;
font-size: 60px;
line-height: 72px;
margin-left: 20px;
margin-top: 100px;
margin-right: 150px;
}
q::before {
content: '“';
position: absolute;
display: inline-block;
margin-left: -2.1em;
width: 2em;
text-align: right;
font-size: 90px;
color: rgb(192, 192, 192);
}
q::after {
content: '”';
position: absolute;
margin-left: .1em;
font-size: 90px;
color: rgb(192, 192, 192);
}
div.author {
text-align: right;
font-size: 40px;
margin-top: 20px;
margin-right: 150px;
}
div.author::before {
content: '—';
}
/* Size variants */
article.smaller p,
article.smaller ul {
font-size: 20px;
line-height: 24px;
letter-spacing: 0;
}
article.smaller table {
font-size: 20px;
line-height: 24px;
letter-spacing: 0;
}
article.smaller pre {
font-size: 15px;
line-height: 20px;
letter-spacing: 0;
}
article.smaller q {
font-size: 40px;
line-height: 48px;
}
article.smaller q::before,
article.smaller q::after {
font-size: 60px;
}
/* Builds */
.build > * {
transition: opacity 0.5s ease-in-out 0.2s;
-o-transition: opacity 0.5s ease-in-out 0.2s;
-moz-transition: opacity 0.5s ease-in-out 0.2s;
-webkit-transition: opacity 0.5s ease-in-out 0.2s;
}
.to-build {
opacity: 0;
}
/* Pretty print */
.prettyprint .str, /* string content */
.prettyprint .atv { /* a markup attribute value */
color: rgb(0, 138, 53);
}
.prettyprint .kwd, /* a keyword */
.prettyprint .tag { /* a markup tag name */
color: rgb(0, 102, 204);
}
.prettyprint .com { /* a comment */
color: rgb(127, 127, 127);
font-style: italic;
}
.prettyprint .lit { /* a literal value */
color: rgb(127, 0, 0);
}
.prettyprint .pun, /* punctuation, lisp open bracket, lisp close bracket */
.prettyprint .opn,
.prettyprint .clo {
color: rgb(127, 127, 127);
}
.prettyprint .typ, /* a type name */
.prettyprint .atn, /* a markup attribute name */
.prettyprint .dec,
.prettyprint .var { /* a declaration; a variable name */
color: rgb(127, 0, 127);
}
.mylogo{
width: 200px;
height: 80px;
background: white;
position: absolute;
bottom: 0;
right: 0;
} | Java |
/*
Linux PINMUX.C
*/
#include <asm/arch/am_regs.h>
#include <asm/arch/am_eth_reg.h>
#include <asm/arch/pinmux.h>
int clear_mio_mux(unsigned mux_index, unsigned mux_mask)
{
unsigned mux_reg[] = {PERIPHS_PIN_MUX_0, PERIPHS_PIN_MUX_1, PERIPHS_PIN_MUX_2,PERIPHS_PIN_MUX_3,
PERIPHS_PIN_MUX_4,PERIPHS_PIN_MUX_5,PERIPHS_PIN_MUX_6,PERIPHS_PIN_MUX_7,PERIPHS_PIN_MUX_8,
PERIPHS_PIN_MUX_9,PERIPHS_PIN_MUX_10,PERIPHS_PIN_MUX_11,PERIPHS_PIN_MUX_12};
if (mux_index < 13) {
CLEAR_CBUS_REG_MASK(mux_reg[mux_index], mux_mask);
return 0;
}
return -1;
}
int set_mio_mux(unsigned mux_index, unsigned mux_mask)
{
unsigned mux_reg[] = {PERIPHS_PIN_MUX_0, PERIPHS_PIN_MUX_1, PERIPHS_PIN_MUX_2,PERIPHS_PIN_MUX_3,
PERIPHS_PIN_MUX_4,PERIPHS_PIN_MUX_5,PERIPHS_PIN_MUX_6,PERIPHS_PIN_MUX_7,PERIPHS_PIN_MUX_8,
PERIPHS_PIN_MUX_9,PERIPHS_PIN_MUX_10,PERIPHS_PIN_MUX_11,PERIPHS_PIN_MUX_12};
if (mux_index < 13) {
SET_CBUS_REG_MASK(mux_reg[mux_index], mux_mask);
return 0;
}
return -1;
}
/*
call it before pinmux init;
call it before soft reset;
*/
void clearall_pinmux(void)
{
int i;
for(i=0;i<13;i++)
clear_mio_mux(i,0xffffffff);
return;
}
/*ETH PINMUX SETTING
More details can get from am_eth_pinmux.h
*/
int eth_set_pinmux(int bank_id,int clk_in_out_id,unsigned long ext_msk)
{
int ret=0;
switch(bank_id)
{
case ETH_BANK0_GPIOX46_X54:
if(ext_msk>0)
set_mio_mux(ETH_BANK0_REG1,ext_msk);
else
set_mio_mux(ETH_BANK0_REG1,ETH_BANK0_REG1_VAL);
break;
case ETH_BANK1_GPIOX59_X67:
if(ext_msk>0)
set_mio_mux(ETH_BANK1_REG1,ext_msk);
else
set_mio_mux(ETH_BANK1_REG1,ETH_BANK1_REG1_VAL);
break;
default:
printf("UNknow pinmux setting of ethernet!error bankid=%d,must be 0-2\n",bank_id);
ret=-1;
}
switch(clk_in_out_id)
{
case ETH_CLK_IN_GPIOX45_REG3_11:
set_mio_mux(3,1<<11);
break;
case ETH_CLK_IN_GPIOX55_REG3_0:
set_mio_mux(3,1);
break;
case ETH_CLK_IN_GPIOX58_REG3_24:
set_mio_mux(3,1<<24);
break;
case ETH_CLK_IN_GPIOX68_REG3_13:
set_mio_mux(3,1<<13);
break;
case ETH_CLK_OUT_GPIOX45_REG3_12:
set_mio_mux(3,1<<12);
break;
case ETH_CLK_OUT_GPIOX55_REG3_1:
set_mio_mux(3,1<<1);
break;
case ETH_CLK_OUT_GPIOX58_REG3_25:
set_mio_mux(3,1<<25);
break;
case ETH_CLK_OUT_GPIOX68_REG3_14:
set_mio_mux(3,1<<14);
break;
default:
printf("UNknow clk_in_out_id setting of ethernet!error clk_in_out_id=%d,must be 0-7\n",clk_in_out_id);
ret=-1;
}
return ret;
}
| Java |
<?php
/**
* @version $Id: helper.php 20228 2011-01-10 00:52:54Z eddieajau $
* @package Joomla.Site
* @subpackage mod_stats
* @copyright Copyright (C) 2005 - 2011 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
// no direct access
defined('_JEXEC') or die;
/**
* @package Joomla.Site
* @subpackage mod_stats
* @since 1.5
*/
class modStatsHelper
{
static function &getList(&$params)
{
$app = JFactory::getApplication();
$db = JFactory::getDbo();
$rows = array();
$query = $db->getQuery(true);
$serverinfo = $params->get('serverinfo');
$siteinfo = $params->get('siteinfo');
$counter = $params->get('counter');
$increase = $params->get('increase');
$i = 0;
if ($serverinfo) {
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_OS');
$rows[$i]->data = substr(php_uname(), 0, 7);
$i++;
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_PHP');
$rows[$i]->data = phpversion();
$i++;
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_MYSQL');
$rows[$i]->data = $db->getVersion();
$i++;
$rows[$i] = new stdClass;
$rows[$i]->title = JTEXT::_('MOD_STATS_TIME');
$rows[$i]->data = JHTML::_('date','now', 'H:i');
$i++;
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_CACHING');
$rows[$i]->data = $app->getCfg('caching') ? JText::_('JENABLED'):JText::_('JDISABLED');
$i++;
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_GZIP');
$rows[$i]->data = $app->getCfg('gzip') ? JText::_('JENABLED'):JText::_('JDISABLED');
$i++;
}
if ($siteinfo) {
$query->select('COUNT(id) AS count_users');
$query->from('#__users');
$db->setQuery($query);
$users = $db->loadResult();
$query->clear();
$query->select('COUNT(id) AS count_items');
$query->from('#__content');
$query->where('state = 1');
$db->setQuery($query);
$items = $db->loadResult();
$query->clear();
$query->select('COUNT(id) AS count_links ');
$query->from('#__weblinks');
$query->where('state = 1');
$db->setQuery($query);
$links = $db->loadResult();
if ($users) {
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_USERS');
$rows[$i]->data = $users;
$i++;
}
if ($items) {
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_ARTICLES');
$rows[$i]->data = $items;
$i++;
}
if ($links) {
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_WEBLINKS');
$rows[$i]->data = $links;
$i++;
}
}
if ($counter) {
$query->clear();
$query->select('SUM(hits) AS count_hits');
$query->from('#__content');
$query->where('state = 1');
$db->setQuery($query);
$hits = $db->loadResult();
if ($hits) {
$rows[$i] = new stdClass;
$rows[$i]->title = JText::_('MOD_STATS_ARTICLES_VIEW_HITS');
$rows[$i]->data = $hits + $increase;
$i++;
}
}
return $rows;
}
} | Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_55) on Sun Feb 15 12:26:30 PST 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.handler.component.HttpShardHandler (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.handler.component.HttpShardHandler (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/handler/component/HttpShardHandler.html" title="class in org.apache.solr.handler.component">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/HttpShardHandler.html" target="_top">Frames</a></li>
<li><a href="HttpShardHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.handler.component.HttpShardHandler" class="title">Uses of Class<br>org.apache.solr.handler.component.HttpShardHandler</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.handler.component.HttpShardHandler</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../../org/apache/solr/handler/component/HttpShardHandler.html" title="class in org.apache.solr.handler.component">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../../index.html?org/apache/solr/handler/component/class-use/HttpShardHandler.html" target="_top">Frames</a></li>
<li><a href="HttpShardHandler.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
| Java |
/***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id$
*
* Copyright (C) 2002 by Alan Korr
*
* 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 software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include "config.h"
#include "hwcompat.h"
#include "kernel.h"
#include "lcd.h"
#include "system.h"
/*** definitions ***/
#define LCD_SET_LOWER_COLUMN_ADDRESS ((char)0x00)
#define LCD_SET_HIGHER_COLUMN_ADDRESS ((char)0x10)
#define LCD_SET_INTERNAL_REGULATOR_RESISTOR_RATIO ((char)0x20)
#define LCD_SET_POWER_CONTROL_REGISTER ((char)0x28)
#define LCD_SET_DISPLAY_START_LINE ((char)0x40)
#define LCD_SET_CONTRAST_CONTROL_REGISTER ((char)0x81)
#define LCD_SET_SEGMENT_REMAP ((char)0xA0)
#define LCD_SET_LCD_BIAS ((char)0xA2)
#define LCD_SET_ENTIRE_DISPLAY_OFF ((char)0xA4)
#define LCD_SET_ENTIRE_DISPLAY_ON ((char)0xA5)
#define LCD_SET_NORMAL_DISPLAY ((char)0xA6)
#define LCD_SET_REVERSE_DISPLAY ((char)0xA7)
#define LCD_SET_MULTIPLEX_RATIO ((char)0xA8)
#define LCD_SET_BIAS_TC_OSC ((char)0xA9)
#define LCD_SET_1OVER4_BIAS_RATIO ((char)0xAA)
#define LCD_SET_INDICATOR_OFF ((char)0xAC)
#define LCD_SET_INDICATOR_ON ((char)0xAD)
#define LCD_SET_DISPLAY_OFF ((char)0xAE)
#define LCD_SET_DISPLAY_ON ((char)0xAF)
#define LCD_SET_PAGE_ADDRESS ((char)0xB0)
#define LCD_SET_COM_OUTPUT_SCAN_DIRECTION ((char)0xC0)
#define LCD_SET_TOTAL_FRAME_PHASES ((char)0xD2)
#define LCD_SET_DISPLAY_OFFSET ((char)0xD3)
#define LCD_SET_READ_MODIFY_WRITE_MODE ((char)0xE0)
#define LCD_SOFTWARE_RESET ((char)0xE2)
#define LCD_NOP ((char)0xE3)
#define LCD_SET_END_OF_READ_MODIFY_WRITE_MODE ((char)0xEE)
/* LCD command codes */
#define LCD_CNTL_RESET 0xe2 /* Software reset */
#define LCD_CNTL_POWER 0x2f /* Power control */
#define LCD_CNTL_CONTRAST 0x81 /* Contrast */
#define LCD_CNTL_OUTSCAN 0xc8 /* Output scan direction */
#define LCD_CNTL_SEGREMAP 0xa1 /* Segment remap */
#define LCD_CNTL_DISPON 0xaf /* Display on */
#define LCD_CNTL_PAGE 0xb0 /* Page address */
#define LCD_CNTL_HIGHCOL 0x10 /* Upper column address */
#define LCD_CNTL_LOWCOL 0x00 /* Lower column address */
/** globals **/
static int xoffset; /* needed for flip */
/*** hardware configuration ***/
int lcd_default_contrast(void)
{
return (HW_MASK & LCD_CONTRAST_BIAS) ? 31 : 49;
}
void lcd_set_contrast(int val)
{
lcd_write_command(LCD_CNTL_CONTRAST);
lcd_write_command(val);
}
void lcd_set_invert_display(bool yesno)
{
if (yesno)
lcd_write_command(LCD_SET_REVERSE_DISPLAY);
else
lcd_write_command(LCD_SET_NORMAL_DISPLAY);
}
/* turn the display upside down (call lcd_update() afterwards) */
void lcd_set_flip(bool yesno)
{
#ifdef HAVE_DISPLAY_FLIPPED
if (!yesno)
#else
if (yesno)
#endif
{
lcd_write_command(LCD_SET_SEGMENT_REMAP);
lcd_write_command(LCD_SET_COM_OUTPUT_SCAN_DIRECTION);
xoffset = 132 - LCD_WIDTH; /* 132 colums minus the 112 we have */
}
else
{
lcd_write_command(LCD_SET_SEGMENT_REMAP | 0x01);
lcd_write_command(LCD_SET_COM_OUTPUT_SCAN_DIRECTION | 0x08);
xoffset = 0;
}
}
void lcd_init_device(void)
{
/* Initialize PB0-3 as output pins */
PBCR2 &= 0xff00; /* MD = 00 */
PBIOR |= 0x000f; /* IOR = 1 */
/* inits like the original firmware */
lcd_write_command(LCD_SOFTWARE_RESET);
lcd_write_command(LCD_SET_INTERNAL_REGULATOR_RESISTOR_RATIO + 4);
lcd_write_command(LCD_SET_1OVER4_BIAS_RATIO + 0); /* force 1/4 bias: 0 */
lcd_write_command(LCD_SET_POWER_CONTROL_REGISTER + 7);
/* power control register: op-amp=1, regulator=1, booster=1 */
lcd_write_command(LCD_SET_DISPLAY_ON);
lcd_write_command(LCD_SET_NORMAL_DISPLAY);
lcd_set_flip(false);
lcd_write_command(LCD_SET_DISPLAY_START_LINE + 0);
lcd_set_contrast(lcd_default_contrast());
lcd_write_command(LCD_SET_PAGE_ADDRESS);
lcd_write_command(LCD_SET_LOWER_COLUMN_ADDRESS + 0);
lcd_write_command(LCD_SET_HIGHER_COLUMN_ADDRESS + 0);
lcd_clear_display();
lcd_update();
}
/*** Update functions ***/
/* Performance function that works with an external buffer
note that by and bheight are in 8-pixel units! */
void lcd_blit_mono(const unsigned char *data, int x, int by, int width,
int bheight, int stride)
{
/* Copy display bitmap to hardware */
while (bheight--)
{
lcd_write_command (LCD_CNTL_PAGE | (by++ & 0xf));
lcd_write_command (LCD_CNTL_HIGHCOL | (((x+xoffset)>>4) & 0xf));
lcd_write_command (LCD_CNTL_LOWCOL | ((x+xoffset) & 0xf));
lcd_write_data(data, width);
data += stride;
}
}
/* Helper function for lcd_grey_phase_blit(). */
void lcd_grey_data(unsigned char *values, unsigned char *phases, int count);
/* Performance function that works with an external buffer
note that by and bheight are in 8-pixel units! */
void lcd_blit_grey_phase(unsigned char *values, unsigned char *phases,
int x, int by, int width, int bheight, int stride)
{
stride <<= 3; /* 8 pixels per block */
while (bheight--)
{
lcd_write_command (LCD_CNTL_PAGE | (by++ & 0xf));
lcd_write_command (LCD_CNTL_HIGHCOL | (((x+xoffset)>>4) & 0xf));
lcd_write_command (LCD_CNTL_LOWCOL | ((x+xoffset) & 0xf));
lcd_grey_data(values, phases, width);
values += stride;
phases += stride;
}
}
/* Update the display.
This must be called after all other LCD functions that change the display. */
void lcd_update(void)
{
int y;
/* Copy display bitmap to hardware */
for (y = 0; y < LCD_FBHEIGHT; y++)
{
lcd_write_command (LCD_CNTL_PAGE | (y & 0xf));
lcd_write_command (LCD_CNTL_HIGHCOL | ((xoffset >> 4) & 0xf));
lcd_write_command (LCD_CNTL_LOWCOL | (xoffset & 0xf));
lcd_write_data (FBADDR(0, y), LCD_WIDTH);
}
}
/* Update a fraction of the display. */
void lcd_update_rect(int x, int y, int width, int height)
{
int ymax;
/* The Y coordinates have to work on even 8 pixel rows */
ymax = (y + height-1) >> 3;
y >>= 3;
if(x + width > LCD_WIDTH)
width = LCD_WIDTH - x;
if (width <= 0)
return; /* nothing left to do, 0 is harmful to lcd_write_data() */
if(ymax >= LCD_FBHEIGHT)
ymax = LCD_FBHEIGHT-1;
/* Copy specified rectange bitmap to hardware */
for (; y <= ymax; y++)
{
lcd_write_command (LCD_CNTL_PAGE | (y & 0xf));
lcd_write_command (LCD_CNTL_HIGHCOL | (((x+xoffset) >> 4) & 0xf));
lcd_write_command (LCD_CNTL_LOWCOL | ((x+xoffset) & 0xf));
lcd_write_data (FBADDR(x,y), width);
}
}
| Java |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace XORCISMModel
{
using System;
using System.Collections.Generic;
public partial class PERIMETER
{
public int PerimeterID { get; set; }
}
}
| Java |
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package pt.jkaiui.core.messages;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import pt.jkaiui.core.KaiString;
import pt.jkaiui.manager.I_InMessage;
/**
*
* @author yuu@akron
*/
public class ConnectedArena extends Message implements I_InMessage {
public ConnectedArena() {
}
public Message parse(String s) {
Pattern p = Pattern.compile("KAI_CLIENT_CONNECTED_ARENA;");
Matcher m = p.matcher(s);
if (m.matches()){
ConnectedArena msg = new ConnectedArena();
return msg;
}
return null;
}
}
| Java |
#ifndef NO_OGL
//OpenGL library
#pragma comment( lib, "OpenGL32" )
// MFC
#include "stdafx.h"
//GUI
#include "MainWnd.h"
#include "FullscreenSettings.h"
// Internals
#include "../System.h"
#include "../gba/GBA.h"
#include "../gba/Globals.h"
#include "../Util.h"
#include "../gb/gbGlobals.h"
#include "../common/memgzio.h"
//Math
#include <cmath>
#include <sys/stat.h>
// OpenGL
#include <gl/GL.h> // main include file
#include <GL/glu.h>
#include "glFont.h"
#include <gl/glext.h>
typedef BOOL (APIENTRY *PFNWGLSWAPINTERVALFARPROC)( int );
extern int Init_2xSaI(u32);
extern void winlog(const char *,...);
extern int systemSpeed;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#ifdef MMX
extern "C" bool cpu_mmx;
extern bool detectMMX();
#endif
class OpenGLDisplay : public IDisplay {
private:
HDC hDC;
HGLRC hRC;
GLuint texture;
int width,height;
float size;
u8 *filterData;
RECT destRect;
bool failed;
GLFONT font;
int pitch;
u8 *data;
DWORD currentAdapter;
void initializeMatrices( int w, int h );
bool initializeTexture( int w, int h );
void updateFiltering( int value );
void setVSync( int interval = 1 );
void calculateDestRect( int w, int h );
void initializeFont();
public:
OpenGLDisplay();
virtual ~OpenGLDisplay();
virtual DISPLAY_TYPE getType() { return OPENGL; };
virtual void EnableOpenGL();
virtual void DisableOpenGL();
virtual bool initialize();
virtual void cleanup();
virtual void clear();
virtual void render();
virtual bool changeRenderSize( int w, int h );
virtual void resize( int w, int h );
virtual void setOption( const char *, int );
virtual bool selectFullScreenMode( VIDEO_MODE &mode );
};
#include "gzglfont.h"
//Load GL font
void OpenGLDisplay::initializeFont()
{
int ret;
z_stream strm;
char *buf = (char *)malloc(GZGLFONT_SIZE);
/* allocate inflate state */
strm.zalloc = Z_NULL;
strm.zfree = Z_NULL;
strm.opaque = Z_NULL;
strm.avail_in = 0;
strm.next_in = Z_NULL;
ret = inflateInit2(&strm, 16+MAX_WBITS);
if (ret != Z_OK)
return;
strm.avail_in = sizeof(gzglfont);
strm.next_in = gzglfont;
strm.avail_out = GZGLFONT_SIZE;
strm.next_out = (Bytef *)buf;
ret = inflate(&strm, Z_NO_FLUSH);
if (ret==Z_STREAM_END)
{
glGenTextures( 1, &texture );
glFontCreate(&font, (char *)buf, texture);
texture=0;
}
free(buf);
(void)inflateEnd(&strm);
}
//OpenGL class constructor
OpenGLDisplay::OpenGLDisplay()
{
hDC = NULL;
hRC = NULL;
texture = 0;
width = 0;
height = 0;
size = 0.0f;
failed = false;
filterData = NULL;
currentAdapter = 0;
}
//OpenGL class destroyer
OpenGLDisplay::~OpenGLDisplay()
{
cleanup();
}
//Set OpenGL PFD and contexts
void OpenGLDisplay::EnableOpenGL()
{
PIXELFORMATDESCRIPTOR pfd;
// get the device context (DC)
hDC = GetDC( theApp.m_pMainWnd->GetSafeHwnd() );
// set the pixel format for the DC
ZeroMemory( &pfd, sizeof( pfd ) );
pfd.nSize = sizeof( pfd );
pfd.nVersion = 1;
pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
pfd.iPixelType = PFD_TYPE_RGBA;
pfd.cColorBits = 24;
pfd.cDepthBits = 16;
pfd.iLayerType = PFD_MAIN_PLANE;
SetPixelFormat (GetDC (theApp.m_pMainWnd->GetSafeHwnd()), ChoosePixelFormat ( GetDC (theApp.m_pMainWnd->GetSafeHwnd()), &pfd), &pfd);
wglMakeCurrent (GetDC (theApp.m_pMainWnd->GetSafeHwnd()), wglCreateContext(GetDC (theApp.m_pMainWnd->GetSafeHwnd()) ) );
}
//Remove contexts
void OpenGLDisplay::DisableOpenGL()
{
wglMakeCurrent( NULL, NULL );
wglDeleteContext( hRC );
ReleaseDC( theApp.m_pMainWnd->GetSafeHwnd(), hDC );
}
//Remove resources used
void OpenGLDisplay::cleanup()
{
if(texture != 0) {
glDeleteTextures(1, &texture);
texture = 0;
}
DisableOpenGL();
if(filterData) {
free(filterData);
filterData = NULL;
}
width = 0;
height = 0;
size = 0.0f;
DISPLAY_DEVICE dev;
ZeroMemory( &dev, sizeof(dev) );
dev.cb = sizeof(dev);
EnumDisplayDevices( NULL, currentAdapter, &dev, 0 );
// restore default video mode
ChangeDisplaySettingsEx( dev.DeviceName, NULL, NULL, 0, NULL );
}
//init renderer
bool OpenGLDisplay::initialize()
{
switch( theApp.cartridgeType )
{
case IMAGE_GBA:
theApp.sizeX = 240;
theApp.sizeY = 160;
break;
case IMAGE_GB:
if ( gbBorderOn )
{
theApp.sizeX = 256;
theApp.sizeY = 224;
}
else
{
theApp.sizeX = 160;
theApp.sizeY = 144;
}
break;
}
switch(theApp.videoOption)
{
case VIDEO_1X:
theApp.surfaceSizeX = theApp.sizeX;
theApp.surfaceSizeY = theApp.sizeY;
break;
case VIDEO_2X:
theApp.surfaceSizeX = theApp.sizeX * 2;
theApp.surfaceSizeY = theApp.sizeY * 2;
break;
case VIDEO_3X:
theApp.surfaceSizeX = theApp.sizeX * 3;
theApp.surfaceSizeY = theApp.sizeY * 3;
break;
case VIDEO_4X:
theApp.surfaceSizeX = theApp.sizeX * 4;
theApp.surfaceSizeY = theApp.sizeY * 4;
break;
case VIDEO_5X:
theApp.surfaceSizeX = theApp.sizeX * 5;
theApp.surfaceSizeY = theApp.sizeY * 5;
break;
case VIDEO_6X:
theApp.surfaceSizeX = theApp.sizeX * 6;
theApp.surfaceSizeY = theApp.sizeY * 6;
break;
case VIDEO_320x240:
case VIDEO_640x480:
case VIDEO_800x600:
case VIDEO_1024x768:
case VIDEO_1280x1024:
case VIDEO_OTHER:
{
if( theApp.fullScreenStretch ) {
theApp.surfaceSizeX = theApp.fsWidth;
theApp.surfaceSizeY = theApp.fsHeight;
} else {
float scaleX = (float)theApp.fsWidth / (float)theApp.sizeX;
float scaleY = (float)theApp.fsHeight / (float)theApp.sizeY;
float min = ( scaleX < scaleY ) ? scaleX : scaleY;
if( theApp.maxScale )
min = ( min > (float)theApp.maxScale ) ? (float)theApp.maxScale : min;
theApp.surfaceSizeX = (int)((float)theApp.sizeX * min);
theApp.surfaceSizeY = (int)((float)theApp.sizeY * min);
}
}
break;
}
theApp.rect.left = 0;
theApp.rect.top = 0;
theApp.rect.right = theApp.sizeX;
theApp.rect.bottom = theApp.sizeY;
theApp.dest.left = 0;
theApp.dest.top = 0;
theApp.dest.right = theApp.surfaceSizeX;
theApp.dest.bottom = theApp.surfaceSizeY;
DWORD style = WS_POPUP | WS_VISIBLE;
DWORD styleEx = 0;
if( theApp.videoOption <= VIDEO_6X )
style |= WS_OVERLAPPEDWINDOW;
else
styleEx = 0;
if( theApp.videoOption <= VIDEO_6X )
AdjustWindowRectEx( &theApp.dest, style, TRUE, styleEx );
else
AdjustWindowRectEx( &theApp.dest, style, FALSE, styleEx );
int winSizeX = theApp.dest.right - theApp.dest.left;
int winSizeY = theApp.dest.bottom - theApp.dest.top;
int x = 0, y = 0;
if( theApp.videoOption <= VIDEO_6X ) {
x = theApp.windowPositionX;
y = theApp.windowPositionY;
} else {
winSizeX = theApp.fsWidth;
winSizeY = theApp.fsHeight;
}
theApp.updateMenuBar();
theApp.adjustDestRect();
currentAdapter = theApp.fsAdapter;
DISPLAY_DEVICE dev;
ZeroMemory( &dev, sizeof(dev) );
dev.cb = sizeof(dev);
EnumDisplayDevices( NULL, currentAdapter, &dev, 0 );
if( theApp.videoOption >= VIDEO_320x240 ) {
// enter full screen mode
DEVMODE mode;
ZeroMemory( &mode, sizeof(mode) );
mode.dmSize = sizeof(mode);
mode.dmBitsPerPel = theApp.fsColorDepth;
mode.dmPelsWidth = theApp.fsWidth;
mode.dmPelsHeight = theApp.fsHeight;
mode.dmDisplayFrequency = theApp.fsFrequency;
mode.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT | DM_DISPLAYFREQUENCY;
LONG ret = ChangeDisplaySettingsEx( dev.DeviceName, &mode, NULL, CDS_FULLSCREEN, NULL );
if( ret != DISP_CHANGE_SUCCESSFUL ) {
systemMessage( 0, "Can not change display mode!" );
failed = true;
}
} else {
// restore default mode
ChangeDisplaySettingsEx( dev.DeviceName, NULL, NULL, 0, NULL );
}
EnableOpenGL();
initializeFont();
glPushAttrib( GL_ENABLE_BIT );
glDisable( GL_DEPTH_TEST );
glDisable( GL_CULL_FACE );
glEnable( GL_TEXTURE_2D );
glEnable(GL_BLEND);
glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
initializeMatrices( theApp.surfaceSizeX, theApp.surfaceSizeY );
setVSync( theApp.vsync );
#ifdef MMX
if(!theApp.disableMMX)
cpu_mmx = theApp.detectMMX();
else
cpu_mmx = 0;
#endif
systemRedShift = 3;
systemGreenShift = 11;
systemBlueShift = 19;
systemColorDepth = 32;
theApp.fsColorDepth = 32;
Init_2xSaI(32);
utilUpdateSystemColorMaps(theApp.cartridgeType == IMAGE_GBA && gbColorOption == 1);
theApp.updateFilter();
theApp.updateIFB();
pitch = theApp.filterWidth * (systemColorDepth>>3) + 4;
data = pix + ( theApp.sizeX + 1 ) * 4;
if(failed)
return false;
return true;
}
//clear colour buffer
void OpenGLDisplay::clear()
{
glClearColor(0.0,0.0,0.0,1.0);
glClear( GL_COLOR_BUFFER_BIT );
}
//main render func
void OpenGLDisplay::render()
{
clear();
pitch = theApp.filterWidth * (systemColorDepth>>3) + 4;
data = pix + ( theApp.sizeX + 1 ) * 4;
// apply pixel filter
if(theApp.filterFunction) {
data = filterData;
theApp.filterFunction(
pix + pitch,
pitch,
(u8*)theApp.delta,
(u8*)filterData,
width * 4 ,
theApp.filterWidth,
theApp.filterHeight);
}
// Texturemap complete texture to surface
// so we have free scaling and antialiasing
if( theApp.filterFunction ) {
glPixelStorei( GL_UNPACK_ROW_LENGTH, width);
} else {
glPixelStorei( GL_UNPACK_ROW_LENGTH, theApp.sizeX + 1 );
}
glTexSubImage2D(GL_TEXTURE_2D,0,0,0,width,height,GL_RGBA,GL_UNSIGNED_BYTE,data );
glBegin( GL_QUADS );
glTexCoord2f( 0.0f, 0.0f );
glVertex3i( 0, 0, 0 );
glTexCoord2f( (float)(width) / size, 0.0f );
glVertex3i( theApp.surfaceSizeX, 0, 0 );
glTexCoord2f( (float)(width) / size, (float)(height) / size );
glVertex3i( theApp.surfaceSizeX, theApp.surfaceSizeY, 0 );
glTexCoord2f( 0.0f, (float)(height) / size );
glVertex3i( 0, theApp.surfaceSizeY, 0 );
glEnd();
if( theApp.showSpeed ) { // && ( theApp.videoOption > VIDEO_6X ) ) {
char buffer[30];
if( theApp.showSpeed == 1 ) {
sprintf( buffer, "%3d%%", systemSpeed );
} else {
sprintf( buffer, "%3d%%(%d, %d fps)", systemSpeed, systemFrameSkip, theApp.showRenderedFrames );
}
glFontBegin(&font);
glPushMatrix();
float fontscale = (float)theApp.surfaceSizeX / 100.0f;
glScalef(fontscale, fontscale, fontscale);
glColor4f(1.0f, 0.25f, 0.25f, 1.0f);
glFontTextOut(buffer, (theApp.surfaceSizeX-(strlen(buffer)*11))/(fontscale*2), (theApp.surfaceSizeY-20)/fontscale, 0);
glPopMatrix();
glFontEnd();
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBindTexture( GL_TEXTURE_2D, texture );
}
if( theApp.screenMessage ) {
if( ( ( GetTickCount() - theApp.screenMessageTime ) < 3000 ) && !theApp.disableStatusMessage ) {
glFontBegin(&font);
glPushMatrix();
float fontscale = (float)theApp.surfaceSizeX / 100.0f;
glScalef(fontscale, fontscale, fontscale);
glColor4f(1.0f, 0.25f, 0.25f, 1.0f);
glFontTextOut((char *)((const char *)theApp.screenMessageBuffer), (theApp.surfaceSizeX-(theApp.screenMessageBuffer.GetLength()*11))/(fontscale*2), (theApp.surfaceSizeY-40)/fontscale, 0);
glPopMatrix();
glFontEnd();
glColor4f(1.0f, 1.0f, 1.0f, 1.0f);
glBindTexture( GL_TEXTURE_2D, texture );
} else {
theApp.screenMessage = false;
}
}
glFlush();
SwapBuffers( hDC );
// since OpenGL draws on the back buffer,
// we have to swap it to the front buffer to see the content
}
//resize screen
void OpenGLDisplay::resize( int w, int h )
{
initializeMatrices( w, h );
}
//update filtering methods
void OpenGLDisplay::updateFiltering( int value )
{
switch( value )
{
case 0:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
break;
case 1:
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
}
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
}
//init projection matrixes and viewports
void OpenGLDisplay::initializeMatrices( int w, int h )
{
if( theApp.fullScreenStretch ) {
glViewport( 0, 0, w, h );
} else {
calculateDestRect( w, h );
glViewport(
destRect.left,
destRect.top,
destRect.right - destRect.left,
destRect.bottom - destRect.top );
}
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
glOrtho(
/* left */ 1.0f,
/* right */ (GLdouble)(w - 1),
/* bottom */ (GLdouble)(h - 1),
/* top */ 1.0f,
0.0f,
1.0f );
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
//init font texture
bool OpenGLDisplay::initializeTexture( int w, int h )
{
// size = 2^n
// w = 24 > size = 256 = 2^8
// w = 255 > size = 256 = 2^8
// w = 256 > size = 512 = 2^9
// w = 300 > size = 512 = 2^9
// OpenGL textures have to be square and a power of 2
// We could use methods that allow tex's to not be powers of two
// but that requires extra OGL extensions
float n1 = log10( (float)w ) / log10( 2.0f );
float n2 = log10( (float)h ) / log10( 2.0f );
float n = ( n1 > n2 ) ? n1 : n2;
if( ((float)((int)n)) != n ) {
// round up
n = ((float)((int)n)) + 1.0f;
}
size = pow( 2.0f, n );
glGenTextures( 1, &texture );
glBindTexture( GL_TEXTURE_2D, texture );
updateFiltering( theApp.glFilter );
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA,
(GLsizei)size,
(GLsizei)size,
0,
GL_RGBA,
GL_UNSIGNED_BYTE,
NULL );
width = w;
height = h;
//return ( glGetError() == GL_NO_ERROR) ? true : false;
// Workaround: We usually get GL_INVALID_VALUE, but somehow it works nevertheless
// In consequence, we must not treat it as an error or else the app behaves as if an error occured.
// This in the end results in theApp->input not being created = no input when switching from D3D to OGL
return true;
}
//turn vsync on or off
void OpenGLDisplay::setVSync( int interval )
{
const char *extensions = (const char *)glGetString( GL_EXTENSIONS );
if( strstr( extensions, "WGL_EXT_swap_control" ) == 0 ) {
winlog( "Error: WGL_EXT_swap_control extension not supported on your computer.\n" );
return;
} else {
PFNWGLSWAPINTERVALFARPROC wglSwapIntervalEXT = NULL;
wglSwapIntervalEXT = (PFNWGLSWAPINTERVALFARPROC)wglGetProcAddress( "wglSwapIntervalEXT" );
if( wglSwapIntervalEXT ) {
wglSwapIntervalEXT( interval );
}
}
}
//change render size for fonts and filter data
bool OpenGLDisplay::changeRenderSize( int w, int h )
{
if( (width != w) || (height != h) ) {
if( texture != 0 ) {
glDeleteTextures( 1, &texture );
texture = 0;
}
if( !initializeTexture( w, h ) ) {
failed = true;
return false;
}
if (filterData)
free(filterData);
filterData = (u8 *)malloc(4*w*h);
}
return true;
}
//calculate RECTs
void OpenGLDisplay::calculateDestRect( int w, int h )
{
float scaleX = (float)w / (float)width;
float scaleY = (float)h / (float)height;
float min = (scaleX < scaleY) ? scaleX : scaleY;
if( theApp.maxScale && (min > theApp.maxScale) ) {
min = (float)theApp.maxScale;
}
destRect.left = 0;
destRect.top = 0;
destRect.right = (LONG)(width * min);
destRect.bottom = (LONG)(height * min);
if( destRect.right != w ) {
LONG diff = (w - destRect.right) / 2;
destRect.left += diff;
destRect.right += diff;
}
if( destRect.bottom != h ) {
LONG diff = (h - destRect.bottom) / 2;
destRect.top += diff;
destRect.bottom += diff;
}
}
//config options
void OpenGLDisplay::setOption( const char *option, int value )
{
if( !_tcscmp( option, _T("vsync") ) ) {
setVSync( value );
}
if( !_tcscmp( option, _T("glFilter") ) ) {
updateFiltering( value );
}
if( !_tcscmp( option, _T("maxScale") ) ) {
initializeMatrices( theApp.dest.right-theApp.dest.left, theApp.dest.bottom-theApp.dest.top );
}
if( !_tcscmp( option, _T("fullScreenStretch") ) ) {
initializeMatrices( theApp.dest.right-theApp.dest.left, theApp.dest.bottom-theApp.dest.top );
}
}
//set fullscreen mode
bool OpenGLDisplay::selectFullScreenMode( VIDEO_MODE &mode )
{
FullscreenSettings dlg;
dlg.setAPI( this->getType() );
INT_PTR ret = dlg.DoModal();
if( ret == IDOK ) {
mode.adapter = dlg.m_device;
switch( dlg.m_colorDepth )
{
case 30:
// TODO: support
return false;
break;
case 24:
mode.bitDepth = 32;
break;
case 16:
case 15:
mode.bitDepth = 16;
break;
}
mode.width = dlg.m_width;
mode.height = dlg.m_height;
mode.frequency = dlg.m_refreshRate;
return true;
} else {
return false;
}
}
IDisplay *newOpenGLDisplay()
{
return new OpenGLDisplay();
}
#endif // #ifndef NO_OGL
| Java |
/* asn.h
*
* Copyright (C) 2006-2016 wolfSSL Inc.
*
* This file is part of wolfSSL.
*
* wolfSSL 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.
*
* wolfSSL 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-1335, USA
*/
#ifndef WOLF_CRYPT_ASN_H
#define WOLF_CRYPT_ASN_H
#include <wolfssl/wolfcrypt/types.h>
#ifndef NO_ASN
#include <wolfssl/wolfcrypt/integer.h>
#ifndef NO_RSA
#include <wolfssl/wolfcrypt/rsa.h>
#endif
/* fips declare of RsaPrivateKeyDecode @wc_fips */
#if defined(HAVE_FIPS) && !defined(NO_RSA)
#include <cyassl/ctaocrypt/rsa.h>
#endif
#ifndef NO_DH
#include <wolfssl/wolfcrypt/dh.h>
#endif
#ifndef NO_DSA
#include <wolfssl/wolfcrypt/dsa.h>
#endif
#ifndef NO_SHA
#include <wolfssl/wolfcrypt/sha.h>
#endif
#ifndef NO_MD5
#include <wolfssl/wolfcrypt/md5.h>
#endif
#include <wolfssl/wolfcrypt/sha256.h>
#include <wolfssl/wolfcrypt/asn_public.h> /* public interface */
#ifdef HAVE_ECC
#include <wolfssl/wolfcrypt/ecc.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
enum {
ISSUER = 0,
SUBJECT = 1,
EXTERNAL_SERIAL_SIZE = 32,
BEFORE = 0,
AFTER = 1
};
/* ASN Tags */
enum ASN_Tags {
ASN_BOOLEAN = 0x01,
ASN_INTEGER = 0x02,
ASN_BIT_STRING = 0x03,
ASN_OCTET_STRING = 0x04,
ASN_TAG_NULL = 0x05,
ASN_OBJECT_ID = 0x06,
ASN_ENUMERATED = 0x0a,
ASN_UTF8STRING = 0x0c,
ASN_SEQUENCE = 0x10,
ASN_SET = 0x11,
ASN_UTC_TIME = 0x17,
ASN_OTHER_TYPE = 0x00,
ASN_RFC822_TYPE = 0x01,
ASN_DNS_TYPE = 0x02,
ASN_DIR_TYPE = 0x04,
ASN_GENERALIZED_TIME = 0x18,
CRL_EXTENSIONS = 0xa0,
ASN_EXTENSIONS = 0xa3,
ASN_LONG_LENGTH = 0x80
};
enum ASN_Flags{
ASN_CONSTRUCTED = 0x20,
ASN_CONTEXT_SPECIFIC = 0x80
};
enum DN_Tags {
ASN_COMMON_NAME = 0x03, /* CN */
ASN_SUR_NAME = 0x04, /* SN */
ASN_SERIAL_NUMBER = 0x05, /* serialNumber */
ASN_COUNTRY_NAME = 0x06, /* C */
ASN_LOCALITY_NAME = 0x07, /* L */
ASN_STATE_NAME = 0x08, /* ST */
ASN_ORG_NAME = 0x0a, /* O */
ASN_ORGUNIT_NAME = 0x0b /* OU */
};
enum PBES {
PBE_MD5_DES = 0,
PBE_SHA1_DES = 1,
PBE_SHA1_DES3 = 2,
PBE_SHA1_RC4_128 = 3,
PBES2 = 13 /* algo ID */
};
enum ENCRYPTION_TYPES {
DES_TYPE = 0,
DES3_TYPE = 1,
RC4_TYPE = 2
};
enum ECC_TYPES {
ECC_PREFIX_0 = 160,
ECC_PREFIX_1 = 161
};
enum Misc_ASN {
ASN_NAME_MAX = 256,
MAX_SALT_SIZE = 64, /* MAX PKCS Salt length */
MAX_IV_SIZE = 64, /* MAX PKCS Iv length */
MAX_KEY_SIZE = 64, /* MAX PKCS Key length */
PKCS5 = 5, /* PKCS oid tag */
PKCS5v2 = 6, /* PKCS #5 v2.0 */
PKCS12 = 12, /* PKCS #12 */
MAX_UNICODE_SZ = 256,
ASN_BOOL_SIZE = 2, /* including type */
ASN_ECC_HEADER_SZ = 2, /* String type + 1 byte len */
ASN_ECC_CONTEXT_SZ = 2, /* Content specific type + 1 byte len */
#ifdef NO_SHA
KEYID_SIZE = SHA256_DIGEST_SIZE,
#else
KEYID_SIZE = SHA_DIGEST_SIZE,
#endif
RSA_INTS = 8, /* RSA ints in private key */
DSA_INTS = 5, /* DSA ints in private key */
MIN_DATE_SIZE = 13,
MAX_DATE_SIZE = 32,
ASN_GEN_TIME_SZ = 15, /* 7 numbers * 2 + Zulu tag */
MAX_ENCODED_SIG_SZ = 512,
MAX_SIG_SZ = 256,
MAX_ALGO_SZ = 20,
MAX_SEQ_SZ = 5, /* enum(seq | con) + length(4) */
MAX_SET_SZ = 5, /* enum(set | con) + length(4) */
MAX_OCTET_STR_SZ = 5, /* enum(set | con) + length(4) */
MAX_EXP_SZ = 5, /* enum(contextspec|con|exp) + length(4) */
MAX_PRSTR_SZ = 5, /* enum(prstr) + length(4) */
MAX_VERSION_SZ = 5, /* enum + id + version(byte) + (header(2))*/
MAX_ENCODED_DIG_SZ = 73, /* sha512 + enum(bit or octet) + length(4) */
MAX_RSA_INT_SZ = 517, /* RSA raw sz 4096 for bits + tag + len(4) */
MAX_NTRU_KEY_SZ = 610, /* NTRU 112 bit public key */
MAX_NTRU_ENC_SZ = 628, /* NTRU 112 bit DER public encoding */
MAX_LENGTH_SZ = 4, /* Max length size for DER encoding */
MAX_RSA_E_SZ = 16, /* Max RSA public e size */
MAX_CA_SZ = 32, /* Max encoded CA basic constraint length */
MAX_SN_SZ = 35, /* Max encoded serial number (INT) length */
MAX_DER_DIGEST_SZ = MAX_ENCODED_DIG_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ, /* Maximum DER digest size */
#ifdef WOLFSSL_CERT_GEN
#ifdef WOLFSSL_CERT_REQ
/* Max encoded cert req attributes length */
MAX_ATTRIB_SZ = MAX_SEQ_SZ * 3 + (11 + MAX_SEQ_SZ) * 2 +
MAX_PRSTR_SZ + CTC_NAME_SIZE, /* 11 is the OID size */
#endif
#if defined(WOLFSSL_ALT_NAMES) || defined(WOLFSSL_CERT_EXT)
MAX_EXTENSIONS_SZ = 1 + MAX_LENGTH_SZ + CTC_MAX_ALT_SIZE,
#else
MAX_EXTENSIONS_SZ = 1 + MAX_LENGTH_SZ + MAX_CA_SZ,
#endif
/* Max total extensions, id + len + others */
#endif
#ifdef WOLFSSL_CERT_EXT
MAX_KID_SZ = 45, /* Max encoded KID length (SHA-256 case) */
MAX_KEYUSAGE_SZ = 18, /* Max encoded Key Usage length */
MAX_OID_SZ = 32, /* Max DER length of OID*/
MAX_OID_STRING_SZ = 64, /* Max string length representation of OID*/
MAX_CERTPOL_NB = CTC_MAX_CERTPOL_NB,/* Max number of Cert Policy */
MAX_CERTPOL_SZ = CTC_MAX_CERTPOL_SZ,
#endif
OCSP_NONCE_EXT_SZ = 37, /* OCSP Nonce Extension size */
MAX_OCSP_EXT_SZ = 58, /* Max OCSP Extension length */
MAX_OCSP_NONCE_SZ = 16, /* OCSP Nonce size */
EIGHTK_BUF = 8192, /* Tmp buffer size */
MAX_PUBLIC_KEY_SZ = MAX_NTRU_ENC_SZ + MAX_ALGO_SZ + MAX_SEQ_SZ * 2,
/* use bigger NTRU size */
HEADER_ENCRYPTED_KEY_SIZE = 88,/* Extra header size for encrypted key */
TRAILING_ZERO = 1 /* Used for size of zero pad */
};
enum Oid_Types {
oidHashType = 0,
oidSigType = 1,
oidKeyType = 2,
oidCurveType = 3,
oidBlkType = 4,
oidOcspType = 5,
oidCertExtType = 6,
oidCertAuthInfoType = 7,
oidCertPolicyType = 8,
oidCertAltNameType = 9,
oidCertKeyUseType = 10,
oidKdfType = 11,
oidIgnoreType
};
enum Hash_Sum {
MD2h = 646,
MD5h = 649,
SHAh = 88,
SHA256h = 414,
SHA384h = 415,
SHA512h = 416
};
enum Block_Sum {
DESb = 69,
DES3b = 652
};
enum Key_Sum {
DSAk = 515,
RSAk = 645,
NTRUk = 274,
ECDSAk = 518
};
enum Ecc_Sum {
ECC_256R1 = 526,
ECC_384R1 = 210,
ECC_521R1 = 211,
ECC_160R1 = 184,
ECC_192R1 = 520,
ECC_224R1 = 209
};
enum KDF_Sum {
PBKDF2_OID = 660
};
enum Extensions_Sum {
BASIC_CA_OID = 133,
ALT_NAMES_OID = 131,
CRL_DIST_OID = 145,
AUTH_INFO_OID = 69,
AUTH_KEY_OID = 149,
SUBJ_KEY_OID = 128,
CERT_POLICY_OID = 146,
KEY_USAGE_OID = 129, /* 2.5.29.15 */
INHIBIT_ANY_OID = 168, /* 2.5.29.54 */
EXT_KEY_USAGE_OID = 151, /* 2.5.29.37 */
NAME_CONS_OID = 144 /* 2.5.29.30 */
};
enum CertificatePolicy_Sum {
CP_ANY_OID = 146 /* id-ce 32 0 */
};
enum SepHardwareName_Sum {
HW_NAME_OID = 79 /* 1.3.6.1.5.5.7.8.4 from RFC 4108*/
};
enum AuthInfo_Sum {
AIA_OCSP_OID = 116, /* 1.3.6.1.5.5.7.48.1 */
AIA_CA_ISSUER_OID = 117 /* 1.3.6.1.5.5.7.48.2 */
};
enum ExtKeyUsage_Sum { /* From RFC 5280 */
EKU_ANY_OID = 151, /* 2.5.29.37.0, anyExtendedKeyUsage */
EKU_SERVER_AUTH_OID = 71, /* 1.3.6.1.5.5.7.3.1, id-kp-serverAuth */
EKU_CLIENT_AUTH_OID = 72, /* 1.3.6.1.5.5.7.3.2, id-kp-clientAuth */
EKU_OCSP_SIGN_OID = 79 /* 1.3.6.1.5.5.7.3.9, OCSPSigning */
};
enum VerifyType {
NO_VERIFY = 0,
VERIFY = 1
};
#ifdef WOLFSSL_CERT_EXT
enum KeyIdType {
SKID_TYPE = 0,
AKID_TYPE = 1
};
#endif
/* Key usage extension bits */
#define KEYUSE_DIGITAL_SIG 0x0080
#define KEYUSE_CONTENT_COMMIT 0x0040
#define KEYUSE_KEY_ENCIPHER 0x0020
#define KEYUSE_DATA_ENCIPHER 0x0010
#define KEYUSE_KEY_AGREE 0x0008
#define KEYUSE_KEY_CERT_SIGN 0x0004
#define KEYUSE_CRL_SIGN 0x0002
#define KEYUSE_ENCIPHER_ONLY 0x0001
#define KEYUSE_DECIPHER_ONLY 0x8000
#define EXTKEYUSE_ANY 0x08
#define EXTKEYUSE_OCSP_SIGN 0x04
#define EXTKEYUSE_CLIENT_AUTH 0x02
#define EXTKEYUSE_SERVER_AUTH 0x01
typedef struct DNS_entry DNS_entry;
struct DNS_entry {
DNS_entry* next; /* next on DNS list */
char* name; /* actual DNS name */
};
typedef struct Base_entry Base_entry;
struct Base_entry {
Base_entry* next; /* next on name base list */
char* name; /* actual name base */
int nameSz; /* name length */
byte type; /* Name base type (DNS or RFC822) */
};
struct DecodedName {
char* fullName;
int fullNameLen;
int entryCount;
int cnIdx;
int cnLen;
int snIdx;
int snLen;
int cIdx;
int cLen;
int lIdx;
int lLen;
int stIdx;
int stLen;
int oIdx;
int oLen;
int ouIdx;
int ouLen;
int emailIdx;
int emailLen;
int uidIdx;
int uidLen;
int serialIdx;
int serialLen;
};
typedef struct DecodedCert DecodedCert;
typedef struct DecodedName DecodedName;
typedef struct Signer Signer;
#ifdef WOLFSSL_TRUST_PEER_CERT
typedef struct TrustedPeerCert TrustedPeerCert;
#endif /* WOLFSSL_TRUST_PEER_CERT */
struct DecodedCert {
byte* publicKey;
word32 pubKeySize;
int pubKeyStored;
word32 certBegin; /* offset to start of cert */
word32 sigIndex; /* offset to start of signature */
word32 sigLength; /* length of signature */
word32 signatureOID; /* sum of algorithm object id */
word32 keyOID; /* sum of key algo object id */
int version; /* cert version, 1 or 3 */
DNS_entry* altNames; /* alt names list of dns entries */
#ifndef IGNORE_NAME_CONSTRAINTS
DNS_entry* altEmailNames; /* alt names list of RFC822 entries */
Base_entry* permittedNames; /* Permitted name bases */
Base_entry* excludedNames; /* Excluded name bases */
#endif /* IGNORE_NAME_CONSTRAINTS */
byte subjectHash[KEYID_SIZE]; /* hash of all Names */
byte issuerHash[KEYID_SIZE]; /* hash of all Names */
#ifdef HAVE_OCSP
byte issuerKeyHash[KEYID_SIZE]; /* hash of the public Key */
#endif /* HAVE_OCSP */
byte* signature; /* not owned, points into raw cert */
char* subjectCN; /* CommonName */
int subjectCNLen; /* CommonName Length */
char subjectCNEnc; /* CommonName Encoding */
int subjectCNStored; /* have we saved a copy we own */
char issuer[ASN_NAME_MAX]; /* full name including common name */
char subject[ASN_NAME_MAX]; /* full name including common name */
int verify; /* Default to yes, but could be off */
byte* source; /* byte buffer holder cert, NOT owner */
word32 srcIdx; /* current offset into buffer */
word32 maxIdx; /* max offset based on init size */
void* heap; /* for user memory overrides */
byte serial[EXTERNAL_SERIAL_SIZE]; /* raw serial number */
int serialSz; /* raw serial bytes stored */
byte* extensions; /* not owned, points into raw cert */
int extensionsSz; /* length of cert extensions */
word32 extensionsIdx; /* if want to go back and parse later */
byte* extAuthInfo; /* Authority Information Access URI */
int extAuthInfoSz; /* length of the URI */
byte* extCrlInfo; /* CRL Distribution Points */
int extCrlInfoSz; /* length of the URI */
byte extSubjKeyId[KEYID_SIZE]; /* Subject Key ID */
byte extSubjKeyIdSet; /* Set when the SKID was read from cert */
byte extAuthKeyId[KEYID_SIZE]; /* Authority Key ID */
byte extAuthKeyIdSet; /* Set when the AKID was read from cert */
#ifndef IGNORE_NAME_CONSTRAINTS
byte extNameConstraintSet;
#endif /* IGNORE_NAME_CONSTRAINTS */
byte isCA; /* CA basic constraint true */
byte weOwnAltNames; /* altNames haven't been given to copy */
byte extKeyUsageSet;
word16 extKeyUsage; /* Key usage bitfield */
byte extExtKeyUsageSet; /* Extended Key Usage */
byte extExtKeyUsage; /* Extended Key usage bitfield */
#ifdef OPENSSL_EXTRA
byte extBasicConstSet;
byte extBasicConstCrit;
byte extBasicConstPlSet;
word32 pathLength; /* CA basic constraint path length, opt */
byte extSubjAltNameSet;
byte extSubjAltNameCrit;
byte extAuthKeyIdCrit;
#ifndef IGNORE_NAME_CONSTRAINTS
byte extNameConstraintCrit;
#endif /* IGNORE_NAME_CONSTRAINTS */
byte extSubjKeyIdCrit;
byte extKeyUsageCrit;
byte extExtKeyUsageCrit;
byte* extExtKeyUsageSrc;
word32 extExtKeyUsageSz;
word32 extExtKeyUsageCount;
byte* extAuthKeyIdSrc;
word32 extAuthKeyIdSz;
byte* extSubjKeyIdSrc;
word32 extSubjKeyIdSz;
#endif
#ifdef HAVE_ECC
word32 pkCurveOID; /* Public Key's curve OID */
#endif /* HAVE_ECC */
byte* beforeDate;
int beforeDateLen;
byte* afterDate;
int afterDateLen;
#ifdef HAVE_PKCS7
byte* issuerRaw; /* pointer to issuer inside source */
int issuerRawLen;
#endif
#ifndef IGNORE_NAME_CONSTRAINT
byte* subjectRaw; /* pointer to subject inside source */
int subjectRawLen;
#endif
#if defined(WOLFSSL_CERT_GEN)
/* easy access to subject info for other sign */
char* subjectSN;
int subjectSNLen;
char subjectSNEnc;
char* subjectC;
int subjectCLen;
char subjectCEnc;
char* subjectL;
int subjectLLen;
char subjectLEnc;
char* subjectST;
int subjectSTLen;
char subjectSTEnc;
char* subjectO;
int subjectOLen;
char subjectOEnc;
char* subjectOU;
int subjectOULen;
char subjectOUEnc;
char* subjectEmail;
int subjectEmailLen;
#endif /* WOLFSSL_CERT_GEN */
#ifdef OPENSSL_EXTRA
DecodedName issuerName;
DecodedName subjectName;
#endif /* OPENSSL_EXTRA */
#ifdef WOLFSSL_SEP
int deviceTypeSz;
byte* deviceType;
int hwTypeSz;
byte* hwType;
int hwSerialNumSz;
byte* hwSerialNum;
#ifdef OPENSSL_EXTRA
byte extCertPolicySet;
byte extCertPolicyCrit;
#endif /* OPENSSL_EXTRA */
#endif /* WOLFSSL_SEP */
#ifdef WOLFSSL_CERT_EXT
char extCertPolicies[MAX_CERTPOL_NB][MAX_CERTPOL_SZ];
int extCertPoliciesNb;
#endif /* WOLFSSL_CERT_EXT */
};
extern const char* BEGIN_CERT;
extern const char* END_CERT;
extern const char* BEGIN_CERT_REQ;
extern const char* END_CERT_REQ;
extern const char* BEGIN_DH_PARAM;
extern const char* END_DH_PARAM;
extern const char* BEGIN_X509_CRL;
extern const char* END_X509_CRL;
extern const char* BEGIN_RSA_PRIV;
extern const char* END_RSA_PRIV;
extern const char* BEGIN_PRIV_KEY;
extern const char* END_PRIV_KEY;
extern const char* BEGIN_ENC_PRIV_KEY;
extern const char* END_ENC_PRIV_KEY;
extern const char* BEGIN_EC_PRIV;
extern const char* END_EC_PRIV;
extern const char* BEGIN_DSA_PRIV;
extern const char* END_DSA_PRIV;
extern const char* BEGIN_PUB_KEY;
extern const char* END_PUB_KEY;
#ifdef NO_SHA
#define SIGNER_DIGEST_SIZE SHA256_DIGEST_SIZE
#else
#define SIGNER_DIGEST_SIZE SHA_DIGEST_SIZE
#endif
/* CA Signers */
/* if change layout change PERSIST_CERT_CACHE functions too */
struct Signer {
word32 pubKeySize;
word32 keyOID; /* key type */
word16 keyUsage;
byte* publicKey;
int nameLen;
char* name; /* common name */
#ifndef IGNORE_NAME_CONSTRAINTS
Base_entry* permittedNames;
Base_entry* excludedNames;
#endif /* IGNORE_NAME_CONSTRAINTS */
byte subjectNameHash[SIGNER_DIGEST_SIZE];
/* sha hash of names in certificate */
#ifndef NO_SKID
byte subjectKeyIdHash[SIGNER_DIGEST_SIZE];
/* sha hash of names in certificate */
#endif
Signer* next;
};
#ifdef WOLFSSL_TRUST_PEER_CERT
/* used for having trusted peer certs rather then CA */
struct TrustedPeerCert {
int nameLen;
char* name; /* common name */
#ifndef IGNORE_NAME_CONSTRAINTS
Base_entry* permittedNames;
Base_entry* excludedNames;
#endif /* IGNORE_NAME_CONSTRAINTS */
byte subjectNameHash[SIGNER_DIGEST_SIZE];
/* sha hash of names in certificate */
#ifndef NO_SKID
byte subjectKeyIdHash[SIGNER_DIGEST_SIZE];
/* sha hash of names in certificate */
#endif
word32 sigLen;
byte* sig;
struct TrustedPeerCert* next;
};
#endif /* WOLFSSL_TRUST_PEER_CERT */
/* not for public consumption but may use for testing sometimes */
#ifdef WOLFSSL_TEST_CERT
#define WOLFSSL_TEST_API WOLFSSL_API
#else
#define WOLFSSL_TEST_API WOLFSSL_LOCAL
#endif
WOLFSSL_TEST_API void FreeAltNames(DNS_entry*, void*);
#ifndef IGNORE_NAME_CONSTRAINTS
WOLFSSL_TEST_API void FreeNameSubtrees(Base_entry*, void*);
#endif /* IGNORE_NAME_CONSTRAINTS */
WOLFSSL_TEST_API void InitDecodedCert(DecodedCert*, byte*, word32, void*);
WOLFSSL_TEST_API void FreeDecodedCert(DecodedCert*);
WOLFSSL_TEST_API int ParseCert(DecodedCert*, int type, int verify, void* cm);
WOLFSSL_LOCAL int ParseCertRelative(DecodedCert*,int type,int verify,void* cm);
WOLFSSL_LOCAL int DecodeToKey(DecodedCert*, int verify);
WOLFSSL_LOCAL Signer* MakeSigner(void*);
WOLFSSL_LOCAL void FreeSigner(Signer*, void*);
WOLFSSL_LOCAL void FreeSignerTable(Signer**, int, void*);
#ifdef WOLFSSL_TRUST_PEER_CERT
WOLFSSL_LOCAL void FreeTrustedPeer(TrustedPeerCert*, void*);
WOLFSSL_LOCAL void FreeTrustedPeerTable(TrustedPeerCert**, int, void*);
#endif /* WOLFSSL_TRUST_PEER_CERT */
WOLFSSL_LOCAL int ToTraditional(byte* buffer, word32 length);
WOLFSSL_LOCAL int ToTraditionalEnc(byte* buffer, word32 length,const char*,int);
WOLFSSL_LOCAL int ValidateDate(const byte* date, byte format, int dateType);
/* ASN.1 helper functions */
WOLFSSL_LOCAL int GetLength(const byte* input, word32* inOutIdx, int* len,
word32 maxIdx);
WOLFSSL_LOCAL int GetSequence(const byte* input, word32* inOutIdx, int* len,
word32 maxIdx);
WOLFSSL_LOCAL int GetSet(const byte* input, word32* inOutIdx, int* len,
word32 maxIdx);
WOLFSSL_LOCAL int GetMyVersion(const byte* input, word32* inOutIdx,
int* version);
WOLFSSL_LOCAL int GetInt(mp_int* mpi, const byte* input, word32* inOutIdx,
word32 maxIdx);
WOLFSSL_LOCAL int GetObjectId(const byte* input, word32* inOutIdx, word32* oid,
word32 oidType, word32 maxIdx);
WOLFSSL_LOCAL int GetAlgoId(const byte* input, word32* inOutIdx, word32* oid,
word32 oidType, word32 maxIdx);
WOLFSSL_LOCAL word32 SetLength(word32 length, byte* output);
WOLFSSL_LOCAL word32 SetSequence(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetOctetString(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetImplicit(byte tag,byte number,word32 len,byte* output);
WOLFSSL_LOCAL word32 SetExplicit(byte number, word32 len, byte* output);
WOLFSSL_LOCAL word32 SetSet(word32 len, byte* output);
WOLFSSL_LOCAL word32 SetAlgoID(int algoOID,byte* output,int type,int curveSz);
WOLFSSL_LOCAL int SetMyVersion(word32 version, byte* output, int header);
WOLFSSL_LOCAL int SetSerialNumber(const byte* sn, word32 snSz, byte* output);
WOLFSSL_LOCAL int GetNameHash(const byte* source, word32* idx, byte* hash,
int maxIdx);
#ifdef HAVE_ECC
/* ASN sig helpers */
WOLFSSL_LOCAL int StoreECC_DSA_Sig(byte* out, word32* outLen, mp_int* r,
mp_int* s);
WOLFSSL_LOCAL int DecodeECC_DSA_Sig(const byte* sig, word32 sigLen,
mp_int* r, mp_int* s);
#endif
#ifdef WOLFSSL_CERT_GEN
enum cert_enums {
NAME_ENTRIES = 8,
JOINT_LEN = 2,
EMAIL_JOINT_LEN = 9,
RSA_KEY = 10,
NTRU_KEY = 11,
ECC_KEY = 12
};
#ifndef WOLFSSL_PEMCERT_TODER_DEFINED
#ifndef NO_FILESYSTEM
/* forward from wolfSSL */
WOLFSSL_API
int wolfSSL_PemCertToDer(const char* fileName,unsigned char* derBuf,int derSz);
#define WOLFSSL_PEMCERT_TODER_DEFINED
#endif
#endif
#endif /* WOLFSSL_CERT_GEN */
/* for pointer use */
typedef struct CertStatus CertStatus;
#ifdef HAVE_OCSP
enum Ocsp_Response_Status {
OCSP_SUCCESSFUL = 0, /* Response has valid confirmations */
OCSP_MALFORMED_REQUEST = 1, /* Illegal confirmation request */
OCSP_INTERNAL_ERROR = 2, /* Internal error in issuer */
OCSP_TRY_LATER = 3, /* Try again later */
OCSP_SIG_REQUIRED = 5, /* Must sign the request (4 is skipped) */
OCSP_UNAUTHROIZED = 6 /* Request unauthorized */
};
enum Ocsp_Cert_Status {
CERT_GOOD = 0,
CERT_REVOKED = 1,
CERT_UNKNOWN = 2
};
enum Ocsp_Sums {
OCSP_BASIC_OID = 117,
OCSP_NONCE_OID = 118
};
typedef struct OcspRequest OcspRequest;
typedef struct OcspResponse OcspResponse;
struct CertStatus {
CertStatus* next;
byte serial[EXTERNAL_SERIAL_SIZE];
int serialSz;
int status;
byte thisDate[MAX_DATE_SIZE];
byte nextDate[MAX_DATE_SIZE];
byte thisDateFormat;
byte nextDateFormat;
byte* rawOcspResponse;
word32 rawOcspResponseSz;
};
struct OcspResponse {
int responseStatus; /* return code from Responder */
byte* response; /* Pointer to beginning of OCSP Response */
word32 responseSz; /* length of the OCSP Response */
byte producedDate[MAX_DATE_SIZE];
/* Date at which this response was signed */
byte producedDateFormat; /* format of the producedDate */
byte* issuerHash;
byte* issuerKeyHash;
byte* cert;
word32 certSz;
byte* sig; /* Pointer to sig in source */
word32 sigSz; /* Length in octets for the sig */
word32 sigOID; /* OID for hash used for sig */
CertStatus* status; /* certificate status to fill out */
byte* nonce; /* pointer to nonce inside ASN.1 response */
int nonceSz; /* length of the nonce string */
byte* source; /* pointer to source buffer, not owned */
word32 maxIdx; /* max offset based on init size */
};
struct OcspRequest {
byte issuerHash[KEYID_SIZE];
byte issuerKeyHash[KEYID_SIZE];
byte* serial; /* copy of the serial number in source cert */
int serialSz;
byte* url; /* copy of the extAuthInfo in source cert */
int urlSz;
byte nonce[MAX_OCSP_NONCE_SZ];
int nonceSz;
};
WOLFSSL_LOCAL void InitOcspResponse(OcspResponse*, CertStatus*, byte*, word32);
WOLFSSL_LOCAL int OcspResponseDecode(OcspResponse*, void*);
WOLFSSL_LOCAL int InitOcspRequest(OcspRequest*, DecodedCert*, byte);
WOLFSSL_LOCAL void FreeOcspRequest(OcspRequest*);
WOLFSSL_LOCAL int EncodeOcspRequest(OcspRequest*, byte*, word32);
WOLFSSL_LOCAL word32 EncodeOcspRequestExtensions(OcspRequest*, byte*, word32);
WOLFSSL_LOCAL int CompareOcspReqResp(OcspRequest*, OcspResponse*);
#endif /* HAVE_OCSP */
/* for pointer use */
typedef struct RevokedCert RevokedCert;
#ifdef HAVE_CRL
struct RevokedCert {
byte serialNumber[EXTERNAL_SERIAL_SIZE];
int serialSz;
RevokedCert* next;
};
typedef struct DecodedCRL DecodedCRL;
struct DecodedCRL {
word32 certBegin; /* offset to start of cert */
word32 sigIndex; /* offset to start of signature */
word32 sigLength; /* length of signature */
word32 signatureOID; /* sum of algorithm object id */
byte* signature; /* pointer into raw source, not owned */
byte issuerHash[SIGNER_DIGEST_SIZE]; /* issuer hash */
byte crlHash[SIGNER_DIGEST_SIZE]; /* raw crl data hash */
byte lastDate[MAX_DATE_SIZE]; /* last date updated */
byte nextDate[MAX_DATE_SIZE]; /* next update date */
byte lastDateFormat; /* format of last date */
byte nextDateFormat; /* format of next date */
RevokedCert* certs; /* revoked cert list */
int totalCerts; /* number on list */
};
WOLFSSL_LOCAL void InitDecodedCRL(DecodedCRL*);
WOLFSSL_LOCAL int ParseCRL(DecodedCRL*, const byte* buff, word32 sz, void* cm);
WOLFSSL_LOCAL void FreeDecodedCRL(DecodedCRL*);
#endif /* HAVE_CRL */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* !NO_ASN */
#endif /* WOLF_CRYPT_ASN_H */
| Java |
/*
* Customer code to add GPIO control during WLAN start/stop
* Copyright (C) 1999-2010, Broadcom Corporation
*
* Unless you and Broadcom execute a separate written software license
* agreement governing use of this software, this software is licensed to you
* under the terms of the GNU General Public License version 2 (the "GPL"),
* available at http://www.broadcom.com/licenses/GPLv2.php, with the
* following added to such license:
*
* As a special exception, the copyright holders of this software give you
* permission to link this software with independent modules, and to copy and
* distribute the resulting executable under terms of your choice, provided that
* you also meet, for each linked independent module, the terms and conditions of
* the license of that module. An independent module is a module which is not
* derived from this software. The special exception does not apply to any
* modifications of the software.
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Broadcom software provided under a license
* other than the GPL, without Broadcom's express prior written consent.
*
* $Id: dhd_custom_gpio.c,v 1.1.4.8.4.4 2011/01/20 20:23:09 Exp $
*/
#include <typedefs.h>
#include <linuxver.h>
#include <osl.h>
#include <bcmutils.h>
#include <dngl_stats.h>
#include <dhd.h>
#include <wlioctl.h>
#include <wl_iw.h>
#define WL_ERROR(x) printf x
#define WL_TRACE(x)
#ifdef CUSTOMER_HW_SAMSUNG
extern void bcm_wlan_power_off(int);
extern void bcm_wlan_power_on(int);
extern void wlan_setup_power(int, int);
#endif /* CUSTOMER_HW_SAMSUNG */
#ifdef CUSTOMER_HW
extern void bcm_wlan_power_off(int);
extern void bcm_wlan_power_on(int);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
int wifi_set_carddetect(int on);
int wifi_set_power(int on, unsigned long msec);
int wifi_get_irq_number(unsigned long *irq_flags_ptr);
int wifi_get_mac_addr(unsigned char *buf);
void *wifi_get_country_code(char *ccode);
#endif
#if defined(OOB_INTR_ONLY)
#if defined(BCMLXSDMMC)
extern int sdioh_mmc_irq(int irq);
#endif /* (BCMLXSDMMC) */
#ifdef CUSTOMER_HW3
#include <mach/gpio.h>
#endif
/* Customer specific Host GPIO defintion */
/* Customer specific Host GPIO defintion */
#ifdef CUSTOMER_HW_SAMSUNG
static int dhd_oob_gpio_num = IRQ_EINT(20);
#else
static int dhd_oob_gpio_num = -1; /* GG 19 */
#endif
module_param(dhd_oob_gpio_num, int, 0644);
MODULE_PARM_DESC(dhd_oob_gpio_num, "DHD oob gpio number");
int dhd_customer_oob_irq_map(unsigned long *irq_flags_ptr)
{
int host_oob_irq = 0;
#ifdef CUSTOMER_HW2
host_oob_irq = wifi_get_irq_number(irq_flags_ptr);
#else /* for NOT CUSTOMER_HW2 */
#if defined(CUSTOM_OOB_GPIO_NUM)
if (dhd_oob_gpio_num < 0) {
dhd_oob_gpio_num = CUSTOM_OOB_GPIO_NUM;
}
#endif
if (dhd_oob_gpio_num < 0) {
WL_ERROR(("%s: ERROR customer specific Host GPIO is NOT defined \n",
__FUNCTION__));
return (dhd_oob_gpio_num);
}
WL_ERROR(("%s: customer specific Host GPIO number is (%d)\n",
__FUNCTION__, dhd_oob_gpio_num));
#if defined CUSTOMER_HW
host_oob_irq = MSM_GPIO_TO_INT(dhd_oob_gpio_num);
#elif defined CUSTOMER_HW3
gpio_request(dhd_oob_gpio_num, "oob irq");
host_oob_irq = gpio_to_irq(dhd_oob_gpio_num);
gpio_direction_input(dhd_oob_gpio_num);
#elif defined CUSTOMER_HW_SAMSUNG
host_oob_irq = dhd_oob_gpio_num;
#endif /* CUSTOMER_HW */
#endif /* CUSTOMER_HW2 */
return (host_oob_irq);
}
#endif /* defined(OOB_INTR_ONLY) */
/* Customer function to control hw specific wlan gpios */
void
dhd_customer_gpio_wlan_ctrl(int onoff)
{
switch (onoff) {
case WLAN_RESET_OFF:
WL_TRACE(("%s: call customer specific GPIO to insert WLAN RESET\n",
__FUNCTION__));
#ifdef CUSTOMER_HW_SAMSUNG
//bcm_wlan_power_off(2);
wlan_setup_power(0, 2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW
bcm_wlan_power_off(2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
wifi_set_power(0, 0);
#endif
WL_ERROR(("=========== WLAN placed in RESET ========\n"));
break;
case WLAN_RESET_ON:
WL_TRACE(("%s: callc customer specific GPIO to remove WLAN RESET\n",
__FUNCTION__));
#ifdef CUSTOMER_HW_SAMSUNG
//bcm_wlan_power_on(2);
wlan_setup_power(1, 2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW
bcm_wlan_power_on(2);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW2
wifi_set_power(1, 0);
#endif
WL_ERROR(("=========== WLAN going back to live ========\n"));
break;
case WLAN_POWER_OFF:
WL_TRACE(("%s: call customer specific GPIO to turn off WL_REG_ON\n",
__FUNCTION__));
#ifdef CUSTOMER_HW_SAMSUNG
//bcm_wlan_power_off(1);
wlan_setup_power(0, 1);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW
bcm_wlan_power_off(1);
#endif /* CUSTOMER_HW */
break;
case WLAN_POWER_ON:
WL_TRACE(("%s: call customer specific GPIO to turn on WL_REG_ON\n",
__FUNCTION__));
#ifdef CUSTOMER_HW_SAMSUNG
//bcm_wlan_power_on(1);
wlan_setup_power(1, 1);
#endif /* CUSTOMER_HW */
#ifdef CUSTOMER_HW
bcm_wlan_power_on(1);
/* Lets customer power to get stable */
OSL_DELAY(50);
#endif /* CUSTOMER_HW */
break;
}
}
#ifdef GET_CUSTOM_MAC_ENABLE
/* Function to get custom MAC address */
int
dhd_custom_get_mac_address(unsigned char *buf)
{
int ret = 0;
WL_TRACE(("%s Enter\n", __FUNCTION__));
if (!buf)
return -EINVAL;
/* Customer access to MAC address stored outside of DHD driver */
#ifdef CUSTOMER_HW2
ret = wifi_get_mac_addr(buf);
#endif
#ifdef EXAMPLE_GET_MAC
/* EXAMPLE code */
{
struct ether_addr ea_example = {{0x00, 0x11, 0x22, 0x33, 0x44, 0xFF}};
bcopy((char *)&ea_example, buf, sizeof(struct ether_addr));
}
#endif /* EXAMPLE_GET_MAC */
return ret;
}
#endif /* GET_CUSTOM_MAC_ENABLE */
/* Customized Locale table : OPTIONAL feature */
const struct cntry_locales_custom translate_custom_table[] = {
/* Table should be filled out based on custom platform regulatory requirement */
#ifdef EXAMPLE_TABLE
{"", "XY", 4}, /* universal */
{"US", "US", 69}, /* input ISO "US" to : US regrev 69 */
{"CA", "US", 69}, /* input ISO "CA" to : US regrev 69 */
{"EU", "EU", 5}, /* European union countries */
{"AT", "EU", 5},
{"BE", "EU", 5},
{"BG", "EU", 5},
{"CY", "EU", 5},
{"CZ", "EU", 5},
{"DK", "EU", 5},
{"EE", "EU", 5},
{"FI", "EU", 5},
{"FR", "EU", 5},
{"DE", "EU", 5},
{"GR", "EU", 5},
{"HU", "EU", 5},
{"IE", "EU", 5},
{"IT", "EU", 5},
{"LV", "EU", 5},
{"LI", "EU", 5},
{"LT", "EU", 5},
{"LU", "EU", 5},
{"MT", "EU", 5},
{"NL", "EU", 5},
{"PL", "EU", 5},
{"PT", "EU", 5},
{"RO", "EU", 5},
{"SK", "EU", 5},
{"SI", "EU", 5},
{"ES", "EU", 5},
{"SE", "EU", 5},
{"GB", "EU", 5}, /* input ISO "GB" to : EU regrev 05 */
{"IL", "IL", 0},
{"CH", "CH", 0},
{"TR", "TR", 0},
{"NO", "NO", 0},
{"KR", "XY", 3},
{"AU", "XY", 3},
{"CN", "XY", 3}, /* input ISO "CN" to : XY regrev 03 */
{"TW", "XY", 3},
{"AR", "XY", 3},
{"MX", "XY", 3}
#endif /* EXAMPLE_TABLE */
};
/* Customized Locale convertor
* input : ISO 3166-1 country abbreviation
* output: customized cspec
*/
void get_customized_country_code(char *country_iso_code, wl_country_t *cspec)
{
#ifdef CUSTOMER_HW2
struct cntry_locales_custom *cloc_ptr;
if (!cspec)
return;
cloc_ptr = wifi_get_country_code(country_iso_code);
if (cloc_ptr) {
strlcpy(cspec->ccode, cloc_ptr->custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = cloc_ptr->custom_locale_rev;
}
return;
#else
int size, i;
size = ARRAYSIZE(translate_custom_table);
if (cspec == 0)
return;
if (size == 0)
return;
for (i = 0; i < size; i++) {
if (strcmp(country_iso_code, translate_custom_table[i].iso_abbrev) == 0) {
memcpy(cspec->ccode, translate_custom_table[i].custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = translate_custom_table[i].custom_locale_rev;
return;
}
}
memcpy(cspec->ccode, translate_custom_table[0].custom_locale, WLC_CNTRY_BUF_SZ);
cspec->rev = translate_custom_table[0].custom_locale_rev;
return;
#endif
}
| Java |
// Test for method java.util.IllegalFormatPrecisionException.getClass().getFields()
// Copyright (C) 2012 Pavel Tisnovsky <ptisnovs@redhat.com>
// This file is part of Mauve.
// Mauve 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.
// Mauve 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 Mauve; see the file COPYING. If not, write to
// the Free Software Foundation, Inc., 51 Franklin Street,
// Fifth Floor, Boston, MA 02110-1301 USA.
// Tags: JDK1.5
package gnu.testlet.java.util.IllegalFormatPrecisionException.classInfo;
import gnu.testlet.TestHarness;
import gnu.testlet.Testlet;
import java.util.IllegalFormatPrecisionException;
import java.util.Map;
import java.util.HashMap;
/**
* Test for method java.util.IllegalFormatPrecisionException.getClass().getFields()
*/
public class getFields implements Testlet
{
/**
* Runs the test using the specified harness.
*
* @param harness the test harness (<code>null</code> not permitted).
*/
public void test(TestHarness harness)
{
// map of fields which should exists
Map<String, String> testedFields = null;
// map of fields for (Open)JDK6
Map<String, String> testedFields_jdk6 = new HashMap<String, String>();
// map of fields for (Open)JDK7
Map<String, String> testedFields_jdk7 = new HashMap<String, String>();
// map for fields declared in (Open)JDK6
// --- empty ---
// map for fields declared in (Open)JDK7
// --- empty ---
// create instance of a class IllegalFormatPrecisionException
final Object o = new IllegalFormatPrecisionException(42);
// get a runtime class of an object "o"
final Class c = o.getClass();
// get the right map containing field signatures
testedFields = getJavaVersion() < 7 ? testedFields_jdk6 : testedFields_jdk7;
// get all fields for this class
java.lang.reflect.Field[] fields = c.getFields();
// expected number of fields
final int expectedNumberOfFields = testedFields.size();
// basic check for a number of fields
harness.check(fields.length, expectedNumberOfFields);
}
/**
* Returns version of Java. The input could have the following form: "1.7.0_06"
* and we are interested only in "7" in this case.
*
* @return Java version
*/
protected int getJavaVersion() {
String javaVersionStr = System.getProperty("java.version");
String[] parts = javaVersionStr.split("\\.");
return Integer.parseInt(parts[1]);
}
}
| Java |
# Turn Off the Lights Browser Extension
<img alt="Turn Off the Lights Browser Extension Logo" src="https://github.com/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/blob/master/src/icons/icon48.png" align="left" style="padding: 0 10px 5px 0">
**Turn Off the Lights** is a popular browser extension that works on all major web browsers such as Google Chrome, Firefox, Opera, Safari, Yandex, Maxthon, Brave, Vivaldi, Cốc Cốc, and Microsoft Edge.



Project<br>
[](https://github.com/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/actions/workflows/codeql-analysis.yml)
[](https://lgtm.com/projects/g/turnoffthelights/Turn-Off-the-Lights-Chrome-extension/context:javascript)
Using Turn Off the Lights to dims the web page and reduces the eye strain caused by the bright screen. And it will highlight the video player on that web page such as on YouTube.
**[Join our growing community on Facebook](https://www.facebook.com/turnoffthelight) to stay up to date!**
**[Join our growing Translators community on Crowdin](https://www.crowdin.com/project/turnoffthelights) to stay up to date!**
**[Please use and enjoy it, and if you can make a donation of any amount, I'd appreciate it immensely](https://www.turnoffthelights.com/donate.html)**
<div style="text-align:center">
<img alt="Turn Off the Lights Browser extension Screenshot in Google Chrome" src="https://www.turnoffthelights.com/images/turnoffthelights-twitter.png">
</div>
## Features
* Turn the lights back on, by clicking on it
* Support multiple video sites: YouTube, HTML5 video,... and more
* Customize your YouTube:
* Auto HD: Set videos to play in HD automatically. Users can select from highres > 8K > 5K> 4K > 1080p > 720p > 480p > 360p > 240p > 144p > default
* Auto Wide: Automatically plays the video on the widest mode
,... and more
* Easter Eggs:
* Shortcut key: T -> Do you like a real movie theater feeling?
* Option to make the screen dark when the user clicks on the play button
* Option to turn on/off the fade in and fade out effects
* Custom colors
* Option to Flash Detection
* Option to Show Dimness Level Bar
* Option Eye Protection for when it's night. And with whitelist/blacklist filter
* Option atmosphere lighting that shows a glow around the video player
* Option to show the dark layer on the top of the window
* Options to shortcut keys:
* Ctrl + Shift + L to toggle the lights
* Alt + F8 to restore the default opacity value
* Alt + F9 to save the current opacity value
* Alt + F10 to enable/disable the Eye Protection feature
* Alt + (arrow up) to increase the opacity
* Alt + (arrow down) to decrease the opacity
* Alt + * to toggle the lights on all open tabs
* Option Camera Motion
* Option Speech Recognition
* Option for Mouse Wheel Volume Control for each HTML5 video player
* Option to add a filter to the current HTML5 video player (grayscale, sepia, invert, contrast, saturate, hue rotation and brightness)
* Option to show the Audio Visualization effect on top of the current HTML5 video (Blocks, Frequency and Music Tunnel)
* Option to loop the current HTML5 video player
* Option to place the Night Mode switch to toggle YouTube in black or white theme. And with whitelist/blacklist filter
* Time stamp: Activate the Night Mode within the chosen time
* Blackout: Dims the web page and activates the Night Mode
* Option to stop YouTube and HTML5 videos from automatically playing.
## Installation
#### Loading it in Chrome:
1. Open your Google Chrome web browser, browse to [chrome://extensions](chrome://extensions)
1. If you have already Turn Off the Lights Chrome extension installed, disable it
1. Check **Developer mode** in the top of the Extensions page
1. Click **Load unpacked extension...**
1. Choose the sub-directory **src** (where manifest.json resides)
#### Store hyperlinks:
The Browser extension is available in the following stores:
* [Google Chrome in the Chrome web store](https://chrome.google.com/webstore/detail/turn-off-the-lights/bfbmjmiodbnnpllbbbfblcplfjjepjdn)
* [Opera in the Opera Extension gallery](https://addons.opera.com/extensions/details/turn-off-the-lights/)
* [Firefox in the Firefox Extension gallery](https://addons.mozilla.org/firefox/addon/turn-off-the-lights/)
* [Safari in the Safari Extension gallery](https://itunes.apple.com/us/app/turn-off-the-lights-for-safari/id1273998507?ls=1&mt=12&at=1010lwtb)
* Available for Yandex: See Yandex built-in extension
* [Maxthon in the Maxthon Extension gallery](http://extension.maxthon.com/detail/index.php?view_id=1813)
* [Microsoft Edge in the Windows Store](https://microsoftedge.microsoft.com/addons/detail/turn-off-the-lights/fmamkbgpnienhphflfdamlhnljffjdgm)
| Java |
/** ============================================================================
* @file zsp800m_map.c
*
* @path $(APUDRV)/gpp/src/arch/ZSP800M/
*
* @desc Defines the configuration mapping information for the APU DRIVER
* driver.
*
* @ver 0.01.00.00
* ============================================================================
* Copyright (C) 2011-2012, Nufront Incorporated - http://www.nufront.com/
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any kind,
* whether express or implied; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* ============================================================================
*/
/* ----------------------------------- APU DRIVER Headers */
#include <apudrv.h>
#include <_apudrv.h>
#if defined (POOL_COMPONENT)
#include <pooldefs.h>
#endif /* if defined (POOL_COMPONENT) */
#if defined (MSGQ_COMPONENT)
#include <msgqdefs.h>
#endif /* if defined (MSGQ_COMPONENT) */
#include <cfgmap.h>
#if defined (__cplusplus)
EXTERN "C" {
#endif /* defined (__cplusplus) */
/** ============================================================================
* @name ZSP800MMAP_DspObjects
*
* @desc Array of configuration mapping objects for the DSPs in the system.
* ============================================================================
*/
EXTERN DSP_Interface ZSP800M_Interface ;
CONST CFGMAP_Dsp ZSP800MMAP_DspObjects [] =
{
{
"ZSP800M", /* NAME : Name of the DSP */
&ZSP800M_Interface /* INTERFACE : DSP interface table */
}
} ;
/** ============================================================================
* @name ZSP800MMAP_LoaderObjects
*
* @desc Array of configuration mapping objects for the DSP executable
* loaders in the system.
* ============================================================================
*/
EXTERN KFILE_Interface KFILEPSEUDO_Interface ;
EXTERN KFILE_Interface KFILEDEF_Interface ;
CONST CFGMAP_Loader ZSP800MMAP_LoaderObjects [] =
{
{
"BIN",
NULL,//&BINFILE_Interface,
&KFILEDEF_Interface
}
} ;
#if (!defined (ONLY_PROC_COMPONENT))
/** ============================================================================
* @name ZSP800MMAP_LinkDrvObjects
*
* @desc Array of configuration mapping objects for the link drivers in the
* system.
* ============================================================================
*/
EXTERN DRV_Interface SHMDRV_Interface ;
CONST CFGMAP_LinkDrv ZSP800MMAP_LinkDrvObjects [] =
{
{
"SHMDRV", /* NAME : Name of the link driver */
&SHMDRV_Interface /* INTERFACE : Link driver interface table */
}
} ;
/** ============================================================================
* @name ZSP800MMAP_IpsObjects
*
* @desc Array of configuration mapping objects for the IPS components in the
* system.
* ============================================================================
*/
EXTERN FnIpsInit IPS_init ;
EXTERN FnIpsExit IPS_exit ;
#if defined (DDSP_DEBUG)
EXTERN FnIpsDebug IPS_debug ;
#endif /* if defined (DDSP_DEBUG) */
CONST CFGMAP_Ips ZSP800MMAP_IpsObjects [] =
{
{
"IPS", /* NAME : Name of the IPS */
(FnIpsInit) &IPS_init, /* FXN_INIT : Init function for the IPS */
(FnIpsExit) &IPS_exit, /* FXN_EXIT : Exit function for the IPS */
#if defined (DDSP_DEBUG)
(FnIpsDebug) &IPS_debug /* FXN_DEBUG : Debug function for the IPS */
#endif /* if defined (DDSP_DEBUG) */
}
} ;
#endif /* if (!defined (ONLY_PROC_COMPONENT)) */
#if defined (POOL_COMPONENT)
/** ============================================================================
* @name ZSP800MMAP_PoolObjects
*
* @desc Array of configuration mapping objects for the POOLs in the system.
* ============================================================================
*/
EXTERN FnPoolInit SMAPOOL_init ;
EXTERN FnPoolExit SMAPOOL_exit ;
EXTERN POOL_Interface SMAPOOL_Interface ;
#if defined (PCPY_LINK)
EXTERN FnPoolInit BUFPOOL_init ;
EXTERN FnPoolExit BUFPOOL_exit ;
EXTERN POOL_Interface BUFPOOL_Interface ;
#endif /* if defined (PCPY_LINK) */
CONST CFGMAP_Pool ZSP800MMAP_PoolObjects [] =
{
{
"SMAPOOL", /* NAME : Name of the pool */
(FnPoolInit) &SMAPOOL_init, /* FXN_INIT : Init function for the pool */
(FnPoolExit) &SMAPOOL_exit, /* FXN_EXIT : Exit function for the pool */
&SMAPOOL_Interface /* INTERFACE : Pool interface table */
},
#if defined (PCPY_LINK)
{
"BUFPOOL", /* NAME : Name of the pool */
(FnPoolInit) &BUFPOOL_init, /* FXN_INIT : Init function for the pool */
(FnPoolExit) &BUFPOOL_exit, /* FXN_EXIT : Exit function for the pool */
&BUFPOOL_Interface /* INTERFACE : Pool interface table */
}
#endif /* if defined (PCPY_LINK) */
} ;
#endif /* if defined (POOL_COMPONENT) */
#if defined (CHNL_COMPONENT)
/** ============================================================================
* @name ZSP800MMAP_DataDrvObjects
*
* @desc Array of configuration mapping objects for the Data drivers in the
* system.
* ============================================================================
*/
EXTERN DATA_Interface ZCPYDATA_Interface ;
CONST CFGMAP_DataDrv ZSP800MMAP_DataDrvObjects [] =
{
{
"ZCPYDATA", /* NAME : Name of the data driver */
&ZCPYDATA_Interface /* INTERFACE : Data transfer interface table */
}
} ;
#endif /* if defined (CHNL_COMPONENT) */
#if defined (MSGQ_COMPONENT)
/** ============================================================================
* @name ZSP800MMAP_MqtObjects
*
* @desc Array of configuration mapping objects for the Message Queue
* Transports in the system.
* ============================================================================
*/
EXTERN MQT_Interface ZCPYMQT_Interface ;
CONST CFGMAP_Mqt ZSP800MMAP_MqtObjects [] =
{
{
"ZCPYMQT", /* NAME : Name of the Message Queue Transport */
&ZCPYMQT_Interface /* INTERFACE : MQT Interface table */
}
} ;
#endif /* if defined (MSGQ_COMPONENT) */
/** ============================================================================
* @name ZSP800MMAP_Config
*
* @desc APU DRIVER configuration mapping structure.
* ============================================================================
*/
CFGMAP_Object ZSP800MMAP_Config = {
1, /* NUMDSPS : Number of types of DSPs */
(CFGMAP_Dsp *) ZSP800MMAP_DspObjects, /* DSPOBJECTS : Array of DSP configuration mapping objects */
1, /* NUMLOADERS : Number of types of DSP executable loaders */
(CFGMAP_Loader *) ZSP800MMAP_LoaderObjects, /* LOADERS : Array of DSP executable loader configuration mapping objects */
#if (!defined (ONLY_PROC_COMPONENT))
1, /* NUMLINKDRVS : Number of types of link drivers */
(CFGMAP_LinkDrv *) ZSP800MMAP_LinkDrvObjects, /* LINKDRVOBJECTS : Array of Link Driver configuration mapping objects */
1, /* NUMIPS : Number of types of IPS */
(CFGMAP_Ips *) ZSP800MMAP_IpsObjects, /* IPSOBJECTS : Array of IPS configuration mapping objects */
#else
0, /* NUMLINKDRVS : Number of types of link drivers */
NULL, /* LINKDRVOBJECTS : Array of Link Driver configuration mapping objects */
0, /* NUMIPS : Number of types of IPS */
NULL, /* IPSOBJECTS : Array of IPS configuration mapping objects */
#endif /* if (!defined (ONLY_PROC_COMPONENT)) */
#if defined (POOL_COMPONENT)
1, /* NUMPOOLS : Number of types of POOLs */
(CFGMAP_Pool *) ZSP800MMAP_PoolObjects, /* POOLOBJECTS : Array of POOL configuration mapping objects */
#endif /* if defined (POOL_COMPONENT) */
#if defined (CHNL_COMPONENT)
1, /* NUMDATADRIVERS : Number of types of Data drivers */
(CFGMAP_DataDrv *) ZSP800MMAP_DataDrvObjects, /* DATADRIVERS : Array of Data driver configuration mapping objects */
#endif /* if defined (CHNL_COMPONENT) */
#if defined (MSGQ_COMPONENT)
1, /* NUMMQTS : Number of types of MQTs */
(CFGMAP_Mqt *) ZSP800MMAP_MqtObjects /* MQTOBJECTS : Array of MQT configuration mapping objects */
#endif /* if defined (MSGQ_COMPONENT) */
} ;
#if defined (__cplusplus)
}
#endif /* defined (__cplusplus) */
| Java |
<?php
$consumer_key = $_GET['1'];
$consumer_secret = $_GET['2'];
$oauth_access_token = $_GET['3'];
$oauth_access_token_secret = $_GET['4'];
switch($_GET['url'])
{
case 'timeline':
$rest = 'statuses/user_timeline' ;
$params = Array('count' => $_GET['count'], 'include_rts' => $_GET['include_rts'], 'exclude_replies' => $_GET['exclude_replies'], 'screen_name' => $_GET['screen_name']);
break;
case 'search':
$rest = "search/tweets";
$params = Array('q' => $_GET['q'], 'count' => $_GET['count'], 'include_rts' => $_GET['include_rts']);
break;
case 'list':
$rest = "lists/statuses";
$params = Array('list_id' => $_GET['list_id'], 'count' => $_GET['count'], 'include_rts' => $_GET['include_rts']);
break;
default:
$rest = 'statuses/user_timeline' ;
$params = Array('count' => '20');
break;
}
$auth = new dcsnt_TwitterOAuth($consumer_key,$consumer_secret,$oauth_access_token,$oauth_access_token_secret);
$get = $auth->get( $rest, $params );
if( ! $get ) {
echo 'An error occurs while reading the feed, please check your connection or settings';
}
if( isset( $get->errors ) ) {
// foreach( $get->errors as $key => $val ) echo $val;
echo 'errors';
//print_r($get->errors);
} else {
echo $get;
}
/*
* Abraham Williams (abraham@abrah.am) http://abrah.am
*
* The first PHP Library to support OAuth for Twitter's REST API.
*/
/**
* Twitter OAuth class
*/
class dcsnt_TwitterOAuth {
/* Contains the last HTTP status code returned. */
public $http_code;
/* Contains the last API call. */
public $url;
/* Set up the API root URL. */
public $host = "https://api.twitter.com/1.1/";
/* Set timeout default. */
public $timeout = 30;
/* Set connect timeout. */
public $connecttimeout = 30;
/* Verify SSL Cert. */
public $ssl_verifypeer = FALSE;
/* Respons format. */
public $format = 'json';
/* Decode returned json data. */
public $decode_json = false;
/* Contains the last HTTP headers returned. */
public $http_info;
/* Set the useragnet. */
public $useragent = 'TwitterOAuth v0.2.0-beta2';
/* Immediately retry the API call if the response was not successful. */
//public $retry = TRUE;
/**
* Set API URLS
*/
function accessTokenURL() { return 'https://api.twitter.com/oauth/access_token'; }
function authenticateURL() { return 'https://api.twitter.com/oauth/authenticate'; }
function authorizeURL() { return 'https://api.twitter.com/oauth/authorize'; }
function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; }
/**
* Debug helpers
*/
function lastStatusCode() { return $this->http_status; }
function lastAPICall() { return $this->last_api_call; }
/**
* construct TwitterOAuth object
*/
function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
$this->sha1_method = new dcsnt_OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new dcsnt_OAuthConsumer($consumer_key, $consumer_secret);
if (!empty($oauth_token) && !empty($oauth_token_secret)) {
$this->token = new dcsnt_OAuthConsumer($oauth_token, $oauth_token_secret);
} else {
$this->token = NULL;
}
}
/**
* Get a request_token from Twitter
*
* @returns a key/value array containing oauth_token and oauth_token_secret
*/
function getRequestToken($oauth_callback = NULL) {
$parameters = array();
if (!empty($oauth_callback)) {
$parameters['oauth_callback'] = $oauth_callback;
}
$request = $this->dcsnt_OAuthRequest($this->requestTokenURL(), 'GET', $parameters);
$token = dcsnt_OAuthUtil::parse_parameters($request);
$this->token = new dcsnt_OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
/**
* Get the authorize URL
*
* @returns a string
*/
function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) {
if (is_array($token)) {
$token = $token['oauth_token'];
}
if (empty($sign_in_with_twitter)) {
return $this->authorizeURL() . "?oauth_token={$token}";
} else {
return $this->authenticateURL() . "?oauth_token={$token}";
}
}
/**
* Exchange request token and secret for an access token and
* secret, to sign API calls.
*
* @returns array("oauth_token" => "the-access-token",
* "oauth_token_secret" => "the-access-secret",
* "user_id" => "9436992",
* "screen_name" => "abraham")
*/
function getAccessToken($oauth_verifier = FALSE) {
$parameters = array();
if (!empty($oauth_verifier)) {
$parameters['oauth_verifier'] = $oauth_verifier;
}
$request = $this->dcsnt_OAuthRequest($this->accessTokenURL(), 'GET', $parameters);
$token = dcsnt_OAuthUtil::parse_parameters($request);
$this->token = new dcsnt_OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
/**
* One time exchange of username and password for access token and secret.
*
* @returns array("oauth_token" => "the-access-token",
* "oauth_token_secret" => "the-access-secret",
* "user_id" => "9436992",
* "screen_name" => "abraham",
* "x_auth_expires" => "0")
*/
function getXAuthToken($username, $password) {
$parameters = array();
$parameters['x_auth_username'] = $username;
$parameters['x_auth_password'] = $password;
$parameters['x_auth_mode'] = 'client_auth';
$request = $this->dcsnt_OAuthRequest($this->accessTokenURL(), 'POST', $parameters);
$token = dcsnt_OAuthUtil::parse_parameters($request);
$this->token = new dcsnt_OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
return $token;
}
/**
* GET wrapper for dcsnt_OAuthRequest.
*/
function get($url, $parameters = array()) {
$response = $this->dcsnt_OAuthRequest($url, 'GET', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
/**
* POST wrapper for dcsnt_OAuthRequest.
*/
function post($url, $parameters = array()) {
$response = $this->dcsnt_OAuthRequest($url, 'POST', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
/**
* DELETE wrapper for oAuthReqeust.
*/
function delete($url, $parameters = array()) {
$response = $this->dcsnt_OAuthRequest($url, 'DELETE', $parameters);
if ($this->format === 'json' && $this->decode_json) {
return json_decode($response);
}
return $response;
}
/**
* Format and sign an OAuth / API request
*/
function dcsnt_OAuthRequest($url, $method, $parameters) {
if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
$url = "{$this->host}{$url}.{$this->format}";
}
$request = dcsnt_OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
$request->sign_request($this->sha1_method, $this->consumer, $this->token);
switch ($method) {
case 'GET':
return $this->http($request->to_url(), 'GET');
default:
return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
}
}
/**
* Make an HTTP request
*
* @return API results
*/
function http($url, $method, $postfields = NULL) {
$this->http_info = array();
$ci = curl_init();
/* Curl settings */
curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
curl_setopt($ci, CURLOPT_HEADER, FALSE);
switch ($method) {
case 'POST':
curl_setopt($ci, CURLOPT_POST, TRUE);
if (!empty($postfields)) {
curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
}
break;
case 'DELETE':
curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
if (!empty($postfields)) {
$url = "{$url}?{$postfields}";
}
}
curl_setopt($ci, CURLOPT_URL, $url);
$response = curl_exec($ci);
$this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($ci));
$this->url = $url;
curl_close ($ci);
return $response;
}
/**
* Get the header info to store.
*/
function getHeader($ch, $header) {
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
$this->http_header[$key] = $value;
}
return strlen($header);
}
}
// vim: foldmethod=marker
/* Generic exception class
*/
class dcsnt_OAuthException extends Exception {
// pass
}
class dcsnt_OAuthConsumer {
public $key;
public $secret;
function __construct($key, $secret, $callback_url=NULL) {
$this->key = $key;
$this->secret = $secret;
$this->callback_url = $callback_url;
}
function __toString() {
return "OAuthConsumer[key=$this->key,secret=$this->secret]";
}
}
class dcsnt_OAuthToken {
// access tokens and request tokens
public $key;
public $secret;
/**
* key = the token
* secret = the token secret
*/
function __construct($key, $secret) {
$this->key = $key;
$this->secret = $secret;
}
/**
* generates the basic string serialization of a token that a server
* would respond to request_token and access_token calls with
*/
function to_string() {
return "oauth_token=" .
dcsnt_OAuthUtil::urlencode_rfc3986($this->key) .
"&oauth_token_secret=" .
dcsnt_OAuthUtil::urlencode_rfc3986($this->secret);
}
function __toString() {
return $this->to_string();
}
}
/**
* A class for implementing a Signature Method
* See section 9 ("Signing Requests") in the spec
*/
abstract class dcsnt_OAuthSignatureMethod {
/**
* Needs to return the name of the Signature Method (ie HMAC-SHA1)
* @return string
*/
abstract public function get_name();
/**
* Build up the signature
* NOTE: The output of this function MUST NOT be urlencoded.
* the encoding is handled in dcsnt_OAuthRequest when the final
* request is serialized
* @param dcsnt_OAuthRequest $request
* @param OAuthConsumer $consumer
* @param dcsnt_OAuthToken $token
* @return string
*/
abstract public function build_signature($request, $consumer, $token);
/**
* Verifies that a given signature is correct
* @param dcsnt_OAuthRequest $request
* @param OAuthConsumer $consumer
* @param dcsnt_OAuthToken $token
* @param string $signature
* @return bool
*/
public function check_signature($request, $consumer, $token, $signature) {
$built = $this->build_signature($request, $consumer, $token);
return $built == $signature;
}
}
/**
* The HMAC-SHA1 signature method uses the HMAC-SHA1 signature algorithm as defined in [RFC2104]
* where the Signature Base String is the text and the key is the concatenated values (each first
* encoded per Parameter Encoding) of the Consumer Secret and Token Secret, separated by an '&'
* character (ASCII code 38) even if empty.
* - Chapter 9.2 ("HMAC-SHA1")
*/
class dcsnt_OAuthSignatureMethod_HMAC_SHA1 extends dcsnt_OAuthSignatureMethod {
function get_name() {
return "HMAC-SHA1";
}
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = dcsnt_OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
return base64_encode(hash_hmac('sha1', $base_string, $key, true));
}
}
/**
* The PLAINTEXT method does not provide any security protection and SHOULD only be used
* over a secure channel such as HTTPS. It does not use the Signature Base String.
* - Chapter 9.4 ("PLAINTEXT")
*/
class dcsnt_OAuthSignatureMethod_PLAINTEXT extends dcsnt_OAuthSignatureMethod {
public function get_name() {
return "PLAINTEXT";
}
/**
* oauth_signature is set to the concatenated encoded values of the Consumer Secret and
* Token Secret, separated by a '&' character (ASCII code 38), even if either secret is
* empty. The result MUST be encoded again.
* - Chapter 9.4.1 ("Generating Signatures")
*
* Please note that the second encoding MUST NOT happen in the SignatureMethod, as
* dcsnt_OAuthRequest handles this!
*/
public function build_signature($request, $consumer, $token) {
$key_parts = array(
$consumer->secret,
($token) ? $token->secret : ""
);
$key_parts = dcsnt_OAuthUtil::urlencode_rfc3986($key_parts);
$key = implode('&', $key_parts);
$request->base_string = $key;
return $key;
}
}
/**
* The RSA-SHA1 signature method uses the RSASSA-PKCS1-v1_5 signature algorithm as defined in
* [RFC3447] section 8.2 (more simply known as PKCS#1), using SHA-1 as the hash function for
* EMSA-PKCS1-v1_5. It is assumed that the Consumer has provided its RSA public key in a
* verified way to the Service Provider, in a manner which is beyond the scope of this
* specification.
* - Chapter 9.3 ("RSA-SHA1")
*/
abstract class dcsnt_OAuthSignatureMethod_RSA_SHA1 extends dcsnt_OAuthSignatureMethod {
public function get_name() {
return "RSA-SHA1";
}
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
// (2) fetch via http using a url provided by the requester
// (3) some sort of specific discovery code based on request
//
// Either way should return a string representation of the certificate
protected abstract function fetch_public_cert(&$request);
// Up to the SP to implement this lookup of keys. Possible ideas are:
// (1) do a lookup in a table of trusted certs keyed off of consumer
//
// Either way should return a string representation of the certificate
protected abstract function fetch_private_cert(&$request);
public function build_signature($request, $consumer, $token) {
$base_string = $request->get_signature_base_string();
$request->base_string = $base_string;
// Fetch the private key cert based on the request
$cert = $this->fetch_private_cert($request);
// Pull the private key ID from the certificate
$privatekeyid = openssl_get_privatekey($cert);
// Sign using the key
$ok = openssl_sign($base_string, $signature, $privatekeyid);
// Release the key resource
openssl_free_key($privatekeyid);
return base64_encode($signature);
}
public function check_signature($request, $consumer, $token, $signature) {
$decoded_sig = base64_decode($signature);
$base_string = $request->get_signature_base_string();
// Fetch the public key cert based on the request
$cert = $this->fetch_public_cert($request);
// Pull the public key ID from the certificate
$publickeyid = openssl_get_publickey($cert);
// Check the computed signature against the one passed in the query
$ok = openssl_verify($base_string, $decoded_sig, $publickeyid);
// Release the key resource
openssl_free_key($publickeyid);
return $ok == 1;
}
}
class dcsnt_OAuthRequest {
private $parameters;
private $http_method;
private $http_url;
// for debug purposes
public $base_string;
public static $version = '1.0';
public static $POST_INPUT = 'php://input';
function __construct($http_method, $http_url, $parameters=NULL) {
@$parameters or $parameters = array();
$parameters = array_merge( dcsnt_OAuthUtil::parse_parameters(parse_url($http_url, PHP_URL_QUERY)), $parameters);
$this->parameters = $parameters;
$this->http_method = $http_method;
$this->http_url = $http_url;
}
/**
* attempt to build up a request from what was passed to the server
*/
public static function from_request($http_method=NULL, $http_url=NULL, $parameters=NULL) {
$scheme = (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] != "on")
? 'http'
: 'https';
@$http_url or $http_url = $scheme .
'://' . $_SERVER['HTTP_HOST'] .
':' .
$_SERVER['SERVER_PORT'] .
$_SERVER['REQUEST_URI'];
@$http_method or $http_method = $_SERVER['REQUEST_METHOD'];
// We weren't handed any parameters, so let's find the ones relevant to
// this request.
// If you run XML-RPC or similar you should use this to provide your own
// parsed parameter-list
if (!$parameters) {
// Find request headers
$request_headers = dcsnt_OAuthUtil::get_headers();
// Parse the query-string to find GET parameters
$parameters = dcsnt_OAuthUtil::parse_parameters($_SERVER['QUERY_STRING']);
// It's a POST request of the proper content-type, so parse POST
// parameters and add those overriding any duplicates from GET
if ($http_method == "POST"
&& @strstr($request_headers["Content-Type"],
"application/x-www-form-urlencoded")
) {
$post_data = dcsnt_OAuthUtil::parse_parameters(
file_get_contents(self::$POST_INPUT)
);
$parameters = array_merge($parameters, $post_data);
}
// We have a Authorization-header with OAuth data. Parse the header
// and add those overriding any duplicates from GET or POST
if (@substr($request_headers['Authorization'], 0, 6) == "OAuth ") {
$header_parameters = dcsnt_OAuthUtil::split_header(
$request_headers['Authorization']
);
$parameters = array_merge($parameters, $header_parameters);
}
}
return new dcsnt_OAuthRequest($http_method, $http_url, $parameters);
}
/**
* pretty much a helper function to set up the request
*/
public static function from_consumer_and_token($consumer, $token, $http_method, $http_url, $parameters=NULL) {
@$parameters or $parameters = array();
$defaults = array("oauth_version" => dcsnt_OAuthRequest::$version,
"oauth_nonce" => dcsnt_OAuthRequest::generate_nonce(),
"oauth_timestamp" => dcsnt_OAuthRequest::generate_timestamp(),
"oauth_consumer_key" => $consumer->key);
if ($token)
$defaults['oauth_token'] = $token->key;
$parameters = array_merge($defaults, $parameters);
return new dcsnt_OAuthRequest($http_method, $http_url, $parameters);
}
public function set_parameter($name, $value, $allow_duplicates = true) {
if ($allow_duplicates && isset($this->parameters[$name])) {
// We have already added parameter(s) with this name, so add to the list
if (is_scalar($this->parameters[$name])) {
// This is the first duplicate, so transform scalar (string)
// into an array so we can add the duplicates
$this->parameters[$name] = array($this->parameters[$name]);
}
$this->parameters[$name][] = $value;
} else {
$this->parameters[$name] = $value;
}
}
public function get_parameter($name) {
return isset($this->parameters[$name]) ? $this->parameters[$name] : null;
}
public function get_parameters() {
return $this->parameters;
}
public function unset_parameter($name) {
unset($this->parameters[$name]);
}
/**
* The request parameters, sorted and concatenated into a normalized string.
* @return string
*/
public function get_signable_parameters() {
// Grab all parameters
$params = $this->parameters;
// Remove oauth_signature if present
// Ref: Spec: 9.1.1 ("The oauth_signature parameter MUST be excluded.")
if (isset($params['oauth_signature'])) {
unset($params['oauth_signature']);
}
return dcsnt_OAuthUtil::build_http_query($params);
}
/**
* Returns the base string of this request
*
* The base string defined as the method, the url
* and the parameters (normalized), each urlencoded
* and the concated with &.
*/
public function get_signature_base_string() {
$parts = array(
$this->get_normalized_http_method(),
$this->get_normalized_http_url(),
$this->get_signable_parameters()
);
$parts = dcsnt_OAuthUtil::urlencode_rfc3986($parts);
return implode('&', $parts);
}
/**
* just uppercases the http method
*/
public function get_normalized_http_method() {
return strtoupper($this->http_method);
}
/**
* parses the url and rebuilds it to be
* scheme://host/path
*/
public function get_normalized_http_url() {
$parts = parse_url($this->http_url);
$port = @$parts['port'];
$scheme = $parts['scheme'];
$host = $parts['host'];
$path = @$parts['path'];
$port or $port = ($scheme == 'https') ? '443' : '80';
if (($scheme == 'https' && $port != '443')
|| ($scheme == 'http' && $port != '80')) {
$host = "$host:$port";
}
return "$scheme://$host$path";
}
/**
* builds a url usable for a GET request
*/
public function to_url() {
$post_data = $this->to_postdata();
$out = $this->get_normalized_http_url();
if ($post_data) {
$out .= '?'.$post_data;
}
return $out;
}
/**
* builds the data one would send in a POST request
*/
public function to_postdata() {
return dcsnt_OAuthUtil::build_http_query($this->parameters);
}
/**
* builds the Authorization: header
*/
public function to_header($realm=null) {
$first = true;
if($realm) {
$out = 'Authorization: OAuth realm="' . dcsnt_OAuthUtil::urlencode_rfc3986($realm) . '"';
$first = false;
} else
$out = 'Authorization: OAuth';
$total = array();
foreach ($this->parameters as $k => $v) {
if (substr($k, 0, 5) != "oauth") continue;
if (is_array($v)) {
throw new dcsnt_OAuthException('Arrays not supported in headers');
}
$out .= ($first) ? ' ' : ',';
$out .= dcsnt_OAuthUtil::urlencode_rfc3986($k) .
'="' .
dcsnt_OAuthUtil::urlencode_rfc3986($v) .
'"';
$first = false;
}
return $out;
}
public function __toString() {
return $this->to_url();
}
public function sign_request($signature_method, $consumer, $token) {
$this->set_parameter(
"oauth_signature_method",
$signature_method->get_name(),
false
);
$signature = $this->build_signature($signature_method, $consumer, $token);
$this->set_parameter("oauth_signature", $signature, false);
}
public function build_signature($signature_method, $consumer, $token) {
$signature = $signature_method->build_signature($this, $consumer, $token);
return $signature;
}
/**
* util function: current timestamp
*/
private static function generate_timestamp() {
return time();
}
/**
* util function: current nonce
*/
private static function generate_nonce() {
$mt = microtime();
$rand = mt_rand();
return md5($mt . $rand); // md5s look nicer than numbers
}
}
class dcsnt_OAuthServer {
protected $timestamp_threshold = 300; // in seconds, five minutes
protected $version = '1.0'; // hi blaine
protected $signature_methods = array();
protected $data_store;
function __construct($data_store) {
$this->data_store = $data_store;
}
public function add_signature_method($signature_method) {
$this->signature_methods[$signature_method->get_name()] =
$signature_method;
}
// high level functions
/**
* process a request_token request
* returns the request token on success
*/
public function fetch_request_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// no token required for the initial token request
$token = NULL;
$this->check_signature($request, $consumer, $token);
// Rev A change
$callback = $request->get_parameter('oauth_callback');
$new_token = $this->data_store->new_request_token($consumer, $callback);
return $new_token;
}
/**
* process an access_token request
* returns the access token on success
*/
public function fetch_access_token(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
// requires authorized request token
$token = $this->get_token($request, $consumer, "request");
$this->check_signature($request, $consumer, $token);
// Rev A change
$verifier = $request->get_parameter('oauth_verifier');
$new_token = $this->data_store->new_access_token($token, $consumer, $verifier);
return $new_token;
}
/**
* verify an api call, checks all the parameters
*/
public function verify_request(&$request) {
$this->get_version($request);
$consumer = $this->get_consumer($request);
$token = $this->get_token($request, $consumer, "access");
$this->check_signature($request, $consumer, $token);
return array($consumer, $token);
}
// Internals from here
/**
* version 1
*/
private function get_version(&$request) {
$version = $request->get_parameter("oauth_version");
if (!$version) {
// Service Providers MUST assume the protocol version to be 1.0 if this parameter is not present.
// Chapter 7.0 ("Accessing Protected Ressources")
$version = '1.0';
}
if ($version !== $this->version) {
throw new dcsnt_OAuthException("OAuth version '$version' not supported");
}
return $version;
}
/**
* figure out the signature with some defaults
*/
private function get_signature_method(&$request) {
$signature_method =
@$request->get_parameter("oauth_signature_method");
if (!$signature_method) {
// According to chapter 7 ("Accessing Protected Ressources") the signature-method
// parameter is required, and we can't just fallback to PLAINTEXT
throw new dcsnt_OAuthException('No signature method parameter. This parameter is required');
}
if (!in_array($signature_method,
array_keys($this->signature_methods))) {
throw new dcsnt_OAuthException(
"Signature method '$signature_method' not supported " .
"try one of the following: " .
implode(", ", array_keys($this->signature_methods))
);
}
return $this->signature_methods[$signature_method];
}
/**
* try to find the consumer for the provided request's consumer key
*/
private function get_consumer(&$request) {
$consumer_key = @$request->get_parameter("oauth_consumer_key");
if (!$consumer_key) {
throw new dcsnt_OAuthException("Invalid consumer key");
}
$consumer = $this->data_store->lookup_consumer($consumer_key);
if (!$consumer) {
throw new dcsnt_OAuthException("Invalid consumer");
}
return $consumer;
}
/**
* try to find the token for the provided request's token key
*/
private function get_token(&$request, $consumer, $token_type="access") {
$token_field = @$request->get_parameter('oauth_token');
$token = $this->data_store->lookup_token(
$consumer, $token_type, $token_field
);
if (!$token) {
throw new dcsnt_OAuthException("Invalid $token_type token: $token_field");
}
return $token;
}
/**
* all-in-one function to check the signature on a request
* should guess the signature method appropriately
*/
private function check_signature(&$request, $consumer, $token) {
// this should probably be in a different method
$timestamp = @$request->get_parameter('oauth_timestamp');
$nonce = @$request->get_parameter('oauth_nonce');
$this->check_timestamp($timestamp);
$this->check_nonce($consumer, $token, $nonce, $timestamp);
$signature_method = $this->get_signature_method($request);
$signature = $request->get_parameter('oauth_signature');
$valid_sig = $signature_method->check_signature(
$request,
$consumer,
$token,
$signature
);
if (!$valid_sig) {
throw new dcsnt_OAuthException("Invalid signature");
}
}
/**
* check that the timestamp is new enough
*/
private function check_timestamp($timestamp) {
if( ! $timestamp )
throw new dcsnt_OAuthException(
'Missing timestamp parameter. The parameter is required'
);
// verify that timestamp is recentish
$now = time();
if (abs($now - $timestamp) > $this->timestamp_threshold) {
throw new dcsnt_OAuthException(
"Expired timestamp, yours $timestamp, ours $now"
);
}
}
/**
* check that the nonce is not repeated
*/
private function check_nonce($consumer, $token, $nonce, $timestamp) {
if( ! $nonce )
throw new dcsnt_OAuthException(
'Missing nonce parameter. The parameter is required'
);
// verify that the nonce is uniqueish
$found = $this->data_store->lookup_nonce(
$consumer,
$token,
$nonce,
$timestamp
);
if ($found) {
throw new dcsnt_OAuthException("Nonce already used: $nonce");
}
}
}
class dcsnt_OAuthDataStore {
function lookup_consumer($consumer_key) {
// implement me
}
function lookup_token($consumer, $token_type, $token) {
// implement me
}
function lookup_nonce($consumer, $token, $nonce, $timestamp) {
// implement me
}
function new_request_token($consumer, $callback = null) {
// return a new token attached to this consumer
}
function new_access_token($token, $consumer, $verifier = null) {
// return a new access token attached to this consumer
// for the user associated with this token if the request token
// is authorized
// should also invalidate the request token
}
}
class dcsnt_OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
return array_map(array('dcsnt_OAuthUtil', 'urlencode_rfc3986'), $input);
} else if (is_scalar($input)) {
return str_replace(
'+',
' ',
str_replace('%7E', '~', rawurlencode($input))
);
} else {
return '';
}
}
// This decode function isn't taking into consideration the above
// modifications to the encoding process. However, this method doesn't
// seem to be used anywhere so leaving it as is.
public static function urldecode_rfc3986($string) {
return urldecode($string);
}
// Utility function for turning the Authorization: header into
// parameters, has to do some unescaping
// Can filter out any non-oauth parameters if needed (default behaviour)
public static function split_header($header, $only_allow_oauth_parameters = true) {
$pattern = '/(([-_a-z]*)=("([^"]*)"|([^,]*)),?)/';
$offset = 0;
$params = array();
while (preg_match($pattern, $header, $matches, PREG_OFFSET_CAPTURE, $offset) > 0) {
$match = $matches[0];
$header_name = $matches[2][0];
$header_content = (isset($matches[5])) ? $matches[5][0] : $matches[4][0];
if (preg_match('/^oauth_/', $header_name) || !$only_allow_oauth_parameters) {
$params[$header_name] = dcsnt_OAuthUtil::urldecode_rfc3986($header_content);
}
$offset = $match[1] + strlen($match[0]);
}
if (isset($params['realm'])) {
unset($params['realm']);
}
return $params;
}
// helper to try to sort out headers for people who aren't running apache
public static function get_headers() {
if (function_exists('apache_request_headers')) {
// we need this to get the actual Authorization: header
// because apache tends to tell us it doesn't exist
$headers = apache_request_headers();
// sanitize the output of apache_request_headers because
// we always want the keys to be Cased-Like-This and arh()
// returns the headers in the same case as they are in the
// request
$out = array();
foreach( $headers AS $key => $value ) {
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("-", " ", $key)))
);
$out[$key] = $value;
}
} else {
// otherwise we don't have apache and are just going to have to hope
// that $_SERVER actually contains what we need
$out = array();
if( isset($_SERVER['CONTENT_TYPE']) )
$out['Content-Type'] = $_SERVER['CONTENT_TYPE'];
if( isset($_ENV['CONTENT_TYPE']) )
$out['Content-Type'] = $_ENV['CONTENT_TYPE'];
foreach ($_SERVER as $key => $value) {
if (substr($key, 0, 5) == "HTTP_") {
// this is chaos, basically it is just there to capitalize the first
// letter of every word that is not an initial HTTP and strip HTTP
// code from przemek
$key = str_replace(
" ",
"-",
ucwords(strtolower(str_replace("_", " ", substr($key, 5))))
);
$out[$key] = $value;
}
}
}
return $out;
}
// This function takes a input like a=b&a=c&d=e and returns the parsed
// parameters like this
// array('a' => array('b','c'), 'd' => 'e')
public static function parse_parameters( $input ) {
if (!isset($input) || !$input) return array();
$pairs = explode('&', $input);
$parsed_parameters = array();
foreach ($pairs as $pair) {
$split = explode('=', $pair, 2);
$parameter = dcsnt_OAuthUtil::urldecode_rfc3986($split[0]);
$value = isset($split[1]) ? dcsnt_OAuthUtil::urldecode_rfc3986($split[1]) : '';
if (isset($parsed_parameters[$parameter])) {
// We have already recieved parameter(s) with this name, so add to the list
// of parameters with this name
if (is_scalar($parsed_parameters[$parameter])) {
// This is the first duplicate, so transform scalar (string) into an array
// so we can add the duplicates
$parsed_parameters[$parameter] = array($parsed_parameters[$parameter]);
}
$parsed_parameters[$parameter][] = $value;
} else {
$parsed_parameters[$parameter] = $value;
}
}
return $parsed_parameters;
}
public static function build_http_query($params) {
if (!$params) return '';
// Urlencode both keys and values
$keys = dcsnt_OAuthUtil::urlencode_rfc3986(array_keys($params));
$values = dcsnt_OAuthUtil::urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
// Parameters are sorted by name, using lexicographical byte value ordering.
// Ref: Spec: 9.1.1 (1)
uksort($params, 'strcmp');
$pairs = array();
foreach ($params as $parameter => $value) {
if (is_array($value)) {
// If two or more parameters share the same name, they are sorted by their value
// Ref: Spec: 9.1.1 (1)
natsort($value);
foreach ($value as $duplicate_value) {
$pairs[] = $parameter . '=' . $duplicate_value;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character (ASCII code 38)
return implode('&', $pairs);
}
}
?> | Java |
#if !defined(__MAC80211_DRIVER_TRACE) || defined(TRACE_HEADER_MULTI_READ)
#define __MAC80211_DRIVER_TRACE
#include <linux/tracepoint.h>
#include <net/mac80211.h>
#include "ieee80211_i.h"
#undef TRACE_SYSTEM
#define TRACE_SYSTEM mac80211
#define MAXNAME 32
#define LOCAL_ENTRY __array(char, wiphy_name, 32)
#define LOCAL_ASSIGN strlcpy(__entry->wiphy_name, wiphy_name(local->hw.wiphy), MAXNAME)
#define LOCAL_PR_FMT "%s"
#define LOCAL_PR_ARG __entry->wiphy_name
#define STA_ENTRY __array(char, sta_addr, ETH_ALEN)
#define STA_ASSIGN (sta ? memcpy(__entry->sta_addr, sta->addr, ETH_ALEN) : memset(__entry->sta_addr, 0, ETH_ALEN))
#define STA_PR_FMT " sta:%pM"
#define STA_PR_ARG __entry->sta_addr
#define VIF_ENTRY __field(enum nl80211_iftype, vif_type) __field(void *, sdata) \
__field(bool, p2p) \
__string(vif_name, sdata->dev ? sdata->dev->name : "<nodev>")
#define VIF_ASSIGN __entry->vif_type = sdata->vif.type; __entry->sdata = sdata; \
__entry->p2p = sdata->vif.p2p; \
__assign_str(vif_name, sdata->dev ? sdata->dev->name : "<nodev>")
#define VIF_PR_FMT " vif:%s(%d%s)"
#define VIF_PR_ARG __get_str(vif_name), __entry->vif_type, __entry->p2p ? "/p2p" : ""
/*
* Tracing for driver callbacks.
*/
DECLARE_EVENT_CLASS(local_only_evt,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local),
TP_STRUCT__entry(
LOCAL_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
),
TP_printk(LOCAL_PR_FMT, LOCAL_PR_ARG)
);
DECLARE_EVENT_CLASS(local_sdata_addr_evt,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__array(char, addr, 6)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
memcpy(__entry->addr, sdata->vif.addr, 6);
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT " addr:%pM",
LOCAL_PR_ARG, VIF_PR_ARG, __entry->addr
)
);
DECLARE_EVENT_CLASS(local_u32_evt,
TP_PROTO(struct ieee80211_local *local, u32 value),
TP_ARGS(local, value),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, value)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->value = value;
),
TP_printk(
LOCAL_PR_FMT " value:%d",
LOCAL_PR_ARG, __entry->value
)
);
DECLARE_EVENT_CLASS(local_sdata_evt,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT,
LOCAL_PR_ARG, VIF_PR_ARG
)
);
DEFINE_EVENT(local_only_evt, drv_return_void,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(drv_return_int,
TP_PROTO(struct ieee80211_local *local, int ret),
TP_ARGS(local, ret),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(int, ret)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->ret = ret;
),
TP_printk(LOCAL_PR_FMT " - %d", LOCAL_PR_ARG, __entry->ret)
);
TRACE_EVENT(drv_return_bool,
TP_PROTO(struct ieee80211_local *local, bool ret),
TP_ARGS(local, ret),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(bool, ret)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->ret = ret;
),
TP_printk(LOCAL_PR_FMT " - %s", LOCAL_PR_ARG, (__entry->ret) ?
"true" : "false")
);
TRACE_EVENT(drv_return_u64,
TP_PROTO(struct ieee80211_local *local, u64 ret),
TP_ARGS(local, ret),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u64, ret)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->ret = ret;
),
TP_printk(LOCAL_PR_FMT " - %llu", LOCAL_PR_ARG, __entry->ret)
);
DEFINE_EVENT(local_only_evt, drv_start,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
DEFINE_EVENT(local_only_evt, drv_suspend,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
DEFINE_EVENT(local_only_evt, drv_resume,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(drv_set_wakeup,
TP_PROTO(struct ieee80211_local *local, bool enabled),
TP_ARGS(local, enabled),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(bool, enabled)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->enabled = enabled;
),
TP_printk(LOCAL_PR_FMT " enabled:%d", LOCAL_PR_ARG, __entry->enabled)
);
DEFINE_EVENT(local_only_evt, drv_stop,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
DEFINE_EVENT(local_sdata_addr_evt, drv_add_interface,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
TRACE_EVENT(drv_change_interface,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
enum nl80211_iftype type, bool p2p),
TP_ARGS(local, sdata, type, p2p),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__field(u32, new_type)
__field(bool, new_p2p)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
__entry->new_type = type;
__entry->new_p2p = p2p;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT " new type:%d%s",
LOCAL_PR_ARG, VIF_PR_ARG, __entry->new_type,
__entry->new_p2p ? "/p2p" : ""
)
);
DEFINE_EVENT(local_sdata_addr_evt, drv_remove_interface,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
TRACE_EVENT(drv_config,
TP_PROTO(struct ieee80211_local *local,
u32 changed),
TP_ARGS(local, changed),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, changed)
__field(u32, flags)
__field(int, power_level)
__field(int, dynamic_ps_timeout)
__field(int, max_sleep_period)
__field(u16, listen_interval)
__field(u8, long_frame_max_tx_count)
__field(u8, short_frame_max_tx_count)
__field(int, center_freq)
__field(int, channel_type)
__field(int, smps)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->changed = changed;
__entry->flags = local->hw.conf.flags;
__entry->power_level = local->hw.conf.power_level;
__entry->dynamic_ps_timeout = local->hw.conf.dynamic_ps_timeout;
__entry->max_sleep_period = local->hw.conf.max_sleep_period;
__entry->listen_interval = local->hw.conf.listen_interval;
__entry->long_frame_max_tx_count = local->hw.conf.long_frame_max_tx_count;
__entry->short_frame_max_tx_count = local->hw.conf.short_frame_max_tx_count;
__entry->center_freq = local->hw.conf.channel->center_freq;
__entry->channel_type = local->hw.conf.channel_type;
__entry->smps = local->hw.conf.smps_mode;
),
TP_printk(
LOCAL_PR_FMT " ch:%#x freq:%d",
LOCAL_PR_ARG, __entry->changed, __entry->center_freq
)
);
TRACE_EVENT(drv_bss_info_changed,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct ieee80211_bss_conf *info,
u32 changed),
TP_ARGS(local, sdata, info, changed),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__field(bool, assoc)
__field(u16, aid)
__field(bool, cts)
__field(bool, shortpre)
__field(bool, shortslot)
__field(u8, dtimper)
__field(u16, bcnint)
__field(u16, assoc_cap)
__field(u64, timestamp)
__field(u32, basic_rates)
__field(u32, changed)
__field(bool, enable_beacon)
__field(u16, ht_operation_mode)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
__entry->changed = changed;
__entry->aid = info->aid;
__entry->assoc = info->assoc;
__entry->shortpre = info->use_short_preamble;
__entry->cts = info->use_cts_prot;
__entry->shortslot = info->use_short_slot;
__entry->dtimper = info->dtim_period;
__entry->bcnint = info->beacon_int;
__entry->assoc_cap = info->assoc_capability;
__entry->timestamp = info->last_tsf;
__entry->basic_rates = info->basic_rates;
__entry->enable_beacon = info->enable_beacon;
__entry->ht_operation_mode = info->ht_operation_mode;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT " changed:%#x",
LOCAL_PR_ARG, VIF_PR_ARG, __entry->changed
)
);
TRACE_EVENT(drv_prepare_multicast,
TP_PROTO(struct ieee80211_local *local, int mc_count),
TP_ARGS(local, mc_count),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(int, mc_count)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->mc_count = mc_count;
),
TP_printk(
LOCAL_PR_FMT " prepare mc (%d)",
LOCAL_PR_ARG, __entry->mc_count
)
);
TRACE_EVENT(drv_configure_filter,
TP_PROTO(struct ieee80211_local *local,
unsigned int changed_flags,
unsigned int *total_flags,
u64 multicast),
TP_ARGS(local, changed_flags, total_flags, multicast),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(unsigned int, changed)
__field(unsigned int, total)
__field(u64, multicast)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->changed = changed_flags;
__entry->total = *total_flags;
__entry->multicast = multicast;
),
TP_printk(
LOCAL_PR_FMT " changed:%#x total:%#x",
LOCAL_PR_ARG, __entry->changed, __entry->total
)
);
TRACE_EVENT(drv_set_tim,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sta *sta, bool set),
TP_ARGS(local, sta, set),
TP_STRUCT__entry(
LOCAL_ENTRY
STA_ENTRY
__field(bool, set)
),
TP_fast_assign(
LOCAL_ASSIGN;
STA_ASSIGN;
__entry->set = set;
),
TP_printk(
LOCAL_PR_FMT STA_PR_FMT " set:%d",
LOCAL_PR_ARG, STA_PR_FMT, __entry->set
)
);
TRACE_EVENT(drv_set_key,
TP_PROTO(struct ieee80211_local *local,
enum set_key_cmd cmd, struct ieee80211_sub_if_data *sdata,
struct ieee80211_sta *sta,
struct ieee80211_key_conf *key),
TP_ARGS(local, cmd, sdata, sta, key),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
__field(u32, cipher)
__field(u8, hw_key_idx)
__field(u8, flags)
__field(s8, keyidx)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
__entry->cipher = key->cipher;
__entry->flags = key->flags;
__entry->keyidx = key->keyidx;
__entry->hw_key_idx = key->hw_key_idx;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT,
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG
)
);
TRACE_EVENT(drv_update_tkip_key,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct ieee80211_key_conf *conf,
struct ieee80211_sta *sta, u32 iv32),
TP_ARGS(local, sdata, conf, sta, iv32),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
__field(u32, iv32)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
__entry->iv32 = iv32;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " iv32:%#x",
LOCAL_PR_ARG,VIF_PR_ARG,STA_PR_ARG, __entry->iv32
)
);
DEFINE_EVENT(local_sdata_evt, drv_hw_scan,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
DEFINE_EVENT(local_sdata_evt, drv_cancel_hw_scan,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
DEFINE_EVENT(local_sdata_evt, drv_sched_scan_start,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
DEFINE_EVENT(local_sdata_evt, drv_sched_scan_stop,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
DEFINE_EVENT(local_only_evt, drv_sw_scan_start,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
DEFINE_EVENT(local_only_evt, drv_sw_scan_complete,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(drv_get_stats,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_low_level_stats *stats,
int ret),
TP_ARGS(local, stats, ret),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(int, ret)
__field(unsigned int, ackfail)
__field(unsigned int, rtsfail)
__field(unsigned int, fcserr)
__field(unsigned int, rtssucc)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->ret = ret;
__entry->ackfail = stats->dot11ACKFailureCount;
__entry->rtsfail = stats->dot11RTSFailureCount;
__entry->fcserr = stats->dot11FCSErrorCount;
__entry->rtssucc = stats->dot11RTSSuccessCount;
),
TP_printk(
LOCAL_PR_FMT " ret:%d",
LOCAL_PR_ARG, __entry->ret
)
);
TRACE_EVENT(drv_get_tkip_seq,
TP_PROTO(struct ieee80211_local *local,
u8 hw_key_idx, u32 *iv32, u16 *iv16),
TP_ARGS(local, hw_key_idx, iv32, iv16),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u8, hw_key_idx)
__field(u32, iv32)
__field(u16, iv16)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->hw_key_idx = hw_key_idx;
__entry->iv32 = *iv32;
__entry->iv16 = *iv16;
),
TP_printk(
LOCAL_PR_FMT, LOCAL_PR_ARG
)
);
DEFINE_EVENT(local_u32_evt, drv_set_frag_threshold,
TP_PROTO(struct ieee80211_local *local, u32 value),
TP_ARGS(local, value)
);
DEFINE_EVENT(local_u32_evt, drv_set_rts_threshold,
TP_PROTO(struct ieee80211_local *local, u32 value),
TP_ARGS(local, value)
);
TRACE_EVENT(drv_set_coverage_class,
TP_PROTO(struct ieee80211_local *local, u8 value),
TP_ARGS(local, value),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u8, value)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->value = value;
),
TP_printk(
LOCAL_PR_FMT " value:%d",
LOCAL_PR_ARG, __entry->value
)
);
TRACE_EVENT(drv_sta_notify,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
enum sta_notify_cmd cmd,
struct ieee80211_sta *sta),
TP_ARGS(local, sdata, cmd, sta),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
__field(u32, cmd)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
__entry->cmd = cmd;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " cmd:%d",
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->cmd
)
);
TRACE_EVENT(drv_sta_state,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct ieee80211_sta *sta,
enum ieee80211_sta_state old_state,
enum ieee80211_sta_state new_state),
TP_ARGS(local, sdata, sta, old_state, new_state),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
__field(u32, old_state)
__field(u32, new_state)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
__entry->old_state = old_state;
__entry->new_state = new_state;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " state: %d->%d",
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG,
__entry->old_state, __entry->new_state
)
);
TRACE_EVENT(drv_sta_rc_update,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct ieee80211_sta *sta,
u32 changed),
TP_ARGS(local, sdata, sta, changed),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
__field(u32, changed)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
__entry->changed = changed;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " changed: 0x%x",
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->changed
)
);
TRACE_EVENT(drv_sta_add,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct ieee80211_sta *sta),
TP_ARGS(local, sdata, sta),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT,
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG
)
);
TRACE_EVENT(drv_sta_remove,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct ieee80211_sta *sta),
TP_ARGS(local, sdata, sta),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
STA_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT,
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG
)
);
TRACE_EVENT(drv_conf_tx,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
u16 ac, const struct ieee80211_tx_queue_params *params),
TP_ARGS(local, sdata, ac, params),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__field(u16, ac)
__field(u16, txop)
__field(u16, cw_min)
__field(u16, cw_max)
__field(u8, aifs)
__field(bool, uapsd)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
__entry->ac = ac;
__entry->txop = params->txop;
__entry->cw_max = params->cw_max;
__entry->cw_min = params->cw_min;
__entry->aifs = params->aifs;
__entry->uapsd = params->uapsd;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT " AC:%d",
LOCAL_PR_ARG, VIF_PR_ARG, __entry->ac
)
);
DEFINE_EVENT(local_sdata_evt, drv_get_tsf,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
TRACE_EVENT(drv_set_tsf,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
u64 tsf),
TP_ARGS(local, sdata, tsf),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__field(u64, tsf)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
__entry->tsf = tsf;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT " tsf:%llu",
LOCAL_PR_ARG, VIF_PR_ARG, (unsigned long long)__entry->tsf
)
);
DEFINE_EVENT(local_sdata_evt, drv_reset_tsf,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata),
TP_ARGS(local, sdata)
);
DEFINE_EVENT(local_only_evt, drv_tx_last_beacon,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(drv_ampdu_action,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
enum ieee80211_ampdu_mlme_action action,
struct ieee80211_sta *sta, u16 tid,
u16 *ssn, u8 buf_size),
TP_ARGS(local, sdata, action, sta, tid, ssn, buf_size),
TP_STRUCT__entry(
LOCAL_ENTRY
STA_ENTRY
__field(u32, action)
__field(u16, tid)
__field(u16, ssn)
__field(u8, buf_size)
VIF_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
STA_ASSIGN;
__entry->action = action;
__entry->tid = tid;
__entry->ssn = ssn ? *ssn : 0;
__entry->buf_size = buf_size;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT STA_PR_FMT " action:%d tid:%d buf:%d",
LOCAL_PR_ARG, VIF_PR_ARG, STA_PR_ARG, __entry->action,
__entry->tid, __entry->buf_size
)
);
TRACE_EVENT(drv_get_survey,
TP_PROTO(struct ieee80211_local *local, int idx,
struct survey_info *survey),
TP_ARGS(local, idx, survey),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(int, idx)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->idx = idx;
),
TP_printk(
LOCAL_PR_FMT " idx:%d",
LOCAL_PR_ARG, __entry->idx
)
);
TRACE_EVENT(drv_flush,
TP_PROTO(struct ieee80211_local *local, bool drop),
TP_ARGS(local, drop),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(bool, drop)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->drop = drop;
),
TP_printk(
LOCAL_PR_FMT " drop:%d",
LOCAL_PR_ARG, __entry->drop
)
);
TRACE_EVENT(drv_channel_switch,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_channel_switch *ch_switch),
TP_ARGS(local, ch_switch),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u64, timestamp)
__field(bool, block_tx)
__field(u16, freq)
__field(u8, count)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->timestamp = ch_switch->timestamp;
__entry->block_tx = ch_switch->block_tx;
__entry->freq = ch_switch->channel->center_freq;
__entry->count = ch_switch->count;
),
TP_printk(
LOCAL_PR_FMT " new freq:%u count:%d",
LOCAL_PR_ARG, __entry->freq, __entry->count
)
);
TRACE_EVENT(drv_set_antenna,
TP_PROTO(struct ieee80211_local *local, u32 tx_ant, u32 rx_ant, int ret),
TP_ARGS(local, tx_ant, rx_ant, ret),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, tx_ant)
__field(u32, rx_ant)
__field(int, ret)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->tx_ant = tx_ant;
__entry->rx_ant = rx_ant;
__entry->ret = ret;
),
TP_printk(
LOCAL_PR_FMT " tx_ant:%d rx_ant:%d ret:%d",
LOCAL_PR_ARG, __entry->tx_ant, __entry->rx_ant, __entry->ret
)
);
TRACE_EVENT(drv_get_antenna,
TP_PROTO(struct ieee80211_local *local, u32 tx_ant, u32 rx_ant, int ret),
TP_ARGS(local, tx_ant, rx_ant, ret),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, tx_ant)
__field(u32, rx_ant)
__field(int, ret)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->tx_ant = tx_ant;
__entry->rx_ant = rx_ant;
__entry->ret = ret;
),
TP_printk(
LOCAL_PR_FMT " tx_ant:%d rx_ant:%d ret:%d",
LOCAL_PR_ARG, __entry->tx_ant, __entry->rx_ant, __entry->ret
)
);
TRACE_EVENT(drv_remain_on_channel,
TP_PROTO(struct ieee80211_local *local, struct ieee80211_channel *chan,
enum nl80211_channel_type chantype, unsigned int duration),
TP_ARGS(local, chan, chantype, duration),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(int, center_freq)
__field(int, channel_type)
__field(unsigned int, duration)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->center_freq = chan->center_freq;
__entry->channel_type = chantype;
__entry->duration = duration;
),
TP_printk(
LOCAL_PR_FMT " freq:%dMHz duration:%dms",
LOCAL_PR_ARG, __entry->center_freq, __entry->duration
)
);
DEFINE_EVENT(local_only_evt, drv_cancel_remain_on_channel,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(drv_offchannel_tx,
TP_PROTO(struct ieee80211_local *local, struct sk_buff *skb,
struct ieee80211_channel *chan,
enum nl80211_channel_type channel_type,
unsigned int wait),
TP_ARGS(local, skb, chan, channel_type, wait),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(int, center_freq)
__field(int, channel_type)
__field(unsigned int, wait)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->center_freq = chan->center_freq;
__entry->channel_type = channel_type;
__entry->wait = wait;
),
TP_printk(
LOCAL_PR_FMT " freq:%dMHz, wait:%dms",
LOCAL_PR_ARG, __entry->center_freq, __entry->wait
)
);
TRACE_EVENT(drv_set_ringparam,
TP_PROTO(struct ieee80211_local *local, u32 tx, u32 rx),
TP_ARGS(local, tx, rx),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, tx)
__field(u32, rx)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->tx = tx;
__entry->rx = rx;
),
TP_printk(
LOCAL_PR_FMT " tx:%d rx %d",
LOCAL_PR_ARG, __entry->tx, __entry->rx
)
);
TRACE_EVENT(drv_get_ringparam,
TP_PROTO(struct ieee80211_local *local, u32 *tx, u32 *tx_max,
u32 *rx, u32 *rx_max),
TP_ARGS(local, tx, tx_max, rx, rx_max),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, tx)
__field(u32, tx_max)
__field(u32, rx)
__field(u32, rx_max)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->tx = *tx;
__entry->tx_max = *tx_max;
__entry->rx = *rx;
__entry->rx_max = *rx_max;
),
TP_printk(
LOCAL_PR_FMT " tx:%d tx_max %d rx %d rx_max %d",
LOCAL_PR_ARG,
__entry->tx, __entry->tx_max, __entry->rx, __entry->rx_max
)
);
DEFINE_EVENT(local_only_evt, drv_tx_frames_pending,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
DEFINE_EVENT(local_only_evt, drv_offchannel_tx_cancel_wait,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(drv_set_bitrate_mask,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
const struct cfg80211_bitrate_mask *mask),
TP_ARGS(local, sdata, mask),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__field(u32, legacy_2g)
__field(u32, legacy_5g)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
__entry->legacy_2g = mask->control[IEEE80211_BAND_2GHZ].legacy;
__entry->legacy_5g = mask->control[IEEE80211_BAND_5GHZ].legacy;
),
TP_printk(
LOCAL_PR_FMT VIF_PR_FMT " 2G Mask:0x%x 5G Mask:0x%x",
LOCAL_PR_ARG, VIF_PR_ARG, __entry->legacy_2g, __entry->legacy_5g
)
);
TRACE_EVENT(drv_set_rekey_data,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sub_if_data *sdata,
struct cfg80211_gtk_rekey_data *data),
TP_ARGS(local, sdata, data),
TP_STRUCT__entry(
LOCAL_ENTRY
VIF_ENTRY
__array(u8, kek, NL80211_KEK_LEN)
__array(u8, kck, NL80211_KCK_LEN)
__array(u8, replay_ctr, NL80211_REPLAY_CTR_LEN)
),
TP_fast_assign(
LOCAL_ASSIGN;
VIF_ASSIGN;
memcpy(__entry->kek, data->kek, NL80211_KEK_LEN);
memcpy(__entry->kck, data->kck, NL80211_KCK_LEN);
memcpy(__entry->replay_ctr, data->replay_ctr,
NL80211_REPLAY_CTR_LEN);
),
TP_printk(LOCAL_PR_FMT VIF_PR_FMT,
LOCAL_PR_ARG, VIF_PR_ARG)
);
TRACE_EVENT(drv_rssi_callback,
TP_PROTO(struct ieee80211_local *local,
enum ieee80211_rssi_event rssi_event),
TP_ARGS(local, rssi_event),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u32, rssi_event)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->rssi_event = rssi_event;
),
TP_printk(
LOCAL_PR_FMT " rssi_event:%d",
LOCAL_PR_ARG, __entry->rssi_event
)
);
DECLARE_EVENT_CLASS(release_evt,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sta *sta,
u16 tids, int num_frames,
enum ieee80211_frame_release_type reason,
bool more_data),
TP_ARGS(local, sta, tids, num_frames, reason, more_data),
TP_STRUCT__entry(
LOCAL_ENTRY
STA_ENTRY
__field(u16, tids)
__field(int, num_frames)
__field(int, reason)
__field(bool, more_data)
),
TP_fast_assign(
LOCAL_ASSIGN;
STA_ASSIGN;
__entry->tids = tids;
__entry->num_frames = num_frames;
__entry->reason = reason;
__entry->more_data = more_data;
),
TP_printk(
LOCAL_PR_FMT STA_PR_FMT
" TIDs:0x%.4x frames:%d reason:%d more:%d",
LOCAL_PR_ARG, STA_PR_ARG, __entry->tids, __entry->num_frames,
__entry->reason, __entry->more_data
)
);
DEFINE_EVENT(release_evt, drv_release_buffered_frames,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sta *sta,
u16 tids, int num_frames,
enum ieee80211_frame_release_type reason,
bool more_data),
TP_ARGS(local, sta, tids, num_frames, reason, more_data)
);
DEFINE_EVENT(release_evt, drv_allow_buffered_frames,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sta *sta,
u16 tids, int num_frames,
enum ieee80211_frame_release_type reason,
bool more_data),
TP_ARGS(local, sta, tids, num_frames, reason, more_data)
);
/*
* Tracing for API calls that drivers call.
*/
TRACE_EVENT(api_start_tx_ba_session,
TP_PROTO(struct ieee80211_sta *sta, u16 tid),
TP_ARGS(sta, tid),
TP_STRUCT__entry(
STA_ENTRY
__field(u16, tid)
),
TP_fast_assign(
STA_ASSIGN;
__entry->tid = tid;
),
TP_printk(
STA_PR_FMT " tid:%d",
STA_PR_ARG, __entry->tid
)
);
TRACE_EVENT(api_start_tx_ba_cb,
TP_PROTO(struct ieee80211_sub_if_data *sdata, const u8 *ra, u16 tid),
TP_ARGS(sdata, ra, tid),
TP_STRUCT__entry(
VIF_ENTRY
__array(u8, ra, ETH_ALEN)
__field(u16, tid)
),
TP_fast_assign(
VIF_ASSIGN;
memcpy(__entry->ra, ra, ETH_ALEN);
__entry->tid = tid;
),
TP_printk(
VIF_PR_FMT " ra:%pM tid:%d",
VIF_PR_ARG, __entry->ra, __entry->tid
)
);
TRACE_EVENT(api_stop_tx_ba_session,
TP_PROTO(struct ieee80211_sta *sta, u16 tid),
TP_ARGS(sta, tid),
TP_STRUCT__entry(
STA_ENTRY
__field(u16, tid)
),
TP_fast_assign(
STA_ASSIGN;
__entry->tid = tid;
),
TP_printk(
STA_PR_FMT " tid:%d",
STA_PR_ARG, __entry->tid
)
);
TRACE_EVENT(api_stop_tx_ba_cb,
TP_PROTO(struct ieee80211_sub_if_data *sdata, const u8 *ra, u16 tid),
TP_ARGS(sdata, ra, tid),
TP_STRUCT__entry(
VIF_ENTRY
__array(u8, ra, ETH_ALEN)
__field(u16, tid)
),
TP_fast_assign(
VIF_ASSIGN;
memcpy(__entry->ra, ra, ETH_ALEN);
__entry->tid = tid;
),
TP_printk(
VIF_PR_FMT " ra:%pM tid:%d",
VIF_PR_ARG, __entry->ra, __entry->tid
)
);
DEFINE_EVENT(local_only_evt, api_restart_hw,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(api_beacon_loss,
TP_PROTO(struct ieee80211_sub_if_data *sdata),
TP_ARGS(sdata),
TP_STRUCT__entry(
VIF_ENTRY
),
TP_fast_assign(
VIF_ASSIGN;
),
TP_printk(
VIF_PR_FMT,
VIF_PR_ARG
)
);
TRACE_EVENT(api_connection_loss,
TP_PROTO(struct ieee80211_sub_if_data *sdata),
TP_ARGS(sdata),
TP_STRUCT__entry(
VIF_ENTRY
),
TP_fast_assign(
VIF_ASSIGN;
),
TP_printk(
VIF_PR_FMT,
VIF_PR_ARG
)
);
TRACE_EVENT(api_cqm_rssi_notify,
TP_PROTO(struct ieee80211_sub_if_data *sdata,
enum nl80211_cqm_rssi_threshold_event rssi_event),
TP_ARGS(sdata, rssi_event),
TP_STRUCT__entry(
VIF_ENTRY
__field(u32, rssi_event)
),
TP_fast_assign(
VIF_ASSIGN;
__entry->rssi_event = rssi_event;
),
TP_printk(
VIF_PR_FMT " event:%d",
VIF_PR_ARG, __entry->rssi_event
)
);
TRACE_EVENT(api_scan_completed,
TP_PROTO(struct ieee80211_local *local, bool aborted),
TP_ARGS(local, aborted),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(bool, aborted)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->aborted = aborted;
),
TP_printk(
LOCAL_PR_FMT " aborted:%d",
LOCAL_PR_ARG, __entry->aborted
)
);
TRACE_EVENT(api_sched_scan_results,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local),
TP_STRUCT__entry(
LOCAL_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
),
TP_printk(
LOCAL_PR_FMT, LOCAL_PR_ARG
)
);
TRACE_EVENT(api_sched_scan_stopped,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local),
TP_STRUCT__entry(
LOCAL_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
),
TP_printk(
LOCAL_PR_FMT, LOCAL_PR_ARG
)
);
TRACE_EVENT(api_sta_block_awake,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sta *sta, bool block),
TP_ARGS(local, sta, block),
TP_STRUCT__entry(
LOCAL_ENTRY
STA_ENTRY
__field(bool, block)
),
TP_fast_assign(
LOCAL_ASSIGN;
STA_ASSIGN;
__entry->block = block;
),
TP_printk(
LOCAL_PR_FMT STA_PR_FMT " block:%d",
LOCAL_PR_ARG, STA_PR_FMT, __entry->block
)
);
TRACE_EVENT(api_chswitch_done,
TP_PROTO(struct ieee80211_sub_if_data *sdata, bool success),
TP_ARGS(sdata, success),
TP_STRUCT__entry(
VIF_ENTRY
__field(bool, success)
),
TP_fast_assign(
VIF_ASSIGN;
__entry->success = success;
),
TP_printk(
VIF_PR_FMT " success=%d",
VIF_PR_ARG, __entry->success
)
);
DEFINE_EVENT(local_only_evt, api_ready_on_channel,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
DEFINE_EVENT(local_only_evt, api_remain_on_channel_expired,
TP_PROTO(struct ieee80211_local *local),
TP_ARGS(local)
);
TRACE_EVENT(api_gtk_rekey_notify,
TP_PROTO(struct ieee80211_sub_if_data *sdata,
const u8 *bssid, const u8 *replay_ctr),
TP_ARGS(sdata, bssid, replay_ctr),
TP_STRUCT__entry(
VIF_ENTRY
__array(u8, bssid, ETH_ALEN)
__array(u8, replay_ctr, NL80211_REPLAY_CTR_LEN)
),
TP_fast_assign(
VIF_ASSIGN;
memcpy(__entry->bssid, bssid, ETH_ALEN);
memcpy(__entry->replay_ctr, replay_ctr, NL80211_REPLAY_CTR_LEN);
),
TP_printk(VIF_PR_FMT, VIF_PR_ARG)
);
TRACE_EVENT(api_enable_rssi_reports,
TP_PROTO(struct ieee80211_sub_if_data *sdata,
int rssi_min_thold, int rssi_max_thold),
TP_ARGS(sdata, rssi_min_thold, rssi_max_thold),
TP_STRUCT__entry(
VIF_ENTRY
__field(int, rssi_min_thold)
__field(int, rssi_max_thold)
),
TP_fast_assign(
VIF_ASSIGN;
__entry->rssi_min_thold = rssi_min_thold;
__entry->rssi_max_thold = rssi_max_thold;
),
TP_printk(
VIF_PR_FMT " rssi_min_thold =%d, rssi_max_thold = %d",
VIF_PR_ARG, __entry->rssi_min_thold, __entry->rssi_max_thold
)
);
TRACE_EVENT(api_eosp,
TP_PROTO(struct ieee80211_local *local,
struct ieee80211_sta *sta),
TP_ARGS(local, sta),
TP_STRUCT__entry(
LOCAL_ENTRY
STA_ENTRY
),
TP_fast_assign(
LOCAL_ASSIGN;
STA_ASSIGN;
),
TP_printk(
LOCAL_PR_FMT STA_PR_FMT,
LOCAL_PR_ARG, STA_PR_FMT
)
);
/*
* Tracing for internal functions
* (which may also be called in response to driver calls)
*/
TRACE_EVENT(wake_queue,
TP_PROTO(struct ieee80211_local *local, u16 queue,
enum queue_stop_reason reason),
TP_ARGS(local, queue, reason),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u16, queue)
__field(u32, reason)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->queue = queue;
__entry->reason = reason;
),
TP_printk(
LOCAL_PR_FMT " queue:%d, reason:%d",
LOCAL_PR_ARG, __entry->queue, __entry->reason
)
);
TRACE_EVENT(stop_queue,
TP_PROTO(struct ieee80211_local *local, u16 queue,
enum queue_stop_reason reason),
TP_ARGS(local, queue, reason),
TP_STRUCT__entry(
LOCAL_ENTRY
__field(u16, queue)
__field(u32, reason)
),
TP_fast_assign(
LOCAL_ASSIGN;
__entry->queue = queue;
__entry->reason = reason;
),
TP_printk(
LOCAL_PR_FMT " queue:%d, reason:%d",
LOCAL_PR_ARG, __entry->queue, __entry->reason
)
);
#endif /* !__MAC80211_DRIVER_TRACE || TRACE_HEADER_MULTI_READ */
#undef TRACE_INCLUDE_PATH
#define TRACE_INCLUDE_PATH .
#undef TRACE_INCLUDE_FILE
#define TRACE_INCLUDE_FILE driver-trace
#include <trace/define_trace.h>
| Java |
import win32pipe
import win32console
import win32process
import time
import win32con
import codecs
import ctypes
user32 = ctypes.windll.user32
CONQUE_WINDOWS_VK = {
'3' : win32con.VK_CANCEL,
'8' : win32con.VK_BACK,
'9' : win32con.VK_TAB,
'12' : win32con.VK_CLEAR,
'13' : win32con.VK_RETURN,
'17' : win32con.VK_CONTROL,
'20' : win32con.VK_CAPITAL,
'27' : win32con.VK_ESCAPE,
'28' : win32con.VK_CONVERT,
'35' : win32con.VK_END,
'36' : win32con.VK_HOME,
'37' : win32con.VK_LEFT,
'38' : win32con.VK_UP,
'39' : win32con.VK_RIGHT,
'40' : win32con.VK_DOWN,
'45' : win32con.VK_INSERT,
'46' : win32con.VK_DELETE,
'47' : win32con.VK_HELP
}
def make_input_key(c, control_key_state=None):
kc = win32console.PyINPUT_RECORDType (win32console.KEY_EVENT)
kc.KeyDown = True
kc.RepeatCount = 1
cnum = ord(c)
if cnum == 3:
pid_list = win32console.GetConsoleProcessList()
win32console.GenerateConsoleCtrlEvent(win32con.CTRL_C_EVENT, 0)
return
else:
kc.Char = unicode(c)
if str(cnum) in CONQUE_WINDOWS_VK:
kc.VirtualKeyCode = CONQUE_WINDOWS_VK[str(cnum)]
else:
kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum)
#kc.VirtualKeyCode = ctypes.windll.user32.VkKeyScanA(cnum+96)
#kc.ControlKeyState = win32con.LEFT_CTRL_PRESSED
return kc
#win32console.AttachConsole()
coord = win32console.PyCOORDType
con_stdout = win32console.GetStdHandle(win32console.STD_OUTPUT_HANDLE)
con_stdin = win32console.GetStdHandle(win32console.STD_INPUT_HANDLE)
flags = win32process.NORMAL_PRIORITY_CLASS
si = win32process.STARTUPINFO()
si.dwFlags |= win32con.STARTF_USESHOWWINDOW
(handle1, handle2, i1, i2) = win32process.CreateProcess(None, "cmd.exe", None, None, 0, flags, None, '.', si)
time.sleep(1)
#size = con_stdout.GetConsoleScreenBufferInfo()['Window']
# with codecs.open("log.txt", "w", "utf8") as f:
# for i in xrange(0, size.Bottom):
# f.write(con_stdout.ReadConsoleOutputCharacter(size.Right+1, coord(0, i)))
# f.write("\n")
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
HOST = "127.0.0.1"
PORT = 5554
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
(sc, scname) = s.accept()
while True:
msg = sc.recv(1)
if ord(msg) == 0:
break
keys = [make_input_key(msg)]
if keys:
con_stdin.WriteConsoleInput(keys)
win32process.TerminateProcess(handle1, 0) | Java |
class EventsController < ApplicationController
before_filter :authorize_organizer, except: [:index, :show]
def index
@events_upcoming = Event.paginate(page: params[:page_upcoming], :per_page => 5).upcoming()
@events_past = Event.paginate(page: params[:page_past], :per_page => 5).past()
@events_past_count = Event.past().count
end
def show
@event = Event.find(params[:id])
end
def new
@event = Event.new
@event.date = Date.today
end
def edit
@event = Event.find(params[:id])
end
def create
@event = Event.new(params[:event])
if @event.save
flash[:success] = "Event was successfully created."
redirect_to @event
else
render 'new'
end
end
def update
@event = Event.find(params[:id])
if @event.update_attributes(params[:event])
flash[:success] = "Event was successfully updated."
redirect_to @event
else
render 'edit'
end
end
def destroy
@event = Event.find(params[:id])
@event.destroy
flash[:success] = "Event was successfully deleted."
redirect_to events_url
end
end
| Java |
<?php global $woocommerce; ?>
<?php $woocommerce->show_messages(); ?>
<?php do_action('woocommerce_before_customer_login_form'); ?>
<?php if (get_option('woocommerce_enable_myaccount_registration')=='yes') : ?>
<div class="col2-set" id="customer_login">
<div class="col-1">
<?php endif; ?>
<h2><?php _e('Login', 'sp'); ?></h2>
<form method="post" class="login">
<p class="form-row form-row-first">
<label for="username"><?php _e('Username', 'sp'); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="username" id="username" />
</p>
<p class="form-row form-row-last">
<label for="password"><?php _e('Password', 'sp'); ?> <span class="required">*</span></label>
<input class="input-text" type="password" name="password" id="password" />
</p>
<div class="group"></div>
<p class="form-row">
<?php $woocommerce->nonce_field('login', 'login') ?>
<input type="submit" class="button" name="login" value="<?php _e('Login', 'sp'); ?>" />
<a class="lost_password" href="<?php echo esc_url( wp_lostpassword_url( home_url() ) ); ?>"><?php _e('Lost Password?', 'sp'); ?></a>
</p>
</form>
<?php if (get_option('woocommerce_enable_myaccount_registration')=='yes') : ?>
</div>
<div class="col-2">
<h2><?php _e('Register', 'sp'); ?></h2>
<form method="post" class="register">
<p class="form-row form-row-first">
<label for="reg_username"><?php _e('Username', 'sp'); ?> <span class="required">*</span></label>
<input type="text" class="input-text" name="username" id="reg_username" value="<?php if (isset($_POST['username'])) echo esc_attr($_POST['username']); ?>" />
</p>
<p class="form-row form-row-last">
<label for="reg_email"><?php _e('Email', 'sp'); ?> <span class="required">*</span></label>
<input type="email" class="input-text" name="email" id="reg_email" value="<?php if (isset($_POST['email'])) echo esc_attr($_POST['email']); ?>" />
</p>
<div class="group"></div>
<p class="form-row form-row-first">
<label for="reg_password"><?php _e('Password', 'sp'); ?> <span class="required">*</span></label>
<input type="password" class="input-text" name="password" id="reg_password" value="<?php if (isset($_POST['password'])) echo esc_attr($_POST['password']); ?>" />
</p>
<p class="form-row form-row-last">
<label for="reg_password2"><?php _e('Re-enter password', 'sp'); ?> <span class="required">*</span></label>
<input type="password" class="input-text" name="password2" id="reg_password2" value="<?php if (isset($_POST['password2'])) echo esc_attr($_POST['password2']); ?>" />
</p>
<div class="group"></div>
<!-- Spam Trap -->
<div style="left:-999em; position:absolute;"><label for="trap">Anti-spam</label><input type="text" name="email_2" id="trap" /></div>
<?php do_action( 'register_form' ); ?>
<p class="form-row">
<?php $woocommerce->nonce_field('register', 'register') ?>
<input type="submit" class="button" name="register" value="<?php _e('Register', 'sp'); ?>" />
</p>
</form>
</div>
</div>
<?php endif; ?>
<?php do_action('woocommerce_after_customer_login_form'); ?> | Java |
#!/bin/bash
#
###########################################################
# copie_clepub_veyon.sh
# Ce script est à lancer sur les clients veyon
# Il recupère la clé publique "teacher" du poste "maitre" veyon
# 20180327
##########################################################
DATE1=$(date +%F+%0kh%0M)
#Couleurs
ROUGE="\\033[1;31m"
VERT="\\033[1;32m"
BLEU="\\033[1;34m"
JAUNE="\\033[1;33m"
COLTITRE="\033[1;35m" # Rose
COLDEFAUT="\033[0;33m" # Brun-jaune
COLCMD="\033[1;37m" # Blanc
COLERREUR="\033[1;31m" # Rouge
COLTXT="\033[0;37m" # Gris
COLINFO="\033[0;36m" # Cyan
COLPARTIE="\033[1;34m" # Bleu
cle=key
repcle=/etc/veyon/keys/public/teacher
echo -e "$JAUNE"
echo "###########################################################################"
echo ""
echo "Voulez-vous configurer veyon (client) sur ce poste ?"
echo "Il faudra indiquer l'adresse ip du poste maitre veyon et son mdp root."
echo ""
echo "###########################################################################"
echo -e "$COLTXT"
echo -e "$COLINFO"
read -p "Que voulez-vous faire ?
1 (je veux configurer veyon sur ce client)
2 (non, je veux sortir !) : " rep
echo -e "$COLTXT"
case $rep in
1 )
echo -e "$JAUNE"
echo "Entrez l'adresse ip du poste veyon-master : "
echo -e "$COLTXT"
read IPMAST
cd /etc
rm -rf veyon
cd
mkdir -p $repcle
#mv $repcle/$cle $repcle/cle_$DATE1
cd $repcle
scp root@$IPMAST:$repcle/$cle . || ERREUR="1"
if [ "$ERREUR" = "1" ];then
echo -e "$COLERREUR"
echo "Erreur lors de la copie de la clé..."
echo "Vérifier l'adresse ip du poste veyon-master puis relancez le script."
echo -e "$COLTXT"
else
# Ajustement des droits et message
cd /etc
chmod -R 777 veyon/
echo -e "$VERT"
echo "La clé a été copiée depuis le poste veyon-master $IPMAST"
echo -e "$COLTXT"
# Neutralisation de master et de configurator sur le poste eleve
chmod -x /usr/bin/veyon-master
chmod -x /usr/bin/veyon-configurator
cd /usr/share/applications
mv veyon-master.desktop veyon-master.desktop.bak
mv veyon-configurator.desktop veyon-configurator.desktop.bak
cd
echo -e "$COLDEFAUT"
echo "Info : veyon-master et veyon-configurator ont été désactivés sur ce poste."
echo -e "$COLTXT"
fi
;;
* )
echo -e "$COLINFO"
echo "Pas de copie demandée."
echo -e "$VERT"
echo "###########################################################################"
echo ""
echo "Vous pourrez copier la clé publique veyon plus tard en lançant le script"
echo "/mnt/netlogon/alancer/copie_clepub_veyon.sh"
echo ""
echo "###########################################################################"
echo -e "$COLINFO"
echo "A bientôt !"
echo -e "$COLTXT"
exit 0
;;
esac
echo "Terminé !"
exit 0
| Java |
$('#section').on('click', '[id$="Empty"]', function(event) {
event.preventDefault();
var match = /(.+)Empty/.exec($(event.target).closest('.unwell').attr('id'));
var id = match[1];
var emptyId = match[0];
$('#'+id).trigger('addrow');
$('#'+emptyId).addClass('hidden');
return false;
});
$('#section').on('submit', 'form[name="formItem"]', function(e) {
e.preventDefault();
var form = $(this),
btn = form.find('.btn-primary'),
valid = isFormValid(form);
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
if($(e).val() == "Select an option"){
valid = false;
showPermanentError(form, "Please select a valid action.");
}
});
if (valid) {
btn.button('loading');
resetAlert($('#section'));
$.ajax({
type: 'POST',
url: form.attr('action'),
data: form.serialize()
}).always(function() {
btn.button('reset');
}).done(function(data, textStatus, jqXHR) {
showSuccess(form, "Saved");
window.location.hash = "#config/portal_module/"+form.find('input[name="id"]').val()+"/read"
}).fail(function(jqXHR) {
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(form, status_msg);
});
}
});
$('#section').on('click', '.delete-portal-module', function(e){
e.preventDefault();
var button = $(e.target);
button.button('loading');
$.ajax({
type: 'GET',
url: button.attr('href'),
}).always(function() {
}).done(function(data, textStatus, jqXHR) {
showSuccess(button.closest('.table'), "Deleted");
button.closest('tr').remove();
}).fail(function(jqXHR) {
button.button('reset');
$("body,html").animate({scrollTop:0}, 'fast');
var status_msg = getStatusMsg(jqXHR);
showPermanentError(button.closest('.table'), status_msg);
});
return false;
});
$('#section').on('click', '.expand', function(e){
e.preventDefault();
$(e.target).hide(function(){
$($(e.target).attr('data-expand')).slideDown();
});
return false;
});
$('#section').on('change', '#actions select[name$=".type"]', function(event) {
var type_input = $(event.currentTarget);
updateActionMatchInput(type_input,false);
});
$('#section').on('click', '#actionsContainer a[href="#add"]', function(event) {
setTimeout(initActionMatchInput, 3000);
});
function initActionMatchInput() {
$('select[name$=".type"]:not(:disabled)').each(function(i,e){
updateActionMatchInput($(e),true);
});
}
function updateActionMatchInput(type_input, keep) {
var match_input = type_input.next();
var type_value = type_input.val();
var match_input_template_id = '#' + type_value + "_action_match";
var match_input_template = $(match_input_template_id);
if ( match_input_template.length == 0 ) {
match_input_template = $('#default_action_match');
}
if ( match_input_template.length ) {
changeInputFromTemplate(match_input, match_input_template, keep);
if (type_value == "switch") {
type_input.next().typeahead({
source: searchSwitchesGenerator($('#section h2')),
minLength: 2,
items: 11,
matcher: function(item) { return true; }
});
}
}
}
| Java |
/*
* EffecTV for Android
* Copyright (C) 2013 Morihiro Soft
*
* MatrixTV.h :
*
* 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.
*/
/*
* EffecTV - Realtime Digital Video Effector
* Copyright (C) 2001-2006 FUKUCHI Kentaro
*
* matrixTV - A Matrix Like effect.
* This plugin for EffectTV is under GNU General Public License
* See the "COPYING" that should be shiped with this source code
* Copyright (C) 2001-2003 Monniez Christophe
* d-fence@swing.be
*
* 2003/12/24 Kentaro Fukuchi
* - Completely rewrote but based on Monniez's idea.
* - Uses edge detection, not only G value of each pixel.
* - Added 4x4 font includes number, alphabet and Japanese Katakana characters.
*/
#ifndef __MATRIXTV__
#define __MATRIXTV__
#include "BaseEffecTV.h"
class MatrixTV : public BaseEffecTV {
typedef BaseEffecTV super;
protected:
struct Blip {
int mode;
int y;
int timer;
int speed;
};
int show_info;
int mode;
int pause;
int mapW;
int mapH;
unsigned char* cmap;
unsigned char* vmap;
unsigned char* img;
unsigned char* font;
RGB32* palette;
Blip* blips;
virtual void intialize(bool reset);
virtual int readConfig();
virtual int writeConfig();
public:
MatrixTV(void);
virtual ~MatrixTV(void);
virtual const char* name(void);
virtual const char* title(void);
virtual const char** funcs(void);
virtual int start(Utils* utils, int width, int height);
virtual int stop(void);
virtual int draw(YUV* src_yuv, RGB32* dst_rgb, char* dst_msg);
virtual const char* event(int key_code);
virtual const char* touch(int action, int x, int y);
protected:
RGB32 green(unsigned int v);
int setPalette(void);
int setPattern(void);
void drawChar(RGB32* dst, unsigned char c, unsigned char v);
void createImg(RGB32* src);
void updateCharMap(void);
void darkenColumn(int);
void blipNone(int x);
void blipFall(int x);
void blipStop(int x);
void blipSlide(int x);
};
#endif // __MATRIXTV__
| Java |
jQuery(function($){
$.supersized({
//Functionality
slideshow : 1, //Slideshow on/off
autoplay : 1, //Slideshow starts playing automatically
start_slide : 1, //Start slide (0 is random)
slide_interval : 4000, //Length between transitions
slideshow_interval : 4000, //Length between transitions
transition : 1, //0-None, 1-Fade, 2-Slide Top, 3-Slide Right, 4-Slide Bottom, 5-Slide Left, 6-Carousel Right, 7-Carousel Left
transition_speed : 500, //Speed of transition
new_window : 1, //Image links open in new window/tab
pause_hover : 0, //Pause slideshow on hover
keyboard_nav : 1, //Keyboard navigation on/off
performance : 1, //0-Normal, 1-Hybrid speed/quality, 2-Optimizes image quality, 3-Optimizes transition speed // (Only works for Firefox/IE, not Webkit)
image_protect : 1, //Disables image dragging and right click with Javascript
image_path : 'img/', //Default image path
//Size & Position
min_width : 0, //Min width allowed (in pixels)
min_height : 0, //Min height allowed (in pixels)
vertical_center : 1, //Vertically center background
horizontal_center : 1, //Horizontally center background
fit_portrait : 1, //Portrait images will not exceed browser height
fit_landscape : 0, //Landscape images will not exceed browser width
//Components
navigation : 1, //Slideshow controls on/off
thumbnail_navigation : 1, //Thumbnail navigation
slide_counter : 1, //Display slide numbers
slide_captions : 1, //Slide caption (Pull from "title" in slides array)
slides : (function(){
var ret = new Array();
for(var i in supersizedImgs){
ret.push({image: supersizedImgs[i]});
}
return ret;
})()
});
}); | Java |
/*
* This file is part of the coreboot project.
*
* Copyright (C) 2012 ChromeOS Authors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <string.h>
#include <cbfs.h>
#include <cbmem.h>
#include <console/console.h>
#include <arch/cpu.h>
#include <cpu/x86/bist.h>
#include <cpu/x86/msr.h>
#include <cpu/x86/mtrr.h>
#include <halt.h>
#include <lib.h>
#include <timestamp.h>
#include <arch/io.h>
#include <arch/stages.h>
#include <device/pci_def.h>
#include <cpu/x86/lapic.h>
#include <cbfs.h>
#include <romstage_handoff.h>
#include <reset.h>
#include <stage_cache.h>
#include <vendorcode/google/chromeos/chromeos.h>
#if CONFIG_EC_GOOGLE_CHROMEEC
#include <ec/google/chromeec/ec.h>
#endif
#include "haswell.h"
#include "northbridge/intel/haswell/haswell.h"
#include "northbridge/intel/haswell/raminit.h"
#include "southbridge/intel/lynxpoint/pch.h"
#include "southbridge/intel/lynxpoint/me.h"
static inline void reset_system(void)
{
hard_reset();
halt();
}
/* The cache-as-ram assembly file calls romstage_main() after setting up
* cache-as-ram. romstage_main() will then call the mainboards's
* mainboard_romstage_entry() function. That function then calls
* romstage_common() below. The reason for the back and forth is to provide
* common entry point from cache-as-ram while still allowing for code sharing.
* Because we can't use global variables the stack is used for allocations --
* thus the need to call back and forth. */
static inline u32 *stack_push(u32 *stack, u32 value)
{
stack = &stack[-1];
*stack = value;
return stack;
}
/* Romstage needs quite a bit of stack for decompressing images since the lzma
* lib keeps its state on the stack during romstage. */
#define ROMSTAGE_RAM_STACK_SIZE 0x5000
static unsigned long choose_top_of_stack(void)
{
unsigned long stack_top;
/* cbmem_add() does a find() before add(). */
stack_top = (unsigned long)cbmem_add(CBMEM_ID_ROMSTAGE_RAM_STACK,
ROMSTAGE_RAM_STACK_SIZE);
stack_top += ROMSTAGE_RAM_STACK_SIZE;
return stack_top;
}
/* setup_romstage_stack_after_car() determines the stack to use after
* cache-as-ram is torn down as well as the MTRR settings to use. */
static void *setup_romstage_stack_after_car(void)
{
unsigned long top_of_stack;
int num_mtrrs;
u32 *slot;
u32 mtrr_mask_upper;
u32 top_of_ram;
/* Top of stack needs to be aligned to a 4-byte boundary. */
top_of_stack = choose_top_of_stack() & ~3;
slot = (void *)top_of_stack;
num_mtrrs = 0;
/* The upper bits of the MTRR mask need to set according to the number
* of physical address bits. */
mtrr_mask_upper = (1 << ((cpuid_eax(0x80000008) & 0xff) - 32)) - 1;
/* The order for each MTRR is value then base with upper 32-bits of
* each value coming before the lower 32-bits. The reasoning for
* this ordering is to create a stack layout like the following:
* +0: Number of MTRRs
* +4: MTRR base 0 31:0
* +8: MTRR base 0 63:32
* +12: MTRR mask 0 31:0
* +16: MTRR mask 0 63:32
* +20: MTRR base 1 31:0
* +24: MTRR base 1 63:32
* +28: MTRR mask 1 31:0
* +32: MTRR mask 1 63:32
*/
/* Cache the ROM as WP just below 4GiB. */
slot = stack_push(slot, mtrr_mask_upper); /* upper mask */
slot = stack_push(slot, ~(CACHE_ROM_SIZE - 1) | MTRRphysMaskValid);
slot = stack_push(slot, 0); /* upper base */
slot = stack_push(slot, ~(CACHE_ROM_SIZE - 1) | MTRR_TYPE_WRPROT);
num_mtrrs++;
/* Cache RAM as WB from 0 -> CONFIG_RAMTOP. */
slot = stack_push(slot, mtrr_mask_upper); /* upper mask */
slot = stack_push(slot, ~(CONFIG_RAMTOP - 1) | MTRRphysMaskValid);
slot = stack_push(slot, 0); /* upper base */
slot = stack_push(slot, 0 | MTRR_TYPE_WRBACK);
num_mtrrs++;
top_of_ram = (uint32_t)cbmem_top();
/* Cache 8MiB below the top of ram. On haswell systems the top of
* ram under 4GiB is the start of the TSEG region. It is required to
* be 8MiB aligned. Set this area as cacheable so it can be used later
* for ramstage before setting up the entire RAM as cacheable. */
slot = stack_push(slot, mtrr_mask_upper); /* upper mask */
slot = stack_push(slot, ~((8 << 20) - 1) | MTRRphysMaskValid);
slot = stack_push(slot, 0); /* upper base */
slot = stack_push(slot, (top_of_ram - (8 << 20)) | MTRR_TYPE_WRBACK);
num_mtrrs++;
/* Cache 8MiB at the top of ram. Top of ram on haswell systems
* is where the TSEG region resides. However, it is not restricted
* to SMM mode until SMM has been relocated. By setting the region
* to cacheable it provides faster access when relocating the SMM
* handler as well as using the TSEG region for other purposes. */
slot = stack_push(slot, mtrr_mask_upper); /* upper mask */
slot = stack_push(slot, ~((8 << 20) - 1) | MTRRphysMaskValid);
slot = stack_push(slot, 0); /* upper base */
slot = stack_push(slot, top_of_ram | MTRR_TYPE_WRBACK);
num_mtrrs++;
/* Save the number of MTRRs to setup. Return the stack location
* pointing to the number of MTRRs. */
slot = stack_push(slot, num_mtrrs);
return slot;
}
void * asmlinkage romstage_main(unsigned long bist)
{
int i;
void *romstage_stack_after_car;
const int num_guards = 4;
const u32 stack_guard = 0xdeadbeef;
u32 *stack_base = (void *)(CONFIG_DCACHE_RAM_BASE +
CONFIG_DCACHE_RAM_SIZE -
CONFIG_DCACHE_RAM_ROMSTAGE_STACK_SIZE);
printk(BIOS_DEBUG, "Setting up stack guards.\n");
for (i = 0; i < num_guards; i++)
stack_base[i] = stack_guard;
mainboard_romstage_entry(bist);
/* Check the stack. */
for (i = 0; i < num_guards; i++) {
if (stack_base[i] == stack_guard)
continue;
printk(BIOS_DEBUG, "Smashed stack detected in romstage!\n");
}
/* Get the stack to use after cache-as-ram is torn down. */
romstage_stack_after_car = setup_romstage_stack_after_car();
return romstage_stack_after_car;
}
void romstage_common(const struct romstage_params *params)
{
int boot_mode;
int wake_from_s3;
struct romstage_handoff *handoff;
timestamp_init(get_initial_timestamp());
timestamp_add_now(TS_START_ROMSTAGE);
if (params->bist == 0)
enable_lapic();
wake_from_s3 = early_pch_init(params->gpio_map, params->rcba_config);
#if CONFIG_EC_GOOGLE_CHROMEEC
/* Ensure the EC is in the right mode for recovery */
google_chromeec_early_init();
#endif
/* Halt if there was a built in self test failure */
report_bist_failure(params->bist);
/* Perform some early chipset initialization required
* before RAM initialization can work
*/
haswell_early_initialization(HASWELL_MOBILE);
printk(BIOS_DEBUG, "Back from haswell_early_initialization()\n");
if (wake_from_s3) {
#if CONFIG_HAVE_ACPI_RESUME
printk(BIOS_DEBUG, "Resume from S3 detected.\n");
#else
printk(BIOS_DEBUG, "Resume from S3 detected, but disabled.\n");
wake_from_s3 = 0;
#endif
}
/* There are hard coded assumptions of 2 meaning s3 wake. Normalize
* the users of the 2 literal here based off wake_from_s3. */
boot_mode = wake_from_s3 ? 2 : 0;
/* Prepare USB controller early in S3 resume */
if (wake_from_s3)
enable_usb_bar();
post_code(0x3a);
params->pei_data->boot_mode = boot_mode;
timestamp_add_now(TS_BEFORE_INITRAM);
report_platform_info();
if (params->copy_spd != NULL)
params->copy_spd(params->pei_data);
sdram_initialize(params->pei_data);
timestamp_add_now(TS_AFTER_INITRAM);
post_code(0x3b);
intel_early_me_status();
quick_ram_check();
post_code(0x3e);
if (!wake_from_s3) {
cbmem_initialize_empty();
stage_cache_create_empty();
/* Save data returned from MRC on non-S3 resumes. */
save_mrc_data(params->pei_data);
} else {
stage_cache_recover();
if (cbmem_initialize()) {
#if CONFIG_HAVE_ACPI_RESUME
/* Failed S3 resume, reset to come up cleanly */
reset_system();
#endif
}
}
handoff = romstage_handoff_find_or_add();
if (handoff != NULL)
handoff->s3_resume = wake_from_s3;
else
printk(BIOS_DEBUG, "Romstage handoff structure not added!\n");
post_code(0x3f);
#if CONFIG_CHROMEOS
init_chromeos(boot_mode);
#endif
timestamp_add_now(TS_END_ROMSTAGE);
}
static inline void prepare_for_resume(struct romstage_handoff *handoff)
{
/* Only need to save memory when ramstage isn't relocatable. */
#if !CONFIG_RELOCATABLE_RAMSTAGE
#if CONFIG_HAVE_ACPI_RESUME
/* Back up the OS-controlled memory where ramstage will be loaded. */
if (handoff != NULL && handoff->s3_resume) {
void *src = (void *)CONFIG_RAMBASE;
void *dest = cbmem_find(CBMEM_ID_RESUME);
if (dest != NULL)
memcpy(dest, src, HIGH_MEMORY_SAVE);
}
#endif
#endif
}
void romstage_after_car(void)
{
struct romstage_handoff *handoff;
handoff = romstage_handoff_find_or_add();
prepare_for_resume(handoff);
/* Load the ramstage. */
copy_and_run();
}
#if IS_ENABLED(CONFIG_CACHE_RELOCATED_RAMSTAGE_OUTSIDE_CBMEM)
void stage_cache_external_region(void **base, size_t *size)
{
/* The ramstage cache lives in the TSEG region at RESERVED_SMM_OFFSET.
* The top of ram is defined to be the TSEG base address. */
*size = RESERVED_SMM_SIZE;
*base = (void *)((uint32_t)cbmem_top() + RESERVED_SMM_OFFSET);
}
void ramstage_cache_invalid(void)
{
#if CONFIG_RESET_ON_INVALID_RAMSTAGE_CACHE
reset_system();
#endif
}
#endif
| Java |
package com.mmm.product.domain;
import java.io.Serializable;
public class ShippingDetails implements Serializable{
private static final long serialVersionUID = 5941389959992371612L;
}
| Java |
package org.jiserte.bioformats.readers.phylip;
import org.jiserte.bioformats.readers.faults.AlignmentReadingFault;
public class FirstBlockLinePhylipFault extends AlignmentReadingFault {
public FirstBlockLinePhylipFault() {
super();
this.setMessage("Sequences in the first block of data must have a description of 10 characters and then the sequence.");
}
}
| Java |
<?php
/*=======================================================================
// File: BACKEND.INC.PHP
// Description: All various output backends for QR barcodes available
// Created: 2008-08-01
// Ver: $Id: backend.inc.php 1504 2009-07-06 13:34:57Z ljp $
//
// Copyright (c) 2008 Aditus Consulting. All rights reserved.
//========================================================================
*/
DEFINE('BACKEND_ASCII', 0);
DEFINE('BACKEND_IMAGE', 1);
DEFINE('BACKEND_PS', 2);
DEFINE('BACKEND_EPS', 3);
//--------------------------------------------------------------------------------
// Class: QRCodeBackend
// Description: Parent class for all common functionality for barcode backends
//--------------------------------------------------------------------------------
class QRCodeBackend {
protected $iEncoder = NULL;
protected $iModWidth = 2;
protected $iInv = false;
protected $iQuietZone = 0;
protected $iError = 0;
protected $iQRInfo = array(); // Holds some infromation the QR code just generated
function __construct($aBarcodeEncoder) {
$this->iEncoder = $aBarcodeEncoder;
}
function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') {
if( $aDebug !== FALSE ) {
$this->iEncoder->SetDebugLevel($aDebug);
}
// If data is an array we assume it is supposed to be manual encodation.
// (A more thorough data check is made in the encodation class)
$manual = is_array($aData) ;
// Return the print specificiation (QRLayout)
return $this->iEncoder->Enc($aData, $manual);
}
function GetQRInfo() {
return $this->iQRInfo;
}
function isCmdLine() {
$s=php_sapi_name();
return substr($s, 0, 3) == 'cli';
}
function fmtInfo($aS) {
if ( !$this->isCmdLine() ) {
return '<pre>' . $aS . '<pre>';
}
else return $aS;
}
function SetModuleWidth($aW) {
$this->iModWidth = $aW;
}
function SetQuietZone($aW) {
$this->iQuietZone = $aW;
}
function SetTilde($aFlg = true) {
//throw new QRException('Tilde processing is not yet supported for QR Barcodes.',-1);
throw new QRExceptionL(1000);
//$this->iEncoder->SetTilde($aFlg);
}
function SetInvert($aFlg = true) {
//throw new QRException("Inverting the bit pattern is not supported for QR Barcodes.",-1);
throw new QRExceptionL(1001);
}
function GetError() {
return $this->iError;
}
function StrokeFromFile($aFromFileName,$aFileName='',$aDebug=FALSE) {
$data = @file_get_contents($aFromFileName);
if( $data === FALSE ) {
//throw new QRException("Cannot read data from file $aFromFileName");
throw new QRExceptionL(1002,$aFromFileName);
}
$this->Stroke($data,$aFileName,$aDebug);
}
}
//--------------------------------------------------------------------------------
// Class: QRCodeBackend_PS
// Description: Backend to generate postscript (or EPS) representation of the barcode
//--------------------------------------------------------------------------------
class QRCodeBackend_PS extends QRCodeBackend {
private $iEPS = false;
function __construct($aBarcodeEncoder) {
parent::__construct($aBarcodeEncoder);
}
function SetEPS($aFlg=true) {
$this->iEPS = $aFlg;
}
function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') {
$pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile);
$w = $this->iModWidth;
$n = $pspec->iSize[0]; // width/height of matrix
$ystart = 4*$w + $n*$w;
$xstart = 4*$w ;
$totwidth = $n*$w+8*$w ;
$totheight = $n*$w+8*$w ;
$psbar = "%Data: $aData\n";
$psbar .= "%Each line represents one row and the x-position for black modules: [xpos]\n";
if( is_array($aData)) {
$data = " (manual encodation schemas) \n";
$m = count($aData);
for($i=0; $i < $m; $i++) {
$data .= "%% (" . $aData[$i][0] . " : " . $aData[$i][1] . ")\n" ;
}
$aData = $data;
}
$y = $ystart;
$psbar .= "\n";
$psbar .= ($w+0.05)." setlinewidth\n";
for( $r=0; $r < $n ; ++$r, $y -= $w ) {
$psbar .= '[';
$x = $xstart;
for( $i=0; $i < $n; ++$i, $x += $w ) {
if( $pspec->iMatrix[$r][$i] == 1) {
$psbar .= "[$x]";
}
}
$psbar .= "] {{} forall $y moveto 0 -".($w+0.05)." rlineto stroke} forall\n";
}
$psbar .= "\n";
$y += 4*$w;
$psbar .= "%End of QR Barcode \n\n";
if( !$this->iEPS )
$psbar .= "showpage \n\n";
$psbar .= "%%Trailer\n\n";
$errStr = array('L', 'M', 'Q', 'H');
$ps = ($this->iEPS ? "%!PS-Adobe EPSF-3.0\n" : "%!PS-Adobe-3.0\n" ) .
"%%Title: QR Barcode ".$pspec->iVersion."-".$errStr[$pspec->iErrLevel].", mask=".$pspec->iMaskIdx."\n".
"%%Creator: JpGraph Barcode http://www.aditus.nu/jpgraph/\n".
"%%CreationDate: ".date("D j M H:i:s Y",time())."\n";
if( $this->iEPS ) {
$ps .= "%%BoundingBox: 0 0 $totwidth $totheight\n";
}
else {
$ps .= "%%DocumentPaperSizes: A4\n";
}
$ps .=
"%%EndComments\n".
"%%BeginProlog\n".
"%%EndProlog\n";
if( !$this->iEPS )
$ps .= "%%Page: 1 1\n";
$ps .= "\n%Module width: $this->iModWidth pt\n\n";
/*
if( $this->iScale != 1 ) {
$ps .=
"%%Scale barcode\n".
"$this->iScale $this->iScale scale\n\n";
}
*/
$ps = $ps.$psbar;
$errStr=array ( 'L', 'M', 'Q', 'H' );
$this->iQRInfo = array($pspec->iVersion,$errStr[$pspec->iErrLevel],$pspec->iMaskIdx);
if( $aFileName !== '' ) {
$fp = @fopen($aFileName,'wt');
if( $fp === FALSE ) {
// throw new QRException("Cannot open file $aFileName.");
throw new QRExceptionL(1003,$aFileName);
}
if( fwrite($fp,$ps) === FALSE ) {
//throw new QRException("Cannot write barcode to file $aFileName.");
throw new QRExceptionL(1004,$aFileName);
}
return fclose($fp);
}
else {
return $ps;
}
}
}
require_once('rgb_colors.inc.php');
//--------------------------------------------------------------------------------
// Class: QRCodeBackend_IMAGE
// Description: Backend to generate image representation of the barcode
//--------------------------------------------------------------------------------
class QRCodeBackend_IMAGE extends QRCodeBackend {
private $iColor = array ( array ( 0, 0, 0 ), array ( 255, 255, 255 ), array ( 255, 255, 255 ) );
private $iRGB = null;
private $iImgFormat = 'png', $iQualityJPEG = 75;
function __construct($aBarcodeEncoder) {
parent::__construct($aBarcodeEncoder);
$this->iRGB=new BarcodeRGB();
}
function SetSize($aShapeIdx) {
$this->iEncoder->SetSize($aShapeIdx);
}
function SetColor($aOne, $aZero, $aBackground = array ( 255, 255, 255 )) {
$this->iColor[0]=$aOne;
$this->iColor[1]=$aZero;
$this->iColor[2]=$aBackground;
}
// Specify image format. Note depending on your installation
// of PHP not all formats may be supported.
function SetImgFormat($aFormat, $aQuality = 75) {
$this->iQualityJPEG=$aQuality;
$this->iImgFormat=$aFormat;
}
function PrepareImgFormat() {
$format=strtolower($this->iImgFormat);
if ( $format == 'jpg' ) {
$format = 'jpeg';
}
$tst=true;
$supported=imagetypes();
if ( $format == "auto" ) {
if ( $supported & IMG_PNG )
$this->iImgFormat="png";
elseif( $supported & IMG_JPG )
$this->iImgFormat="jpeg";
elseif( $supported & IMG_GIF )
$this->iImgFormat="gif";
elseif( $supported & IMG_WBMP )
$this->iImgFormat="wbmp";
else {
//throw new QRException('Unsupported image format selected. Check your GD installation', -1);
throw new QRExceptionL(1005);
}
}
else {
if ( $format == "jpeg" || $format == "png" || $format == "gif" ) {
if ( $format == "jpeg" && !($supported & IMG_JPG) )
$tst=false;
elseif( $format == "png" && !($supported & IMG_PNG) )
$tst=false;
elseif( $format == "gif" && !($supported & IMG_GIF) )
$tst=false;
elseif( $format == "wbmp" && !($supported & IMG_WBMP) )
$tst=false;
else {
$this->iImgFormat = $format;
}
}
else
$tst=false;
if ( !$tst ) {
//throw new QRException('Unsupported image format selected. Check your GD installation', -1);
throw new QRExceptionL(1005);
}
}
return true;
}
function Stroke(&$aData, $aFileName = '', $aDebug = false, $aDebugFile = 'qrlog.txt') {
// Check the chosen graphic format
$this->PrepareImgFormat();
$pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile);
$mat=$pspec->iMatrix;
$m=$this->iModWidth;
$this->iQuietZone = $pspec->iQuietZone;
$h=$pspec->iSize[0] * $m + 2 * $m * $this->iQuietZone;
$w=$pspec->iSize[1] * $m + 2 * $m * $this->iQuietZone;
$img=@imagecreatetruecolor($w, $h);
if ( !$img ) {
$this->iError=-12;
return false;
}
$canvas_color = $this->iRGB->Allocate($img, 'white');
$one_color = $this->iRGB->Allocate($img, $this->iColor[0]);
$zero_color = $this->iRGB->Allocate($img, $this->iColor[1]);
$bkg_color = $this->iRGB->Allocate($img, $this->iColor[2]);
if ( $this->iInv && $pspec->iAllowColorInversion ) {
// Swap one/zero colors
$tmp=$one_color;
$one_color=$zero_color;
$zero_color=$tmp;
}
if ( $canvas_color === false || $one_color === false || $zero_color === false || $bkg_color === false ) {
// throw new QRException('Cannot set the selected colors. Check your GD installation and spelling of color name', -1);
throw new QRExceptionL(1006);
}
imagefilledrectangle($img, 0, 0, $w - 1, $h - 1, $canvas_color);
imagefilledrectangle($img, 0, 0, $w - 1, $h - 1, $bkg_color);
$borderoffset=0;
if ( $pspec->iDrawLeftBottomBorder ) {
// Left alignment line
imagefilledrectangle($img, $m * $this->iQuietZone, $m * $this->iQuietZone, $m * $this->iQuietZone + $m - 1,
$h - $m * $this->iQuietZone - 1, $one_color);
// Bottom alignment line
imagefilledrectangle($img, $m * $this->iQuietZone, $h - $m * $this->iQuietZone - $m,
$w - $m * $this->iQuietZone - 1, $h - $m * $this->iQuietZone - 1, $one_color);
$borderoffset=1;
}
for( $i = 0; $i < $pspec->iSize[0] - $borderoffset; ++$i ) {
for( $j = $borderoffset; $j < $pspec->iSize[1]; ++$j ) {
$bit = $mat[$i][$j] == 1 ? $one_color : $zero_color;
if ( $m == 1 ) {
imagesetpixel($img, $j + $m * $this->iQuietZone, $i + $m * $this->iQuietZone, $bit);
}
else {
imagefilledrectangle($img, $j * $m + $m * $this->iQuietZone,
$i * $m + $m * $this->iQuietZone, $j * $m + $m - 1 + $m * $this->iQuietZone,
$i * $m + $m - 1 + $m * $this->iQuietZone, $bit);
}
}
}
if ( $pspec->iDrawLeftBottomBorder ) {
// Left alignment line
imagefilledrectangle($img, $this->iQuietZone, $this->iQuietZone, $this->iQuietZone + $m - 1,
$h - $this->iQuietZone - 1, $one_color);
// Bottom alignment line
imagefilledrectangle($img, $this->iQuietZone, $h - $this->iQuietZone - $m, $w - $this->iQuietZone - 1,
$h - $this->iQuietZone - 1, $one_color);
}
if ( headers_sent($file, $lineno) ) {
// Headers already sent special error
throw new QRExceptionL(1007,$file,$lineno);
}
if ( $aFileName == '' ) {
$s=php_sapi_name();
if ( substr($s, 0, 3) != 'cli' ) {
header("Content-type: image/$this->iImgFormat");
}
switch( $this->iImgFormat ) {
case 'png':
$res=@imagepng($img);
break;
case 'jpeg':
$res=@imagejpeg($img, NULL, $this->iQualityJPEG);
break;
case 'gif':
$res=@imagegif($img);
break;
case 'wbmp':
$res=@imagewbmp($img);
break;
}
if( $res === FALSE ) {
throw new QRExceptionL(1008,$this->iImgFormat);
//throw new QRException("Could not create the barcode image. Check your GD/PHP installation.");
}
}
else {
switch( $this->iImgFormat ) {
case 'png':
$res=@imagepng($img, $aFileName);
break;
case 'jpeg':
$res=@imagejpeg($img, $aFileName, $this->iQualityJPEG);
break;
case 'gif':
$res=@imagegif($img, $aFileName);
break;
case 'wbmp':
$res=@imagewbmp($img, $aFileName);
break;
}
if( $res === FALSE ) {
throw new QRExceptionL(1011,$this->iImgFormat);
// 1011 => 'Could not write the barcode to file. Check the filesystem permission.',
}
}
// If debugging is enabled store encoding info in the specified log file
if( $aDebug !== FALSE && $aDebugFile !== '' ) {
$s = "QR Barcode Log created: " . date('r')."\n";
$s .= "Debug level = $aDebug \n";
$s .= "SAPI: " . php_sapi_name() ."\n\n";
$s .= $this->iEncoder;
$s .= $pspec;
$fp = @fopen($aDebugFile,'wt');
if( $fp === FALSE ) {
//throw new QRException("Cannot open log file for writing $aDebugFile.");
throw new QRExceptionL(1009,$aDebugFile);
}
if( @fwrite($fp,$s) === FALSE ) {
//throw new QRException("Cannot write log info to log file $aDebugFile.");
throw new QRExceptionL(1010,$aDebugFile);
}
fclose($fp);
}
$errStr=array ( 'L', 'M', 'Q', 'H' );
$this->iQRInfo = array($pspec->iVersion,$errStr[$pspec->iErrLevel],$pspec->iMaskIdx);
return 'true';
}
}
//--------------------------------------------------------------------------------
// Class: QRCodeBackend_ASCII
// Description: Backend to generate ASCII representation of the barcode
//--------------------------------------------------------------------------------
class QRCodeBackend_ASCII extends QRCodeBackend {
function __construct(&$aBarcodeEncoder) {
parent::__construct($aBarcodeEncoder);
}
function GetMatrixString($mat, $inv = false, $width = 1, $aOne = 'X', $aZero = '-') {
if ( $width > 1 ) {
$m=count($mat);
$n=count($mat[0]);
$newmat=array();
for( $i = 0; $i < $m; ++$i )
for( $j = 0; $j < $n; ++$j )
for( $k = 0; $k < $width; ++$k )
for( $l = 0; $l < $width; ++$l )
$newmat[$i * $width + $k][$j * $width + $l]=$mat[$i][$j];
$mat=$newmat;
}
$m=count($mat);
$n=count($mat[0]);
$s = '';
for( $i = 0; $i < $m; ++$i ) {
for( $j = 0; $j < $n; ++$j ) {
if ( !$inv ) {
$s .= $mat[$i][$j] ? $aOne : $aZero;
}
else {
$s .= !$mat[$i][$j] ? $aOne : $aZero;
}
}
$s .= "\n";
}
$s .= "\n";
return $this->fmtInfo($s);
}
function Stroke(&$aData, $aFileName='', $aDebug = FALSE, $aDebugFile = '') {
$pspec = parent::Stroke($aData, $aFileName, $aDebug, $aDebugFile);
// If debugging is enabled store encoding info in the specified log file
if( $aDebug !== FALSE ) {
$s = str_repeat('=',80)."\n";
$s .= "QR Barcode Log created: " . date('r')."\n";
$s .= str_repeat('=',80)."\n";
$s .= "Debug level = $aDebug \n";
$s .= "SAPI: " . php_sapi_name() ."\n\n";
$s .= $this->iEncoder;
$s .= $pspec . "\n";
$s .= str_repeat('=',80)."\nEnd of QR Barcode log file.\n".str_repeat('=',80)."\n\n";
if( $aDebugFile != '' ) {
$fp = @fopen($aDebugFile,'wt');
if( $fp === FALSE ) {
// throw new QRException("Cannot open log file for writing $aDebugFile.");
throw new QRExceptionL(1009,$aDebugFile);
}
if( @fwrite($fp,$s) === FALSE ) {
// throw new QRException("Cannot write log info to log file $aDebugFile.");
throw new QRExceptionL(1010,$aDebugFile);
}
fclose($fp);
}
else {
echo $this->fmtInfo($s);
}
}
$s = $this->GetMatrixString($pspec->iMatrix, $this->iInv, $this->iModWidth, 'X', '-') . "\n";
if( $aFileName !== '' ) {
$fp = @fopen($aFileName,'wt');
if( $fp === FALSE ) {
// throw new QRException("Cannot open file $aFileName.");
throw new QRExceptionL(1003,$aFileName);
}
if( fwrite($fp,$s) === FALSE ) {
// throw new QRException("Cannot write barcode to file $aFileName.");
throw new QRExceptionL(1004,$aFileName);
}
return fclose($fp);
}
else {
return $s;
}
}
}
//--------------------------------------------------------------------------------
// Class: QRCodeBackendFactory
// Description: Factory to return a suitable backend for generating barcode
//--------------------------------------------------------------------------------
class QRCodeBackendFactory {
static function Create(&$aBarcodeEncoder, $aBackend = BACKEND_IMAGE) {
switch( $aBackend ) {
case BACKEND_ASCII:
return new QRCodeBackend_ASCII($aBarcodeEncoder);
break;
case BACKEND_IMAGE:
return new QRCodeBackend_Image($aBarcodeEncoder);
break;
case BACKEND_PS:
return new QRCodeBackend_PS($aBarcodeEncoder);
break;
case BACKEND_EPS:
$b = new QRCodeBackend_PS($aBarcodeEncoder);
$b->SetEPS(true);
return $b;
break;
default:
return false;
}
}
}
?> | Java |
namespace Tipshare
{
partial class Tipshare
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.gbAM = new System.Windows.Forms.GroupBox();
this.tbAMUnallocatedAdj = new System.Windows.Forms.TextBox();
this.lblAMCurrentUnallocated = new System.Windows.Forms.Label();
this.tbAMUnallocatedSugg = new System.Windows.Forms.TextBox();
this.lblAMUnallocated = new System.Windows.Forms.Label();
this.lAMAdj = new System.Windows.Forms.Label();
this.lAMSugg = new System.Windows.Forms.Label();
this.lAMID = new System.Windows.Forms.Label();
this.lAMName = new System.Windows.Forms.Label();
this.gbControls = new System.Windows.Forms.GroupBox();
this.btnDistributeUnallocated = new System.Windows.Forms.Button();
this.btnSettings = new System.Windows.Forms.Button();
this.btnReset = new System.Windows.Forms.Button();
this.btnSave = new System.Windows.Forms.Button();
this.lDate = new System.Windows.Forms.Label();
this.lDay = new System.Windows.Forms.Label();
this.bDayBack = new System.Windows.Forms.Button();
this.bDayForward = new System.Windows.Forms.Button();
this.gbPM = new System.Windows.Forms.GroupBox();
this.tbPMUnallocatedAdj = new System.Windows.Forms.TextBox();
this.lblPMCurrentUnallocated = new System.Windows.Forms.Label();
this.tbPMUnallocatedSugg = new System.Windows.Forms.TextBox();
this.lblPMUnallocated = new System.Windows.Forms.Label();
this.lPMAdj = new System.Windows.Forms.Label();
this.lPMSugg = new System.Windows.Forms.Label();
this.lPMID = new System.Windows.Forms.Label();
this.lPMName = new System.Windows.Forms.Label();
this.msMenu = new System.Windows.Forms.MenuStrip();
this.mFile = new System.Windows.Forms.ToolStripMenuItem();
this.miJump = new System.Windows.Forms.ToolStripMenuItem();
this.miPrint = new System.Windows.Forms.ToolStripMenuItem();
this.miExit = new System.Windows.Forms.ToolStripMenuItem();
this.mAbout = new System.Windows.Forms.ToolStripMenuItem();
this.miHelp = new System.Windows.Forms.ToolStripMenuItem();
this.miAbout = new System.Windows.Forms.ToolStripMenuItem();
this.tTimer = new System.Windows.Forms.Timer(this.components);
this.gbTotals = new System.Windows.Forms.GroupBox();
this.lTotalSugg = new System.Windows.Forms.Label();
this.lTotalAdj = new System.Windows.Forms.Label();
this.lLabTotSug = new System.Windows.Forms.Label();
this.lTotalAMSugg = new System.Windows.Forms.Label();
this.lTotalAMAdj = new System.Windows.Forms.Label();
this.lLabTotAMSugg = new System.Windows.Forms.Label();
this.lTotalPMSugg = new System.Windows.Forms.Label();
this.lTotalPMAdj = new System.Windows.Forms.Label();
this.lLabTotPMSugg = new System.Windows.Forms.Label();
this.gbAM.SuspendLayout();
this.gbControls.SuspendLayout();
this.gbPM.SuspendLayout();
this.msMenu.SuspendLayout();
this.gbTotals.SuspendLayout();
this.SuspendLayout();
//
// gbAM
//
this.gbAM.Controls.Add(this.tbAMUnallocatedAdj);
this.gbAM.Controls.Add(this.lblAMCurrentUnallocated);
this.gbAM.Controls.Add(this.tbAMUnallocatedSugg);
this.gbAM.Controls.Add(this.lblAMUnallocated);
this.gbAM.Controls.Add(this.lAMAdj);
this.gbAM.Controls.Add(this.lAMSugg);
this.gbAM.Controls.Add(this.lAMID);
this.gbAM.Controls.Add(this.lAMName);
this.gbAM.Location = new System.Drawing.Point(12, 27);
this.gbAM.Name = "gbAM";
this.gbAM.Size = new System.Drawing.Size(318, 430);
this.gbAM.TabIndex = 1;
this.gbAM.TabStop = false;
this.gbAM.Text = "AM Declarations";
//
// tbAMUnallocatedAdj
//
this.tbAMUnallocatedAdj.Location = new System.Drawing.Point(277, 404);
this.tbAMUnallocatedAdj.Name = "tbAMUnallocatedAdj";
this.tbAMUnallocatedAdj.ReadOnly = true;
this.tbAMUnallocatedAdj.Size = new System.Drawing.Size(35, 20);
this.tbAMUnallocatedAdj.TabIndex = 14;
//
// lblAMCurrentUnallocated
//
this.lblAMCurrentUnallocated.AutoSize = true;
this.lblAMCurrentUnallocated.Location = new System.Drawing.Point(167, 407);
this.lblAMCurrentUnallocated.Name = "lblAMCurrentUnallocated";
this.lblAMCurrentUnallocated.Size = new System.Drawing.Size(104, 13);
this.lblAMCurrentUnallocated.TabIndex = 13;
this.lblAMCurrentUnallocated.Text = "Current Unallocated:";
//
// tbAMUnallocatedSugg
//
this.tbAMUnallocatedSugg.Location = new System.Drawing.Point(118, 404);
this.tbAMUnallocatedSugg.Name = "tbAMUnallocatedSugg";
this.tbAMUnallocatedSugg.ReadOnly = true;
this.tbAMUnallocatedSugg.Size = new System.Drawing.Size(35, 20);
this.tbAMUnallocatedSugg.TabIndex = 12;
//
// lblAMUnallocated
//
this.lblAMUnallocated.AutoSize = true;
this.lblAMUnallocated.Location = new System.Drawing.Point(6, 407);
this.lblAMUnallocated.Name = "lblAMUnallocated";
this.lblAMUnallocated.Size = new System.Drawing.Size(106, 13);
this.lblAMUnallocated.TabIndex = 10;
this.lblAMUnallocated.Text = "Starting Unallocated:";
//
// lAMAdj
//
this.lAMAdj.AutoSize = true;
this.lAMAdj.Location = new System.Drawing.Point(276, 16);
this.lAMAdj.Name = "lAMAdj";
this.lAMAdj.Size = new System.Drawing.Size(22, 13);
this.lAMAdj.TabIndex = 9;
this.lAMAdj.Text = "Adj";
//
// lAMSugg
//
this.lAMSugg.AutoSize = true;
this.lAMSugg.Location = new System.Drawing.Point(216, 16);
this.lAMSugg.Name = "lAMSugg";
this.lAMSugg.Size = new System.Drawing.Size(32, 13);
this.lAMSugg.TabIndex = 8;
this.lAMSugg.Text = "Sugg";
//
// lAMID
//
this.lAMID.AutoSize = true;
this.lAMID.Location = new System.Drawing.Point(169, 16);
this.lAMID.Name = "lAMID";
this.lAMID.Size = new System.Drawing.Size(18, 13);
this.lAMID.TabIndex = 7;
this.lAMID.Text = "ID";
//
// lAMName
//
this.lAMName.AutoSize = true;
this.lAMName.Location = new System.Drawing.Point(69, 16);
this.lAMName.Name = "lAMName";
this.lAMName.Size = new System.Drawing.Size(35, 13);
this.lAMName.TabIndex = 6;
this.lAMName.Text = "Name";
//
// gbControls
//
this.gbControls.Controls.Add(this.btnDistributeUnallocated);
this.gbControls.Controls.Add(this.btnSettings);
this.gbControls.Controls.Add(this.btnReset);
this.gbControls.Controls.Add(this.btnSave);
this.gbControls.Controls.Add(this.lDate);
this.gbControls.Controls.Add(this.lDay);
this.gbControls.Controls.Add(this.bDayBack);
this.gbControls.Controls.Add(this.bDayForward);
this.gbControls.Location = new System.Drawing.Point(12, 518);
this.gbControls.Name = "gbControls";
this.gbControls.Size = new System.Drawing.Size(648, 62);
this.gbControls.TabIndex = 2;
this.gbControls.TabStop = false;
this.gbControls.Text = "Controls";
//
// btnDistributeUnallocated
//
this.btnDistributeUnallocated.Enabled = false;
this.btnDistributeUnallocated.Location = new System.Drawing.Point(123, 19);
this.btnDistributeUnallocated.Name = "btnDistributeUnallocated";
this.btnDistributeUnallocated.Size = new System.Drawing.Size(111, 35);
this.btnDistributeUnallocated.TabIndex = 13;
this.btnDistributeUnallocated.Text = "Distribute Unallocated";
this.btnDistributeUnallocated.UseVisualStyleBackColor = true;
this.btnDistributeUnallocated.Click += new System.EventHandler(this.btnDistributeUnallocated_Click);
//
// btnSettings
//
this.btnSettings.Location = new System.Drawing.Point(6, 19);
this.btnSettings.Name = "btnSettings";
this.btnSettings.Size = new System.Drawing.Size(111, 35);
this.btnSettings.TabIndex = 12;
this.btnSettings.Text = "Advanced Settings";
this.btnSettings.UseVisualStyleBackColor = true;
this.btnSettings.Click += new System.EventHandler(this.btnSettings_Click);
//
// btnReset
//
this.btnReset.Location = new System.Drawing.Point(414, 19);
this.btnReset.Name = "btnReset";
this.btnReset.Size = new System.Drawing.Size(111, 35);
this.btnReset.TabIndex = 11;
this.btnReset.Text = "Reset Day";
this.btnReset.UseVisualStyleBackColor = true;
this.btnReset.Click += new System.EventHandler(this.btnReset_Click);
//
// btnSave
//
this.btnSave.Location = new System.Drawing.Point(531, 19);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(111, 35);
this.btnSave.TabIndex = 10;
this.btnSave.Text = "SAVE";
this.btnSave.UseVisualStyleBackColor = true;
this.btnSave.Click += new System.EventHandler(this.btnSave_Click);
//
// lDate
//
this.lDate.AutoSize = true;
this.lDate.Location = new System.Drawing.Point(297, 19);
this.lDate.Name = "lDate";
this.lDate.Size = new System.Drawing.Size(64, 13);
this.lDate.TabIndex = 9;
this.lDate.Text = "##DATE##";
//
// lDay
//
this.lDay.AutoSize = true;
this.lDay.Location = new System.Drawing.Point(308, 41);
this.lDay.Name = "lDay";
this.lDay.Size = new System.Drawing.Size(26, 13);
this.lDay.TabIndex = 8;
this.lDay.Text = "Day";
//
// bDayBack
//
this.bDayBack.Location = new System.Drawing.Point(263, 35);
this.bDayBack.Name = "bDayBack";
this.bDayBack.Size = new System.Drawing.Size(39, 23);
this.bDayBack.TabIndex = 1;
this.bDayBack.Text = "<<";
this.bDayBack.UseVisualStyleBackColor = true;
this.bDayBack.Click += new System.EventHandler(this.bDayBack_Click);
//
// bDayForward
//
this.bDayForward.Location = new System.Drawing.Point(340, 36);
this.bDayForward.Name = "bDayForward";
this.bDayForward.Size = new System.Drawing.Size(39, 23);
this.bDayForward.TabIndex = 0;
this.bDayForward.Text = ">>";
this.bDayForward.UseVisualStyleBackColor = true;
this.bDayForward.Click += new System.EventHandler(this.bDayForward_Click);
//
// gbPM
//
this.gbPM.Controls.Add(this.tbPMUnallocatedAdj);
this.gbPM.Controls.Add(this.lblPMCurrentUnallocated);
this.gbPM.Controls.Add(this.tbPMUnallocatedSugg);
this.gbPM.Controls.Add(this.lblPMUnallocated);
this.gbPM.Controls.Add(this.lPMAdj);
this.gbPM.Controls.Add(this.lPMSugg);
this.gbPM.Controls.Add(this.lPMID);
this.gbPM.Controls.Add(this.lPMName);
this.gbPM.Location = new System.Drawing.Point(342, 27);
this.gbPM.Name = "gbPM";
this.gbPM.Size = new System.Drawing.Size(318, 430);
this.gbPM.TabIndex = 4;
this.gbPM.TabStop = false;
this.gbPM.Text = "PM Declarations";
//
// tbPMUnallocatedAdj
//
this.tbPMUnallocatedAdj.Location = new System.Drawing.Point(277, 404);
this.tbPMUnallocatedAdj.Name = "tbPMUnallocatedAdj";
this.tbPMUnallocatedAdj.ReadOnly = true;
this.tbPMUnallocatedAdj.Size = new System.Drawing.Size(35, 20);
this.tbPMUnallocatedAdj.TabIndex = 18;
//
// lblPMCurrentUnallocated
//
this.lblPMCurrentUnallocated.AutoSize = true;
this.lblPMCurrentUnallocated.Location = new System.Drawing.Point(167, 407);
this.lblPMCurrentUnallocated.Name = "lblPMCurrentUnallocated";
this.lblPMCurrentUnallocated.Size = new System.Drawing.Size(104, 13);
this.lblPMCurrentUnallocated.TabIndex = 17;
this.lblPMCurrentUnallocated.Text = "Current Unallocated:";
//
// tbPMUnallocatedSugg
//
this.tbPMUnallocatedSugg.Location = new System.Drawing.Point(115, 404);
this.tbPMUnallocatedSugg.Name = "tbPMUnallocatedSugg";
this.tbPMUnallocatedSugg.ReadOnly = true;
this.tbPMUnallocatedSugg.Size = new System.Drawing.Size(35, 20);
this.tbPMUnallocatedSugg.TabIndex = 15;
//
// lblPMUnallocated
//
this.lblPMUnallocated.AutoSize = true;
this.lblPMUnallocated.Location = new System.Drawing.Point(6, 407);
this.lblPMUnallocated.Name = "lblPMUnallocated";
this.lblPMUnallocated.Size = new System.Drawing.Size(106, 13);
this.lblPMUnallocated.TabIndex = 14;
this.lblPMUnallocated.Text = "Starting Unallocated:";
//
// lPMAdj
//
this.lPMAdj.AutoSize = true;
this.lPMAdj.Location = new System.Drawing.Point(276, 16);
this.lPMAdj.Name = "lPMAdj";
this.lPMAdj.Size = new System.Drawing.Size(22, 13);
this.lPMAdj.TabIndex = 13;
this.lPMAdj.Text = "Adj";
//
// lPMSugg
//
this.lPMSugg.AutoSize = true;
this.lPMSugg.Location = new System.Drawing.Point(216, 16);
this.lPMSugg.Name = "lPMSugg";
this.lPMSugg.Size = new System.Drawing.Size(32, 13);
this.lPMSugg.TabIndex = 12;
this.lPMSugg.Text = "Sugg";
//
// lPMID
//
this.lPMID.AutoSize = true;
this.lPMID.Location = new System.Drawing.Point(169, 16);
this.lPMID.Name = "lPMID";
this.lPMID.Size = new System.Drawing.Size(18, 13);
this.lPMID.TabIndex = 11;
this.lPMID.Text = "ID";
//
// lPMName
//
this.lPMName.AutoSize = true;
this.lPMName.Location = new System.Drawing.Point(69, 16);
this.lPMName.Name = "lPMName";
this.lPMName.Size = new System.Drawing.Size(35, 13);
this.lPMName.TabIndex = 10;
this.lPMName.Text = "Name";
//
// msMenu
//
this.msMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mFile,
this.mAbout});
this.msMenu.Location = new System.Drawing.Point(0, 0);
this.msMenu.Name = "msMenu";
this.msMenu.Size = new System.Drawing.Size(672, 24);
this.msMenu.TabIndex = 5;
this.msMenu.Text = "MenuStrip";
//
// mFile
//
this.mFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miJump,
this.miPrint,
this.miExit});
this.mFile.Name = "mFile";
this.mFile.Size = new System.Drawing.Size(37, 20);
this.mFile.Text = "File";
//
// miJump
//
this.miJump.Name = "miJump";
this.miJump.Size = new System.Drawing.Size(148, 22);
this.miJump.Text = "Jump to day...";
//
// miPrint
//
this.miPrint.Name = "miPrint";
this.miPrint.Size = new System.Drawing.Size(148, 22);
this.miPrint.Text = "Print Today";
this.miPrint.Click += new System.EventHandler(this.miPrint_Click);
//
// miExit
//
this.miExit.Name = "miExit";
this.miExit.Size = new System.Drawing.Size(148, 22);
this.miExit.Text = "Exit";
this.miExit.Click += new System.EventHandler(this.miExit_Click);
//
// mAbout
//
this.mAbout.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.miHelp,
this.miAbout});
this.mAbout.Name = "mAbout";
this.mAbout.Size = new System.Drawing.Size(52, 20);
this.mAbout.Text = "About";
//
// miHelp
//
this.miHelp.Name = "miHelp";
this.miHelp.Size = new System.Drawing.Size(107, 22);
this.miHelp.Text = "Help";
this.miHelp.Click += new System.EventHandler(this.miHelp_Click);
//
// miAbout
//
this.miAbout.Name = "miAbout";
this.miAbout.Size = new System.Drawing.Size(107, 22);
this.miAbout.Text = "About";
this.miAbout.Click += new System.EventHandler(this.miAbout_Click);
//
// tTimer
//
this.tTimer.Tick += new System.EventHandler(this.tTimer_Tick);
//
// gbTotals
//
this.gbTotals.Controls.Add(this.lTotalSugg);
this.gbTotals.Controls.Add(this.lTotalAdj);
this.gbTotals.Controls.Add(this.lLabTotSug);
this.gbTotals.Controls.Add(this.lTotalAMSugg);
this.gbTotals.Controls.Add(this.lTotalAMAdj);
this.gbTotals.Controls.Add(this.lLabTotAMSugg);
this.gbTotals.Controls.Add(this.lTotalPMSugg);
this.gbTotals.Controls.Add(this.lTotalPMAdj);
this.gbTotals.Controls.Add(this.lLabTotPMSugg);
this.gbTotals.Location = new System.Drawing.Point(12, 463);
this.gbTotals.Name = "gbTotals";
this.gbTotals.Size = new System.Drawing.Size(648, 49);
this.gbTotals.TabIndex = 6;
this.gbTotals.TabStop = false;
this.gbTotals.Text = "Totals";
//
// lTotalSugg
//
this.lTotalSugg.AutoSize = true;
this.lTotalSugg.Location = new System.Drawing.Point(285, 29);
this.lTotalSugg.Name = "lTotalSugg";
this.lTotalSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalSugg.TabIndex = 8;
this.lTotalSugg.Text = "##";
//
// lTotalAdj
//
this.lTotalAdj.AutoSize = true;
this.lTotalAdj.Location = new System.Drawing.Point(348, 29);
this.lTotalAdj.Name = "lTotalAdj";
this.lTotalAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalAdj.TabIndex = 7;
this.lTotalAdj.Text = "##";
//
// lLabTotSug
//
this.lLabTotSug.AutoSize = true;
this.lLabTotSug.Location = new System.Drawing.Point(285, 16);
this.lLabTotSug.Name = "lLabTotSug";
this.lLabTotSug.Size = new System.Drawing.Size(79, 13);
this.lLabTotSug.TabIndex = 6;
this.lLabTotSug.Text = "Total Sugg/Adj";
//
// lTotalAMSugg
//
this.lTotalAMSugg.AutoSize = true;
this.lTotalAMSugg.Location = new System.Drawing.Point(32, 29);
this.lTotalAMSugg.Name = "lTotalAMSugg";
this.lTotalAMSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalAMSugg.TabIndex = 5;
this.lTotalAMSugg.Text = "##";
//
// lTotalAMAdj
//
this.lTotalAMAdj.AutoSize = true;
this.lTotalAMAdj.Location = new System.Drawing.Point(83, 29);
this.lTotalAMAdj.Name = "lTotalAMAdj";
this.lTotalAMAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalAMAdj.TabIndex = 4;
this.lTotalAMAdj.Text = "##";
//
// lLabTotAMSugg
//
this.lLabTotAMSugg.AutoSize = true;
this.lLabTotAMSugg.Location = new System.Drawing.Point(19, 16);
this.lLabTotAMSugg.Name = "lLabTotAMSugg";
this.lLabTotAMSugg.Size = new System.Drawing.Size(98, 13);
this.lLabTotAMSugg.TabIndex = 3;
this.lLabTotAMSugg.Text = "Total AM Sugg/Adj";
//
// lTotalPMSugg
//
this.lTotalPMSugg.AutoSize = true;
this.lTotalPMSugg.Location = new System.Drawing.Point(545, 29);
this.lTotalPMSugg.Name = "lTotalPMSugg";
this.lTotalPMSugg.Size = new System.Drawing.Size(21, 13);
this.lTotalPMSugg.TabIndex = 2;
this.lTotalPMSugg.Text = "##";
//
// lTotalPMAdj
//
this.lTotalPMAdj.AutoSize = true;
this.lTotalPMAdj.Location = new System.Drawing.Point(596, 29);
this.lTotalPMAdj.Name = "lTotalPMAdj";
this.lTotalPMAdj.Size = new System.Drawing.Size(21, 13);
this.lTotalPMAdj.TabIndex = 1;
this.lTotalPMAdj.Text = "##";
//
// lLabTotPMSugg
//
this.lLabTotPMSugg.AutoSize = true;
this.lLabTotPMSugg.Location = new System.Drawing.Point(530, 16);
this.lLabTotPMSugg.Name = "lLabTotPMSugg";
this.lLabTotPMSugg.Size = new System.Drawing.Size(98, 13);
this.lLabTotPMSugg.TabIndex = 0;
this.lLabTotPMSugg.Text = "Total PM Sugg/Adj";
//
// Tipshare
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(672, 592);
this.Controls.Add(this.gbTotals);
this.Controls.Add(this.gbPM);
this.Controls.Add(this.gbControls);
this.Controls.Add(this.gbAM);
this.Controls.Add(this.msMenu);
this.MainMenuStrip = this.msMenu;
this.Name = "Tipshare";
this.Text = "Tipshare##VERSION## - ##STORENAME##";
this.Load += new System.EventHandler(this.Tipshare_Load);
this.gbAM.ResumeLayout(false);
this.gbAM.PerformLayout();
this.gbControls.ResumeLayout(false);
this.gbControls.PerformLayout();
this.gbPM.ResumeLayout(false);
this.gbPM.PerformLayout();
this.msMenu.ResumeLayout(false);
this.msMenu.PerformLayout();
this.gbTotals.ResumeLayout(false);
this.gbTotals.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.GroupBox gbAM;
private System.Windows.Forms.GroupBox gbControls;
private System.Windows.Forms.GroupBox gbPM;
private System.Windows.Forms.Button bDayBack;
private System.Windows.Forms.Button bDayForward;
private System.Windows.Forms.Label lAMName;
private System.Windows.Forms.Label lAMAdj;
private System.Windows.Forms.Label lAMSugg;
private System.Windows.Forms.Label lAMID;
private System.Windows.Forms.Label lDate;
private System.Windows.Forms.Label lDay;
private System.Windows.Forms.Button btnSave;
private System.Windows.Forms.Button btnDistributeUnallocated;
private System.Windows.Forms.Button btnSettings;
private System.Windows.Forms.Button btnReset;
private System.Windows.Forms.Label lPMAdj;
private System.Windows.Forms.Label lPMSugg;
private System.Windows.Forms.Label lPMID;
private System.Windows.Forms.Label lPMName;
private System.Windows.Forms.MenuStrip msMenu;
private System.Windows.Forms.ToolStripMenuItem mFile;
private System.Windows.Forms.ToolStripMenuItem miJump;
private System.Windows.Forms.ToolStripMenuItem miPrint;
private System.Windows.Forms.ToolStripMenuItem miExit;
private System.Windows.Forms.ToolStripMenuItem mAbout;
private System.Windows.Forms.ToolStripMenuItem miHelp;
private System.Windows.Forms.ToolStripMenuItem miAbout;
private System.Windows.Forms.Timer tTimer;
private System.Windows.Forms.GroupBox gbTotals;
private System.Windows.Forms.Label lTotalPMAdj;
private System.Windows.Forms.Label lLabTotPMSugg;
private System.Windows.Forms.Label lTotalAMSugg;
private System.Windows.Forms.Label lTotalAMAdj;
private System.Windows.Forms.Label lLabTotAMSugg;
private System.Windows.Forms.Label lTotalPMSugg;
private System.Windows.Forms.Label lTotalSugg;
private System.Windows.Forms.Label lTotalAdj;
private System.Windows.Forms.Label lLabTotSug;
private System.Windows.Forms.TextBox tbAMUnallocatedSugg;
private System.Windows.Forms.Label lblAMUnallocated;
private System.Windows.Forms.TextBox tbPMUnallocatedSugg;
private System.Windows.Forms.Label lblPMUnallocated;
private System.Windows.Forms.TextBox tbAMUnallocatedAdj;
private System.Windows.Forms.Label lblAMCurrentUnallocated;
private System.Windows.Forms.TextBox tbPMUnallocatedAdj;
private System.Windows.Forms.Label lblPMCurrentUnallocated;
}
}
| Java |
using SFML.Graphics;
using SFML.Window;
namespace LudumDare.ParticleSystem
{
public class Emitter
{
public Vector2f Position;
public int ParticlesSpawnRate;
public float Spread;
public Color Color;
}
} | Java |
/*
SDL - Simple DirectMedia Layer
Copyright (C) 1997-2012 Sam Lantinga
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
Sam Lantinga
slouken@libsdl.org
*/
#include "SDL_config.h"
#include "SDL_mouse.h"
#include "../../events/SDL_events_c.h"
#include "SDL_vglvideo.h"
#include "SDL_vglmouse_c.h"
struct WMcursor {
int unused;
};
void VGL_FreeWMCursor(_THIS, WMcursor *cursor)
{
return;
}
WMcursor *VGL_CreateWMCursor(_THIS,
Uint8 *data, Uint8 *mask, int w, int h, int hot_x, int hot_y)
{
return(NULL);
}
int VGL_ShowWMCursor(_THIS, WMcursor *cursor)
{
return(0);
}
void VGL_WarpWMCursor(_THIS, Uint16 x, Uint16 y)
{
SDL_PrivateMouseMotion(0, 0, x, y);
}
| Java |
/*
Copyright (c) 2006 Paolo Capriotti <p.capriotti@gmail.com>
(c) 2006 Maurizio Monge <maurizio.monge@kdemail.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.
*/
#include <cmath>
#include <QDebug>
#include <QString>
#include "common.h"
#include "point.h"
Point::Point(int x, int y)
: x(x), y(y) {
}
Point::Point(const QPoint& p)
: x(p.x()), y(p.y()) {
}
Point::Point() {
}
Point::Point(const QString& str, int ysize) {
x = y = -1;
int length = str.length();
if(length == 0)
return;
if(str[0].isLetter()) {
char c = str[0].toAscii();
if(c >= 'a' && c <= 'z')
x = c-'a';
else if(c >= 'A' && c <= 'Z')
x = c-'A';
if(length>1)
y = ysize - str.mid(1).toInt();
}
else
y = ysize - str.toInt();
}
QString Point::row(int ysize) const {
if (y != -1)
return QString::number(ysize - y);
else
return QString();
}
QString Point::numcol(int xsize) const {
if (x != -1)
return QString::number(xsize - x);
else
return QString();
}
QString Point::col() const {
if (x != -1) {
if(x >= 26)
return QChar(static_cast<char>(x - 26 + 'A'));
else
return QChar(static_cast<char>(x + 'a'));
}
else
return QString();
}
QString Point::alpharow() const {
if (y != -1) {
if(y >= 26)
return QChar(static_cast<char>(y - 26 + 'A'));
else
return QChar(static_cast<char>(y + 'a'));
}
else
return QString();
}
QString Point::toString(int ysize) const {
return col() + row(ysize);
}
Point Point::operator+(const Point& other) const {
return Point(x + other.x, y + other.y);
}
Point Point::operator+=(const Point& other) {
return *this = *this + other;
}
Point Point::operator-() const {
return Point(-x, -y);
}
Point Point::operator-(const Point& other) const {
return Point(x - other.x, y - other.y);
}
Point Point::operator*(int n) const {
return Point(x * n, y * n);
}
Point Point::operator/(int n) const {
return Point(x / n, y / n);
}
Point Point::div(int n) const {
return Point(x >= 0 ? x / n : x / n - 1,
y >= 0 ? y / n : y / n - 1);
}
bool Point::operator==(const Point& other) const {
return x == other.x && y == other.y;
}
bool Point::operator!=(const Point& other) const {
return !(*this == other);
}
bool Point::operator<(const Point& other) const {
return y < other.y || (y == other.y && x < other.x);
}
bool Point::operator<=(const Point& other) const {
return y <= other.y || (y == other.y && x <= other.x);
}
bool Point::resembles(const Point& other) const {
return (other.x == -1 || x == other.x) &&
(other.y == -1 || y == other.y);
}
Point::operator QPoint() const {
return QPoint(x,y);
}
Point Point::normalizeInfinity() const {
return Point(
normalizeInfinityHelper(x),
normalizeInfinityHelper(y)
);
}
double Point::norm() const {
return sqrt((double)(x*x + y*y));
}
int Point::normalizeInfinityHelper(int n) const {
if (n == 0)
return 0;
else
return n > 0 ? 1 : -1;
}
QDebug operator<<(QDebug dbg, const Point& p) {
dbg << "(" << (p.x == -1 ? QString("?") : QString::number(p.x))
<< ", " << (p.y == -1 ? QString("?") : QString::number(p.y)) << ")";
return dbg;
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_04) on Thu May 15 10:36:11 IDT 2014 -->
<title>Painter (Codename One API)</title>
<meta name="date" content="2014-05-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="Painter (Codename One 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 class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../com/codename1/ui/MenuBar.html" title="class in com.codename1.ui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../com/codename1/ui/PeerComponent.html" title="class in com.codename1.ui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/codename1/ui/Painter.html" target="_top">Frames</a></li>
<li><a href="Painter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </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">com.codename1.ui</div>
<h2 title="Interface Painter" class="title">Interface Painter</h2>
</div>
<div class="contentContainer">
<div class="description">
<ul class="blockList">
<li class="blockList">
<dl>
<dt>All Known Implementing Classes:</dt>
<dd><a href="../../../com/codename1/ui/painter/BackgroundPainter.html" title="class in com.codename1.ui.painter">BackgroundPainter</a>, <a href="../../../com/codename1/ui/util/GlassTutorial.html" title="class in com.codename1.ui.util">GlassTutorial</a>, <a href="../../../com/codename1/ui/painter/PainterChain.html" title="class in com.codename1.ui.painter">PainterChain</a>, <a href="../../../com/codename1/ui/animations/Timeline.html" title="class in com.codename1.ui.animations">Timeline</a></dd>
</dl>
<hr>
<br>
<pre>public interface <span class="strong">Painter</span></pre>
<div class="block">Painter can be used to draw on components backgrounds.
The use of such painter allows reuse of a background painters for various
components.
Note in order to view the painter drawing, component need to have some level
of transparency.</div>
</li>
</ul>
</div>
<div class="summary">
<ul class="blockList">
<li class="blockList">
<!-- ========== METHOD SUMMARY =========== -->
<ul class="blockList">
<li class="blockList"><a name="method_summary">
<!-- -->
</a>
<h3>Method Summary</h3>
<table class="overviewSummary" border="0" cellpadding="3" cellspacing="0" summary="Method Summary table, listing methods, and an explanation">
<caption><span>Methods</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>
<tr class="altColor">
<td class="colFirst"><code>void</code></td>
<td class="colLast"><code><strong><a href="../../../com/codename1/ui/Painter.html#paint(com.codename1.ui.Graphics, com.codename1.ui.geom.Rectangle)">paint</a></strong>(<a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui">Graphics</a> g,
<a href="../../../com/codename1/ui/geom/Rectangle.html" title="class in com.codename1.ui.geom">Rectangle</a> rect)</code>
<div class="block">Draws inside the given rectangle clipping area.</div>
</td>
</tr>
</table>
</li>
</ul>
</li>
</ul>
</div>
<div class="details">
<ul class="blockList">
<li class="blockList">
<!-- ============ METHOD DETAIL ========== -->
<ul class="blockList">
<li class="blockList"><a name="method_detail">
<!-- -->
</a>
<h3>Method Detail</h3>
<a name="paint(com.codename1.ui.Graphics, com.codename1.ui.geom.Rectangle)">
<!-- -->
</a>
<ul class="blockListLast">
<li class="blockList">
<h4>paint</h4>
<pre>void paint(<a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui">Graphics</a> g,
<a href="../../../com/codename1/ui/geom/Rectangle.html" title="class in com.codename1.ui.geom">Rectangle</a> rect)</pre>
<div class="block">Draws inside the given rectangle clipping area.</div>
<dl><dt><span class="strong">Parameters:</span></dt><dd><code>g</code> - the <a href="../../../com/codename1/ui/Graphics.html" title="class in com.codename1.ui"><code>Graphics</code></a> object</dd><dd><code>rect</code> - the given rectangle cliping area</dd></dl>
</li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
</div>
<!-- ========= END OF CLASS DATA ========= -->
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../overview-summary.html">Overview</a></li>
<li><a href="package-summary.html">Package</a></li>
<li class="navBarCell1Rev">Class</li>
<li><a href="package-tree.html">Tree</a></li>
<li><a href="../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../index-all.html">Index</a></li>
<li><a href="../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li><a href="../../../com/codename1/ui/MenuBar.html" title="class in com.codename1.ui"><span class="strong">Prev Class</span></a></li>
<li><a href="../../../com/codename1/ui/PeerComponent.html" title="class in com.codename1.ui"><span class="strong">Next Class</span></a></li>
</ul>
<ul class="navList">
<li><a href="../../../index.html?com/codename1/ui/Painter.html" target="_top">Frames</a></li>
<li><a href="Painter.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<div>
<ul class="subNavList">
<li>Summary: </li>
<li>Nested | </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_summary">Method</a></li>
</ul>
<ul class="subNavList">
<li>Detail: </li>
<li>Field | </li>
<li>Constr | </li>
<li><a href="#method_detail">Method</a></li>
</ul>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Java |
# class.upload by verot.net
## contributor github.com/paulds
#### v0.31 Download from verot.net/php_class_upload_download.htm
This version is not PHP 5.3 compatible | Java |
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Felix Natter in 2013.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.core.resources.components;
import javax.swing.JButton;
import com.jgoodies.forms.builder.DefaultFormBuilder;
public class ButtonProperty extends PropertyBean implements IPropertyControl {
final JButton mButton;
/**
*/
public ButtonProperty(final String name, JButton button) {
super(name);
mButton = button;
}
@Override
public String getValue() {
return "";
}
public void appendToForm(final DefaultFormBuilder builder) {
appendToForm(builder, mButton);
}
public void setEnabled(final boolean pEnabled) {
mButton.setEnabled(pEnabled);
super.setEnabled(pEnabled);
}
@Override
public void setValue(final String value) {
}
public void setToolTipText(String text) {
mButton.setToolTipText(text);
}
}
| Java |
/*
* @author Philip Stutz
* @author Francisco de Freitas
*
* Copyright 2011 University of Zurich
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package com.signalcollect.configuration
import com.signalcollect.interfaces._
import java.util.HashMap
import com.signalcollect._
import com.signalcollect.logging.DefaultLogger
import akka.actor.ActorRef
import com.signalcollect.nodeprovisioning.NodeProvisioner
import com.signalcollect.nodeprovisioning.local.LocalNodeProvisioner
/**
* All the graph configuration parameters with their defaults.
*/
case class GraphConfiguration(
maxInboxSize: Option[Long] = Some(Runtime.getRuntime.availableProcessors * 5000), //None
loggingLevel: Int = LoggingLevel.Warning,
logger: LogMessage => Unit = DefaultLogger.log,
workerFactory: WorkerFactory = factory.worker.Akka,
messageBusFactory: MessageBusFactory = factory.messagebus.SharedMemory,
storageFactory: StorageFactory = factory.storage.InMemory,
statusUpdateIntervalInMillis: Option[Long] = Some(500l),
akkaDispatcher: AkkaDispatcher = Pinned,
nodeProvisioner: NodeProvisioner = new LocalNodeProvisioner)
object LoggingLevel {
val Debug = 0
val Config = 100
val Info = 200
val Warning = 300
val Severe = 400
}
sealed trait AkkaDispatcher
case object EventBased extends AkkaDispatcher
case object Pinned extends AkkaDispatcher
| Java |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2010 Lennart Poettering
systemd is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.
systemd is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "sd-id128.h"
#include "sd-messages.h"
#include "alloc-util.h"
#include "bus-common-errors.h"
#include "bus-util.h"
#include "cgroup-util.h"
#include "dbus-unit.h"
#include "dbus.h"
#include "dropin.h"
#include "escape.h"
#include "execute.h"
#include "fileio-label.h"
#include "formats-util.h"
#include "load-dropin.h"
#include "load-fragment.h"
#include "log.h"
#include "macro.h"
#include "missing.h"
#include "mkdir.h"
#include "parse-util.h"
#include "path-util.h"
#include "process-util.h"
#include "set.h"
#include "special.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
#include "unit-name.h"
#include "unit.h"
#include "user-util.h"
#include "virt.h"
const UnitVTable * const unit_vtable[_UNIT_TYPE_MAX] = {
[UNIT_SERVICE] = &service_vtable,
[UNIT_SOCKET] = &socket_vtable,
[UNIT_BUSNAME] = &busname_vtable,
[UNIT_TARGET] = &target_vtable,
[UNIT_DEVICE] = &device_vtable,
[UNIT_MOUNT] = &mount_vtable,
[UNIT_AUTOMOUNT] = &automount_vtable,
[UNIT_SWAP] = &swap_vtable,
[UNIT_TIMER] = &timer_vtable,
[UNIT_PATH] = &path_vtable,
[UNIT_SLICE] = &slice_vtable,
[UNIT_SCOPE] = &scope_vtable
};
static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency);
Unit *unit_new(Manager *m, size_t size) {
Unit *u;
assert(m);
assert(size >= sizeof(Unit));
u = malloc0(size);
if (!u)
return NULL;
u->names = set_new(&string_hash_ops);
if (!u->names) {
free(u);
return NULL;
}
u->manager = m;
u->type = _UNIT_TYPE_INVALID;
u->default_dependencies = true;
u->unit_file_state = _UNIT_FILE_STATE_INVALID;
u->unit_file_preset = -1;
u->on_failure_job_mode = JOB_REPLACE;
u->cgroup_inotify_wd = -1;
RATELIMIT_INIT(u->auto_stop_ratelimit, 10 * USEC_PER_SEC, 16);
return u;
}
bool unit_has_name(Unit *u, const char *name) {
assert(u);
assert(name);
return !!set_get(u->names, (char*) name);
}
static void unit_init(Unit *u) {
CGroupContext *cc;
ExecContext *ec;
KillContext *kc;
assert(u);
assert(u->manager);
assert(u->type >= 0);
cc = unit_get_cgroup_context(u);
if (cc) {
cgroup_context_init(cc);
/* Copy in the manager defaults into the cgroup
* context, _before_ the rest of the settings have
* been initialized */
cc->cpu_accounting = u->manager->default_cpu_accounting;
cc->blockio_accounting = u->manager->default_blockio_accounting;
cc->memory_accounting = u->manager->default_memory_accounting;
cc->tasks_accounting = u->manager->default_tasks_accounting;
}
ec = unit_get_exec_context(u);
if (ec)
exec_context_init(ec);
kc = unit_get_kill_context(u);
if (kc)
kill_context_init(kc);
if (UNIT_VTABLE(u)->init)
UNIT_VTABLE(u)->init(u);
}
int unit_add_name(Unit *u, const char *text) {
_cleanup_free_ char *s = NULL, *i = NULL;
UnitType t;
int r;
assert(u);
assert(text);
if (unit_name_is_valid(text, UNIT_NAME_TEMPLATE)) {
if (!u->instance)
return -EINVAL;
r = unit_name_replace_instance(text, u->instance, &s);
if (r < 0)
return r;
} else {
s = strdup(text);
if (!s)
return -ENOMEM;
}
if (set_contains(u->names, s))
return 0;
if (hashmap_contains(u->manager->units, s))
return -EEXIST;
if (!unit_name_is_valid(s, UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE))
return -EINVAL;
t = unit_name_to_type(s);
if (t < 0)
return -EINVAL;
if (u->type != _UNIT_TYPE_INVALID && t != u->type)
return -EINVAL;
r = unit_name_to_instance(s, &i);
if (r < 0)
return r;
if (i && unit_vtable[t]->no_instances)
return -EINVAL;
/* Ensure that this unit is either instanced or not instanced,
* but not both. Note that we do allow names with different
* instance names however! */
if (u->type != _UNIT_TYPE_INVALID && !u->instance != !i)
return -EINVAL;
if (unit_vtable[t]->no_alias && !set_isempty(u->names))
return -EEXIST;
if (hashmap_size(u->manager->units) >= MANAGER_MAX_NAMES)
return -E2BIG;
r = set_put(u->names, s);
if (r < 0)
return r;
assert(r > 0);
r = hashmap_put(u->manager->units, s, u);
if (r < 0) {
(void) set_remove(u->names, s);
return r;
}
if (u->type == _UNIT_TYPE_INVALID) {
u->type = t;
u->id = s;
u->instance = i;
LIST_PREPEND(units_by_type, u->manager->units_by_type[t], u);
unit_init(u);
i = NULL;
}
s = NULL;
unit_add_to_dbus_queue(u);
return 0;
}
int unit_choose_id(Unit *u, const char *name) {
_cleanup_free_ char *t = NULL;
char *s, *i;
int r;
assert(u);
assert(name);
if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
if (!u->instance)
return -EINVAL;
r = unit_name_replace_instance(name, u->instance, &t);
if (r < 0)
return r;
name = t;
}
/* Selects one of the names of this unit as the id */
s = set_get(u->names, (char*) name);
if (!s)
return -ENOENT;
/* Determine the new instance from the new id */
r = unit_name_to_instance(s, &i);
if (r < 0)
return r;
u->id = s;
free(u->instance);
u->instance = i;
unit_add_to_dbus_queue(u);
return 0;
}
int unit_set_description(Unit *u, const char *description) {
char *s;
assert(u);
if (isempty(description))
s = NULL;
else {
s = strdup(description);
if (!s)
return -ENOMEM;
}
free(u->description);
u->description = s;
unit_add_to_dbus_queue(u);
return 0;
}
bool unit_check_gc(Unit *u) {
UnitActiveState state;
assert(u);
if (u->job)
return true;
if (u->nop_job)
return true;
state = unit_active_state(u);
/* If the unit is inactive and failed and no job is queued for
* it, then release its runtime resources */
if (UNIT_IS_INACTIVE_OR_FAILED(state) &&
UNIT_VTABLE(u)->release_resources)
UNIT_VTABLE(u)->release_resources(u);
/* But we keep the unit object around for longer when it is
* referenced or configured to not be gc'ed */
if (state != UNIT_INACTIVE)
return true;
if (UNIT_VTABLE(u)->no_gc)
return true;
if (u->no_gc)
return true;
if (u->refs)
return true;
if (UNIT_VTABLE(u)->check_gc)
if (UNIT_VTABLE(u)->check_gc(u))
return true;
return false;
}
void unit_add_to_load_queue(Unit *u) {
assert(u);
assert(u->type != _UNIT_TYPE_INVALID);
if (u->load_state != UNIT_STUB || u->in_load_queue)
return;
LIST_PREPEND(load_queue, u->manager->load_queue, u);
u->in_load_queue = true;
}
void unit_add_to_cleanup_queue(Unit *u) {
assert(u);
if (u->in_cleanup_queue)
return;
LIST_PREPEND(cleanup_queue, u->manager->cleanup_queue, u);
u->in_cleanup_queue = true;
}
void unit_add_to_gc_queue(Unit *u) {
assert(u);
if (u->in_gc_queue || u->in_cleanup_queue)
return;
if (unit_check_gc(u))
return;
LIST_PREPEND(gc_queue, u->manager->gc_queue, u);
u->in_gc_queue = true;
u->manager->n_in_gc_queue ++;
}
void unit_add_to_dbus_queue(Unit *u) {
assert(u);
assert(u->type != _UNIT_TYPE_INVALID);
if (u->load_state == UNIT_STUB || u->in_dbus_queue)
return;
/* Shortcut things if nobody cares */
if (sd_bus_track_count(u->manager->subscribed) <= 0 &&
set_isempty(u->manager->private_buses)) {
u->sent_dbus_new_signal = true;
return;
}
LIST_PREPEND(dbus_queue, u->manager->dbus_unit_queue, u);
u->in_dbus_queue = true;
}
static void bidi_set_free(Unit *u, Set *s) {
Iterator i;
Unit *other;
assert(u);
/* Frees the set and makes sure we are dropped from the
* inverse pointers */
SET_FOREACH(other, s, i) {
UnitDependency d;
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
set_remove(other->dependencies[d], u);
unit_add_to_gc_queue(other);
}
set_free(s);
}
static void unit_remove_transient(Unit *u) {
char **i;
assert(u);
if (!u->transient)
return;
if (u->fragment_path)
(void) unlink(u->fragment_path);
STRV_FOREACH(i, u->dropin_paths) {
_cleanup_free_ char *p = NULL;
(void) unlink(*i);
p = dirname_malloc(*i);
if (p)
(void) rmdir(p);
}
}
static void unit_free_requires_mounts_for(Unit *u) {
char **j;
STRV_FOREACH(j, u->requires_mounts_for) {
char s[strlen(*j) + 1];
PATH_FOREACH_PREFIX_MORE(s, *j) {
char *y;
Set *x;
x = hashmap_get2(u->manager->units_requiring_mounts_for, s, (void**) &y);
if (!x)
continue;
set_remove(x, u);
if (set_isempty(x)) {
hashmap_remove(u->manager->units_requiring_mounts_for, y);
free(y);
set_free(x);
}
}
}
u->requires_mounts_for = strv_free(u->requires_mounts_for);
}
static void unit_done(Unit *u) {
ExecContext *ec;
CGroupContext *cc;
int r;
assert(u);
if (u->type < 0)
return;
if (UNIT_VTABLE(u)->done)
UNIT_VTABLE(u)->done(u);
ec = unit_get_exec_context(u);
if (ec)
exec_context_done(ec);
cc = unit_get_cgroup_context(u);
if (cc)
cgroup_context_done(cc);
r = unit_remove_from_netclass_cgroup(u);
if (r < 0)
log_warning_errno(r, "Unable to remove unit from netclass group: %m");
}
void unit_free(Unit *u) {
UnitDependency d;
Iterator i;
char *t;
assert(u);
if (u->manager->n_reloading <= 0)
unit_remove_transient(u);
bus_unit_send_removed_signal(u);
unit_done(u);
sd_bus_slot_unref(u->match_bus_slot);
unit_free_requires_mounts_for(u);
SET_FOREACH(t, u->names, i)
hashmap_remove_value(u->manager->units, t, u);
if (u->job) {
Job *j = u->job;
job_uninstall(j);
job_free(j);
}
if (u->nop_job) {
Job *j = u->nop_job;
job_uninstall(j);
job_free(j);
}
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
bidi_set_free(u, u->dependencies[d]);
if (u->type != _UNIT_TYPE_INVALID)
LIST_REMOVE(units_by_type, u->manager->units_by_type[u->type], u);
if (u->in_load_queue)
LIST_REMOVE(load_queue, u->manager->load_queue, u);
if (u->in_dbus_queue)
LIST_REMOVE(dbus_queue, u->manager->dbus_unit_queue, u);
if (u->in_cleanup_queue)
LIST_REMOVE(cleanup_queue, u->manager->cleanup_queue, u);
if (u->in_gc_queue) {
LIST_REMOVE(gc_queue, u->manager->gc_queue, u);
u->manager->n_in_gc_queue--;
}
if (u->in_cgroup_queue)
LIST_REMOVE(cgroup_queue, u->manager->cgroup_queue, u);
unit_release_cgroup(u);
(void) manager_update_failed_units(u->manager, u, false);
set_remove(u->manager->startup_units, u);
free(u->description);
strv_free(u->documentation);
free(u->fragment_path);
free(u->source_path);
strv_free(u->dropin_paths);
free(u->instance);
free(u->job_timeout_reboot_arg);
set_free_free(u->names);
unit_unwatch_all_pids(u);
condition_free_list(u->conditions);
condition_free_list(u->asserts);
unit_ref_unset(&u->slice);
while (u->refs)
unit_ref_unset(u->refs);
free(u);
}
UnitActiveState unit_active_state(Unit *u) {
assert(u);
if (u->load_state == UNIT_MERGED)
return unit_active_state(unit_follow_merge(u));
/* After a reload it might happen that a unit is not correctly
* loaded but still has a process around. That's why we won't
* shortcut failed loading to UNIT_INACTIVE_FAILED. */
return UNIT_VTABLE(u)->active_state(u);
}
const char* unit_sub_state_to_string(Unit *u) {
assert(u);
return UNIT_VTABLE(u)->sub_state_to_string(u);
}
static int complete_move(Set **s, Set **other) {
int r;
assert(s);
assert(other);
if (!*other)
return 0;
if (*s) {
r = set_move(*s, *other);
if (r < 0)
return r;
} else {
*s = *other;
*other = NULL;
}
return 0;
}
static int merge_names(Unit *u, Unit *other) {
char *t;
Iterator i;
int r;
assert(u);
assert(other);
r = complete_move(&u->names, &other->names);
if (r < 0)
return r;
set_free_free(other->names);
other->names = NULL;
other->id = NULL;
SET_FOREACH(t, u->names, i)
assert_se(hashmap_replace(u->manager->units, t, u) == 0);
return 0;
}
static int reserve_dependencies(Unit *u, Unit *other, UnitDependency d) {
unsigned n_reserve;
assert(u);
assert(other);
assert(d < _UNIT_DEPENDENCY_MAX);
/*
* If u does not have this dependency set allocated, there is no need
* to reserve anything. In that case other's set will be transferred
* as a whole to u by complete_move().
*/
if (!u->dependencies[d])
return 0;
/* merge_dependencies() will skip a u-on-u dependency */
n_reserve = set_size(other->dependencies[d]) - !!set_get(other->dependencies[d], u);
return set_reserve(u->dependencies[d], n_reserve);
}
static void merge_dependencies(Unit *u, Unit *other, const char *other_id, UnitDependency d) {
Iterator i;
Unit *back;
int r;
assert(u);
assert(other);
assert(d < _UNIT_DEPENDENCY_MAX);
/* Fix backwards pointers */
SET_FOREACH(back, other->dependencies[d], i) {
UnitDependency k;
for (k = 0; k < _UNIT_DEPENDENCY_MAX; k++) {
/* Do not add dependencies between u and itself */
if (back == u) {
if (set_remove(back->dependencies[k], other))
maybe_warn_about_dependency(u, other_id, k);
} else {
r = set_remove_and_put(back->dependencies[k], other, u);
if (r == -EEXIST)
set_remove(back->dependencies[k], other);
else
assert(r >= 0 || r == -ENOENT);
}
}
}
/* Also do not move dependencies on u to itself */
back = set_remove(other->dependencies[d], u);
if (back)
maybe_warn_about_dependency(u, other_id, d);
/* The move cannot fail. The caller must have performed a reservation. */
assert_se(complete_move(&u->dependencies[d], &other->dependencies[d]) == 0);
other->dependencies[d] = set_free(other->dependencies[d]);
}
int unit_merge(Unit *u, Unit *other) {
UnitDependency d;
const char *other_id = NULL;
int r;
assert(u);
assert(other);
assert(u->manager == other->manager);
assert(u->type != _UNIT_TYPE_INVALID);
other = unit_follow_merge(other);
if (other == u)
return 0;
if (u->type != other->type)
return -EINVAL;
if (!u->instance != !other->instance)
return -EINVAL;
if (other->load_state != UNIT_STUB &&
other->load_state != UNIT_NOT_FOUND)
return -EEXIST;
if (other->job)
return -EEXIST;
if (other->nop_job)
return -EEXIST;
if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
return -EEXIST;
if (other->id)
other_id = strdupa(other->id);
/* Make reservations to ensure merge_dependencies() won't fail */
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
r = reserve_dependencies(u, other, d);
/*
* We don't rollback reservations if we fail. We don't have
* a way to undo reservations. A reservation is not a leak.
*/
if (r < 0)
return r;
}
/* Merge names */
r = merge_names(u, other);
if (r < 0)
return r;
/* Redirect all references */
while (other->refs)
unit_ref_set(other->refs, u);
/* Merge dependencies */
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++)
merge_dependencies(u, other, other_id, d);
other->load_state = UNIT_MERGED;
other->merged_into = u;
/* If there is still some data attached to the other node, we
* don't need it anymore, and can free it. */
if (other->load_state != UNIT_STUB)
if (UNIT_VTABLE(other)->done)
UNIT_VTABLE(other)->done(other);
unit_add_to_dbus_queue(u);
unit_add_to_cleanup_queue(other);
return 0;
}
int unit_merge_by_name(Unit *u, const char *name) {
Unit *other;
int r;
_cleanup_free_ char *s = NULL;
assert(u);
assert(name);
if (unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
if (!u->instance)
return -EINVAL;
r = unit_name_replace_instance(name, u->instance, &s);
if (r < 0)
return r;
name = s;
}
other = manager_get_unit(u->manager, name);
if (other)
return unit_merge(u, other);
return unit_add_name(u, name);
}
Unit* unit_follow_merge(Unit *u) {
assert(u);
while (u->load_state == UNIT_MERGED)
assert_se(u = u->merged_into);
return u;
}
int unit_add_exec_dependencies(Unit *u, ExecContext *c) {
int r;
assert(u);
assert(c);
if (c->working_directory) {
r = unit_require_mounts_for(u, c->working_directory);
if (r < 0)
return r;
}
if (c->root_directory) {
r = unit_require_mounts_for(u, c->root_directory);
if (r < 0)
return r;
}
if (u->manager->running_as != MANAGER_SYSTEM)
return 0;
if (c->private_tmp) {
r = unit_require_mounts_for(u, "/tmp");
if (r < 0)
return r;
r = unit_require_mounts_for(u, "/var/tmp");
if (r < 0)
return r;
}
if (c->std_output != EXEC_OUTPUT_KMSG &&
c->std_output != EXEC_OUTPUT_SYSLOG &&
c->std_output != EXEC_OUTPUT_JOURNAL &&
c->std_output != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
c->std_output != EXEC_OUTPUT_SYSLOG_AND_CONSOLE &&
c->std_output != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
c->std_error != EXEC_OUTPUT_KMSG &&
c->std_error != EXEC_OUTPUT_SYSLOG &&
c->std_error != EXEC_OUTPUT_JOURNAL &&
c->std_error != EXEC_OUTPUT_KMSG_AND_CONSOLE &&
c->std_error != EXEC_OUTPUT_JOURNAL_AND_CONSOLE &&
c->std_error != EXEC_OUTPUT_SYSLOG_AND_CONSOLE)
return 0;
/* If syslog or kernel logging is requested, make sure our own
* logging daemon is run first. */
r = unit_add_dependency_by_name(u, UNIT_AFTER, SPECIAL_JOURNALD_SOCKET, NULL, true);
if (r < 0)
return r;
return 0;
}
const char *unit_description(Unit *u) {
assert(u);
if (u->description)
return u->description;
return strna(u->id);
}
void unit_dump(Unit *u, FILE *f, const char *prefix) {
char *t, **j;
UnitDependency d;
Iterator i;
const char *prefix2;
char
timestamp1[FORMAT_TIMESTAMP_MAX],
timestamp2[FORMAT_TIMESTAMP_MAX],
timestamp3[FORMAT_TIMESTAMP_MAX],
timestamp4[FORMAT_TIMESTAMP_MAX],
timespan[FORMAT_TIMESPAN_MAX];
Unit *following;
_cleanup_set_free_ Set *following_set = NULL;
int r;
assert(u);
assert(u->type >= 0);
prefix = strempty(prefix);
prefix2 = strjoina(prefix, "\t");
fprintf(f,
"%s-> Unit %s:\n"
"%s\tDescription: %s\n"
"%s\tInstance: %s\n"
"%s\tUnit Load State: %s\n"
"%s\tUnit Active State: %s\n"
"%s\tInactive Exit Timestamp: %s\n"
"%s\tActive Enter Timestamp: %s\n"
"%s\tActive Exit Timestamp: %s\n"
"%s\tInactive Enter Timestamp: %s\n"
"%s\tGC Check Good: %s\n"
"%s\tNeed Daemon Reload: %s\n"
"%s\tTransient: %s\n"
"%s\tSlice: %s\n"
"%s\tCGroup: %s\n"
"%s\tCGroup realized: %s\n"
"%s\tCGroup mask: 0x%x\n"
"%s\tCGroup members mask: 0x%x\n",
prefix, u->id,
prefix, unit_description(u),
prefix, strna(u->instance),
prefix, unit_load_state_to_string(u->load_state),
prefix, unit_active_state_to_string(unit_active_state(u)),
prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->inactive_exit_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp2, sizeof(timestamp2), u->active_enter_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp3, sizeof(timestamp3), u->active_exit_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp4, sizeof(timestamp4), u->inactive_enter_timestamp.realtime)),
prefix, yes_no(unit_check_gc(u)),
prefix, yes_no(unit_need_daemon_reload(u)),
prefix, yes_no(u->transient),
prefix, strna(unit_slice_name(u)),
prefix, strna(u->cgroup_path),
prefix, yes_no(u->cgroup_realized),
prefix, u->cgroup_realized_mask,
prefix, u->cgroup_members_mask);
SET_FOREACH(t, u->names, i)
fprintf(f, "%s\tName: %s\n", prefix, t);
STRV_FOREACH(j, u->documentation)
fprintf(f, "%s\tDocumentation: %s\n", prefix, *j);
following = unit_following(u);
if (following)
fprintf(f, "%s\tFollowing: %s\n", prefix, following->id);
r = unit_following_set(u, &following_set);
if (r >= 0) {
Unit *other;
SET_FOREACH(other, following_set, i)
fprintf(f, "%s\tFollowing Set Member: %s\n", prefix, other->id);
}
if (u->fragment_path)
fprintf(f, "%s\tFragment Path: %s\n", prefix, u->fragment_path);
if (u->source_path)
fprintf(f, "%s\tSource Path: %s\n", prefix, u->source_path);
STRV_FOREACH(j, u->dropin_paths)
fprintf(f, "%s\tDropIn Path: %s\n", prefix, *j);
if (u->job_timeout > 0)
fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0));
if (u->job_timeout_action != FAILURE_ACTION_NONE)
fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, failure_action_to_string(u->job_timeout_action));
if (u->job_timeout_reboot_arg)
fprintf(f, "%s\tJob Timeout Reboot Argument: %s\n", prefix, u->job_timeout_reboot_arg);
condition_dump_list(u->conditions, f, prefix, condition_type_to_string);
condition_dump_list(u->asserts, f, prefix, assert_type_to_string);
if (dual_timestamp_is_set(&u->condition_timestamp))
fprintf(f,
"%s\tCondition Timestamp: %s\n"
"%s\tCondition Result: %s\n",
prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->condition_timestamp.realtime)),
prefix, yes_no(u->condition_result));
if (dual_timestamp_is_set(&u->assert_timestamp))
fprintf(f,
"%s\tAssert Timestamp: %s\n"
"%s\tAssert Result: %s\n",
prefix, strna(format_timestamp(timestamp1, sizeof(timestamp1), u->assert_timestamp.realtime)),
prefix, yes_no(u->assert_result));
for (d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {
Unit *other;
SET_FOREACH(other, u->dependencies[d], i)
fprintf(f, "%s\t%s: %s\n", prefix, unit_dependency_to_string(d), other->id);
}
if (!strv_isempty(u->requires_mounts_for)) {
fprintf(f,
"%s\tRequiresMountsFor:", prefix);
STRV_FOREACH(j, u->requires_mounts_for)
fprintf(f, " %s", *j);
fputs("\n", f);
}
if (u->load_state == UNIT_LOADED) {
fprintf(f,
"%s\tStopWhenUnneeded: %s\n"
"%s\tRefuseManualStart: %s\n"
"%s\tRefuseManualStop: %s\n"
"%s\tDefaultDependencies: %s\n"
"%s\tOnFailureJobMode: %s\n"
"%s\tIgnoreOnIsolate: %s\n",
prefix, yes_no(u->stop_when_unneeded),
prefix, yes_no(u->refuse_manual_start),
prefix, yes_no(u->refuse_manual_stop),
prefix, yes_no(u->default_dependencies),
prefix, job_mode_to_string(u->on_failure_job_mode),
prefix, yes_no(u->ignore_on_isolate));
if (UNIT_VTABLE(u)->dump)
UNIT_VTABLE(u)->dump(u, f, prefix2);
} else if (u->load_state == UNIT_MERGED)
fprintf(f,
"%s\tMerged into: %s\n",
prefix, u->merged_into->id);
else if (u->load_state == UNIT_ERROR)
fprintf(f, "%s\tLoad Error Code: %s\n", prefix, strerror(-u->load_error));
if (u->job)
job_dump(u->job, f, prefix2);
if (u->nop_job)
job_dump(u->nop_job, f, prefix2);
}
/* Common implementation for multiple backends */
int unit_load_fragment_and_dropin(Unit *u) {
int r;
assert(u);
/* Load a .{service,socket,...} file */
r = unit_load_fragment(u);
if (r < 0)
return r;
if (u->load_state == UNIT_STUB)
return -ENOENT;
/* Load drop-in directory data */
r = unit_load_dropin(unit_follow_merge(u));
if (r < 0)
return r;
return 0;
}
/* Common implementation for multiple backends */
int unit_load_fragment_and_dropin_optional(Unit *u) {
int r;
assert(u);
/* Same as unit_load_fragment_and_dropin(), but whether
* something can be loaded or not doesn't matter. */
/* Load a .service file */
r = unit_load_fragment(u);
if (r < 0)
return r;
if (u->load_state == UNIT_STUB)
u->load_state = UNIT_LOADED;
/* Load drop-in directory data */
r = unit_load_dropin(unit_follow_merge(u));
if (r < 0)
return r;
return 0;
}
int unit_add_default_target_dependency(Unit *u, Unit *target) {
assert(u);
assert(target);
if (target->type != UNIT_TARGET)
return 0;
/* Only add the dependency if both units are loaded, so that
* that loop check below is reliable */
if (u->load_state != UNIT_LOADED ||
target->load_state != UNIT_LOADED)
return 0;
/* If either side wants no automatic dependencies, then let's
* skip this */
if (!u->default_dependencies ||
!target->default_dependencies)
return 0;
/* Don't create loops */
if (set_get(target->dependencies[UNIT_BEFORE], u))
return 0;
return unit_add_dependency(target, UNIT_AFTER, u, true);
}
static int unit_add_target_dependencies(Unit *u) {
static const UnitDependency deps[] = {
UNIT_REQUIRED_BY,
UNIT_REQUISITE_OF,
UNIT_WANTED_BY,
UNIT_BOUND_BY
};
Unit *target;
Iterator i;
unsigned k;
int r = 0;
assert(u);
for (k = 0; k < ELEMENTSOF(deps); k++)
SET_FOREACH(target, u->dependencies[deps[k]], i) {
r = unit_add_default_target_dependency(u, target);
if (r < 0)
return r;
}
return r;
}
static int unit_add_slice_dependencies(Unit *u) {
assert(u);
if (!UNIT_HAS_CGROUP_CONTEXT(u))
return 0;
if (UNIT_ISSET(u->slice))
return unit_add_two_dependencies(u, UNIT_AFTER, UNIT_REQUIRES, UNIT_DEREF(u->slice), true);
if (unit_has_name(u, SPECIAL_ROOT_SLICE))
return 0;
return unit_add_two_dependencies_by_name(u, UNIT_AFTER, UNIT_REQUIRES, SPECIAL_ROOT_SLICE, NULL, true);
}
static int unit_add_mount_dependencies(Unit *u) {
char **i;
int r;
assert(u);
STRV_FOREACH(i, u->requires_mounts_for) {
char prefix[strlen(*i) + 1];
PATH_FOREACH_PREFIX_MORE(prefix, *i) {
_cleanup_free_ char *p = NULL;
Unit *m;
r = unit_name_from_path(prefix, ".mount", &p);
if (r < 0)
return r;
m = manager_get_unit(u->manager, p);
if (!m) {
/* Make sure to load the mount unit if
* it exists. If so the dependencies
* on this unit will be added later
* during the loading of the mount
* unit. */
(void) manager_load_unit_prepare(u->manager, p, NULL, NULL, &m);
continue;
}
if (m == u)
continue;
if (m->load_state != UNIT_LOADED)
continue;
r = unit_add_dependency(u, UNIT_AFTER, m, true);
if (r < 0)
return r;
if (m->fragment_path) {
r = unit_add_dependency(u, UNIT_REQUIRES, m, true);
if (r < 0)
return r;
}
}
}
return 0;
}
static int unit_add_startup_units(Unit *u) {
CGroupContext *c;
int r;
c = unit_get_cgroup_context(u);
if (!c)
return 0;
if (c->startup_cpu_shares == CGROUP_CPU_SHARES_INVALID &&
c->startup_blockio_weight == CGROUP_BLKIO_WEIGHT_INVALID)
return 0;
r = set_ensure_allocated(&u->manager->startup_units, NULL);
if (r < 0)
return r;
return set_put(u->manager->startup_units, u);
}
int unit_load(Unit *u) {
int r;
assert(u);
if (u->in_load_queue) {
LIST_REMOVE(load_queue, u->manager->load_queue, u);
u->in_load_queue = false;
}
if (u->type == _UNIT_TYPE_INVALID)
return -EINVAL;
if (u->load_state != UNIT_STUB)
return 0;
if (UNIT_VTABLE(u)->load) {
r = UNIT_VTABLE(u)->load(u);
if (r < 0)
goto fail;
}
if (u->load_state == UNIT_STUB) {
r = -ENOENT;
goto fail;
}
if (u->load_state == UNIT_LOADED) {
r = unit_add_target_dependencies(u);
if (r < 0)
goto fail;
r = unit_add_slice_dependencies(u);
if (r < 0)
goto fail;
r = unit_add_mount_dependencies(u);
if (r < 0)
goto fail;
r = unit_add_startup_units(u);
if (r < 0)
goto fail;
if (u->on_failure_job_mode == JOB_ISOLATE && set_size(u->dependencies[UNIT_ON_FAILURE]) > 1) {
log_unit_error(u, "More than one OnFailure= dependencies specified but OnFailureJobMode=isolate set. Refusing.");
r = -EINVAL;
goto fail;
}
unit_update_cgroup_members_masks(u);
/* If we are reloading, we need to wait for the deserializer
* to restore the net_cls ids that have been set previously */
if (u->manager->n_reloading <= 0) {
r = unit_add_to_netclass_cgroup(u);
if (r < 0)
return r;
}
}
assert((u->load_state != UNIT_MERGED) == !u->merged_into);
unit_add_to_dbus_queue(unit_follow_merge(u));
unit_add_to_gc_queue(u);
return 0;
fail:
u->load_state = u->load_state == UNIT_STUB ? UNIT_NOT_FOUND : UNIT_ERROR;
u->load_error = r;
unit_add_to_dbus_queue(u);
unit_add_to_gc_queue(u);
log_unit_debug_errno(u, r, "Failed to load configuration: %m");
return r;
}
static bool unit_condition_test_list(Unit *u, Condition *first, const char *(*to_string)(ConditionType t)) {
Condition *c;
int triggered = -1;
assert(u);
assert(to_string);
/* If the condition list is empty, then it is true */
if (!first)
return true;
/* Otherwise, if all of the non-trigger conditions apply and
* if any of the trigger conditions apply (unless there are
* none) we return true */
LIST_FOREACH(conditions, c, first) {
int r;
r = condition_test(c);
if (r < 0)
log_unit_warning(u,
"Couldn't determine result for %s=%s%s%s, assuming failed: %m",
to_string(c->type),
c->trigger ? "|" : "",
c->negate ? "!" : "",
c->parameter);
else
log_unit_debug(u,
"%s=%s%s%s %s.",
to_string(c->type),
c->trigger ? "|" : "",
c->negate ? "!" : "",
c->parameter,
condition_result_to_string(c->result));
if (!c->trigger && r <= 0)
return false;
if (c->trigger && triggered <= 0)
triggered = r > 0;
}
return triggered != 0;
}
static bool unit_condition_test(Unit *u) {
assert(u);
dual_timestamp_get(&u->condition_timestamp);
u->condition_result = unit_condition_test_list(u, u->conditions, condition_type_to_string);
return u->condition_result;
}
static bool unit_assert_test(Unit *u) {
assert(u);
dual_timestamp_get(&u->assert_timestamp);
u->assert_result = unit_condition_test_list(u, u->asserts, assert_type_to_string);
return u->assert_result;
}
_pure_ static const char* unit_get_status_message_format(Unit *u, JobType t) {
const char *format;
const UnitStatusMessageFormats *format_table;
assert(u);
assert(t == JOB_START || t == JOB_STOP || t == JOB_RELOAD);
if (t != JOB_RELOAD) {
format_table = &UNIT_VTABLE(u)->status_message_formats;
if (format_table) {
format = format_table->starting_stopping[t == JOB_STOP];
if (format)
return format;
}
}
/* Return generic strings */
if (t == JOB_START)
return "Starting %s.";
else if (t == JOB_STOP)
return "Stopping %s.";
else
return "Reloading %s.";
}
static void unit_status_print_starting_stopping(Unit *u, JobType t) {
const char *format;
assert(u);
format = unit_get_status_message_format(u, t);
DISABLE_WARNING_FORMAT_NONLITERAL;
unit_status_printf(u, "", format);
REENABLE_WARNING;
}
static void unit_status_log_starting_stopping_reloading(Unit *u, JobType t) {
const char *format;
char buf[LINE_MAX];
sd_id128_t mid;
assert(u);
if (t != JOB_START && t != JOB_STOP && t != JOB_RELOAD)
return;
if (log_on_console())
return;
/* We log status messages for all units and all operations. */
format = unit_get_status_message_format(u, t);
DISABLE_WARNING_FORMAT_NONLITERAL;
snprintf(buf, sizeof(buf), format, unit_description(u));
REENABLE_WARNING;
mid = t == JOB_START ? SD_MESSAGE_UNIT_STARTING :
t == JOB_STOP ? SD_MESSAGE_UNIT_STOPPING :
SD_MESSAGE_UNIT_RELOADING;
/* Note that we deliberately use LOG_MESSAGE() instead of
* LOG_UNIT_MESSAGE() here, since this is supposed to mimic
* closely what is written to screen using the status output,
* which is supposed the highest level, friendliest output
* possible, which means we should avoid the low-level unit
* name. */
log_struct(LOG_INFO,
LOG_MESSAGE_ID(mid),
LOG_UNIT_ID(u),
LOG_MESSAGE("%s", buf),
NULL);
}
void unit_status_emit_starting_stopping_reloading(Unit *u, JobType t) {
unit_status_log_starting_stopping_reloading(u, t);
/* Reload status messages have traditionally not been printed to console. */
if (t != JOB_RELOAD)
unit_status_print_starting_stopping(u, t);
}
/* Errors:
* -EBADR: This unit type does not support starting.
* -EALREADY: Unit is already started.
* -EAGAIN: An operation is already in progress. Retry later.
* -ECANCELED: Too many requests for now.
* -EPROTO: Assert failed
*/
int unit_start(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
/* Units that aren't loaded cannot be started */
if (u->load_state != UNIT_LOADED)
return -EINVAL;
/* If this is already started, then this will succeed. Note
* that this will even succeed if this unit is not startable
* by the user. This is relied on to detect when we need to
* wait for units and when waiting is finished. */
state = unit_active_state(u);
if (UNIT_IS_ACTIVE_OR_RELOADING(state))
return -EALREADY;
/* If the conditions failed, don't do anything at all. If we
* already are activating this call might still be useful to
* speed up activation in case there is some hold-off time,
* but we don't want to recheck the condition in that case. */
if (state != UNIT_ACTIVATING &&
!unit_condition_test(u)) {
log_unit_debug(u, "Starting requested but condition failed. Not starting unit.");
return -EALREADY;
}
/* If the asserts failed, fail the entire job */
if (state != UNIT_ACTIVATING &&
!unit_assert_test(u)) {
log_unit_notice(u, "Starting requested but asserts failed.");
return -EPROTO;
}
/* Units of types that aren't supported cannot be
* started. Note that we do this test only after the condition
* checks, so that we rather return condition check errors
* (which are usually not considered a true failure) than "not
* supported" errors (which are considered a failure).
*/
if (!unit_supported(u))
return -EOPNOTSUPP;
/* Forward to the main object, if we aren't it. */
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting start request from %s to %s.", u->id, following->id);
return unit_start(following);
}
/* If it is stopped, but we cannot start it, then fail */
if (!UNIT_VTABLE(u)->start)
return -EBADR;
/* We don't suppress calls to ->start() here when we are
* already starting, to allow this request to be used as a
* "hurry up" call, for example when the unit is in some "auto
* restart" state where it waits for a holdoff timer to elapse
* before it will start again. */
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->start(u);
}
bool unit_can_start(Unit *u) {
assert(u);
if (u->load_state != UNIT_LOADED)
return false;
if (!unit_supported(u))
return false;
return !!UNIT_VTABLE(u)->start;
}
bool unit_can_isolate(Unit *u) {
assert(u);
return unit_can_start(u) &&
u->allow_isolate;
}
/* Errors:
* -EBADR: This unit type does not support stopping.
* -EALREADY: Unit is already stopped.
* -EAGAIN: An operation is already in progress. Retry later.
*/
int unit_stop(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
state = unit_active_state(u);
if (UNIT_IS_INACTIVE_OR_FAILED(state))
return -EALREADY;
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting stop request from %s to %s.", u->id, following->id);
return unit_stop(following);
}
if (!UNIT_VTABLE(u)->stop)
return -EBADR;
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->stop(u);
}
/* Errors:
* -EBADR: This unit type does not support reloading.
* -ENOEXEC: Unit is not started.
* -EAGAIN: An operation is already in progress. Retry later.
*/
int unit_reload(Unit *u) {
UnitActiveState state;
Unit *following;
assert(u);
if (u->load_state != UNIT_LOADED)
return -EINVAL;
if (!unit_can_reload(u))
return -EBADR;
state = unit_active_state(u);
if (state == UNIT_RELOADING)
return -EALREADY;
if (state != UNIT_ACTIVE) {
log_unit_warning(u, "Unit cannot be reloaded because it is inactive.");
return -ENOEXEC;
}
following = unit_following(u);
if (following) {
log_unit_debug(u, "Redirecting reload request from %s to %s.", u->id, following->id);
return unit_reload(following);
}
unit_add_to_dbus_queue(u);
return UNIT_VTABLE(u)->reload(u);
}
bool unit_can_reload(Unit *u) {
assert(u);
if (!UNIT_VTABLE(u)->reload)
return false;
if (!UNIT_VTABLE(u)->can_reload)
return true;
return UNIT_VTABLE(u)->can_reload(u);
}
static void unit_check_unneeded(Unit *u) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
static const UnitDependency needed_dependencies[] = {
UNIT_REQUIRED_BY,
UNIT_REQUISITE_OF,
UNIT_WANTED_BY,
UNIT_BOUND_BY,
};
Unit *other;
Iterator i;
unsigned j;
int r;
assert(u);
/* If this service shall be shut down when unneeded then do
* so. */
if (!u->stop_when_unneeded)
return;
if (!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
return;
for (j = 0; j < ELEMENTSOF(needed_dependencies); j++)
SET_FOREACH(other, u->dependencies[needed_dependencies[j]], i)
if (unit_active_or_pending(other))
return;
/* If stopping a unit fails continously we might enter a stop
* loop here, hence stop acting on the service being
* unnecessary after a while. */
if (!ratelimit_test(&u->auto_stop_ratelimit)) {
log_unit_warning(u, "Unit not needed anymore, but not stopping since we tried this too often recently.");
return;
}
log_unit_info(u, "Unit not needed anymore. Stopping.");
/* Ok, nobody needs us anymore. Sniff. Then let's commit suicide */
r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
if (r < 0)
log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
}
static void unit_check_binds_to(Unit *u) {
_cleanup_bus_error_free_ sd_bus_error error = SD_BUS_ERROR_NULL;
bool stop = false;
Unit *other;
Iterator i;
int r;
assert(u);
if (u->job)
return;
if (unit_active_state(u) != UNIT_ACTIVE)
return;
SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i) {
if (other->job)
continue;
if (!UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other)))
continue;
stop = true;
break;
}
if (!stop)
return;
/* If stopping a unit fails continously we might enter a stop
* loop here, hence stop acting on the service being
* unnecessary after a while. */
if (!ratelimit_test(&u->auto_stop_ratelimit)) {
log_unit_warning(u, "Unit is bound to inactive unit %s, but not stopping since we tried this too often recently.", other->id);
return;
}
assert(other);
log_unit_info(u, "Unit is bound to inactive unit %s. Stopping, too.", other->id);
/* A unit we need to run is gone. Sniff. Let's stop this. */
r = manager_add_job(u->manager, JOB_STOP, u, JOB_FAIL, &error, NULL);
if (r < 0)
log_unit_warning_errno(u, r, "Failed to enqueue stop job, ignoring: %s", bus_error_message(&error, r));
}
static void retroactively_start_dependencies(Unit *u) {
Iterator i;
Unit *other;
assert(u);
assert(UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)));
SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
if (!set_get(u->dependencies[UNIT_AFTER], other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
if (!set_get(u->dependencies[UNIT_AFTER], other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_START, other, JOB_REPLACE, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
if (!set_get(u->dependencies[UNIT_AFTER], other) &&
!UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_START, other, JOB_FAIL, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_CONFLICTS], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
SET_FOREACH(other, u->dependencies[UNIT_CONFLICTED_BY], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
}
static void retroactively_stop_dependencies(Unit *u) {
Iterator i;
Unit *other;
assert(u);
assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
/* Pull down units which are bound to us recursively if enabled */
SET_FOREACH(other, u->dependencies[UNIT_BOUND_BY], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
manager_add_job(u->manager, JOB_STOP, other, JOB_REPLACE, NULL, NULL);
}
static void check_unneeded_dependencies(Unit *u) {
Iterator i;
Unit *other;
assert(u);
assert(UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)));
/* Garbage collect services that might not be needed anymore, if enabled */
SET_FOREACH(other, u->dependencies[UNIT_REQUIRES], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
SET_FOREACH(other, u->dependencies[UNIT_WANTS], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
SET_FOREACH(other, u->dependencies[UNIT_REQUISITE], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
SET_FOREACH(other, u->dependencies[UNIT_BINDS_TO], i)
if (!UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(other)))
unit_check_unneeded(other);
}
void unit_start_on_failure(Unit *u) {
Unit *other;
Iterator i;
assert(u);
if (set_size(u->dependencies[UNIT_ON_FAILURE]) <= 0)
return;
log_unit_info(u, "Triggering OnFailure= dependencies.");
SET_FOREACH(other, u->dependencies[UNIT_ON_FAILURE], i) {
int r;
r = manager_add_job(u->manager, JOB_START, other, u->on_failure_job_mode, NULL, NULL);
if (r < 0)
log_unit_error_errno(u, r, "Failed to enqueue OnFailure= job: %m");
}
}
void unit_trigger_notify(Unit *u) {
Unit *other;
Iterator i;
assert(u);
SET_FOREACH(other, u->dependencies[UNIT_TRIGGERED_BY], i)
if (UNIT_VTABLE(other)->trigger_notify)
UNIT_VTABLE(other)->trigger_notify(other, u);
}
void unit_notify(Unit *u, UnitActiveState os, UnitActiveState ns, bool reload_success) {
Manager *m;
bool unexpected;
assert(u);
assert(os < _UNIT_ACTIVE_STATE_MAX);
assert(ns < _UNIT_ACTIVE_STATE_MAX);
/* Note that this is called for all low-level state changes,
* even if they might map to the same high-level
* UnitActiveState! That means that ns == os is an expected
* behavior here. For example: if a mount point is remounted
* this function will be called too! */
m = u->manager;
/* Update timestamps for state changes */
if (m->n_reloading <= 0) {
dual_timestamp ts;
dual_timestamp_get(&ts);
if (UNIT_IS_INACTIVE_OR_FAILED(os) && !UNIT_IS_INACTIVE_OR_FAILED(ns))
u->inactive_exit_timestamp = ts;
else if (!UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_INACTIVE_OR_FAILED(ns))
u->inactive_enter_timestamp = ts;
if (!UNIT_IS_ACTIVE_OR_RELOADING(os) && UNIT_IS_ACTIVE_OR_RELOADING(ns))
u->active_enter_timestamp = ts;
else if (UNIT_IS_ACTIVE_OR_RELOADING(os) && !UNIT_IS_ACTIVE_OR_RELOADING(ns))
u->active_exit_timestamp = ts;
}
/* Keep track of failed units */
(void) manager_update_failed_units(u->manager, u, ns == UNIT_FAILED);
/* Make sure the cgroup is always removed when we become inactive */
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
unit_prune_cgroup(u);
/* Note that this doesn't apply to RemainAfterExit services exiting
* successfully, since there's no change of state in that case. Which is
* why it is handled in service_set_state() */
if (UNIT_IS_INACTIVE_OR_FAILED(os) != UNIT_IS_INACTIVE_OR_FAILED(ns)) {
ExecContext *ec;
ec = unit_get_exec_context(u);
if (ec && exec_context_may_touch_console(ec)) {
if (UNIT_IS_INACTIVE_OR_FAILED(ns)) {
m->n_on_console --;
if (m->n_on_console == 0)
/* unset no_console_output flag, since the console is free */
m->no_console_output = false;
} else
m->n_on_console ++;
}
}
if (u->job) {
unexpected = false;
if (u->job->state == JOB_WAITING)
/* So we reached a different state for this
* job. Let's see if we can run it now if it
* failed previously due to EAGAIN. */
job_add_to_run_queue(u->job);
/* Let's check whether this state change constitutes a
* finished job, or maybe contradicts a running job and
* hence needs to invalidate jobs. */
switch (u->job->type) {
case JOB_START:
case JOB_VERIFY_ACTIVE:
if (UNIT_IS_ACTIVE_OR_RELOADING(ns))
job_finish_and_invalidate(u->job, JOB_DONE, true);
else if (u->job->state == JOB_RUNNING && ns != UNIT_ACTIVATING) {
unexpected = true;
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
}
break;
case JOB_RELOAD:
case JOB_RELOAD_OR_START:
if (u->job->state == JOB_RUNNING) {
if (ns == UNIT_ACTIVE)
job_finish_and_invalidate(u->job, reload_success ? JOB_DONE : JOB_FAILED, true);
else if (ns != UNIT_ACTIVATING && ns != UNIT_RELOADING) {
unexpected = true;
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(u->job, ns == UNIT_FAILED ? JOB_FAILED : JOB_DONE, true);
}
}
break;
case JOB_STOP:
case JOB_RESTART:
case JOB_TRY_RESTART:
if (UNIT_IS_INACTIVE_OR_FAILED(ns))
job_finish_and_invalidate(u->job, JOB_DONE, true);
else if (u->job->state == JOB_RUNNING && ns != UNIT_DEACTIVATING) {
unexpected = true;
job_finish_and_invalidate(u->job, JOB_FAILED, true);
}
break;
default:
assert_not_reached("Job type unknown");
}
} else
unexpected = true;
if (m->n_reloading <= 0) {
/* If this state change happened without being
* requested by a job, then let's retroactively start
* or stop dependencies. We skip that step when
* deserializing, since we don't want to create any
* additional jobs just because something is already
* activated. */
if (unexpected) {
if (UNIT_IS_INACTIVE_OR_FAILED(os) && UNIT_IS_ACTIVE_OR_ACTIVATING(ns))
retroactively_start_dependencies(u);
else if (UNIT_IS_ACTIVE_OR_ACTIVATING(os) && UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
retroactively_stop_dependencies(u);
}
/* stop unneeded units regardless if going down was expected or not */
if (UNIT_IS_INACTIVE_OR_DEACTIVATING(ns))
check_unneeded_dependencies(u);
if (ns != os && ns == UNIT_FAILED) {
log_unit_notice(u, "Unit entered failed state.");
unit_start_on_failure(u);
}
}
/* Some names are special */
if (UNIT_IS_ACTIVE_OR_RELOADING(ns)) {
if (unit_has_name(u, SPECIAL_DBUS_SERVICE))
/* The bus might have just become available,
* hence try to connect to it, if we aren't
* yet connected. */
bus_init(m, true);
if (u->type == UNIT_SERVICE &&
!UNIT_IS_ACTIVE_OR_RELOADING(os) &&
m->n_reloading <= 0) {
/* Write audit record if we have just finished starting up */
manager_send_unit_audit(m, u, AUDIT_SERVICE_START, true);
u->in_audit = true;
}
if (!UNIT_IS_ACTIVE_OR_RELOADING(os))
manager_send_unit_plymouth(m, u);
} else {
/* We don't care about D-Bus here, since we'll get an
* asynchronous notification for it anyway. */
if (u->type == UNIT_SERVICE &&
UNIT_IS_INACTIVE_OR_FAILED(ns) &&
!UNIT_IS_INACTIVE_OR_FAILED(os) &&
m->n_reloading <= 0) {
/* Hmm, if there was no start record written
* write it now, so that we always have a nice
* pair */
if (!u->in_audit) {
manager_send_unit_audit(m, u, AUDIT_SERVICE_START, ns == UNIT_INACTIVE);
if (ns == UNIT_INACTIVE)
manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, true);
} else
/* Write audit record if we have just finished shutting down */
manager_send_unit_audit(m, u, AUDIT_SERVICE_STOP, ns == UNIT_INACTIVE);
u->in_audit = false;
}
}
manager_recheck_journal(m);
unit_trigger_notify(u);
if (u->manager->n_reloading <= 0) {
/* Maybe we finished startup and are now ready for
* being stopped because unneeded? */
unit_check_unneeded(u);
/* Maybe we finished startup, but something we needed
* has vanished? Let's die then. (This happens when
* something BindsTo= to a Type=oneshot unit, as these
* units go directly from starting to inactive,
* without ever entering started.) */
unit_check_binds_to(u);
}
unit_add_to_dbus_queue(u);
unit_add_to_gc_queue(u);
}
int unit_watch_pid(Unit *u, pid_t pid) {
int q, r;
assert(u);
assert(pid >= 1);
/* Watch a specific PID. We only support one or two units
* watching each PID for now, not more. */
r = set_ensure_allocated(&u->pids, NULL);
if (r < 0)
return r;
r = hashmap_ensure_allocated(&u->manager->watch_pids1, NULL);
if (r < 0)
return r;
r = hashmap_put(u->manager->watch_pids1, PID_TO_PTR(pid), u);
if (r == -EEXIST) {
r = hashmap_ensure_allocated(&u->manager->watch_pids2, NULL);
if (r < 0)
return r;
r = hashmap_put(u->manager->watch_pids2, PID_TO_PTR(pid), u);
}
q = set_put(u->pids, PID_TO_PTR(pid));
if (q < 0)
return q;
return r;
}
void unit_unwatch_pid(Unit *u, pid_t pid) {
assert(u);
assert(pid >= 1);
(void) hashmap_remove_value(u->manager->watch_pids1, PID_TO_PTR(pid), u);
(void) hashmap_remove_value(u->manager->watch_pids2, PID_TO_PTR(pid), u);
(void) set_remove(u->pids, PID_TO_PTR(pid));
}
void unit_unwatch_all_pids(Unit *u) {
assert(u);
while (!set_isempty(u->pids))
unit_unwatch_pid(u, PTR_TO_PID(set_first(u->pids)));
u->pids = set_free(u->pids);
}
void unit_tidy_watch_pids(Unit *u, pid_t except1, pid_t except2) {
Iterator i;
void *e;
assert(u);
/* Cleans dead PIDs from our list */
SET_FOREACH(e, u->pids, i) {
pid_t pid = PTR_TO_PID(e);
if (pid == except1 || pid == except2)
continue;
if (!pid_is_unwaited(pid))
unit_unwatch_pid(u, pid);
}
}
bool unit_job_is_applicable(Unit *u, JobType j) {
assert(u);
assert(j >= 0 && j < _JOB_TYPE_MAX);
switch (j) {
case JOB_VERIFY_ACTIVE:
case JOB_START:
case JOB_STOP:
case JOB_NOP:
return true;
case JOB_RESTART:
case JOB_TRY_RESTART:
return unit_can_start(u);
case JOB_RELOAD:
return unit_can_reload(u);
case JOB_RELOAD_OR_START:
return unit_can_reload(u) && unit_can_start(u);
default:
assert_not_reached("Invalid job type");
}
}
static void maybe_warn_about_dependency(Unit *u, const char *other, UnitDependency dependency) {
assert(u);
/* Only warn about some unit types */
if (!IN_SET(dependency, UNIT_CONFLICTS, UNIT_CONFLICTED_BY, UNIT_BEFORE, UNIT_AFTER, UNIT_ON_FAILURE, UNIT_TRIGGERS, UNIT_TRIGGERED_BY))
return;
if (streq_ptr(u->id, other))
log_unit_warning(u, "Dependency %s=%s dropped", unit_dependency_to_string(dependency), u->id);
else
log_unit_warning(u, "Dependency %s=%s dropped, merged into %s", unit_dependency_to_string(dependency), strna(other), u->id);
}
int unit_add_dependency(Unit *u, UnitDependency d, Unit *other, bool add_reference) {
static const UnitDependency inverse_table[_UNIT_DEPENDENCY_MAX] = {
[UNIT_REQUIRES] = UNIT_REQUIRED_BY,
[UNIT_WANTS] = UNIT_WANTED_BY,
[UNIT_REQUISITE] = UNIT_REQUISITE_OF,
[UNIT_BINDS_TO] = UNIT_BOUND_BY,
[UNIT_PART_OF] = UNIT_CONSISTS_OF,
[UNIT_REQUIRED_BY] = UNIT_REQUIRES,
[UNIT_REQUISITE_OF] = UNIT_REQUISITE,
[UNIT_WANTED_BY] = UNIT_WANTS,
[UNIT_BOUND_BY] = UNIT_BINDS_TO,
[UNIT_CONSISTS_OF] = UNIT_PART_OF,
[UNIT_CONFLICTS] = UNIT_CONFLICTED_BY,
[UNIT_CONFLICTED_BY] = UNIT_CONFLICTS,
[UNIT_BEFORE] = UNIT_AFTER,
[UNIT_AFTER] = UNIT_BEFORE,
[UNIT_ON_FAILURE] = _UNIT_DEPENDENCY_INVALID,
[UNIT_REFERENCES] = UNIT_REFERENCED_BY,
[UNIT_REFERENCED_BY] = UNIT_REFERENCES,
[UNIT_TRIGGERS] = UNIT_TRIGGERED_BY,
[UNIT_TRIGGERED_BY] = UNIT_TRIGGERS,
[UNIT_PROPAGATES_RELOAD_TO] = UNIT_RELOAD_PROPAGATED_FROM,
[UNIT_RELOAD_PROPAGATED_FROM] = UNIT_PROPAGATES_RELOAD_TO,
[UNIT_JOINS_NAMESPACE_OF] = UNIT_JOINS_NAMESPACE_OF,
};
int r, q = 0, v = 0, w = 0;
Unit *orig_u = u, *orig_other = other;
assert(u);
assert(d >= 0 && d < _UNIT_DEPENDENCY_MAX);
assert(other);
u = unit_follow_merge(u);
other = unit_follow_merge(other);
/* We won't allow dependencies on ourselves. We will not
* consider them an error however. */
if (u == other) {
maybe_warn_about_dependency(orig_u, orig_other->id, d);
return 0;
}
r = set_ensure_allocated(&u->dependencies[d], NULL);
if (r < 0)
return r;
if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID) {
r = set_ensure_allocated(&other->dependencies[inverse_table[d]], NULL);
if (r < 0)
return r;
}
if (add_reference) {
r = set_ensure_allocated(&u->dependencies[UNIT_REFERENCES], NULL);
if (r < 0)
return r;
r = set_ensure_allocated(&other->dependencies[UNIT_REFERENCED_BY], NULL);
if (r < 0)
return r;
}
q = set_put(u->dependencies[d], other);
if (q < 0)
return q;
if (inverse_table[d] != _UNIT_DEPENDENCY_INVALID && inverse_table[d] != d) {
v = set_put(other->dependencies[inverse_table[d]], u);
if (v < 0) {
r = v;
goto fail;
}
}
if (add_reference) {
w = set_put(u->dependencies[UNIT_REFERENCES], other);
if (w < 0) {
r = w;
goto fail;
}
r = set_put(other->dependencies[UNIT_REFERENCED_BY], u);
if (r < 0)
goto fail;
}
unit_add_to_dbus_queue(u);
return 0;
fail:
if (q > 0)
set_remove(u->dependencies[d], other);
if (v > 0)
set_remove(other->dependencies[inverse_table[d]], u);
if (w > 0)
set_remove(u->dependencies[UNIT_REFERENCES], other);
return r;
}
int unit_add_two_dependencies(Unit *u, UnitDependency d, UnitDependency e, Unit *other, bool add_reference) {
int r;
assert(u);
r = unit_add_dependency(u, d, other, add_reference);
if (r < 0)
return r;
return unit_add_dependency(u, e, other, add_reference);
}
static int resolve_template(Unit *u, const char *name, const char*path, char **buf, const char **ret) {
int r;
assert(u);
assert(name || path);
assert(buf);
assert(ret);
if (!name)
name = basename(path);
if (!unit_name_is_valid(name, UNIT_NAME_TEMPLATE)) {
*buf = NULL;
*ret = name;
return 0;
}
if (u->instance)
r = unit_name_replace_instance(name, u->instance, buf);
else {
_cleanup_free_ char *i = NULL;
r = unit_name_to_prefix(u->id, &i);
if (r < 0)
return r;
r = unit_name_replace_instance(name, i, buf);
}
if (r < 0)
return r;
*ret = *buf;
return 0;
}
int unit_add_dependency_by_name(Unit *u, UnitDependency d, const char *name, const char *path, bool add_reference) {
_cleanup_free_ char *buf = NULL;
Unit *other;
int r;
assert(u);
assert(name || path);
r = resolve_template(u, name, path, &buf, &name);
if (r < 0)
return r;
r = manager_load_unit(u->manager, name, path, NULL, &other);
if (r < 0)
return r;
return unit_add_dependency(u, d, other, add_reference);
}
int unit_add_two_dependencies_by_name(Unit *u, UnitDependency d, UnitDependency e, const char *name, const char *path, bool add_reference) {
_cleanup_free_ char *buf = NULL;
Unit *other;
int r;
assert(u);
assert(name || path);
r = resolve_template(u, name, path, &buf, &name);
if (r < 0)
return r;
r = manager_load_unit(u->manager, name, path, NULL, &other);
if (r < 0)
return r;
return unit_add_two_dependencies(u, d, e, other, add_reference);
}
int set_unit_path(const char *p) {
/* This is mostly for debug purposes */
if (setenv("SYSTEMD_UNIT_PATH", p, 1) < 0)
return -errno;
return 0;
}
char *unit_dbus_path(Unit *u) {
assert(u);
if (!u->id)
return NULL;
return unit_dbus_path_from_name(u->id);
}
int unit_set_slice(Unit *u, Unit *slice) {
assert(u);
assert(slice);
/* Sets the unit slice if it has not been set before. Is extra
* careful, to only allow this for units that actually have a
* cgroup context. Also, we don't allow to set this for slices
* (since the parent slice is derived from the name). Make
* sure the unit we set is actually a slice. */
if (!UNIT_HAS_CGROUP_CONTEXT(u))
return -EOPNOTSUPP;
if (u->type == UNIT_SLICE)
return -EINVAL;
if (unit_active_state(u) != UNIT_INACTIVE)
return -EBUSY;
if (slice->type != UNIT_SLICE)
return -EINVAL;
if (unit_has_name(u, SPECIAL_INIT_SCOPE) &&
!unit_has_name(slice, SPECIAL_ROOT_SLICE))
return -EPERM;
if (UNIT_DEREF(u->slice) == slice)
return 0;
if (UNIT_ISSET(u->slice))
return -EBUSY;
unit_ref_set(&u->slice, slice);
return 1;
}
int unit_set_default_slice(Unit *u) {
_cleanup_free_ char *b = NULL;
const char *slice_name;
Unit *slice;
int r;
assert(u);
if (UNIT_ISSET(u->slice))
return 0;
if (u->instance) {
_cleanup_free_ char *prefix = NULL, *escaped = NULL;
/* Implicitly place all instantiated units in their
* own per-template slice */
r = unit_name_to_prefix(u->id, &prefix);
if (r < 0)
return r;
/* The prefix is already escaped, but it might include
* "-" which has a special meaning for slice units,
* hence escape it here extra. */
escaped = unit_name_escape(prefix);
if (!escaped)
return -ENOMEM;
if (u->manager->running_as == MANAGER_SYSTEM)
b = strjoin("system-", escaped, ".slice", NULL);
else
b = strappend(escaped, ".slice");
if (!b)
return -ENOMEM;
slice_name = b;
} else
slice_name =
u->manager->running_as == MANAGER_SYSTEM && !unit_has_name(u, SPECIAL_INIT_SCOPE)
? SPECIAL_SYSTEM_SLICE
: SPECIAL_ROOT_SLICE;
r = manager_load_unit(u->manager, slice_name, NULL, NULL, &slice);
if (r < 0)
return r;
return unit_set_slice(u, slice);
}
const char *unit_slice_name(Unit *u) {
assert(u);
if (!UNIT_ISSET(u->slice))
return NULL;
return UNIT_DEREF(u->slice)->id;
}
int unit_load_related_unit(Unit *u, const char *type, Unit **_found) {
_cleanup_free_ char *t = NULL;
int r;
assert(u);
assert(type);
assert(_found);
r = unit_name_change_suffix(u->id, type, &t);
if (r < 0)
return r;
if (unit_has_name(u, t))
return -EINVAL;
r = manager_load_unit(u->manager, t, NULL, NULL, _found);
assert(r < 0 || *_found != u);
return r;
}
static int signal_name_owner_changed(sd_bus_message *message, void *userdata, sd_bus_error *error) {
const char *name, *old_owner, *new_owner;
Unit *u = userdata;
int r;
assert(message);
assert(u);
r = sd_bus_message_read(message, "sss", &name, &old_owner, &new_owner);
if (r < 0) {
bus_log_parse_error(r);
return 0;
}
if (UNIT_VTABLE(u)->bus_name_owner_change)
UNIT_VTABLE(u)->bus_name_owner_change(u, name, old_owner, new_owner);
return 0;
}
int unit_install_bus_match(Unit *u, sd_bus *bus, const char *name) {
const char *match;
assert(u);
assert(bus);
assert(name);
if (u->match_bus_slot)
return -EBUSY;
match = strjoina("type='signal',"
"sender='org.freedesktop.DBus',"
"path='/org/freedesktop/DBus',"
"interface='org.freedesktop.DBus',"
"member='NameOwnerChanged',"
"arg0='", name, "'",
NULL);
return sd_bus_add_match(bus, &u->match_bus_slot, match, signal_name_owner_changed, u);
}
int unit_watch_bus_name(Unit *u, const char *name) {
int r;
assert(u);
assert(name);
/* Watch a specific name on the bus. We only support one unit
* watching each name for now. */
if (u->manager->api_bus) {
/* If the bus is already available, install the match directly.
* Otherwise, just put the name in the list. bus_setup_api() will take care later. */
r = unit_install_bus_match(u, u->manager->api_bus, name);
if (r < 0)
return log_warning_errno(r, "Failed to subscribe to NameOwnerChanged signal for '%s': %m", name);
}
r = hashmap_put(u->manager->watch_bus, name, u);
if (r < 0) {
u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
return log_warning_errno(r, "Failed to put bus name to hashmap: %m");
}
return 0;
}
void unit_unwatch_bus_name(Unit *u, const char *name) {
assert(u);
assert(name);
hashmap_remove_value(u->manager->watch_bus, name, u);
u->match_bus_slot = sd_bus_slot_unref(u->match_bus_slot);
}
bool unit_can_serialize(Unit *u) {
assert(u);
return UNIT_VTABLE(u)->serialize && UNIT_VTABLE(u)->deserialize_item;
}
int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs) {
int r;
assert(u);
assert(f);
assert(fds);
if (unit_can_serialize(u)) {
ExecRuntime *rt;
r = UNIT_VTABLE(u)->serialize(u, f, fds);
if (r < 0)
return r;
rt = unit_get_exec_runtime(u);
if (rt) {
r = exec_runtime_serialize(u, rt, f, fds);
if (r < 0)
return r;
}
}
dual_timestamp_serialize(f, "inactive-exit-timestamp", &u->inactive_exit_timestamp);
dual_timestamp_serialize(f, "active-enter-timestamp", &u->active_enter_timestamp);
dual_timestamp_serialize(f, "active-exit-timestamp", &u->active_exit_timestamp);
dual_timestamp_serialize(f, "inactive-enter-timestamp", &u->inactive_enter_timestamp);
dual_timestamp_serialize(f, "condition-timestamp", &u->condition_timestamp);
dual_timestamp_serialize(f, "assert-timestamp", &u->assert_timestamp);
if (dual_timestamp_is_set(&u->condition_timestamp))
unit_serialize_item(u, f, "condition-result", yes_no(u->condition_result));
if (dual_timestamp_is_set(&u->assert_timestamp))
unit_serialize_item(u, f, "assert-result", yes_no(u->assert_result));
unit_serialize_item(u, f, "transient", yes_no(u->transient));
unit_serialize_item_format(u, f, "cpuacct-usage-base", "%" PRIu64, u->cpuacct_usage_base);
if (u->cgroup_path)
unit_serialize_item(u, f, "cgroup", u->cgroup_path);
unit_serialize_item(u, f, "cgroup-realized", yes_no(u->cgroup_realized));
if (u->cgroup_netclass_id)
unit_serialize_item_format(u, f, "netclass-id", "%" PRIu32, u->cgroup_netclass_id);
if (serialize_jobs) {
if (u->job) {
fprintf(f, "job\n");
job_serialize(u->job, f, fds);
}
if (u->nop_job) {
fprintf(f, "job\n");
job_serialize(u->nop_job, f, fds);
}
}
/* End marker */
fputc('\n', f);
return 0;
}
int unit_serialize_item(Unit *u, FILE *f, const char *key, const char *value) {
assert(u);
assert(f);
assert(key);
if (!value)
return 0;
fputs(key, f);
fputc('=', f);
fputs(value, f);
fputc('\n', f);
return 1;
}
int unit_serialize_item_escaped(Unit *u, FILE *f, const char *key, const char *value) {
_cleanup_free_ char *c = NULL;
assert(u);
assert(f);
assert(key);
if (!value)
return 0;
c = cescape(value);
if (!c)
return -ENOMEM;
fputs(key, f);
fputc('=', f);
fputs(c, f);
fputc('\n', f);
return 1;
}
int unit_serialize_item_fd(Unit *u, FILE *f, FDSet *fds, const char *key, int fd) {
int copy;
assert(u);
assert(f);
assert(key);
if (fd < 0)
return 0;
copy = fdset_put_dup(fds, fd);
if (copy < 0)
return copy;
fprintf(f, "%s=%i\n", key, copy);
return 1;
}
void unit_serialize_item_format(Unit *u, FILE *f, const char *key, const char *format, ...) {
va_list ap;
assert(u);
assert(f);
assert(key);
assert(format);
fputs(key, f);
fputc('=', f);
va_start(ap, format);
vfprintf(f, format, ap);
va_end(ap);
fputc('\n', f);
}
int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
ExecRuntime **rt = NULL;
size_t offset;
int r;
assert(u);
assert(f);
assert(fds);
offset = UNIT_VTABLE(u)->exec_runtime_offset;
if (offset > 0)
rt = (ExecRuntime**) ((uint8_t*) u + offset);
for (;;) {
char line[LINE_MAX], *l, *v;
size_t k;
if (!fgets(line, sizeof(line), f)) {
if (feof(f))
return 0;
return -errno;
}
char_array_0(line);
l = strstrip(line);
/* End marker */
if (isempty(l))
return 0;
k = strcspn(l, "=");
if (l[k] == '=') {
l[k] = 0;
v = l+k+1;
} else
v = l+k;
if (streq(l, "job")) {
if (v[0] == '\0') {
/* new-style serialized job */
Job *j;
j = job_new_raw(u);
if (!j)
return log_oom();
r = job_deserialize(j, f, fds);
if (r < 0) {
job_free(j);
return r;
}
r = hashmap_put(u->manager->jobs, UINT32_TO_PTR(j->id), j);
if (r < 0) {
job_free(j);
return r;
}
r = job_install_deserialized(j);
if (r < 0) {
hashmap_remove(u->manager->jobs, UINT32_TO_PTR(j->id));
job_free(j);
return r;
}
} else /* legacy for pre-44 */
log_unit_warning(u, "Update from too old systemd versions are unsupported, cannot deserialize job: %s", v);
continue;
} else if (streq(l, "inactive-exit-timestamp")) {
dual_timestamp_deserialize(v, &u->inactive_exit_timestamp);
continue;
} else if (streq(l, "active-enter-timestamp")) {
dual_timestamp_deserialize(v, &u->active_enter_timestamp);
continue;
} else if (streq(l, "active-exit-timestamp")) {
dual_timestamp_deserialize(v, &u->active_exit_timestamp);
continue;
} else if (streq(l, "inactive-enter-timestamp")) {
dual_timestamp_deserialize(v, &u->inactive_enter_timestamp);
continue;
} else if (streq(l, "condition-timestamp")) {
dual_timestamp_deserialize(v, &u->condition_timestamp);
continue;
} else if (streq(l, "assert-timestamp")) {
dual_timestamp_deserialize(v, &u->assert_timestamp);
continue;
} else if (streq(l, "condition-result")) {
r = parse_boolean(v);
if (r < 0)
log_unit_debug(u, "Failed to parse condition result value %s, ignoring.", v);
else
u->condition_result = r;
continue;
} else if (streq(l, "assert-result")) {
r = parse_boolean(v);
if (r < 0)
log_unit_debug(u, "Failed to parse assert result value %s, ignoring.", v);
else
u->assert_result = r;
continue;
} else if (streq(l, "transient")) {
r = parse_boolean(v);
if (r < 0)
log_unit_debug(u, "Failed to parse transient bool %s, ignoring.", v);
else
u->transient = r;
continue;
} else if (streq(l, "cpuacct-usage-base")) {
r = safe_atou64(v, &u->cpuacct_usage_base);
if (r < 0)
log_unit_debug(u, "Failed to parse CPU usage %s, ignoring.", v);
continue;
} else if (streq(l, "cgroup")) {
r = unit_set_cgroup_path(u, v);
if (r < 0)
log_unit_debug_errno(u, r, "Failed to set cgroup path %s, ignoring: %m", v);
(void) unit_watch_cgroup(u);
continue;
} else if (streq(l, "cgroup-realized")) {
int b;
b = parse_boolean(v);
if (b < 0)
log_unit_debug(u, "Failed to parse cgroup-realized bool %s, ignoring.", v);
else
u->cgroup_realized = b;
continue;
} else if (streq(l, "netclass-id")) {
r = safe_atou32(v, &u->cgroup_netclass_id);
if (r < 0)
log_unit_debug(u, "Failed to parse netclass ID %s, ignoring.", v);
else {
r = unit_add_to_netclass_cgroup(u);
if (r < 0)
log_unit_debug_errno(u, r, "Failed to add unit to netclass cgroup, ignoring: %m");
}
continue;
}
if (unit_can_serialize(u)) {
if (rt) {
r = exec_runtime_deserialize_item(u, rt, l, v, fds);
if (r < 0) {
log_unit_warning(u, "Failed to deserialize runtime parameter '%s', ignoring.", l);
continue;
}
/* Returns positive if key was handled by the call */
if (r > 0)
continue;
}
r = UNIT_VTABLE(u)->deserialize_item(u, l, v, fds);
if (r < 0)
log_unit_warning(u, "Failed to deserialize unit parameter '%s', ignoring.", l);
}
}
}
int unit_add_node_link(Unit *u, const char *what, bool wants) {
Unit *device;
_cleanup_free_ char *e = NULL;
int r;
assert(u);
/* Adds in links to the device node that this unit is based on */
if (isempty(what))
return 0;
if (!is_device_path(what))
return 0;
/* When device units aren't supported (such as in a
* container), don't create dependencies on them. */
if (!unit_type_supported(UNIT_DEVICE))
return 0;
r = unit_name_from_path(what, ".device", &e);
if (r < 0)
return r;
r = manager_load_unit(u->manager, e, NULL, NULL, &device);
if (r < 0)
return r;
r = unit_add_two_dependencies(u, UNIT_AFTER, u->manager->running_as == MANAGER_SYSTEM ? UNIT_BINDS_TO : UNIT_WANTS, device, true);
if (r < 0)
return r;
if (wants) {
r = unit_add_dependency(device, UNIT_WANTS, u, false);
if (r < 0)
return r;
}
return 0;
}
int unit_coldplug(Unit *u) {
int r = 0, q = 0;
assert(u);
/* Make sure we don't enter a loop, when coldplugging
* recursively. */
if (u->coldplugged)
return 0;
u->coldplugged = true;
if (UNIT_VTABLE(u)->coldplug)
r = UNIT_VTABLE(u)->coldplug(u);
if (u->job)
q = job_coldplug(u->job);
if (r < 0)
return r;
if (q < 0)
return q;
return 0;
}
void unit_status_printf(Unit *u, const char *status, const char *unit_status_msg_format) {
DISABLE_WARNING_FORMAT_NONLITERAL;
manager_status_printf(u->manager, STATUS_TYPE_NORMAL,
status, unit_status_msg_format, unit_description(u));
REENABLE_WARNING;
}
bool unit_need_daemon_reload(Unit *u) {
_cleanup_strv_free_ char **t = NULL;
char **path;
struct stat st;
unsigned loaded_cnt, current_cnt;
assert(u);
if (u->fragment_path) {
zero(st);
if (stat(u->fragment_path, &st) < 0)
/* What, cannot access this anymore? */
return true;
if (u->fragment_mtime > 0 &&
timespec_load(&st.st_mtim) != u->fragment_mtime)
return true;
}
if (u->source_path) {
zero(st);
if (stat(u->source_path, &st) < 0)
return true;
if (u->source_mtime > 0 &&
timespec_load(&st.st_mtim) != u->source_mtime)
return true;
}
(void) unit_find_dropin_paths(u, &t);
loaded_cnt = strv_length(t);
current_cnt = strv_length(u->dropin_paths);
if (loaded_cnt == current_cnt) {
if (loaded_cnt == 0)
return false;
if (strv_overlap(u->dropin_paths, t)) {
STRV_FOREACH(path, u->dropin_paths) {
zero(st);
if (stat(*path, &st) < 0)
return true;
if (u->dropin_mtime > 0 &&
timespec_load(&st.st_mtim) > u->dropin_mtime)
return true;
}
return false;
} else
return true;
} else
return true;
}
void unit_reset_failed(Unit *u) {
assert(u);
if (UNIT_VTABLE(u)->reset_failed)
UNIT_VTABLE(u)->reset_failed(u);
}
Unit *unit_following(Unit *u) {
assert(u);
if (UNIT_VTABLE(u)->following)
return UNIT_VTABLE(u)->following(u);
return NULL;
}
bool unit_stop_pending(Unit *u) {
assert(u);
/* This call does check the current state of the unit. It's
* hence useful to be called from state change calls of the
* unit itself, where the state isn't updated yet. This is
* different from unit_inactive_or_pending() which checks both
* the current state and for a queued job. */
return u->job && u->job->type == JOB_STOP;
}
bool unit_inactive_or_pending(Unit *u) {
assert(u);
/* Returns true if the unit is inactive or going down */
if (UNIT_IS_INACTIVE_OR_DEACTIVATING(unit_active_state(u)))
return true;
if (unit_stop_pending(u))
return true;
return false;
}
bool unit_active_or_pending(Unit *u) {
assert(u);
/* Returns true if the unit is active or going up */
if (UNIT_IS_ACTIVE_OR_ACTIVATING(unit_active_state(u)))
return true;
if (u->job &&
(u->job->type == JOB_START ||
u->job->type == JOB_RELOAD_OR_START ||
u->job->type == JOB_RESTART))
return true;
return false;
}
int unit_kill(Unit *u, KillWho w, int signo, sd_bus_error *error) {
assert(u);
assert(w >= 0 && w < _KILL_WHO_MAX);
assert(signo > 0);
assert(signo < _NSIG);
if (!UNIT_VTABLE(u)->kill)
return -EOPNOTSUPP;
return UNIT_VTABLE(u)->kill(u, w, signo, error);
}
static Set *unit_pid_set(pid_t main_pid, pid_t control_pid) {
Set *pid_set;
int r;
pid_set = set_new(NULL);
if (!pid_set)
return NULL;
/* Exclude the main/control pids from being killed via the cgroup */
if (main_pid > 0) {
r = set_put(pid_set, PID_TO_PTR(main_pid));
if (r < 0)
goto fail;
}
if (control_pid > 0) {
r = set_put(pid_set, PID_TO_PTR(control_pid));
if (r < 0)
goto fail;
}
return pid_set;
fail:
set_free(pid_set);
return NULL;
}
int unit_kill_common(
Unit *u,
KillWho who,
int signo,
pid_t main_pid,
pid_t control_pid,
sd_bus_error *error) {
int r = 0;
bool killed = false;
if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL)) {
if (main_pid < 0)
return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no main processes", unit_type_to_string(u->type));
else if (main_pid == 0)
return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No main process to kill");
}
if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL)) {
if (control_pid < 0)
return sd_bus_error_setf(error, BUS_ERROR_NO_SUCH_PROCESS, "%s units have no control processes", unit_type_to_string(u->type));
else if (control_pid == 0)
return sd_bus_error_set_const(error, BUS_ERROR_NO_SUCH_PROCESS, "No control process to kill");
}
if (IN_SET(who, KILL_CONTROL, KILL_CONTROL_FAIL, KILL_ALL, KILL_ALL_FAIL))
if (control_pid > 0) {
if (kill(control_pid, signo) < 0)
r = -errno;
else
killed = true;
}
if (IN_SET(who, KILL_MAIN, KILL_MAIN_FAIL, KILL_ALL, KILL_ALL_FAIL))
if (main_pid > 0) {
if (kill(main_pid, signo) < 0)
r = -errno;
else
killed = true;
}
if (IN_SET(who, KILL_ALL, KILL_ALL_FAIL) && u->cgroup_path) {
_cleanup_set_free_ Set *pid_set = NULL;
int q;
/* Exclude the main/control pids from being killed via the cgroup */
pid_set = unit_pid_set(main_pid, control_pid);
if (!pid_set)
return -ENOMEM;
q = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, signo, false, false, false, pid_set);
if (q < 0 && q != -EAGAIN && q != -ESRCH && q != -ENOENT)
r = q;
else
killed = true;
}
if (r == 0 && !killed && IN_SET(who, KILL_ALL_FAIL, KILL_CONTROL_FAIL, KILL_ALL_FAIL))
return -ESRCH;
return r;
}
int unit_following_set(Unit *u, Set **s) {
assert(u);
assert(s);
if (UNIT_VTABLE(u)->following_set)
return UNIT_VTABLE(u)->following_set(u, s);
*s = NULL;
return 0;
}
UnitFileState unit_get_unit_file_state(Unit *u) {
int r;
assert(u);
if (u->unit_file_state < 0 && u->fragment_path) {
r = unit_file_get_state(
u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
NULL,
basename(u->fragment_path),
&u->unit_file_state);
if (r < 0)
u->unit_file_state = UNIT_FILE_BAD;
}
return u->unit_file_state;
}
int unit_get_unit_file_preset(Unit *u) {
assert(u);
if (u->unit_file_preset < 0 && u->fragment_path)
u->unit_file_preset = unit_file_query_preset(
u->manager->running_as == MANAGER_SYSTEM ? UNIT_FILE_SYSTEM : UNIT_FILE_USER,
NULL,
basename(u->fragment_path));
return u->unit_file_preset;
}
Unit* unit_ref_set(UnitRef *ref, Unit *u) {
assert(ref);
assert(u);
if (ref->unit)
unit_ref_unset(ref);
ref->unit = u;
LIST_PREPEND(refs, u->refs, ref);
return u;
}
void unit_ref_unset(UnitRef *ref) {
assert(ref);
if (!ref->unit)
return;
LIST_REMOVE(refs, ref->unit->refs, ref);
ref->unit = NULL;
}
int unit_patch_contexts(Unit *u) {
CGroupContext *cc;
ExecContext *ec;
unsigned i;
int r;
assert(u);
/* Patch in the manager defaults into the exec and cgroup
* contexts, _after_ the rest of the settings have been
* initialized */
ec = unit_get_exec_context(u);
if (ec) {
/* This only copies in the ones that need memory */
for (i = 0; i < _RLIMIT_MAX; i++)
if (u->manager->rlimit[i] && !ec->rlimit[i]) {
ec->rlimit[i] = newdup(struct rlimit, u->manager->rlimit[i], 1);
if (!ec->rlimit[i])
return -ENOMEM;
}
if (u->manager->running_as == MANAGER_USER &&
!ec->working_directory) {
r = get_home_dir(&ec->working_directory);
if (r < 0)
return r;
/* Allow user services to run, even if the
* home directory is missing */
ec->working_directory_missing_ok = true;
}
if (u->manager->running_as == MANAGER_USER &&
(ec->syscall_whitelist ||
!set_isempty(ec->syscall_filter) ||
!set_isempty(ec->syscall_archs) ||
ec->address_families_whitelist ||
!set_isempty(ec->address_families)))
ec->no_new_privileges = true;
if (ec->private_devices)
ec->capability_bounding_set_drop |= (uint64_t) 1ULL << (uint64_t) CAP_MKNOD;
}
cc = unit_get_cgroup_context(u);
if (cc) {
if (ec &&
ec->private_devices &&
cc->device_policy == CGROUP_AUTO)
cc->device_policy = CGROUP_CLOSED;
}
return 0;
}
ExecContext *unit_get_exec_context(Unit *u) {
size_t offset;
assert(u);
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->exec_context_offset;
if (offset <= 0)
return NULL;
return (ExecContext*) ((uint8_t*) u + offset);
}
KillContext *unit_get_kill_context(Unit *u) {
size_t offset;
assert(u);
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->kill_context_offset;
if (offset <= 0)
return NULL;
return (KillContext*) ((uint8_t*) u + offset);
}
CGroupContext *unit_get_cgroup_context(Unit *u) {
size_t offset;
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->cgroup_context_offset;
if (offset <= 0)
return NULL;
return (CGroupContext*) ((uint8_t*) u + offset);
}
ExecRuntime *unit_get_exec_runtime(Unit *u) {
size_t offset;
if (u->type < 0)
return NULL;
offset = UNIT_VTABLE(u)->exec_runtime_offset;
if (offset <= 0)
return NULL;
return *(ExecRuntime**) ((uint8_t*) u + offset);
}
static int unit_drop_in_dir(Unit *u, UnitSetPropertiesMode mode, bool transient, char **dir) {
assert(u);
if (u->manager->running_as == MANAGER_USER) {
int r;
if (mode == UNIT_PERSISTENT && !transient)
r = user_config_home(dir);
else
r = user_runtime_dir(dir);
if (r == 0)
return -ENOENT;
return r;
}
if (mode == UNIT_PERSISTENT && !transient)
*dir = strdup("/etc/systemd/system");
else
*dir = strdup("/run/systemd/system");
if (!*dir)
return -ENOMEM;
return 0;
}
int unit_write_drop_in(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
_cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL;
int r;
assert(u);
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
r = unit_drop_in_dir(u, mode, u->transient, &dir);
if (r < 0)
return r;
r = write_drop_in(dir, u->id, 50, name, data);
if (r < 0)
return r;
r = drop_in_file(dir, u->id, 50, name, &p, &q);
if (r < 0)
return r;
r = strv_extend(&u->dropin_paths, q);
if (r < 0)
return r;
strv_sort(u->dropin_paths);
strv_uniq(u->dropin_paths);
u->dropin_mtime = now(CLOCK_REALTIME);
return 0;
}
int unit_write_drop_in_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
assert(u);
assert(name);
assert(format);
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return unit_write_drop_in(u, mode, name, p);
}
int unit_write_drop_in_private(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *data) {
_cleanup_free_ char *ndata = NULL;
assert(u);
assert(name);
assert(data);
if (!UNIT_VTABLE(u)->private_section)
return -EINVAL;
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
ndata = strjoin("[", UNIT_VTABLE(u)->private_section, "]\n", data, NULL);
if (!ndata)
return -ENOMEM;
return unit_write_drop_in(u, mode, name, ndata);
}
int unit_write_drop_in_private_format(Unit *u, UnitSetPropertiesMode mode, const char *name, const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
assert(u);
assert(name);
assert(format);
if (!IN_SET(mode, UNIT_PERSISTENT, UNIT_RUNTIME))
return 0;
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return unit_write_drop_in_private(u, mode, name, p);
}
int unit_make_transient(Unit *u) {
assert(u);
if (!UNIT_VTABLE(u)->can_transient)
return -EOPNOTSUPP;
u->load_state = UNIT_STUB;
u->load_error = 0;
u->transient = true;
u->fragment_path = mfree(u->fragment_path);
return 0;
}
int unit_kill_context(
Unit *u,
KillContext *c,
KillOperation k,
pid_t main_pid,
pid_t control_pid,
bool main_pid_alien) {
bool wait_for_exit = false;
int sig, r;
assert(u);
assert(c);
if (c->kill_mode == KILL_NONE)
return 0;
switch (k) {
case KILL_KILL:
sig = SIGKILL;
break;
case KILL_ABORT:
sig = SIGABRT;
break;
case KILL_TERMINATE:
sig = c->kill_signal;
break;
default:
assert_not_reached("KillOperation unknown");
}
if (main_pid > 0) {
r = kill_and_sigcont(main_pid, sig);
if (r < 0 && r != -ESRCH) {
_cleanup_free_ char *comm = NULL;
get_process_comm(main_pid, &comm);
log_unit_warning_errno(u, r, "Failed to kill main process " PID_FMT " (%s), ignoring: %m", main_pid, strna(comm));
} else {
if (!main_pid_alien)
wait_for_exit = true;
if (c->send_sighup && k == KILL_TERMINATE)
(void) kill(main_pid, SIGHUP);
}
}
if (control_pid > 0) {
r = kill_and_sigcont(control_pid, sig);
if (r < 0 && r != -ESRCH) {
_cleanup_free_ char *comm = NULL;
get_process_comm(control_pid, &comm);
log_unit_warning_errno(u, r, "Failed to kill control process " PID_FMT " (%s), ignoring: %m", control_pid, strna(comm));
} else {
wait_for_exit = true;
if (c->send_sighup && k == KILL_TERMINATE)
(void) kill(control_pid, SIGHUP);
}
}
if (u->cgroup_path &&
(c->kill_mode == KILL_CONTROL_GROUP || (c->kill_mode == KILL_MIXED && k == KILL_KILL))) {
_cleanup_set_free_ Set *pid_set = NULL;
/* Exclude the main/control pids from being killed via the cgroup */
pid_set = unit_pid_set(main_pid, control_pid);
if (!pid_set)
return -ENOMEM;
r = cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, sig, true, k != KILL_TERMINATE, false, pid_set);
if (r < 0) {
if (r != -EAGAIN && r != -ESRCH && r != -ENOENT)
log_unit_warning_errno(u, r, "Failed to kill control group %s, ignoring: %m", u->cgroup_path);
} else if (r > 0) {
/* FIXME: For now, on the legacy hierarchy, we
* will not wait for the cgroup members to die
* if we are running in a container or if this
* is a delegation unit, simply because cgroup
* notification is unreliable in these
* cases. It doesn't work at all in
* containers, and outside of containers it
* can be confused easily by left-over
* directories in the cgroup -- which however
* should not exist in non-delegated units. On
* the unified hierarchy that's different,
* there we get proper events. Hence rely on
* them.*/
if (cg_unified() > 0 ||
(detect_container() == 0 && !unit_cgroup_delegate(u)))
wait_for_exit = true;
if (c->send_sighup && k != KILL_KILL) {
set_free(pid_set);
pid_set = unit_pid_set(main_pid, control_pid);
if (!pid_set)
return -ENOMEM;
cg_kill_recursive(SYSTEMD_CGROUP_CONTROLLER, u->cgroup_path, SIGHUP, false, true, false, pid_set);
}
}
}
return wait_for_exit;
}
int unit_require_mounts_for(Unit *u, const char *path) {
char prefix[strlen(path) + 1], *p;
int r;
assert(u);
assert(path);
/* Registers a unit for requiring a certain path and all its
* prefixes. We keep a simple array of these paths in the
* unit, since its usually short. However, we build a prefix
* table for all possible prefixes so that new appearing mount
* units can easily determine which units to make themselves a
* dependency of. */
if (!path_is_absolute(path))
return -EINVAL;
p = strdup(path);
if (!p)
return -ENOMEM;
path_kill_slashes(p);
if (!path_is_safe(p)) {
free(p);
return -EPERM;
}
if (strv_contains(u->requires_mounts_for, p)) {
free(p);
return 0;
}
r = strv_consume(&u->requires_mounts_for, p);
if (r < 0)
return r;
PATH_FOREACH_PREFIX_MORE(prefix, p) {
Set *x;
x = hashmap_get(u->manager->units_requiring_mounts_for, prefix);
if (!x) {
char *q;
r = hashmap_ensure_allocated(&u->manager->units_requiring_mounts_for, &string_hash_ops);
if (r < 0)
return r;
q = strdup(prefix);
if (!q)
return -ENOMEM;
x = set_new(NULL);
if (!x) {
free(q);
return -ENOMEM;
}
r = hashmap_put(u->manager->units_requiring_mounts_for, q, x);
if (r < 0) {
free(q);
set_free(x);
return r;
}
}
r = set_put(x, u);
if (r < 0)
return r;
}
return 0;
}
int unit_setup_exec_runtime(Unit *u) {
ExecRuntime **rt;
size_t offset;
Iterator i;
Unit *other;
offset = UNIT_VTABLE(u)->exec_runtime_offset;
assert(offset > 0);
/* Check if there already is an ExecRuntime for this unit? */
rt = (ExecRuntime**) ((uint8_t*) u + offset);
if (*rt)
return 0;
/* Try to get it from somebody else */
SET_FOREACH(other, u->dependencies[UNIT_JOINS_NAMESPACE_OF], i) {
*rt = unit_get_exec_runtime(other);
if (*rt) {
exec_runtime_ref(*rt);
return 0;
}
}
return exec_runtime_make(rt, unit_get_exec_context(u), u->id);
}
bool unit_type_supported(UnitType t) {
if (_unlikely_(t < 0))
return false;
if (_unlikely_(t >= _UNIT_TYPE_MAX))
return false;
if (!unit_vtable[t]->supported)
return true;
return unit_vtable[t]->supported();
}
void unit_warn_if_dir_nonempty(Unit *u, const char* where) {
int r;
assert(u);
assert(where);
r = dir_is_empty(where);
if (r > 0)
return;
if (r < 0) {
log_unit_warning_errno(u, r, "Failed to check directory %s: %m", where);
return;
}
log_struct(LOG_NOTICE,
LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
LOG_UNIT_ID(u),
LOG_UNIT_MESSAGE(u, "Directory %s to mount over is not empty, mounting anyway.", where),
"WHERE=%s", where,
NULL);
}
int unit_fail_if_symlink(Unit *u, const char* where) {
int r;
assert(u);
assert(where);
r = is_symlink(where);
if (r < 0) {
log_unit_debug_errno(u, r, "Failed to check symlink %s, ignoring: %m", where);
return 0;
}
if (r == 0)
return 0;
log_struct(LOG_ERR,
LOG_MESSAGE_ID(SD_MESSAGE_OVERMOUNTING),
LOG_UNIT_ID(u),
LOG_UNIT_MESSAGE(u, "Mount on symlink %s not allowed.", where),
"WHERE=%s", where,
NULL);
return -ELOOP;
}
| Java |
// logs.cpp
//
// Rivendell web service portal -- Log services
//
// (C) Copyright 2013,2016 Fred Gleason <fredg@paravelsystems.com>
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2 as
// published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public
// License along with this program; if not, write to the Free Software
// Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
//
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <rdcreate_log.h>
#include <rddb.h>
#include <rdformpost.h>
#include <rdweb.h>
#include <rdsvc.h>
#include <rduser.h>
#include <rdlog.h>
#include <rdlog_event.h>
#include <rdlog_line.h>
#include <rdconf.h>
#include <rdescape_string.h>
#include <rdxport.h>
void Xport::AddLog()
{
QString log_name;
QString service_name;
//
// Get Arguments
//
if(!xport_post->getValue("LOG_NAME",&log_name)) {
XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("SERVICE_NAME",&service_name)) {
XmlExit("Missing SERVICE_NAME",400,"logs.cpp",LINE_NUMBER);
}
RDSvc *svc=new RDSvc(service_name);
if(!svc->exists()) {
XmlExit("No such service",404,"logs.cpp",LINE_NUMBER);
}
//
// Verify User Perms
//
if(!xport_user->createLog()) {
XmlExit("Unauthorized",404,"logs.cpp",LINE_NUMBER);
}
RDLog *log=new RDLog(log_name);
if(!log->exists()) {
delete log;
log=new RDLog(log_name,true);
if(!log->exists()) {
delete log;
XmlExit("Unable to create log",500,"logs.cpp",LINE_NUMBER);
}
log->setOriginUser(xport_user->name());
log->setDescription("[new log]");
log->setService(service_name);
}
delete log;
RDCreateLogTable(RDLog::tableName(log_name));
XmlExit("OK",200,"logs.cpp",LINE_NUMBER);
}
void Xport::DeleteLog()
{
QString log_name;
//
// Get Arguments
//
if(!xport_post->getValue("LOG_NAME",&log_name)) {
XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER);
}
//
// Verify User Perms
//
if(!xport_user->deleteLog()) {
XmlExit("Unauthorized",404,"logs.cpp",LINE_NUMBER);
}
RDLog *log=new RDLog(log_name);
if(log->exists()) {
if(!log->remove(xport_station,xport_user,xport_config)) {
delete log;
XmlExit("Unable to delete log",500,"logs.cpp",LINE_NUMBER);
}
}
delete log;
XmlExit("OK",200,"logs.cpp",LINE_NUMBER);
}
void Xport::ListLogs()
{
QString sql;
RDSqlQuery *q;
RDLog *log;
QString service_name="";
QString log_name="";
QString trackable;
//
// Get Options
//
xport_post->getValue("SERVICE_NAME",&service_name);
xport_post->getValue("LOG_NAME",&log_name);
xport_post->getValue("TRACKABLE",&trackable);
//
// Generate Log List
//
sql="select NAME from LOGS";
if((!service_name.isEmpty())||(!log_name.isEmpty())||(trackable=="1")) {
sql+=" where";
if(!log_name.isEmpty()) {
sql+=" (NAME=\""+RDEscapeString(log_name)+"\")&&";
}
if(!service_name.isEmpty()) {
sql+=" (SERVICE=\""+RDEscapeString(service_name)+"\")&&";
}
if(trackable=="1") {
sql+=" (SCHEDULED_TRACKS>0)&&";
}
sql=sql.left(sql.length()-2);
}
sql+=" order by NAME";
q=new RDSqlQuery(sql);
//
// Process Request
//
printf("Content-type: application/xml\n");
printf("Status: 200\n\n");
printf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
printf("<logList>\n");
while(q->next()) {
log=new RDLog(q->value(0).toString());
printf("%s",(const char *)log->xml());
delete log;
}
printf("</logList>\n");
delete q;
Exit(0);
}
void Xport::ListLog()
{
RDLog *log;
QString name="";
//
// Get Options
//
xport_post->getValue("NAME",&name);
//
// Verify that log exists
//
log=new RDLog(name);
if(!log->exists()) {
delete log;
XmlExit("No such log",404,"logs.cpp",LINE_NUMBER);
}
//
// Generate Log Listing
//
RDLogEvent *log_event=log->createLogEvent();
log_event->load(true);
//
// Process Request
//
printf("Content-type: application/xml\n");
printf("Status: 200\n\n");
printf("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
printf("%s\n",(const char *)log_event->xml());
Exit(0);
}
void Xport::SaveLog()
{
//
// Verify User Perms
//
if((!xport_user->addtoLog())||(!xport_user->removefromLog())||(!xport_user->arrangeLog())) {
XmlExit("No user privilege",404,"logs.cpp",LINE_NUMBER);
}
QString log_name;
QString service_name;
QString description;
QDate purge_date;
bool auto_refresh;
QDate start_date;
QDate end_date;
int line_quantity;
//
// Header Data
//
if(!xport_post->getValue("LOG_NAME",&log_name)) {
XmlExit("Missing LOG_NAME",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("SERVICE_NAME",&service_name)) {
XmlExit("Missing SERVICE_NAME",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("DESCRIPTION",&description)) {
XmlExit("Missing DESCRIPTION",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("PURGE_DATE",&purge_date)) {
XmlExit("Missing PURGE_DATE",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("AUTO_REFRESH",&auto_refresh)) {
XmlExit("Missing AUTO_REFRESH",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("START_DATE",&start_date)) {
XmlExit("Missing START_DATE",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("END_DATE",&end_date)) {
XmlExit("Missing END_DATE",400,"logs.cpp",LINE_NUMBER);
}
if(!xport_post->getValue("LINE_QUANTITY",&line_quantity)) {
XmlExit("Missing LINE_QUANTITY",400,"logs.cpp",LINE_NUMBER);
}
//
// Logline Data
//
RDLogEvent *logevt=new RDLogEvent(RDLog::tableName(log_name));
for(int i=0;i<line_quantity;i++) {
logevt->insert(i,1);
RDLogLine *ll=logevt->logLine(i);
QString line=QString().sprintf("LINE%d",i);
QString str;
int integer1;
int integer2;
QDateTime datetime;
QTime time;
bool state;
bool ok=false;
if(!xport_post->getValue(line+"_ID",&integer1,&ok)) {
XmlExit("Missing "+line+"_ID",400,"logs.cpp",LINE_NUMBER);
}
if(!ok) {
XmlExit("Invalid "+line+"_ID",400,"logs.cpp",LINE_NUMBER);
}
ll->setId(integer1);
if(!xport_post->getValue(line+"_TYPE",&integer1)) {
XmlExit("Missing "+line+"_TYPE",400,"logs.cpp",LINE_NUMBER);
}
ll->setType((RDLogLine::Type)integer1);
if(!xport_post->getValue(line+"_CART_NUMBER",&integer1)) {
XmlExit("Missing "+line+"_CART_NUMBER",400,"logs.cpp",LINE_NUMBER);
}
ll->setCartNumber(integer1);
if(!xport_post->getValue(line+"_TIME_TYPE",&integer2)) {
XmlExit("Missing "+line+"_TIME_TYPE",400,"logs.cpp",LINE_NUMBER);
}
ll->setTimeType((RDLogLine::TimeType)integer2);
if(!xport_post->getValue(line+"_START_TIME",&integer1)) {
XmlExit("Missing "+line+"_START_TIME",400,"logs.cpp",LINE_NUMBER);
}
if(ll->timeType()==RDLogLine::Hard) {
ll->setStartTime(RDLogLine::Logged,QTime().addMSecs(integer1));
}
else {
ll->setStartTime(RDLogLine::Predicted,QTime().addMSecs(integer1));
}
if(!xport_post->getValue(line+"_GRACE_TIME",&integer1)) {
XmlExit("Missing "+line+"_GRACE_TIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setGraceTime(integer1);
if(!xport_post->getValue(line+"_TRANS_TYPE",&str)) {
XmlExit("Missing "+line+"_TRANS_TYPE",400,"logs.cpp",LINE_NUMBER);
}
integer1=-1;
if(str.lower()=="play") {
integer1=RDLogLine::Play;
}
if(str.lower()=="segue") {
integer1=RDLogLine::Segue;
}
if(str.lower()=="stop") {
integer1=RDLogLine::Stop;
}
if(integer1<0) {
XmlExit("Invalid transition type in "+line+"_TRANS_TYPE",400,
"logs.cpp",LINE_NUMBER);
}
ll->setTransType((RDLogLine::TransType)integer1);
if(!xport_post->getValue(line+"_START_POINT",&integer1)) {
XmlExit("Missing "+line+"_START_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setStartPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_END_POINT",&integer1)) {
XmlExit("Missing "+line+"_END_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setEndPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_SEGUE_START_POINT",&integer1)) {
XmlExit("Missing "+line+"_SEGUE_START_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setSegueStartPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_SEGUE_END_POINT",&integer1)) {
XmlExit("Missing "+line+"_SEGUE_END_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setSegueEndPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_FADEUP_POINT",&integer1)) {
XmlExit("Missing "+line+"_FADEUP_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadeupPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_FADEUP_GAIN",&integer1)) {
XmlExit("Missing "+line+"_FADEUP_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadeupGain(integer1);
if(!xport_post->getValue(line+"_FADEDOWN_POINT",&integer1)) {
XmlExit("Missing "+line+"_FADEDOWN_POINT",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadedownPoint(integer1,RDLogLine::LogPointer);
if(!xport_post->getValue(line+"_FADEDOWN_GAIN",&integer1)) {
XmlExit("Missing "+line+"_FADEDOWN_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setFadedownGain(integer1);
if(!xport_post->getValue(line+"_DUCK_UP_GAIN",&integer1)) {
XmlExit("Missing "+line+"_DUCK_UP_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setDuckUpGain(integer1);
if(!xport_post->getValue(line+"_DUCK_DOWN_GAIN",&integer1)) {
XmlExit("Missing "+line+"_DUCK_DOWN_GAIN",400,"logs.cpp",LINE_NUMBER);
}
ll->setDuckDownGain(integer1);
if(!xport_post->getValue(line+"_COMMENT",&str)) {
XmlExit("Missing "+line+"_COMMENT",400,"logs.cpp",LINE_NUMBER);
}
ll->setMarkerComment(str);
if(!xport_post->getValue(line+"_LABEL",&str)) {
XmlExit("Missing "+line+"_LABEL",400,"logs.cpp",LINE_NUMBER);
}
ll->setMarkerLabel(str);
if(!xport_post->getValue(line+"_ORIGIN_USER",&str)) {
XmlExit("Missing "+line+"_ORIGIN_USER",400,"logs.cpp",LINE_NUMBER);
}
ll->setOriginUser(str);
if(!xport_post->getValue(line+"_ORIGIN_DATETIME",&datetime)) {
XmlExit("Missing "+line+"_ORIGIN_DATETIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setOriginDateTime(datetime);
if(!xport_post->getValue(line+"_EVENT_LENGTH",&integer1)) {
XmlExit("Missing "+line+"_EVENT_LENGTH",400,"logs.cpp",LINE_NUMBER);
}
ll->setEventLength(integer1);
if(!xport_post->getValue(line+"_LINK_EVENT_NAME",&str)) {
XmlExit("Missing "+line+"_LINK_EVENT_NAME",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkEventName(str);
if(!xport_post->getValue(line+"_LINK_START_TIME",&integer1)) {
XmlExit("Missing "+line+"_LINK_START_TIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkStartTime(QTime().addMSecs(integer1));
if(!xport_post->getValue(line+"_LINK_LENGTH",&integer1)) {
XmlExit("Missing "+line+"_LINK_LENGTH",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkLength(integer1);
if(!xport_post->getValue(line+"_LINK_START_SLOP",&integer1)) {
XmlExit("Missing "+line+"_LINK_START_SLOP",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkStartSlop(integer1);
if(!xport_post->getValue(line+"_LINK_END_SLOP",&integer1)) {
XmlExit("Missing "+line+"_LINK_END_SLOP",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkEndSlop(integer1);
if(!xport_post->getValue(line+"_LINK_ID",&integer1)) {
XmlExit("Missing "+line+"_LINK_ID",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkId(integer1);
if(!xport_post->getValue(line+"_LINK_EMBEDDED",&state)) {
XmlExit("Missing "+line+"_LINK_EMBEDDED",400,"logs.cpp",LINE_NUMBER);
}
ll->setLinkEmbedded(state);
if(!xport_post->getValue(line+"_EXT_START_TIME",&time)) {
XmlExit("Missing "+line+"_EXT_START_TIME",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtStartTime(time);
if(!xport_post->getValue(line+"_EXT_CART_NAME",&str)) {
XmlExit("Missing "+line+"_EXT_CART_NAME",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtCartName(str);
if(!xport_post->getValue(line+"_EXT_DATA",&str)) {
XmlExit("Missing "+line+"_EXT_DATA",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtData(str);
if(!xport_post->getValue(line+"_EXT_EVENT_ID",&str)) {
XmlExit("Missing "+line+"_EXT_EVENT_ID",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtEventId(str);
if(!xport_post->getValue(line+"_EXT_ANNC_TYPE",&str)) {
XmlExit("Missing "+line+"_EXT_ANNC_TYPE",400,"logs.cpp",LINE_NUMBER);
}
ll->setExtAnncType(str);
}
RDLog *log=new RDLog(log_name);
if(!log->exists()) {
XmlExit("No such log",404,"logs.cpp",LINE_NUMBER);
}
log->setService(service_name);
log->setDescription(description);
log->setPurgeDate(purge_date);
log->setAutoRefresh(auto_refresh);
log->setStartDate(start_date);
log->setEndDate(end_date);
log->setModifiedDatetime(QDateTime::currentDateTime());
logevt->save();
XmlExit(QString().sprintf("OK Saved %d events",logevt->size()),
200,"logs.cpp",LINE_NUMBER);
}
| Java |
/***************************************************************************
Copyright (C) 2003-2009 Robby Stephenson <robby@periapsis.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) version 3 or any later version *
* accepted by the membership of KDE e.V. (or its successor approved *
* by the membership of KDE e.V.), which shall act as a proxy *
* defined in Section 14 of version 3 of the license. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program. If not, see <http://www.gnu.org/licenses/>. *
* *
***************************************************************************/
// The layout borrows heavily from kmsearchpatternedit.cpp in kmail
// which is authored by Marc Mutz <Marc@Mutz.com> under the GPL
#include "filterdialog.h"
#include "tellico_kernel.h"
#include "document.h"
#include "collection.h"
#include "fieldcompletion.h"
#include "gui/filterrulewidgetlister.h"
#include "gui/filterrulewidget.h"
#include "tellico_debug.h"
#include <KLocalizedString>
#include <KHelpClient>
#include <QGroupBox>
#include <QRadioButton>
#include <QButtonGroup>
#include <QLabel>
#include <QApplication>
#include <QFrame>
#include <QVBoxLayout>
#include <QPushButton>
#include <QLineEdit>
#include <QDialogButtonBox>
using Tellico::FilterDialog;
namespace {
static const int FILTER_MIN_WIDTH = 600;
}
// modal dialog so I don't have to worry about updating stuff
// don't show apply button if not saving, i.e. just modifying existing filter
FilterDialog::FilterDialog(Mode mode_, QWidget* parent_)
: QDialog(parent_), m_filter(nullptr), m_mode(mode_), m_saveFilter(nullptr) {
setModal(true);
setWindowTitle(mode_ == CreateFilter ? i18n("Advanced Filter") : i18n("Modify Filter"));
QVBoxLayout* topLayout = new QVBoxLayout();
setLayout(topLayout);
QDialogButtonBox* buttonBox;
if(mode_ == CreateFilter) {
buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel|QDialogButtonBox::Apply);
} else {
buttonBox = new QDialogButtonBox(QDialogButtonBox::Help|QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
}
m_okButton = buttonBox->button(QDialogButtonBox::Ok);
m_applyButton = buttonBox->button(QDialogButtonBox::Apply);
connect(m_okButton, &QAbstractButton::clicked, this, &FilterDialog::slotOk);
if(m_applyButton) {
connect(m_applyButton, &QAbstractButton::clicked, this, &FilterDialog::slotApply);
}
connect(buttonBox, &QDialogButtonBox::accepted, this, &QDialog::accept);
connect(buttonBox, &QDialogButtonBox::rejected, this, &QDialog::reject);
connect(buttonBox, &QDialogButtonBox::helpRequested, this, &FilterDialog::slotHelp);
QGroupBox* m_matchGroup = new QGroupBox(i18n("Filter Criteria"), this);
QVBoxLayout* vlay = new QVBoxLayout(m_matchGroup);
topLayout->addWidget(m_matchGroup);
m_matchGroup->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Fixed);
m_matchAll = new QRadioButton(i18n("Match a&ll of the following"), m_matchGroup);
m_matchAny = new QRadioButton(i18n("Match an&y of the following"), m_matchGroup);
m_matchAll->setChecked(true);
vlay->addWidget(m_matchAll);
vlay->addWidget(m_matchAny);
QButtonGroup* bg = new QButtonGroup(m_matchGroup);
bg->addButton(m_matchAll);
bg->addButton(m_matchAny);
#if (QT_VERSION < QT_VERSION_CHECK(5, 15, 0))
void (QButtonGroup::* buttonClicked)(int) = &QButtonGroup::buttonClicked;
connect(bg, buttonClicked, this, &FilterDialog::slotFilterChanged);
#else
connect(bg, &QButtonGroup::idClicked, this, &FilterDialog::slotFilterChanged);
#endif
m_ruleLister = new FilterRuleWidgetLister(m_matchGroup);
connect(m_ruleLister, &KWidgetLister::widgetRemoved, this, &FilterDialog::slotShrink);
connect(m_ruleLister, &FilterRuleWidgetLister::signalModified, this, &FilterDialog::slotFilterChanged);
m_ruleLister->setFocus();
vlay->addWidget(m_ruleLister);
QHBoxLayout* blay = new QHBoxLayout();
topLayout->addLayout(blay);
QLabel* lab = new QLabel(i18n("Filter name:"), this);
blay->addWidget(lab);
m_filterName = new QLineEdit(this);
blay->addWidget(m_filterName);
connect(m_filterName, &QLineEdit::textChanged, this, &FilterDialog::slotFilterChanged);
// only when creating a new filter can it be saved
if(m_mode == CreateFilter) {
m_saveFilter = new QPushButton(QIcon::fromTheme(QStringLiteral("view-filter")), i18n("&Save Filter"), this);
blay->addWidget(m_saveFilter);
m_saveFilter->setEnabled(false);
connect(m_saveFilter, &QAbstractButton::clicked, this, &FilterDialog::slotSaveFilter);
m_applyButton->setEnabled(false);
}
m_okButton->setEnabled(false); // disable at start
buttonBox->button(QDialogButtonBox::Cancel)->setDefault(true);
setMinimumWidth(qMax(minimumWidth(), FILTER_MIN_WIDTH));
topLayout->addWidget(buttonBox);
}
Tellico::FilterPtr FilterDialog::currentFilter(bool alwaysCreateNew_) {
FilterPtr newFilter(new Filter(Filter::MatchAny));
if(m_matchAll->isChecked()) {
newFilter->setMatch(Filter::MatchAll);
} else {
newFilter->setMatch(Filter::MatchAny);
}
foreach(QWidget* widget, m_ruleLister->widgetList()) {
FilterRuleWidget* rw = static_cast<FilterRuleWidget*>(widget);
FilterRule* rule = rw->rule();
if(rule && !rule->isEmpty()) {
newFilter->append(rule);
} else {
delete rule;
}
}
newFilter->setName(m_filterName->text());
if(!m_filter || !alwaysCreateNew_) {
m_filter = newFilter;
}
return newFilter;
}
void FilterDialog::setFilter(Tellico::FilterPtr filter_) {
if(!filter_) {
slotClear();
return;
}
if(filter_->op() == Filter::MatchAll) {
m_matchAll->setChecked(true);
} else {
m_matchAny->setChecked(true);
}
m_ruleLister->setFilter(filter_);
m_filterName->setText(filter_->name());
m_filter = filter_;
}
void FilterDialog::slotOk() {
slotApply();
accept();
}
void FilterDialog::slotApply() {
emit signalUpdateFilter(currentFilter());
}
void FilterDialog::slotHelp() {
KHelpClient::invokeHelp(QStringLiteral("filter-dialog"));
}
void FilterDialog::slotClear() {
// myDebug();
m_matchAll->setChecked(true);
m_ruleLister->reset();
m_filterName->clear();
}
void FilterDialog::slotShrink() {
updateGeometry();
QApplication::sendPostedEvents();
resize(width(), sizeHint().height());
}
void FilterDialog::slotFilterChanged() {
const bool hadFilter = m_filter && !m_filter->isEmpty();
const bool emptyFilter = currentFilter(true)->isEmpty();
// an empty filter can be ok if the filter was originally not empty
const bool enableOk = !currentFilter()->isEmpty() || hadFilter;
if(m_saveFilter) {
m_saveFilter->setEnabled(!m_filterName->text().isEmpty() && !emptyFilter);
if(m_applyButton) {
m_applyButton->setEnabled(!emptyFilter);
}
}
if(m_applyButton) {
m_applyButton->setEnabled(enableOk);
}
m_okButton->setEnabled(enableOk);
m_okButton->setDefault(enableOk);
}
void FilterDialog::slotSaveFilter() {
// non-op if editing an existing filter
if(m_mode != CreateFilter) {
return;
}
// in this case, currentFilter() either creates a new filter or
// updates the current one. If creating a new one, then I want to copy it
const bool wasEmpty = !m_filter;
FilterPtr filter(new Filter(*currentFilter()));
if(wasEmpty) {
m_filter = filter;
}
// this keeps the saving completely decoupled from the filter setting in the detailed view
if(filter->isEmpty()) {
m_filter = FilterPtr();
return;
}
Kernel::self()->addFilter(filter);
}
| Java |
<?php
/**
* @Project NUKEVIET 4.x
* @Author VINADES.,JSC (contact@vinades.vn)
* @Copyright (C) 2014 VINADES.,JSC. All rights reserved
* @Language Tiếng Việt
* @License CC BY-SA (http://creativecommons.org/licenses/by-sa/4.0/)
* @Createdate Mar 04, 2010, 03:22:00 PM
*/
if (!defined('NV_ADMIN') or !defined('NV_MAINFILE')) {
die('Stop!!!');
}
$lang_translator['author'] = 'VINADES.,JSC (contact@vinades.vn)';
$lang_translator['createdate'] = '04/03/2010, 15:22';
$lang_translator['copyright'] = '@Copyright (C) 2012 VINADES.,JSC. All rights reserved';
$lang_translator['info'] = '';
$lang_translator['langtype'] = 'lang_module';
$lang_module['is_suspend0'] = 'Hoạt động';
$lang_module['is_suspend1'] = 'Bị đình chỉ vào “%1$s” bởi “%2$s” với lý do “%3$s”';
$lang_module['is_suspend2'] = 'Bị đình chỉ';
$lang_module['last_login0'] = 'Chưa bao giờ';
$lang_module['login'] = 'Tên tài khoản';
$lang_module['email'] = 'Email';
$lang_module['full_name'] = 'Tên gọi trên site';
$lang_module['name'] = 'Tên gọi trên site';
$lang_module['sig'] = 'Chữ ký';
$lang_module['editor'] = 'Trình soạn thảo';
$lang_module['lev'] = 'Quyền hạn';
$lang_module['position'] = 'Chức danh';
$lang_module['regtime'] = 'Ngày tham gia';
$lang_module['is_suspend'] = 'Tình trạng hiện tại';
$lang_module['last_login'] = 'Lần đăng nhập gần đây';
$lang_module['last_ip'] = 'Bằng IP';
$lang_module['browser'] = 'Bằng trình duyệt';
$lang_module['os'] = 'Bằng hệ điều hành';
$lang_module['admin_info_title1'] = 'Thông tin tài khoản: %s';
$lang_module['admin_info_title2'] = 'Thông tin tài khoản: %s (là bạn)';
$lang_module['menulist'] = 'Danh sách Quản trị';
$lang_module['menuadd'] = 'Thêm Quản trị';
$lang_module['main'] = 'Danh sách Quản trị website';
$lang_module['nv_admin_edit'] = 'Sửa thông tin Quản trị website';
$lang_module['nv_admin_add'] = 'Thêm Quản trị website';
$lang_module['nv_admin_del'] = 'Xóa Quản trị website';
$lang_module['username_noactive'] = 'Lỗi: tài khoản: %s chưa được kích hoạt, bạn cần kích hoạt tài khoản này trước khi thêm vào quản trị site';
$lang_module['full_name_incorrect'] = 'Bạn chưa khai báo tên gọi của người quản trị này';
$lang_module['position_incorrect'] = 'Bạn chưa khai báo chức danh của người quản trị này';
$lang_module['nv_admin_add_info'] = 'Để tạo một tài khoản Quản trị website mới, bạn cần khai báo đầy đủ vào các ô trống dưới đây. Bạn chỉ có quyền tạo tài khoản Quản trị dưới cấp của mình';
$lang_module['if_level3_selected'] = 'Hãy đánh dấu tích vào những module mà bạn cho phép quản lý';
$lang_module['login_info'] = 'Bạn cần nhập tên thành viên, nếu chưa có thành viên bạn cần tạo thành viên trước.';
$lang_module['nv_admin_add_result'] = 'Thông tin về Quản trị website mới';
$lang_module['nv_admin_add_title'] = 'Hệ thống đã tạo thành công tài khoản Quản trị website mới với những thông tin dưới đây';
$lang_module['nv_admin_modules'] = 'Quản lý các module';
$lang_module['admin_account_info'] = 'Thông tin tài khoản Quản trị website %s';
$lang_module['nv_admin_add_download'] = 'Tải về';
$lang_module['nv_admin_add_sendmail'] = 'Gửi thông báo';
$lang_module['nv_admin_login_address'] = 'URL trang quản lý website';
$lang_module['nv_admin_edit_info'] = 'Thay đổi thông tin tài khoản “<strong>%s</strong>”';
$lang_module['show_mail'] = 'Hiển thị email';
$lang_module['sig_info'] = 'Chữ ký được chèn vào cuối mỗi bài trả lời, thư... được gửi đi từ tài khoản Quản trị “<strong>%s</strong>”. Chỉ chấp nhận dạng text đơn thuần';
$lang_module['not_use'] = 'Không sử dụng';
$lang_module['nv_admin_edit_result'] = 'Thay đổi thông tin tài khoản Quản trị: %s';
$lang_module['nv_admin_edit_result_title'] = 'Những thay đổi vừa được thực hiện đối với tài khoản Quản trị %s';
$lang_module['show_mail0'] = 'Không hiển thị';
$lang_module['show_mail1'] = 'Hiển thị';
$lang_module['field'] = 'tiêu chí';
$lang_module['old_value'] = 'Cũ';
$lang_module['new_value'] = 'Mới';
$lang_module['chg_is_suspend0'] = 'Tình trạng hiện tại: Đang bị đình chỉ. Để Khôi phục hoạt động của tài khoản quản trị này, bạn hãy khai báo vào các ô trống dưới đây';
$lang_module['chg_is_suspend1'] = 'Tình trạng hiện tại: Đang hoạt động. Để Đình chỉ hoạt động của tài khoản quản trị này, bạn hãy khai báo vào các ô trống dưới đây';
$lang_module['chg_is_suspend2'] = 'Khôi phục/Đình chỉ hoạt động';
$lang_module['nv_admin_chg_suspend'] = 'Thay đổi trạng thái hoạt động của tài khoản Quản trị “<strong>%s</strong>”';
$lang_module['position_info'] = 'Chức danh dùng trong các hoạt động đối ngoại như trao đổi thư từ, viết lời bình...';
$lang_module['susp_reason_empty'] = 'Bạn chưa khai báo lý do đình chỉ hoạt động của tài khoản Quản trị “<strong>%s</strong>”';
$lang_module['suspend_info_empty'] = 'Tài khoản quản trị “<strong>%s</strong>” chưa bị đình chỉ hoạt động lần nào';
$lang_module['suspend_info_yes'] = 'Danh sách các lần đình chỉ hoạt động của tài khoản quản trị “<strong>%s</strong>”';
$lang_module['suspend_start'] = 'Bắt đầu';
$lang_module['suspend_end'] = 'Kết thúc';
$lang_module['suspend_reason'] = 'Lý do đình chỉ';
$lang_module['suspend_info'] = 'Vào: %1$s<br />Bởi: %2$s';
$lang_module['suspend0'] = 'Khôi phục hoạt động';
$lang_module['suspend1'] = 'Đình chỉ hoạt động';
$lang_module['clean_history'] = 'Xóa lịch sử';
$lang_module['suspend_sendmail'] = 'Gửi thông báo';
$lang_module['suspend_sendmail_mess1'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị đình chỉ hoạt động vào %2$s vì lý do: %3$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %4$s';
$lang_module['suspend_sendmail_mess0'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã hoạt động trở lại vào %2$s.<br />Trước đó tài khoản này đã bị đình chỉ hoạt động vì lý do: %3$s';
$lang_module['suspend_sendmail_title'] = 'Thông báo từ website %s';
$lang_module['delete_sendmail_mess0'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị xóa vào %2$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %3$s';
$lang_module['delete_sendmail_mess1'] = 'Ban quản trị website %1$s xin thông báo:<br />Tài khoản quản trị của bạn tại website %1$s đã bị xóa vào %2$s vì lý do: %3$s.<br />Mọi đề nghị, thắc mắc... xin gửi đến địa chỉ %4$s';
$lang_module['delete_sendmail_title'] = 'Thông báo từ website %s';
$lang_module['delete_sendmail_info'] = 'Bạn thực sự muốn xóa tài khoản quản trị “<strong>%s</strong>”? Hãy điền các thông tin vào các ô trống dưới đây để khẳng định thao tác này';
$lang_module['admin_del_sendmail'] = 'Gửi thông báo';
$lang_module['admin_del_reason'] = 'Lý do xóa';
$lang_module['allow_files_type'] = 'Các kiểu file được phép tải lên';
$lang_module['allow_modify_files'] = 'Được phép sửa, xóa files';
$lang_module['allow_create_subdirectories'] = 'Được phép tạo thư mục';
$lang_module['allow_modify_subdirectories'] = 'Được phép đổi tên, xóa thư mục';
$lang_module['admin_login_incorrect'] = 'Tài khoản “<strong>%s</strong>” đã có trong danh sách quản trị. Hãy sử dụng một tài khoản khác';
$lang_module['config'] = 'Cấu hình';
$lang_module['funcs'] = 'Chức năng';
$lang_module['checkall'] = 'Chọn tất cả';
$lang_module['uncheckall'] = 'Bỏ chọn tất cả';
$lang_module['ip_version'] = 'Loại IP';
$lang_module['adminip'] = 'Quản lý IP truy cập khu vực quản trị';
$lang_module['adminip_ip'] = 'Ip';
$lang_module['adminip_timeban'] = 'Thời gian bắt đầu';
$lang_module['adminip_timeendban'] = 'Thời gian kết thúc';
$lang_module['adminip_add'] = 'Thêm địa chỉ IP';
$lang_module['adminip_address'] = 'Địa chỉ';
$lang_module['adminip_begintime'] = 'Thời gian bắt đầu';
$lang_module['adminip_endtime'] = 'Thời gian kết thúc';
$lang_module['adminip_notice'] = 'Ghi chú';
$lang_module['save'] = 'Lưu thay đổi';
$lang_module['adminip_mask_select'] = 'Hãy chọn';
$lang_module['adminip_nolimit'] = 'Vô thời hạn';
$lang_module['adminip_del_success'] = 'Đã xóa thành công !';
$lang_module['adminip_delete_confirm'] = 'Bạn có chắc muốn xóa ip này ra khỏi danh sách?';
$lang_module['adminip_mask'] = 'Mask IP';
$lang_module['adminip_edit'] = 'Sửa địa chỉ IP';
$lang_module['adminip_delete'] = 'Xóa';
$lang_module['adminip_error_ip'] = 'Hãy nhập Ip được truy cập khu vực quản trị ';
$lang_module['adminip_error_validip'] = 'Lỗi: Bạn cần nhập IP đúng chuẩn';
$lang_module['title_username'] = 'Quản lý tài khoản tường lửa khu vực admin';
$lang_module['admfirewall'] = 'Kiểm tra tường lửa cho khu vực admin';
$lang_module['block_admin_ip'] = 'Kiểm tra IP khi truy cập khu vực admin';
$lang_module['username_add'] = 'Thêm tài khoản';
$lang_module['username_edit'] = 'Sửa tài khoản';
$lang_module['nicknam_delete_confirm'] = 'Bạn có chắc muốn xóa tài khoản này ra khỏi danh sách?';
$lang_module['passwordsincorrect'] = 'Mật khẩu bạn nhập hai lần không giống nhau.';
$lang_module['nochangepass'] = 'Nếu không thay đổi mật khẩu bạn không nhập hai trường mật khẩu';
$lang_module['rule_user'] = 'Tài khoản chỉ dùng các ký tự a-zA-Z0-9_-';
$lang_module['rule_pass'] = 'Mật khẩu chỉ dùng các ký tự a-zA-Z0-9_-';
$lang_module['spadmin_add_admin'] = 'Cho phép người điều hành chung tạo và thay đổi quyền hạn người điều hành modules';
$lang_module['authors_detail_main'] = 'Hiển thị chi tiết các thông tin tài khoản của người quản trị';
$lang_module['admin_check_pass_time'] = 'Thời gian kiểm tra lại mật khẩu, nếu admin không sử dụng trình duyệt';
$lang_module['add_user'] = 'Chỉ định thành viên';
$lang_module['add_select'] = 'Chọn';
$lang_module['add_error_choose'] = 'Lỗi: Bạn chưa chọn thành viên được chỉ định làm quản trị';
$lang_module['add_error_exist'] = 'Lỗi: Thành viên này đã là quản trị';
$lang_module['add_error_notexist'] = 'Lỗi: Thành viên này không tồn tại';
$lang_module['add_error_diff'] = 'Xảy ra lỗi không xác định';
$lang_module['action_account'] = 'Tài khoản thành viên';
$lang_module['action_account_nochange'] = 'Giữ nguyên tài khoản thành viên';
$lang_module['action_account_suspend'] = 'Khóa tài khoản thành viên';
$lang_module['action_account_del'] = 'Xóa tài khoản thành viên';
$lang_module['module_admin'] = 'Phân quyền hệ thống';
$lang_module['users'] = 'Tài khoản';
$lang_module['number'] = 'STT';
$lang_module['module'] = 'Tên module';
$lang_module['custom_title'] = 'Tiêu đề';
$lang_module['main_module'] = 'Module trang chính';
$lang_module['themeadmin'] = 'Giao diện người quản trị';
$lang_module['theme_default'] = 'Mặc định theo cấu hình site';
$lang_module['2step_manager'] = 'Quản lý xác thực hai bước';
$lang_module['2step_code_off'] = 'Xác thực hai bước bằng ứng dụng đang tắt';
$lang_module['2step_code_on'] = 'Xác thực hai bước bằng ứng dụng đang bật';
$lang_module['2step_oauth'] = 'Xác thực hai bước bằng Oauth';
$lang_module['2step_oauth_gate'] = 'Cổng Oauth';
$lang_module['2step_oauth_email'] = 'Email sử dụng';
$lang_module['2step_oauth_empty'] = 'Chưa có tài khoản xác thực nào';
$lang_module['2step_add_google'] = 'Thêm tài khoản Google';
$lang_module['2step_add_facebook'] = 'Thêm tài khoản Facebook';
$lang_module['2step_delete_all'] = 'Gỡ tất cả';
$lang_module['2step_error_oauth_exists'] = 'Tài khoản này đã có trong danh sách xác thực';
$lang_module['2step_addtime'] = 'Thêm lúc';
| Java |
/* -*- c++ -*- ----------------------------------------------------------
LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator
http://lammps.sandia.gov, Sandia National Laboratories
Steve Plimpton, sjplimp@sandia.gov
Copyright (2003) Sandia Corporation. Under the terms of Contract
DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains
certain rights in this software. This software is distributed under
the GNU General Public License.
See the README file in the top-level LAMMPS directory.
------------------------------------------------------------------------- */
#ifndef LMP_KSPACE_H
#define LMP_KSPACE_H
#include "pointers.h" // IWYU pragma: export
#ifdef FFT_SINGLE
typedef float FFT_SCALAR;
#define MPI_FFT_SCALAR MPI_FLOAT
#else
typedef double FFT_SCALAR;
#define MPI_FFT_SCALAR MPI_DOUBLE
#endif
namespace LAMMPS_NS {
class KSpace : protected Pointers {
friend class ThrOMP;
friend class FixOMP;
public:
double energy; // accumulated energies
double energy_1,energy_6;
double virial[6]; // accumulated virial
double *eatom,**vatom; // accumulated per-atom energy/virial
double e2group; // accumulated group-group energy
double f2group[3]; // accumulated group-group force
int triclinic_support; // 1 if supports triclinic geometries
int ewaldflag; // 1 if a Ewald solver
int pppmflag; // 1 if a PPPM solver
int msmflag; // 1 if a MSM solver
int dispersionflag; // 1 if a LJ/dispersion solver
int tip4pflag; // 1 if a TIP4P solver
int dipoleflag; // 1 if a dipole solver
int spinflag; // 1 if a spin solver
int differentiation_flag;
int neighrequest_flag; // used to avoid obsolete construction
// of neighbor lists
int mixflag; // 1 if geometric mixing rules are enforced
// for LJ coefficients
int slabflag;
int scalar_pressure_flag; // 1 if using MSM fast scalar pressure
double slab_volfactor;
int warn_nonneutral; // 0 = error if non-neutral system
// 1 = warn once if non-neutral system
// 2 = warn, but already warned
int warn_nocharge; // 0 = already warned
// 1 = warn if zero charge
int order,order_6,order_allocated;
double accuracy; // accuracy of KSpace solver (force units)
double accuracy_absolute; // user-specified accuracy in force units
double accuracy_relative; // user-specified dimensionless accuracy
// accurary = acc_rel * two_charge_force
double accuracy_real_6; // real space accuracy for
// dispersion solver (force units)
double accuracy_kspace_6; // reciprocal space accuracy for
// dispersion solver (force units)
int auto_disp_flag; // use automatic parameter generation for pppm/disp
double two_charge_force; // force in user units of two point
// charges separated by 1 Angstrom
double g_ewald,g_ewald_6;
int nx_pppm,ny_pppm,nz_pppm; // global FFT grid for Coulombics
int nx_pppm_6,ny_pppm_6,nz_pppm_6; // global FFT grid for dispersion
int nx_msm_max,ny_msm_max,nz_msm_max;
int group_group_enable; // 1 if style supports group/group calculation
// KOKKOS host/device flag and data masks
ExecutionSpace execution_space;
unsigned int datamask_read,datamask_modify;
int copymode;
int compute_flag; // 0 if skip compute()
int fftbench; // 0 if skip FFT timing
int collective_flag; // 1 if use MPI collectives for FFT/remap
int stagger_flag; // 1 if using staggered PPPM grids
double splittol; // tolerance for when to truncate splitting
KSpace(class LAMMPS *);
virtual ~KSpace();
void two_charge();
void triclinic_check();
void modify_params(int, char **);
void *extract(const char *);
void compute_dummy(int, int);
// triclinic
void x2lamdaT(double *, double *);
void lamda2xT(double *, double *);
void lamda2xvector(double *, double *);
void kspacebbox(double, double *);
// public so can be called by commands that change charge
void qsum_qsq(int warning_flag = 1);
// general child-class methods
virtual void settings(int, char **) {};
virtual void init() = 0;
virtual void setup() = 0;
virtual void setup_grid() {};
virtual void compute(int, int) = 0;
virtual void compute_group_group(int, int, int) {};
virtual void pack_forward(int, FFT_SCALAR *, int, int *) {};
virtual void unpack_forward(int, FFT_SCALAR *, int, int *) {};
virtual void pack_reverse(int, FFT_SCALAR *, int, int *) {};
virtual void unpack_reverse(int, FFT_SCALAR *, int, int *) {};
virtual int timing(int, double &, double &) {return 0;}
virtual int timing_1d(int, double &) {return 0;}
virtual int timing_3d(int, double &) {return 0;}
virtual int modify_param(int, char **) {return 0;}
virtual double memory_usage() {return 0.0;}
/* ----------------------------------------------------------------------
compute gamma for MSM and pair styles
see Eq 4 from Parallel Computing 35 (2009) 164-177
------------------------------------------------------------------------- */
double gamma(const double &rho) const
{
if (rho <= 1.0) {
const int split_order = order/2;
const double rho2 = rho*rho;
double g = gcons[split_order][0];
double rho_n = rho2;
for (int n = 1; n <= split_order; n++) {
g += gcons[split_order][n]*rho_n;
rho_n *= rho2;
}
return g;
} else return (1.0/rho);
}
/* ----------------------------------------------------------------------
compute the derivative of gamma for MSM and pair styles
see Eq 4 from Parallel Computing 35 (2009) 164-177
------------------------------------------------------------------------- */
double dgamma(const double &rho) const
{
if (rho <= 1.0) {
const int split_order = order/2;
const double rho2 = rho*rho;
double dg = dgcons[split_order][0]*rho;
double rho_n = rho*rho2;
for (int n = 1; n < split_order; n++) {
dg += dgcons[split_order][n]*rho_n;
rho_n *= rho2;
}
return dg;
} else return (-1.0/rho/rho);
}
double **get_gcons() { return gcons; }
double **get_dgcons() { return dgcons; }
protected:
int gridflag,gridflag_6;
int gewaldflag,gewaldflag_6;
int minorder,overlap_allowed;
int adjust_cutoff_flag;
int suffix_flag; // suffix compatibility flag
bigint natoms_original;
double scale,qqrd2e;
double qsum,qsqsum,q2;
double **gcons,**dgcons; // accumulated per-atom energy/virial
int evflag,evflag_atom;
int eflag_either,eflag_global,eflag_atom;
int vflag_either,vflag_global,vflag_atom;
int maxeatom,maxvatom;
int kewaldflag; // 1 if kspace range set for Ewald sum
int kx_ewald,ky_ewald,kz_ewald; // kspace settings for Ewald sum
void pair_check();
void ev_init(int eflag, int vflag, int alloc = 1) {
if (eflag||vflag) ev_setup(eflag, vflag, alloc);
else evflag = eflag_either = eflag_global = eflag_atom = vflag_either = vflag_global = vflag_atom = 0;
}
void ev_setup(int, int, int alloc = 1);
double estimate_table_accuracy(double, double);
};
}
#endif
/* ERROR/WARNING messages:
E: KSpace style does not yet support triclinic geometries
The specified kspace style does not allow for non-orthogonal
simulation boxes.
E: KSpace solver requires a pair style
No pair style is defined.
E: KSpace style is incompatible with Pair style
Setting a kspace style requires that a pair style with matching
long-range Coulombic or dispersion components be used.
W: Using kspace solver on system with no charge
Self-explanatory.
E: System is not charge neutral, net charge = %g
The total charge on all atoms on the system is not 0.0.
For some KSpace solvers this is an error.
W: System is not charge neutral, net charge = %g
The total charge on all atoms on the system is not 0.0.
For some KSpace solvers this is only a warning.
W: For better accuracy use 'pair_modify table 0'
The user-specified force accuracy cannot be achieved unless the table
feature is disabled by using 'pair_modify table 0'.
E: Illegal ... command
Self-explanatory. Check the input script syntax and compare to the
documentation for the command. You can use -echo screen as a
command-line option when running LAMMPS to see the offending line.
E: Bad kspace_modify slab parameter
Kspace_modify value for the slab/volume keyword must be >= 2.0.
E: Kspace_modify mesh parameter must be all zero or all positive
Valid kspace mesh parameters are >0. The code will try to auto-detect
suitable values when all three mesh sizes are set to zero (the default).
E: Kspace_modify mesh/disp parameter must be all zero or all positive
Valid kspace mesh/disp parameters are >0. The code will try to auto-detect
suitable values when all three mesh sizes are set to zero [and]
the required accuracy via {force/disp/real} as well as
{force/disp/kspace} is set.
W: Kspace_modify slab param < 2.0 may cause unphysical behavior
The kspace_modify slab parameter should be larger to insure periodic
grids padded with empty space do not overlap.
E: Bad kspace_modify kmax/ewald parameter
Kspace_modify values for the kmax/ewald keyword must be integers > 0
E: Kspace_modify eigtol must be smaller than one
Self-explanatory.
*/
| Java |
// Copyright 2013 Dolphin Emulator Project
// Licensed under GPLv2
// Refer to the license.txt file included.
#include <cstddef>
#include <string>
#include <vector>
#include <wx/chartype.h>
#include <wx/defs.h>
#include <wx/dynarray.h>
#include <wx/event.h>
#include <wx/frame.h>
#include <wx/gdicmn.h>
#include <wx/list.h>
#include <wx/menu.h>
#include <wx/menuitem.h>
#include <wx/msgdlg.h>
#include <wx/object.h>
#include <wx/panel.h>
#include <wx/rtti.h>
#include <wx/sizer.h>
#include <wx/statusbr.h>
#include <wx/string.h>
#include <wx/textdlg.h>
#include <wx/toplevel.h>
#include <wx/translation.h>
#include <wx/window.h>
#include <wx/windowid.h>
#include <wx/aui/auibar.h>
#include <wx/aui/auibook.h>
#include <wx/aui/framemanager.h>
#include "Common/CommonTypes.h"
#include "Common/FileUtil.h"
#include "Common/IniFile.h"
#include "Common/MathUtil.h"
#include "Common/StringUtil.h"
#include "Common/Logging/ConsoleListener.h"
#include "Core/ConfigManager.h"
#include "DolphinWX/Frame.h"
#include "DolphinWX/Globals.h"
#include "DolphinWX/LogConfigWindow.h"
#include "DolphinWX/LogWindow.h"
#include "DolphinWX/WxUtils.h"
#include "DolphinWX/Debugger/CodeWindow.h"
// ------------
// Aui events
void CFrame::OnManagerResize(wxAuiManagerEvent& event)
{
if (!g_pCodeWindow && m_LogWindow &&
m_Mgr->GetPane("Pane 1").IsShown() &&
!m_Mgr->GetPane("Pane 1").IsFloating())
{
m_LogWindow->x = m_Mgr->GetPane("Pane 1").rect.GetWidth();
m_LogWindow->y = m_Mgr->GetPane("Pane 1").rect.GetHeight();
m_LogWindow->winpos = m_Mgr->GetPane("Pane 1").dock_direction;
}
event.Skip();
}
void CFrame::OnPaneClose(wxAuiManagerEvent& event)
{
event.Veto();
wxAuiNotebook * nb = (wxAuiNotebook*)event.pane->window;
if (!nb) return;
if (!g_pCodeWindow)
{
if (nb->GetPage(0)->GetId() == IDM_LOGWINDOW ||
nb->GetPage(0)->GetId() == IDM_LOGCONFIGWINDOW)
{
SConfig::GetInstance().m_InterfaceLogWindow = false;
SConfig::GetInstance().m_InterfaceLogConfigWindow = false;
ToggleLogWindow(false);
ToggleLogConfigWindow(false);
}
}
else
{
if (GetNotebookCount() == 1)
{
wxMessageBox(_("At least one pane must remain open."),
_("Notice"), wxOK, this);
}
else if (nb->GetPageCount() != 0 && !nb->GetPageText(0).IsSameAs("<>"))
{
wxMessageBox(_("You can't close panes that have pages in them."),
_("Notice"), wxOK, this);
}
else
{
// Detach and delete the empty notebook
event.pane->DestroyOnClose(true);
m_Mgr->ClosePane(*event.pane);
}
}
m_Mgr->Update();
}
void CFrame::ToggleLogWindow(bool bShow)
{
if (!m_LogWindow)
return;
GetMenuBar()->FindItem(IDM_LOGWINDOW)->Check(bShow);
if (bShow)
{
// Create a new log window if it doesn't exist.
if (!m_LogWindow)
{
m_LogWindow = new CLogWindow(this, IDM_LOGWINDOW);
}
m_LogWindow->Enable();
DoAddPage(m_LogWindow,
g_pCodeWindow ? g_pCodeWindow->iNbAffiliation[0] : 0,
g_pCodeWindow ? bFloatWindow[0] : false);
}
else
{
// Hiding the log window, so disable it and remove it.
m_LogWindow->Disable();
DoRemovePage(m_LogWindow, true);
}
// Hide or Show the pane
if (!g_pCodeWindow)
TogglePane();
}
void CFrame::ToggleLogConfigWindow(bool bShow)
{
GetMenuBar()->FindItem(IDM_LOGCONFIGWINDOW)->Check(bShow);
if (bShow)
{
if (!m_LogConfigWindow)
m_LogConfigWindow = new LogConfigWindow(this, m_LogWindow, IDM_LOGCONFIGWINDOW);
const int nbIndex = IDM_LOGCONFIGWINDOW - IDM_LOGWINDOW;
DoAddPage(m_LogConfigWindow,
g_pCodeWindow ? g_pCodeWindow->iNbAffiliation[nbIndex] : 0,
g_pCodeWindow ? bFloatWindow[nbIndex] : false);
}
else
{
DoRemovePage(m_LogConfigWindow, false);
m_LogConfigWindow = nullptr;
}
// Hide or Show the pane
if (!g_pCodeWindow)
TogglePane();
}
void CFrame::OnToggleWindow(wxCommandEvent& event)
{
bool bShow = GetMenuBar()->IsChecked(event.GetId());
switch (event.GetId())
{
case IDM_LOGWINDOW:
if (!g_pCodeWindow)
SConfig::GetInstance().m_InterfaceLogWindow = bShow;
ToggleLogWindow(bShow);
break;
case IDM_LOGCONFIGWINDOW:
if (!g_pCodeWindow)
SConfig::GetInstance().m_InterfaceLogConfigWindow = bShow;
ToggleLogConfigWindow(bShow);
break;
case IDM_REGISTERWINDOW:
g_pCodeWindow->ToggleRegisterWindow(bShow);
break;
case IDM_WATCHWINDOW:
g_pCodeWindow->ToggleWatchWindow(bShow);
break;
case IDM_BREAKPOINTWINDOW:
g_pCodeWindow->ToggleBreakPointWindow(bShow);
break;
case IDM_MEMORYWINDOW:
g_pCodeWindow->ToggleMemoryWindow(bShow);
break;
case IDM_JITWINDOW:
g_pCodeWindow->ToggleJitWindow(bShow);
break;
case IDM_SOUNDWINDOW:
g_pCodeWindow->ToggleSoundWindow(bShow);
break;
case IDM_VIDEOWINDOW:
g_pCodeWindow->ToggleVideoWindow(bShow);
break;
}
}
// Notebooks
// ---------------------
void CFrame::ClosePages()
{
ToggleLogWindow(false);
ToggleLogConfigWindow(false);
if (g_pCodeWindow)
{
g_pCodeWindow->ToggleCodeWindow(false);
g_pCodeWindow->ToggleRegisterWindow(false);
g_pCodeWindow->ToggleWatchWindow(false);
g_pCodeWindow->ToggleBreakPointWindow(false);
g_pCodeWindow->ToggleMemoryWindow(false);
g_pCodeWindow->ToggleJitWindow(false);
g_pCodeWindow->ToggleSoundWindow(false);
g_pCodeWindow->ToggleVideoWindow(false);
}
}
void CFrame::OnNotebookPageChanged(wxAuiNotebookEvent& event)
{
event.Skip();
if (!g_pCodeWindow)
return;
// Remove the blank page if any
AddRemoveBlankPage();
// Update the notebook affiliation
for (int i = IDM_LOGWINDOW; i <= IDM_CODEWINDOW; i++)
{
if (GetNotebookAffiliation(i) >= 0)
g_pCodeWindow->iNbAffiliation[i - IDM_LOGWINDOW] = GetNotebookAffiliation(i);
}
}
void CFrame::OnNotebookPageClose(wxAuiNotebookEvent& event)
{
// Override event
event.Veto();
wxAuiNotebook* Ctrl = (wxAuiNotebook*)event.GetEventObject();
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_LOGWINDOW)
ToggleLogWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_LOGCONFIGWINDOW)
ToggleLogConfigWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_REGISTERWINDOW)
g_pCodeWindow->ToggleRegisterWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_WATCHWINDOW)
g_pCodeWindow->ToggleWatchWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_BREAKPOINTWINDOW)
g_pCodeWindow->ToggleBreakPointWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_JITWINDOW)
g_pCodeWindow->ToggleJitWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_MEMORYWINDOW)
g_pCodeWindow->ToggleMemoryWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_SOUNDWINDOW)
g_pCodeWindow->ToggleSoundWindow(false);
if (Ctrl->GetPage(event.GetSelection())->GetId() == IDM_VIDEOWINDOW)
g_pCodeWindow->ToggleVideoWindow(false);
}
void CFrame::OnFloatingPageClosed(wxCloseEvent& event)
{
ToggleFloatWindow(event.GetId() - IDM_LOGWINDOW_PARENT + IDM_FLOAT_LOGWINDOW);
}
void CFrame::OnFloatingPageSize(wxSizeEvent& event)
{
event.Skip();
}
void CFrame::OnFloatWindow(wxCommandEvent& event)
{
ToggleFloatWindow(event.GetId());
}
void CFrame::ToggleFloatWindow(int Id)
{
wxWindowID WinId = Id - IDM_FLOAT_LOGWINDOW + IDM_LOGWINDOW;
if (GetNotebookPageFromId(WinId))
{
DoFloatNotebookPage(WinId);
bFloatWindow[WinId - IDM_LOGWINDOW] = true;
}
else
{
if (FindWindowById(WinId))
DoUnfloatPage(WinId - IDM_LOGWINDOW + IDM_LOGWINDOW_PARENT);
bFloatWindow[WinId - IDM_LOGWINDOW] = false;
}
}
void CFrame::DoFloatNotebookPage(wxWindowID Id)
{
wxPanel *Win = (wxPanel*)FindWindowById(Id);
if (!Win) return;
for (int i = 0; i < GetNotebookCount(); i++)
{
wxAuiNotebook *nb = GetNotebookFromId(i);
if (nb->GetPageIndex(Win) != wxNOT_FOUND)
{
nb->RemovePage(nb->GetPageIndex(Win));
// Create the parent frame and reparent the window
CreateParentFrame(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW,
Win->GetName(), Win);
if (nb->GetPageCount() == 0)
AddRemoveBlankPage();
}
}
}
void CFrame::DoUnfloatPage(int Id)
{
wxFrame * Win = (wxFrame*)FindWindowById(Id);
if (!Win) return;
wxWindow * Child = Win->GetChildren().Item(0)->GetData();
Child->Reparent(this);
DoAddPage(Child, g_pCodeWindow->iNbAffiliation[Child->GetId() - IDM_LOGWINDOW], false);
Win->Destroy();
}
void CFrame::OnTab(wxAuiNotebookEvent& event)
{
event.Skip();
if (!g_pCodeWindow) return;
// Create the popup menu
wxMenu* MenuPopup = new wxMenu;
wxMenuItem* Item = new wxMenuItem(MenuPopup, wxID_ANY, _("Select floating windows"));
MenuPopup->Append(Item);
Item->Enable(false);
MenuPopup->Append(new wxMenuItem(MenuPopup));
for (int i = IDM_LOGWINDOW; i <= IDM_CODEWINDOW; i++)
{
wxWindow *Win = FindWindowById(i);
if (Win && Win->IsEnabled())
{
Item = new wxMenuItem(MenuPopup, i + IDM_FLOAT_LOGWINDOW - IDM_LOGWINDOW,
Win->GetName(), "", wxITEM_CHECK);
MenuPopup->Append(Item);
Item->Check(!!FindWindowById(i + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW));
}
}
// Line up our menu with the cursor
wxPoint Pt = ::wxGetMousePosition();
Pt = ScreenToClient(Pt);
// Show
PopupMenu(MenuPopup, Pt);
}
void CFrame::OnAllowNotebookDnD(wxAuiNotebookEvent& event)
{
event.Skip();
event.Allow();
}
void CFrame::ShowResizePane()
{
if (!m_LogWindow) return;
// Make sure the size is sane
if (m_LogWindow->x > GetClientRect().GetWidth())
m_LogWindow->x = GetClientRect().GetWidth() / 2;
if (m_LogWindow->y > GetClientRect().GetHeight())
m_LogWindow->y = GetClientRect().GetHeight() / 2;
wxAuiPaneInfo &pane = m_Mgr->GetPane("Pane 1");
// Hide first otherwise a resize doesn't work
pane.Hide();
m_Mgr->Update();
pane.BestSize(m_LogWindow->x, m_LogWindow->y)
.MinSize(m_LogWindow->x, m_LogWindow->y)
.Direction(m_LogWindow->winpos).Show();
m_Mgr->Update();
// Reset the minimum size of the pane
pane.MinSize(-1, -1);
m_Mgr->Update();
}
void CFrame::TogglePane()
{
// Get the first notebook
wxAuiNotebook * NB = nullptr;
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
}
if (NB)
{
if (NB->GetPageCount() == 0)
{
m_Mgr->GetPane("Pane 1").Hide();
m_Mgr->Update();
}
else
{
ShowResizePane();
}
}
}
void CFrame::DoRemovePage(wxWindow *Win, bool bHide)
{
if (!Win) return;
wxWindow *Parent = FindWindowById(Win->GetId() +
IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW);
if (Parent)
{
if (bHide)
{
Win->Hide();
Win->Reparent(this);
}
else
{
Win->Destroy();
}
Parent->Destroy();
}
else
{
for (int i = 0; i < GetNotebookCount(); i++)
{
int PageIndex = GetNotebookFromId(i)->GetPageIndex(Win);
if (PageIndex != wxNOT_FOUND)
{
GetNotebookFromId(i)->RemovePage(PageIndex);
if (bHide)
{
Win->Hide();
Win->Reparent(this);
}
else
{
Win->Destroy();
}
}
}
}
if (g_pCodeWindow)
AddRemoveBlankPage();
}
void CFrame::DoAddPage(wxWindow *Win, int i, bool Float)
{
if (!Win) return;
// Ensure accessor remains within valid bounds.
if (i < 0 || i > GetNotebookCount()-1)
i = 0;
// The page was already previously added, no need to add it again.
if (Win && GetNotebookFromId(i)->GetPageIndex(Win) != wxNOT_FOUND)
return;
if (!Float)
GetNotebookFromId(i)->AddPage(Win, Win->GetName(), true);
else
CreateParentFrame(Win->GetId() + IDM_LOGWINDOW_PARENT - IDM_LOGWINDOW,
Win->GetName(), Win);
}
void CFrame::PopulateSavedPerspectives()
{
// If the perspective submenu hasn't been created yet, return
if (!m_SavedPerspectives) return;
// Delete all saved perspective menu items
while (m_SavedPerspectives->GetMenuItemCount() != 0)
{
// Delete the first menu item in the list (while there are menu items)
m_SavedPerspectives->Delete(m_SavedPerspectives->FindItemByPosition(0));
}
if (Perspectives.size() > 0)
{
for (u32 i = 0; i < Perspectives.size(); i++)
{
wxMenuItem* mItem = new wxMenuItem(m_SavedPerspectives, IDM_PERSPECTIVES_0 + i,
StrToWxStr(Perspectives[i].Name), "", wxITEM_CHECK);
m_SavedPerspectives->Append(mItem);
if (i == ActivePerspective)
{
mItem->Check(true);
}
}
}
}
void CFrame::OnPerspectiveMenu(wxCommandEvent& event)
{
ClearStatusBar();
switch (event.GetId())
{
case IDM_SAVE_PERSPECTIVE:
if (Perspectives.size() == 0)
{
wxMessageBox(_("Please create a perspective before saving"),
_("Notice"), wxOK, this);
return;
}
SaveIniPerspectives();
GetStatusBar()->SetStatusText(StrToWxStr(std::string
("Saved " + Perspectives[ActivePerspective].Name)), 0);
break;
case IDM_PERSPECTIVES_ADD_PANE:
AddPane();
break;
case IDM_EDIT_PERSPECTIVES:
m_bEdit = event.IsChecked();
TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES);
break;
case IDM_ADD_PERSPECTIVE:
{
wxTextEntryDialog dlg(this,
_("Enter a name for the new perspective:"),
_("Create new perspective"));
wxString DefaultValue = wxString::Format(_("Perspective %d"), (int)(Perspectives.size() + 1));
dlg.SetValue(DefaultValue);
int Return = 0;
bool DlgOk = false;
while (!DlgOk)
{
Return = dlg.ShowModal();
if (Return == wxID_CANCEL)
{
return;
}
else if (dlg.GetValue().Find(",") != -1)
{
wxMessageBox(_("The name cannot contain the character ','"),
_("Notice"), wxOK, this);
wxString Str = dlg.GetValue();
Str.Replace(",", "", true);
dlg.SetValue(Str);
}
else if (dlg.GetValue().IsSameAs(""))
{
wxMessageBox(_("The name cannot be empty"),
_("Notice"), wxOK, this);
dlg.SetValue(DefaultValue);
}
else
{
DlgOk = true;
}
}
SPerspectives Tmp;
Tmp.Name = WxStrToStr(dlg.GetValue());
Tmp.Perspective = m_Mgr->SavePerspective();
ActivePerspective = (u32)Perspectives.size();
Perspectives.push_back(Tmp);
UpdateCurrentPerspective();
PopulateSavedPerspectives();
}
break;
case IDM_TAB_SPLIT:
m_bTabSplit = event.IsChecked();
ToggleNotebookStyle(m_bTabSplit, wxAUI_NB_TAB_SPLIT);
break;
case IDM_NO_DOCKING:
m_bNoDocking = event.IsChecked();
TogglePaneStyle(m_bNoDocking, IDM_NO_DOCKING);
break;
}
}
void CFrame::TogglePaneStyle(bool On, int EventId)
{
wxAuiPaneInfoArray& AllPanes = m_Mgr->GetAllPanes();
for (u32 i = 0; i < AllPanes.GetCount(); ++i)
{
wxAuiPaneInfo& Pane = AllPanes[i];
if (Pane.window->IsKindOf(CLASSINFO(wxAuiNotebook)))
{
// Default
Pane.CloseButton(true);
Pane.MaximizeButton(true);
Pane.MinimizeButton(true);
Pane.PinButton(true);
Pane.Show();
switch (EventId)
{
case IDM_EDIT_PERSPECTIVES:
Pane.CaptionVisible(On);
Pane.Movable(On);
Pane.Floatable(On);
Pane.Dockable(On);
break;
}
Pane.Dockable(!m_bNoDocking);
}
}
m_Mgr->Update();
}
void CFrame::ToggleNotebookStyle(bool On, long Style)
{
wxAuiPaneInfoArray& AllPanes = m_Mgr->GetAllPanes();
for (int i = 0, Count = (int)AllPanes.GetCount(); i < Count; ++i)
{
wxAuiPaneInfo& Pane = AllPanes[i];
if (Pane.window->IsKindOf(CLASSINFO(wxAuiNotebook)))
{
wxAuiNotebook* NB = (wxAuiNotebook*)Pane.window;
if (On)
NB->SetWindowStyleFlag(NB->GetWindowStyleFlag() | Style);
else
NB->SetWindowStyleFlag(NB->GetWindowStyleFlag() &~ Style);
NB->Refresh();
}
}
}
void CFrame::OnSelectPerspective(wxCommandEvent& event)
{
u32 _Selection = event.GetId() - IDM_PERSPECTIVES_0;
if (Perspectives.size() <= _Selection) _Selection = 0;
ActivePerspective = _Selection;
DoLoadPerspective();
}
void CFrame::SetPaneSize()
{
if (Perspectives.size() <= ActivePerspective)
return;
int iClientX = GetSize().GetX();
int iClientY = GetSize().GetY();
for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiToolBar)))
{
if (!m_Mgr->GetAllPanes()[i].IsOk())
return;
if (Perspectives[ActivePerspective].Width.size() <= j ||
Perspectives[ActivePerspective].Height.size() <= j)
continue;
// Width and height of the active perspective
u32 W = Perspectives[ActivePerspective].Width[j],
H = Perspectives[ActivePerspective].Height[j];
// Check limits
MathUtil::Clamp<u32>(&W, 5, 95);
MathUtil::Clamp<u32>(&H, 5, 95);
// Convert percentages to pixel lengths
W = (W * iClientX) / 100;
H = (H * iClientY) / 100;
m_Mgr->GetAllPanes()[i].BestSize(W,H).MinSize(W,H);
j++;
}
}
m_Mgr->Update();
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiToolBar)))
{
m_Mgr->GetAllPanes()[i].MinSize(-1,-1);
}
}
}
void CFrame::ReloadPanes()
{
// Close all pages
ClosePages();
CloseAllNotebooks();
// Create new panes with notebooks
for (u32 i = 0; i < Perspectives[ActivePerspective].Width.size() - 1; i++)
{
wxString PaneName = wxString::Format("Pane %i", i + 1);
m_Mgr->AddPane(CreateEmptyNotebook(), wxAuiPaneInfo().Hide()
.CaptionVisible(m_bEdit).Dockable(!m_bNoDocking).Position(i)
.Name(PaneName).Caption(PaneName));
}
// Perspectives
m_Mgr->LoadPerspective(Perspectives[ActivePerspective].Perspective, false);
// Restore settings
TogglePaneStyle(m_bNoDocking, IDM_NO_DOCKING);
TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES);
// Load GUI settings
g_pCodeWindow->Load();
// Open notebook pages
AddRemoveBlankPage();
g_pCodeWindow->OpenPages();
// Repopulate perspectives
PopulateSavedPerspectives();
}
void CFrame::DoLoadPerspective()
{
ReloadPanes();
// Restore the exact window sizes, which LoadPerspective doesn't always do
SetPaneSize();
m_Mgr->Update();
}
// Update the local perspectives array
void CFrame::LoadIniPerspectives()
{
Perspectives.clear();
std::vector<std::string> VPerspectives;
std::string _Perspectives;
IniFile ini;
ini.Load(File::GetUserPath(F_DEBUGGERCONFIG_IDX));
IniFile::Section* perspectives = ini.GetOrCreateSection("Perspectives");
perspectives->Get("Perspectives", &_Perspectives, "Perspective 1");
perspectives->Get("Active", &ActivePerspective, 0);
SplitString(_Perspectives, ',', VPerspectives);
for (auto& VPerspective : VPerspectives)
{
SPerspectives Tmp;
std::string _Section, _Perspective, _Widths, _Heights;
std::vector<std::string> _SWidth, _SHeight;
Tmp.Name = VPerspective;
// Don't save a blank perspective
if (Tmp.Name.empty())
{
continue;
}
_Section = StringFromFormat("P - %s", Tmp.Name.c_str());
IniFile::Section* perspec_section = ini.GetOrCreateSection(_Section);
perspec_section->Get("Perspective", &_Perspective,
"layout2|"
"name=Pane 0;caption=Pane 0;state=768;dir=5;prop=100000;|"
"name=Pane 1;caption=Pane 1;state=31458108;dir=4;prop=100000;|"
"dock_size(5,0,0)=22|dock_size(4,0,0)=333|");
perspec_section->Get("Width", &_Widths, "70,25");
perspec_section->Get("Height", &_Heights, "80,80");
Tmp.Perspective = StrToWxStr(_Perspective);
SplitString(_Widths, ',', _SWidth);
SplitString(_Heights, ',', _SHeight);
for (auto& Width : _SWidth)
{
int _Tmp;
if (TryParse(Width, &_Tmp))
Tmp.Width.push_back(_Tmp);
}
for (auto& Height : _SHeight)
{
int _Tmp;
if (TryParse(Height, &_Tmp))
Tmp.Height.push_back(_Tmp);
}
Perspectives.push_back(Tmp);
}
}
void CFrame::UpdateCurrentPerspective()
{
SPerspectives *current = &Perspectives[ActivePerspective];
current->Perspective = m_Mgr->SavePerspective();
// Get client size
int iClientX = GetSize().GetX(), iClientY = GetSize().GetY();
current->Width.clear();
current->Height.clear();
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->
IsKindOf(CLASSINFO(wxAuiToolBar)))
{
// Save width and height as a percentage of the client width and height
current->Width.push_back(
(m_Mgr->GetAllPanes()[i].window->GetClientSize().GetX() * 100) /
iClientX);
current->Height.push_back(
(m_Mgr->GetAllPanes()[i].window->GetClientSize().GetY() * 100) /
iClientY);
}
}
}
void CFrame::SaveIniPerspectives()
{
if (Perspectives.size() == 0) return;
if (ActivePerspective >= Perspectives.size()) ActivePerspective = 0;
// Turn off edit before saving
TogglePaneStyle(false, IDM_EDIT_PERSPECTIVES);
UpdateCurrentPerspective();
IniFile ini;
ini.Load(File::GetUserPath(F_DEBUGGERCONFIG_IDX));
// Save perspective names
std::string STmp = "";
for (auto& Perspective : Perspectives)
{
STmp += Perspective.Name + ",";
}
STmp = STmp.substr(0, STmp.length()-1);
IniFile::Section* perspectives = ini.GetOrCreateSection("Perspectives");
perspectives->Set("Perspectives", STmp);
perspectives->Set("Active", ActivePerspective);
// Save the perspectives
for (auto& Perspective : Perspectives)
{
std::string _Section = "P - " + Perspective.Name;
IniFile::Section* perspec_section = ini.GetOrCreateSection(_Section);
perspec_section->Set("Perspective", WxStrToStr(Perspective.Perspective));
std::string SWidth = "", SHeight = "";
for (u32 j = 0; j < Perspective.Width.size(); j++)
{
SWidth += StringFromFormat("%i,", Perspective.Width[j]);
SHeight += StringFromFormat("%i,", Perspective.Height[j]);
}
// Remove the ending ","
SWidth = SWidth.substr(0, SWidth.length()-1);
SHeight = SHeight.substr(0, SHeight.length()-1);
perspec_section->Set("Width", SWidth);
perspec_section->Set("Height", SHeight);
}
ini.Save(File::GetUserPath(F_DEBUGGERCONFIG_IDX));
// Save notebook affiliations
g_pCodeWindow->Save();
TogglePaneStyle(m_bEdit, IDM_EDIT_PERSPECTIVES);
}
void CFrame::AddPane()
{
int PaneNum = GetNotebookCount() + 1;
wxString PaneName = wxString::Format("Pane %i", PaneNum);
m_Mgr->AddPane(CreateEmptyNotebook(), wxAuiPaneInfo()
.CaptionVisible(m_bEdit).Dockable(!m_bNoDocking)
.Name(PaneName).Caption(PaneName)
.Position(GetNotebookCount()));
AddRemoveBlankPage();
m_Mgr->Update();
}
wxWindow * CFrame::GetNotebookPageFromId(wxWindowID Id)
{
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
for (u32 j = 0; j < NB->GetPageCount(); j++)
{
if (NB->GetPage(j)->GetId() == Id)
return NB->GetPage(j);
}
}
return nullptr;
}
wxFrame* CFrame::CreateParentFrame(wxWindowID Id, const wxString& Title, wxWindow* Child)
{
wxFrame* Frame = new wxFrame(this, Id, Title);
Child->Reparent(Frame);
wxBoxSizer* m_MainSizer = new wxBoxSizer(wxHORIZONTAL);
m_MainSizer->Add(Child, 1, wxEXPAND);
Frame->Bind(wxEVT_CLOSE_WINDOW, &CFrame::OnFloatingPageClosed, this);
// Main sizer
Frame->SetSizer(m_MainSizer);
// Minimum frame size
Frame->SetMinSize(wxSize(200, 200));
Frame->Show();
return Frame;
}
wxAuiNotebook* CFrame::CreateEmptyNotebook()
{
const long NOTEBOOK_STYLE = wxAUI_NB_TOP | wxAUI_NB_TAB_SPLIT |
wxAUI_NB_TAB_EXTERNAL_MOVE | wxAUI_NB_SCROLL_BUTTONS |
wxAUI_NB_WINDOWLIST_BUTTON | wxNO_BORDER;
wxAuiNotebook* NB = new wxAuiNotebook(this, wxID_ANY,
wxDefaultPosition, wxDefaultSize, NOTEBOOK_STYLE);
return NB;
}
void CFrame::AddRemoveBlankPage()
{
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
for (u32 j = 0; j < NB->GetPageCount(); j++)
{
if (NB->GetPageText(j).IsSameAs("<>") && NB->GetPageCount() > 1)
NB->DeletePage(j);
}
if (NB->GetPageCount() == 0)
NB->AddPage(new wxPanel(this, wxID_ANY), "<>", true);
}
}
int CFrame::GetNotebookAffiliation(wxWindowID Id)
{
for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
wxAuiNotebook * NB = (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
for (u32 k = 0; k < NB->GetPageCount(); k++)
{
if (NB->GetPage(k)->GetId() == Id)
return j;
}
j++;
}
return -1;
}
// Close all panes with notebooks
void CFrame::CloseAllNotebooks()
{
wxAuiPaneInfoArray AllPanes = m_Mgr->GetAllPanes();
for (u32 i = 0; i < AllPanes.GetCount(); i++)
{
if (AllPanes[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
{
AllPanes[i].DestroyOnClose(true);
m_Mgr->ClosePane(AllPanes[i]);
}
}
}
int CFrame::GetNotebookCount()
{
int Ret = 0;
for (u32 i = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
Ret++;
}
return Ret;
}
wxAuiNotebook * CFrame::GetNotebookFromId(u32 NBId)
{
for (u32 i = 0, j = 0; i < m_Mgr->GetAllPanes().GetCount(); i++)
{
if (!m_Mgr->GetAllPanes()[i].window->IsKindOf(CLASSINFO(wxAuiNotebook)))
continue;
if (j == NBId)
return (wxAuiNotebook*)m_Mgr->GetAllPanes()[i].window;
j++;
}
return nullptr;
}
| Java |
/*****************************************************************************
* Free42 -- an HP-42S calculator simulator
* Copyright (C) 2004-2016 Thomas Okken
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License, version 2,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see http://www.gnu.org/licenses/.
*****************************************************************************/
#include <stdlib.h>
#include "core_commands2.h"
#include "core_commands3.h"
#include "core_commands4.h"
#include "core_display.h"
#include "core_helpers.h"
#include "core_linalg1.h"
#include "core_sto_rcl.h"
#include "core_variables.h"
/********************************************************/
/* Implementations of HP-42S built-in functions, part 4 */
/********************************************************/
int docmd_insr(arg_struct *arg) {
vartype *m, *newx;
vartype_realmatrix *rm;
vartype_complexmatrix *cm;
int4 rows, columns, i;
int err, refcount;
int interactive;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
interactive = matedit_mode == 2 || matedit_mode == 3;
if (interactive) {
err = docmd_stoel(NULL);
if (err != ERR_NONE)
return err;
}
if (m->type == TYPE_REALMATRIX) {
rm = (vartype_realmatrix *) m;
rows = rm->rows;
columns = rm->columns;
refcount = rm->array->refcount;
if (interactive) {
newx = new_real(0);
if (newx == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
} else {
cm = (vartype_complexmatrix *) m;
rows = cm->rows;
columns = cm->columns;
refcount = cm->array->refcount;
if (interactive) {
newx = new_complex(0, 0);
if (newx == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
}
if (matedit_i >= rows)
matedit_i = rows - 1;
if (matedit_j >= columns)
matedit_j = columns - 1;
if (refcount == 1) {
/* We have this array to ourselves so we can modify it in place */
err = dimension_array_ref(m, rows + 1, columns);
if (err != ERR_NONE) {
if (interactive)
free_vartype(newx);
return err;
}
rows++;
if (m->type == TYPE_REALMATRIX) {
for (i = rows * columns - 1; i >= (matedit_i + 1) * columns; i--) {
rm->array->is_string[i] = rm->array->is_string[i - columns];
rm->array->data[i] = rm->array->data[i - columns];
}
for (i = matedit_i * columns; i < (matedit_i + 1) * columns; i++) {
rm->array->is_string[i] = 0;
rm->array->data[i] = 0;
}
} else {
for (i = 2 * rows * columns - 1;
i >= 2 * (matedit_i + 1) * columns; i--)
cm->array->data[i] = cm->array->data[i - 2 * columns];
for (i = 2 * matedit_i * columns;
i < 2 * (matedit_i + 1) * columns; i++)
cm->array->data[i] = 0;
}
} else {
/* We're sharing this array. I don't use disentangle() because it
* does not deal with resizing. */
int4 newsize = (rows + 1) * columns;
if (m->type == TYPE_REALMATRIX) {
realmatrix_data *array = (realmatrix_data *)
malloc(sizeof(realmatrix_data));
if (array == NULL) {
if (interactive)
free_vartype(newx);
return ERR_INSUFFICIENT_MEMORY;
}
array->data = (phloat *) malloc(newsize * sizeof(phloat));
if (array->data == NULL) {
if (interactive)
free_vartype(newx);
free(array);
return ERR_INSUFFICIENT_MEMORY;
}
array->is_string = (char *) malloc(newsize);
if (array->is_string == NULL) {
if (interactive)
free_vartype(newx);
free(array->data);
free(array);
return ERR_INSUFFICIENT_MEMORY;
}
for (i = 0; i < matedit_i * columns; i++) {
array->is_string[i] = rm->array->is_string[i];
array->data[i] = rm->array->data[i];
}
for (i = matedit_i * columns; i < (matedit_i + 1) * columns; i++) {
array->is_string[i] = 0;
array->data[i] = 0;
}
for (i = (matedit_i + 1) * columns; i < newsize; i++) {
array->is_string[i] = rm->array->is_string[i - columns];
array->data[i] = rm->array->data[i - columns];
}
array->refcount = 1;
rm->array->refcount--;
rm->array = array;
rm->rows++;
} else {
complexmatrix_data *array = (complexmatrix_data *)
malloc(sizeof(complexmatrix_data));
if (array == NULL) {
if (interactive)
free_vartype(newx);
return ERR_INSUFFICIENT_MEMORY;
}
array->data = (phloat *) malloc(2 * newsize * sizeof(phloat));
if (array->data == NULL) {
if (interactive)
free_vartype(newx);
free(array);
return ERR_INSUFFICIENT_MEMORY;
}
for (i = 0; i < 2 * matedit_i * columns; i++)
array->data[i] = cm->array->data[i];
for (i = 2 * matedit_i * columns;
i < 2 * (matedit_i + 1) * columns; i++)
array->data[i] = 0;
for (i = 2 * (matedit_i + 1) * columns; i < 2 * newsize; i++)
array->data[i] = cm->array->data[i - 2 * columns];
array->refcount = 1;
cm->array->refcount--;
cm->array = array;
cm->rows++;
}
}
if (interactive) {
free_vartype(reg_x);
reg_x = newx;
}
mode_disable_stack_lift = true;
return ERR_NONE;
}
static void invrt_completion(int error, vartype *res) {
if (error == ERR_NONE)
unary_result(res);
}
int docmd_invrt(arg_struct *arg) {
if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_COMPLEX)
return ERR_INVALID_TYPE;
else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return linalg_inv(reg_x, invrt_completion);
}
int docmd_j_add(arg_struct *arg) {
int4 rows, columns;
int4 oldi = matedit_i;
int4 oldj = matedit_j;
int err = matedit_get_dim(&rows, &columns);
if (err != ERR_NONE)
return err;
if (++matedit_j >= columns) {
flags.f.matrix_edge_wrap = 1;
matedit_j = 0;
if (++matedit_i >= rows) {
flags.f.matrix_end_wrap = 1;
if (flags.f.grow) {
if (matedit_mode == 2)
err = dimension_array_ref(matedit_x, rows + 1, columns);
else
err = dimension_array(matedit_name, matedit_length,
rows + 1, columns);
if (err != ERR_NONE) {
matedit_i = oldi;
matedit_j = oldj;
return err;
}
matedit_i = rows;
} else
matedit_i = 0;
} else
flags.f.matrix_end_wrap = 0;
} else {
flags.f.matrix_edge_wrap = 0;
flags.f.matrix_end_wrap = 0;
}
return ERR_NONE;
}
int docmd_j_sub(arg_struct *arg) {
int4 rows, columns;
int err = matedit_get_dim(&rows, &columns);
if (err != ERR_NONE)
return err;
if (--matedit_j < 0) {
flags.f.matrix_edge_wrap = 1;
matedit_j = columns - 1;
if (--matedit_i < 0) {
flags.f.matrix_end_wrap = 1;
matedit_i = rows - 1;
} else
flags.f.matrix_end_wrap = 0;
} else {
flags.f.matrix_edge_wrap = 0;
flags.f.matrix_end_wrap = 0;
}
return ERR_NONE;
}
static int mappable_ln_1_x(phloat x, phloat *y) {
if (x <= -1)
return ERR_INVALID_DATA;
*y = log1p(x);
return ERR_NONE;
}
int docmd_ln_1_x(arg_struct *arg) {
if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_REALMATRIX) {
vartype *v;
int err = map_unary(reg_x, &v, mappable_ln_1_x, NULL);
if (err == ERR_NONE)
unary_result(v);
return err;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_old(arg_struct *arg) {
return docmd_rclel(NULL);
}
int docmd_posa(arg_struct *arg) {
int pos = -1;
vartype *v;
if (reg_x->type == TYPE_REAL) {
phloat x = ((vartype_real *) reg_x)->x;
char c;
int i;
if (x < 0)
x = -x;
if (x >= 256)
return ERR_INVALID_DATA;
c = to_char(x);
for (i = 0; i < reg_alpha_length; i++)
if (reg_alpha[i] == c) {
pos = i;
break;
}
} else if (reg_x->type == TYPE_STRING) {
vartype_string *s = (vartype_string *) reg_x;
if (s->length != 0) {
int i, j;
for (i = 0; i < reg_alpha_length - s->length; i++) {
for (j = 0; j < s->length; j++)
if (reg_alpha[i + j] != s->text[j])
goto notfound;
pos = i;
break;
notfound:;
}
}
} else
return ERR_INVALID_TYPE;
v = new_real(pos);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
unary_result(v);
return ERR_NONE;
}
int docmd_putm(arg_struct *arg) {
vartype *m;
int4 i, j;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
/* Shouldn't happen, but could, as long as I don't
* implement matrix locking
*/
return ERR_INVALID_TYPE;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else if (reg_x->type == TYPE_REAL || reg_x->type == TYPE_COMPLEX)
return ERR_INVALID_TYPE;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *src, *dst;
if (reg_x->type == TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
src = (vartype_realmatrix *) reg_x;
dst = (vartype_realmatrix *) m;
if (src->rows + matedit_i > dst->rows
|| src->columns + matedit_j > dst->columns)
return ERR_DIMENSION_ERROR;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < src->rows; i++)
for (j = 0; j < src->columns; j++) {
int4 n1 = i * src->columns + j;
int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j;
dst->array->is_string[n2] = src->array->is_string[n1];
dst->array->data[n2] = src->array->data[n1];
}
return ERR_NONE;
} else if (reg_x->type == TYPE_REALMATRIX) {
vartype_realmatrix *src = (vartype_realmatrix *) reg_x;
vartype_complexmatrix *dst = (vartype_complexmatrix *) m;
if (src->rows + matedit_i > dst->rows
|| src->columns + matedit_j > dst->columns)
return ERR_DIMENSION_ERROR;
for (i = 0; i < src->rows * src->columns; i++)
if (src->array->is_string[i])
return ERR_ALPHA_DATA_IS_INVALID;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < src->rows; i++)
for (j = 0; j < src->columns; j++) {
int4 n1 = i * src->columns + j;
int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j;
dst->array->data[n2 * 2] = src->array->data[n1];
dst->array->data[n2 * 2 + 1] = 0;
}
return ERR_NONE;
} else {
vartype_complexmatrix *src = (vartype_complexmatrix *) reg_x;
vartype_complexmatrix *dst = (vartype_complexmatrix *) m;
if (src->rows + matedit_i > dst->rows
|| src->columns + matedit_j > dst->columns)
return ERR_DIMENSION_ERROR;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < src->rows; i++)
for (j = 0; j < src->columns; j++) {
int4 n1 = i * src->columns + j;
int4 n2 = (i + matedit_i) * dst->columns + j + matedit_j;
dst->array->data[n2 * 2] = src->array->data[n1 * 2];
dst->array->data[n2 * 2 + 1] = src->array->data[n1 * 2 + 1];
}
return ERR_NONE;
}
}
int docmd_rclel(arg_struct *arg) {
vartype *m, *v;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
int4 n = matedit_i * rm->columns + matedit_j;
if (rm->array->is_string[n])
v = new_string(phloat_text(rm->array->data[n]),
phloat_length(rm->array->data[n]));
else
v = new_real(rm->array->data[n]);
} else if (m->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
int4 n = matedit_i * cm->columns + matedit_j;
v = new_complex(cm->array->data[2 * n],
cm->array->data[2 * n + 1]);
} else
return ERR_INVALID_TYPE;
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
recall_result(v);
return ERR_NONE;
}
int docmd_rclij(arg_struct *arg) {
vartype *i, *j;
if (matedit_mode == 0)
return ERR_NONEXISTENT;
i = new_real(matedit_i + 1);
j = new_real(matedit_j + 1);
if (i == NULL || j == NULL) {
free_vartype(i);
free_vartype(j);
return ERR_INSUFFICIENT_MEMORY;
}
recall_two_results(j, i);
return ERR_NONE;
}
int docmd_rnrm(arg_struct *arg) {
if (reg_x->type == TYPE_REALMATRIX) {
vartype *v;
vartype_realmatrix *rm = (vartype_realmatrix *) reg_x;
int4 size = rm->rows * rm->columns;
int4 i, j;
phloat max = 0;
for (i = 0; i < size; i++)
if (rm->array->is_string[i])
return ERR_ALPHA_DATA_IS_INVALID;
for (i = 0; i < rm->rows; i++) {
phloat nrm = 0;
for (j = 0; j < rm->columns; j++) {
phloat x = rm->array->data[i * rm->columns + j];
if (x >= 0)
nrm += x;
else
nrm -= x;
}
if (p_isinf(nrm)) {
if (flags.f.range_error_ignore)
max = POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
break;
}
if (nrm > max)
max = nrm;
}
v = new_real(max);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
unary_result(v);
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEXMATRIX) {
vartype *v;
vartype_complexmatrix *cm = (vartype_complexmatrix *) reg_x;
int4 i, j;
phloat max = 0;
for (i = 0; i < cm->rows; i++) {
phloat nrm = 0;
for (j = 0; j < cm->columns; j++) {
phloat re = cm->array->data[2 * (i * cm->columns + j)];
phloat im = cm->array->data[2 * (i * cm->columns + j) + 1];
nrm += hypot(re, im);
}
if (p_isinf(nrm)) {
if (flags.f.range_error_ignore)
max = POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
break;
}
if (nrm > max)
max = nrm;
}
v = new_real(max);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
unary_result(v);
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_rsum(arg_struct *arg) {
if (reg_x->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) reg_x;
vartype_realmatrix *res;
int4 size = rm->rows * rm->columns;
int4 i, j;
for (i = 0; i < size; i++)
if (rm->array->is_string[i])
return ERR_ALPHA_DATA_IS_INVALID;
res = (vartype_realmatrix *) new_realmatrix(rm->rows, 1);
if (res == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rm->rows; i++) {
phloat sum = 0;
int inf;
for (j = 0; j < rm->columns; j++)
sum += rm->array->data[i * rm->columns + j];
if ((inf = p_isinf(sum)) != 0) {
if (flags.f.range_error_ignore)
sum = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else {
free_vartype((vartype *) res);
return ERR_OUT_OF_RANGE;
}
}
res->array->data[i] = sum;
}
unary_result((vartype *) res);
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *cm = (vartype_complexmatrix *) reg_x;
vartype_complexmatrix *res;
int4 i, j;
res = (vartype_complexmatrix *) new_complexmatrix(cm->rows, 1);
if (res == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < cm->rows; i++) {
phloat sum_re = 0, sum_im = 0;
int inf;
for (j = 0; j < cm->columns; j++) {
sum_re += cm->array->data[2 * (i * cm->columns + j)];
sum_im += cm->array->data[2 * (i * cm->columns + j) + 1];
}
if ((inf = p_isinf(sum_re)) != 0) {
if (flags.f.range_error_ignore)
sum_re = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else {
free_vartype((vartype *) res);
return ERR_OUT_OF_RANGE;
}
}
if ((inf = p_isinf(sum_im)) != 0) {
if (flags.f.range_error_ignore)
sum_im = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else {
free_vartype((vartype *) res);
return ERR_OUT_OF_RANGE;
}
}
res->array->data[2 * i] = sum_re;
res->array->data[2 * i + 1] = sum_im;
}
unary_result((vartype *) res);
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_swap_r(arg_struct *arg) {
vartype *m;
phloat xx, yy;
int4 x, y, i;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
/* Should not happen, but could, as long as I don't implement
* matrix locking. */
return ERR_INVALID_TYPE;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_x->type != TYPE_REAL)
return ERR_INVALID_TYPE;
if (reg_y->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_y->type != TYPE_REAL)
return ERR_INVALID_TYPE;
xx = ((vartype_real *) reg_x)->x;
if (xx <= -2147483648.0 || xx >= 2147483648.0)
return ERR_DIMENSION_ERROR;
x = to_int4(xx);
if (x == 0)
return ERR_DIMENSION_ERROR;
if (x < 0)
x = -x;
x--;
yy = ((vartype_real *) reg_y)->x;
if (yy <= -2147483648.0 || yy >= 2147483648.0)
return ERR_DIMENSION_ERROR;
y = to_int4(yy);
if (y == 0)
return ERR_DIMENSION_ERROR;
if (y < 0)
y = -y;
y--;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
if (x > rm->rows || y > rm->rows)
return ERR_DIMENSION_ERROR;
else if (x == y)
return ERR_NONE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rm->columns; i++) {
int4 n1 = x * rm->columns + i;
int4 n2 = y * rm->columns + i;
char tempc = rm->array->is_string[n1];
phloat tempds = rm->array->data[n1];
rm->array->is_string[n1] = rm->array->is_string[n2];
rm->array->data[n1] = rm->array->data[n2];
rm->array->is_string[n2] = tempc;
rm->array->data[n2] = tempds;
}
return ERR_NONE;
} else /* m->type == TYPE_COMPLEXMATRIX */ {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
if (x > cm->rows || y > cm->rows)
return ERR_DIMENSION_ERROR;
else if (x == y)
return ERR_NONE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < 2 * cm->columns; i++) {
int4 n1 = x * 2 * cm->columns + i;
int4 n2 = y * 2 * cm->columns + i;
phloat tempd = cm->array->data[n1];
cm->array->data[n1] = cm->array->data[n2];
cm->array->data[n2] = tempd;
}
return ERR_NONE;
}
}
static int mappable_sinh_r(phloat x, phloat *y) {
int inf;
*y = sinh(x);
if ((inf = p_isinf(*y)) != 0) {
if (flags.f.range_error_ignore)
*y = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
return ERR_NONE;
}
static int mappable_sinh_c(phloat xre, phloat xim, phloat *yre, phloat *yim) {
phloat sinhxre, coshxre;
phloat sinxim, cosxim;
int inf;
sinhxre = sinh(xre);
coshxre = cosh(xre);
sincos(xim, &sinxim, &cosxim);
*yre = sinhxre * cosxim;
if ((inf = p_isinf(*yre)) != 0) {
if (flags.f.range_error_ignore)
*yre = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
*yim = coshxre * sinxim;
if ((inf = p_isinf(*yim)) != 0) {
if (flags.f.range_error_ignore)
*yim = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
return ERR_NONE;
}
int docmd_sinh(arg_struct *arg) {
if (reg_x->type != TYPE_STRING) {
vartype *v;
int err = map_unary(reg_x, &v, mappable_sinh_r, mappable_sinh_c);
if (err == ERR_NONE)
unary_result(v);
return err;
} else
return ERR_ALPHA_DATA_IS_INVALID;
}
int docmd_stoel(arg_struct *arg) {
vartype *m;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX && m->type != TYPE_COMPLEXMATRIX)
/* Should not happen, but could, as long as I don't implement
* matrix locking.
*/
return ERR_INVALID_TYPE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
int4 n = matedit_i * rm->columns + matedit_j;
if (reg_x->type == TYPE_REAL) {
rm->array->is_string[n] = 0;
rm->array->data[n] = ((vartype_real *) reg_x)->x;
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING) {
vartype_string *s = (vartype_string *) reg_x;
int i;
rm->array->is_string[n] = 1;
phloat_length(rm->array->data[n]) = s->length;
for (i = 0; i < s->length; i++)
phloat_text(rm->array->data[n])[i] = s->text[i];
return ERR_NONE;
} else
return ERR_INVALID_TYPE;
} else /* m->type == TYPE_COMPLEXMATRIX */ {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
int4 n = matedit_i * cm->columns + matedit_j;
if (reg_x->type == TYPE_REAL) {
cm->array->data[2 * n] = ((vartype_real *) reg_x)->x;
cm->array->data[2 * n + 1] = 0;
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEX) {
vartype_complex *c = (vartype_complex *) reg_x;
cm->array->data[2 * n] = c->re;
cm->array->data[2 * n + 1] = c->im;
return ERR_NONE;
} else
return ERR_INVALID_TYPE;
}
}
int docmd_stoij(arg_struct *arg) {
vartype *m;
phloat x, y;
int4 i, j;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_x->type != TYPE_REAL)
return ERR_INVALID_TYPE;
if (reg_y->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_y->type != TYPE_REAL)
return ERR_INVALID_TYPE;
x = ((vartype_real *) reg_x)->x;
if (x <= -2147483648.0 || x >= 2147483648.0)
return ERR_DIMENSION_ERROR;
j = to_int4(x);
if (j < 0)
j = -j;
y = ((vartype_real *) reg_y)->x;
if (y <= -2147483648.0 || y >= 2147483648.0)
return ERR_DIMENSION_ERROR;
i = to_int4(y);
if (i < 0)
i = -i;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) m;
if (i == 0 || i > rm->rows || j == 0 || j > rm->columns)
return ERR_DIMENSION_ERROR;
} else if (m->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
if (i == 0 || i > cm->rows || j == 0 || j > cm->columns)
return ERR_DIMENSION_ERROR;
} else
/* Should not happen, but could, as long as I don't implement
* matrix locking. */
return ERR_INVALID_TYPE;
matedit_i = i - 1;
matedit_j = j - 1;
return ERR_NONE;
}
static int mappable_tanh_r(phloat x, phloat *y) {
*y = tanh(x);
return ERR_NONE;
}
static int mappable_tanh_c(phloat xre, phloat xim, phloat *yre, phloat *yim) {
phloat sinhxre, coshxre;
phloat sinxim, cosxim;
phloat re_sinh, re_cosh, im_sinh, im_cosh, abs_cosh;
int inf;
sinhxre = sinh(xre);
coshxre = cosh(xre);
sincos(xim, &sinxim, &cosxim);
re_sinh = sinhxre * cosxim;
im_sinh = coshxre * sinxim;
re_cosh = coshxre * cosxim;
im_cosh = sinhxre * sinxim;
abs_cosh = hypot(re_cosh, im_cosh);
if (abs_cosh == 0) {
if (flags.f.range_error_ignore) {
*yre = re_sinh * im_sinh + re_cosh * im_cosh > 0 ? POS_HUGE_PHLOAT
: NEG_HUGE_PHLOAT;
*yim = im_sinh * re_cosh - re_sinh * im_cosh > 0 ? POS_HUGE_PHLOAT
: NEG_HUGE_PHLOAT;
} else
return ERR_OUT_OF_RANGE;
}
*yre = (re_sinh * re_cosh + im_sinh * im_cosh) / abs_cosh / abs_cosh;
if ((inf = p_isinf(*yre)) != 0) {
if (flags.f.range_error_ignore)
*yre = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
*yim = (im_sinh * re_cosh - re_sinh * im_cosh) / abs_cosh / abs_cosh;
if ((inf = p_isinf(*yim)) != 0) {
if (flags.f.range_error_ignore)
*yim = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
return ERR_NONE;
}
int docmd_tanh(arg_struct *arg) {
if (reg_x->type != TYPE_STRING) {
vartype *v;
int err = map_unary(reg_x, &v, mappable_tanh_r, mappable_tanh_c);
if (err == ERR_NONE)
unary_result(v);
return err;
} else
return ERR_ALPHA_DATA_IS_INVALID;
}
int docmd_trans(arg_struct *arg) {
if (reg_x->type == TYPE_REALMATRIX) {
vartype_realmatrix *src = (vartype_realmatrix *) reg_x;
vartype_realmatrix *dst;
int4 rows = src->rows;
int4 columns = src->columns;
int4 i, j;
dst = (vartype_realmatrix *) new_realmatrix(columns, rows);
if (dst == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++) {
int4 n1 = i * columns + j;
int4 n2 = j * rows + i;
dst->array->is_string[n2] = src->array->is_string[n1];
dst->array->data[n2] = src->array->data[n1];
}
unary_result((vartype *) dst);
return ERR_NONE;
} else if (reg_x->type == TYPE_COMPLEXMATRIX) {
vartype_complexmatrix *src = (vartype_complexmatrix *) reg_x;
vartype_complexmatrix *dst;
int4 rows = src->rows;
int4 columns = src->columns;
int4 i, j;
dst = (vartype_complexmatrix *) new_complexmatrix(columns, rows);
if (dst == NULL)
return ERR_INSUFFICIENT_MEMORY;
for (i = 0; i < rows; i++)
for (j = 0; j < columns; j++) {
int4 n1 = 2 * (i * columns + j);
int4 n2 = 2 * (j * rows + i);
dst->array->data[n2] = src->array->data[n1];
dst->array->data[n2 + 1] = src->array->data[n1 + 1];
}
unary_result((vartype *) dst);
return ERR_NONE;
} else if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
else
return ERR_INVALID_TYPE;
}
int docmd_wrap(arg_struct *arg) {
flags.f.grow = 0;
return ERR_NONE;
}
int docmd_x_swap(arg_struct *arg) {
vartype *v;
int err = generic_rcl(arg, &v);
if (err != ERR_NONE)
return err;
err = generic_sto(arg, 0);
if (err != ERR_NONE)
free_vartype(v);
else {
free_vartype(reg_x);
reg_x = v;
if (flags.f.trace_print && flags.f.printer_exists)
docmd_prx(NULL);
}
return err;
}
#define DIR_LEFT 0
#define DIR_RIGHT 1
#define DIR_UP 2
#define DIR_DOWN 3
static int matedit_move(int direction) {
vartype *m, *v;
vartype_realmatrix *rm;
vartype_complexmatrix *cm;
int4 rows, columns, new_i, new_j, old_n, new_n;
int edge_flag = 0;
int end_flag = 0;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type == TYPE_REALMATRIX) {
rm = (vartype_realmatrix *) m;
rows = rm->rows;
columns = rm->columns;
} else if (m->type == TYPE_COMPLEXMATRIX) {
cm = (vartype_complexmatrix *) m;
rows = cm->rows;
columns = cm->columns;
} else
return ERR_INVALID_TYPE;
if (!disentangle(m))
return ERR_INSUFFICIENT_MEMORY;
new_i = matedit_i;
new_j = matedit_j;
switch (direction) {
case DIR_LEFT:
if (--new_j < 0) {
edge_flag = 1;
new_j = columns - 1;
if (--new_i < 0) {
end_flag = 1;
new_i = rows - 1;
}
}
break;
case DIR_RIGHT:
if (++new_j >= columns) {
edge_flag = 1;
new_j = 0;
if (++new_i >= rows) {
end_flag = 1;
if (flags.f.grow) {
int err;
if (matedit_mode == 2)
err = dimension_array_ref(matedit_x,
rows + 1, columns);
else
err = dimension_array(matedit_name, matedit_length,
rows + 1, columns);
if (err != ERR_NONE)
return err;
new_i = rows++;
} else
new_i = 0;
}
}
break;
case DIR_UP:
if (--new_i < 0) {
edge_flag = 1;
new_i = rows - 1;
if (--new_j < 0) {
end_flag = 1;
new_j = columns - 1;
}
}
break;
case DIR_DOWN:
if (++new_i >= rows) {
edge_flag = 1;
new_i = 0;
if (++new_j >= columns) {
end_flag = 1;
new_j = 0;
}
}
break;
}
old_n = matedit_i * columns + matedit_j;
new_n = new_i * columns + new_j;
if (m->type == TYPE_REALMATRIX) {
if (old_n != new_n) {
if (rm->array->is_string[new_n])
v = new_string(phloat_text(rm->array->data[new_n]),
phloat_length(rm->array->data[new_n]));
else
v = new_real(rm->array->data[new_n]);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
if (reg_x->type == TYPE_REAL) {
rm->array->is_string[old_n] = 0;
rm->array->data[old_n] = ((vartype_real *) reg_x)->x;
} else if (reg_x->type == TYPE_STRING) {
vartype_string *s = (vartype_string *) reg_x;
int i;
rm->array->is_string[old_n] = 1;
phloat_length(rm->array->data[old_n]) = s->length;
for (i = 0; i < s->length; i++)
phloat_text(rm->array->data[old_n])[i] = s->text[i];
} else {
free_vartype(v);
return ERR_INVALID_TYPE;
}
} else /* m->type == TYPE_COMPLEXMATRIX */ {
if (old_n != new_n) {
v = new_complex(cm->array->data[2 * new_n],
cm->array->data[2 * new_n + 1]);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
if (reg_x->type == TYPE_REAL) {
cm->array->data[2 * old_n] = ((vartype_real *) reg_x)->x;
cm->array->data[2 * old_n + 1] = 0;
} else if (reg_x->type == TYPE_COMPLEX) {
vartype_complex *c = (vartype_complex *) reg_x;
cm->array->data[2 * old_n] = c->re;
cm->array->data[2 * old_n + 1] = c->im;
} else {
free_vartype(v);
return ERR_INVALID_TYPE;
}
}
matedit_i = new_i;
matedit_j = new_j;
flags.f.matrix_edge_wrap = edge_flag;
flags.f.matrix_end_wrap = end_flag;
if (old_n != new_n) {
free_vartype(reg_x);
reg_x = v;
}
mode_disable_stack_lift = true;
if (flags.f.trace_print && flags.f.printer_enable)
docmd_prx(NULL);
return ERR_NONE;
}
int docmd_left(arg_struct *arg) {
return matedit_move(DIR_LEFT);
}
int docmd_up(arg_struct *arg) {
return matedit_move(DIR_UP);
}
int docmd_down(arg_struct *arg) {
return matedit_move(DIR_DOWN);
}
int docmd_right(arg_struct *arg) {
return matedit_move(DIR_RIGHT);
}
int docmd_percent_ch(arg_struct *arg) {
phloat x, y, r;
int inf;
vartype *v;
if (reg_x->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_x->type != TYPE_REAL)
return ERR_INVALID_TYPE;
if (reg_y->type == TYPE_STRING)
return ERR_ALPHA_DATA_IS_INVALID;
if (reg_y->type != TYPE_REAL)
return ERR_INVALID_TYPE;
x = ((vartype_real *) reg_x)->x;
y = ((vartype_real *) reg_y)->x;
if (y == 0)
return ERR_DIVIDE_BY_0;
r = (x - y) / y * 100;
if ((inf = p_isinf(r)) != 0) {
if (flags.f.range_error_ignore)
r = inf < 0 ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
else
return ERR_OUT_OF_RANGE;
}
v = new_real(r);
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
/* Binary function, but unary result, like % */
unary_result(v);
return ERR_NONE;
}
static vartype *matx_v;
static void matx_completion(int error, vartype *res) {
if (error != ERR_NONE) {
free_vartype(matx_v);
return;
}
store_var("MATX", 4, res);
matedit_prev_appmenu = MENU_MATRIX_SIMQ;
set_menu(MENULEVEL_APP, MENU_MATRIX_EDIT1);
/* NOTE: no need to use set_menu_return_err() here, since the MAT[ABX]
* commands can only be invoked from the SIMQ menu; the SIMQ menu
* has no exit callback, so leaving it never fails.
*/
set_appmenu_exitcallback(1);
if (res->type == TYPE_REALMATRIX) {
vartype_realmatrix *m = (vartype_realmatrix *) res;
vartype_real *v = (vartype_real *) matx_v;
v->x = m->array->data[0];
} else {
vartype_complexmatrix *m = (vartype_complexmatrix *) res;
vartype_complex *v = (vartype_complex *) matx_v;
v->re = m->array->data[0];
v->im = m->array->data[1];
}
free_vartype(reg_x);
reg_x = matx_v;
matedit_mode = 3;
matedit_length = 4;
matedit_name[0] = 'M';
matedit_name[1] = 'A';
matedit_name[2] = 'T';
matedit_name[3] = 'X';
matedit_i = 0;
matedit_j = 0;
}
static int matabx(int which) {
vartype *mat, *v;
switch (which) {
case 0:
mat = recall_var("MATA", 4);
break;
case 1:
mat = recall_var("MATB", 4);
break;
case 2: {
vartype *mata, *matb;
mata = recall_var("MATA", 4);
if (mata == NULL)
return ERR_NONEXISTENT;
if (mata->type != TYPE_REALMATRIX
&& mata->type != TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
matb = recall_var("MATB", 4);
if (matb == NULL)
return ERR_NONEXISTENT;
if (matb->type != TYPE_REALMATRIX
&& matb->type != TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
if (mata->type == TYPE_REALMATRIX && matb->type == TYPE_REALMATRIX)
matx_v = new_real(0);
else
matx_v = new_complex(0, 0);
if (matx_v == NULL)
return ERR_INSUFFICIENT_MEMORY;
return linalg_div(matb, mata, matx_completion);
}
}
if (mat->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm = (vartype_realmatrix *) mat;
if (rm->array->is_string[0])
v = new_string(phloat_text(rm->array->data[0]),
phloat_length(rm->array->data[0]));
else
v = new_real(rm->array->data[0]);
} else {
vartype_complexmatrix *cm = (vartype_complexmatrix *) mat;
v = new_complex(cm->array->data[0], cm->array->data[1]);
}
if (v == NULL)
return ERR_INSUFFICIENT_MEMORY;
matedit_prev_appmenu = MENU_MATRIX_SIMQ;
set_menu(MENULEVEL_APP, MENU_MATRIX_EDIT1);
/* NOTE: no need to use set_menu_return_err() here, since the MAT[ABX]
* commands can only be invoked from the SIMQ menu; the SIMQ menu
* has no exit callback, so leaving it never fails.
*/
set_appmenu_exitcallback(1);
free_vartype(reg_x);
reg_x = v;
matedit_mode = 3;
matedit_length = 4;
matedit_name[0] = 'M';
matedit_name[1] = 'A';
matedit_name[2] = 'T';
matedit_name[3] = which == 0 ? 'A' : 'B';
matedit_i = 0;
matedit_j = 0;
return ERR_NONE;
}
int docmd_mata(arg_struct *arg) {
return matabx(0);
}
int docmd_matb(arg_struct *arg) {
return matabx(1);
}
int docmd_matx(arg_struct *arg) {
return matabx(2);
}
int docmd_simq(arg_struct *arg) {
vartype *m, *mata, *matb, *matx;
int4 dim;
int err;
if (arg->type != ARGTYPE_NUM)
return ERR_INVALID_TYPE;
dim = arg->val.num;
if (dim <= 0)
return ERR_DIMENSION_ERROR;
m = recall_var("MATA", 4);
if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) {
mata = dup_vartype(m);
if (mata == NULL)
return ERR_INSUFFICIENT_MEMORY;
err = dimension_array_ref(mata, dim, dim);
if (err != ERR_NONE)
goto abort_and_free_a;
} else {
mata = new_realmatrix(dim, dim);
if (mata == NULL)
return ERR_INSUFFICIENT_MEMORY;
}
m = recall_var("MATB", 4);
if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) {
matb = dup_vartype(m);
if (matb == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a;
}
err = dimension_array_ref(matb, dim, 1);
if (err != ERR_NONE)
goto abort_and_free_a_b;
} else {
matb = new_realmatrix(dim, 1);
if (matb == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a;
}
}
m = recall_var("MATX", 4);
if (m != NULL && (m->type == TYPE_REALMATRIX || m->type == TYPE_COMPLEXMATRIX)) {
matx = dup_vartype(m);
if (matx == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a_b;
}
err = dimension_array_ref(matx, dim, 1);
if (err != ERR_NONE)
goto abort_and_free_a_b_x;
} else {
matx = new_realmatrix(dim, 1);
if (matx == NULL) {
err = ERR_INSUFFICIENT_MEMORY;
goto abort_and_free_a_b;
}
}
err = set_menu_return_err(MENULEVEL_APP, MENU_MATRIX_SIMQ);
if (err != ERR_NONE) {
/* Didn't work; we're stuck in the matrix editor
* waiting for the user to put something valid into X.
* (Then again, how can anyone issue the SIMQ command if
* they're in the matrix editor? SIMQ has the 'hidden'
* command property. Oh, well, better safe than sorry...)
*/
abort_and_free_a_b_x:
free_vartype(matx);
abort_and_free_a_b:
free_vartype(matb);
abort_and_free_a:
free_vartype(mata);
return err;
}
store_var("MATX", 4, matx);
store_var("MATB", 4, matb);
store_var("MATA", 4, mata);
return ERR_NONE;
}
static int max_min_helper(int do_max) {
vartype *m;
vartype_realmatrix *rm;
phloat max_or_min_value = do_max ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT;
int4 i, max_or_min_index = 0;
vartype *new_x, *new_y;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type != TYPE_REALMATRIX)
return ERR_INVALID_TYPE;
rm = (vartype_realmatrix *) m;
for (i = matedit_i; i < rm->rows; i++) {
int4 index = i * rm->columns + matedit_j;
phloat e;
if (rm->array->is_string[index])
return ERR_ALPHA_DATA_IS_INVALID;
e = rm->array->data[index];
if (do_max ? e >= max_or_min_value : e <= max_or_min_value) {
max_or_min_value = e;
max_or_min_index = i;
}
}
new_x = new_real(max_or_min_value);
if (new_x == NULL)
return ERR_INSUFFICIENT_MEMORY;
new_y = new_real(max_or_min_index + 1);
if (new_y == NULL) {
free_vartype(new_x);
return ERR_INSUFFICIENT_MEMORY;
}
recall_two_results(new_x, new_y);
return ERR_NONE;
}
int docmd_max(arg_struct *arg) {
return max_min_helper(1);
}
int docmd_min(arg_struct *arg) {
return max_min_helper(0);
}
int docmd_find(arg_struct *arg) {
vartype *m;
if (reg_x->type == TYPE_REALMATRIX || reg_x->type == TYPE_COMPLEXMATRIX)
return ERR_INVALID_TYPE;
switch (matedit_mode) {
case 0:
return ERR_NONEXISTENT;
case 1:
case 3:
m = recall_var(matedit_name, matedit_length);
break;
case 2:
m = matedit_x;
break;
default:
return ERR_INTERNAL_ERROR;
}
if (m == NULL)
return ERR_NONEXISTENT;
if (m->type == TYPE_REALMATRIX) {
vartype_realmatrix *rm;
int4 i, j, p = 0;
if (reg_x->type == TYPE_COMPLEX)
return ERR_NO;
rm = (vartype_realmatrix *) m;
if (reg_x->type == TYPE_REAL) {
phloat d = ((vartype_real *) reg_x)->x;
for (i = 0; i < rm->rows; i++)
for (j = 0; j < rm->columns; j++)
if (!rm->array->is_string[p] && rm->array->data[p] == d) {
matedit_i = i;
matedit_j = j;
return ERR_YES;
} else
p++;
} else /* reg_x->type == TYPE_STRING */ {
vartype_string *s = (vartype_string *) reg_x;
for (i = 0; i < rm->rows; i++)
for (j = 0; j < rm->columns; j++)
if (rm->array->is_string[p]
&& string_equals(s->text, s->length,
phloat_text(rm->array->data[p]),
phloat_length(rm->array->data[p]))) {
matedit_i = i;
matedit_j = j;
return ERR_YES;
} else
p++;
}
} else /* m->type == TYPE_COMPLEXMATRIX */ {
vartype_complexmatrix *cm;
int4 i, j, p = 0;
phloat re, im;
if (reg_x->type != TYPE_COMPLEX)
return ERR_NO;
cm = (vartype_complexmatrix *) m;
re = ((vartype_complex *) reg_x)->re;
im = ((vartype_complex *) reg_x)->im;
for (i = 0; i < cm->rows; i++)
for (j = 0; j < cm->columns; j++)
if (cm->array->data[p] == re && cm->array->data[p + 1] == im) {
matedit_i = i;
matedit_j = j;
return ERR_YES;
} else
p += 2;
}
return ERR_NO;
}
int docmd_xrom(arg_struct *arg) {
return ERR_NONEXISTENT;
}
| Java |
/*
* mpc8610-pcm.h - ALSA PCM interface for the Freescale MPC8610 SoC
*
* 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.
*/
#ifndef _MPC8610_PCM_H
#define _MPC8610_PCM_H
struct ccsr_dma {
u8 res0[0x100];
struct ccsr_dma_channel {
__be32 mr; /* Mode register */
__be32 sr; /* Status register */
__be32 eclndar; /* Current link descriptor extended addr reg */
__be32 clndar; /* Current link descriptor address register */
__be32 satr; /* Source attributes register */
__be32 sar; /* Source address register */
__be32 datr; /* Destination attributes register */
__be32 dar; /* Destination address register */
__be32 bcr; /* Byte count register */
__be32 enlndar; /* Next link descriptor extended address reg */
__be32 nlndar; /* Next link descriptor address register */
u8 res1[4];
__be32 eclsdar; /* Current list descriptor extended addr reg */
__be32 clsdar; /* Current list descriptor address register */
__be32 enlsdar; /* Next list descriptor extended address reg */
__be32 nlsdar; /* Next list descriptor address register */
__be32 ssr; /* Source stride register */
__be32 dsr; /* Destination stride register */
u8 res2[0x38];
} channel[4];
__be32 dgsr;
};
#define CCSR_DMA_MR_BWC_DISABLED 0x0F000000
#define CCSR_DMA_MR_BWC_SHIFT 24
#define CCSR_DMA_MR_BWC_MASK 0x0F000000
#define CCSR_DMA_MR_BWC(x) \
((ilog2(x) << CCSR_DMA_MR_BWC_SHIFT) & CCSR_DMA_MR_BWC_MASK)
#define CCSR_DMA_MR_EMP_EN 0x00200000
#define CCSR_DMA_MR_EMS_EN 0x00040000
#define CCSR_DMA_MR_DAHTS_MASK 0x00030000
#define CCSR_DMA_MR_DAHTS_1 0x00000000
#define CCSR_DMA_MR_DAHTS_2 0x00010000
#define CCSR_DMA_MR_DAHTS_4 0x00020000
#define CCSR_DMA_MR_DAHTS_8 0x00030000
#define CCSR_DMA_MR_SAHTS_MASK 0x0000C000
#define CCSR_DMA_MR_SAHTS_1 0x00000000
#define CCSR_DMA_MR_SAHTS_2 0x00004000
#define CCSR_DMA_MR_SAHTS_4 0x00008000
#define CCSR_DMA_MR_SAHTS_8 0x0000C000
#define CCSR_DMA_MR_DAHE 0x00002000
#define CCSR_DMA_MR_SAHE 0x00001000
#define CCSR_DMA_MR_SRW 0x00000400
#define CCSR_DMA_MR_EOSIE 0x00000200
#define CCSR_DMA_MR_EOLNIE 0x00000100
#define CCSR_DMA_MR_EOLSIE 0x00000080
#define CCSR_DMA_MR_EIE 0x00000040
#define CCSR_DMA_MR_XFE 0x00000020
#define CCSR_DMA_MR_CDSM_SWSM 0x00000010
#define CCSR_DMA_MR_CA 0x00000008
#define CCSR_DMA_MR_CTM 0x00000004
#define CCSR_DMA_MR_CC 0x00000002
#define CCSR_DMA_MR_CS 0x00000001
#define CCSR_DMA_SR_TE 0x00000080
#define CCSR_DMA_SR_CH 0x00000020
#define CCSR_DMA_SR_PE 0x00000010
#define CCSR_DMA_SR_EOLNI 0x00000008
#define CCSR_DMA_SR_CB 0x00000004
#define CCSR_DMA_SR_EOSI 0x00000002
#define CCSR_DMA_SR_EOLSI 0x00000001
/* ECLNDAR takes bits 32-36 of the CLNDAR register */
static inline u32 CCSR_DMA_ECLNDAR_ADDR(u64 x)
{
return (x >> 32) & 0xf;
}
#define CCSR_DMA_CLNDAR_ADDR(x) ((x) & 0xFFFFFFFE)
#define CCSR_DMA_CLNDAR_EOSIE 0x00000008
/* SATR and DATR, combined */
#define CCSR_DMA_ATR_PBATMU 0x20000000
#define CCSR_DMA_ATR_TFLOWLVL_0 0x00000000
#define CCSR_DMA_ATR_TFLOWLVL_1 0x06000000
#define CCSR_DMA_ATR_TFLOWLVL_2 0x08000000
#define CCSR_DMA_ATR_TFLOWLVL_3 0x0C000000
#define CCSR_DMA_ATR_PCIORDER 0x02000000
#define CCSR_DMA_ATR_SME 0x01000000
#define CCSR_DMA_ATR_NOSNOOP 0x00040000
#define CCSR_DMA_ATR_SNOOP 0x00050000
#define CCSR_DMA_ATR_ESAD_MASK 0x0000000F
/**
* List Descriptor for extended chaining mode DMA operations.
*
* The CLSDAR register points to the first (in a linked-list) List
* Descriptor. Each object must be aligned on a 32-byte boundary. Each
* list descriptor points to a linked-list of link Descriptors.
*/
struct fsl_dma_list_descriptor {
__be64 next; /* Address of next list descriptor */
__be64 first_link; /* Address of first link descriptor */
__be32 source; /* Source stride */
__be32 dest; /* Destination stride */
u8 res[8]; /* Reserved */
} __attribute__ ((aligned(32), packed));
/**
* Link Descriptor for basic and extended chaining mode DMA operations.
*
* A Link Descriptor points to a single DMA buffer. Each link descriptor
* must be aligned on a 32-byte boundary.
*/
struct fsl_dma_link_descriptor {
__be32 source_attr; /* Programmed into SATR register */
__be32 source_addr; /* Programmed into SAR register */
__be32 dest_attr; /* Programmed into DATR register */
__be32 dest_addr; /* Programmed into DAR register */
__be64 next; /* Address of next link descriptor */
__be32 count; /* Byte count */
u8 res[4]; /* Reserved */
} __attribute__ ((aligned(32), packed));
<<<<<<< HEAD
=======
/* DMA information needed to create a snd_soc_dai object
*
* ssi_stx_phys: bus address of SSI STX register to use
* ssi_srx_phys: bus address of SSI SRX register to use
* dma[0]: points to the DMA channel to use for playback
* dma[1]: points to the DMA channel to use for capture
* dma_irq[0]: IRQ of the DMA channel to use for playback
* dma_irq[1]: IRQ of the DMA channel to use for capture
*/
struct fsl_dma_info {
dma_addr_t ssi_stx_phys;
dma_addr_t ssi_srx_phys;
struct ccsr_dma_channel __iomem *dma_channel[2];
unsigned int dma_irq[2];
};
extern struct snd_soc_platform fsl_soc_platform;
int fsl_dma_configure(struct fsl_dma_info *dma_info);
>>>>>>> 296c66da8a02d52243f45b80521febece5ed498a
#endif
| Java |
ALTER TABLE db_version CHANGE COLUMN required_z0652_134_01_mangos_creature_model_info required_z0662_135_01_mangos_mangos_string bit;
DELETE FROM mangos_string WHERE entry BETWEEN 1149 AND 1151;
INSERT INTO mangos_string VALUES
(1149,' (Pool %u)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
(1150,' (Event %i)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL),
(1151,' (Pool %u Event %i)',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL);
DELETE FROM mangos_string WHERE entry in (515, 517, 1110, 1111, 1137);
INSERT INTO mangos_string VALUES
(515,'%d%s - |cffffffff|Hcreature:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r ',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_CREATURE_LIST_CHAT (.list creature)
(517,'%d%s, Entry %d - |cffffffff|Hgameobject:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_GO_MIXED_LIST_CHAT (.gobject near)
(1110,'%d%s - %s X:%f Y:%f Z:%f MapId:%d',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_CREATURE_LIST_CONSOLE
(1111,'%d%s - %s X:%f Y:%f Z:%f MapId:%d',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL), -- LANG_GO_LIST_CONSOLE
(1137,'%d%s - |cffffffff|Hgameobject:%d|h[%s X:%f Y:%f Z:%f MapId:%d]|h|r ',NULL,NULL,NULL,NULL,NULL,NULL,NULL,NULL); -- LANG_GO_LIST_CHAT (.list object) | Java |
/*
* HT Editor
* syssdl.h
*
* Copyright (C) 2004 Stefan Weyergraf
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#ifndef __SYSSDL_H__
#define __SYSSDL_H__
#ifdef __MACH__
#include <SDL/SDL.h>
#else
#include <SDL.h>
#endif
#include "system/display.h"
#include "system/systhread.h"
extern SDL_Surface * gSDLScreen;
class SDLSystemDisplay: public SystemDisplay {
protected:
DisplayCharacteristics mSDLChar;
byte * mSDLFrameBuffer;
bool mChangingScreen;
SDL_Surface * mSDLClientScreen;
sys_mutex mRedrawMutex;
SDL_Cursor * mVisibleCursor;
SDL_Cursor * mInvisibleCursor;
uint bitsPerPixelToXBitmapPad(uint bitsPerPixel);
void dumpDisplayChar(const DisplayCharacteristics &chr);
public:
char * mTitle;
DisplayCharacteristics mSDLChartemp;
SDL_cond *mWaitcondition;
bool mChangeResRet;
uint32 mEventThreadID;
SDLSystemDisplay(const char *title, const DisplayCharacteristics &chr, int redraw_ms);
void finishMenu();
virtual void updateTitle();
virtual int toString(char *buf, int buflen) const;
void toggleFullScreen();
virtual void displayShow();
virtual void convertCharacteristicsToHost(DisplayCharacteristics &aHostChar, const DisplayCharacteristics &aClientChar);
virtual bool changeResolution(const DisplayCharacteristics &aCharacteristics);
virtual bool changeResolutionREAL(const DisplayCharacteristics &aCharacteristics);
virtual void getHostCharacteristics(Container &modes);
virtual void setMouseGrab(bool enable);
virtual void initCursor();
};
#endif
| Java |
/***************************************************/
/*! \class BiQuad
\brief STK biquad (two-pole, two-zero) filter class.
This class implements a two-pole, two-zero digital filter.
Methods are provided for creating a resonance or notch in the
frequency response while maintaining a constant filter gain.
by Perry R. Cook and Gary P. Scavone, 1995-2012.
*/
/***************************************************/
#include "BiQuad.h"
#include <cmath>
namespace stk {
BiQuad :: BiQuad() : Filter()
{
b_.resize( 3, 0.0 );
a_.resize( 3, 0.0 );
b_[0] = 1.0;
a_[0] = 1.0;
inputs_.resize( 3, 1, 0.0 );
outputs_.resize( 3, 1, 0.0 );
Stk::addSampleRateAlert( this );
}
BiQuad :: ~BiQuad()
{
Stk::removeSampleRateAlert( this );
}
void BiQuad :: setCoefficients( StkFloat b0, StkFloat b1, StkFloat b2, StkFloat a1, StkFloat a2, bool clearState )
{
b_[0] = b0;
b_[1] = b1;
b_[2] = b2;
a_[1] = a1;
a_[2] = a2;
if ( clearState ) this->clear();
}
void BiQuad :: sampleRateChanged( StkFloat newRate, StkFloat oldRate )
{
if ( !ignoreSampleRateChange_ ) {
std::cerr << "BiQuad::sampleRateChanged: you may need to recompute filter coefficients!";
handleError( StkError::WARNING );
}
}
void BiQuad :: setResonance( StkFloat frequency, StkFloat radius, bool normalize )
{
#if defined(_STK_DEBUG_)
if ( frequency < 0.0 || frequency > 0.5 * Stk::sampleRate() ) {
std::cerr << "BiQuad::setResonance: frequency argument (" << frequency << ") is out of range!";
handleError( StkError::WARNING ); return;
}
if ( radius < 0.0 || radius >= 1.0 ) {
std::cerr << "BiQuad::setResonance: radius argument (" << radius << ") is out of range!";
handleError( StkError::WARNING ); return;
}
#endif
a_[2] = radius * radius;
a_[1] = -2.0 * radius * cos( TWO_PI * frequency / Stk::sampleRate() );
if ( normalize ) {
// Use zeros at +- 1 and normalize the filter peak gain.
b_[0] = 0.5 - 0.5 * a_[2];
b_[1] = 0.0;
b_[2] = -b_[0];
}
}
void BiQuad :: setNotch( StkFloat frequency, StkFloat radius )
{
#if defined(_STK_DEBUG_)
if ( frequency < 0.0 || frequency > 0.5 * Stk::sampleRate() ) {
std::cerr << "BiQuad::setNotch: frequency argument (" << frequency << ") is out of range!";
handleError( StkError::WARNING ); return;
}
if ( radius < 0.0 ) {
std::cerr << "BiQuad::setNotch: radius argument (" << radius << ") is negative!";
handleError( StkError::WARNING ); return;
}
#endif
// This method does not attempt to normalize the filter gain.
b_[2] = radius * radius;
b_[1] = (StkFloat) -2.0 * radius * cos( TWO_PI * (double) frequency / Stk::sampleRate() );
}
void BiQuad :: setEqualGainZeroes( void )
{
b_[0] = 1.0;
b_[1] = 0.0;
b_[2] = -1.0;
}
} // stk namespace
| Java |
/*
* Copyright (C) 2005-2014 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 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mpqfile.h"
#include <deque>
#include <cstdio>
#include "StormLib.h"
MPQFile::MPQFile(HANDLE mpq, const char* filename, bool warnNoExist /*= true*/) :
eof(false),
buffer(0),
pointer(0),
size(0)
{
HANDLE file;
if (!SFileOpenFileEx(mpq, filename, SFILE_OPEN_PATCHED_FILE, &file))
{
if (warnNoExist || GetLastError() != ERROR_FILE_NOT_FOUND)
fprintf(stderr, "Can't open %s, err=%u!\n", filename, GetLastError());
eof = true;
return;
}
DWORD hi = 0;
size = SFileGetFileSize(file, &hi);
if (hi)
{
fprintf(stderr, "Can't open %s, size[hi] = %u!\n", filename, uint32(hi));
SFileCloseFile(file);
eof = true;
return;
}
if (size <= 1)
{
fprintf(stderr, "Can't open %s, size = %u!\n", filename, uint32(size));
SFileCloseFile(file);
eof = true;
return;
}
DWORD read = 0;
buffer = new char[size];
if (!SFileReadFile(file, buffer, size, &read) || size != read)
{
fprintf(stderr, "Can't read %s, size=%u read=%u!\n", filename, uint32(size), uint32(read));
SFileCloseFile(file);
eof = true;
return;
}
SFileCloseFile(file);
}
size_t MPQFile::read(void* dest, size_t bytes)
{
if (eof) return 0;
size_t rpos = pointer + bytes;
if (rpos > size) {
bytes = size - pointer;
eof = true;
}
memcpy(dest, &(buffer[pointer]), bytes);
pointer = rpos;
return bytes;
}
void MPQFile::seek(int offset)
{
pointer = offset;
eof = (pointer >= size);
}
void MPQFile::seekRelative(int offset)
{
pointer += offset;
eof = (pointer >= size);
}
void MPQFile::close()
{
if (buffer) delete[] buffer;
buffer = 0;
eof = true;
}
| Java |
<div><p><br/></p></div><div class="container">
<div class="row">
<div id="index" class="col-md-3">
<div >
<div class="panel panel-default">
<div class="panel-heading">Classes</div>
<div class="panel-body"><a href="/docs/api/BB_Frame"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Frame</span></span></a></div>
<div class="panel-body"><a href="/docs/api/BB_RecPlayer"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">RecPlayer</span></span></a></div>
<div class="panel-body"><a href="/docs/api/BB_Recording"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Recording</span></span></a></div>
<div class="panel-body"><a href="/docs/api/BB_Session"><span class="indent" style="padding-left:14px;"><i class="icon-jsdoc icon-jsdoc-class"></i><span class="jsdoc-class-index">Session</span></span></a></div>
<div class="panel-body"><a href="/docs/api/_global_"><span class="indent" style="padding-left:0px;"><i class="icon-jsdoc icon-jsdoc-namespace"></i><span class="jsdoc-class-index">_global_</span></span></a></div>
</div>
</div>
</div>
<div id="content" class="col-md-9">
<pre class="prettyprint linenums">goog.provide('BB.Session');
goog.require('BB.Frame');
goog.require('BB.Recording');
/**
*
* @param {string} backendUrl
* @param {number=} fps
* @param {string=} title
* @param {string=} url
*
* @constructor
*/
BB.Session = function(backendUrl, fps, title, url) {
/** @type {string} */
this.backendUrl = backendUrl;
/** @type {number} */
this.fps = fps || 3;
/** @type {number} */
this.TICK_MILLI = 1000 / this.fps;
/** @type {string} */
this.title = title || BB.Session.getPageTitle();
/** @type {string} */
this.url = url || BB.Session.getPageUrl();
/** @type {Array.<BB.Frame>} */
this.frames = [];
/** @type {boolean} */
this.active = false;
/** @type {number} Pointer to setTimeout */
this.timer;
/** @type {boolean} */
this.clicked = false;
this.init();
};
/**
* @private
*/
BB.Session.prototype.init = function(){
var self = this;
document.addEventListener('mousemove', function(e) {
BB.Session.mouse.x = e.clientX || e.pageX;
BB.Session.mouse.y = e.clientY || e.pageY;
}, false);
document.addEventListener('click', function(e) {
self.clicked = true;
}, false);
};
/**
* Start recording a session
*/
BB.Session.prototype.start = function(){
if (!this.active) {
this.active = true;
this.tick();
}
};
/**
* Stop recording a session
*/
BB.Session.prototype.stop = function(){
clearTimeout(this.timer);
this.active = false;
};
/**
* Captures the current frame
*
* @private
*/
BB.Session.prototype.tick = function(){
if (this.active) {
var frame = new BB.Frame(
BB.Frame.getCurrentWin(),
BB.Frame.getCurrentScroll(),
BB.Frame.getCurrentMouse(),
this.clicked
);
this.frames.push(frame);
this.timer = setTimeout(this.tick.bind(this), this.TICK_MILLI);
this.clicked = false;
}
};
/**
* Send recording to backend server
*/
BB.Session.prototype.upload = function(){
var xhr = new XMLHttpRequest();
xhr.open('POST', '/save.php', true);
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.send('recording=' + this.toString());
};
/**
*
* @returns {string}
*/
BB.Session.getPageTitle = function() {
var el = document.getElementsByTagName('title');
var title = 'Untitled document';
if (el.length > 0) {
title = el[0].textContent;
}
return title;
};
/**
*
* @returns {string}
*/
BB.Session.getPageUrl = function(){
return window.location.href;
};
/**
*
* @returns {string}
*/
BB.Session.prototype.toString = function(){
return JSON.stringify(
new BB.Recording(this.title, this.url, BB.Frame.getClientRes(), this.fps, this.frames)
);
};
/**
*
* @type {BB.mouse}
*/
BB.Session.mouse = {
x: 0,
y: 0
};
</div>
</div>
</div>
<script type="text/javascript">
prettyPrint();
var i = 1;
$('#source-code li').each(function() {
$(this).attr({ id: 'line' + (i++) });
});
</script>
</div></div> | Java |
import urllib2
import appuifw, e32
from key_codes import *
class Drinker(object):
def __init__(self):
self.id = 0
self.name = ""
self.prom = 0.0
self.idle = ""
self.drinks = 0
def get_drinker_list():
data = urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/get_datas/").read().split("\n")
drinkers = []
for data_row in data:
if data_row == '': continue
fields = data_row.split('|')
drinker = Drinker()
drinker.id = int(fields[0])
drinker.name = fields[1]
drinker.drinks = int(fields[2])
drinker.prom = float(fields[3])
drinker.idle = fields[4]
drinkers.append(drinker)
return drinkers
def get_listbox_items(drinkers):
items = []
for drinker in drinkers:
items.append(unicode('%s, %d drinks, %s' % (drinker.name, drinker.drinks, drinker.idle)))
return items
appuifw.app.title = u"Alkoholilaskuri"
app_lock = e32.Ao_lock()
#Define the exit function
def quit():
app_lock.signal()
appuifw.app.exit_key_handler = quit
drinkers = get_drinker_list()
items = get_listbox_items(drinkers)
#Define a function that is called when an item is selected
def handle_selection():
selected_drinker = drinkers[lb.current()]
urllib2.urlopen("http://192.168.11.5:8080/drinkcounter/add_drink/%d/" % (selected_drinker.id))
appuifw.note(u"A drink has been added to " + drinkers[lb.current()].name, 'info')
new_drinkers = get_drinker_list()
items = get_listbox_items(new_drinkers)
lb.set_list(items, lb.current())
#Create an instance of Listbox and set it as the application's body
lb = appuifw.Listbox(items, handle_selection)
appuifw.app.body = lb
app_lock.wait()
| Java |
package com.mikesantiago.mariofighter;
import static com.mikesantiago.mariofighter.GlobalVariables.PPM;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.Fixture;
import com.badlogic.gdx.physics.box2d.FixtureDef;
import com.badlogic.gdx.physics.box2d.PolygonShape;
import com.badlogic.gdx.physics.box2d.World;
import com.mikesantiago.mariofighter.assets.Animation;
public class PlayerOne
{
public enum Direction
{
LEFT, RIGHT, STOP
}
private BodyDef playerBodyDef;
private Body playerBody;
private PolygonShape playerShape;
private FixtureDef playerFixtureDef;
private Fixture playerFixture;
private boolean isMoving = false;
private Direction currentDirection = Direction.RIGHT;
private Animation animationRight;
private Animation animationLeft;
public boolean getMoving(){return isMoving;}
public Direction getCurrentDirection(){return currentDirection;}
public PlayerOne(World worldToCreateIn)
{
playerBodyDef = new BodyDef();
playerBodyDef.type = BodyType.DynamicBody;
playerBodyDef.position.set(new Vector2(32f / PPM, 256f / PPM));
playerBody = worldToCreateIn.createBody(playerBodyDef);
playerShape = new PolygonShape();
playerShape.setAsBox((32f / 2) / PPM, (36f / 2) / PPM);
playerFixtureDef = new FixtureDef();
playerFixtureDef.shape = playerShape;
playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT;
playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT;
playerFixture = playerBody.createFixture(playerFixtureDef);
playerFixture.setUserData("body");
//create foot sensor
{
playerShape.setAsBox(2 / PPM, 2 / PPM, new Vector2(0, -32 / PPM), 0);
playerFixtureDef.shape = playerShape;
playerFixtureDef.filter.categoryBits = GlobalVariables.PLAYER_BIT;
playerFixtureDef.filter.maskBits = GlobalVariables.GROUND_BIT;
playerFixtureDef.isSensor = true;
playerBody.createFixture(playerFixtureDef).setUserData("FOOT");
}
CreateAnimation();
System.out.println("Player 1 created!");
}
private void CreateAnimation()
{
float updateInterval = 1 / 20f;
Texture tex = GlobalVariables.manager.GetTexture("mario");
TextureRegion[] sprites = TextureRegion.split(tex, 16, 28)[0];
if(animationRight == null)
animationRight = new Animation();
animationRight.setFrames(sprites, updateInterval);
if(animationLeft == null)
animationLeft = new Animation();
TextureRegion[] leftSprites = TextureRegion.split(tex, 16, 28)[0];
for(TextureRegion tr : leftSprites)
tr.flip(true, false);
animationLeft.setFrames(leftSprites, updateInterval);
sprWidth = sprites[0].getRegionWidth();
sprHeight = sprites[0].getRegionHeight();
}
private int sprWidth, sprHeight;
public void update(float dt)
{
if(this.isMoving)
{
animationRight.update(dt);
animationLeft.update(dt);
}
}
public void render(SpriteBatch sb)
{
if(!sb.isDrawing())
sb.begin();
sb.setProjectionMatrix(GlobalVariables.maincamera.combined);
if(this.isMoving)
{
if(this.currentDirection == Direction.RIGHT)
{
sb.draw(animationRight.getFrame(),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
else if(this.currentDirection == Direction.LEFT)
{
sb.draw(animationLeft.getFrame(),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
}
else
{
if(this.currentDirection == Direction.RIGHT)
{
sb.draw(animationRight.getFrame(0),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
else if(this.currentDirection == Direction.LEFT)
{
sb.draw(animationLeft.getFrame(0),
(playerBody.getPosition().x * PPM) - 16, (playerBody.getPosition().y * PPM) - 34,
sprWidth * 2, sprHeight * 2);
}
}
if(sb.isDrawing())
sb.end();
}
public void setMoving(boolean a){this.isMoving = a;}
public void setCurrentDirection(Direction a){currentDirection = a;}
public BodyDef getPlayerBodyDef() {
return playerBodyDef;
}
public void setPlayerBodyDef(BodyDef playerBodyDef) {
this.playerBodyDef = playerBodyDef;
}
public Body getPlayerBody() {
return playerBody;
}
public void setPlayerBody(Body playerBody) {
this.playerBody = playerBody;
}
public PolygonShape getPlayerShape() {
return playerShape;
}
public void setPlayerShape(PolygonShape playerShape) {
this.playerShape = playerShape;
}
public FixtureDef getPlayerFixtureDef() {
return playerFixtureDef;
}
public void setPlayerFixtureDef(FixtureDef playerFixtureDef) {
this.playerFixtureDef = playerFixtureDef;
}
public Fixture getPlayerFixture() {
return playerFixture;
}
public void setPlayerFixture(Fixture playerFixture) {
this.playerFixture = playerFixture;
}
}
| Java |
#include "exec/def-helper.h"
#ifdef CONFIG_TCG_PLUGIN
DEF_HELPER_FLAGS_4(tcg_plugin_pre_tb, 0, void, i64, i64, i64, i64)
#endif
DEF_HELPER_2(exception, noreturn, env, i32)
DEF_HELPER_3(exception_cause, noreturn, env, i32, i32)
DEF_HELPER_4(exception_cause_vaddr, noreturn, env, i32, i32, i32)
DEF_HELPER_3(debug_exception, noreturn, env, i32, i32)
DEF_HELPER_FLAGS_1(nsa, TCG_CALL_NO_RWG_SE, i32, i32)
DEF_HELPER_FLAGS_1(nsau, TCG_CALL_NO_RWG_SE, i32, i32)
DEF_HELPER_2(wsr_windowbase, void, env, i32)
DEF_HELPER_4(entry, void, env, i32, i32, i32)
DEF_HELPER_2(retw, i32, env, i32)
DEF_HELPER_2(rotw, void, env, i32)
DEF_HELPER_3(window_check, void, env, i32, i32)
DEF_HELPER_1(restore_owb, void, env)
DEF_HELPER_2(movsp, void, env, i32)
DEF_HELPER_2(wsr_lbeg, void, env, i32)
DEF_HELPER_2(wsr_lend, void, env, i32)
DEF_HELPER_1(simcall, void, env)
DEF_HELPER_1(dump_state, void, env)
DEF_HELPER_3(waiti, void, env, i32, i32)
DEF_HELPER_3(timer_irq, void, env, i32, i32)
DEF_HELPER_2(advance_ccount, void, env, i32)
DEF_HELPER_1(check_interrupts, void, env)
DEF_HELPER_3(check_atomctl, void, env, i32, i32)
DEF_HELPER_2(wsr_rasid, void, env, i32)
DEF_HELPER_FLAGS_3(rtlb0, TCG_CALL_NO_RWG_SE, i32, env, i32, i32)
DEF_HELPER_FLAGS_3(rtlb1, TCG_CALL_NO_RWG_SE, i32, env, i32, i32)
DEF_HELPER_3(itlb, void, env, i32, i32)
DEF_HELPER_3(ptlb, i32, env, i32, i32)
DEF_HELPER_4(wtlb, void, env, i32, i32, i32)
DEF_HELPER_2(wsr_ibreakenable, void, env, i32)
DEF_HELPER_3(wsr_ibreaka, void, env, i32, i32)
DEF_HELPER_3(wsr_dbreaka, void, env, i32, i32)
DEF_HELPER_3(wsr_dbreakc, void, env, i32, i32)
DEF_HELPER_2(wur_fcr, void, env, i32)
DEF_HELPER_FLAGS_1(abs_s, TCG_CALL_NO_RWG_SE, f32, f32)
DEF_HELPER_FLAGS_1(neg_s, TCG_CALL_NO_RWG_SE, f32, f32)
DEF_HELPER_3(add_s, f32, env, f32, f32)
DEF_HELPER_3(sub_s, f32, env, f32, f32)
DEF_HELPER_3(mul_s, f32, env, f32, f32)
DEF_HELPER_4(madd_s, f32, env, f32, f32, f32)
DEF_HELPER_4(msub_s, f32, env, f32, f32, f32)
DEF_HELPER_FLAGS_3(ftoi, TCG_CALL_NO_RWG_SE, i32, f32, i32, i32)
DEF_HELPER_FLAGS_3(ftoui, TCG_CALL_NO_RWG_SE, i32, f32, i32, i32)
DEF_HELPER_3(itof, f32, env, i32, i32)
DEF_HELPER_3(uitof, f32, env, i32, i32)
DEF_HELPER_4(un_s, void, env, i32, f32, f32)
DEF_HELPER_4(oeq_s, void, env, i32, f32, f32)
DEF_HELPER_4(ueq_s, void, env, i32, f32, f32)
DEF_HELPER_4(olt_s, void, env, i32, f32, f32)
DEF_HELPER_4(ult_s, void, env, i32, f32, f32)
DEF_HELPER_4(ole_s, void, env, i32, f32, f32)
DEF_HELPER_4(ule_s, void, env, i32, f32, f32)
#include "exec/def-helper.h"
| Java |
<?php
class Request {
public static function redirect($to) {
header('Location: ' . Config::get('url') . $to);
}
public static function path() {
return $_SERVER['REQUEST_URI'];
}
public static function method() {
$method = $_SERVER['REQUEST_METHOD'];
if($method === 'PUT') return 'put';
if($method === 'GET') return 'post';
if($method === 'GET') return 'get';
if($method === 'HEAD') return 'head';
if($method === 'DELETE') return 'delete';
if($method === 'OPTIONS') return 'options';
return false;
}
public static function isMethod($method) {
if(self::method() === $method) {
return true;
}
return false;
}
}
| Java |
# show_off_web_app/services
| Java |
/* Copyright (c) 2012, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/gpio.h>
#include <linux/slab.h>
#include <linux/of_gpio.h>
#include <linux/platform_device.h>
#include <linux/irq.h>
#include <media/rc-core.h>
#include <media/gpio-ir-recv.h>
#define GPIO_IR_DRIVER_NAME "gpio-rc-recv"
#define GPIO_IR_DEVICE_NAME "gpio_ir_recv"
struct gpio_rc_dev {
struct rc_dev *rcdev;
unsigned int gpio_nr;
bool active_low;
int can_sleep;
};
#ifdef CONFIG_OF
/*
* Translate OpenFirmware node properties into platform_data
*/
static int gpio_ir_recv_get_devtree_pdata(struct device *dev,
struct gpio_ir_recv_platform_data *pdata)
{
struct device_node *np = dev->of_node;
enum of_gpio_flags flags;
int gpio;
gpio = of_get_gpio_flags(np, 0, &flags);
if (gpio < 0) {
if (gpio != -EPROBE_DEFER)
dev_err(dev, "Failed to get gpio flags (%d)\n", gpio);
return gpio;
}
pdata->gpio_nr = gpio;
pdata->active_low = (flags & OF_GPIO_ACTIVE_LOW);
/* probe() takes care of map_name == NULL or allowed_protos == 0 */
pdata->map_name = of_get_property(np, "linux,rc-map-name", NULL);
pdata->allowed_protos = 0;
return 0;
}
static struct of_device_id gpio_ir_recv_of_match[] = {
{ .compatible = "gpio-ir-receiver", },
{ },
};
MODULE_DEVICE_TABLE(of, gpio_ir_recv_of_match);
#else /* !CONFIG_OF */
#define gpio_ir_recv_get_devtree_pdata(dev, pdata) (-ENOSYS)
#endif
static irqreturn_t gpio_ir_recv_irq(int irq, void *dev_id)
{
struct gpio_rc_dev *gpio_dev = dev_id;
unsigned int gval;
int rc = 0;
enum raw_event_type type = IR_SPACE;
if (gpio_dev->can_sleep)
gval = gpio_get_value_cansleep(gpio_dev->gpio_nr);
else
gval = gpio_get_value(gpio_dev->gpio_nr);
if (gval < 0)
goto err_get_value;
if (gpio_dev->active_low)
gval = !gval;
if (gval == 1)
type = IR_PULSE;
rc = ir_raw_event_store_edge(gpio_dev->rcdev, type);
if (rc < 0)
goto err_get_value;
ir_raw_event_handle(gpio_dev->rcdev);
err_get_value:
return IRQ_HANDLED;
}
static int gpio_ir_recv_probe(struct platform_device *pdev)
{
struct gpio_rc_dev *gpio_dev;
struct rc_dev *rcdev;
const struct gpio_ir_recv_platform_data *pdata =
pdev->dev.platform_data;
int rc;
if (pdev->dev.of_node) {
struct gpio_ir_recv_platform_data *dtpdata =
devm_kzalloc(&pdev->dev, sizeof(*dtpdata), GFP_KERNEL);
if (!dtpdata)
return -ENOMEM;
rc = gpio_ir_recv_get_devtree_pdata(&pdev->dev, dtpdata);
if (rc)
return rc;
pdata = dtpdata;
}
if (!pdata)
return -EINVAL;
if (pdata->gpio_nr < 0)
return -EINVAL;
gpio_dev = kzalloc(sizeof(struct gpio_rc_dev), GFP_KERNEL);
if (!gpio_dev)
return -ENOMEM;
rcdev = rc_allocate_device();
if (!rcdev) {
rc = -ENOMEM;
goto err_allocate_device;
}
rcdev->priv = gpio_dev;
rcdev->driver_type = RC_DRIVER_IR_RAW;
rcdev->input_name = GPIO_IR_DEVICE_NAME;
rcdev->input_phys = GPIO_IR_DEVICE_NAME "/input0";
rcdev->input_id.bustype = BUS_HOST;
rcdev->input_id.vendor = 0x0001;
rcdev->input_id.product = 0x0001;
rcdev->input_id.version = 0x0100;
rcdev->dev.parent = &pdev->dev;
rcdev->driver_name = GPIO_IR_DRIVER_NAME;
<<<<<<< HEAD
rcdev->map_name = RC_MAP_SAMSUNG_NECX;
=======
if (pdata->allowed_protos)
rcdev->allowed_protos = pdata->allowed_protos;
else
rcdev->allowed_protos = RC_BIT_ALL;
rcdev->map_name = pdata->map_name ?: RC_MAP_EMPTY;
>>>>>>> common/android-3.10.y
gpio_dev->rcdev = rcdev;
gpio_dev->gpio_nr = pdata->gpio_nr;
gpio_dev->active_low = pdata->active_low;
rc = gpio_request(pdata->gpio_nr, "gpio-ir-recv");
if (rc < 0)
goto err_gpio_request;
gpio_dev->can_sleep = gpio_cansleep(pdata->gpio_nr);
rc = gpio_direction_input(pdata->gpio_nr);
if (rc < 0)
goto err_gpio_direction_input;
rc = rc_register_device(rcdev);
if (rc < 0) {
dev_err(&pdev->dev, "failed to register rc device\n");
goto err_register_rc_device;
}
platform_set_drvdata(pdev, gpio_dev);
rc = request_any_context_irq(gpio_to_irq(pdata->gpio_nr),
gpio_ir_recv_irq,
IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING,
"gpio-ir-recv-irq", gpio_dev);
if (rc < 0)
goto err_request_irq;
device_init_wakeup(&pdev->dev, pdata->can_wakeup);
return 0;
err_request_irq:
platform_set_drvdata(pdev, NULL);
rc_unregister_device(rcdev);
rcdev = NULL;
err_register_rc_device:
err_gpio_direction_input:
gpio_free(pdata->gpio_nr);
err_gpio_request:
rc_free_device(rcdev);
err_allocate_device:
kfree(gpio_dev);
return rc;
}
static int gpio_ir_recv_remove(struct platform_device *pdev)
{
struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev);
free_irq(gpio_to_irq(gpio_dev->gpio_nr), gpio_dev);
platform_set_drvdata(pdev, NULL);
rc_unregister_device(gpio_dev->rcdev);
gpio_free(gpio_dev->gpio_nr);
kfree(gpio_dev);
return 0;
}
#ifdef CONFIG_PM
static int gpio_ir_recv_suspend(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev);
if (device_may_wakeup(dev))
enable_irq_wake(gpio_to_irq(gpio_dev->gpio_nr));
else
disable_irq(gpio_to_irq(gpio_dev->gpio_nr));
return 0;
}
static int gpio_ir_recv_resume(struct device *dev)
{
struct platform_device *pdev = to_platform_device(dev);
struct gpio_rc_dev *gpio_dev = platform_get_drvdata(pdev);
if (device_may_wakeup(dev))
disable_irq_wake(gpio_to_irq(gpio_dev->gpio_nr));
else
enable_irq(gpio_to_irq(gpio_dev->gpio_nr));
return 0;
}
static const struct dev_pm_ops gpio_ir_recv_pm_ops = {
.suspend = gpio_ir_recv_suspend,
.resume = gpio_ir_recv_resume,
};
#endif
static struct platform_driver gpio_ir_recv_driver = {
.probe = gpio_ir_recv_probe,
.remove = gpio_ir_recv_remove,
.driver = {
.name = GPIO_IR_DRIVER_NAME,
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(gpio_ir_recv_of_match),
#ifdef CONFIG_PM
.pm = &gpio_ir_recv_pm_ops,
#endif
},
};
module_platform_driver(gpio_ir_recv_driver);
MODULE_DESCRIPTION("GPIO IR Receiver driver");
MODULE_LICENSE("GPL v2");
| Java |
/*
* Copyright (c) 1998-2011 Caucho Technology -- all rights reserved
*
* This file is part of Resin(R) Open Source
*
* Each copy or derived work must preserve the copyright notice and this
* notice unmodified.
*
* Resin Open Source 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.
*
* Resin Open Source 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, or any warranty
* of NON-INFRINGEMENT. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License
* along with Resin Open Source; if not, write to the
*
* Free Software Foundation, Inc.
* 59 Temple Place, Suite 330
* Boston, MA 02111-1307 USA
*
* @author Sam
*/
package com.caucho.quercus.lib.spl;
import com.caucho.quercus.env.Value;
public interface OuterIterator
extends Iterator
{
public Value getInnerIterator();
}
| Java |
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// This file is part of Libmoleculizer
//
// Copyright (C) 2001-2009 The Molecular Sciences Institute.
//
//::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
//
// Moleculizer 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.
//
// Moleculizer 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 Moleculizer; if not, write to the Free Software Foundation
// Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA
//
// END HEADER
//
// Original Author:
// Larry Lok, Research Fellow, Molecular Sciences Institute, 2001
//
// Modifing Authors:
//
//
#ifndef FND_DUMPSTREAM_H
#define FND_DUMPSTREAM_H
#include <fstream>
#include <vector>
#include "utl/xcpt.hh"
#include "utl/autoVector.hh"
#include "fnd/dumpable.hh"
#include "fnd/dmpColumn.hh"
namespace fnd
{
class dumpStream :
public utl::autoVector<basicDmpColumn>
{
// Now that the output stream and everything else is passed to
// the dumpables through a dumpArg, these are here mainly to
// memory-manage the stream, to emphasize that this class is what
// corresponds to a .dmp file, and to facilitate the construction
// of dumpArg's through getOstream(), in particular.
std::string fileName;
std::ostream* pOs;
std::ofstream* pFileStream;
public:
// Use a genuine file path, "-" for std::cout, "+" for std::cerr.
dumpStream( const std::string& rFileName )
throw( utl::xcpt );
~dumpStream( void )
{
// This is null if the output stream not actually a file.
delete pFileStream;
}
std::ostream&
getOstream( void ) const
{
return *pOs;
}
// Returns the file name given at construction time, including
// the special cases.
const std::string&
getFileName( void ) const
{
return fileName;
}
// Initializes output stream and writes column headers.
void
init( void )
throw( utl::xcpt );
// Writes a line in the output file.
void
doDump( void );
};
}
#endif // FND_DUMPSTREAM_H
| Java |
from config import config, ConfigSlider, ConfigSelection, ConfigYesNo, \
ConfigEnableDisable, ConfigSubsection, ConfigBoolean, ConfigSelectionNumber, ConfigNothing, NoSave
from enigma import eAVSwitch, getDesktop
from SystemInfo import SystemInfo
from os import path as os_path
class AVSwitch:
def setInput(self, input):
INPUT = { "ENCODER": 0, "SCART": 1, "AUX": 2 }
eAVSwitch.getInstance().setInput(INPUT[input])
def setColorFormat(self, value):
eAVSwitch.getInstance().setColorFormat(value)
def setAspectRatio(self, value):
eAVSwitch.getInstance().setAspectRatio(value)
def setSystem(self, value):
eAVSwitch.getInstance().setVideomode(value)
def getOutputAspect(self):
valstr = config.av.aspectratio.value
if valstr in ("4_3_letterbox", "4_3_panscan"): # 4:3
return (4,3)
elif valstr == "16_9": # auto ... 4:3 or 16:9
try:
aspect_str = open("/proc/stb/vmpeg/0/aspect", "r").read()
if aspect_str == "1": # 4:3
return (4,3)
except IOError:
pass
elif valstr in ("16_9_always", "16_9_letterbox"): # 16:9
pass
elif valstr in ("16_10_letterbox", "16_10_panscan"): # 16:10
return (16,10)
return (16,9)
def getFramebufferScale(self):
aspect = self.getOutputAspect()
fb_size = getDesktop(0).size()
return (aspect[0] * fb_size.height(), aspect[1] * fb_size.width())
def getAspectRatioSetting(self):
valstr = config.av.aspectratio.value
if valstr == "4_3_letterbox":
val = 0
elif valstr == "4_3_panscan":
val = 1
elif valstr == "16_9":
val = 2
elif valstr == "16_9_always":
val = 3
elif valstr == "16_10_letterbox":
val = 4
elif valstr == "16_10_panscan":
val = 5
elif valstr == "16_9_letterbox":
val = 6
return val
def setAspectWSS(self, aspect=None):
if not config.av.wss.value:
value = 2 # auto(4:3_off)
else:
value = 1 # auto
eAVSwitch.getInstance().setWSS(value)
def InitAVSwitch():
config.av = ConfigSubsection()
config.av.yuvenabled = ConfigBoolean(default=False)
colorformat_choices = {"cvbs": _("CVBS"), "rgb": _("RGB"), "svideo": _("S-Video")}
# when YUV is not enabled, don't let the user select it
if config.av.yuvenabled.value:
colorformat_choices["yuv"] = _("YPbPr")
# ikseong
config.av.colorformat = ConfigSelection(choices=colorformat_choices, default="cvbs")
config.av.aspectratio = ConfigSelection(choices={
"4_3_letterbox": _("4:3 Letterbox"),
"4_3_panscan": _("4:3 PanScan"),
"16_9": _("16:9"),
"16_9_always": _("16:9 always"),
"16_10_letterbox": _("16:10 Letterbox"),
"16_10_panscan": _("16:10 PanScan"),
"16_9_letterbox": _("16:9 Letterbox")},
default = "4_3_letterbox")
config.av.aspect = ConfigSelection(choices={
"4_3": _("4:3"),
"16_9": _("16:9"),
"16_10": _("16:10"),
"auto": _("Automatic")},
default = "auto")
config.av.policy_169 = ConfigSelection(choices={
# TRANSLATORS: (aspect ratio policy: black bars on top/bottom) in doubt, keep english term.
"letterbox": _("Letterbox"),
# TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term
"panscan": _("Pan&Scan"),
# TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect)
"scale": _("Just Scale")},
default = "letterbox")
config.av.policy_43 = ConfigSelection(choices={
# TRANSLATORS: (aspect ratio policy: black bars on left/right) in doubt, keep english term.
"pillarbox": _("Pillarbox"),
# TRANSLATORS: (aspect ratio policy: cropped content on left/right) in doubt, keep english term
"panscan": _("Pan&Scan"),
# TRANSLATORS: (aspect ratio policy: display as fullscreen, with stretching the left/right)
"nonlinear": _("Nonlinear"),
# TRANSLATORS: (aspect ratio policy: display as fullscreen, even if this breaks the aspect)
"scale": _("Just Scale")},
default = "pillarbox")
config.av.tvsystem = ConfigSelection(choices = {"pal": _("PAL"), "ntsc": _("NTSC"), "multinorm": _("multinorm")}, default="pal")
config.av.wss = ConfigEnableDisable(default = True)
config.av.defaultac3 = ConfigYesNo(default = False)
config.av.generalAC3delay = ConfigSelectionNumber(-1000, 1000, 25, default = 0)
config.av.generalPCMdelay = ConfigSelectionNumber(-1000, 1000, 25, default = 0)
config.av.vcrswitch = ConfigEnableDisable(default = False)
iAVSwitch = AVSwitch()
def setColorFormat(configElement):
map = {"cvbs": 0, "rgb": 1, "svideo": 2, "yuv": 3}
iAVSwitch.setColorFormat(map[configElement.value])
def setAspectRatio(configElement):
map = {"4_3_letterbox": 0, "4_3_panscan": 1, "16_9": 2, "16_9_always": 3, "16_10_letterbox": 4, "16_10_panscan": 5, "16_9_letterbox" : 6}
iAVSwitch.setAspectRatio(map[configElement.value])
def setSystem(configElement):
map = {"pal": 0, "ntsc": 1, "multinorm" : 2}
iAVSwitch.setSystem(map[configElement.value])
def setWSS(configElement):
iAVSwitch.setAspectWSS()
# this will call the "setup-val" initial
config.av.colorformat.addNotifier(setColorFormat)
config.av.aspectratio.addNotifier(setAspectRatio)
config.av.tvsystem.addNotifier(setSystem)
config.av.wss.addNotifier(setWSS)
iAVSwitch.setInput("ENCODER") # init on startup
SystemInfo["ScartSwitch"] = eAVSwitch.getInstance().haveScartSwitch()
try:
can_downmix = open("/proc/stb/audio/ac3_choices", "r").read()[:-1].find("downmix") != -1
except:
can_downmix = False
SystemInfo["CanDownmixAC3"] = can_downmix
if can_downmix:
def setAC3Downmix(configElement):
open("/proc/stb/audio/ac3", "w").write(configElement.value and "downmix" or "passthrough")
config.av.downmix_ac3 = ConfigYesNo(default = True)
config.av.downmix_ac3.addNotifier(setAC3Downmix)
try:
can_downmix_aac = open("/proc/stb/audio/aac_choices", "r").read()[:-1].find("downmix") != -1
except:
can_downmix_aac = False
SystemInfo["CanDownmixAAC"] = can_downmix_aac
if can_downmix_aac:
def setAACDownmix(configElement):
open("/proc/stb/audio/aac", "w").write(configElement.value and "downmix" or "passthrough")
config.av.downmix_aac = ConfigYesNo(default = True)
config.av.downmix_aac.addNotifier(setAACDownmix)
try:
can_osd_alpha = open("/proc/stb/video/alpha", "r") and True or False
except:
can_osd_alpha = False
SystemInfo["CanChangeOsdAlpha"] = can_osd_alpha
def setAlpha(config):
open("/proc/stb/video/alpha", "w").write(str(config.value))
if can_osd_alpha:
config.av.osd_alpha = ConfigSlider(default=255, limits=(0,255))
config.av.osd_alpha.addNotifier(setAlpha)
if os_path.exists("/proc/stb/vmpeg/0/pep_scaler_sharpness"):
def setScaler_sharpness(config):
myval = int(config.value)
try:
print "--> setting scaler_sharpness to: %0.8X" % myval
open("/proc/stb/vmpeg/0/pep_scaler_sharpness", "w").write("%0.8X" % myval)
open("/proc/stb/vmpeg/0/pep_apply", "w").write("1")
except IOError:
print "couldn't write pep_scaler_sharpness"
config.av.scaler_sharpness = ConfigSlider(default=13, limits=(0,26))
config.av.scaler_sharpness.addNotifier(setScaler_sharpness)
else:
config.av.scaler_sharpness = NoSave(ConfigNothing())
| Java |
/*
* Network block device - make block devices work over TCP
*
* Note that you can not swap over this thing, yet. Seems to work but
* deadlocks sometimes - you can not swap over TCP in general.
*
* Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
* Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
*
* This file is released under GPLv2 or later.
*
* (part of code stolen from loop.c)
*/
#include <linux/major.h>
#include <linux/blkdev.h>
#include <linux/module.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/bio.h>
#include <linux/stat.h>
#include <linux/errno.h>
#include <linux/file.h>
#include <linux/ioctl.h>
#include <linux/mutex.h>
#include <linux/compiler.h>
#include <linux/err.h>
#include <linux/kernel.h>
#include <linux/slab.h>
#include <net/sock.h>
#include <linux/net.h>
#include <linux/kthread.h>
#include <asm/uaccess.h>
#include <asm/types.h>
#include <linux/nbd.h>
#define NBD_MAGIC 0x68797548
#ifdef NDEBUG
#define dprintk(flags, fmt...)
#else /* NDEBUG */
#define dprintk(flags, fmt...) do { \
if (debugflags & (flags)) printk(KERN_DEBUG fmt); \
} while (0)
#define DBG_IOCTL 0x0004
#define DBG_INIT 0x0010
#define DBG_EXIT 0x0020
#define DBG_BLKDEV 0x0100
#define DBG_RX 0x0200
#define DBG_TX 0x0400
static unsigned int debugflags;
#endif /* NDEBUG */
static unsigned int nbds_max = 16;
static struct nbd_device *nbd_dev;
static int max_part;
/*
* Use just one lock (or at most 1 per NIC). Two arguments for this:
* 1. Each NIC is essentially a synchronization point for all servers
* accessed through that NIC so there's no need to have more locks
* than NICs anyway.
* 2. More locks lead to more "Dirty cache line bouncing" which will slow
* down each lock to the point where they're actually slower than just
* a single lock.
* Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
*/
static DEFINE_SPINLOCK(nbd_lock);
#ifndef NDEBUG
static const char *ioctl_cmd_to_ascii(int cmd)
{
switch (cmd) {
case NBD_SET_SOCK: return "set-sock";
case NBD_SET_BLKSIZE: return "set-blksize";
case NBD_SET_SIZE: return "set-size";
case NBD_SET_TIMEOUT: return "set-timeout";
case NBD_SET_FLAGS: return "set-flags";
case NBD_DO_IT: return "do-it";
case NBD_CLEAR_SOCK: return "clear-sock";
case NBD_CLEAR_QUE: return "clear-que";
case NBD_PRINT_DEBUG: return "print-debug";
case NBD_SET_SIZE_BLOCKS: return "set-size-blocks";
case NBD_DISCONNECT: return "disconnect";
case BLKROSET: return "set-read-only";
case BLKFLSBUF: return "flush-buffer-cache";
}
return "unknown";
}
static const char *nbdcmd_to_ascii(int cmd)
{
switch (cmd) {
case NBD_CMD_READ: return "read";
case NBD_CMD_WRITE: return "write";
case NBD_CMD_DISC: return "disconnect";
case NBD_CMD_FLUSH: return "flush";
case NBD_CMD_TRIM: return "trim/discard";
}
return "invalid";
}
#endif /* NDEBUG */
static void nbd_end_request(struct request *req)
{
int error = req->errors ? -EIO : 0;
struct request_queue *q = req->q;
unsigned long flags;
dprintk(DBG_BLKDEV, "%s: request %p: %s\n", req->rq_disk->disk_name,
req, error ? "failed" : "done");
spin_lock_irqsave(q->queue_lock, flags);
__blk_end_request_all(req, error);
spin_unlock_irqrestore(q->queue_lock, flags);
}
static void sock_shutdown(struct nbd_device *nbd, int lock)
{
/* Forcibly shutdown the socket causing all listeners
* to error
*
* FIXME: This code is duplicated from sys_shutdown, but
* there should be a more generic interface rather than
* calling socket ops directly here */
if (lock)
mutex_lock(&nbd->tx_lock);
if (nbd->sock) {
dev_warn(disk_to_dev(nbd->disk), "shutting down socket\n");
kernel_sock_shutdown(nbd->sock, SHUT_RDWR);
nbd->sock = NULL;
}
if (lock)
mutex_unlock(&nbd->tx_lock);
}
static void nbd_xmit_timeout(unsigned long arg)
{
struct task_struct *task = (struct task_struct *)arg;
printk(KERN_WARNING "nbd: killing hung xmit (%s, pid: %d)\n",
task->comm, task->pid);
force_sig(SIGKILL, task);
}
/*
* Send or receive packet.
*/
static int sock_xmit(struct nbd_device *nbd, int send, void *buf, int size,
int msg_flags)
{
struct socket *sock = nbd->sock;
int result;
struct msghdr msg;
struct kvec iov;
sigset_t blocked, oldset;
unsigned long pflags = current->flags;
if (unlikely(!sock)) {
dev_err(disk_to_dev(nbd->disk),
"Attempted %s on closed socket in sock_xmit\n",
(send ? "send" : "recv"));
return -EINVAL;
}
/* Allow interception of SIGKILL only
* Don't allow other signals to interrupt the transmission */
siginitsetinv(&blocked, sigmask(SIGKILL));
sigprocmask(SIG_SETMASK, &blocked, &oldset);
current->flags |= PF_MEMALLOC;
do {
sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
iov.iov_base = buf;
iov.iov_len = size;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = msg_flags | MSG_NOSIGNAL;
if (send) {
struct timer_list ti;
if (nbd->xmit_timeout) {
init_timer(&ti);
ti.function = nbd_xmit_timeout;
ti.data = (unsigned long)current;
ti.expires = jiffies + nbd->xmit_timeout;
add_timer(&ti);
}
result = kernel_sendmsg(sock, &msg, &iov, 1, size);
if (nbd->xmit_timeout)
del_timer_sync(&ti);
} else
result = kernel_recvmsg(sock, &msg, &iov, 1, size,
msg.msg_flags);
if (signal_pending(current)) {
siginfo_t info;
printk(KERN_WARNING "nbd (pid %d: %s) got signal %d\n",
task_pid_nr(current), current->comm,
dequeue_signal_lock(current, ¤t->blocked, &info));
result = -EINTR;
sock_shutdown(nbd, !send);
break;
}
if (result <= 0) {
if (result == 0)
result = -EPIPE; /* short read */
break;
}
size -= result;
buf += result;
} while (size > 0);
sigprocmask(SIG_SETMASK, &oldset, NULL);
tsk_restore_flags(current, pflags, PF_MEMALLOC);
return result;
}
static inline int sock_send_bvec(struct nbd_device *nbd, struct bio_vec *bvec,
int flags)
{
int result;
void *kaddr = kmap(bvec->bv_page);
result = sock_xmit(nbd, 1, kaddr + bvec->bv_offset,
bvec->bv_len, flags);
kunmap(bvec->bv_page);
return result;
}
/* always call with the tx_lock held */
static int nbd_send_req(struct nbd_device *nbd, struct request *req)
{
int result, flags;
struct nbd_request request;
unsigned long size = blk_rq_bytes(req);
request.magic = htonl(NBD_REQUEST_MAGIC);
request.type = htonl(nbd_cmd(req));
if (nbd_cmd(req) == NBD_CMD_FLUSH) {
/* Other values are reserved for FLUSH requests. */
request.from = 0;
request.len = 0;
} else {
request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
request.len = htonl(size);
}
memcpy(request.handle, &req, sizeof(req));
dprintk(DBG_TX, "%s: request %p: sending control (%s@%llu,%uB)\n",
nbd->disk->disk_name, req,
nbdcmd_to_ascii(nbd_cmd(req)),
(unsigned long long)blk_rq_pos(req) << 9,
blk_rq_bytes(req));
result = sock_xmit(nbd, 1, &request, sizeof(request),
(nbd_cmd(req) == NBD_CMD_WRITE) ? MSG_MORE : 0);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk),
"Send control failed (result %d)\n", result);
goto error_out;
}
if (nbd_cmd(req) == NBD_CMD_WRITE) {
struct req_iterator iter;
struct bio_vec bvec;
/*
* we are really probing at internals to determine
* whether to set MSG_MORE or not...
*/
rq_for_each_segment(bvec, req, iter) {
flags = 0;
if (!rq_iter_last(bvec, iter))
flags = MSG_MORE;
dprintk(DBG_TX, "%s: request %p: sending %d bytes data\n",
nbd->disk->disk_name, req, bvec.bv_len);
result = sock_send_bvec(nbd, &bvec, flags);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk),
"Send data failed (result %d)\n",
result);
goto error_out;
}
}
}
return 0;
error_out:
return -EIO;
}
static struct request *nbd_find_request(struct nbd_device *nbd,
struct request *xreq)
{
struct request *req, *tmp;
int err;
err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
if (unlikely(err))
goto out;
spin_lock(&nbd->queue_lock);
list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
if (req != xreq)
continue;
list_del_init(&req->queuelist);
spin_unlock(&nbd->queue_lock);
return req;
}
spin_unlock(&nbd->queue_lock);
err = -ENOENT;
out:
return ERR_PTR(err);
}
static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
{
int result;
void *kaddr = kmap(bvec->bv_page);
result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
MSG_WAITALL);
kunmap(bvec->bv_page);
return result;
}
/* NULL returned = something went wrong, inform userspace */
static struct request *nbd_read_stat(struct nbd_device *nbd)
{
int result;
struct nbd_reply reply;
struct request *req;
reply.magic = 0;
result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk),
"Receive control failed (result %d)\n", result);
goto harderror;
}
if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
(unsigned long)ntohl(reply.magic));
result = -EPROTO;
goto harderror;
}
req = nbd_find_request(nbd, *(struct request **)reply.handle);
if (IS_ERR(req)) {
result = PTR_ERR(req);
if (result != -ENOENT)
goto harderror;
dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
reply.handle);
result = -EBADR;
goto harderror;
}
if (ntohl(reply.error)) {
dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
ntohl(reply.error));
req->errors++;
return req;
}
dprintk(DBG_RX, "%s: request %p: got reply\n",
nbd->disk->disk_name, req);
if (nbd_cmd(req) == NBD_CMD_READ) {
struct req_iterator iter;
struct bio_vec bvec;
rq_for_each_segment(bvec, req, iter) {
result = sock_recv_bvec(nbd, &bvec);
if (result <= 0) {
dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
result);
req->errors++;
return req;
}
dprintk(DBG_RX, "%s: request %p: got %d bytes data\n",
nbd->disk->disk_name, req, bvec.bv_len);
}
}
return req;
harderror:
nbd->harderror = result;
return NULL;
}
static ssize_t pid_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct gendisk *disk = dev_to_disk(dev);
return sprintf(buf, "%ld\n",
(long) ((struct nbd_device *)disk->private_data)->pid);
}
static struct device_attribute pid_attr = {
.attr = { .name = "pid", .mode = S_IRUGO},
.show = pid_show,
};
static int nbd_do_it(struct nbd_device *nbd)
{
struct request *req;
int ret;
BUG_ON(nbd->magic != NBD_MAGIC);
sk_set_memalloc(nbd->sock->sk);
nbd->pid = task_pid_nr(current);
ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
if (ret) {
dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
nbd->pid = 0;
return ret;
}
while ((req = nbd_read_stat(nbd)) != NULL)
nbd_end_request(req);
device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
nbd->pid = 0;
return 0;
}
static void nbd_clear_que(struct nbd_device *nbd)
{
struct request *req;
BUG_ON(nbd->magic != NBD_MAGIC);
/*
* Because we have set nbd->sock to NULL under the tx_lock, all
* modifications to the list must have completed by now. For
* the same reason, the active_req must be NULL.
*
* As a consequence, we don't need to take the spin lock while
* purging the list here.
*/
BUG_ON(nbd->sock);
BUG_ON(nbd->active_req);
while (!list_empty(&nbd->queue_head)) {
req = list_entry(nbd->queue_head.next, struct request,
queuelist);
list_del_init(&req->queuelist);
req->errors++;
nbd_end_request(req);
}
while (!list_empty(&nbd->waiting_queue)) {
req = list_entry(nbd->waiting_queue.next, struct request,
queuelist);
list_del_init(&req->queuelist);
req->errors++;
nbd_end_request(req);
}
}
static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
{
if (req->cmd_type != REQ_TYPE_FS)
goto error_out;
nbd_cmd(req) = NBD_CMD_READ;
if (rq_data_dir(req) == WRITE) {
if ((req->cmd_flags & REQ_DISCARD)) {
WARN_ON(!(nbd->flags & NBD_FLAG_SEND_TRIM));
nbd_cmd(req) = NBD_CMD_TRIM;
} else
nbd_cmd(req) = NBD_CMD_WRITE;
if (nbd->flags & NBD_FLAG_READ_ONLY) {
dev_err(disk_to_dev(nbd->disk),
"Write on read-only\n");
goto error_out;
}
}
if (req->cmd_flags & REQ_FLUSH) {
BUG_ON(unlikely(blk_rq_sectors(req)));
nbd_cmd(req) = NBD_CMD_FLUSH;
}
req->errors = 0;
mutex_lock(&nbd->tx_lock);
if (unlikely(!nbd->sock)) {
mutex_unlock(&nbd->tx_lock);
dev_err(disk_to_dev(nbd->disk),
"Attempted send on closed socket\n");
goto error_out;
}
nbd->active_req = req;
if (nbd_send_req(nbd, req) != 0) {
dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
req->errors++;
nbd_end_request(req);
} else {
spin_lock(&nbd->queue_lock);
list_add_tail(&req->queuelist, &nbd->queue_head);
spin_unlock(&nbd->queue_lock);
}
nbd->active_req = NULL;
mutex_unlock(&nbd->tx_lock);
wake_up_all(&nbd->active_wq);
return;
error_out:
req->errors++;
nbd_end_request(req);
}
static int nbd_thread(void *data)
{
struct nbd_device *nbd = data;
struct request *req;
set_user_nice(current, MIN_NICE);
while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
/* wait for something to do */
wait_event_interruptible(nbd->waiting_wq,
kthread_should_stop() ||
!list_empty(&nbd->waiting_queue));
/* extract request */
if (list_empty(&nbd->waiting_queue))
continue;
spin_lock_irq(&nbd->queue_lock);
req = list_entry(nbd->waiting_queue.next, struct request,
queuelist);
list_del_init(&req->queuelist);
spin_unlock_irq(&nbd->queue_lock);
/* handle request */
nbd_handle_req(nbd, req);
}
return 0;
}
/*
* We always wait for result of write, for now. It would be nice to make it optional
* in future
* if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
* { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
*/
static void do_nbd_request(struct request_queue *q)
__releases(q->queue_lock) __acquires(q->queue_lock)
{
struct request *req;
while ((req = blk_fetch_request(q)) != NULL) {
struct nbd_device *nbd;
spin_unlock_irq(q->queue_lock);
dprintk(DBG_BLKDEV, "%s: request %p: dequeued (flags=%x)\n",
req->rq_disk->disk_name, req, req->cmd_type);
nbd = req->rq_disk->private_data;
BUG_ON(nbd->magic != NBD_MAGIC);
if (unlikely(!nbd->sock)) {
dev_err(disk_to_dev(nbd->disk),
"Attempted send on closed socket\n");
req->errors++;
nbd_end_request(req);
spin_lock_irq(q->queue_lock);
continue;
}
spin_lock_irq(&nbd->queue_lock);
list_add_tail(&req->queuelist, &nbd->waiting_queue);
spin_unlock_irq(&nbd->queue_lock);
wake_up(&nbd->waiting_wq);
spin_lock_irq(q->queue_lock);
}
}
/* Must be called with tx_lock held */
static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
unsigned int cmd, unsigned long arg)
{
switch (cmd) {
case NBD_DISCONNECT: {
struct request sreq;
dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
if (!nbd->sock)
return -EINVAL;
mutex_unlock(&nbd->tx_lock);
fsync_bdev(bdev);
mutex_lock(&nbd->tx_lock);
blk_rq_init(NULL, &sreq);
sreq.cmd_type = REQ_TYPE_SPECIAL;
nbd_cmd(&sreq) = NBD_CMD_DISC;
/* Check again after getting mutex back. */
if (!nbd->sock)
return -EINVAL;
nbd->disconnect = 1;
nbd_send_req(nbd, &sreq);
return 0;
}
case NBD_CLEAR_SOCK: {
struct socket *sock = nbd->sock;
nbd->sock = NULL;
nbd_clear_que(nbd);
BUG_ON(!list_empty(&nbd->queue_head));
BUG_ON(!list_empty(&nbd->waiting_queue));
kill_bdev(bdev);
if (sock)
sockfd_put(sock);
return 0;
}
case NBD_SET_SOCK: {
struct socket *sock;
int err;
if (nbd->sock)
return -EBUSY;
sock = sockfd_lookup(arg, &err);
if (sock) {
nbd->sock = sock;
if (max_part > 0)
bdev->bd_invalidated = 1;
nbd->disconnect = 0; /* we're connected now */
return 0;
}
return -EINVAL;
}
case NBD_SET_BLKSIZE:
nbd->blksize = arg;
nbd->bytesize &= ~(nbd->blksize-1);
bdev->bd_inode->i_size = nbd->bytesize;
set_blocksize(bdev, nbd->blksize);
set_capacity(nbd->disk, nbd->bytesize >> 9);
return 0;
case NBD_SET_SIZE:
nbd->bytesize = arg & ~(nbd->blksize-1);
bdev->bd_inode->i_size = nbd->bytesize;
set_blocksize(bdev, nbd->blksize);
set_capacity(nbd->disk, nbd->bytesize >> 9);
return 0;
case NBD_SET_TIMEOUT:
nbd->xmit_timeout = arg * HZ;
return 0;
case NBD_SET_FLAGS:
nbd->flags = arg;
return 0;
case NBD_SET_SIZE_BLOCKS:
nbd->bytesize = ((u64) arg) * nbd->blksize;
bdev->bd_inode->i_size = nbd->bytesize;
set_blocksize(bdev, nbd->blksize);
set_capacity(nbd->disk, nbd->bytesize >> 9);
return 0;
case NBD_DO_IT: {
struct task_struct *thread;
struct socket *sock;
int error;
if (nbd->pid)
return -EBUSY;
if (!nbd->sock)
return -EINVAL;
mutex_unlock(&nbd->tx_lock);
if (nbd->flags & NBD_FLAG_READ_ONLY)
set_device_ro(bdev, true);
if (nbd->flags & NBD_FLAG_SEND_TRIM)
queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
nbd->disk->queue);
if (nbd->flags & NBD_FLAG_SEND_FLUSH)
blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
else
blk_queue_flush(nbd->disk->queue, 0);
thread = kthread_create(nbd_thread, nbd, "%s",
nbd->disk->disk_name);
if (IS_ERR(thread)) {
mutex_lock(&nbd->tx_lock);
return PTR_ERR(thread);
}
wake_up_process(thread);
error = nbd_do_it(nbd);
kthread_stop(thread);
mutex_lock(&nbd->tx_lock);
if (error)
return error;
sock_shutdown(nbd, 0);
sock = nbd->sock;
nbd->sock = NULL;
nbd_clear_que(nbd);
dev_warn(disk_to_dev(nbd->disk), "queue cleared\n");
kill_bdev(bdev);
queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
set_device_ro(bdev, false);
if (sock)
sockfd_put(sock);
nbd->flags = 0;
nbd->bytesize = 0;
bdev->bd_inode->i_size = 0;
set_capacity(nbd->disk, 0);
if (max_part > 0)
ioctl_by_bdev(bdev, BLKRRPART, 0);
if (nbd->disconnect) /* user requested, ignore socket errors */
return 0;
return nbd->harderror;
}
case NBD_CLEAR_QUE:
/*
* This is for compatibility only. The queue is always cleared
* by NBD_DO_IT or NBD_CLEAR_SOCK.
*/
return 0;
case NBD_PRINT_DEBUG:
dev_info(disk_to_dev(nbd->disk),
"next = %p, prev = %p, head = %p\n",
nbd->queue_head.next, nbd->queue_head.prev,
&nbd->queue_head);
return 0;
}
return -ENOTTY;
}
static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
unsigned int cmd, unsigned long arg)
{
struct nbd_device *nbd = bdev->bd_disk->private_data;
int error;
if (!capable(CAP_SYS_ADMIN))
return -EPERM;
BUG_ON(nbd->magic != NBD_MAGIC);
/* Anyone capable of this syscall can do *real bad* things */
dprintk(DBG_IOCTL, "%s: nbd_ioctl cmd=%s(0x%x) arg=%lu\n",
nbd->disk->disk_name, ioctl_cmd_to_ascii(cmd), cmd, arg);
mutex_lock(&nbd->tx_lock);
error = __nbd_ioctl(bdev, nbd, cmd, arg);
mutex_unlock(&nbd->tx_lock);
return error;
}
static const struct block_device_operations nbd_fops =
{
.owner = THIS_MODULE,
.ioctl = nbd_ioctl,
};
/*
* And here should be modules and kernel interface
* (Just smiley confuses emacs :-)
*/
static int __init nbd_init(void)
{
int err = -ENOMEM;
int i;
int part_shift;
BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
if (max_part < 0) {
printk(KERN_ERR "nbd: max_part must be >= 0\n");
return -EINVAL;
}
nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
if (!nbd_dev)
return -ENOMEM;
part_shift = 0;
if (max_part > 0) {
part_shift = fls(max_part);
/*
* Adjust max_part according to part_shift as it is exported
* to user space so that user can know the max number of
* partition kernel should be able to manage.
*
* Note that -1 is required because partition 0 is reserved
* for the whole disk.
*/
max_part = (1UL << part_shift) - 1;
}
if ((1UL << part_shift) > DISK_MAX_PARTS)
return -EINVAL;
if (nbds_max > 1UL << (MINORBITS - part_shift))
return -EINVAL;
for (i = 0; i < nbds_max; i++) {
struct gendisk *disk = alloc_disk(1 << part_shift);
if (!disk)
goto out;
nbd_dev[i].disk = disk;
/*
* The new linux 2.5 block layer implementation requires
* every gendisk to have its very own request_queue struct.
* These structs are big so we dynamically allocate them.
*/
disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
if (!disk->queue) {
put_disk(disk);
goto out;
}
/*
* Tell the block layer that we are not a rotational device
*/
queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
disk->queue->limits.discard_granularity = 512;
disk->queue->limits.max_discard_sectors = UINT_MAX;
disk->queue->limits.discard_zeroes_data = 0;
blk_queue_max_hw_sectors(disk->queue, 65536);
disk->queue->limits.max_sectors = 256;
}
if (register_blkdev(NBD_MAJOR, "nbd")) {
err = -EIO;
goto out;
}
printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
dprintk(DBG_INIT, "nbd: debugflags=0x%x\n", debugflags);
for (i = 0; i < nbds_max; i++) {
struct gendisk *disk = nbd_dev[i].disk;
nbd_dev[i].magic = NBD_MAGIC;
INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
spin_lock_init(&nbd_dev[i].queue_lock);
INIT_LIST_HEAD(&nbd_dev[i].queue_head);
mutex_init(&nbd_dev[i].tx_lock);
init_waitqueue_head(&nbd_dev[i].active_wq);
init_waitqueue_head(&nbd_dev[i].waiting_wq);
nbd_dev[i].blksize = 1024;
nbd_dev[i].bytesize = 0;
disk->major = NBD_MAJOR;
disk->first_minor = i << part_shift;
disk->fops = &nbd_fops;
disk->private_data = &nbd_dev[i];
sprintf(disk->disk_name, "nbd%d", i);
set_capacity(disk, 0);
add_disk(disk);
}
return 0;
out:
while (i--) {
blk_cleanup_queue(nbd_dev[i].disk->queue);
put_disk(nbd_dev[i].disk);
}
kfree(nbd_dev);
return err;
}
static void __exit nbd_cleanup(void)
{
int i;
for (i = 0; i < nbds_max; i++) {
struct gendisk *disk = nbd_dev[i].disk;
nbd_dev[i].magic = 0;
if (disk) {
del_gendisk(disk);
blk_cleanup_queue(disk->queue);
put_disk(disk);
}
}
unregister_blkdev(NBD_MAJOR, "nbd");
kfree(nbd_dev);
printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
}
module_init(nbd_init);
module_exit(nbd_cleanup);
MODULE_DESCRIPTION("Network Block Device");
MODULE_LICENSE("GPL");
module_param(nbds_max, int, 0444);
MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
module_param(max_part, int, 0444);
MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
#ifndef NDEBUG
module_param(debugflags, int, 0644);
MODULE_PARM_DESC(debugflags, "flags for controlling debug output");
#endif
| Java |
<?php
namespace App\Test\Fixture;
use Cake\TestSuite\Fixture\TestFixture;
/**
* ContactsourcesFixture
*
*/
class ContactsourcesFixture extends TestFixture
{
/**
* Fields
*
* @var array
*/
public $fields = [
'id' => ['type' => 'integer', 'length' => 6, 'unsigned' => false, 'null' => false, 'default' => null, 'comment' => '', 'autoIncrement' => true, 'precision' => null],
'name' => ['type' => 'string', 'length' => 45, 'null' => true, 'default' => null, 'comment' => '', 'precision' => null, 'fixed' => null],
'_constraints' => [
'primary' => ['type' => 'primary', 'columns' => ['id'], 'length' => []],
],
'_options' => [
'engine' => 'InnoDB', 'collation' => 'utf8_hungarian_ci'
],
];
/**
* Records
*
* @var array
*/
public $records = [
[
'id' => 1,
'name' => 'Contactsoure 1'
],
[
'id' => 2,
'name' => 'Contactsoure 2'
],
];
}
| Java |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc on Sat Aug 06 17:04:43 EDT 2005 -->
<TITLE>
Xalan-Java 2.7.0: Uses of Class org.apache.xpath.functions.FuncCurrent
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">
</HEAD>
<BODY BGCOLOR="white">
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_top"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xpath/functions/FuncCurrent.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="FuncCurrent.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
<CENTER>
<H2>
<B>Uses of Class<br>org.apache.xpath.functions.FuncCurrent</B></H2>
</CENTER>
No usage of org.apache.xpath.functions.FuncCurrent
<P>
<HR>
<!-- ========== START OF NAVBAR ========== -->
<A NAME="navbar_bottom"><!-- --></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../org/apache/xpath/functions/FuncCurrent.html"><FONT CLASS="NavBarFont1"><B>Class</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Use</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../index-all.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
PREV
NEXT</FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../../../../../index.html" TARGET="_top"><B>FRAMES</B></A>
<A HREF="FuncCurrent.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD>
</TR>
</TABLE>
<!-- =========== END OF NAVBAR =========== -->
<HR>
Copyright © 2005 Apache XML Project. All Rights Reserved.
</BODY>
</HTML>
| Java |
#ifndef UTILITIES_H
#define UTILITIES_H
#include "edge.h"
#include <cstring>
#include "resume.h"
#include <algorithm>
#include <vector>
#include "Hungarian.h"
#include "BipartiteGraph.h"
#include "Matrix.h"
using namespace std;
typedef vector<vector<string>> section;
#include "pair_section.h"
class PairSection;
typedef vector<string> line;
typedef vector<pair<int, PairSection>> evidence;
//class Resume;
namespace string_util {
char tolower(char in){
if(in<='Z' && in>='A')
return in-('Z'-'z');
return in;
}
string tolower(string s) {
string ret=s;
for(int i=0;i<s.length();i++) ret[i]=tolower(s[i]);
return ret;
}
// trim from start
std::string &Ltrim(std::string &s) {
s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace))));
return s;
}
// trim from end
std::string &Rtrim(std::string &s) {
s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());
return s;
}
// trim from both ends
std::string strip(std::string s) {
return Ltrim(Rtrim(s));
}
bool IsPresent(vector<string> v, string s) {
for(int i=0;i<v.size();i++) if(v[i]==s) return true;
return false;
}
vector<string> BagOfWordsFromString(vector<string> stopwords, string teststr) {
vector<string> bag;
//string teststr("The quick brown fox:test1,test2'test3\"test4");
//teststr=string_util::tolower(teststr);
char *teststr_c_str = (char *)teststr.c_str();
char *token_c_str = strtok(teststr_c_str, DELIM);
while (token_c_str) {
if(!string_util::IsPresent(stopwords,string(token_c_str))) bag.push_back(string(token_c_str));
//printf ("Token: %s\n", p);
token_c_str = strtok(NULL, DELIM);
}
//cout<<"Line: "<<teststr<<" bag =";
//for(int i=0;i<bag.size();i++) cout<<bag[i]<<"_";
//cout<<endl;
//cin>>teststr;
//cin.get();
return bag;
}
}
namespace resume_util {
bool IsBegin(string s) {
int pos=s.find("CS0");
if(pos==0) return true;
return false;
}
bool IsSection(string s,string section) {
int pos=s.find(section);
int len = s.length();
//if(pos==0 ) return true;
if(pos==0 && pos<len && len-pos-section.length()<=10) return true;
return false;
}
bool IsSummary(string s) {
if(IsSection(s,"summary") || IsSection(s,"professional summary")
|| IsSection(s,"summary of qualifications"))
return true;
return false;
}
bool IsSkills(string s) {
if(IsSection(s,"skills") || IsSection(s,"technical skills") ||
IsSection(s,"business and technical skills"))
return true;
return false;
}
bool IsExperience(string s) {
if(IsSection(s,"experience") || IsSection(s,"project experience") ||
IsSection(s,"work experience") || IsSection(s,"professional experience") ||
IsSection(s,"recent experience"))
return true;
return false;
}
bool IsEducation(string s) {
if(IsSection(s,"education") )
return true;
return false;
}
bool IsResponsibilities(string s) {
if(IsSection(s,"responsibilities"))
return true;
return false;
}
bool IsEnvSection(string s,string section) {
int pos=s.find(section);
//cout<<s<<"\n"<<section<<"__"<<pos<<endl;
if(pos==0 ) return true;
return false;
}
bool IsEnvironment(string s) {
if(IsEnvSection(s,"environment:") ||
IsEnvSection(s,"environment :") ||
IsEnvSection(s,"tools and technologies:") ||
IsEnvSection(s,"tools and technologies :") ||
IsEnvSection(s,"tools & technolgies:") ||
IsEnvSection(s,"tools & technolgies :"))
return true;
return false;
}
}
namespace distance_util {
int Jaccard(line v1, line v2) {
sort(v1.begin(),v1.end());
sort(v2.begin(),v2.end());
line inter;
line uni;
set_intersection(v1.begin(),v1.end(),
v2.begin(),v2.end(),
back_inserter(inter));
set_union(v1.begin(),v1.end(),
v2.begin(),v2.end(),
back_inserter(uni));
float num=(float)(inter.size());
float denom=(float)(uni.size());
if(num == 0 || denom == 0) return 0;
return int((num/denom)*1000);
}
}
namespace matching_util {
//Credit: http://www.frc.ri.cmu.edu/~lantao/codes/hungarian.php
double MaxBipartiteMatching(const section& s1, const section & s2, vector<pair_line> &pl)
{
printf("ENTER\n");
size_t nrows = s1.size();
size_t ncols = s2.size();
//define a matrix
Matrix matrix;
matrix.resize(nrows);
for(unsigned int i=0; i<nrows; i++)
matrix[i].resize(ncols);
// generate
for(unsigned int i=0; i<nrows; i++)
for(unsigned int j=0; j<ncols; j++){
matrix[i][j].SetWeight(distance_util::Jaccard(s1[i],s2[j]));
}
BipartiteGraph bg(matrix);
Hungarian h(bg);
h.HungarianAlgo();
BipartiteGraph* result = h.GetBG();
Matrix result_matrix = *(result->GetMatrix());
double sum=0;
for(unsigned int i=0; i< result->GetNumAgents(); i++){
for(unsigned int j=0; j< result->GetNumTasks(); j++){
if(result->GetMatrix(i,j)->GetMatchedFlag()) {
pl.push_back(pair_line(i,j,result_matrix[i][j].GetWeight()));
sum += result_matrix[i][j].GetWeight();
}
}
}
printf("score= %f\n",sum);
return sum;
}
int SectionSimilarity(const section& s1, const section& s2, vector<pair_line> &pl) {
int nrow= s1.size();
int ncol= s2.size();
if(nrow <= ncol) {
return (int)MaxBipartiteMatching(s1,s2,pl);
} else {
double val = MaxBipartiteMatching(s2,s1,pl);
for(int i=0;i<pl.size();i++) {
int temp_u = pl[i].u;
pl[i].u = pl[i].v;
pl[i].v = temp_u;
}
return (int)val;
}
}
//Credit: http://stackoverflow.com/questions/10580982/c-sort-keeping-track-of-indices
template <typename T>
std::vector<size_t> ordered(std::vector<T> const& values) {
std::vector<size_t> indices(values.size());
for(int i=0;i<values.size();i++) indices[i] = i;
//iota(begin(indices), end(indices), static_cast<size_t>(0));
std::sort(
begin(indices), end(indices),
[&](size_t a, size_t b) { return values[a] > values[b]; }
);
return indices;
}
}
#endif
| Java |
/*
Copyright (C) 1997-2001 Id Software, 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.
*/
// G:\quake2\baseq2\models/monsters/boss3/rider
// This file generated by ModelGen - Do NOT Modify
#define FRAME_attak101 0
#define FRAME_attak102 1
#define FRAME_attak103 2
#define FRAME_attak104 3
#define FRAME_attak105 4
#define FRAME_attak106 5
#define FRAME_attak107 6
#define FRAME_attak108 7
#define FRAME_attak109 8
#define FRAME_attak110 9
#define FRAME_attak111 10
#define FRAME_attak112 11
#define FRAME_attak113 12
#define FRAME_attak114 13
#define FRAME_attak115 14
#define FRAME_attak116 15
#define FRAME_attak117 16
#define FRAME_attak118 17
#define FRAME_attak201 18
#define FRAME_attak202 19
#define FRAME_attak203 20
#define FRAME_attak204 21
#define FRAME_attak205 22
#define FRAME_attak206 23
#define FRAME_attak207 24
#define FRAME_attak208 25
#define FRAME_attak209 26
#define FRAME_attak210 27
#define FRAME_attak211 28
#define FRAME_attak212 29
#define FRAME_attak213 30
#define FRAME_death01 31
#define FRAME_death02 32
#define FRAME_death03 33
#define FRAME_death04 34
#define FRAME_death05 35
#define FRAME_death06 36
#define FRAME_death07 37
#define FRAME_death08 38
#define FRAME_death09 39
#define FRAME_death10 40
#define FRAME_death11 41
#define FRAME_death12 42
#define FRAME_death13 43
#define FRAME_death14 44
#define FRAME_death15 45
#define FRAME_death16 46
#define FRAME_death17 47
#define FRAME_death18 48
#define FRAME_death19 49
#define FRAME_death20 50
#define FRAME_death21 51
#define FRAME_death22 52
#define FRAME_death23 53
#define FRAME_death24 54
#define FRAME_death25 55
#define FRAME_death26 56
#define FRAME_death27 57
#define FRAME_death28 58
#define FRAME_death29 59
#define FRAME_death30 60
#define FRAME_death31 61
#define FRAME_death32 62
#define FRAME_death33 63
#define FRAME_death34 64
#define FRAME_death35 65
#define FRAME_death36 66
#define FRAME_death37 67
#define FRAME_death38 68
#define FRAME_death39 69
#define FRAME_death40 70
#define FRAME_death41 71
#define FRAME_death42 72
#define FRAME_death43 73
#define FRAME_death44 74
#define FRAME_death45 75
#define FRAME_death46 76
#define FRAME_death47 77
#define FRAME_death48 78
#define FRAME_death49 79
#define FRAME_death50 80
#define FRAME_pain101 81
#define FRAME_pain102 82
#define FRAME_pain103 83
#define FRAME_pain201 84
#define FRAME_pain202 85
#define FRAME_pain203 86
#define FRAME_pain301 87
#define FRAME_pain302 88
#define FRAME_pain303 89
#define FRAME_pain304 90
#define FRAME_pain305 91
#define FRAME_pain306 92
#define FRAME_pain307 93
#define FRAME_pain308 94
#define FRAME_pain309 95
#define FRAME_pain310 96
#define FRAME_pain311 97
#define FRAME_pain312 98
#define FRAME_pain313 99
#define FRAME_pain314 100
#define FRAME_pain315 101
#define FRAME_pain316 102
#define FRAME_pain317 103
#define FRAME_pain318 104
#define FRAME_pain319 105
#define FRAME_pain320 106
#define FRAME_pain321 107
#define FRAME_pain322 108
#define FRAME_pain323 109
#define FRAME_pain324 110
#define FRAME_pain325 111
#define FRAME_stand01 112
#define FRAME_stand02 113
#define FRAME_stand03 114
#define FRAME_stand04 115
#define FRAME_stand05 116
#define FRAME_stand06 117
#define FRAME_stand07 118
#define FRAME_stand08 119
#define FRAME_stand09 120
#define FRAME_stand10 121
#define FRAME_stand11 122
#define FRAME_stand12 123
#define FRAME_stand13 124
#define FRAME_stand14 125
#define FRAME_stand15 126
#define FRAME_stand16 127
#define FRAME_stand17 128
#define FRAME_stand18 129
#define FRAME_stand19 130
#define FRAME_stand20 131
#define FRAME_stand21 132
#define FRAME_stand22 133
#define FRAME_stand23 134
#define FRAME_stand24 135
#define FRAME_stand25 136
#define FRAME_stand26 137
#define FRAME_stand27 138
#define FRAME_stand28 139
#define FRAME_stand29 140
#define FRAME_stand30 141
#define FRAME_stand31 142
#define FRAME_stand32 143
#define FRAME_stand33 144
#define FRAME_stand34 145
#define FRAME_stand35 146
#define FRAME_stand36 147
#define FRAME_stand37 148
#define FRAME_stand38 149
#define FRAME_stand39 150
#define FRAME_stand40 151
#define FRAME_stand41 152
#define FRAME_stand42 153
#define FRAME_stand43 154
#define FRAME_stand44 155
#define FRAME_stand45 156
#define FRAME_stand46 157
#define FRAME_stand47 158
#define FRAME_stand48 159
#define FRAME_stand49 160
#define FRAME_stand50 161
#define FRAME_stand51 162
#define FRAME_walk01 163
#define FRAME_walk02 164
#define FRAME_walk03 165
#define FRAME_walk04 166
#define FRAME_walk05 167
#define FRAME_walk06 168
#define FRAME_walk07 169
#define FRAME_walk08 170
#define FRAME_walk09 171
#define FRAME_walk10 172
#define FRAME_walk11 173
#define FRAME_walk12 174
#define FRAME_walk13 175
#define FRAME_walk14 176
#define FRAME_walk15 177
#define FRAME_walk16 178
#define FRAME_walk17 179
#define FRAME_walk18 180
#define FRAME_walk19 181
#define FRAME_walk20 182
#define FRAME_walk21 183
#define FRAME_walk22 184
#define FRAME_walk23 185
#define FRAME_walk24 186
#define FRAME_walk25 187
#define FRAME_active01 188
#define FRAME_active02 189
#define FRAME_active03 190
#define FRAME_active04 191
#define FRAME_active05 192
#define FRAME_active06 193
#define FRAME_active07 194
#define FRAME_active08 195
#define FRAME_active09 196
#define FRAME_active10 197
#define FRAME_active11 198
#define FRAME_active12 199
#define FRAME_active13 200
#define FRAME_attak301 201
#define FRAME_attak302 202
#define FRAME_attak303 203
#define FRAME_attak304 204
#define FRAME_attak305 205
#define FRAME_attak306 206
#define FRAME_attak307 207
#define FRAME_attak308 208
#define FRAME_attak401 209
#define FRAME_attak402 210
#define FRAME_attak403 211
#define FRAME_attak404 212
#define FRAME_attak405 213
#define FRAME_attak406 214
#define FRAME_attak407 215
#define FRAME_attak408 216
#define FRAME_attak409 217
#define FRAME_attak410 218
#define FRAME_attak411 219
#define FRAME_attak412 220
#define FRAME_attak413 221
#define FRAME_attak414 222
#define FRAME_attak415 223
#define FRAME_attak416 224
#define FRAME_attak417 225
#define FRAME_attak418 226
#define FRAME_attak419 227
#define FRAME_attak420 228
#define FRAME_attak421 229
#define FRAME_attak422 230
#define FRAME_attak423 231
#define FRAME_attak424 232
#define FRAME_attak425 233
#define FRAME_attak426 234
#define FRAME_attak501 235
#define FRAME_attak502 236
#define FRAME_attak503 237
#define FRAME_attak504 238
#define FRAME_attak505 239
#define FRAME_attak506 240
#define FRAME_attak507 241
#define FRAME_attak508 242
#define FRAME_attak509 243
#define FRAME_attak510 244
#define FRAME_attak511 245
#define FRAME_attak512 246
#define FRAME_attak513 247
#define FRAME_attak514 248
#define FRAME_attak515 249
#define FRAME_attak516 250
#define FRAME_death201 251
#define FRAME_death202 252
#define FRAME_death203 253
#define FRAME_death204 254
#define FRAME_death205 255
#define FRAME_death206 256
#define FRAME_death207 257
#define FRAME_death208 258
#define FRAME_death209 259
#define FRAME_death210 260
#define FRAME_death211 261
#define FRAME_death212 262
#define FRAME_death213 263
#define FRAME_death214 264
#define FRAME_death215 265
#define FRAME_death216 266
#define FRAME_death217 267
#define FRAME_death218 268
#define FRAME_death219 269
#define FRAME_death220 270
#define FRAME_death221 271
#define FRAME_death222 272
#define FRAME_death223 273
#define FRAME_death224 274
#define FRAME_death225 275
#define FRAME_death226 276
#define FRAME_death227 277
#define FRAME_death228 278
#define FRAME_death229 279
#define FRAME_death230 280
#define FRAME_death231 281
#define FRAME_death232 282
#define FRAME_death233 283
#define FRAME_death234 284
#define FRAME_death235 285
#define FRAME_death236 286
#define FRAME_death237 287
#define FRAME_death238 288
#define FRAME_death239 289
#define FRAME_death240 290
#define FRAME_death241 291
#define FRAME_death242 292
#define FRAME_death243 293
#define FRAME_death244 294
#define FRAME_death245 295
#define FRAME_death246 296
#define FRAME_death247 297
#define FRAME_death248 298
#define FRAME_death249 299
#define FRAME_death250 300
#define FRAME_death251 301
#define FRAME_death252 302
#define FRAME_death253 303
#define FRAME_death254 304
#define FRAME_death255 305
#define FRAME_death256 306
#define FRAME_death257 307
#define FRAME_death258 308
#define FRAME_death259 309
#define FRAME_death260 310
#define FRAME_death261 311
#define FRAME_death262 312
#define FRAME_death263 313
#define FRAME_death264 314
#define FRAME_death265 315
#define FRAME_death266 316
#define FRAME_death267 317
#define FRAME_death268 318
#define FRAME_death269 319
#define FRAME_death270 320
#define FRAME_death271 321
#define FRAME_death272 322
#define FRAME_death273 323
#define FRAME_death274 324
#define FRAME_death275 325
#define FRAME_death276 326
#define FRAME_death277 327
#define FRAME_death278 328
#define FRAME_death279 329
#define FRAME_death280 330
#define FRAME_death281 331
#define FRAME_death282 332
#define FRAME_death283 333
#define FRAME_death284 334
#define FRAME_death285 335
#define FRAME_death286 336
#define FRAME_death287 337
#define FRAME_death288 338
#define FRAME_death289 339
#define FRAME_death290 340
#define FRAME_death291 341
#define FRAME_death292 342
#define FRAME_death293 343
#define FRAME_death294 344
#define FRAME_death295 345
#define FRAME_death301 346
#define FRAME_death302 347
#define FRAME_death303 348
#define FRAME_death304 349
#define FRAME_death305 350
#define FRAME_death306 351
#define FRAME_death307 352
#define FRAME_death308 353
#define FRAME_death309 354
#define FRAME_death310 355
#define FRAME_death311 356
#define FRAME_death312 357
#define FRAME_death313 358
#define FRAME_death314 359
#define FRAME_death315 360
#define FRAME_death316 361
#define FRAME_death317 362
#define FRAME_death318 363
#define FRAME_death319 364
#define FRAME_death320 365
#define FRAME_jump01 366
#define FRAME_jump02 367
#define FRAME_jump03 368
#define FRAME_jump04 369
#define FRAME_jump05 370
#define FRAME_jump06 371
#define FRAME_jump07 372
#define FRAME_jump08 373
#define FRAME_jump09 374
#define FRAME_jump10 375
#define FRAME_jump11 376
#define FRAME_jump12 377
#define FRAME_jump13 378
#define FRAME_pain401 379
#define FRAME_pain402 380
#define FRAME_pain403 381
#define FRAME_pain404 382
#define FRAME_pain501 383
#define FRAME_pain502 384
#define FRAME_pain503 385
#define FRAME_pain504 386
#define FRAME_pain601 387
#define FRAME_pain602 388
#define FRAME_pain603 389
#define FRAME_pain604 390
#define FRAME_pain605 391
#define FRAME_pain606 392
#define FRAME_pain607 393
#define FRAME_pain608 394
#define FRAME_pain609 395
#define FRAME_pain610 396
#define FRAME_pain611 397
#define FRAME_pain612 398
#define FRAME_pain613 399
#define FRAME_pain614 400
#define FRAME_pain615 401
#define FRAME_pain616 402
#define FRAME_pain617 403
#define FRAME_pain618 404
#define FRAME_pain619 405
#define FRAME_pain620 406
#define FRAME_pain621 407
#define FRAME_pain622 408
#define FRAME_pain623 409
#define FRAME_pain624 410
#define FRAME_pain625 411
#define FRAME_pain626 412
#define FRAME_pain627 413
#define FRAME_stand201 414
#define FRAME_stand202 415
#define FRAME_stand203 416
#define FRAME_stand204 417
#define FRAME_stand205 418
#define FRAME_stand206 419
#define FRAME_stand207 420
#define FRAME_stand208 421
#define FRAME_stand209 422
#define FRAME_stand210 423
#define FRAME_stand211 424
#define FRAME_stand212 425
#define FRAME_stand213 426
#define FRAME_stand214 427
#define FRAME_stand215 428
#define FRAME_stand216 429
#define FRAME_stand217 430
#define FRAME_stand218 431
#define FRAME_stand219 432
#define FRAME_stand220 433
#define FRAME_stand221 434
#define FRAME_stand222 435
#define FRAME_stand223 436
#define FRAME_stand224 437
#define FRAME_stand225 438
#define FRAME_stand226 439
#define FRAME_stand227 440
#define FRAME_stand228 441
#define FRAME_stand229 442
#define FRAME_stand230 443
#define FRAME_stand231 444
#define FRAME_stand232 445
#define FRAME_stand233 446
#define FRAME_stand234 447
#define FRAME_stand235 448
#define FRAME_stand236 449
#define FRAME_stand237 450
#define FRAME_stand238 451
#define FRAME_stand239 452
#define FRAME_stand240 453
#define FRAME_stand241 454
#define FRAME_stand242 455
#define FRAME_stand243 456
#define FRAME_stand244 457
#define FRAME_stand245 458
#define FRAME_stand246 459
#define FRAME_stand247 460
#define FRAME_stand248 461
#define FRAME_stand249 462
#define FRAME_stand250 463
#define FRAME_stand251 464
#define FRAME_stand252 465
#define FRAME_stand253 466
#define FRAME_stand254 467
#define FRAME_stand255 468
#define FRAME_stand256 469
#define FRAME_stand257 470
#define FRAME_stand258 471
#define FRAME_stand259 472
#define FRAME_stand260 473
#define FRAME_walk201 474
#define FRAME_walk202 475
#define FRAME_walk203 476
#define FRAME_walk204 477
#define FRAME_walk205 478
#define FRAME_walk206 479
#define FRAME_walk207 480
#define FRAME_walk208 481
#define FRAME_walk209 482
#define FRAME_walk210 483
#define FRAME_walk211 484
#define FRAME_walk212 485
#define FRAME_walk213 486
#define FRAME_walk214 487
#define FRAME_walk215 488
#define FRAME_walk216 489
#define FRAME_walk217 490
#define MODEL_SCALE 1.000000
| Java |
<?php
// $Id$
/**
* @file
* general functions for mothership
*/
function mothership_id_safe($string, $vars = "default") {
// Replace with dashes anything that isn't A-Z, numbers, dashes, or underscores.
if($vars == "remove-numbers"){
$string = strtolower(preg_replace('/[^a-zA-Z_-]+/', '-', $string));
}else{
$string = strtolower(preg_replace('/[^a-zA-Z0-9_-]+/', '-', $string));
}
// change the "_" to "-"
$string = strtolower(str_replace('_', '-', $string));
// If the first character is not a-z, add 'n' in front.
if (function_exists('ctype_lower')) {
if (!ctype_lower($string{0})) { // Don't use ctype_alpha since its locale aware.
$string = 'id' . $string;
}
}
else {
preg_match('/[a-z]+/', $string{0}, $matches);
if (count($matches) == 0) {
$string = 'id' . $string;
}
}
return $string;
}
/*
getting some of the userprofile data into a single function
*/
function mothership_userprofile($user){
if ($user->uid) {
// global $user;
// $profile = profile_load_profile($user);
//$user->profile_name
//user picture
if ($user->picture) {
$userimage = '<img src="/' . $user->picture . '">';
print '<div class="profile-image">' . l($userimage, 'user/' . $user->uid, $options = array('html' => TRUE)) . '</div>';
}
print '<ul class="profile">';
print '<li class="profile-name">' . l($user->name, 'user/' . $user->uid . '') . '</li>';
print '<li class="profile-edit">' . l(t('edit'), 'user/' . $user->uid . '/edit') . '</li>';
print '<li class="profile-logout">' . l(t('Sign out'), 'logout') . '</li>';
print '</ul>';
}
}
/*
Quick & handy function for adding time ago
*/
function mothership_time_ago($timestamp,$granularity = 2, $langcode = NULL){
$difference = time() - $timestamp;
$text = format_interval($difference, $granularity, $langcode) ." ". t("ago");
return $text;
}
/*
return only the terms from a vocabulary in the node
*/
function return_terms_from_vocabulary($node, $vid){
$terms = taxonomy_node_get_terms_by_vocabulary($node, $vid, $key = 'tid');
// $vocabulary = taxonomy_vocabulary_load($vid);
// $content .='<div class="vocabulary">'.$vocabulary->name.'</div>';
$termslist = '';
if ($terms) {
$content .= '<span class="terms">';
foreach ($terms as $term) {
$termslist = $termslist . '<span class="term-icon-'. mothership_id_safe($term->name) .'">' . l($term->name, 'taxonomy/term/'.$term->tid) .'</span> | ';
}
//TODO make a better split option hardcoded is kinda sad ;)
$content.= trim ($termslist," |").'</span>';
}
return $content;
}
| Java |
/* Source for:
* Cypress TrueTouch(TM) Standard Product I2C touchscreen driver.
* drivers/input/touchscreen/cyttsp-i2c.c
*
* Copyright (C) 2009, 2010 Cypress Semiconductor, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2, and only version 2, as published by the
* Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* 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.
*
* Cypress reserves the right to make changes without further notice
* to the materials described herein. Cypress does not assume any
* liability arising out of the application described herein.
*
* Contact Cypress Semiconductor at www.cypress.com
*
*/
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/slab.h>
#include <linux/gpio.h>
#include <mach/gpio.h>
#include <linux/irq.h>
#include <linux/interrupt.h>
#include <linux/timer.h>
#include <linux/workqueue.h>
#include <linux/byteorder/generic.h>
#include <linux/bitops.h>
#ifdef CONFIG_HAS_EARLYSUSPEND
#include <linux/earlysuspend.h>
#endif /* CONFIG_HAS_EARLYSUSPEND */
#include <linux/regulator/consumer.h>
#include <mach/vreg.h>
#include <linux/wakelock.h>
#include <linux/input/mt.h>
#define CYTTSP_DECLARE_GLOBALS
#include <linux/miscdevice.h>
#include <linux/cyttsp.h>
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
#include <linux/issp_defs.h>
#include <linux/issp_extern.h>
#endif
#include <linux/uaccess.h>
uint32_t cyttsp_tsdebug1;
module_param_named(tsdebug1, cyttsp_tsdebug1, uint, 0664);
#if defined(CONFIG_EF33_BOARD) || defined(CONFIG_EF34_BOARD)
#define FEATURE_TOUCH_KEY
#endif
/* -------------------------------------------------------------------- */
/* EF33S gpio & resolution & key area*/
/* -------------------------------------------------------------------- */
#define GPIO_TOUCH_RST 95
#define GPIO_TOUCH_CHG 61
#define GPIO_TOUCH_SDA 64
#define GPIO_TOUCH_SCL 65
#define GPIO_TOUCH_ID 93
#define IRQ_TOUCH_INT gpio_to_irq(GPIO_TOUCH_CHG)
/* -------------------------------------------------------------------- */
/* debug option */
/* -------------------------------------------------------------------- */
//#define TOUCH_DBG_ENABLE
#ifdef TOUCH_DBG_ENABLE
#define dbg(fmt, args...) printk("[TOUCH]" fmt, ##args)
#else
#define dbg(fmt, args...)
#endif
#define dbg_func_in() dbg("[FUNC_IN] %s\n", __func__)
#define dbg_func_out() dbg("[FUNC_OUT] %s\n", __func__)
#define dbg_line() dbg("[LINE] %d(%s)\n", __LINE__, __func__)
/* -------------------------------------------------------------------- */
#define FEATURE_SKY_PROCESS_CMD_KEY
#ifdef FEATURE_TOUCH_KEY
#define X_MAX 480
#define Y_MAX 800
#define NULL_KEY_AREA 840
#define MENU_KEY_MIN 40
#define MENU_KEY_MAX 140
#define HOME_KEY_MIN 210
#define HOME_KEY_MAX 280
#define BACK_KEY_MIN 360
#define BACK_KEY_MAX 460
#endif
#ifdef FEATURE_CYTTSP_HEARTBEAT
#define CYTTSP_HEARTBEAT_TIME 3
#endif
#define TOUCH_MAX_NUM 4 // 2
#define SENSOR_X 12
#define SENSOR_Y 20
#define MAX_NODE SENSOR_X*SENSOR_Y
#define CYTTSP_BASE_MIN 65
#define CYTTSP_BASE_MAX 135
#define CYTTSP_MUTEX_LOCK //ST_LIM
//----------------- Added --------------//
/* abs settings */
/* abs value offsets */
#define CY_NUM_ABS_VAL 5 /* number of abs values per setting */
#define CY_SIGNAL_OST 0
#define CY_MIN_OST 1
#define CY_MAX_OST 2
#define CY_FUZZ_OST 3
#define CY_FLAT_OST 4
/* axis signal offsets */
#define CY_NUM_ABS_SET 5 /* number of abs signal sets */
#define CY_ABS_X_OST 0
#define CY_ABS_Y_OST 1
#define CY_ABS_P_OST 2
#define CY_ABS_W_OST 3
#define CY_ABS_ID_OST 4
#define CY_IGNORE_VALUE 0xFFFF /* mark unused signals as ignore */
#define HI_TRACKID(reg) ((reg & 0xF0) >> 4)
#define LO_TRACKID(reg) ((reg & 0x0F) >> 0)
/* Touch structure */
struct cyttsp_trk{
bool tch;
int abs[CY_NUM_ABS_SET];
} ;
int prev_touches=0;
//----------------- --------------------------//
/* ****************************************************************************
* static value
* ************************************************************************** */
static struct cyttsp_gen3_xydata_t g_xy_data;
//static struct cyttsp_bootloader_data_t g_bl_data;
//static struct cyttsp_sysinfo_data_t g_sysinfo_data;
//static struct cyttsp_gen3_xydata_t g_wake_data;
static const struct i2c_device_id cyttsp_id[] = {
{ CYTTSP_I2C_NAME, 0 }, { }
};
/* CY TTSP I2C Driver private data */
struct cyttsp {
struct i2c_client *client;
struct input_dev *input;
struct work_struct work;
#ifdef FEATURE_CYTTSP_HEARTBEAT
struct work_struct work2;
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
//struct work_struct work3; // N1037 20120312 for ICS
struct delayed_work work3;
#endif
struct timer_list timer;
struct mutex mutex;
#ifdef CYTTSP_MUTEX_LOCK
struct mutex lock_mutex;
#endif
char phys[32];
struct cyttsp_platform_data *platform_data;
u8 num_prev_touch;
u16 active_track[CYTTSP_NUM_TRACK_ID];
u16 prev_st_touch[CYTTSP_NUM_ST_TOUCH_ID];
u16 prev_mt_touch[CYTTSP_NUM_MT_TOUCH_ID];
u16 prev_mt_pos[CYTTSP_NUM_MT_TOUCH_ID][2];
struct cyttsp_trk prv_trk[CYTTSP_NUM_TRACK_ID];
atomic_t irq_enabled;
struct early_suspend early_suspend;
};
#ifdef FEATURE_CYTTSP_HEARTBEAT
static int start_heartbeat_timer = false;
#endif
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
struct cyttsp *cyttsp_data = NULL;
#endif
/* To check touch chip */
static int Touch_Dbg_Enable =0;
//static u16 prev_mt_pos[CYTTSP_NUM_TRACK_ID][2];
static struct wake_lock touch_wake_lock;
typedef enum touch_status {
TOUCH_POWERON,
TOUCH_POWEROFF,
TOUCH_UPDATE
} touch_status;
typedef enum
{
BATTERY_PLUGGED_NONE = 0,
BATTERY_PLUGGED_AC = 1,
BATTERY_PLUGGED_USB = 2,
BATTERY_PLUGGED_SLEEP = 10
} CHARGER_MODE;
typedef enum touch_ioctl {
TOUCH_CHARGER_MODE = 701,
TOUCH_IOCTL_READ_LASTKEY = 1001,
TOUCH_IOCTL_DO_KEY,
TOUCH_IOCTL_RELEASE_KEY,
TOUCH_IOCTL_PRESS_TOUCH = 1007,
TOUCH_IOCTL_RELEASE_TOUCH,
TOUCH_IOCTL_SENSOR_X = 2005,
TOUCH_IOCTL_SENSOR_Y,
TOUCH_IOCTL_CHECK_BASE,
TOUCH_IOCTL_READ_IC_VERSION,
TOUCH_IOCTL_READ_FW_VERSION,
TOUCH_IOCTL_START_UPDATE,
TOUCH_IOCTL_SELF_TEST,
TOUCH_IOCTL_SET_COLOR
} touch_ioctl;
static int Touch_Status =TOUCH_POWERON;
static int Touch_ChagerMode = BATTERY_PLUGGED_NONE;
static unsigned char bBlack=false;
struct cyttsp *ts_temp;
#if defined(CONFIG_APACHE_BOARD)
struct delayed_work work_delay_firmware;
#endif
MODULE_DEVICE_TABLE(i2c, cyttsp_id);
/* ****************************************************************************
* Prototypes for static functions
* ************************************************************************** */
static void cyttsp_xy_worker(struct work_struct *work);
#ifdef FEATURE_CYTTSP_HEARTBEAT
static void cyttsp_check_heartbeat(struct work_struct *work2);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
void check_firmware_update(struct work_struct *work3);
#endif
static irqreturn_t cyttsp_irq(int irq, void *handle);
#if 0
static int cyttsp_inlist(u16 prev_track[], u8 curr_track_id, u8 *prev_loc, u8 num_touches);
static int cyttsp_next_avail_inlist(u16 curr_track[], u8 *new_loc, u8 num_touches);
#endif
#ifdef CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
static int cyttsp_putbl(struct cyttsp *ts, int show, int show_status, int show_version, int show_cid);
#endif// CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
static int __devinit cyttsp_probe(struct i2c_client *client, const struct i2c_device_id *id);
static int __devexit cyttsp_remove(struct i2c_client *client);
static int cyttsp_resume(struct i2c_client *client);
static int cyttsp_suspend(struct i2c_client *client, pm_message_t message);
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
static long ts_fops_ioctl(struct file *filp,unsigned int cmd, unsigned long arg);
static int ts_fops_open(struct inode *inode, struct file *filp);
#endif
#ifdef CONFIG_HAS_EARLYSUSPEND
static void cyttsp_early_suspend(struct early_suspend *handler);
static void cyttsp_late_resume(struct early_suspend *handler);
#endif /* CONFIG_HAS_EARLYSUSPEND */
static int pantech_auto_check(u8*);
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
static int firmware_update_by_user(void);
static int firmware_version_check(void);
#endif
static int pantech_selftest_check(void);
void Change_Active_Distance(u8 value); //test
/* ****************************************************************************
*
* ************************************************************************** */
static struct i2c_driver cyttsp_driver = {
.driver = {
.name = CYTTSP_I2C_NAME,
.owner = THIS_MODULE,
},
.probe = cyttsp_probe,
.remove = __devexit_p(cyttsp_remove),
// .suspend = cyttsp_suspend,
// .resume = cyttsp_resume,
.id_table = cyttsp_id,
};
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Cypress TrueTouch(R) Standard touchscreen driver");
MODULE_AUTHOR("Cypress");
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
struct cyttsp *sky_process_cmd_ts=NULL;
static struct file_operations ts_fops = {
.owner = THIS_MODULE,
.open = ts_fops_open,
// .release = ts_fops_close,
.unlocked_ioctl = ts_fops_ioctl,
};
static struct miscdevice touch_event = {
.minor = MISC_DYNAMIC_MINOR,
.name = "touch_fops",
.fops = &ts_fops,
};
static int ts_fops_open(struct inode *inode, struct file *filp)
{
//filp->private_data = cyttsp_data;
return 0;
}
#if 1 //[BIH] ICS port... ioctl changed to unlocked_ioctl or compact_ioctl...
//static DEFINE_MUTEX(cyttsp_mutex);
static long ts_fops_ioctl(struct file *filp,
unsigned int cmd, unsigned long arg)
#else
static int ts_fops_ioctl(struct inode *inode, struct file *filp,
unsigned int cmd, unsigned long arg)
#endif
{
void __user *argp = (void __user *)arg;
if(cyttsp_data ==NULL)
{
cyttsp_debug("Null Device\n");
return 0;
}
cyttsp_debug("cmd = %d, argp = 0x%x\n", cmd, (unsigned int)argp);
// printk("cmd = %d, argp = 0x%x\n", cmd, (unsigned int)argp);
// mutex_lock(&cyttsp_mutex);
switch (cmd)
{
case TOUCH_IOCTL_READ_LASTKEY:
break;
case TOUCH_IOCTL_DO_KEY:
if ( (int)argp == 0x20a )
input_report_key(cyttsp_data->input, 0xe3, 1);
else if ( (int)argp == 0x20b )
input_report_key(cyttsp_data->input, 0xe4, 1);
else
input_report_key(cyttsp_data->input, (int)argp, 1);
input_sync(cyttsp_data->input);
if((int)argp == KEY_9)
{
printk("Enable Touch Debug!!\n");
Touch_Dbg_Enable = true;
}
else if((int)argp == KEY_8)
{
printk("Disable Touch Debug!!\n");
Touch_Dbg_Enable = false;
}
/*
else if((int)argp == KEY_F2)
{
int ret = 0;
printk("Start Touch Firmware update!!\n");
ret = firmware_update_by_user();
}
*/
break;
case TOUCH_IOCTL_RELEASE_KEY:
if ( (int)argp == 0x20a )
input_report_key(cyttsp_data->input, 0xe3, 0);
else if ( (int)argp == 0x20b )
input_report_key(cyttsp_data->input, 0xe4, 0);
else
input_report_key(cyttsp_data->input, (int)argp, 0);
input_sync(cyttsp_data->input);
break;
// +++ FEATURE_P_VZW_PS_STABILITY_AT_CMD
case TOUCH_IOCTL_PRESS_TOUCH:
{
int touchX=arg&0x0000FFFF;
int touchY= (arg >> 16) & 0x0000FFFF;
input_report_abs(cyttsp_data->input, ABS_MT_TOOL_TYPE , 1);
input_report_abs(cyttsp_data->input, ABS_MT_TOUCH_MAJOR, CYTTSP_TOUCH);
input_report_abs(cyttsp_data->input, ABS_MT_WIDTH_MAJOR, CYTTSP_SMALL_TOOL_WIDTH);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_X, touchX);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_Y, touchY);
CYTTSP_MT_SYNC(cyttsp_data->input);
input_sync(cyttsp_data->input);
}
break;
case TOUCH_IOCTL_RELEASE_TOUCH:
{
int touchX=arg&0x0000FFFF;
int touchY= (arg >> 16) & 0x0000FFFF;
input_report_abs(cyttsp_data->input, ABS_MT_TOOL_TYPE , 1);
input_report_abs(cyttsp_data->input, ABS_MT_TOUCH_MAJOR, CYTTSP_NOTOUCH);
input_report_abs(cyttsp_data->input, ABS_MT_WIDTH_MAJOR, CYTTSP_SMALL_TOOL_WIDTH);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_X, touchX);
input_report_abs(cyttsp_data->input, ABS_MT_POSITION_Y, touchY);
CYTTSP_MT_SYNC(cyttsp_data->input);
input_sync(cyttsp_data->input);
}
break;
// ---
case TOUCH_IOCTL_SENSOR_X:
{
int send_data;
send_data = SENSOR_X;
if (copy_to_user(argp, &send_data, sizeof(send_data)))
return false;
}
break;
case TOUCH_IOCTL_SENSOR_Y:
{
int send_data;
send_data = SENSOR_Y;
if (copy_to_user(argp, &send_data, sizeof(send_data)))
return false;
}
break;
case TOUCH_IOCTL_CHECK_BASE:
{
u8 send_byte[MAX_NODE];
//printk("TOUCH_IOCTL_CHECK_BASE!!\n");
disable_irq_nosync(ts_temp->client->irq);
pantech_auto_check(send_byte);
enable_irq(ts_temp->client->irq);
if (copy_to_user(argp, send_byte, MAX_NODE))
return false;
}
break;
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
case TOUCH_IOCTL_READ_IC_VERSION:
{
int ret = 0;
ret = firmware_version_check();
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
case TOUCH_IOCTL_READ_FW_VERSION:
{
int ret =0;
if(bBlack == false) // White Model etc..
ret = CYTTPS_NONBLACK_FIRMWARE_VER_ID;
else // Black Model
ret = CYTTPS_FIRMWARE_VER_ID;
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
case TOUCH_IOCTL_START_UPDATE:
{
int ret = 0;
ret = firmware_update_by_user(); // if ret == 0 success, or not fail
printk("TOUCH_IOCTL_START_UPDATE ret : %d\n", ret);
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
#endif
case TOUCH_CHARGER_MODE:
printk("TOUCH_CHARGER_MODE Setting : %d\n", (int)arg);
Touch_ChagerMode = arg;
break;
case TOUCH_IOCTL_SELF_TEST:
{
int ret = 0;
ret = pantech_selftest_check();
if (copy_to_user(argp, &ret, sizeof(ret)))
return false;
}
break;
case TOUCH_IOCTL_SET_COLOR:
bBlack = arg;
break;
default:
break;
}
// mutex_unlock(&cyttsp_mutex);
return true;
}
#endif
void Change_Active_Distance(u8 value)
{
int rc = -1;
u8 byte_data;
struct cyttsp *ts = ts_temp;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_GEST_SET,sizeof(byte_data), &byte_data);
//printk("Chage_Active_Distance : %02x\n", byte_data);
byte_data = value;
rc = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_GEST_SET, sizeof(byte_data), &byte_data);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
return;
}
static ssize_t cyttsp_irq_status(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct i2c_client *client = container_of(dev,
struct i2c_client, dev);
struct cyttsp *ts = i2c_get_clientdata(client);
return sprintf(buf, "%u\n", atomic_read(&ts->irq_enabled));
}
static ssize_t cyttsp_irq_enable(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t size)
{
struct i2c_client *client = container_of(dev,
struct i2c_client, dev);
struct cyttsp *ts = i2c_get_clientdata(client);
int err = 0;
unsigned long value;
/*
struct qtm_obj_message *msg;
*/
if (size > 2)
return -EINVAL;
err = strict_strtoul(buf, 10, &value);
if (err != 0)
return err;
switch (value) {
case 0:
if (atomic_cmpxchg(&ts->irq_enabled, 1, 0)) {
pr_info("touch irq disabled!\n");
disable_irq_nosync(ts->client->irq);
}
err = size;
break;
case 1:
if (!atomic_cmpxchg(&ts->irq_enabled, 0, 1)) {
pr_info("touch irq enabled!\n");
/*
msg = cyttsp_read_msg(ts);
if (msg == NULL)
pr_err("%s: Cannot read message\n", __func__);
*/
enable_irq(ts->client->irq);
}
err = size;
break;
default:
pr_info("cyttsp_irq_enable failed -> irq_enabled = %d\n",
atomic_read(&ts->irq_enabled));
err = -EINVAL;
break;
}
return err;
}
static DEVICE_ATTR(irq_enable, 0664, cyttsp_irq_status, cyttsp_irq_enable);
int pantech_ctl_update(int cmd, int value)
{
int rt = -1;
struct regulator *vreg_touch, *vreg_touch_temp;
switch(cmd)
{
case ISSP_IOCTL_SCLK_TO_GPIO:
if(value){
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
else{
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
rt = 1;
break;
case ISSP_IOCTL_DATA_TO_GPIO:
if(value){
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
else{
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
}
rt = 1;
break;
case ISSP_IOCTL_SCLK:
gpio_set_value(GPIO_TOUCH_SCL, value);
rt = 1;
break;
case ISSP_IOCTL_DATA:
gpio_set_value(GPIO_TOUCH_SDA, value);
rt = 1;
break;
case ISSP_IOCTL_RESET:
break;
case ISSP_IOCTL_POWER:
//printk("Touch Power: %d, cmd: %d\n", value, cmd);
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
vreg_touch = regulator_get(NULL, "8058_l11");
regulator_set_voltage(vreg_touch, 1900000, 1900000);
#else
vreg_touch = regulator_get(NULL, "8058_lvs0");
#endif
if(value)
rt = regulator_enable(vreg_touch);
else
rt = regulator_disable(vreg_touch);
regulator_put(vreg_touch);
break;
case ISSP_IOCTL_POWER_ALL:
//printk("Touch Power All: %d, cmd: %d\n", value, cmd);
vreg_touch_temp = regulator_get(NULL, "8058_l19");
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
vreg_touch = regulator_get(NULL, "8058_l11");
regulator_set_voltage(vreg_touch, 1900000, 1900000);
#else
vreg_touch = regulator_get(NULL, "8058_lvs0");
#endif
regulator_set_voltage(vreg_touch_temp, 3000000, 3000000);
if(value)
{
rt = regulator_enable(vreg_touch);
rt = regulator_enable(vreg_touch_temp);
}
else
{
rt = regulator_disable(vreg_touch);
rt = regulator_disable(vreg_touch_temp);
}
regulator_put(vreg_touch);
regulator_put(vreg_touch_temp);
break;
case ISSP_IOCTL_READ_DATA_PIN:
rt = gpio_get_value(GPIO_TOUCH_SDA);
break;
case ISSP_IOCTL_WAIT:
udelay(value);
break;
case ISSP_IOCTL_INTR:
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_set_value(GPIO_TOUCH_CHG, value);
rt = 1;
break;
case ISSP_TEST_READ_SCL:
rt = gpio_get_value(GPIO_TOUCH_SCL);
break;
case ISSP_TEST_READ_SDA:
rt = gpio_get_value(GPIO_TOUCH_SDA);
break;
case ISSP_TEST_READ_RESET:
rt = gpio_get_value(GPIO_TOUCH_RST);
break;
case ISSP_COMPLITED_UPDATA:
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_DISABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SDA, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_SCL, 1, GPIO_CFG_OUTPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
rt = 1;
break;
default:
dbg("UNKNOWN CMD\n");
break;
}
return rt;
}
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
void check_firmware_update(struct work_struct *work3)
{
int retry_cnt = 3;
u8 byte_data[4];
int rc = -1, check_update_pass = 0, curr_version =0;
struct cyttsp *ts = ts_temp;
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
return;
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
#endif
wake_lock(&touch_wake_lock);
disable_irq(ts->client->irq);
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_VER_ID,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
} while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
dbg("i2c communcation1 %s, byte_data = %d, %d, %d, %d\n", (rc < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS",byte_data[0],byte_data[1],byte_data[2],byte_data[3]);
if((int)byte_data[0] == 0 || rc < CYTTSP_OPERATIONAL)
{
dbg("Retry read firmware version!\n");
msleep(200);
pantech_ctl_update(ISSP_IOCTL_POWER, 0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 1);
msleep(200);
retry_cnt = 3;
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_VER_ID,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
} while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
}
pantech_ctl_update(ISSP_IOCTL_INTR,0);
#ifdef FEATURE_SKY_NONBLACK_FIRMWARE
if(rc >= CYTTSP_OPERATIONAL) // read success
bBlack = (int)byte_data[0] % 2;
if(bBlack == false) // White Model etc..
curr_version = CYTTPS_NONBLACK_FIRMWARE_VER_ID;
else // Black Model
curr_version = CYTTPS_FIRMWARE_VER_ID;
#else
curr_version = CYTTPS_FIRMWARE_VER_ID;
#endif
dbg("[Touch] Model Black Check: %d, Current Version: %d\n", bBlack, curr_version);
if(((curr_version > byte_data[0]) && (byte_data[0] != 0)) || (rc < CYTTSP_OPERATIONAL))
{
retry_cnt = 5;
dbg("Start Firmware Update chip id: %d\n", byte_data[0]);
do{
check_update_pass = touch_update_main(bBlack);
udelay(2*1000);
}while((check_update_pass != 0) && --retry_cnt);
}
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
pantech_ctl_update(ISSP_IOCTL_INTR,1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA,0);
if(check_update_pass != 0)
{
msleep(200);
pantech_ctl_update(ISSP_IOCTL_POWER, 0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 1);
msleep(100);
cancel_work_sync(&ts->work);
}
dbg("check_firmware_update end!!(check_update_pass = %d)\n",check_update_pass);
enable_irq(ts->client->irq);
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = true;
#endif
wake_unlock(&touch_wake_lock);
return;
}
static int firmware_version_check(void)
{
int rc = -1, retry_cnt = 3;
u8 byte_data[4];
struct cyttsp *ts = ts_temp;
if(Touch_Status >= TOUCH_POWEROFF)
{
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 1);
pantech_ctl_update(ISSP_IOCTL_INTR, 1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA, 0);
msleep(300);
// return false;
}
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_VER_ID,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
}
while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if(rc < CYTTSP_OPERATIONAL)
{
printk("Can't read Touch Firmware Version\n");
return 1;
}
printk("Touch Firmware Update Version : %d, Current Version: %d\n" ,
CYTTPS_FIRMWARE_VER_ID,(int)byte_data[0]);
if(Touch_Status >= TOUCH_POWEROFF)
{
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 0);
}
return (int)byte_data[0]; // Need not
}
static int firmware_set_charger_mode(int mode)
{
int rc = -1, retry_cnt = 3;
u8 byte_data[4], send_byte = 0x00;
struct cyttsp *ts = ts_temp;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_CHARGER_MODE,sizeof(byte_data), (u8 *)&byte_data);
udelay(2*1000);
}
while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if(rc < CYTTSP_OPERATIONAL)
{
printk("Can't read Touch Charger Mode\n");
return 1;
}
if(Touch_Dbg_Enable)
printk("Touch IC Charger Mode %02x\n" ,(int)byte_data[0]);
if(mode > BATTERY_PLUGGED_NONE) // charger mode on
{
if((int)byte_data[0] != CYTTPS_CHARGER_MODE)
{
send_byte = CYTTPS_CHARGER_MODE;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
rc = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_CHARGER_MODE, sizeof(send_byte), &send_byte);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
}
}
else // charger mode off
{
if((int)byte_data[0] != 0x00)
{
send_byte = 0x00;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
rc = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_CHARGER_MODE, sizeof(send_byte), &send_byte);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
}
}
return 0;
}
static int firmware_update_by_user(void)
{
struct cyttsp *ts = ts_temp;
int check_update_pass = -1;
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
{
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 1);
msleep(300);
// return false;
}
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
#endif
Touch_Status= TOUCH_UPDATE;
wake_lock(&touch_wake_lock);
/*ÀÎÅÍ·´ÅÍ PIN HIGH »óŸ¦ º¯°æÇϱâ À§ÇØ IRQ¸¦ ÇØÁ¦ÇÔ */
disable_irq(ts->client->irq);
/* ÀÎÆ®·´ÅÍ PIN HIGH »óÅ·ΠÀÎÇÏ¿© 2.6V_TOUCH Àü¿ø OFFÇÏ¿©µµ 1.2V Àü¾Ð È帣´Â Çö»óÀ¸·Î Value°ªÀ» 0À¸·Î ¼³Á¤ */
pantech_ctl_update(ISSP_IOCTL_INTR,0);
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
check_update_pass = touch_update_main(bBlack);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
pantech_ctl_update(ISSP_IOCTL_INTR,1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA,0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 0);
msleep(100);
pantech_ctl_update(ISSP_IOCTL_POWER, 1);
msleep(100);
cancel_work_sync(&ts->work);
enable_irq(ts->client->irq);
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = true;
#endif
wake_unlock(&touch_wake_lock);
Touch_Status= TOUCH_POWERON;
return check_update_pass;
}
#endif
/* The cyttsp_xy_worker function reads the XY coordinates and sends them to
* the input layer. It is scheduled from the interrupt (or timer).
*/
#ifdef FEATURE_TOUCH_KEY
#define CYTTSP_MENU_KEY 0x01
#define CYTTSP_BACK_KEY 0x02
#define CYTTSP_HOME_KEY 0x04
#define CYTTSP_NULL_KEY 0x08
static int key_status = 0x00;
#endif
#if 0//def FEATURE_SKY_TOUCH_DELTA_DEBUG
static u16 pre_x_data;
static u16 pre_y_data;
static u16 delta_x;
static u16 delta_y;
#endif
#ifdef FEATURE_CYTTSP_HEARTBEAT
void cyttsp_check_heartbeat(struct work_struct *work2)
{
struct cyttsp *ts = container_of(work2,struct cyttsp,work2);
int retry_cnt = 3;
u8 new_heartbeart_data[4];
int rc = -1;
static u8 old_heartbeat_data = 0xFF;
memset((void*)new_heartbeart_data,0x00,sizeof(new_heartbeart_data));
if(start_heartbeat_timer == false)
return;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
/* Read Heartbeat Count */
rc = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_READ_HEARTBEAT,sizeof(new_heartbeart_data), (u8 *)&new_heartbeart_data);
}
while ((rc < CYTTSP_OPERATIONAL) && --retry_cnt);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if(Touch_Dbg_Enable)
printk("##### Check Count = %s, byte_data = %d, %d, %d, %d\n", (rc < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS",new_heartbeart_data[0],new_heartbeart_data[1],new_heartbeart_data[2],new_heartbeart_data[3]);
if(start_heartbeat_timer == false)
return;
if(rc < CYTTSP_OPERATIONAL || old_heartbeat_data == new_heartbeart_data[0])
{
/* I2c error or Touch Chip's heartbeat value is not change */
disable_irq(ts->client->irq);
pantech_ctl_update(ISSP_IOCTL_INTR,0);
pantech_ctl_update(ISSP_IOCTL_POWER,0);
msleep(200);
pantech_ctl_update(ISSP_IOCTL_INTR,1);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_INPUT, GPIO_CFG_PULL_UP, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
enable_irq(ts->client->irq);
pantech_ctl_update(ISSP_IOCTL_POWER,1);
if(Touch_Dbg_Enable)
printk("HeartBeat Fail old_data = %d, new_data = %d",old_heartbeat_data, new_heartbeart_data[0]);
}
if(!start_heartbeat_timer)
old_heartbeat_data = 0xFF;
// Set Charger Mode
firmware_set_charger_mode(Touch_ChagerMode);
return;
}
#endif
static bool cur_touchflag[TOUCH_MAX_NUM];
int touch_mask[TOUCH_MAX_NUM];
struct cyttsp_trk cur_trk[TOUCH_MAX_NUM];
void cyttsp_xy_worker(struct work_struct *work)
{
struct cyttsp *ts = container_of(work,struct cyttsp,work);
int i;
int retval = 0;
u8 curr_touches = 0;
u8 id = 0;
// int t = 0;
// int num_sent = 0;
// int signal = 0;
int tch = 0;
#ifdef FEATURE_TOUCH_KEY
int key_relese = true;
#endif
for (i=0;i<TOUCH_MAX_NUM;i++)
{
touch_mask[i] = -1;
}
if(Touch_Dbg_Enable)
printk("[TOUCH] Start cyttsp_xy_worker\n");
if(Touch_Status >= TOUCH_POWEROFF)
goto exit_xy_worker;
/* get event data from CYTTSP device */
i = CYTTSP_NUM_RETRY;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
do {
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(struct cyttsp_gen3_xydata_t), (u8 *)&g_xy_data);
}
while ((retval < CYTTSP_OPERATIONAL) && --i);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
/* return immediately on failure to read device on the i2c bus */
if (retval < CYTTSP_OPERATIONAL) {
cyttsp_debug("exit_xy_worker 1");
goto exit_xy_worker;
}
cyttsp_xdebug("TTSP worker start 2:\n");
if ((curr_touches = GET_NUM_TOUCHES(g_xy_data.tt_stat)) > CYTTSP_NUM_MT_TOUCH_ID) {
/* if the number of fingers on the touch surface is more than the maximum
* then there will be no new track information even for the orginal
* touches. Therefore, ignore this touch event.
*/
cyttsp_debug("exit_xy_worker 2");
goto exit_xy_worker;
}
else if (IS_LARGE_AREA(g_xy_data.tt_stat)==1) {
/* terminate all active tracks */
curr_touches = CYTTSP_NOTOUCH;
cyttsp_debug("Large object detected. Terminating active tracks\n");
}
#ifdef FEATURE_TOUCH_KEY
for(i=0; i<curr_touches; i++)
{
int x =0, y=0;
switch(i)
{
case 0:
x = be16_to_cpu(g_xy_data.x1);
y = be16_to_cpu(g_xy_data.y1);
break;
case 1:
x = be16_to_cpu(g_xy_data.x2);
y = be16_to_cpu(g_xy_data.y2);
break;
case 2:
x = be16_to_cpu(g_xy_data.x3);
y = be16_to_cpu(g_xy_data.y3);
break;
case 3:
x = be16_to_cpu(g_xy_data.x4);
y = be16_to_cpu(g_xy_data.y4);
break;
default:
break;
}
if(y > Y_MAX)
{
key_relese = false;
if(y < NULL_KEY_AREA && (!key_status || key_status == CYTTSP_NULL_KEY))
{
key_status = CYTTSP_NULL_KEY;
dbg("Down TOUCH NULL\n");
}
else if((MENU_KEY_MIN < x && x < MENU_KEY_MAX) && (!key_status || key_status == CYTTSP_MENU_KEY))
{
key_status = CYTTSP_MENU_KEY;
input_report_key(ts->input, KEY_MENU, CYTTSP_TOUCH);
dbg("Down TOUCH MENU\n");
input_sync(ts->input);
}
else if((HOME_KEY_MIN < x && x < HOME_KEY_MAX) && (!key_status || key_status == CYTTSP_HOME_KEY))
{
key_status = CYTTSP_HOME_KEY;
input_report_key(ts->input, KEY_HOMEPAGE, CYTTSP_TOUCH);
dbg("Down TOUCH HOME\n");
input_sync(ts->input);
}
else if((BACK_KEY_MIN < x && x < BACK_KEY_MAX) && (!key_status || key_status == CYTTSP_BACK_KEY))
{
key_status = CYTTSP_BACK_KEY;
input_report_key(ts->input, KEY_BACK, CYTTSP_TOUCH);
dbg("Down TOUCH BACK\n");
input_sync(ts->input);
}
else if(!key_status)
key_status = CYTTSP_NULL_KEY;
}
}
if(key_relese && (curr_touches < prev_touches) && key_status)
{
if(key_status == CYTTSP_MENU_KEY)
input_report_key(ts->input, KEY_MENU, CYTTSP_NOTOUCH);
if(key_status == CYTTSP_HOME_KEY)
input_report_key(ts->input, KEY_HOMEPAGE, CYTTSP_NOTOUCH);
if(key_status == CYTTSP_BACK_KEY)
input_report_key(ts->input, KEY_BACK, CYTTSP_NOTOUCH);
if(key_status != CYTTSP_NULL_KEY)
input_sync(ts->input);
dbg("Up Key: %02x\n", key_status);
key_status = 0;
}
#endif
/* send no events if there were no previous touches and no new touches */
if ((prev_touches == CYTTSP_NOTOUCH) &&
((curr_touches == CYTTSP_NOTOUCH) || (curr_touches > CYTTSP_NUM_MT_TOUCH_ID))) {
cyttsp_debug("exit_xy_worker 3");
goto exit_xy_worker;
}
cyttsp_debug("prev=%d curr=%d\n", prev_touches, curr_touches);
dbg("cur#: %d, tch : 0x%x\n", curr_touches,tch);
dbg("touch12_id : 0x%x, touch34_id : 0x%x\n", g_xy_data.touch12_id,g_xy_data.touch34_id);
/* extract xy_data for all currently reported touches */
for (tch = 0; tch < curr_touches; tch++)
{
if (tch < 2)
{
id = (tch & 0x01) ?
GET_TOUCH2_ID(g_xy_data.touch12_id) : //LO_TRACKID(*(ts->tch_map[tch].id)) :
GET_TOUCH1_ID(g_xy_data.touch12_id); //HI_TRACKID(*(ts->tch_map[tch].id));
// touch_mask[id] = tch;
if (tch == 0)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x1);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y1);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z1;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
if (tch == 1)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x2);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y2);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z2;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
}
else
{
id = (tch & 0x01) ?
GET_TOUCH4_ID(g_xy_data.touch34_id) : //LO_TRACKID(*(ts->tch_map[tch].id)) :
GET_TOUCH3_ID(g_xy_data.touch34_id); //HI_TRACKID(*(ts->tch_map[tch].id));
if (tch == 2)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x3);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y3);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z3;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
if (tch == 3)
{
if(id < TOUCH_MAX_NUM){
cur_trk[id].tch = CYTTSP_TOUCH;
cur_trk[id].abs[CY_ABS_X_OST] = be16_to_cpu(g_xy_data.x4);
cur_trk[id].abs[CY_ABS_Y_OST] = be16_to_cpu(g_xy_data.y4);
cur_trk[id].abs[CY_ABS_P_OST] = g_xy_data.z4;
cur_trk[id].abs[CY_ABS_W_OST] = CYTTSP_SMALL_TOOL_WIDTH;
cur_trk[id].abs[CY_ABS_ID_OST] = id;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
}
}
if(id < TOUCH_MAX_NUM){
touch_mask[id] = tch;
}else{
if(Touch_Dbg_Enable)
printk("over Max touch ID id#: %d !!!\n", id);
}
dbg("tch#: %d, ID: %d, Xpos: %d, Ypos: %d\n",
tch, id, cur_trk[id].abs[CY_ABS_X_OST], cur_trk[id].abs[CY_ABS_Y_OST]);
}
// Release Event
if ( curr_touches == 0 )
{
dbg("Touch Released\n");
for (i=0; i < TOUCH_MAX_NUM; i++)
{
if (cur_touchflag[i] /*cur_trk[i].abs[CY_ABS_ID_OST] >= 0*/)
{
cur_trk[i].abs[CY_ABS_ID_OST] = -1;
cur_touchflag[i] = 0;
input_mt_slot(ts->input, i);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
dbg("Touch Released 1, I : %d\n",i);
}
}
}
// Finger Touched
else
{
dbg("Touch Pressed\n");
for (i=0; i<TOUCH_MAX_NUM; i++)
{
if ( touch_mask[i] < 0 ) // 1 case - the 1st finger : touched / the 2nd finger : released
{
#if 1
if ( cur_trk[i].abs[CY_ABS_ID_OST] >= 0 )
{
cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]] = 0;
cur_trk[i].abs[CY_ABS_ID_OST] = -1;
input_mt_slot(ts->input, i);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
dbg("Touch Pressed 1\n");
}
#endif
}
else
{
if(touch_mask[i] >= 0) // if finger is touched
{
input_mt_slot(ts->input, i);
if ( (cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]] == 0) )
{
dbg("Touch Pressed 2-1 I:%d, touchflag : %d\n",i,cur_touchflag[i]);
cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]] = 1;
//cur_trk[i].abs[CY_ABS_ID_OST] = input_mt_new_trkid(ts->input);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
}
// Move Event
// input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[i].abs[CY_ABS_ID_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_X, cur_trk[i].abs[CY_ABS_X_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_Y, cur_trk[i].abs[CY_ABS_Y_OST]);
input_report_abs(ts->input, ABS_MT_PRESSURE, cur_trk[i].abs[CY_ABS_P_OST]);
input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, 1);
input_report_abs(ts->input, ABS_MT_WIDTH_MAJOR, cur_trk[i].abs[CY_ABS_P_OST]);
dbg("Touch Pressed 2-2 I:%d, touchflag : %d\n",i,cur_touchflag[cur_trk[i].abs[CY_ABS_ID_OST]]);
}
}
}
}
input_report_key(ts->input, BTN_TOUCH, (curr_touches>0)? 1:0 );
input_sync(ts->input);
// update previous touch num
prev_touches = curr_touches;
goto exit_xy_worker;
#if 0
/* provide input event signaling for each active touch */
for (id = 0, num_sent = 0; id < CYTTSP_NUM_TRACK_ID; id++)
{
if (cur_trk[id].tch)
{
t = cur_trk[id].abs[CY_ABS_ID_OST];
/* send 0 based track id's */
t -= 1;
input_report_abs(ts->input, ABS_MT_TRACKING_ID, t);
input_report_abs(ts->input, ABS_MT_POSITION_X, cur_trk[id].abs[CY_ABS_X_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_Y, cur_trk[id].abs[CY_ABS_Y_OST]);
input_report_abs(ts->input, ABS_MT_PRESSURE, cur_trk[id].abs[CY_ABS_P_OST]);
input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, cur_trk[id].abs[CY_ABS_W_OST]);
num_sent++;
input_mt_sync(ts->input);
ts->prv_trk[id] = cur_trk[id];
ts->prv_trk[id].abs[CY_ABS_ID_OST] = t;
#if 0
cyttsp_dbg(ts, CY_DBG_LVL_1, "%s: ID:%3d X:%3d Y:%3d " "Z:%3d W=%3d T=%3d\n", __func__, id,
cur_trk[id].abs[CY_ABS_X_OST],
cur_trk[id].abs[CY_ABS_Y_OST],
cur_trk[id].abs[CY_ABS_P_OST],
cur_trk[id].abs[CY_ABS_W_OST],
t);
#endif
}
else if ((ABS_MT_PRESSURE == ABS_MT_TOUCH_MAJOR) && ts->prv_trk[id].tch)
{
/*
* pre-Gingerbread:
* need to report last position with
* and report that position with
* no touch if the touch lifts off
*/
input_report_abs(ts->input, ABS_MT_TRACKING_ID, ts->prv_trk[id].abs[CY_ABS_ID_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_X, ts->prv_trk[id].abs[CY_ABS_X_OST]);
input_report_abs(ts->input, ABS_MT_POSITION_Y, ts->prv_trk[id].abs[CY_ABS_Y_OST]);
input_report_abs(ts->input, ABS_MT_PRESSURE, CYTTSP_NOTOUCH);
input_report_abs(ts->input, ABS_MT_TOUCH_MAJOR, CYTTSP_NOTOUCH);
num_sent++;
input_mt_sync(ts->input);
ts->prv_trk[id].tch = CYTTSP_NOTOUCH;
#if 0
cyttsp_dbg(ts, CY_DBG_LVL_1,
"%s: ID:%3d X:%3d Y:%3d "
"Z:%3d W=%3d T=%3d liftoff\n",
__func__, ts->prv_trk[id].abs[CY_ABS_ID_OST],
ts->prv_trk[id].abs[CY_ABS_X_OST],
ts->prv_trk[id].abs[CY_ABS_Y_OST],
CYTTSP_NOTOUCH,
CYTTSP_NOTOUCH,
ts->prv_trk[id].abs[CY_ABS_ID_OST]);
#endif
}
}
if (num_sent == 0)
{
/* in case of 0-touch; all liftoff; Gingerbread+ */
input_mt_sync(ts->input);
}
input_sync(ts->input);
// update previous touch num
prev_touches = curr_touches;
goto exit_xy_worker;
#endif
exit_xy_worker:
/*if(cyttsp_disable_touch) {
cyttsp_debug("Not enabling touch\n");
}
else*/ { // N1037 20120521 for ICS cyttsp_disable_touch ¼³Á¤µÇ¸é¼ touch¿Àµ¿ÀÛ ¹ß»ý ICS org¿¡¼ »ç¿ëµÇÁö ¾Ê´Â ÄÚµå ÀÓ
if(ts->client->irq == 0) {
/* restart event timer */
mod_timer(&ts->timer, jiffies + TOUCHSCREEN_TIMEOUT);
}
else {
/* re-enable the interrupt after processing */
enable_irq(ts->client->irq);
}
}
return;
}
#if 0
static int cyttsp_inlist(u16 prev_track[], u8 curr_track_id, u8 *prev_loc, u8 num_touches)
{
u8 id =0;
*prev_loc = CYTTSP_IGNORE_TOUCH;
cyttsp_xdebug("IN p[%d]=%d c=%d n=%d loc=%d\n", \
id, prev_track[id], curr_track_id, num_touches, *prev_loc);
for (id = 0, *prev_loc = CYTTSP_IGNORE_TOUCH;
(id < num_touches); id++) {
cyttsp_xdebug("p[%d]=%d c=%d n=%d loc=%d\n", \
id, prev_track[id], curr_track_id, num_touches, *prev_loc);
if (prev_track[id] == curr_track_id) {
*prev_loc = id;
break;
}
}
cyttsp_xdebug("OUT p[%d]=%d c=%d n=%d loc=%d\n", \
id, prev_track[id], curr_track_id, num_touches, *prev_loc);
return ((*prev_loc < CYTTSP_NUM_TRACK_ID) ? true : false);
}
static int cyttsp_next_avail_inlist(u16 curr_track[], u8 *new_loc, u8 num_touches)
{
u8 id;
for (id = 0, *new_loc = CYTTSP_IGNORE_TOUCH;
(id < num_touches); id++) {
if (curr_track[id] > CYTTSP_NUM_TRACK_ID) {
*new_loc = id;
break;
}
}
return ((*new_loc < CYTTSP_NUM_TRACK_ID) ? true : false);
}
#endif
/* Timer function used as dummy interrupt driver */
static void cyttsp_timer(unsigned long handle)
{
struct cyttsp *ts = (struct cyttsp *) handle;
cyttsp_xdebug("TTSP Device timer event\n");
#ifdef FEATURE_CYTTSP_HEARTBEAT
/* schedule motion signal handling */
if(start_heartbeat_timer)
{
schedule_work(&ts->work2);
mod_timer(&ts->timer, jiffies + CYTTSP_HEARTBEAT_TIME * HZ);
}
#else
/* schedule motion signal handling */
schedule_work(&ts->work);
#endif
return;
}
/* ************************************************************************
* ISR function. This function is general, initialized in drivers init
* function
* ************************************************************************ */
static irqreturn_t cyttsp_irq(int irq, void *handle)
{
struct cyttsp *ts = (struct cyttsp *) handle;
cyttsp_xdebug("%s: Got IRQ\n", CYTTSP_I2C_NAME);
if(Touch_Status >= TOUCH_POWEROFF)
return IRQ_HANDLED;
/* disable further interrupts until this interrupt is processed */
disable_irq_nosync(ts->client->irq);
/* schedule motion signal handling */
schedule_work(&ts->work);
return IRQ_HANDLED;
}
#ifdef CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
/* ************************************************************************
* Probe initialization functions
* ************************************************************************ */
static int cyttsp_putbl(struct cyttsp *ts, int show, int show_status, int show_version, int show_cid)
{
int retval = CYTTSP_OPERATIONAL;
int num_bytes = (show_status * 3) + (show_version * 6) + (show_cid * 3);
if (show_cid) {
num_bytes = sizeof(struct cyttsp_bootloader_data_t);
}
else if (show_version) {
num_bytes = sizeof(struct cyttsp_bootloader_data_t) - 3;
}
else {
num_bytes = sizeof(struct cyttsp_bootloader_data_t) - 9;
}
if (show) {
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_BASE,
num_bytes, (u8 *)&g_bl_data);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
if (show_status) {
cyttsp_debug("BL%d: f=%02X s=%02X err=%02X bl=%02X%02X bld=%02X%02X\n", \
show, \
g_bl_data.bl_file, g_bl_data.bl_status, g_bl_data.bl_error, \
g_bl_data.blver_hi, g_bl_data.blver_lo, \
g_bl_data.bld_blver_hi, g_bl_data.bld_blver_lo);
}
if (show_version) {
cyttsp_debug("BL%d: ttspver=0x%02X%02X appid=0x%02X%02X appver=0x%02X%02X\n", \
show, \
g_bl_data.ttspver_hi, g_bl_data.ttspver_lo, \
g_bl_data.appid_hi, g_bl_data.appid_lo, \
g_bl_data.appver_hi, g_bl_data.appver_lo);
}
if (show_cid) {
cyttsp_debug("BL%d: cid=0x%02X%02X%02X\n", \
show, \
g_bl_data.cid_0, g_bl_data.cid_1, g_bl_data.cid_2);
}
mdelay(CYTTSP_DELAY_DFLT);
}
return retval;
}
#endif //CYTTSP_INCLUDE_LOAD_FILE //[BIH] ICS port...
#ifdef CYTTSP_INCLUDE_LOAD_FILE
#define CYTTSP_MAX_I2C_LEN 256
#define CYTTSP_MAX_TRY 10
#define CYTTSP_BL_PAGE_SIZE 16
#define CYTTSP_BL_NUM_PAGES 5
static int cyttsp_i2c_write_block_data(struct i2c_client *client, u8 command,
u8 length, const u8 *values)
{
int retval = CYTTSP_OPERATIONAL;
u8 dataray[CYTTSP_MAX_I2C_LEN];
u8 try;
dataray[0] = command;
if (length) {
memcpy(&dataray[1], values, length);
}
try = CYTTSP_MAX_TRY;
do {
retval = i2c_master_send(client, dataray, length+1);
mdelay(CYTTSP_DELAY_DFLT*2);
}
while ((retval != length+1) && try--);
return retval;
}
static int cyttsp_i2c_write_block_data_chunks(struct cyttsp *ts, u8 command,
u8 length, const u8 *values)
{
int retval = CYTTSP_OPERATIONAL;
int block = 1;
u8 dataray[CYTTSP_MAX_I2C_LEN];
/* first page already includes the bl page offset */
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
CYTTSP_BL_PAGE_SIZE+1, values);
mdelay(10);
values += CYTTSP_BL_PAGE_SIZE+1;
length -= CYTTSP_BL_PAGE_SIZE+1;
/* rem blocks require bl page offset stuffing */
while (length && (block < CYTTSP_BL_NUM_PAGES) && !(retval < CYTTSP_OPERATIONAL)) {
dataray[0] = CYTTSP_BL_PAGE_SIZE*block;
memcpy(&dataray[1], values,
length >= CYTTSP_BL_PAGE_SIZE ? CYTTSP_BL_PAGE_SIZE : length);
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
length >= CYTTSP_BL_PAGE_SIZE ? CYTTSP_BL_PAGE_SIZE+1 : length+1, dataray);
mdelay(10);
values += CYTTSP_BL_PAGE_SIZE;
length = length >= CYTTSP_BL_PAGE_SIZE ? length - CYTTSP_BL_PAGE_SIZE : 0;
block++;
}
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
return retval;
}
static int cyttsp_bootload_app(struct cyttsp *ts)
{
int retval = CYTTSP_OPERATIONAL;
int i, tries;
u8 host_reg;
cyttsp_debug("load new firmware \n");
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
/* reset TTSP Device back to bootloader mode */
host_reg = CYTTSP_SOFT_RESET_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete reset back to bootloader */
// mdelay(CYTTSP_DELAY_DFLT);
mdelay(1000);
cyttsp_putbl(ts,3, true, true, true);
cyttsp_debug("load file -- tts_ver=0x%02X%02X app_id=0x%02X%02X app_ver=0x%02X%02X\n", \
cyttsp_fw_tts_verh, cyttsp_fw_tts_verl, \
cyttsp_fw_app_idh, cyttsp_fw_app_idl, \
cyttsp_fw_app_verh, cyttsp_fw_app_verl);
/* download new TTSP Application to the Bootloader
*
*/
if (!(retval < CYTTSP_OPERATIONAL)) {
i = 0;
/* send bootload initiation command */
if (cyttsp_fw[i].Command == CYTTSP_BL_INIT_LOAD) {
g_bl_data.bl_file = 0;
g_bl_data.bl_status = 0;
g_bl_data.bl_error = 0;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
cyttsp_fw[i].Length, cyttsp_fw[i].Block);
/* delay to allow bootloader to get ready for block writes */
i++;
tries = 0;
cyttsp_debug("wait init f=%02X, s=%02X, e=%02X t=%d\n",g_bl_data.bl_file,
g_bl_data.bl_status, g_bl_data.bl_error, tries);
do {
mdelay(1000);
cyttsp_putbl(ts,4, true, false, false);
}
while (g_bl_data.bl_status != 0x10 &&
g_bl_data.bl_status != 0x11 &&
tries++ < 10);
/* send bootload firmware load blocks -
* kernel limits transfers to I2C_SMBUS_BLOCK_MAX(32) bytes
*/
if (!(retval < CYTTSP_OPERATIONAL)) {
while (cyttsp_fw[i].Command == CYTTSP_BL_WRITE_BLK) {
retval = cyttsp_i2c_write_block_data_chunks(ts,
CYTTSP_REG_BASE,
cyttsp_fw[i].Length, cyttsp_fw[i].Block);
// if (cyttsp_fw[i].Address & 0x01) {
// mdelay(CYTTSP_DELAY_DNLOAD);
// }
// else {
// mdelay(CYTTSP_DELAY_DNLOAD);
// }
/* bootloader requires delay after odd block addresses */
mdelay(100);
cyttsp_debug("BL DNLD Rec=% 3d Len=% 3d Addr=%04X\n",
cyttsp_fw[i].Record, cyttsp_fw[i].Length,
cyttsp_fw[i].Address);
i++;
if (retval < CYTTSP_OPERATIONAL) {
cyttsp_debug("BL fail Rec=%3d retval=%d\n",cyttsp_fw[i-1].Record, retval);
break;
}
else {
/* reset TTSP I2C counter */
retval = cyttsp_i2c_write_block_data(ts->client,
CYTTSP_REG_BASE,
0, NULL);
mdelay(10);
/* set arg2 to non-0 to activate */
cyttsp_putbl(ts,5, true, false, false);
}
}
if (!(retval < CYTTSP_OPERATIONAL)) {
while (i < cyttsp_fw_records) {
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
cyttsp_fw[i].Length, cyttsp_fw[i].Block);
i++;
tries = 0;
cyttsp_debug("wait init f=%02X, s=%02X, e=%02X t=%d\n",g_bl_data.bl_file,
g_bl_data.bl_status, g_bl_data.bl_error, tries);
do {
mdelay(1000);
cyttsp_putbl(ts,6, true, false, false);
}
while (g_bl_data.bl_status != 0x10 &&
g_bl_data.bl_status != 0x11 &&
tries++ < 10);
cyttsp_putbl(ts,7, true, false, false);
if (retval < CYTTSP_OPERATIONAL) {
break;
}
}
}
}
}
}
/* Do we need to reset TTSP Device back to bootloader mode?? */
/*
*/
host_reg = CYTTSP_SOFT_RESET_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete reset back to bootloader */
/*
*/
mdelay(1000);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
/* set arg2 to non-0 to activate */
retval = cyttsp_putbl(ts, 8, true, true, true);
return retval;
}
#else
#if 0
static int cyttsp_bootload_app(struct cyttsp *ts)
{
cyttsp_debug("no-load new firmware \n");
return CYTTSP_OPERATIONAL;
}
#endif
#endif /* CYTTSP_INCLUDE_LOAD_FILE */
#if 0
static int cyttsp_power_on(struct cyttsp *ts)
{
int retval = CYTTSP_OPERATIONAL;
u8 host_reg;
int tries;
static u8 bl_cmd[] = {
CYTTSP_BL_FILE0, CYTTSP_BL_CMD, CYTTSP_BL_EXIT,
CYTTSP_BL_KEY0, CYTTSP_BL_KEY1, CYTTSP_BL_KEY2,
CYTTSP_BL_KEY3, CYTTSP_BL_KEY4, CYTTSP_BL_KEY5,
CYTTSP_BL_KEY6, CYTTSP_BL_KEY7};
cyttsp_debug("Power up \n");
/* check if the TTSP device has a bootloader installed */
host_reg = CYTTSP_SOFT_RESET_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
tries = 0;
do {
mdelay(1000);
/* set arg2 to non-0 to activate */
retval = cyttsp_putbl(ts, 1, true, true, true);
cyttsp_info("BL%d: f=%02X s=%02X err=%02X bl=%02X%02X bld=%02X%02X R=%d\n", \
101, \
g_bl_data.bl_file, g_bl_data.bl_status, g_bl_data.bl_error, \
g_bl_data.blver_hi, g_bl_data.blver_lo, \
g_bl_data.bld_blver_hi, g_bl_data.bld_blver_lo,
retval);
cyttsp_info("BL%d: tver=%02X%02X a_id=%02X%02X aver=%02X%02X\n", \
102, \
g_bl_data.ttspver_hi, g_bl_data.ttspver_lo, \
g_bl_data.appid_hi, g_bl_data.appid_lo, \
g_bl_data.appver_hi, g_bl_data.appver_lo);
cyttsp_info("BL%d: c_id=%02X%02X%02X\n", \
103, \
g_bl_data.cid_0, g_bl_data.cid_1, g_bl_data.cid_2);
}
while (!(retval < CYTTSP_OPERATIONAL) &&
!GET_BOOTLOADERMODE(g_bl_data.bl_status) &&
!(g_bl_data.bl_file == CYTTSP_OPERATE_MODE + CYTTSP_LOW_POWER_MODE) &&
tries++ < 10);
/* is bootloader missing? */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_xdebug("Retval=%d Check if bootloader is missing...\n", retval);
if (!GET_BOOTLOADERMODE(g_bl_data.bl_status)) {
/* skip all bootloader and sys info and go straight to operational mode */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_xdebug("Bootloader is missing (retval = %d)\n", retval);
host_reg = CYTTSP_OPERATE_MODE/* + CYTTSP_LOW_POWER_MODE*/;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete switch to Operational mode */
mdelay(1000);
goto bypass;
}
}
}
/* take TTSP out of bootloader mode; go to TrueTouch operational mode */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_xdebug1("exit bootloader; go operational\n");
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(bl_cmd), bl_cmd);
tries = 0;
do {
mdelay(1000);
cyttsp_putbl(ts,4, true, false, false);
cyttsp_info("BL%d: f=%02X s=%02X err=%02X bl=%02X%02X bld=%02X%02X\n", \
104, \
g_bl_data.bl_file, g_bl_data.bl_status, g_bl_data.bl_error, \
g_bl_data.blver_hi, g_bl_data.blver_lo, \
g_bl_data.bld_blver_hi, g_bl_data.bld_blver_lo);
}
while (GET_BOOTLOADERMODE(g_bl_data.bl_status) &&
tries++ < 10);
}
if (!(retval < CYTTSP_OPERATIONAL) &&
cyttsp_app_load()) {
mdelay(1000);
if (CYTTSP_DIFF(g_bl_data.ttspver_hi, cyttsp_tts_verh()) ||
CYTTSP_DIFF(g_bl_data.ttspver_lo, cyttsp_tts_verl()) ||
CYTTSP_DIFF(g_bl_data.appid_hi, cyttsp_app_idh()) ||
CYTTSP_DIFF(g_bl_data.appid_lo, cyttsp_app_idl()) ||
CYTTSP_DIFF(g_bl_data.appver_hi, cyttsp_app_verh()) ||
CYTTSP_DIFF(g_bl_data.appver_lo, cyttsp_app_verl()) ||
CYTTSP_DIFF(g_bl_data.cid_0, cyttsp_cid_0()) ||
CYTTSP_DIFF(g_bl_data.cid_1, cyttsp_cid_1()) ||
CYTTSP_DIFF(g_bl_data.cid_2, cyttsp_cid_2()) ||
cyttsp_force_fw_load()) {
cyttsp_debug("blttsp=0x%02X%02X flttsp=0x%02X%02X force=%d\n", \
g_bl_data.ttspver_hi, g_bl_data.ttspver_lo, \
cyttsp_tts_verh(), cyttsp_tts_verl(), cyttsp_force_fw_load());
cyttsp_debug("blappid=0x%02X%02X flappid=0x%02X%02X\n", \
g_bl_data.appid_hi, g_bl_data.appid_lo, \
cyttsp_app_idh(), cyttsp_app_idl());
cyttsp_debug("blappver=0x%02X%02X flappver=0x%02X%02X\n", \
g_bl_data.appver_hi, g_bl_data.appver_lo, \
cyttsp_app_verh(), cyttsp_app_verl());
cyttsp_debug("blcid=0x%02X%02X%02X flcid=0x%02X%02X%02X\n", \
g_bl_data.cid_0, g_bl_data.cid_1, g_bl_data.cid_2, \
cyttsp_cid_0(), cyttsp_cid_1(), cyttsp_cid_2());
/* enter bootloader to load new app into TTSP Device */
retval = cyttsp_bootload_app(ts);
/* take TTSP device out of bootloader mode; switch back to TrueTouch operational mode */
if (!(retval < CYTTSP_OPERATIONAL)) {
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(bl_cmd), bl_cmd);
/* wait for TTSP Device to complete switch to Operational mode */
mdelay(1000);
}
}
}
bypass:
/* switch to System Information mode to read versions and set interval registers */
if (!(retval < CYTTSP_OPERATIONAL)) {
cyttsp_debug("switch to sysinfo mode \n");
host_reg = CYTTSP_SYSINFO_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete switch to SysInfo mode */
mdelay(1000);
if (!(retval < CYTTSP_OPERATIONAL)) {
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(struct cyttsp_sysinfo_data_t), (u8 *)&g_sysinfo_data);
cyttsp_debug("SI2: hst_mode=0x%02X mfg_cmd=0x%02X mfg_stat=0x%02X\n", \
g_sysinfo_data.hst_mode, g_sysinfo_data.mfg_cmd, \
g_sysinfo_data.mfg_stat);
cyttsp_debug("SI2: bl_ver=0x%02X%02X\n", \
g_sysinfo_data.bl_verh, g_sysinfo_data.bl_verl);
cyttsp_debug("SI2: sysinfo act_int=0x%02X tch_tmout=0x%02X lp_int=0x%02X\n", \
g_sysinfo_data.act_intrvl, g_sysinfo_data.tch_tmout, \
g_sysinfo_data.lp_intrvl);
cyttsp_info("SI%d: tver=%02X%02X a_id=%02X%02X aver=%02X%02X\n", \
102, \
g_sysinfo_data.tts_verh, g_sysinfo_data.tts_verl, \
g_sysinfo_data.app_idh, g_sysinfo_data.app_idl, \
g_sysinfo_data.app_verh, g_sysinfo_data.app_verl);
cyttsp_info("SI%d: c_id=%02X%02X%02X\n", \
103, \
g_sysinfo_data.cid[0], g_sysinfo_data.cid[1], g_sysinfo_data.cid[2]);
if (!(retval < CYTTSP_OPERATIONAL) &&
(CYTTSP_DIFF(ts->platform_data->act_intrvl, CYTTSP_ACT_INTRVL_DFLT) ||
CYTTSP_DIFF(ts->platform_data->tch_tmout, CYTTSP_TCH_TMOUT_DFLT) ||
CYTTSP_DIFF(ts->platform_data->lp_intrvl, CYTTSP_LP_INTRVL_DFLT))) {
if (!(retval < CYTTSP_OPERATIONAL)) {
u8 intrvl_ray[sizeof(ts->platform_data->act_intrvl) +
sizeof(ts->platform_data->tch_tmout) +
sizeof(ts->platform_data->lp_intrvl)];
u8 i = 0;
intrvl_ray[i++] = ts->platform_data->act_intrvl;
intrvl_ray[i++] = ts->platform_data->tch_tmout;
intrvl_ray[i++] = ts->platform_data->lp_intrvl;
cyttsp_debug("SI2: platinfo act_intrvl=0x%02X tch_tmout=0x%02X lp_intrvl=0x%02X\n", \
ts->platform_data->act_intrvl, ts->platform_data->tch_tmout, \
ts->platform_data->lp_intrvl);
// set intrvl registers
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_ACT_INTRVL,
sizeof(intrvl_ray), intrvl_ray);
mdelay(CYTTSP_DELAY_SYSINFO);
}
}
}
/* switch back to Operational mode */
cyttsp_debug("switch back to operational mode \n");
if (!(retval < CYTTSP_OPERATIONAL)) {
host_reg = CYTTSP_OPERATE_MODE/* + CYTTSP_LOW_POWER_MODE*/;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE,
sizeof(host_reg), &host_reg);
/* wait for TTSP Device to complete switch to Operational mode */
mdelay(1000);
}
}
/* init gesture setup;
* this is required even if not using gestures
* in order to set the active distance */
if (!(retval < CYTTSP_OPERATIONAL)) {
u8 gesture_setup;
cyttsp_debug("init gesture setup \n");
gesture_setup = ts->platform_data->gest_set;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_GEST_SET,
sizeof(gesture_setup), &gesture_setup);
mdelay(CYTTSP_DELAY_DFLT);
}
if (!(retval < CYTTSP_OPERATIONAL)) {
ts->platform_data->power_state = CYTTSP_ACTIVE_STATE;
}
else {
ts->platform_data->power_state = CYTTSP_IDLE_STATE;
}
cyttsp_debug("Retval=%d Power state is %s\n", retval, (ts->platform_data->power_state == CYTTSP_ACTIVE_STATE) ? "ACTIVE" : "IDLE");
return retval;
}
#endif
/* cyttsp_initialize: Driver Initialization. This function takes
* care of the following tasks:
* 1. Create and register an input device with input layer
* 2. Take CYTTSP device out of bootloader mode; go operational
* 3. Start any timers/Work queues. */
static int cyttsp_initialize(struct i2c_client *client, struct cyttsp *ts)
{
struct input_dev *input_device;
int error = 0;
int retval = CYTTSP_OPERATIONAL;
u8 id;
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
cyttsp_data = ts;
#endif
/* Create the input device and register it. */
input_device = input_allocate_device();
if (!input_device) {
error = -ENOMEM;
cyttsp_xdebug1("err input allocate device\n");
goto error_free_device;
}
if (!client) {
error = ~ENODEV;
cyttsp_xdebug1("err client is Null\n");
goto error_free_device;
}
if (!ts) {
error = ~ENODEV;
cyttsp_xdebug1("err context is Null\n");
goto error_free_device;
}
ts->input = input_device;
input_device->name = CYTTSP_I2C_NAME;
input_device->phys = ts->phys;
input_device->dev.parent = &client->dev;
set_bit(EV_SYN, input_device->evbit);
set_bit(EV_KEY, input_device->evbit);
set_bit(EV_ABS, input_device->evbit);
set_bit(BTN_TOUCH, input_device->keybit);
//set_bit(BTN_2, input_device->keybit); // N1037 20120321 fix
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
// +++ FEATURE_P_VZW_PS_STABILITY_AT_CMD
set_bit(KEY_MENU, input_device->keybit);
set_bit(KEY_BACK, input_device->keybit);
set_bit(KEY_POWER, input_device->keybit);
set_bit(KEY_HOMEPAGE, input_device->keybit);
// ---
set_bit(KEY_SEARCH, input_device->keybit);
set_bit(KEY_0, input_device->keybit);
set_bit(KEY_1, input_device->keybit);
set_bit(KEY_2, input_device->keybit);
set_bit(KEY_3, input_device->keybit);
set_bit(KEY_4, input_device->keybit);
set_bit(KEY_5, input_device->keybit);
set_bit(KEY_6, input_device->keybit);
set_bit(KEY_7, input_device->keybit);
set_bit(KEY_8, input_device->keybit);
set_bit(KEY_9, input_device->keybit);
set_bit(0xe3, input_device->keybit); /* '*' */
set_bit(0xe4, input_device->keybit); /* '#' */
set_bit(KEY_LEFTSHIFT, input_device->keybit);
set_bit(KEY_RIGHTSHIFT, input_device->keybit);
set_bit(KEY_LEFT, input_device->keybit);
set_bit(KEY_RIGHT, input_device->keybit);
set_bit(KEY_UP, input_device->keybit);
set_bit(KEY_DOWN, input_device->keybit);
set_bit(KEY_ENTER, input_device->keybit);
set_bit(KEY_SEND, input_device->keybit);
set_bit(KEY_END, input_device->keybit);
set_bit(KEY_VOLUMEUP, input_device->keybit);
set_bit(KEY_VOLUMEDOWN, input_device->keybit);
set_bit(KEY_CLEAR, input_device->keybit);
set_bit(KEY_CAMERA, input_device->keybit);
set_bit(KEY_DELETE, input_device->keybit);
set_bit(KEY_WWW, input_device->keybit);
#endif // FEATURE_SKY_PROCESS_CMD_KEY
// for ICS version - 0511 KJHW
/* clear current touch tracking structures */
memset(cur_trk, 0, sizeof(cur_trk));
for (id = 0; id < TOUCH_MAX_NUM; id++)
{
cur_trk[id].abs[CY_ABS_ID_OST] = -1;
cur_touchflag[id] = 0;
}
input_mt_init_slots(input_device, TOUCH_MAX_NUM);
if (ts->platform_data->use_gestures) {
set_bit(BTN_3, input_device->keybit);
}
input_set_abs_params(input_device, ABS_X, 0, ts->platform_data->maxx, 0, 0);
input_set_abs_params(input_device, ABS_Y, 0, ts->platform_data->maxy, 0, 0);
input_set_abs_params(input_device, ABS_TOOL_WIDTH, 0, CYTTSP_LARGE_TOOL_WIDTH, 0 ,0);
input_set_abs_params(input_device, ABS_PRESSURE, 0, CYTTSP_MAXZ, 0, 0);
input_set_abs_params(input_device, ABS_HAT0X, 0, ts->platform_data->maxx, 0, 0);
input_set_abs_params(input_device, ABS_HAT0Y, 0, ts->platform_data->maxy, 0, 0);
if (ts->platform_data->use_gestures) {
input_set_abs_params(input_device, ABS_HAT1X, 0, CYTTSP_MAXZ, 0, 0);
input_set_abs_params(input_device, ABS_HAT1Y, 0, CYTTSP_MAXZ, 0, 0);
}
if (ts->platform_data->use_mt) {
input_set_abs_params(input_device, ABS_MT_POSITION_X, 0, ts->platform_data->maxx, 0, 0);
input_set_abs_params(input_device, ABS_MT_POSITION_Y, 0, ts->platform_data->maxy, 0, 0);
input_set_abs_params(input_device, ABS_MT_TOUCH_MAJOR, 0, CYTTSP_MAXZ, 0, 0);
input_set_abs_params(input_device, ABS_MT_WIDTH_MAJOR, 0, CYTTSP_LARGE_TOOL_WIDTH, 0, 0);
if (ts->platform_data->use_trk_id) {
input_set_abs_params(input_device, ABS_MT_TRACKING_ID, 0, CYTTSP_NUM_TRACK_ID, 0, 0);
}
}
// +++ FEATURE_P_VZW_PS_STABILITY_AT_CMD
input_set_abs_params(input_device, ABS_MT_TOOL_TYPE, 0, 1, 0, 0);
// ---
cyttsp_info("%s: Register input device\n", CYTTSP_I2C_NAME);
error = input_register_device(input_device);
if (error) {
cyttsp_alert("%s: Failed to register input device\n", CYTTSP_I2C_NAME);
retval = error;
goto error_free_device;
}
else
cyttsp_info("%s: Register input device success...\n", CYTTSP_I2C_NAME);
/* Prepare our worker structure prior to setting up the timer/ISR */
INIT_WORK(&ts->work,cyttsp_xy_worker);
#ifdef FEATURE_CYTTSP_HEARTBEAT
INIT_WORK(&ts->work2,cyttsp_check_heartbeat);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
//INIT_WORK(&ts->work3,check_firmware_update); // N1037 20120312 for ICS
INIT_DELAYED_WORK(&ts->work3,check_firmware_update);
#endif
/* Power on the chip and make sure that I/Os are set as specified
* in the platform
*/
#if 0 //Cypress ¾÷ü ¿äû»çÇ×.
retval = cyttsp_power_on(ts);
if (retval < 0) {
goto error_free_device;
}
#endif
/* Timer or Interrupt setup */
if(ts->client->irq == 0) {
cyttsp_info("Setting up timer\n");
setup_timer(&ts->timer, cyttsp_timer, (unsigned long) ts);
mod_timer(&ts->timer, jiffies + TOUCHSCREEN_TIMEOUT);
}
else {
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = true;
setup_timer(&ts->timer, cyttsp_timer, (unsigned long) ts);
mod_timer(&ts->timer, jiffies + CYTTSP_HEARTBEAT_TIME * 20 * HZ); //óÀ½ ½ÃÀÛÀº 60ÃÊ µÚ¿¡ ŸÀÌ¸Ó µ¹°Ô ÇÔ ºÎÆÃ½Ã°£¿¡ ¿µÇâÀ» ÁÖÁö ¾Ê±â À§ÇÔ.
#endif
cyttsp_info("Setting up interrupt\n");
/* request_irq() will also call enable_irq() */
error = request_irq (client->irq,cyttsp_irq,IRQF_TRIGGER_FALLING,
client->dev.driver->name,ts);
if (error) {
cyttsp_alert("error: could not request irq\n");
retval = error;
goto error_free_irq;
}
}
atomic_set(&ts->irq_enabled, 1);
retval = device_create_file(&ts->client->dev, &dev_attr_irq_enable);
if (retval < CYTTSP_OPERATIONAL) {
cyttsp_alert("File device creation failed: %d\n", retval);
retval = -ENODEV;
goto error_free_irq;
}
cyttsp_info("%s: Successful registration\n", CYTTSP_I2C_NAME);
goto success;
error_free_irq:
cyttsp_alert("Error: Failed to register IRQ handler\n");
free_irq(client->irq,ts);
error_free_device:
if (input_device) {
input_free_device(input_device);
}
success:
return retval;
}
static int pantech_auto_check(u8* return_byte)
{
u8 host_reg, byte_data[4], prev_data=0xff, byte_node1[MAX_NODE], byte_node2[MAX_NODE], send_byte[MAX_NODE];
int retval = CYTTSP_OPERATIONAL, retry_cnt = 100, i;
struct cyttsp *ts = ts_temp;
dbg("pantech_auto_check!! start\n");
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
return -1;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
// Enter Test Mode
host_reg = CYTTSP_TEST_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
msleep(100);
// Read Raw counts or baseline
byte_data[0] = 0x00;
do {
/* Read Count */
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_MODE , sizeof(byte_data), (u8 *)&byte_data);
msleep(10);
}
while (byte_data[0] == prev_data && --retry_cnt);
prev_data = byte_data[0];
do {
/* Read Count
Must set a i2c.h I2C_SMBUS_BLOCK_MAX 32 -> I2C_SMBUS_BLOCK_MAX 256
*/
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_SENSOR_BASE , sizeof(byte_node1), (u8 *)&byte_node1);
msleep(10);
}
while (retval < CYTTSP_OPERATIONAL && --retry_cnt);
// Read Raw counts or baseline
host_reg = CYTTSP_T_TEST_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
msleep(100);
byte_data[0] = 0x00;
retry_cnt = 100;
do {
/* Read Count */
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_MODE , sizeof(byte_data), (u8 *)&byte_data);
msleep(10);
}
while (byte_data[0] == prev_data && --retry_cnt);
prev_data = byte_data[0];
do {
/* Read Count */
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_SENSOR_BASE , sizeof(byte_node2), (u8 *)&byte_node2);
msleep(10);
}
while (retval < CYTTSP_OPERATIONAL && --retry_cnt);
for(i=0; i<MAX_NODE; i++)
{
if(byte_node1[i] >= CYTTSP_BASE_MIN && byte_node1[i] <= CYTTSP_BASE_MAX &&
byte_node2[i] >= CYTTSP_BASE_MIN && byte_node2[i] <= CYTTSP_BASE_MAX)
send_byte[i] = 0;
else
send_byte[i] = 1;
// printk("Check Valid %d, byte_node1 %d, byte_node2 %d : %d\n", i , byte_node1[i], byte_node2[i], send_byte[i]);
}
// Retrun Operate Mode
host_reg = CYTTSP_OPERATE_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
msleep(100);
dbg("pantech_auto_check!! end\n");
for(i=0;i<MAX_NODE;i++)
return_byte[i]=send_byte[i];
return 0;
}
static int pantech_selftest_check(void)
{
u8 host_reg, byte_data[2];
int retval = CYTTSP_OPERATIONAL;
struct cyttsp *ts = ts_temp;
printk("pantech_selftest_check!! start\n");
// If phone enter a poweroff, Stop firmware update
if(Touch_Status >= TOUCH_POWEROFF)
return -1;
#ifdef CYTTSP_MUTEX_LOCK
mutex_lock(&ts->lock_mutex);
#endif
// Enter system information Mode
host_reg = CYTTSP_SYSINFO_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
msleep(100);
// Start self test
host_reg = 0x01;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_SELF_TEST, sizeof(host_reg), &host_reg);
msleep(1000);
// Read test result
retval = i2c_smbus_read_i2c_block_data(ts->client, CYTTSP_REG_SELF_TEST , sizeof(byte_data), (u8 *)&byte_data);
printk("0x18 test: %02x, 0x19 test: %02x\n", byte_data[0], byte_data[1]);
// Retrun Operate Mode
host_reg = CYTTSP_OPERATE_MODE;
retval = i2c_smbus_write_i2c_block_data(ts->client, CYTTSP_REG_BASE, sizeof(host_reg), &host_reg);
#ifdef CYTTSP_MUTEX_LOCK
mutex_unlock(&ts->lock_mutex);
#endif
msleep(100);
printk("pantech_selftest_check!! end\n");
if(byte_data[0] != 0)
return CYTTSP_BIST_PROCESS;
else if(byte_data[1] != 0xff)
{
if(!(byte_data[1] & 0x01))
return CYTTSP_OPEN_TEST;
else if(!(byte_data[1] & 0x02))
return CYTTSP_SHORT_GND;
else if(!(byte_data[1] & 0x04))
return CYTTSP_SHORT_VDD;
else if(!(byte_data[1] & 0x08))
return CYTTSP_SHORT_PIN;
else if(!(byte_data[1] & 0x10))
return CYTTSP_LOCAL_IDAC;
else if(!(byte_data[1] & 0x20))
return CYTTSP_GLOBAL_IDAC;
else if(!(byte_data[1] & 0x40))
return CYTTSP_BASELINE_TEST;
else if(!(byte_data[1] & 0x80))
return CYTTSP_COMPLETE_BIT;
}
else
return 0;
return 0;
}
static void init_hw_setting(void)
{
int rc;
struct regulator *vreg_touch, *vreg_power_1_8;
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE);
gpio_set_value(GPIO_TOUCH_CHG, 0);
// Power On, AVDD
vreg_touch = regulator_get(NULL, "8058_l19");
if (IS_ERR(vreg_touch))
{
rc = PTR_ERR(vreg_touch);
printk(KERN_ERR "%s: regulator get of %s failed (%d)\n",
__func__, (char *) vreg_touch, rc);
}
rc = regulator_set_voltage(vreg_touch, 3000000, 3000000);
if (rc) {
printk(KERN_ERR "%s: vreg set level failed (%d)\n", __func__, rc);
return;
}
rc = regulator_enable(vreg_touch);
if (rc) {
printk(KERN_ERR "%s: vreg enable failed (%d)\n",__func__, rc);
return;
}
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
vreg_power_1_8 = regulator_get(NULL, "8058_l11");
if (IS_ERR(vreg_power_1_8))
{
rc = PTR_ERR(vreg_power_1_8);
printk(KERN_ERR "%s: regulator get of %s failed (%d)\n",
__func__, (char *) vreg_power_1_8, rc);
}
rc = regulator_set_voltage(vreg_power_1_8, 1900000, 1900000);
if (rc) {
printk(KERN_ERR "%s: vreg set level failed (%d)\n", __func__, rc);
return;
}
rc = regulator_enable(vreg_power_1_8);
if (rc) {
printk(KERN_ERR "%s: vreg enable failed (%d)\n",__func__, rc);
return;
}
#else
// Power On DVDD
vreg_power_1_8 = regulator_get(NULL, "8058_lvs0");
if (IS_ERR(vreg_power_1_8))
{
rc = PTR_ERR(vreg_power_1_8);
printk(KERN_ERR "%s: regulator get of %s failed (%d)\n",
__func__, (char *) vreg_power_1_8, rc);
}
rc = regulator_enable(vreg_power_1_8);
#endif
gpio_set_value(GPIO_TOUCH_CHG, 1);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_CHG, 0, GPIO_CFG_INPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA), GPIO_CFG_ENABLE);
gpio_tlmm_config(GPIO_CFG(GPIO_TOUCH_ID, 0, GPIO_CFG_OUTPUT, GPIO_CFG_NO_PULL, GPIO_CFG_2MA),GPIO_CFG_ENABLE);
gpio_set_value(GPIO_TOUCH_ID, 0);
regulator_put(vreg_touch);
regulator_put(vreg_power_1_8);
msleep(100);
Touch_Status = TOUCH_POWERON;
}
/* I2C driver probe function */
static int __devinit cyttsp_probe(struct i2c_client *client, const struct i2c_device_id *id)
{
struct cyttsp *ts;
int error;
int retval = CYTTSP_OPERATIONAL;
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
int rc;
#endif
cyttsp_info("Start Probe\n");
/* allocate and clear memory */
ts = kzalloc (sizeof(struct cyttsp),GFP_KERNEL);
if (ts == NULL) {
cyttsp_xdebug1("err kzalloc for cyttsp\n");
retval = -ENOMEM;
}
init_hw_setting();
if (!(retval < CYTTSP_OPERATIONAL)) {
/* register driver_data */
ts->client = client;
ts->platform_data = client->dev.platform_data;
i2c_set_clientdata(client,ts);
ts->client->irq = IRQ_TOUCH_INT;
error = cyttsp_initialize(client, ts);
if (error) {
cyttsp_xdebug1("err cyttsp_initialize\n");
if (ts != NULL) {
/* deallocate memory */
kfree(ts);
}
/*
i2c_del_driver(&cyttsp_driver);
*/
retval = -ENODEV;
}
else {
cyttsp_openlog();
}
}
#ifdef CONFIG_HAS_EARLYSUSPEND
if (!(retval < CYTTSP_OPERATIONAL)) {
ts->early_suspend.level = EARLY_SUSPEND_LEVEL_BLANK_SCREEN + 1;
ts->early_suspend.suspend = cyttsp_early_suspend;
ts->early_suspend.resume = cyttsp_late_resume;
register_early_suspend(&ts->early_suspend);
}
#endif /* CONFIG_HAS_EARLYSUSPEND */
#ifdef FEATURE_SKY_PROCESS_CMD_KEY
rc = misc_register(&touch_event);
if (rc) {
pr_err("::::::::: can''t register touch_fops\n");
}
#endif
cyttsp_info("Start Probe %s\n", (retval < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS");
ts_temp = ts;
#ifdef CYTTSP_MUTEX_LOCK
mutex_init(&ts->lock_mutex);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
#if defined(CONFIG_APACHE_BOARD)
schedule_work(&ts->work3);
// INIT_DELAYED_WORK(&work_delay_firmware,check_firmware_update);
// schedule_delayed_work(&work_delay_firmware, msecs_to_jiffies(30000));
#elif defined(CONFIG_EF33_BOARD) || defined(CONFIG_EF34_BOARD)
#if EF33S_BDVER_GE(WS20) || EF34K_BDVER_GE(WS20)
//schedule_work(&ts->work3); // N1037 20120312 for ICS
schedule_delayed_work(&ts->work3, msecs_to_jiffies(3000));
#endif
#else
schedule_work(&ts->work3);
#endif
#endif
wake_lock_init(&touch_wake_lock, WAKE_LOCK_SUSPEND, "touch");
return retval;
}
/* Function to manage power-on resume */
static int cyttsp_resume(struct i2c_client *client)
{
struct cyttsp *ts;
int ret=0;
int retval = CYTTSP_OPERATIONAL;
dbg("Wake Up\n");
ts = (struct cyttsp *) i2c_get_clientdata(client);
if(ts == NULL)
return retval;
pantech_ctl_update(ISSP_IOCTL_POWER_ALL , 1);
pantech_ctl_update(ISSP_IOCTL_INTR, 1);
pantech_ctl_update(ISSP_COMPLITED_UPDATA, 0);
Touch_Status = TOUCH_POWERON;
// for ICS version - 0511 KJHW
input_mt_init_slots(ts->input, TOUCH_MAX_NUM);
msleep(100);
ret = request_irq (client->irq,cyttsp_irq,IRQF_TRIGGER_FALLING, client->dev.driver->name,ts);
#ifdef FEATURE_CYTTSP_HEARTBEAT
mod_timer(&ts->timer, jiffies + CYTTSP_HEARTBEAT_TIME * HZ);
start_heartbeat_timer = true;
#endif
/* re-enable the interrupt after resuming */
// enable_irq(ts->client->irq);
cyttsp_debug("Wake Up %s\n", (retval < CYTTSP_OPERATIONAL) ? "FAIL" : "PASS" );
return retval;
}
/* Function to manage low power suspend */
static int cyttsp_suspend(struct i2c_client *client, pm_message_t message)
{
struct cyttsp *ts;
int retval = CYTTSP_OPERATIONAL, id =0;
dbg("Enter Sleep\n");
ts = (struct cyttsp *) i2c_get_clientdata(client);
if(ts == NULL)
return retval;
/* disable worker */
disable_irq_nosync(ts->client->irq);
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
retval = cancel_work_sync(&ts->work2);
del_timer(&ts->timer);
#endif
#ifdef FEATURE_CYTTSP_FIRMWAREUPGRADE
// cancel_work_sync(&ts->work3);
#endif
Touch_Status = TOUCH_POWEROFF;
retval = cancel_work_sync(&ts->work);
pantech_ctl_update(ISSP_IOCTL_POWER_ALL, 0);
free_irq(client->irq,ts);
pantech_ctl_update(ISSP_IOCTL_SCLK_TO_GPIO, 1);
pantech_ctl_update(ISSP_IOCTL_DATA_TO_GPIO, 1);
pantech_ctl_update(ISSP_IOCTL_INTR, 0);
pantech_ctl_update(ISSP_IOCTL_SCLK, 0);
pantech_ctl_update(ISSP_IOCTL_DATA, 0);
// for ICS version - 0511 KJHW
for (id = 0; id < TOUCH_MAX_NUM; id++)
{
cur_trk[id].abs[CY_ABS_ID_OST] = -1;
cur_touchflag[id] = 0;
input_mt_slot(ts->input, id);
input_report_abs(ts->input, ABS_MT_TRACKING_ID, cur_trk[id].abs[CY_ABS_ID_OST]);
input_report_key(ts->input, BTN_TOUCH, 0 );
input_sync(ts->input);
}
// for ICS version - 0511 KJHW
input_mt_destroy_slots(ts->input);
return retval;
}
/* registered in driver struct */
static int __devexit cyttsp_remove(struct i2c_client *client)
{
struct cyttsp *ts;
int err;
cyttsp_alert("Unregister\n");
/* clientdata registered on probe */
ts = i2c_get_clientdata(client);
device_remove_file(&ts->client->dev, &dev_attr_irq_enable);
/* Start cleaning up by removing any delayed work and the timer */
if (cancel_delayed_work((struct delayed_work *)&ts->work)<0) {
cyttsp_alert("error: could not remove work from workqueue\n");
}
/* free up timer or irq */
if(ts->client->irq == 0) {
err = del_timer(&ts->timer);
if (err < 0) {
cyttsp_alert("error: failed to delete timer\n");
}
}
else {
#ifdef FEATURE_CYTTSP_HEARTBEAT
start_heartbeat_timer = false;
del_timer(&ts->timer);
#endif
free_irq(client->irq,ts);
}
/* housekeeping */
if (ts != NULL) {
kfree(ts);
}
/* clientdata registered on probe */
cyttsp_alert("Leaving\n");
return 0;
}
#ifdef CONFIG_HAS_EARLYSUSPEND
static void cyttsp_early_suspend(struct early_suspend *handler)
{
struct cyttsp *ts;
ts = container_of(handler, struct cyttsp, early_suspend);
cyttsp_suspend(ts->client, PMSG_SUSPEND);
}
static void cyttsp_late_resume(struct early_suspend *handler)
{
struct cyttsp *ts;
ts = container_of(handler, struct cyttsp, early_suspend);
cyttsp_resume(ts->client);
}
#endif /* CONFIG_HAS_EARLYSUSPEND */
static int cyttsp_init(void)
{
int ret;
cyttsp_info("Cypress TrueTouch(R) Standard Product I2C Touchscreen Driver (Built %s @ %s)\n",__DATE__,__TIME__);
ret = i2c_add_driver(&cyttsp_driver);
return ret;
}
static void cyttsp_exit(void)
{
return i2c_del_driver(&cyttsp_driver);
}
module_init(cyttsp_init);
module_exit(cyttsp_exit);
| Java |
# Again-
Remind me
| Java |
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
global $DB;
global $USER;
// Require config.php file for database connection // 1
require_once('/home/libecour/public_html/moodle/config.php');
// Get quiz number // 2
$quiz = $_GET['quiz'];
// Create connection - MySQLi (object-oriented) // 3
$conn = new mysqli($CFG->dbhost, $CFG->dbuser, $CFG->dbpass, $CFG->dbname);
// Check connection - MySQLi (object-oriented) // 4
if ($conn->connect_error) {
die("Connection to the database failed: " . $conn->connect_error . "<br>");
}
// Set character set to UTF8 // 5
mysqli_set_charset($conn,"utf8");
// Check if user is connected // 6
if ($USER->id != 0) {
// Select Statement - MySQLi (object-oriented) // 7
$sql = "SELECT id FROM mdl_pe_learner_profile WHERE userid = $USER->id" ;
$result = $conn->query($sql);
// Get learner profile id // 8
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$learnerprofileid = $row['id'];
}
// free result set // 9
$result->free();
// Select Statement - MySQLi (object-oriented) // 10
$sql = "SELECT abilitylevel FROM mdl_pe_user_ability_levels WHERE learnerprofileid = $learnerprofileid AND libethemeid = 2" ;
$result = $conn->query($sql);
// Get ability level
if ($result->num_rows > 0) {
$row = $result->fetch_assoc();
$abilitylevel = $row['abilitylevel'];
// free result set // 11
$result->free();
// Insert rows in mdl_pe_ability_level_log table // 12
$sql = "INSERT INTO mdl_pe_ability_level_log (learnerprofileid, libethemeid, quiz, abilitylevel, timelogged) VALUES ($learnerprofileid, 2, $quiz, '$abilitylevel', NULL)";
$conn->query($sql);
}
}
// Close database connection // 13
$conn->close();
| Java |
#!/usr/bin/perl
use strict;
my $head = "download:";
my $output;
open ( RULES, $ARGV[0] ) or die;
while ( <RULES> )
{
chomp;
if ( ! m/^#/ and ! m/^\s*$/ )
{
@_ = split ( /;/, $_ );
my $file = $_[0];
$head .= " \$(archivedir)/" . $file;
$output .= "\$(archivedir)/" . $file . ":\n\tfalse || ";
$output .= "mkdir -p \$(archivedir) && ( \\\n\t";
shift @_;
foreach ( @_ )
{
if ( $_ =~ m#^ftp://# )
{
$output .= "wget -c --passive-ftp --no-check-certificate -P \$(archivedir) " . $_ . "/" . $file . " || \\\n\t";
}
elsif ( $_ =~ m#^(http|https)://# )
{
$output .= "wget -t 2 -T 10 -c --no-check-certificate -P \$(archivedir) " . $_ . "/" . $file . " || \\\n\t";
}
}
$output .= "wget -c --no-check-certificate -P \$(archivedir) http://www.i-have-a-dreambox.com/Archive/" . $file . " )";
$output .= "\n\t\@touch \$\@";
$output .= "\n\n";
}
}
close ( RULES );
print $head . "\n\n" . $output . "\n";
| Java |
---
layout: default
title: (#TBD) Method に関する処理 : Java のコードによるメソッド呼び出し処理 (1) : 呼び出し元(caller側)での invoke 処理 : C2 JIT Compiler が生成したコードの場合
---
[Up](no3059lvH.html) [Top](../index.html)
#### (#TBD) Method に関する処理 : Java のコードによるメソッド呼び出し処理 (1) : 呼び出し元(caller側)での invoke 処理 : C2 JIT Compiler が生成したコードの場合
---
#Under Construction
| Java |
/*
* AudioCore.c: Implements the JNi interface and handles
*
* (C) Copyright 2015 Simon Grätzer
* Email: simon@graetzer.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; version 2
* of the License.
*/
#include "de_rwth_aachen_comsys_audiosync_AudioCore.h"
#include <android/log.h>
#include <android/asset_manager.h>
#include <android/asset_manager_jni.h>
#include <signal.h>
#include <assert.h>
#include "audioplayer.h"
#include "AudioStreamSession.h"
#include "SenderSession.h"
#include "ReceiverSession.h"
#include "decoder.h"
#include "jrtplib/rtpsourcedata.h"
#define debugLog(...) __android_log_print(ANDROID_LOG_DEBUG, "AudioCore", __VA_ARGS__)
//#define debugLog(...) printf(__VA_ARGS__)
#ifdef RTP_SUPPORT_THREAD
void thread_exit_handler(int sig) {
debugLog("this signal is %d \n", sig);
pthread_exit(0);
}
#endif
// Global audiostream manager
AudioStreamSession *audioSession;
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_initAudio(JNIEnv *env, jobject thiz,
jint samplesPerSec,
jint framesPerBuffer) {
audioplayer_initGlobal((uint32_t) samplesPerSec, (uint32_t) framesPerBuffer);
#ifdef RTP_SUPPORT_THREAD
// Workaround to kill threads since pthread_cancel is not supported
// See jthread.cpp
struct sigaction actions;
memset(&actions, 0, sizeof(actions));
sigemptyset(&actions.sa_mask);
actions.sa_flags = 0;
actions.sa_handler = thread_exit_handler;
sigaction(SIGUSR1, &actions, NULL);
#endif
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_deinitAudio(JNIEnv *env, jobject thiz) {
if (audioSession) audioSession->Stop();
if (audioSession) delete audioSession;
audioplayer_cleanup();
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_startStreamingAsset (JNIEnv *env, jobject thiz,
jint portbase,
jobject assetManager,
jstring jPath) {
AAssetManager *mgr = AAssetManager_fromJava(env, assetManager);
const char *path = env->GetStringUTFChars(jPath, 0);
// Open the asset from the assets/ folder
AAsset *asset = AAssetManager_open(mgr, path, AASSET_MODE_UNKNOWN);
env->ReleaseStringUTFChars(jPath, path);
if (NULL == asset) {
debugLog("_ASSET_NOT_FOUND_");
return;
}
off_t outStart, fileSize;
int fd = AAsset_openFileDescriptor(asset, &outStart, &fileSize);
assert(0 <= fd);
debugLog("Audio file offset: %ld, size: %ld", outStart, fileSize);
AMediaExtractor *extr = decoder_createExtractorFromFd(fd, outStart, fileSize);
audioSession = SenderSession::StartStreaming((uint16_t) portbase, extr);
AAsset_close(asset);
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_startStreamingUri
(JNIEnv *env, jobject thiz, jint portbase, jstring jPath) {
const char *path = env->GetStringUTFChars(jPath, 0);
AMediaExtractor *extr = decoder_createExtractorFromUri(path);
env->ReleaseStringUTFChars(jPath, path);
audioSession = SenderSession::StartStreaming((uint16_t) portbase, extr);
}
/*
* Class: de_rwth_aachen_comsys_audiosync_AudioCore
* Method: startReceiving
* Signature: (Ljava/lang/String;I)V
*/
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_startReceiving(JNIEnv *env, jobject thiz,
jstring jHost, jint portbase) {
const char *host = env->GetStringUTFChars(jHost, 0);
audioSession = ReceiverSession::StartReceiving(host, (uint16_t) portbase);
env->ReleaseStringUTFChars(jHost, host);
}
/*
* Class: de_rwth_aachen_comsys_audiosync_AudioCore
* Method: stop
* Signature: ()V
*/
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_stopServices(JNIEnv *env, jobject thiz) {
if (audioSession) audioSession->Stop();
audioplayer_stopPlayback();
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_setDeviceLatency(JNIEnv *env, jobject thiz, jlong latencyMs) {
if (latencyMs >= 0)
audioplayer_setDeviceLatency((int64_t)latencyMs * 1000);
}
/*
* Class: de_rwth_aachen_comsys_audiosync_AudioCore
* Method: getRtpSourceCount
* Signature: ()I
*/
jobjectArray Java_de_rwth_1aachen_comsys_audiosync_AudioCore_getAudioDestinations
(JNIEnv *env, jobject thiz) {
if (audioSession == NULL) return NULL;
int i = 0;
if (audioSession->GotoFirstSource())
do {
jrtplib::RTPSourceData *source = audioSession->GetCurrentSourceInfo();
if (source == nullptr || source->IsOwnSSRC()) continue;
i++;
} while (audioSession->GotoNextSource());
if (i == 0) return NULL;
jclass clzz = env->FindClass("de/rwth_aachen/comsys/audiosync/AudioDestination");
jmethodID init = env->GetMethodID(clzz, "<init>", "()V");
jfieldID nameID = env->GetFieldID(clzz, "name", "Ljava/lang/String;");
jfieldID jitterID = env->GetFieldID(clzz, "jitter", "I");
jfieldID timeOffsetID = env->GetFieldID(clzz, "timeOffset", "I");
jfieldID packetsLostID = env->GetFieldID(clzz, "packetsLost", "I");
jobjectArray ret = env->NewObjectArray(i, clzz, NULL);
i = 0;
if (audioSession->GotoFirstSource()) {
do {
jrtplib::RTPSourceData *source = audioSession->GetCurrentSourceInfo();
if (source != nullptr && !source->IsOwnSSRC()) {
jrtplib::RTPSourceData *sourceData = audioSession->GetCurrentSourceInfo();
size_t nameLen = 0;
uint8_t *nameChars = sourceData->SDES_GetName(&nameLen);
char chars[256] = {0};
memcpy(chars, nameChars, nameLen);
jobject dest = env->NewObject(clzz, init);
env->SetObjectField(dest, nameID, env->NewStringUTF(chars));
env->SetIntField(dest, jitterID, (jint) sourceData->INF_GetJitter());
env->SetIntField(dest, timeOffsetID, (jint)sourceData->GetClockOffsetUSeconds());
env->SetIntField(dest, packetsLostID, (jint) sourceData->RR_GetPacketsLost());
env->SetObjectArrayElement(ret, i, dest);
i++;
}
} while (audioSession->GotoNextSource());
}
return ret;
}
/*
* Return current presentation time in milliseconds
*/
jlong Java_de_rwth_1aachen_comsys_audiosync_AudioCore_getCurrentPresentationTime
(JNIEnv *, jobject) {
if (audioSession != NULL && audioSession->IsRunning())
return (jlong)(audioSession->CurrentPlaybackTimeUs() / 1000);
return -1;
}
jboolean Java_de_rwth_1aachen_comsys_audiosync_AudioCore_isRunning (JNIEnv *, jobject) {
bool a = audioSession != NULL && audioSession->IsRunning();
return (jboolean) (a ? JNI_TRUE : JNI_FALSE);
}
jboolean Java_de_rwth_1aachen_comsys_audiosync_AudioCore_isSending(JNIEnv *, jobject) {
if (audioSession != NULL && audioSession->IsSender()) {
return (jboolean) (audioSession->IsRunning());
}
return JNI_FALSE;
}
void Java_de_rwth_1aachen_comsys_audiosync_AudioCore_pauseSending
(JNIEnv *, jobject) {
if (audioSession != NULL && audioSession->IsSender()) {
SenderSession *sender = (SenderSession *)audioSession;
// TODO
}
}
| Java |
<?php
/**
* This file is for debugging and app development purposes only.
* Should not be used for front-end features.
* Possible purposes are:
* -- you want to test the functionality of the methods you created from another registered class.
* -- or you may want to test the effective of such algorithms.
*
*/
# Begin coding below
?> | Java |
package cz.vutbr.fit.xfekia00;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.LinkedList;
/**
* jedno vykonanie skriptu sa uklada ako polozka historie
* @author Filip Fekiac
*/
public class HistoryItem {
private final String usedDatabase; // pouzity databazovy system
private final LinkedList<String[][]> resultList; // vysledky dopytov
private final LinkedList<String[]> resultHeader; // hlavicky dopytov
private final LinkedList<String> resultCaption; // jednotlive dopyty
private final Calendar date;
public HistoryItem(String _usedDB) {
usedDatabase = _usedDB;
resultList = new LinkedList<>();
resultHeader = new LinkedList<>();
resultCaption = new LinkedList<>();
date = Calendar.getInstance();
}
public void addResultItem(int pos, String[][] _item) {
resultList.add(pos, _item);
}
public void addHeaderItem(int pos, String[] _item) {
resultHeader.add(pos, _item);
}
public void addCaptionItem(int pos, String _item) {
resultCaption.add(pos, _item);
}
public String getUsedDatabase() {
return usedDatabase;
}
public LinkedList<String[][]> getResultList() {
return resultList;
}
public LinkedList<String[]> getResultHeader() {
return resultHeader;
}
public LinkedList<String> getResultCaption() {
return resultCaption;
}
@Override
public String toString() {
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss dd.MM.yyyy");
return format.format(date.getTime()) + " " + usedDatabase;
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.