url
stringlengths 12
221
| text
stringlengths 176
1.03M
| encoding
stringclasses 16
values | confidence
float64 0.7
1
| license
stringlengths 0
347
| copyright
stringlengths 3
31.8k
|
---|---|---|---|---|---|
boost1.71-1.71.0/libs/beast/include/boost/beast/core/detail/stream_base.hpp | //
// Copyright (c) 2016-2019 Vinnie Falco (vinnie dot falco at gmail dot com)
//
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Official repository: https://github.com/boostorg/beast
//
#ifndef BOOST_BEAST_CORE_DETAIL_STREAM_BASE_HPP
#define BOOST_BEAST_CORE_DETAIL_STREAM_BASE_HPP
#include <boost/asio/steady_timer.hpp>
#include <boost/assert.hpp>
#include <boost/core/exchange.hpp>
#include <chrono>
#include <cstdint>
#include <utility>
namespace boost {
namespace beast {
namespace detail {
struct any_endpoint
{
template<class Error, class Endpoint>
bool
operator()(
Error const&, Endpoint const&) const noexcept
{
return true;
}
};
struct stream_base
{
using clock_type = std::chrono::steady_clock;
using time_point = typename
std::chrono::steady_clock::time_point;
using tick_type = std::uint64_t;
struct op_state
{
net::steady_timer timer; // for timing out
tick_type tick = 0; // counts waits
bool pending = false; // if op is pending
bool timeout = false; // if timed out
template<class... Args>
explicit
op_state(Args&&... args)
: timer(std::forward<Args>(args)...)
{
}
};
class pending_guard
{
bool& b_;
bool clear_ = true;
public:
~pending_guard()
{
if(clear_)
b_ = false;
}
explicit
pending_guard(bool& b)
: b_(b)
{
BOOST_ASSERT(! b_);
b_ = true;
}
pending_guard(
pending_guard&& other) noexcept
: b_(other.b_)
, clear_(boost::exchange(
other.clear_, false))
{
}
void
reset()
{
BOOST_ASSERT(clear_);
b_ = false;
clear_ = false;
}
};
static time_point never() noexcept
{
return (time_point::max)();
}
static std::size_t constexpr no_limit =
(std::numeric_limits<std::size_t>::max)();
};
} // detail
} // beast
} // boost
#endif
| utf-8 | 1 | BSL-1.0 | Boost project contributors |
highlight-3.41/src/core/Diluculum/LuaExceptions.cpp | /******************************************************************************\
* LuaExceptions.hpp *
* Exceptions related to Lua errors. *
* *
* *
* Copyright (C) 2005-2013 by Leandro Motta Barros. *
* *
* Permission is hereby granted, free of charge, to any person obtaining a copy *
* of this software and associated documentation files (the "Software"), to *
* deal in the Software without restriction, including without limitation the *
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or *
* sell copies of the Software, and to permit persons to whom the Software is *
* furnished to do so, subject to the following conditions: *
* *
* The above copyright notice and this permission notice shall be included in *
* all copies or substantial portions of the Software. *
* *
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR *
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, *
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE *
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER *
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING *
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS *
* IN THE SOFTWARE. *
\******************************************************************************/
#include <Diluculum/LuaExceptions.hpp>
namespace Diluculum
{
// - TypeMismatchError::TypeMismatchError -----------------------------------
TypeMismatchError::TypeMismatchError (const std::string& expectedType,
const std::string& foundType)
: LuaError (("Type mismatch: '" + expectedType
+ "' was expected but '" + foundType
+ "' was found.").c_str()),
expectedType_ (expectedType), foundType_(foundType)
{ }
} // namespace Diluculum
| utf-8 | 1 | unknown | unknown |
qepcad-1.74+ds/extensions/sfext/extlang/ESCELLWR.c | /* Extended sub-CAD cell write. */
#include "extlang.h"
void ESCELLWR(Word C)
{
Word L,p,l;
for(L = NIL, p = C; LELTI(p,SC_PAR) != NIL; p = LELTI(p,SC_PAR))
L = COMP2(LELTI(p,SC_SIGN),LELTI(p,SC_EXTS),L);
while(L != NIL) {
SWRITE("[");
for(ADV(L,&l,&L); l != NIL; l = RED(l)) {
switch(FIRST(l)) {
case POSITIVE: SWRITE("+"); break;
case ZERO : SWRITE("0"); break;
case NEGATIVE: SWRITE("-"); break;
case FNOTDEF : SWRITE("x"); break; } }
SWRITE("] "); }
OWRITE(LELTI(LELTI(C,SC_REP),INDX));
SWRITE(" ");
switch(LELTI(C,SC_CDTV)) {
case TRUE : SWRITE("T"); break;
case FALSE: SWRITE("F"); break;
default: SWRITE("U"); break; }
SWRITE("\n");
return;
}
| utf-8 | 1 | ISC | 1990, 2008 Hoon Hong & Chris Brown <[email protected]> |
cbmc-5.12/regression/snapshot-harness/structs_01/main.c | #include <assert.h>
struct S
{
int c1;
int c2;
} st;
int *p;
void initialize()
{
st.c1 = 1;
st.c2 = 3;
p = &(st.c2);
}
void checkpoint()
{
}
int main()
{
initialize();
checkpoint();
assert(st.c1 + 2 == st.c2);
assert(st.c1 + 2 == *p);
assert(*p == st.c2);
*p = st.c2 + 1;
assert(*p == st.c2);
}
| utf-8 | 1 | BSD-4-clause | 2001-2018, Daniel Kroening, Edmund Clarke,
Computer Science Department, Oxford University
Computer Systems Institute, ETH Zurich
Computer Science Department, Carnegie Mellon University |
blender-3.0.1+dfsg/extern/xdnd/xdnd.c | /* xdnd.c, xdnd.h - C program library for handling the Xdnd protocol
Copyright (C) 1996-2000 Paul Sheer
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.
*/
/*
Released 1998-08-07
Changes:
2000-08-08: INCR protocol implemented.
*/
/*
DONE:
- INCR protocol now implemented
TODO:
- action_choose_dialog not yet supported (never called)
- widget_delete_selection not yet supported and DELETE requests are ignored
- not yet tested with applications that only supported XDND 0 or 1
*/
#include <X11/Xlib.h>
#include <X11/X.h>
#include <X11/Xatom.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#include <sys/types.h>
#ifdef HAVE_UNISTD_H
# include <unistd.h>
#endif
#ifdef HAVE_SYS_SELECT_H
# include <sys/select.h>
#endif
#include "xdnd.h"
static void xdnd_send_enter (DndClass * dnd, Window window, Window from, Atom * typelist);
static void xdnd_send_position (DndClass * dnd, Window window, Window from, Atom action, int x, int y,
unsigned long etime);
static void xdnd_send_status (DndClass * dnd, Window window, Window from, int will_accept, int want_position,
int x, int y, int w, int h, Atom action);
static void xdnd_send_leave (DndClass * dnd, Window window, Window from);
static void xdnd_send_drop (DndClass * dnd, Window window, Window from, unsigned long etime);
static void xdnd_send_finished (DndClass * dnd, Window window, Window from, int error);
static int xdnd_convert_selection (DndClass * dnd, Window window, Window requester, Atom type);
static void xdnd_selection_send (DndClass * dnd, XSelectionRequestEvent * request, unsigned char *data,
int length);
static int xdnd_get_selection (DndClass * dnd, Window from, Atom property, Window insert);
/* just to remind us : */
#if 0
typedef struct {
int type;
unsigned long serial;
Bool send_event;
Display *display;
Window window;
Atom message_type;
int format;
union {
char b[20];
short s[10];
long l[5];
} data;
} XClientMessageEvent;
XClientMessageEvent xclient;
#endif
/* #define DND_DEBUG */
#define xdnd_xfree(x) {if (x) { free (x); x = 0; }}
#ifdef DND_DEBUG
#include <sys/time.h>
#include <unistd.h>
char *xdnd_debug_milliseconds (void)
{
struct timeval tv;
static char r[22];
gettimeofday (&tv, 0);
sprintf (r, "%.2ld.%.3ld", tv.tv_sec % 100L, tv.tv_usec / 1000L);
return r;
}
#define dnd_debug1(a) printf("%s: %d: %s: " a "\n", __FILE__, __LINE__, xdnd_debug_milliseconds ())
#define dnd_debug2(a,b) printf("%s: %d: %s: " a "\n", __FILE__, __LINE__, xdnd_debug_milliseconds (), b)
#define dnd_debug3(a,b,c) printf("%s: %d: %s: " a "\n", __FILE__, __LINE__, xdnd_debug_milliseconds (), b, c)
#define dnd_debug4(a,b,c,d) printf("%s: %d: %s: " a "\n", __FILE__, __LINE__, xdnd_debug_milliseconds (), b, c, d)
#else
#define dnd_debug1(a) do {} while (0)
#define dnd_debug2(a,b) do {} while (0)
#define dnd_debug3(a,b,c) do {} while (0)
#define dnd_debug4(a,b,c,d) do {} while (0)
#endif
#define dnd_warning(a) fprintf (stderr, a)
#define dnd_version_at_least(a,b) ((a) >= (b))
static unsigned char dnd_copy_cursor_bits[] =
{
0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x0f, 0x00, 0x02, 0x00, 0x08, 0x01,
0x02, 0x00, 0x08, 0x01, 0x02, 0x00, 0x08, 0x01, 0x02, 0x00, 0xe8, 0x0f,
0x02, 0x00, 0x08, 0x01, 0x02, 0x00, 0x08, 0x01, 0x02, 0x00, 0x08, 0x01,
0x02, 0x00, 0x08, 0x00, 0x02, 0x04, 0x08, 0x00, 0x02, 0x0c, 0x08, 0x00,
0x02, 0x1c, 0x08, 0x00, 0x02, 0x3c, 0x08, 0x00, 0x02, 0x7c, 0x08, 0x00,
0x02, 0xfc, 0x08, 0x00, 0x02, 0xfc, 0x09, 0x00, 0x02, 0xfc, 0x0b, 0x00,
0x02, 0x7c, 0x08, 0x00, 0xfe, 0x6d, 0x0f, 0x00, 0x00, 0xc4, 0x00, 0x00,
0x00, 0xc0, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00};
static unsigned char dnd_copy_mask_bits[] =
{
0xff, 0xff, 0x1f, 0x00, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0x1f,
0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f,
0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f,
0x07, 0x06, 0xfc, 0x1f, 0x07, 0x0e, 0xfc, 0x1f, 0x07, 0x1e, 0x1c, 0x00,
0x07, 0x3e, 0x1c, 0x00, 0x07, 0x7e, 0x1c, 0x00, 0x07, 0xfe, 0x1c, 0x00,
0x07, 0xfe, 0x1d, 0x00, 0x07, 0xfe, 0x1f, 0x00, 0x07, 0xfe, 0x1f, 0x00,
0xff, 0xff, 0x1f, 0x00, 0xff, 0xff, 0x1e, 0x00, 0xff, 0xef, 0x1f, 0x00,
0x00, 0xe6, 0x01, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x00, 0xc0, 0x03, 0x00,
0x00, 0x80, 0x01, 0x00};
static unsigned char dnd_move_cursor_bits[] =
{
0x00, 0x00, 0x00, 0xfe, 0xff, 0x0f, 0x02, 0x00, 0x08, 0x02, 0x00, 0x08,
0x02, 0x00, 0x08, 0x02, 0x00, 0x08, 0x02, 0x00, 0x08, 0x02, 0x00, 0x08,
0x02, 0x00, 0x08, 0x02, 0x00, 0x08, 0x02, 0x04, 0x08, 0x02, 0x0c, 0x08,
0x02, 0x1c, 0x08, 0x02, 0x3c, 0x08, 0x02, 0x7c, 0x08, 0x02, 0xfc, 0x08,
0x02, 0xfc, 0x09, 0x02, 0xfc, 0x0b, 0x02, 0x7c, 0x08, 0xfe, 0x6d, 0x0f,
0x00, 0xc4, 0x00, 0x00, 0xc0, 0x00, 0x00, 0x80, 0x01, 0x00, 0x80, 0x01,
0x00, 0x00, 0x00};
static unsigned char dnd_move_mask_bits[] =
{
0xff, 0xff, 0x1f, 0xff, 0xff, 0x1f, 0xff, 0xff, 0x1f, 0x07, 0x00, 0x1c,
0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c, 0x07, 0x00, 0x1c,
0x07, 0x00, 0x1c, 0x07, 0x06, 0x1c, 0x07, 0x0e, 0x1c, 0x07, 0x1e, 0x1c,
0x07, 0x3e, 0x1c, 0x07, 0x7e, 0x1c, 0x07, 0xfe, 0x1c, 0x07, 0xfe, 0x1d,
0x07, 0xfe, 0x1f, 0x07, 0xfe, 0x1f, 0xff, 0xff, 0x1f, 0xff, 0xff, 0x1e,
0xff, 0xef, 0x1f, 0x00, 0xe6, 0x01, 0x00, 0xc0, 0x03, 0x00, 0xc0, 0x03,
0x00, 0x80, 0x01};
static unsigned char dnd_link_cursor_bits[] =
{
0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x0f, 0x00, 0x02, 0x00, 0x08, 0x01,
0x02, 0x00, 0x88, 0x00, 0x02, 0x00, 0x48, 0x00, 0x02, 0x00, 0xe8, 0x0f,
0x02, 0x00, 0x48, 0x00, 0x02, 0x00, 0x88, 0x00, 0x02, 0x00, 0x08, 0x01,
0x02, 0x00, 0x08, 0x00, 0x02, 0x04, 0x08, 0x00, 0x02, 0x0c, 0x08, 0x00,
0x02, 0x1c, 0x08, 0x00, 0x02, 0x3c, 0x08, 0x00, 0x02, 0x7c, 0x08, 0x00,
0x02, 0xfc, 0x08, 0x00, 0x02, 0xfc, 0x09, 0x00, 0x02, 0xfc, 0x0b, 0x00,
0x02, 0x7c, 0x08, 0x00, 0xfe, 0x6d, 0x0f, 0x00, 0x00, 0xc4, 0x00, 0x00,
0x00, 0xc0, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00};
static unsigned char dnd_link_mask_bits[] =
{
0xff, 0xff, 0x1f, 0x00, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0x1f,
0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f,
0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f,
0x07, 0x06, 0xfc, 0x1f, 0x07, 0x0e, 0xfc, 0x1f, 0x07, 0x1e, 0x1c, 0x00,
0x07, 0x3e, 0x1c, 0x00, 0x07, 0x7e, 0x1c, 0x00, 0x07, 0xfe, 0x1c, 0x00,
0x07, 0xfe, 0x1d, 0x00, 0x07, 0xfe, 0x1f, 0x00, 0x07, 0xfe, 0x1f, 0x00,
0xff, 0xff, 0x1f, 0x00, 0xff, 0xff, 0x1e, 0x00, 0xff, 0xef, 0x1f, 0x00,
0x00, 0xe6, 0x01, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x00, 0xc0, 0x03, 0x00,
0x00, 0x80, 0x01, 0x00};
static unsigned char dnd_ask_cursor_bits[] =
{
0x00, 0x00, 0x00, 0x00, 0xfe, 0xff, 0x0f, 0x00, 0x02, 0x00, 0x88, 0x03,
0x02, 0x00, 0x48, 0x04, 0x02, 0x00, 0x08, 0x04, 0x02, 0x00, 0x08, 0x02,
0x02, 0x00, 0x08, 0x01, 0x02, 0x00, 0x08, 0x01, 0x02, 0x00, 0x08, 0x00,
0x02, 0x00, 0x08, 0x01, 0x02, 0x04, 0x08, 0x00, 0x02, 0x0c, 0x08, 0x00,
0x02, 0x1c, 0x08, 0x00, 0x02, 0x3c, 0x08, 0x00, 0x02, 0x7c, 0x08, 0x00,
0x02, 0xfc, 0x08, 0x00, 0x02, 0xfc, 0x09, 0x00, 0x02, 0xfc, 0x0b, 0x00,
0x02, 0x7c, 0x08, 0x00, 0xfe, 0x6d, 0x0f, 0x00, 0x00, 0xc4, 0x00, 0x00,
0x00, 0xc0, 0x00, 0x00, 0x00, 0x80, 0x01, 0x00, 0x00, 0x80, 0x01, 0x00,
0x00, 0x00, 0x00, 0x00};
static unsigned char dnd_ask_mask_bits[] =
{
0xff, 0xff, 0x1f, 0x00, 0xff, 0xff, 0xff, 0x1f, 0xff, 0xff, 0xff, 0x1f,
0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f,
0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f, 0x07, 0x00, 0xfc, 0x1f,
0x07, 0x06, 0xfc, 0x1f, 0x07, 0x0e, 0xfc, 0x1f, 0x07, 0x1e, 0x1c, 0x00,
0x07, 0x3e, 0x1c, 0x00, 0x07, 0x7e, 0x1c, 0x00, 0x07, 0xfe, 0x1c, 0x00,
0x07, 0xfe, 0x1d, 0x00, 0x07, 0xfe, 0x1f, 0x00, 0x07, 0xfe, 0x1f, 0x00,
0xff, 0xff, 0x1f, 0x00, 0xff, 0xff, 0x1e, 0x00, 0xff, 0xef, 0x1f, 0x00,
0x00, 0xe6, 0x01, 0x00, 0x00, 0xc0, 0x03, 0x00, 0x00, 0xc0, 0x03, 0x00,
0x00, 0x80, 0x01, 0x00};
static DndCursor dnd_cursors[] =
{
{29, 25, 10, 10, dnd_copy_cursor_bits, dnd_copy_mask_bits, "XdndActionCopy", 0, 0, 0, 0},
{21, 25, 10, 10, dnd_move_cursor_bits, dnd_move_mask_bits, "XdndActionMove", 0, 0, 0, 0},
{29, 25, 10, 10, dnd_link_cursor_bits, dnd_link_mask_bits, "XdndActionLink", 0, 0, 0, 0},
{29, 25, 10, 10, dnd_ask_cursor_bits, dnd_ask_mask_bits, "XdndActionAsk", 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}
};
void xdnd_reset (DndClass * dnd)
{
dnd->stage = XDND_DROP_STAGE_IDLE;
dnd->dragging_version = 0;
dnd->internal_drag = 0;
dnd->want_position = 0;
dnd->ready_to_drop = 0;
dnd->will_accept = 0;
dnd->rectangle.x = dnd->rectangle.y = 0;
dnd->rectangle.width = dnd->rectangle.height = 0;
dnd->dropper_window = 0;
dnd->dropper_toplevel = 0;
dnd->dragger_window = 0;
dnd->dragger_typelist = 0;
dnd->desired_type = 0;
dnd->time = 0;
}
void xdnd_init (DndClass * dnd, Display * display)
{
DndCursor *cursor;
XColor black, white;
memset (dnd, 0, sizeof (*dnd));
dnd->display = display;
dnd->root_window = DefaultRootWindow (display);
dnd->version = XDND_VERSION;
dnd->XdndAware = XInternAtom (dnd->display, "XdndAware", False);
dnd->XdndSelection = XInternAtom (dnd->display, "XdndSelection", False);
dnd->XdndEnter = XInternAtom (dnd->display, "XdndEnter", False);
dnd->XdndLeave = XInternAtom (dnd->display, "XdndLeave", False);
dnd->XdndPosition = XInternAtom (dnd->display, "XdndPosition", False);
dnd->XdndDrop = XInternAtom (dnd->display, "XdndDrop", False);
dnd->XdndFinished = XInternAtom (dnd->display, "XdndFinished", False);
dnd->XdndStatus = XInternAtom (dnd->display, "XdndStatus", False);
dnd->XdndActionCopy = XInternAtom (dnd->display, "XdndActionCopy", False);
dnd->XdndActionMove = XInternAtom (dnd->display, "XdndActionMove", False);
dnd->XdndActionLink = XInternAtom (dnd->display, "XdndActionLink", False);
dnd->XdndActionAsk = XInternAtom (dnd->display, "XdndActionAsk", False);
dnd->XdndActionPrivate = XInternAtom (dnd->display, "XdndActionPrivate", False);
dnd->XdndTypeList = XInternAtom (dnd->display, "XdndTypeList", False);
dnd->XdndActionList = XInternAtom (dnd->display, "XdndActionList", False);
dnd->XdndActionDescription = XInternAtom (dnd->display, "XdndActionDescription", False);
dnd->Xdnd_NON_PROTOCOL_ATOM = XInternAtom (dnd->display, "JXSelectionWindowProperty", False);
xdnd_reset (dnd);
dnd->cursors = dnd_cursors;
black.pixel = BlackPixel (dnd->display, DefaultScreen (dnd->display));
white.pixel = WhitePixel (dnd->display, DefaultScreen (dnd->display));
XQueryColor (dnd->display, DefaultColormap (dnd->display, DefaultScreen (dnd->display)), &black);
XQueryColor (dnd->display, DefaultColormap (dnd->display, DefaultScreen (dnd->display)), &white);
for (cursor = &dnd->cursors[0]; cursor->width; cursor++) {
cursor->image_pixmap = XCreateBitmapFromData \
(dnd->display, dnd->root_window, (char *) cursor->image_data, cursor->width, cursor->height);
cursor->mask_pixmap = XCreateBitmapFromData \
(dnd->display, dnd->root_window, (char *) cursor->mask_data, cursor->width, cursor->height);
cursor->cursor = XCreatePixmapCursor (dnd->display, cursor->image_pixmap,
cursor->mask_pixmap, &black, &white, cursor->x, cursor->y);
XFreePixmap (dnd->display, cursor->image_pixmap);
XFreePixmap (dnd->display, cursor->mask_pixmap);
cursor->action = XInternAtom (dnd->display, cursor->_action, False);
}
}
void xdnd_shut (DndClass * dnd)
{
DndCursor *cursor;
for (cursor = &dnd->cursors[0]; cursor->width; cursor++)
XFreeCursor (dnd->display, cursor->cursor);
memset (dnd, 0, sizeof (*dnd));
return;
}
/* typelist is a null terminated array */
static int array_length (Atom * a)
{
int n;
for (n = 0; a[n]; n++);
return n;
}
void xdnd_set_dnd_aware (DndClass * dnd, Window window, Atom * typelist)
{
Window root_return, parent;
unsigned int nchildren_return;
Window *children_return = 0;
int r, s;
if(!window) return;
if (dnd->widget_exists)
if (!(*dnd->widget_exists) (dnd, window))
return;
s = XChangeProperty (dnd->display, window, dnd->XdndAware, XA_ATOM, 32, PropModeReplace,
(unsigned char *) &dnd->version, 1);
#if 1
dnd_debug4 ("XChangeProperty() = %d, window = %ld, widget = %s", s, window, "<WIDGET>");
#endif
if (s && typelist) {
int n;
n = array_length (typelist);
if (n)
s = XChangeProperty (dnd->display, window, dnd->XdndAware, XA_ATOM, 32, PropModeAppend,
(unsigned char *) typelist, n);
}
r =
XQueryTree (dnd->display, window, &root_return, &parent, &children_return,
&nchildren_return);
if (children_return)
XFree (children_return);
if (r && parent != root_return)
xdnd_set_dnd_aware (dnd, parent, typelist);
}
int xdnd_is_dnd_aware (DndClass * dnd, Window window, int *version, Atom * typelist)
{
Atom actual;
int format;
unsigned long count, remaining;
unsigned char *data = 0;
Atom *types, *t;
int result = 1;
*version = 0;
XGetWindowProperty (dnd->display, window, dnd->XdndAware,
0, 0x8000000L, False, XA_ATOM,
&actual, &format,
&count, &remaining, &data);
if (actual != XA_ATOM || format != 32 || count == 0 || !data) {
dnd_debug2 ("XGetWindowProperty failed in xdnd_is_dnd_aware - XdndAware = %ld", dnd->XdndAware);
if (data)
XFree (data);
return 0;
}
types = (Atom *) data;
#if XDND_VERSION >= 3
if (types[0] < 3) {
if (data)
XFree (data);
return 0;
}
#endif
*version = dnd->version < types[0] ? dnd->version : types[0]; /* minimum */
dnd_debug2 ("Using XDND version %d", *version);
if (count > 1) {
result = 0;
for (t = typelist; *t; t++) {
int j;
for (j = 1; j < count; j++) {
if (types[j] == *t) {
result = 1;
break;
}
}
if (result)
break;
}
}
XFree (data);
return result;
}
void xdnd_set_type_list (DndClass * dnd, Window window, Atom * typelist)
{
int n;
n = array_length (typelist);
XChangeProperty (dnd->display, window, dnd->XdndTypeList, XA_ATOM, 32,
PropModeReplace, (unsigned char *) typelist, n);
}
/* result must be free'd */
void xdnd_get_type_list (DndClass * dnd, Window window, Atom ** typelist)
{
Atom type, *a;
int format, i;
unsigned long count, remaining;
unsigned char *data = NULL;
*typelist = 0;
XGetWindowProperty (dnd->display, window, dnd->XdndTypeList,
0, 0x8000000L, False, XA_ATOM,
&type, &format, &count, &remaining, &data);
if (type != XA_ATOM || format != 32 || count == 0 || !data) {
if (data)
XFree (data);
dnd_debug2 ("XGetWindowProperty failed in xdnd_get_type_list - dnd->XdndTypeList = %ld", dnd->XdndTypeList);
return;
}
*typelist = malloc ((count + 1) * sizeof (Atom));
a = (Atom *) data;
for (i = 0; i < count; i++)
(*typelist)[i] = a[i];
(*typelist)[count] = 0;
XFree (data);
}
void xdnd_get_three_types (DndClass * dnd, XEvent * xevent, Atom ** typelist)
{
int i;
*typelist = malloc ((XDND_THREE + 1) * sizeof (Atom));
for (i = 0; i < XDND_THREE; i++)
(*typelist)[i] = XDND_ENTER_TYPE (xevent, i);
(*typelist)[XDND_THREE] = 0; /* although (*typelist)[1] or (*typelist)[2] may also be set to nill */
}
/* result must be free'd */
static char *concat_string_list (char **t, int *bytes)
{
int l, n;
char *s;
for (l = n = 0;; n++) {
if (!t[n])
break;
if (!t[n][0])
break;
l += strlen (t[n]) + 1;
}
s = malloc (l + 1);
for (l = n = 0;; n++) {
if (!t[n])
break;
if (!(t[n][0]))
break;
strcpy (s + l, t[n]);
l += strlen (t[n]) + 1;
}
*bytes = l;
s[l] = '\0';
return s;
}
void xdnd_set_actions (DndClass * dnd, Window window, Atom * actions, char **descriptions)
{
int n, l;
char *s;
n = array_length (actions);
XChangeProperty (dnd->display, window, dnd->XdndActionList, XA_ATOM, 32,
PropModeReplace, (unsigned char *) actions, n);
s = concat_string_list (descriptions, &l);
XChangeProperty (dnd->display, window, dnd->XdndActionList, XA_STRING, 8,
PropModeReplace, (unsigned char *) s, l);
xdnd_xfree (s);
}
/* returns 1 on error or no actions, otherwise result must be free'd
xdnd_get_actions (window, &actions, &descriptions);
free (actions); free (descriptions); */
int xdnd_get_actions (DndClass * dnd, Window window, Atom ** actions, char ***descriptions)
{
Atom type, *a;
int format, i;
unsigned long count, dcount, remaining;
unsigned char *data = 0, *r;
*actions = 0;
*descriptions = 0;
XGetWindowProperty (dnd->display, window, dnd->XdndActionList,
0, 0x8000000L, False, XA_ATOM,
&type, &format, &count, &remaining, &data);
if (type != XA_ATOM || format != 32 || count == 0 || !data) {
if (data)
XFree (data);
return 1;
}
*actions = malloc ((count + 1) * sizeof (Atom));
a = (Atom *) data;
for (i = 0; i < count; i++)
(*actions)[i] = a[i];
(*actions)[count] = 0;
XFree (data);
data = 0;
XGetWindowProperty (dnd->display, window, dnd->XdndActionDescription,
0, 0x8000000L, False, XA_STRING, &type, &format,
&dcount, &remaining, &data);
if (type != XA_STRING || format != 8 || dcount == 0) {
if (data)
XFree (data);
*descriptions = malloc ((count + 1) * sizeof (char *));
dnd_warning ("XGetWindowProperty no property or wrong format for action descriptions");
for (i = 0; i < count; i++)
(*descriptions)[i] = "";
(*descriptions)[count] = 0;
} else {
int l;
l = (count + 1) * sizeof (char *);
*descriptions = malloc (l + dcount);
memcpy (*descriptions + l, data, dcount);
XFree (data);
data = (unsigned char *) *descriptions;
data += l;
l = 0;
for (i = 0, r = data;; r += l + 1, i++) {
l = strlen ((char *) r);
if (!l || i >= count)
break;
(*descriptions)[i] = (char *) r;
}
for (; i < count; i++) {
(*descriptions)[i] = "";
}
(*descriptions)[count] = 0;
}
return 0;
}
/* returns non-zero on cancel */
int xdnd_choose_action_dialog (DndClass * dnd, Atom * actions, char **descriptions, Atom * result)
{
if (!actions[0])
return 1;
if (!dnd->action_choose_dialog) { /* default to return the first action if no dialog set */
*result = actions[0];
return 0;
}
return (*dnd->action_choose_dialog) (dnd, descriptions, actions, result);
}
static void xdnd_send_event (DndClass * dnd, Window window, XEvent * xevent)
{
dnd_debug4 ("xdnd_send_event(), window = %ld, l[0] = %ld, l[4] = %ld",
window, xevent->xclient.data.l[0], xevent->xclient.data.l[4]);
dnd_debug2 ("xdnd_send_event(), from widget widget %s", (char *) "<WIDGET>");
XSendEvent (dnd->display, window, 0, 0, xevent);
}
static void xdnd_send_enter (DndClass * dnd, Window window, Window from, Atom * typelist)
{
XEvent xevent;
int n, i;
n = array_length (typelist);
memset (&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = dnd->display;
xevent.xclient.window = window;
xevent.xclient.message_type = dnd->XdndEnter;
xevent.xclient.format = 32;
XDND_ENTER_SOURCE_WIN (&xevent) = from;
XDND_ENTER_THREE_TYPES_SET (&xevent, n > XDND_THREE);
XDND_ENTER_VERSION_SET (&xevent, dnd->version);
for (i = 0; i < n && i < XDND_THREE; i++)
XDND_ENTER_TYPE (&xevent, i) = typelist[i];
xdnd_send_event (dnd, window, &xevent);
}
static void xdnd_send_position (DndClass * dnd, Window window, Window from, Atom action, int x, int y, unsigned long time)
{
XEvent xevent;
memset (&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = dnd->display;
xevent.xclient.window = window;
xevent.xclient.message_type = dnd->XdndPosition;
xevent.xclient.format = 32;
XDND_POSITION_SOURCE_WIN (&xevent) = from;
XDND_POSITION_ROOT_SET (&xevent, x, y);
if (dnd_version_at_least (dnd->dragging_version, 1))
XDND_POSITION_TIME (&xevent) = time;
if (dnd_version_at_least (dnd->dragging_version, 2))
XDND_POSITION_ACTION (&xevent) = action;
xdnd_send_event (dnd, window, &xevent);
}
static void xdnd_send_status (DndClass * dnd, Window window, Window from, int will_accept, \
int want_position, int x, int y, int w, int h, Atom action)
{
XEvent xevent;
memset (&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = dnd->display;
xevent.xclient.window = window;
xevent.xclient.message_type = dnd->XdndStatus;
xevent.xclient.format = 32;
XDND_STATUS_TARGET_WIN (&xevent) = from;
XDND_STATUS_WILL_ACCEPT_SET (&xevent, will_accept);
if (will_accept)
XDND_STATUS_WANT_POSITION_SET (&xevent, want_position);
if (want_position)
XDND_STATUS_RECT_SET (&xevent, x, y, w, h);
if (dnd_version_at_least (dnd->dragging_version, 2))
if (will_accept)
XDND_STATUS_ACTION (&xevent) = action;
xdnd_send_event (dnd, window, &xevent);
}
static void xdnd_send_leave (DndClass * dnd, Window window, Window from)
{
XEvent xevent;
memset (&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = dnd->display;
xevent.xclient.window = window;
xevent.xclient.message_type = dnd->XdndLeave;
xevent.xclient.format = 32;
XDND_LEAVE_SOURCE_WIN (&xevent) = from;
xdnd_send_event (dnd, window, &xevent);
}
static void xdnd_send_drop (DndClass * dnd, Window window, Window from, unsigned long time)
{
XEvent xevent;
memset (&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = dnd->display;
xevent.xclient.window = window;
xevent.xclient.message_type = dnd->XdndDrop;
xevent.xclient.format = 32;
XDND_DROP_SOURCE_WIN (&xevent) = from;
if (dnd_version_at_least (dnd->dragging_version, 1))
XDND_DROP_TIME (&xevent) = time;
xdnd_send_event (dnd, window, &xevent);
}
/* error is not actually used, i think future versions of the protocol should return an error status
to the calling window with the XdndFinished client message */
static void xdnd_send_finished (DndClass * dnd, Window window, Window from, int error)
{
XEvent xevent;
memset (&xevent, 0, sizeof (xevent));
xevent.xany.type = ClientMessage;
xevent.xany.display = dnd->display;
xevent.xclient.window = window;
xevent.xclient.message_type = dnd->XdndFinished;
xevent.xclient.format = 32;
XDND_FINISHED_TARGET_WIN (&xevent) = from;
xdnd_send_event (dnd, window, &xevent);
}
/* returns non-zero on error - i.e. no selection owner set. Type is of course the mime type */
static int xdnd_convert_selection (DndClass * dnd, Window window, Window requester, Atom type)
{
if (!(window = XGetSelectionOwner (dnd->display, dnd->XdndSelection))) {
dnd_debug1 ("xdnd_convert_selection(): XGetSelectionOwner failed");
return 1;
}
XConvertSelection (dnd->display, dnd->XdndSelection, type,
dnd->Xdnd_NON_PROTOCOL_ATOM, requester, CurrentTime);
return 0;
}
/* returns non-zero on error */
static int xdnd_set_selection_owner (DndClass * dnd, Window window, Atom type, Time time)
{
if (!XSetSelectionOwner (dnd->display, dnd->XdndSelection, window, time)) {
dnd_debug1 ("xdnd_set_selection_owner(): XSetSelectionOwner failed");
return 1;
}
return 0;
}
static void xdnd_selection_send (DndClass * dnd, XSelectionRequestEvent * request, unsigned char *data, int length)
{
XEvent xevent;
dnd_debug2 (" requestor = %ld", request->requestor);
dnd_debug2 (" property = %ld", request->property);
dnd_debug2 (" length = %d", length);
XChangeProperty (dnd->display, request->requestor, request->property,
request->target, 8, PropModeReplace, data, length);
xevent.xselection.type = SelectionNotify;
xevent.xselection.property = request->property;
xevent.xselection.display = request->display;
xevent.xselection.requestor = request->requestor;
xevent.xselection.selection = request->selection;
xevent.xselection.target = request->target;
xevent.xselection.time = request->time;
xdnd_send_event (dnd, request->requestor, &xevent);
}
#if 0
/* respond to a notification that a primary selection has been sent */
int xdnd_get_selection (DndClass * dnd, Window from, Atom property, Window insert)
{
long read;
int error = 0;
unsigned long remaining;
if (!property)
return 1;
read = 0;
do {
unsigned char *s;
Atom actual;
int format;
unsigned long count;
if (XGetWindowProperty (dnd->display, insert, property, read / 4, 65536, 1,
AnyPropertyType, &actual, &format,
&count, &remaining,
&s) != Success) {
XFree (s);
return 1;
}
read += count;
if (dnd->widget_insert_drop && !error)
error = (*dnd->widget_insert_drop) (dnd, s, count, remaining, insert, from, actual);
XFree (s);
} while (remaining);
return error;
}
#endif
static int paste_prop_internal (DndClass * dnd, Window from, Window insert, unsigned long prop, int delete_prop)
{
long nread = 0;
unsigned long nitems;
unsigned long bytes_after;
int error = 0;
do {
Atom actual_type;
int actual_fmt;
unsigned char *s = 0;
if (XGetWindowProperty (dnd->display, insert, prop,
nread / 4, 65536, delete_prop,
AnyPropertyType, &actual_type, &actual_fmt,
&nitems, &bytes_after, &s) != Success) {
XFree (s);
return 1;
}
nread += nitems;
if (dnd->widget_insert_drop && !error)
error = (*dnd->widget_insert_drop) (dnd, s, nitems, bytes_after, insert, from, actual_fmt);
XFree (s);
} while (bytes_after);
if (!nread)
return 1;
return 0;
}
/*
* Respond to a notification that a primary selection has been sent (supports INCR)
*/
static int xdnd_get_selection (DndClass * dnd, Window from, Atom prop, Window insert)
{
struct timeval tv, tv_start;
unsigned long bytes_after;
Atom actual_type;
int actual_fmt;
unsigned long nitems;
unsigned char *s = 0;
if (prop == None)
return 1;
if (XGetWindowProperty
(dnd->display, insert, prop, 0, 8, False, AnyPropertyType, &actual_type, &actual_fmt,
&nitems, &bytes_after, &s) != Success) {
XFree (s);
return 1;
}
XFree (s);
if (actual_type != XInternAtom (dnd->display, "INCR", False))
return paste_prop_internal (dnd, from, insert, prop, True);
XDeleteProperty (dnd->display, insert, prop);
gettimeofday (&tv_start, 0);
for (;;) {
long t;
fd_set r;
XEvent xe;
if (XCheckMaskEvent (dnd->display, PropertyChangeMask, &xe)) {
if (xe.type == PropertyNotify && xe.xproperty.state == PropertyNewValue) {
/* time between arrivals of data */
gettimeofday (&tv_start, 0);
if (paste_prop_internal (dnd, from, insert, prop, True))
break;
}
} else {
tv.tv_sec = 0;
tv.tv_usec = 10000;
FD_ZERO (&r);
FD_SET (ConnectionNumber (dnd->display), &r);
select (ConnectionNumber (dnd->display) + 1, &r, 0, 0, &tv);
if (FD_ISSET (ConnectionNumber (dnd->display), &r))
continue;
}
gettimeofday (&tv, 0);
t = (tv.tv_sec - tv_start.tv_sec) * 1000000L + (tv.tv_usec - tv_start.tv_usec);
/* no data for five seconds, so quit */
if (t > 5000000L)
return 1;
}
return 0;
}
int outside_rectangle (int x, int y, XRectangle * r)
{
return (x < r->x || y < r->y || x >= r->x + r->width || y >= r->y + r->height);
}
/* avoids linking with the maths library */
static float xdnd_sqrt (float x)
{
float last_ans, ans = 2, a;
if (x <= 0.0)
return 0.0;
do {
last_ans = ans;
ans = (ans + x / ans) / 2;
a = (ans - last_ans) / ans;
if (a < 0.0)
a = (-a);
} while (a > 0.001);
return ans;
}
#define print_marks print_win_marks(from,__FILE__,__LINE__);
/* returns action on success, 0 otherwise */
Atom xdnd_drag (DndClass * dnd, Window from, Atom action, Atom * typelist)
{
XEvent xevent, xevent_temp;
Window over_window = 0, last_window = 0;
#if XDND_VERSION >= 3
Window last_dropper_toplevel = 0;
int internal_dropable = 1;
#endif
int n;
DndCursor *cursor;
float x_mouse, y_mouse;
int result = 0, dnd_aware;
if (!typelist)
dnd_warning ("xdnd_drag() called with typelist = 0");
/* first wait until the mouse moves more than five pixels */
do {
XNextEvent (dnd->display, &xevent);
if (xevent.type == ButtonRelease) {
dnd_debug1 ("button release - no motion");
XSendEvent (dnd->display, xevent.xany.window, 0, ButtonReleaseMask, &xevent);
return 0;
}
} while (xevent.type != MotionNotify);
x_mouse = (float) xevent.xmotion.x_root;
y_mouse = (float) xevent.xmotion.y_root;
if (!dnd->drag_threshold)
dnd->drag_threshold = 4.0;
for (;;) {
XNextEvent (dnd->display, &xevent);
if (xevent.type == MotionNotify)
if (xdnd_sqrt ((x_mouse - xevent.xmotion.x_root) * (x_mouse - xevent.xmotion.x_root) +
(y_mouse - xevent.xmotion.y_root) * (y_mouse - xevent.xmotion.y_root)) > dnd->drag_threshold)
break;
if (xevent.type == ButtonRelease) {
XSendEvent (dnd->display, xevent.xany.window, 0, ButtonReleaseMask, &xevent);
return 0;
}
}
dnd_debug1 ("moved 5 pixels - going to drag");
n = array_length (typelist);
if (n > XDND_THREE)
xdnd_set_type_list (dnd, from, typelist);
xdnd_reset (dnd);
dnd->stage = XDND_DRAG_STAGE_DRAGGING;
for (cursor = &dnd->cursors[0]; cursor->width; cursor++)
if (cursor->action == action)
break;
if (!cursor->width)
cursor = &dnd->cursors[0];
/* the mouse has been dragged a little, so this is a drag proper */
if (XGrabPointer (dnd->display, dnd->root_window, False,
ButtonMotionMask | PointerMotionMask | ButtonPressMask | ButtonReleaseMask,
GrabModeAsync, GrabModeAsync, None,
cursor->cursor, CurrentTime) != GrabSuccess)
dnd_debug1 ("Unable to grab pointer");
while (xevent.xany.type != ButtonRelease) {
XAllowEvents (dnd->display, SyncPointer, CurrentTime);
XNextEvent (dnd->display, &xevent);
switch (xevent.type) {
case Expose:
if (dnd->handle_expose_events)
(*dnd->handle_expose_events) (dnd, &xevent);
break;
case EnterNotify:
/* this event is not actually reported, so we find out by ourselves from motion events */
break;
case LeaveNotify:
/* this event is not actually reported, so we find out by ourselves from motion events */
break;
case ButtonRelease:
/* done, but must send a leave event */
dnd_debug1 ("ButtonRelease - exiting event loop");
break;
case MotionNotify:
dnd_aware = 0;
dnd->dropper_toplevel = 0;
memcpy (&xevent_temp, &xevent, sizeof (xevent));
xevent.xmotion.subwindow = xevent.xmotion.window;
{
Window root_return, child_return;
int x_temp, y_temp;
unsigned int mask_return;
while (XQueryPointer (dnd->display, xevent.xmotion.subwindow, &root_return, &child_return,
&x_temp, &y_temp, &xevent.xmotion.x,
&xevent.xmotion.y, &mask_return)) {
#if XDND_VERSION >= 3
if (!dnd_aware) {
if ((dnd_aware = xdnd_is_dnd_aware (dnd, xevent.xmotion.subwindow, &dnd->dragging_version, typelist))) {
dnd->dropper_toplevel = xevent.xmotion.subwindow;
xevent.xmotion.x_root = x_temp;
xevent.xmotion.y_root = y_temp;
}
}
#else
xevent.xmotion.x_root = x_temp;
xevent.xmotion.y_root = y_temp;
#endif
if (!child_return)
goto found_descendent;
xevent.xmotion.subwindow = child_return;
}
break;
}
found_descendent:
/* last_window is just for debug purposes */
if (last_window != xevent.xmotion.subwindow) {
dnd_debug2 ("window crossing to %ld", xevent.xmotion.subwindow);
dnd_debug2 (" current window is %ld", over_window);
dnd_debug3 (" last_window = %ld, xmotion.subwindow = %ld", last_window, xevent.xmotion.subwindow);
#if XDND_VERSION >= 3
dnd_debug3 (" dropper_toplevel = %ld, last_dropper_toplevel.subwindow = %ld", dnd->dropper_toplevel, last_dropper_toplevel);
#endif
dnd_debug3 (" dnd_aware = %d, dnd->options & XDND_OPTION_NO_HYSTERESIS = %ld", dnd_aware, (long) dnd->options & XDND_OPTION_NO_HYSTERESIS);
}
#if XDND_VERSION < 3
/* is the new window dnd aware? if not stay in the old window */
if (over_window != xevent.xmotion.subwindow &&
last_window != xevent.xmotion.subwindow &&
(
(dnd_aware = xdnd_is_dnd_aware (dnd, xevent.xmotion.subwindow, &dnd->dragging_version, typelist))
||
(dnd->options & XDND_OPTION_NO_HYSTERESIS)
))
#else
internal_dropable = 1;
if (dnd->widget_exists && (*dnd->widget_exists) (dnd, xevent.xmotion.subwindow))
if (!xdnd_is_dnd_aware (dnd, xevent.xmotion.subwindow, &dnd->dragging_version, typelist))
internal_dropable = 0;
dnd_debug3 ("dnd->dropper_toplevel = %ld, last_dropper_toplevel = %ld\n", dnd->dropper_toplevel, last_dropper_toplevel);
if ((dnd->dropper_toplevel != last_dropper_toplevel ||
last_window != xevent.xmotion.subwindow) && internal_dropable &&
(
(dnd_aware)
||
(dnd->options & XDND_OPTION_NO_HYSTERESIS)
))
#endif
{
/* leaving window we were over */
if (over_window) {
if (dnd->stage == XDND_DRAG_STAGE_ENTERED) {
dnd_debug1 ("got leave at right stage");
dnd->stage = XDND_DRAG_STAGE_DRAGGING;
if (dnd->internal_drag) {
dnd_debug1 (" our own widget");
if (dnd->widget_apply_leave)
(*dnd->widget_apply_leave) (dnd, over_window);
} else {
dnd_debug1 (" not our widget - sending XdndLeave");
#if XDND_VERSION < 3
xdnd_send_leave (dnd, over_window, from);
#else
if (dnd->dropper_toplevel != last_dropper_toplevel) {
xdnd_send_leave (dnd, last_dropper_toplevel, from);
} else {
dnd_debug1 (" not sending leave --> dnd->dropper_toplevel == last_dropper_toplevel");
}
#endif
}
dnd->internal_drag = 0;
dnd->dropper_window = 0;
dnd->ready_to_drop = 0;
} else {
dnd_debug1 ("got leave at wrong stage - ignoring");
}
}
/* entering window we are currently over */
over_window = xevent.xmotion.subwindow;
if (dnd_aware) {
dnd_debug1 (" is dnd aware");
dnd->stage = XDND_DRAG_STAGE_ENTERED;
if (dnd->widget_exists && (*dnd->widget_exists) (dnd, over_window))
dnd->internal_drag = 1;
if (dnd->internal_drag) {
dnd_debug1 (" our own widget");
} else {
dnd_debug2 (" not our widget - sending XdndEnter to %ld", over_window);
#if XDND_VERSION < 3
xdnd_send_enter (dnd, over_window, from, typelist);
#else
if (dnd->dropper_toplevel != last_dropper_toplevel)
xdnd_send_enter (dnd, dnd->dropper_toplevel, from, typelist);
#endif
}
dnd->want_position = 1;
dnd->ready_to_drop = 0;
dnd->rectangle.width = dnd->rectangle.height = 0;
dnd->dropper_window = over_window;
/* we want an additional motion event in case the pointer enters and then stops */
XSendEvent (dnd->display, from, 0, ButtonMotionMask, &xevent_temp);
XSync (dnd->display, 0);
}
#if XDND_VERSION >= 3
last_dropper_toplevel = dnd->dropper_toplevel;
#endif
/* we are now officially in a new window */
} else {
/* got here, so we are just moving `inside' the same window */
if (dnd->stage == XDND_DRAG_STAGE_ENTERED) {
dnd->supported_action = dnd->XdndActionCopy;
dnd_debug1 ("got motion at right stage");
dnd->x = xevent.xmotion.x_root;
dnd->y = xevent.xmotion.y_root;
if (dnd->want_position || outside_rectangle (dnd->x, dnd->y, &dnd->rectangle)) {
dnd_debug1 (" want position and outside rectangle");
if (dnd->internal_drag) {
dnd_debug1 (" our own widget");
dnd->ready_to_drop = (*dnd->widget_apply_position) (dnd, over_window, from,
action, dnd->x, dnd->y, xevent.xmotion.time, typelist,
&dnd->want_position, &dnd->supported_action, &dnd->desired_type, &dnd->rectangle);
/* if not ready, keep sending positions, this check is repeated below for XdndStatus from external widgets */
if (!dnd->ready_to_drop) {
dnd->want_position = 1;
dnd->rectangle.width = dnd->rectangle.height = 0;
}
dnd_debug2 (" return action=%ld", dnd->supported_action);
} else {
#if XDND_VERSION < 3
dnd_debug3 (" not our own widget - sending XdndPosition to %ld, action %ld", over_window, action);
xdnd_send_position (dnd, over_window, from, action, dnd->x, dnd->y, xevent.xmotion.time);
#else
dnd_debug3 (" not our own widget - sending XdndPosition to %ld, action %ld", dnd->dropper_toplevel, action);
xdnd_send_position (dnd, dnd->dropper_toplevel, from, action, dnd->x, dnd->y, xevent.xmotion.time);
#endif
}
} else if (dnd->want_position) {
dnd_debug1 (" inside rectangle");
} else {
dnd_debug1 (" doesn't want position");
}
}
}
last_window = xevent.xmotion.subwindow;
break;
case ClientMessage:
dnd_debug1 ("ClientMessage recieved");
if (xevent.xclient.message_type == dnd->XdndStatus && !dnd->internal_drag) {
dnd_debug1 (" XdndStatus recieved");
if (dnd->stage == XDND_DRAG_STAGE_ENTERED
#if XDND_VERSION < 3
&& XDND_STATUS_TARGET_WIN (&xevent) == dnd->dropper_window
#endif
) {
dnd_debug1 (" XdndStatus stage correct, dropper window correct");
dnd->want_position = XDND_STATUS_WANT_POSITION (&xevent);
dnd->ready_to_drop = XDND_STATUS_WILL_ACCEPT (&xevent);
dnd->rectangle.x = XDND_STATUS_RECT_X (&xevent);
dnd->rectangle.y = XDND_STATUS_RECT_Y (&xevent);
dnd->rectangle.width = XDND_STATUS_RECT_WIDTH (&xevent);
dnd->rectangle.height = XDND_STATUS_RECT_HEIGHT (&xevent);
dnd->supported_action = dnd->XdndActionCopy;
if (dnd_version_at_least (dnd->dragging_version, 2))
dnd->supported_action = XDND_STATUS_ACTION (&xevent);
dnd_debug3 (" return action=%ld, ready=%d", dnd->supported_action, dnd->ready_to_drop);
/* if not ready, keep sending positions, this check is repeated above for internal widgets */
if (!dnd->ready_to_drop) {
dnd->want_position = 1;
dnd->rectangle.width = dnd->rectangle.height = 0;
}
dnd_debug3 (" rectangle = (x=%d, y=%d, ", dnd->rectangle.x, dnd->rectangle.y);
dnd_debug4 ("w=%d, h=%d), want_position=%d\n", dnd->rectangle.width, dnd->rectangle.height, dnd->want_position);
}
#if XDND_VERSION < 3
else if (XDND_STATUS_TARGET_WIN (&xevent) != dnd->dropper_window) {
dnd_debug3 (" XdndStatus XDND_STATUS_TARGET_WIN (&xevent) = %ld, dnd->dropper_window = %ld", XDND_STATUS_TARGET_WIN (&xevent), dnd->dropper_window);
}
#endif
else {
dnd_debug2 (" XdndStatus stage incorrect dnd->stage = %d", dnd->stage);
}
}
break;
case SelectionRequest:{
/* the target widget MAY request data, so wait for SelectionRequest */
int length = 0;
unsigned char *data = 0;
dnd_debug1 ("SelectionRequest - getting widget data");
(*dnd->widget_get_data) (dnd, from, &data, &length, xevent.xselectionrequest.target);
if (data) {
dnd_debug1 (" sending selection");
xdnd_selection_send (dnd, &xevent.xselectionrequest, data, length);
xdnd_xfree (data);
}
}
break;
}
}
if (dnd->ready_to_drop) {
Time time;
dnd_debug1 ("ready_to_drop - sending XdndDrop");
time = xevent.xbutton.time;
if (dnd->internal_drag) {
/* we are dealing with our own widget, no need to send drop events, just put the data straight */
int length = 0;
unsigned char *data = 0;
if (dnd->widget_insert_drop) {
(*dnd->widget_get_data) (dnd, from, &data, &length, dnd->desired_type);
if (data) {
if (!(*dnd->widget_insert_drop) (dnd, data, length, 0, dnd->dropper_window, from, dnd->desired_type)) {
result = dnd->supported_action; /* success - so return action to caller */
dnd_debug1 (" inserted data into widget - success");
} else {
dnd_debug1 (" inserted data into widget - failed");
}
xdnd_xfree (data);
} else {
dnd_debug1 (" got data from widget, but data is null");
}
}
} else {
xdnd_set_selection_owner (dnd, from, dnd->desired_type, time);
#if XDND_VERSION < 3
xdnd_send_drop (dnd, dnd->dropper_window, from, time);
#else
xdnd_send_drop (dnd, dnd->dropper_toplevel, from, time);
#endif
}
if (!dnd->internal_drag)
for (;;) {
XAllowEvents (dnd->display, SyncPointer, CurrentTime);
XNextEvent (dnd->display, &xevent);
if (xevent.type == ClientMessage && xevent.xclient.message_type == dnd->XdndFinished) {
dnd_debug1 ("XdndFinished");
#if XDND_VERSION < 3
if (XDND_FINISHED_TARGET_WIN (&xevent) == dnd->dropper_window) {
#endif
dnd_debug2 (" source correct - exiting event loop, action=%ld", dnd->supported_action);
result = dnd->supported_action; /* success - so return action to caller */
break;
#if XDND_VERSION < 3
}
#endif
} else if (xevent.type == Expose) {
if (dnd->handle_expose_events)
(*dnd->handle_expose_events) (dnd, &xevent);
} else if (xevent.type == MotionNotify) {
if (xevent.xmotion.time > time + (dnd->time_out ? dnd->time_out * 1000 : 10000)) { /* allow a ten second timeout as default */
dnd_debug1 ("timeout - exiting event loop");
break;
}
} else if (xevent.type == SelectionRequest && xevent.xselectionrequest.selection == dnd->XdndSelection) {
/* the target widget is going to request data, so check for SelectionRequest events */
int length = 0;
unsigned char *data = 0;
dnd_debug1 ("SelectionRequest - getting widget data");
(*dnd->widget_get_data) (dnd, from, &data, &length, xevent.xselectionrequest.target);
if (data) {
dnd_debug1 (" sending selection");
xdnd_selection_send (dnd, &xevent.xselectionrequest, data, length);
xdnd_xfree (data);
}
/* don't wait for a XdndFinished event */
if (!dnd_version_at_least (dnd->dragging_version, 2))
break;
}
}
} else {
dnd_debug1 ("not ready_to_drop - ungrabbing pointer");
}
XUngrabPointer (dnd->display, CurrentTime);
xdnd_reset (dnd);
return result;
}
/* returns non-zero if event is handled */
int xdnd_handle_drop_events (DndClass * dnd, XEvent * xevent)
{
int result = 0;
if (xevent->type == SelectionNotify) {
dnd_debug1 ("got SelectionNotify");
if (xevent->xselection.property == dnd->Xdnd_NON_PROTOCOL_ATOM && dnd->stage == XDND_DROP_STAGE_CONVERTING) {
int error;
dnd_debug1 (" property is Xdnd_NON_PROTOCOL_ATOM - getting selection");
error = xdnd_get_selection (dnd, dnd->dragger_window, xevent->xselection.property, xevent->xany.window);
/* error is not actually used, i think future versions of the protocol maybe should return
an error status to the calling window with the XdndFinished client message */
if (dnd_version_at_least (dnd->dragging_version, 2)) {
#if XDND_VERSION >= 3
xdnd_send_finished (dnd, dnd->dragger_window, dnd->dropper_toplevel, error);
#else
xdnd_send_finished (dnd, dnd->dragger_window, dnd->dropper_window, error);
#endif
dnd_debug1 (" sending finished");
}
xdnd_xfree (dnd->dragger_typelist);
xdnd_reset (dnd);
dnd->stage = XDND_DROP_STAGE_IDLE;
result = 1;
} else {
dnd_debug1 (" property is not Xdnd_NON_PROTOCOL_ATOM - ignoring");
}
} else if (xevent->type == ClientMessage) {
dnd_debug2 ("got ClientMessage to xevent->xany.window = %ld", xevent->xany.window);
if (xevent->xclient.message_type == dnd->XdndEnter) {
dnd_debug2 (" message_type is XdndEnter, version = %ld", XDND_ENTER_VERSION (xevent));
#if XDND_VERSION >= 3
if (XDND_ENTER_VERSION (xevent) < 3)
return 0;
#endif
xdnd_reset (dnd);
dnd->dragger_window = XDND_ENTER_SOURCE_WIN (xevent);
#if XDND_VERSION >= 3
dnd->dropper_toplevel = xevent->xany.window;
dnd->dropper_window = 0; /* enter goes to the top level window only,
so we don't really know what the
sub window is yet */
#else
dnd->dropper_window = xevent->xany.window;
#endif
xdnd_xfree (dnd->dragger_typelist);
if (XDND_ENTER_THREE_TYPES (xevent)) {
dnd_debug1 (" three types only");
xdnd_get_three_types (dnd, xevent, &dnd->dragger_typelist);
} else {
dnd_debug1 (" more than three types - getting list");
xdnd_get_type_list (dnd, dnd->dragger_window, &dnd->dragger_typelist);
}
if (dnd->dragger_typelist)
dnd->stage = XDND_DROP_STAGE_ENTERED;
else
dnd_debug1 (" typelist returned as zero!");
dnd->dragging_version = XDND_ENTER_VERSION (xevent);
result = 1;
} else if (xevent->xclient.message_type == dnd->XdndLeave) {
#if XDND_VERSION >= 3
if (xevent->xany.window == dnd->dropper_toplevel && dnd->dropper_window)
xevent->xany.window = dnd->dropper_window;
#endif
dnd_debug1 (" message_type is XdndLeave");
if (dnd->dragger_window == XDND_LEAVE_SOURCE_WIN (xevent) && dnd->stage == XDND_DROP_STAGE_ENTERED) {
dnd_debug1 (" leaving");
if (dnd->widget_apply_leave)
(*dnd->widget_apply_leave) (dnd, xevent->xany.window);
dnd->stage = XDND_DROP_STAGE_IDLE;
xdnd_xfree (dnd->dragger_typelist);
result = 1;
dnd->dropper_toplevel = dnd->dropper_window = 0;
} else {
dnd_debug1 (" wrong stage or from wrong window");
}
} else if (xevent->xclient.message_type == dnd->XdndPosition) {
dnd_debug2 (" message_type is XdndPosition to %ld", xevent->xany.window);
if (dnd->dragger_window == XDND_POSITION_SOURCE_WIN (xevent) && dnd->stage == XDND_DROP_STAGE_ENTERED) {
int want_position;
Atom action;
XRectangle rectangle;
Window last_window;
last_window = dnd->dropper_window;
#if XDND_VERSION >= 3
/* version 3 gives us the top-level window only. WE have to find the child that the pointer is over: */
if (1 || xevent->xany.window != dnd->dropper_toplevel || !dnd->dropper_window) {
Window parent, child, new_child = 0;
dnd->dropper_toplevel = xevent->xany.window;
parent = dnd->root_window;
child = dnd->dropper_toplevel;
for (;;) {
int xd, yd;
new_child = 0;
if (!XTranslateCoordinates (dnd->display, parent, child,
XDND_POSITION_ROOT_X (xevent), XDND_POSITION_ROOT_Y (xevent),
&xd, &yd, &new_child))
break;
if (!new_child)
break;
child = new_child;
}
dnd->dropper_window = xevent->xany.window = child;
dnd_debug2 (" child window translates to %ld", dnd->dropper_window);
} else if (xevent->xany.window == dnd->dropper_toplevel && dnd->dropper_window) {
xevent->xany.window = dnd->dropper_window;
dnd_debug2 (" child window previously found: %ld", dnd->dropper_window);
}
#endif
action = dnd->XdndActionCopy;
dnd->supported_action = dnd->XdndActionCopy;
dnd->x = XDND_POSITION_ROOT_X (xevent);
dnd->y = XDND_POSITION_ROOT_Y (xevent);
dnd->time = CurrentTime;
if (dnd_version_at_least (dnd->dragging_version, 1))
dnd->time = XDND_POSITION_TIME (xevent);
if (dnd_version_at_least (dnd->dragging_version, 1))
action = XDND_POSITION_ACTION (xevent);
#if XDND_VERSION >= 3
if (last_window && last_window != xevent->xany.window)
if (dnd->widget_apply_leave)
(*dnd->widget_apply_leave) (dnd, last_window);
#endif
dnd->will_accept = (*dnd->widget_apply_position) (dnd, xevent->xany.window, dnd->dragger_window,
action, dnd->x, dnd->y, dnd->time, dnd->dragger_typelist,
&want_position, &dnd->supported_action, &dnd->desired_type, &rectangle);
dnd_debug2 (" will accept = %d", dnd->will_accept);
#if XDND_VERSION >= 3
dnd_debug2 (" sending status of %ld", dnd->dropper_toplevel);
xdnd_send_status (dnd, dnd->dragger_window, dnd->dropper_toplevel, dnd->will_accept,
want_position, rectangle.x, rectangle.y, rectangle.width, rectangle.height, dnd->supported_action);
#else
dnd_debug2 (" sending status of %ld", xevent->xany.window);
xdnd_send_status (dnd, dnd->dragger_window, xevent->xany.window, dnd->will_accept,
want_position, rectangle.x, rectangle.y, rectangle.width, rectangle.height, dnd->supported_action);
#endif
result = 1;
} else {
dnd_debug1 (" wrong stage or from wrong window");
}
} else if (xevent->xclient.message_type == dnd->XdndDrop) {
#if XDND_VERSION >= 3
if (xevent->xany.window == dnd->dropper_toplevel && dnd->dropper_window)
xevent->xany.window = dnd->dropper_window;
#endif
dnd_debug1 (" message_type is XdndDrop");
if (dnd->dragger_window == XDND_DROP_SOURCE_WIN (xevent) && dnd->stage == XDND_DROP_STAGE_ENTERED) {
dnd->time = CurrentTime;
if (dnd_version_at_least (dnd->dragging_version, 1))
dnd->time = XDND_DROP_TIME (xevent);
if (dnd->will_accept) {
dnd_debug1 (" will_accept is true - converting selectiong");
dnd_debug2 (" my window is %ld", dnd->dropper_window);
dnd_debug2 (" source window is %ld", dnd->dragger_window);
xdnd_convert_selection (dnd, dnd->dragger_window, dnd->dropper_window, dnd->desired_type);
dnd->stage = XDND_DROP_STAGE_CONVERTING;
} else {
dnd_debug1 (" will_accept is false - sending finished");
if (dnd_version_at_least (dnd->dragging_version, 2)) {
#if XDND_VERSION >= 3
xdnd_send_finished (dnd, dnd->dragger_window, dnd->dropper_toplevel, 1);
#else
xdnd_send_finished (dnd, dnd->dragger_window, xevent->xany.window, 1);
#endif
}
xdnd_xfree (dnd->dragger_typelist);
xdnd_reset (dnd);
dnd->stage = XDND_DROP_STAGE_IDLE;
}
result = 1;
} else {
dnd_debug1 (" wrong stage or from wrong window");
}
}
}
return result;
}
/*
Following here is a sample implementation: Suppose we want a window
to recieve drops, but do not want to be concerned with setting up all
the DndClass methods. All we then do is call xdnd_get_drop() whenever a
ClientMessage is recieved. If the message has nothing to do with XDND,
xdnd_get_drop quickly returns 0. If it is a XdndEnter message, then
xdnd_get_drop enters its own XNextEvent loop and handles all XDND
protocol messages internally, returning the action requested.
You should pass a desired typelist and actionlist to xdnd_get_type.
These must be null terminated arrays of atoms, or a null pointer
if you would like any action or type to be accepted. If typelist
is null then the first type of the dragging widgets typelist will
be the one used. If actionlist is null, then only XdndActionCopy will
be accepted.
The result is stored in *data, length, type, x and y.
*data must be free'd.
*/
struct xdnd_get_drop_info {
unsigned char *drop_data;
int drop_data_length;
int x, y;
Atom return_type;
Atom return_action;
Atom *typelist;
Atom *actionlist;
};
static int widget_insert_drop (DndClass * dnd, unsigned char *data, int length, int remaining, Window into, Window from, Atom type)
{
struct xdnd_get_drop_info *i;
i = (struct xdnd_get_drop_info *) dnd->user_hook1;
if (!i->drop_data) {
i->drop_data = malloc (length);
if (!i->drop_data)
return 1;
memcpy (i->drop_data, data, length);
i->drop_data_length = length;
} else {
unsigned char *t;
t = malloc (i->drop_data_length + length);
if (!t) {
free (i->drop_data);
i->drop_data = 0;
return 1;
}
memcpy (t, i->drop_data, i->drop_data_length);
memcpy (t + i->drop_data_length, data, length);
free (i->drop_data);
i->drop_data = t;
i->drop_data_length += length;
}
return 0;
}
static int widget_apply_position (DndClass * dnd, Window widgets_window, Window from,
Atom action, int x, int y, Time t, Atom * typelist,
int *want_position, Atom * supported_action_return, Atom * desired_type,
XRectangle * rectangle)
{
int i, j;
struct xdnd_get_drop_info *info;
Atom *dropper_typelist, supported_type = 0;
Atom *supported_actions, supported_action = 0;
info = (struct xdnd_get_drop_info *) dnd->user_hook1;
dropper_typelist = info->typelist;
supported_actions = info->actionlist;
if (dropper_typelist) {
/* find a correlation: */
for (j = 0; dropper_typelist[j]; j++) {
for (i = 0; typelist[i]; i++) {
if (typelist[i] == dropper_typelist[j]) {
supported_type = typelist[i];
break;
}
}
if (supported_type)
break;
}
} else {
/* user did not specify, so return first type */
supported_type = typelist[0];
}
/* not supported, so return false */
if (!supported_type)
return 0;
if (supported_actions) {
for (j = 0; supported_actions[j]; j++) {
if (action == supported_actions[j]) {
supported_action = action;
break;
}
}
} else {
/* user did not specify */
if (action == dnd->XdndActionCopy)
supported_action = action;
}
if (!supported_action)
return 0;
*want_position = 1;
rectangle->x = rectangle->y = 0;
rectangle->width = rectangle->height = 0;
info->return_action = *supported_action_return = supported_action;
info->return_type = *desired_type = supported_type;
info->x = x;
info->y = y;
return 1;
}
Atom xdnd_get_drop (Display * display, XEvent * xevent, Atom * typelist, Atom * actionlist,
unsigned char **data, int *length, Atom * type, int *x, int *y)
{
Atom action = 0;
static int initialised = 0;
static DndClass dnd;
if (!initialised) {
xdnd_init (&dnd, display);
initialised = 1;
}
if (xevent->type != ClientMessage || xevent->xclient.message_type != dnd.XdndEnter) {
return 0;
} else {
struct xdnd_get_drop_info i;
/* setup user structure */
memset (&i, 0, sizeof (i));
i.actionlist = actionlist;
i.typelist = typelist;
dnd.user_hook1 = &i;
/* setup methods */
dnd.widget_insert_drop = widget_insert_drop;
dnd.widget_apply_position = widget_apply_position;
/* main loop */
for (;;) {
xdnd_handle_drop_events (&dnd, xevent);
if (dnd.stage == XDND_DROP_STAGE_IDLE)
break;
XNextEvent (dnd.display, xevent);
}
/* return results */
if (i.drop_data) {
*length = i.drop_data_length;
*data = i.drop_data;
action = i.return_action;
*type = i.return_type;
*x = i.x;
*y = i.y;
}
}
return action;
}
| utf-8 | 1 | GPL-2+ | 2001-2013, Blender Foundation
2001-2002, NaN Holding BV.
2009, Joshua Leung
2006-2007, 2009-2012, Nicholas Bishop
2007, 2009, Janne Karhu
2011-2012, AutoCRC
1991, Xerox Corporation
2006, Peter Schlaile
1999-2002, David Hodson
2006, Joseph Eagar
2007, NVIDIA Corporation
2009, Google Inc.
2011, Bastien Montagne
2002-2003, TNCCI Inc.
2005, Elsevier Inc.
1999, Tom Tromey
2000, Red Hat, Inc.
2006-2007, University of Dublin, Trinity College
1989-1993, 1996-1997, Free Software Foundation, Inc.
2005, Shaun Jackman
1995, Software Foundation, Inc.
1990-1998, NeoGeo BV.
2013, Campbell Barton
1999, Stephane Popinet
2000-2004, Bruno Levy
2001, softSurfer
1997-2002, Makoto Matsumoto
1997-2002, Takuji Nishimura
1996-2000, 2003-2006, Erwin Coumans
2006-2007, The Zdeno Ash Miklas
2011, Dan Eicher
1996-2011, Markus Franz Xaver Johannes Oberhumer
1996-2000, Paul Sheer
2009-2010, Mikko Mononen
2000, Gino van den Bergen
2009-2011, Jörg Hermann Müller
2006, 2008, 2011, Peter Schlaile
2009, Daniel Genrich
2001, NaN Technologies B.V.
1997-2001, Id Software, Inc.
1993-2011, Tim Riker
2012, Alex Fraser
2009, Nokia Corporation and/or its subsidiary(-ies)
2008, Frances Y. Kuo and Stephen Joe
1999, 2002, Aladdin Enterprises
2002, Industrial Light & Magic, a division of Lucas
2009-2010, Sony Pictures Imageworks Inc.
2003-2006, Erwin Coumans
2009, www.stani.be
2001-2006, 2009, Fernando Perez
2005-2010, Anthony D'Agostino
2009-2010, Paulo Gomes
2004-2005, Bruce Merry
2001-2013, MakeHuman Team
2010, Fabian Fricke
2011-2013, Alexander Nussbaumer
2004-2009, jm soler juillet
2010, Ken Nign
2009-2012, Laurea University of Applied Sciences
2010, Mariano Hidalgo
2005, Stani Michiels |
openms-2.6.0+cleaned1/src/openms_gui/include/OpenMS/VISUAL/TOPPASEdge.h | // --------------------------------------------------------------------------
// OpenMS -- Open-Source Mass Spectrometry
// --------------------------------------------------------------------------
// Copyright The OpenMS Team -- Eberhard Karls University Tuebingen,
// ETH Zurich, and Freie Universitaet Berlin 2002-2020.
//
// This software is released under a three-clause BSD license:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of any author or any participating institution
// may be used to endorse or promote products derived from this software
// without specific prior written permission.
// For a full list of authors, refer to the file AUTHORS.
// --------------------------------------------------------------------------
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL ANY OF THE AUTHORS OR THE CONTRIBUTING
// INSTITUTIONS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
// EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// --------------------------------------------------------------------------
// $Maintainer: Johannes Veit $
// $Authors: Johannes Junker, Chris Bielow $
// --------------------------------------------------------------------------
#pragma once
// OpenMS_GUI config
#include <OpenMS/VISUAL/OpenMS_GUIConfig.h>
#include <QtWidgets/QGraphicsItem>
namespace OpenMS
{
class TOPPASVertex;
class TOPPASToolVertex;
class TOPPASInputFileListVertex;
class String;
/**
@brief An edge representing a data flow in TOPPAS
Like all TOPPASVertex classes, TOPPASEdge is a subclass of QGraphicsItem and thus implements
methods to draw itself and to react on incoming events such as mouse clicks. It holds
the data needed to represent an edge between two vertices of a TOPPAS workflow.
@ingroup TOPPAS_elements
*/
class OPENMS_GUI_DLLAPI TOPPASEdge :
public QObject,
public QGraphicsItem
{
Q_OBJECT
Q_INTERFACES(QGraphicsItem)
public:
/// The status of this edge
enum EdgeStatus
{
ES_VALID,
ES_NO_TARGET_PARAM,
ES_NO_SOURCE_PARAM,
ES_FILE_EXT_MISMATCH,
ES_MERGER_EXT_MISMATCH,
ES_MERGER_WITHOUT_TOOL,
ES_NOT_READY_YET, // no input files given. We cannot know if the types will match.
ES_TOOL_API_CHANGED,
ES_UNKNOWN
};
/// Standard constructor
TOPPASEdge();
/// Constructor
TOPPASEdge(TOPPASVertex * from, const QPointF & hover_pos);
/// Copy constructor
TOPPASEdge(const TOPPASEdge & rhs);
/// Destructor
~TOPPASEdge() override;
/// Assignment operator
TOPPASEdge & operator=(const TOPPASEdge & rhs);
/// for debug output
String toString();
/// Returns the bounding rectangle of this item
QRectF boundingRect() const override;
/// Returns a more precise shape
QPainterPath shape() const override;
/// Paints the item
void paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget) override;
/// Returns the start position of this edge
QPointF startPos() const;
/// Returns the end position of this edge
QPointF endPos() const;
/// Sets the position of the hovering end while edge is being created
void setHoverPos(const QPointF & pos);
/// Sets the source vertex of this edge
void setSourceVertex(TOPPASVertex * tv);
/// Sets the target vertex of this edge
void setTargetVertex(TOPPASVertex * tv);
/// Returns the source vertex
TOPPASVertex * getSourceVertex();
/// Returns the target vertex
TOPPASVertex * getTargetVertex();
/// Call this before changing the item geometry
void prepareResize();
/// Sets the color
void setColor(const QColor & color);
/// Returns the status of this edge
EdgeStatus getEdgeStatus();
/// Sets the source output parameter index
void setSourceOutParam(int out);
/// Returns the source output parameter index
int getSourceOutParam();
/// Returns the source output parameter name
QString getSourceOutParamName();
/// Sets the target input parameter index
void setTargetInParam(int in);
/// Returns the target input parameter index
int getTargetInParam();
/// Returns the target input parameter index
QString getTargetInParamName();
/// Updates the edge color
void updateColor();
/// Emits the somethingHasChanged() signal
void emitChanged();
/// Shows the I/O mapping dialog
void showIOMappingDialog();
public slots:
/// Called by the source vertex when it has changed
void sourceHasChanged();
signals:
/// Emitted when something has changed
void somethingHasChanged();
protected:
///@name reimplemented Qt events
//@{
void mouseDoubleClickEvent(QGraphicsSceneMouseEvent * e) override;
void contextMenuEvent(QGraphicsSceneContextMenuEvent * event) override;
//@}
///@name helper methods of getEdgeStatus()
//@{
EdgeStatus getToolToolStatus_(TOPPASToolVertex * source, int source_param_index, TOPPASToolVertex * target, int target_param_index);
EdgeStatus getListToolStatus_(TOPPASInputFileListVertex * source, TOPPASToolVertex * target, int target_param_index);
//@}
/// point where the current edge touches the source or target (default) vertex
QPointF borderPoint_(bool atTargetVertex = true) const;
/// Returns the point in the @p list that is nearest to @p origin
QPointF nearestPoint_(const QPointF & origin, const QList<QPointF> & list) const;
/// Pointer to the source of this edge
TOPPASVertex * from_;
/// Pointer to the target of this edge
TOPPASVertex * to_;
/// Position of hovering end while edge is being created
QPointF hover_pos_;
/// The color
QColor color_;
/// The source output parameter index
int source_out_param_;
/// The target input parameter index
int target_in_param_;
};
}
| utf-8 | 1 | BSD-3-clause | 2002-2020 The OpenMS Team -- Eberhard Karls University Tuebingen
20002-2020 The OpenMS Team -- ETH Zurich
20002-2020 The OpenMS Team -- Freie Universitaet Berlin |
ogre-1.12-1.12.10+dfsg2/RenderSystems/GL/include/OgreGLFBORenderTexture.h | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/
#ifndef __OgreGLFBORTT_H__
#define __OgreGLFBORTT_H__
#include "OgreGLCopyingRenderTexture.h"
#include "OgreGLContext.h"
#include "OgreGLFrameBufferObject.h"
/// Extra GL constants
#define GL_DEPTH24_STENCIL8_EXT 0x88F0
namespace Ogre {
class GLFBOManager;
/** RenderTexture for GL FBO
*/
class _OgreGLExport GLFBORenderTexture: public GLRenderTexture
{
public:
GLFBORenderTexture(GLFBOManager *manager, const String &name, const GLSurfaceDesc &target, bool writeGamma, uint fsaa);
virtual void getCustomAttribute(const String& name, void* pData);
/// Override needed to deal with multisample buffers
virtual void swapBuffers();
/// Override so we can attach the depth buffer to the FBO
virtual bool attachDepthBuffer( DepthBuffer *depthBuffer );
virtual void detachDepthBuffer();
virtual void _detachDepthBuffer();
GLContext* getContext() const { return mFB.getContext(); }
GLFrameBufferObjectCommon* getFBO() { return &mFB; }
protected:
GLFrameBufferObject mFB;
};
/** Factory for GL Frame Buffer Objects, and related things.
*/
class _OgreGLExport GLFBOManager: public GLRTTManager
{
public:
GLFBOManager(bool atimode);
~GLFBOManager();
/** Bind a certain render target if it is a FBO. If it is not a FBO, bind the
main frame buffer.
*/
void bind(RenderTarget *target);
/** Unbind a certain render target. No-op for FBOs.
*/
void unbind(RenderTarget *target) {};
/** Get best depth and stencil supported for given internalFormat
*/
void getBestDepthStencil(PixelFormat internalFormat, GLenum *depthFormat, GLenum *stencilFormat);
/** Create a texture rendertarget object
*/
virtual GLFBORenderTexture *createRenderTexture(const String &name,
const GLSurfaceDesc &target, bool writeGamma, uint fsaa);
/** Request a render buffer. If format is GL_NONE, return a zero buffer.
*/
GLSurfaceDesc requestRenderBuffer(GLenum format, uint32 width, uint32 height, uint fsaa);
/** Get a FBO without depth/stencil for temporary use, like blitting between textures.
*/
GLuint getTemporaryFBO() { return mTempFBO; }
private:
/** Temporary FBO identifier
*/
GLuint mTempFBO;
/// Buggy ATI driver?
bool mATIMode;
/** Detect allowed FBO formats */
void detectFBOFormats();
GLuint _tryFormat(GLenum depthFormat, GLenum stencilFormat);
bool _tryPackedFormat(GLenum packedFormat);
void _createTempFramebuffer(GLuint internalfmt, GLuint fmt, GLenum type, GLuint &fb, GLuint &tid);
};
}
#endif
| utf-8 | 1 | MIT | 2000-2019 Torus Knot Software Ltd
2008 Renato Araujo Oliveira Filho <[email protected]>
2015 Kenny Kerr |
mygui-3.4.1+dfsg/Tools/LayoutEditor/MainWorkspaceControl.h | #ifndef _6def8530_1f19_41bb_b4a1_b4924343a908_
#define _6def8530_1f19_41bb_b4a1_b4924343a908_
#include "SeparatorPartControl.h"
#include "ToolsControl.h"
#include "WorkspaceControl.h"
namespace tools
{
class MainWorkspaceControl :
public SeparatorPartControl
{
public:
MainWorkspaceControl(MyGUI::Widget* _parent);
private:
ToolsControl* mToolsControl;
WorkspaceControl* mWorkspaceControl;
};
}
#endif
| utf-8 | 1 | Expat | 2007-2013 MyGUI Developers |
crawl-0.27.1/source/wiz-you.h | /**
* @file
* @brief Player related wizard functions.
**/
#pragma once
#include "enum.h"
#include "job-type.h"
#include "species-type.h"
#include "skill-type.h"
#ifdef WIZARD
#define FREEZE_TIME_KEY "freeze_time"
void wizard_cast_spec_spell();
void wizard_memorise_spec_spell();
void wizard_heal(bool super_heal);
void wizard_set_gold();
void wizard_set_piety();
void wizard_set_piety_to(int new_piety, bool force = false);
void wizard_exercise_skill();
void wizard_set_abyss();
void wizard_set_skill_level(skill_type skill = SK_NONE);
void wizard_set_all_skills();
void wizard_change_species();
void wizard_set_xl(bool change_skills = false);
void set_xl(const int newxl, const bool train, const bool silent=true);
bool wizard_add_mutation();
void wizard_set_stats();
void wizard_edit_durations();
void wizard_list_props();
void wizard_get_god_gift();
void wizard_toggle_xray_vision();
void wizard_freeze_time();
void wizard_god_wrath();
void wizard_god_mollify();
void wizard_transform();
void wizard_join_religion();
job_type find_job_from_string(const string &job_str);
void wizard_change_job_to(job_type job);
void wizard_xom_acts();
void wizard_suppress();
void wizard_set_zot_clock();
#endif
| utf-8 | 1 | unknown | unknown |
libopenobex-1.7.2/apps/ircp/ircp_client.c | #ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <openobex/obex.h>
#ifdef _WIN32
#include <windows.h>
#define in_addr_t unsigned long
#include <direct.h>
#include <io.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include "ircp.h"
#include "ircp_client.h"
#include "ircp_io.h"
#include "dirtraverse.h"
#include "debug.h"
#ifdef DEBUG_TCP
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#endif
#ifdef _WIN32
#define getcwd(b,len) _getcwd(b,len)
#define chdir(s) _chdir(s)
#ifndef S_ISDIR
#define S_ISDIR(x) ((x & _S_IFDIR) != 0)
#endif
#endif
#define TRUE 1
#define FALSE 0
//
// Add more data to stream.
//
static int cli_fillstream(ircp_client_t *cli, obex_object_t *object)
{
int actual;
obex_headerdata_t hdd;
DEBUG(4, "\n");
actual = read(cli->fd, cli->buf, STREAM_CHUNK);
DEBUG(4, "Read %d bytes\n", actual);
if(actual > 0) {
/* Read was ok! */
hdd.bs = cli->buf;
OBEX_ObjectAddHeader(cli->obexhandle, object, OBEX_HDR_BODY,
hdd, actual, OBEX_FL_STREAM_DATA);
}
else if(actual == 0) {
/* EOF */
hdd.bs = cli->buf;
close(cli->fd);
cli->fd = -1;
OBEX_ObjectAddHeader(cli->obexhandle, object, OBEX_HDR_BODY,
hdd, 0, OBEX_FL_STREAM_DATAEND);
}
else {
/* Error */
hdd.bs = NULL;
close(cli->fd);
cli->fd = -1;
OBEX_ObjectAddHeader(cli->obexhandle, object, OBEX_HDR_BODY,
hdd, 0, OBEX_FL_STREAM_DATA);
}
return actual;
}
//
// Incoming event from OpenOBEX.
//
static void cli_obex_event(obex_t *handle, obex_object_t *object, int mode, int event, int obex_cmd, int obex_rsp)
{
ircp_client_t *cli;
cli = OBEX_GetUserData(handle);
switch (event) {
case OBEX_EV_PROGRESS:
break;
case OBEX_EV_REQDONE:
cli->finished = TRUE;
if(obex_rsp == OBEX_RSP_SUCCESS)
cli->success = TRUE;
else
cli->success = FALSE;
cli->obex_rsp = obex_rsp;
break;
case OBEX_EV_LINKERR:
cli->finished = 1;
cli->success = FALSE;
break;
case OBEX_EV_STREAMEMPTY:
cli_fillstream(cli, object);
break;
default:
DEBUG(1, "Unknown event %d\n", event);
break;
}
}
//
// Do an OBEX request sync.
//
static int cli_sync_request(ircp_client_t *cli, obex_object_t *object)
{
int ret;
DEBUG(4, "\n");
cli->finished = FALSE;
OBEX_Request(cli->obexhandle, object);
while(cli->finished == FALSE) {
ret = OBEX_HandleInput(cli->obexhandle, 20);
DEBUG(4, "ret = %d\n", ret);
if (ret <= 0)
return -1;
}
DEBUG(4, "Done success=%d\n", cli->success);
if(cli->success)
return 1;
else
return -1;
}
//
// Create an ircp client
//
ircp_client_t *ircp_cli_open(ircp_info_cb_t infocb)
{
ircp_client_t *cli;
DEBUG(4, "\n");
cli = malloc(sizeof(ircp_client_t));
if(cli == NULL)
return NULL;
cli->infocb = infocb;
cli->fd = -1;
#ifdef DEBUG_TCP
cli->obexhandle = OBEX_Init(OBEX_TRANS_INET, cli_obex_event, 0);
#else
cli->obexhandle = OBEX_Init(OBEX_TRANS_IRDA, cli_obex_event, 0);
#endif
if(cli->obexhandle == NULL) {
goto out_err;
}
OBEX_SetUserData(cli->obexhandle, cli);
/* Buffer for body */
cli->buf = malloc(STREAM_CHUNK);
return cli;
out_err:
if(cli->obexhandle != NULL)
OBEX_Cleanup(cli->obexhandle);
free(cli);
return NULL;
}
//
// Close an ircp client
//
void ircp_cli_close(ircp_client_t *cli)
{
DEBUG(4, "\n");
ircp_return_if_fail(cli != NULL);
OBEX_Cleanup(cli->obexhandle);
free(cli->buf);
free(cli);
}
//
// Do connect as client
//
int ircp_cli_connect(ircp_client_t *cli)
{
obex_object_t *object;
int ret;
DEBUG(4, "\n");
ircp_return_val_if_fail(cli != NULL, -1);
cli->infocb(IRCP_EV_CONNECTING, "");
#ifdef DEBUG_TCP
{
struct sockaddr_in peer;
in_addr_t inaddr;
if ((inaddr = inet_addr("127.0.0.1")) != INADDR_NONE) {
memcpy((char *) &peer.sin_addr, (char *) &inaddr,
sizeof(inaddr));
}
ret = OBEX_TransportConnect(cli->obexhandle, (struct sockaddr *) &peer,
sizeof(struct sockaddr_in));
}
#else
ret = IrOBEX_TransportConnect(cli->obexhandle, "OBEX:IrXfer");
#endif
if (ret < 0) {
cli->infocb(IRCP_EV_ERR, "");
return -1;
}
object = OBEX_ObjectNew(cli->obexhandle, OBEX_CMD_CONNECT);
ret = cli_sync_request(cli, object);
if(ret < 0)
cli->infocb(IRCP_EV_ERR, "");
else
cli->infocb(IRCP_EV_OK, "");
return ret;
}
//
// Do disconnect as client
//
int ircp_cli_disconnect(ircp_client_t *cli)
{
obex_object_t *object;
int ret;
DEBUG(4, "\n");
ircp_return_val_if_fail(cli != NULL, -1);
cli->infocb(IRCP_EV_DISCONNECTING, "");
object = OBEX_ObjectNew(cli->obexhandle, OBEX_CMD_DISCONNECT);
ret = cli_sync_request(cli, object);
if(ret < 0)
cli->infocb(IRCP_EV_ERR, "");
else
cli->infocb(IRCP_EV_OK, "");
OBEX_TransportDisconnect(cli->obexhandle);
return ret;
}
//
// Do an OBEX PUT.
//
static int ircp_put_file(ircp_client_t *cli, char *localname, char *remotename)
{
obex_object_t *object;
int ret;
cli->infocb(IRCP_EV_SENDING, localname);
DEBUG(4, "Sending %s -> %s\n", localname, remotename);
ircp_return_val_if_fail(cli != NULL, -1);
object = build_object_from_file(cli->obexhandle, localname, remotename);
cli->fd = open(localname, O_RDONLY, 0);
if(cli->fd < 0) {
ret = -1;
OBEX_ObjectDelete(cli->obexhandle, object);
}
else {
ret = cli_sync_request(cli, object);
close(cli->fd);
}
if(ret < 0)
cli->infocb(IRCP_EV_ERR, localname);
else
cli->infocb(IRCP_EV_OK, localname);
return ret;
}
//
// Do OBEX SetPath
//
static int ircp_setpath(ircp_client_t *cli, char *name, int up)
{
obex_object_t *object;
obex_headerdata_t hdd;
uint8_t setpath_nohdr_data[2] = {0,};
uint8_t *ucname;
int ucname_len;
int ret;
DEBUG(4, "%s\n", name);
object = OBEX_ObjectNew(cli->obexhandle, OBEX_CMD_SETPATH);
if(up) {
setpath_nohdr_data[0] = 1;
}
else {
ucname_len = strlen(name)*2 + 2;
ucname = malloc(ucname_len);
if(ucname == NULL) {
OBEX_ObjectDelete(cli->obexhandle, object);
return -1;
}
ucname_len = OBEX_CharToUnicode(ucname, (uint8_t *) name, ucname_len);
hdd.bs = ucname;
OBEX_ObjectAddHeader(cli->obexhandle, object, OBEX_HDR_NAME, hdd, ucname_len, 0);
free(ucname);
}
OBEX_ObjectSetNonHdrData(object, setpath_nohdr_data, 2);
ret = cli_sync_request(cli, object);
return ret;
}
//
// Callback from dirtraverse.
//
static int ircp_visit(int action, char *name, char *path, void *userdata)
{
char *remotename;
int ret = -1;
DEBUG(4, "\n");
switch(action) {
case VISIT_FILE:
// Strip /'s before sending file
remotename = strrchr(name, '/');
if(remotename == NULL)
remotename = name;
else
remotename++;
ret = ircp_put_file(userdata, name, remotename);
break;
case VISIT_GOING_DEEPER:
ret = ircp_setpath(userdata, name, FALSE);
break;
case VISIT_GOING_UP:
ret = ircp_setpath(userdata, "", TRUE);
break;
}
DEBUG(4, "returning %d\n", ret);
return ret;
}
//
// Put file or directory
//
int ircp_put(ircp_client_t *cli, char *name)
{
struct stat statbuf;
char *origdir;
int err, ret;
/* Remember cwd */
origdir = getcwd(NULL, 0);
if(origdir == NULL)
return -1;
if(stat(name, &statbuf) == -1) {
return -1;
}
/* This is a directory. CD into it */
if(S_ISDIR(statbuf.st_mode)) {
char *newrealdir = NULL;
char *dirname;
err = chdir(name);
if (err < 0) {
perror("chdir:");
return -1;
}
name = ".";
/* Get real name of new wd, extract last part of and do setpath to it */
newrealdir = getcwd(NULL, 0);
dirname = strrchr(newrealdir, '/') + 1;
if(strlen(dirname) != 0)
ircp_setpath(cli, dirname, FALSE);
free(newrealdir);
}
ret = visit_all_files(name, ircp_visit, cli);
err = chdir(origdir);
free(origdir);
return ret;
}
| utf-8 | 1 | GPL-2+ | 1999, 2000, Pontus Fuchs |
glibc-2.33/io/pwd.c | /* Copyright (C) 1991-2021 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C Library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
The GNU C Library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with the GNU C Library; if not, see
<https://www.gnu.org/licenses/>. */
#include <mcheck.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int
main (void)
{
char *dir;
/* Let this program be used for debugging. */
mtrace ();
dir = getcwd ((char *) NULL, 0);
if (dir == NULL)
perror ("getcwd");
else
{
puts (dir);
free (dir);
}
return (dir == NULL ? EXIT_FAILURE : EXIT_SUCCESS);
}
| utf-8 | 1 | unknown | unknown |
linux-5.16.7/sound/soc/codecs/max9850.h | /* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* max9850.h -- codec driver for max9850
*
* Copyright (C) 2011 taskit GmbH
* Author: Christian Glindkamp <[email protected]>
*/
#ifndef _MAX9850_H
#define _MAX9850_H
#define MAX9850_STATUSA 0x00
#define MAX9850_STATUSB 0x01
#define MAX9850_VOLUME 0x02
#define MAX9850_GENERAL_PURPOSE 0x03
#define MAX9850_INTERRUPT 0x04
#define MAX9850_ENABLE 0x05
#define MAX9850_CLOCK 0x06
#define MAX9850_CHARGE_PUMP 0x07
#define MAX9850_LRCLK_MSB 0x08
#define MAX9850_LRCLK_LSB 0x09
#define MAX9850_DIGITAL_AUDIO 0x0a
#define MAX9850_CACHEREGNUM 11
/* MAX9850_DIGITAL_AUDIO */
#define MAX9850_MASTER (1<<7)
#define MAX9850_INV (1<<6)
#define MAX9850_BCINV (1<<5)
#define MAX9850_DLY (1<<3)
#define MAX9850_RTJ (1<<2)
#endif
| utf-8 | 1 | GPL-2 | 1991-2012 Linus Torvalds and many others |
vtk9-9.1.0+really9.1.0+dfsg2/Rendering/OpenGL2/vtkCompositePolyDataMapper2Internal.h | /*=========================================================================
Program: Visualization Toolkit
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#ifndef vtkCompositePolyDataMapper2Internal_h
#define vtkCompositePolyDataMapper2Internal_h
#include "vtkDeprecation.h" // for deprecation macros
#if VTK_DEPRECATION_LEVEL >= VTK_VERSION_CHECK(9, 1, 0)
#ifdef _MSC_VER
#pragma message( \
"This header has been renamed to `vtkCompositeMapperHelper2.h` to match its provided class name")
#else
#warning \
"This header has been renamed to `vtkCompositeMapperHelper2.h` to match its provided class name"
#endif
#endif
#include "vtkCompositeMapperHelper2.h"
#endif
// VTK-HeaderTest-Exclude: vtkCompositePolyDataMapper2Internal.h
| utf-8 | 1 | BSD-3-clause | 1993-2015 Ken Martin, Will Schroeder, Bill Lorensen,
Kitware inc., Sandia Corporation. |
r-cran-s2-1.0.7/src/s2/s2builderutil_closed_set_normalizer.h | // Copyright 2017 Google Inc. All Rights Reserved.
//
// 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.
//
// Author: [email protected] (Eric Veach)
#ifndef S2_S2BUILDERUTIL_CLOSED_SET_NORMALIZER_H_
#define S2_S2BUILDERUTIL_CLOSED_SET_NORMALIZER_H_
#include <vector>
#include "s2/id_set_lexicon.h"
#include "s2/s2builder_graph.h"
#include "s2/s2builderutil_find_polygon_degeneracies.h"
namespace s2builderutil {
// The purpose of this class is to allow S2Builder::Layer implementations to
// remove polygon and polyline degeneracies by converting them to polylines or
// points. Note that most clients should not use ClosedSetNormalizer itself,
// but should instead call NormalizeClosedSet defined below.
//
// A polyline degeneracy is a polyline consisting of a single degenerate edge.
// A polygon degeneracy is either a single-vertex loop (a degenerate edge from
// a vertex to itself) or a sibling edge pair (consisting of an edge and its
// corresponding reverse edge). Polygon degeneracies are further classified
// as shells or holes depending on whether they are located in the exterior or
// interior of the polygon respectively. For example, a single-vertex loop
// contained within a polygon shell would be classified as a hole.
//
// All objects are modeled as closed, i.e. polygons contain their boundaries
// and polylines contain their endpoints. Note that under this model,
// degenerate polygon shells and holes need to be handled differently.
// Degenerate shells are converted to polylines or points, whereas degenerate
// holes do not affect the set of points contained by the polygon and are
// simply discarded.
//
// Specifically, given three S2Builder::Graphs (corresponding to points,
// polylines, and polygons), this class makes the following transformations:
//
// - Polygon sibling edge pairs are either discarded (for holes) or converted
// to a pair of polyline edges (for shells).
// - Degenerate polygon edges are either discarded (for holes) or converted
// to points (for shells).
// - Degenerate polyline edges are converted to points.
//
// Optionally, this class further normalize the graphs by suppressing edges
// that are duplicates of higher-dimensional edges. In other words:
//
// - Polyline edges that coincide with polygon edges are discarded.
// - Points that coincide with polyline or polygon vertices are discarded.
//
// (When edges are discarded, any labels attached to those edges are discarded
// as well.)
//
// This class takes three graphs as input and yields three graphs as output.
// However note that the output graphs are *not* independent objects; they may
// point to data in the input graphs or data owned by the ClosedSetNormalizer
// itself. For this reason the input graphs and ClosedSetNormalizer must
// persist until the output graphs are no longer needed.
//
// Finally, note that although this class may be necessary in some situations
// (e.g., to implement the OGC Simple Features Access spec), in general the
// recommended approach to degeneracies is simply to keep them (by using a
// representation such as S2LaxPolygonShape or S2LaxPolylineShape).
// Keeping degeneracies has many advantages, such as not needing to deal with
// geometry of multiple dimensions, and being able to preserve polygon
// boundaries accurately (including degenerate holes).
class ClosedSetNormalizer {
public:
class Options {
public:
Options();
// If "suppress_lower_dimensions" is true, then the graphs are further
// normalized by discarding lower-dimensional edges that coincide with
// higher-dimensional edges.
//
// DEFAULT: true
bool suppress_lower_dimensions() const;
void set_suppress_lower_dimensions(bool suppress_lower_dimensions);
private:
bool suppress_lower_dimensions_;
};
// Constructs a ClosedSetNormalizer whose output will be three
// S2Builder::Graphs with the given "graph_options_out".
//
// REQUIRES: graph_options_out.size() == 3
// REQUIRES: graph_options_out[0].edge_type() == DIRECTED
// REQUIRES: graph_options_out[1].sibling_pairs() != {CREATE, REQUIRE}
// REQUIRES: graph_options_out[2].edge_type() == DIRECTED
ClosedSetNormalizer(
const Options& options,
const std::vector<S2Builder::GraphOptions>& graph_options_out);
// Returns the ClosedSetNormalizer options.
const Options& options() const { return options_; }
// Returns the GraphOptions that should be used to construct the input
// S2Builder::Graph of each dimension.
inline const std::vector<S2Builder::GraphOptions>& graph_options() const;
// Normalizes the input graphs and returns a new set of graphs where
// degeneracies have been discarded or converted to objects of lower
// dimension. input[d] is the graph representing edges of dimension "d".
//
// Note that the input graphs, their contents, and the ClosedSetNormalizer
// itself must persist until the output of this class is no longer needed.
// (To emphasize this requirement, a const reference is returned.)
const std::vector<S2Builder::Graph>& Run(
const std::vector<S2Builder::Graph>& input, S2Error* error);
private:
S2Builder::Graph::Edge Advance(
const S2Builder::Graph& g, S2Builder::Graph::EdgeId* id) const;
S2Builder::Graph::Edge AdvanceIncoming(
const S2Builder::Graph& g,
const std::vector<S2Builder::Graph::EdgeId>& in_edges, int* i) const;
void NormalizeEdges(const std::vector<S2Builder::Graph>& g, S2Error* error);
void AddEdge(int new_dim, const S2Builder::Graph& g,
S2Builder::Graph::EdgeId e);
bool is_suppressed(S2Builder::Graph::VertexId v) const;
Options options_;
// Requested options for the output graphs.
std::vector<S2Builder::GraphOptions> graph_options_out_;
// Options to be used to construct the input graphs.
std::vector<S2Builder::GraphOptions> graph_options_in_;
// A sentinel value that compares larger than any valid edge.
const S2Builder::Graph::Edge sentinel_;
// is_suppressed_[i] is true if vertex[i] belongs to a non-degenerate edge,
// and therefore should be suppressed from the output graph for points.
std::vector<bool> is_suppressed_;
// A vector of incoming polygon edges sorted in lexicographic order. This
// is used to suppress directed polyline edges that match a polygon edge in
// the reverse direction.
std::vector<S2Builder::Graph::EdgeId> in_edges2_;
// Output data.
std::vector<S2Builder::Graph> new_graphs_;
std::vector<S2Builder::Graph::Edge> new_edges_[3];
std::vector<S2Builder::Graph::InputEdgeIdSetId> new_input_edge_ids_[3];
IdSetLexicon new_input_edge_id_set_lexicon_;
};
// A LayerVector represents a set of layers that comprise a single object.
// Such objects are typically assembled by gathering the S2Builder::Graphs
// from all of the individual layers and processing them all at once.
using LayerVector = std::vector<std::unique_ptr<S2Builder::Layer>>;
// Given a set of three output layers (one each for dimensions 0, 1, and 2),
// returns a new set of layers that preprocess the input graphs using a
// ClosedSetNormalizer with the given options. This can be used to ensure
// that the graphs passed to "output_layers" do not contain any polyline or
// polygon degeneracies.
//
// Example showing how to compute the union of two S2ShapeIndexes containing
// points, polylines, and/or polygons, and save the result as a collection of
// S2Points, S2Polylines, and S2Polygons in another S2ShapeIndex (where
// degeneracies have been normalized to objects of lower dimension, and
// maximal polylines are constructed from undirected edges):
//
// bool ComputeUnion(const S2ShapeIndex& a, const S2ShapeIndex& b,
// MutableS2ShapeIndex* index, S2Error* error) {
// IndexedS2PolylineVectorLayer::Options polyline_options;
// polyline_options.set_edge_type(EdgeType::UNDIRECTED);
// polyline_options.set_polyline_type(Graph::PolylineType::WALK);
// polyline_options.set_duplicate_edges(DuplicateEdges::MERGE);
// LayerVector layers(3);
// layers[0] = absl::make_unique<IndexedS2PointVectorLayer>(index);
// layers[1] = absl::make_unique<IndexedS2PolylineVectorLayer>(
// index, polyline_options);
// layers[2] = absl::make_unique<IndexedS2PolygonLayer>(index);
// S2BooleanOperation op(S2BooleanOperation::OpType::UNION,
// NormalizeClosedSet(std::move(layers)));
// return op.Build(a, b, error);
// }
LayerVector NormalizeClosedSet(LayerVector output_layers,
const ClosedSetNormalizer::Options& options =
ClosedSetNormalizer::Options());
////////////////// Implementation details follow ////////////////////
inline ClosedSetNormalizer::Options::Options()
: suppress_lower_dimensions_(true) {}
inline bool ClosedSetNormalizer::Options::suppress_lower_dimensions() const {
return suppress_lower_dimensions_;
}
inline void ClosedSetNormalizer::Options::set_suppress_lower_dimensions(
bool suppress_lower_dimensions) {
suppress_lower_dimensions_ = suppress_lower_dimensions;
}
inline const std::vector<S2Builder::GraphOptions>&
ClosedSetNormalizer::graph_options() const {
return graph_options_in_;
}
} // namespace s2builderutil
#endif // S2_S2BUILDERUTIL_CLOSED_SET_NORMALIZER_H_
| utf-8 | 1 | Apache-2.0 | 2015-2020 Dewey Dunnington,
Edzer Pebesma,
Ege Rubak, |
rr-5.5.0/src/test/function_calls.c | /* -*- Mode: C; tab-width: 8; c-basic-offset: 2; indent-tabs-mode: nil; -*- */
#include "util.h"
static volatile int result = 0;
static void funcallD(int n) { result = n; }
static void funcallC(int n) {
funcallD(n);
funcallD(n);
}
static void funcallB(int n) {
funcallC(n);
funcallC(n);
}
static void funcallA(int n) {
funcallB(n);
funcallB(n);
}
static void funcall(int n) {
funcallA(n);
funcallA(n);
}
int main(void) {
funcall(1);
funcall(1);
atomic_printf("result=%d\n", result);
atomic_puts("EXIT-SUCCESS");
return 0;
}
| utf-8 | 1 | X11 and BSD-2 | 2002 Niels Provos
2013 Mozilla Foundation
2015 VMware, Inc |
fsl-5.0.8/src/fslsurface/fslsurfacemaths.cpp | //
// main.cpp
// fslsurfacemaths
//
// Created by Brian Patenaude on 3/27/11.
// Copyright 2011 University of Oxford. All rights reserved.
//
/* Part of FSL - FMRIB's Software Library
http://www.fmrib.ox.ac.uk/fsl
[email protected]
Developed at FMRIB (Oxford Centre for Functional Magnetic Resonance
Imaging of the Brain), Department of Clinical Neurology, Oxford
University, Oxford, UK
LICENCE
FMRIB Software Library, Release 5.0 (c) 2012, The University of
Oxford (the "Software")
The Software remains the property of the University of Oxford ("the
University").
The Software is distributed "AS IS" under this Licence solely for
non-commercial use in the hope that it will be useful, but in order
that the University as a charitable foundation protects its assets for
the benefit of its educational and research purposes, the University
makes clear that no condition is made or to be implied, nor is any
warranty given or to be implied, as to the accuracy of the Software,
or that it will be suitable for any particular purpose or for use
under any specific conditions. Furthermore, the University disclaims
all responsibility for the use which is made of the Software. It
further disclaims any liability for the outcomes arising from using
the Software.
The Licensee agrees to indemnify the University and hold the
University harmless from and against any and all claims, damages and
liabilities asserted by third parties (including claims for
negligence) which arise directly or indirectly from the use of the
Software or the sale of any products based on the Software.
No part of the Software may be reproduced, modified, transmitted or
transferred in any form or by any means, electronic or mechanical,
without the express permission of the University. The permission of
the University is not required if the said reproduction, modification,
transmission or transference is done without financial return, the
conditions of this Licence are imposed upon the receiver of the
product, and all original and amended source code is included in any
transmitted product. You may be held legally responsible for any
copyright infringement that is caused or encouraged by your failure to
abide by these terms and conditions.
You are not permitted under this Licence to use this Software
commercially. Use for which any financial return is received shall be
defined as commercial use, and includes (1) integration of all or part
of the source code or the Software into a product for sale or license
by or on behalf of Licensee to third parties or (2) use of the
Software or any derivative of it for research with the final aim of
developing software products for sale or license to a third party or
(3) use of the Software or any derivative of it for research with the
final aim of developing non-software products for sale or license to a
third party, or (4) use of the Software to provide any service to an
external organisation for which payment is received. If you are
interested in using the Software commercially, please contact Isis
Innovation Limited ("Isis"), the technology transfer company of the
University, to negotiate a licence. Contact details are:
[email protected] quoting reference DE/9564. */
//FSL includes
#include <newimage/newimageall.h>
//#include <fslsurface/fslsurface.h>
//#include <fslsurface/fslsurfacefns.h>
//#include <fslsurface/fslsurfaceio.h>
//#include <fslsurface/fslsurface_first.h>
#include <fslsurface.h>
#include <fslsurfacefns.h>
#include <fslsurfaceio.h>
#include <fslsurface_first.h>
#if defined(__linux) || defined(__FreeBSD_kernel__)
#else
#include <AGL/agl.h>
#endif
#include <iostream>
#include <sstream>
using namespace fslsurface_name;
using namespace NEWIMAGE;
using namespace std;
float string2float(const string & snum ){
stringstream ss;
ss<<snum;
float num;
ss>>num;
return num;
}
void Usage(){
cout<<endl<<endl;
cout<<"--------------------------- Usage ----------------------------------------------"<<endl;
cout<<endl;
cout<<" fslsurfacemaths <first_input_surface> [operations and inputs] <output> \n or \n fslsurfacemaths -reconFromBvars fike.bvars [operations and inputs] <output> \n\n"<<endl;
cout<<"Operations: (some inputs can be either surfaces or numbers) \n\n "<<endl;
cout<<" -readGIFTI <surface.gii> read GIFTI files, will obey GIFTI IO rules for append and overwriting."<<endl;
cout<<" -add <surface> : Add surface vertices to existing vertices."<<endl;
cout<<" -sub <surface> : Subtract surface vertices to existing vertices."<<endl;
cout<<" -mul <scalar> : Multiply surface vertices by a scalar."<<endl;
cout<<" -div <surface> : Add surface vertices to existing vertices."<<endl;
cout<<" -bin <scalars index> : use (scalars>0) to binarise"<<endl;
cout<<" -sc_sub <index> <value>: subtract value from scalars."<<endl;
cout<<" -sc_mul <index> <value>: multiply scalar by value."<<endl;
cout<<" -sc_mul_sc <index> <surf2> <index2>: multiple scalars of 2 surfaces."<<endl;
cout<<" -sc_sub_sc <index> <surf2> <index2> <name_of_new>: subtract scalars of 2 surfaces."<<endl;
cout<<" -sc_bin <index> : Add surface vertices to existing vertices."<<endl;
cout<<" -sc_thr <thresh> : Thresh scalars at index zero."<<endl;
cout<<" -sc_uthr <thresh> : Add surface vertices to existing vertices."<<endl;
cout<<" -cluster <index> <threshold> : Cluster scalars at index with threshold."<<endl;
cout<<" -sc_smooth <index> : Smooth scalars at index."<<endl;
cout<<" -sc_smooth_gauss_geodesic <index> <variance(mm)> : Smoot scalars at index."<<endl;
cout<<" -sc_smooth_gauss_geodesic_4D <variance(mm)> : Smoot scalars at index."<<endl;
cout<<" --projVecOntoNormals <index> : project vector onto normals"<<endl;
cout<<" -applyxfm <xfm.mat> : Apply a linear XFM matrix to the vertices and replace existing vertices (same format as FLIRT)."<<endl;
cout<<" -reg_lq <surface> <dof> <output_name_xfm.mat> : Calculate a linear XFM matrix using Least-Squares (vertex differences). XFM'd vertices replace original. Output matrix stored in 'output_name_xfm' (same format as FLIRT)."<<endl;
cout<<" -copy_CoordSystems <surf> : Copy coordinate systems for a reference surface. Typically used along side -applyxfm"<<endl;
cout<<" -normals : Calculate normals and store in vector field."<<endl;
cout<<" -vmag <vector_index> <scalar_name>: Compute vector magnitude and store in scalars"<<endl;
cout<<" -copy_verts <surface.gii> : Copy the vertices from the following surface."<<endl;
cout<<" -copy_verts2vec : inserts the vertices as vector into the vector field (no input)."<<endl;
cout<<" -copy_scalar2image3D <scalar_index> <output_image> : copies vector into a Nx1x1 NIFTI image."<<endl;
cout<<" -copy_scalars2image4D <output_image> : copies vector into a Nx1x1xNt NIFTI image."<<endl;
cout<<" -copy_image3D2scalar <image_name> <scalar_name> : insert a Nx1x1 NIFTI into the vector field. Also specify the names of the scalars"<<endl;
cout<<" -copy_image4D2scalar <image_name> <scalar_name> : insert a Nx1xM NIFTI into the vector field. Also specify the names of the scalars"<<endl;
cout<<" -copy_vec2image3D <vec_index> <output_image> : copies vector into a Nx3x1 NIFTI image."<<endl;
cout<<" -copy_image3D2vec <image_name> <vector_name> <vec_index> <xyz>: insert a Nx3x1 NIFTI into the vector field. The last arguments specifies which coomponents of the vector to copy over"<<endl;
cout<<" --sampleTimeSeries <4D image> <scalar_name>"<<endl;
cout<<" -vertexMVGLM : <list_of_surfaces> <design_matrix>"<<endl;
cout<<" -FtoP : convert F values to scalar values"<<endl;
cout<<" -fillMesh <label> <ref_im> <save_name> : Draw surface."<<endl;
cout<<" -reconFromBvars <file.bvars> : Reconstructs surfaces from .bvars files output (only first surface)."<<endl;
cout<<" -reconAllFromBvarsAndSave <file.bvars> <output_basename> : Reconstructs all surfaces from .bvars and save"<<endl;
cout<<" -marchingCubes <image> <threshold> <label> <mode> : run marching cubes."<<endl;
cout<<" -xfmToFSLScaledMM : Transform to scaled mm coordinates."<<endl;
cout<<endl;
cout<<"------------------------------------------------------------------------------"<<endl;
}
int main (int argc, char * argv[])
{
//Assume we're working with vertices will allow to change mode to scalars
// insert code here...
std::cout << "Welcome to FSL surface maths !\n";
int i_arg=1;
if (argc<2)
{
cout<<"Too few arguments."<<endl;
Usage();
return 1;
}
fslSurface<float,unsigned int> surf;// = new fslSurface<float,unsigned int>();
if ( ( string(argv[i_arg]) != "-reconFromBvars") && (string(argv[i_arg]) != "-reconAllFromBvarsAndSave") && ( string(argv[i_arg]) != "-vertexMVGLM" ) && ( string(argv[i_arg]) != "-marchingCubes" ) )
{
read_surface(surf,argv[i_arg]);
cout<<"done reading surface "<<endl;
++i_arg;
}
cout<<"iarg "<<i_arg<<" "<<argc<<endl;
while (i_arg < (argc-1)) {
cout<<"i_arg "<<i_arg<<" "<<argc<<" "<<argv[i_arg]<<endl;
string command = string(argv[i_arg]);
if (command == "-readGIFTI"){
readGIFTI(surf, argv[i_arg+1]);
i_arg += 2;
}else if (command == "-sub"){
fslSurface<float,unsigned int> surf2;
cout<<"read surface "<<endl;
read_surface(surf2, argv[i_arg+1]);
cout<<"read surface2 "<<endl;
surf-=surf2;
cout<<"done sub surface "<<endl;
i_arg += 2;
}else if (command == "-sc_sub"){
surf.subtractScalars(atoi(argv[i_arg+1]),string2float(argv[i_arg+2]));
cout<<"done sub surface "<<endl;
i_arg += 3;
}else if (command == "-sc_mul"){
surf.multiplyScalars(atoi(argv[i_arg+1]),string2float(argv[i_arg+2]));
cout<<"done mul surface "<<endl;
i_arg += 3;
}else if (command == "-sc_mul_sc"){
fslSurface<float,unsigned int> surf2;
cout<<"read surface "<<endl;
read_surface(surf2, argv[i_arg+2]);
cout<<"multiply sclars"<<endl;
multiplyScalarsByScalars(surf,atoi(argv[i_arg+1]),surf2,atoi(argv[i_arg+3]));
cout<<"done sc mul surface "<<argv[i_arg+3]<<endl;
i_arg += 4;
cout<<"done sc mul surface2 "<<argv[i_arg]<<endl;
}else if (command == "-sc_sub_sc"){
fslSurface<float,unsigned int> surf2;
cout<<"read surface "<<endl;
read_surface(surf2, argv[i_arg+2]);
cout<<"subtract sclars"<<endl;
string sc_name=argv[i_arg+4];
subtractScalarsFromScalars(surf,atoi(argv[i_arg+1]),surf2,atoi(argv[i_arg+3]),sc_name);
cout<<"done sc sub surface "<<argv[i_arg+3]<<endl;
i_arg += 5;
cout<<"done sc sub surface2 "<<argv[i_arg]<<endl;
}else if (command == "-add"){
fslSurface<float,unsigned int> surf2;// = new fslSurface<float,unsigned int>();
read_surface(surf2, argv[i_arg+1]);
surf+=surf2;
i_arg += 2;
}else if (command == "-mul"){
surf *= string2float(argv[i_arg+1]);
i_arg += 2;
cout<<"done multiply"<<endl;
}else if (command == "-div"){
surf /= string2float(argv[i_arg+1]);
i_arg += 2;
}else if (command == "-sc_bin"){
/// surf /= string2float(argv[i_arg+1]);
surf.binariseScalars(atoi(argv[i_arg+1]),0.0);
i_arg += 2;
}else if (command == "-sc_thr"){
float thresh = string2float(argv[i_arg+1]);
surf.thresholdScalars(0,thresh);
i_arg += 2;
}else if (command == "-sc_uthr"){
float thresh = string2float(argv[i_arg+1]);
surf.upperThresholdScalars(0,thresh);
i_arg += 2;
}else if (command == "-cluster"){
cout<<"foudn cluster "<<atoi(argv[i_arg+1])<<" "<<atof(argv[i_arg+2])<<endl;
fslsurface_name::cluster<float,unsigned int>(surf,atoi(argv[i_arg+1]),atof(argv[i_arg+2]));
i_arg += 3;
}else if ( command == "-sc_smooth" ){
sc_smooth_mean_neighbour<float,unsigned int>(surf,atoi(argv[i_arg+1]));
i_arg += 2;
}else if ( command == "-sc_smooth_gauss_geodesic_4D" ){
sc_smooth_gaussian_geodesic<float,unsigned int>(surf,0,string2float(argv[i_arg+1]),string2float(argv[i_arg+1])*4,true);
i_arg += 2;
}else if (command == "-sc_smooth_gauss_geodesic" ){
sc_smooth_gaussian_geodesic<float,unsigned int>(surf,atoi(argv[i_arg+1]),string2float(argv[i_arg+2]),string2float(argv[i_arg+2])*4);
i_arg+=3;
cout<<"done smooth"<<endl;
}else if (command == "-normals" ){
surf.calculateNormals(true,false);
surf.copyNormalsToVectors(0);
++i_arg;
}else if (command == "-projVecOntoNormals"){
projectVectorsOntoNormals(surf,atoi(argv[i_arg+1]));
i_arg += 2;
}else if (command == "-applyxfm"){
apply_xfm<float, unsigned int>(surf,string(argv[i_arg+1]));
i_arg += 2;
}else if (command == "-xfmToFSLScaledMM"){
// surf /= string2float(argv[i_arg+1]);
vector<double> fmat = surf.getCoordinateSystem("FSL_XFORM_SCALEDMM");
cout<<"got coordinate systrem "<<endl;
if (fmat.size() != 16)
{
cerr<<"Invalid XFM size.Most likely FSL_XFORM_SCALEDMM does not exist."<<endl;
exit (EXIT_FAILURE);
}
cout<<"xfmToFSLScaledMM Matrix"<<endl;
// vector<double> fmati = invertMatrix(fmat);
// for (vector<double>::iterator i = fmati.begin(); i!= fmati.end();++i)
// cout<<*i<<" ";
// cout<<endl;
// print<double>(fmati,"inversematrix");
apply_xfm<float, unsigned int>(surf,fmat);
// apply_xfm<float, unsigned int>(&surf,string(argv[i_arg+1]));
//apply_xfm<float, unsigned int>(&surf,fmati);
cout<<"done apply"<<endl;
++i_arg;// += 2;
}else if (command == "-applyxfmFlirt"){
// surf /= string2float(argv[i_arg+1]);
vector<double> fmat = surf.getCoordinateSystem("FSL_XFORM_SCALEDMM");
cout<<"got coordinate systrem "<<endl;
if (fmat.size() != 16)
{
cerr<<"Invalid XFM size.Most likely FSL_XFORM_SCALEDMM does not exist."<<endl;
exit (EXIT_FAILURE);
}
cout<<"invert Matrix"<<endl;
volume<float> imref;
read_volume_hdr_only(imref, argv[i_arg+2]);
vector<float> xfm = getFSLtoNIFTIxfm(imref);
// vector<double> fmati = invertMatrix(fmat);
//for (vector<double>::iterator i = fmati.begin(); i!= fmati.end();++i)
// cout<<*i<<" ";
//cout<<endl;
// print<double>(fmati,"inversematrix");
apply_xfm<float, unsigned int>(surf,fmat);
apply_xfm<float, unsigned int>(surf,string(argv[i_arg+1]));
apply_xfm<float, unsigned int>(surf,xfm);
i_arg += 3;
}else if (command == "-reg_lq"){
cout<<"reglq"<<endl;
// surf /= string2float(argv[i_arg+1]);
fslSurface<float,unsigned int> surf2;// = new fslSurface<float,unsigned int>();
cout<<"read surface "<<argv[i_arg+1]<<endl;
read_surface(surf2, argv[i_arg+1]);
unsigned int dof = atoi(argv[i_arg+2]);
cout<<"do mesh reg"<<endl;
//do registration
vector<float> xfm = meshRegLeastSq( surf, surf2, dof );
cout<<"xfm4x4 "<<xfm.size()<<endl;
//save linear xfm
ofstream fmat_out(argv[i_arg+3]);
int col=1;
for (vector<float>::iterator i = xfm.begin(); i != xfm.end(); ++i,++col)
{
if ( (col % 4) ==0)
{
fmat_out<<*i<<endl;
}else {
fmat_out<<*i<<" ";
}
}
//applyxfm to vertices
apply_xfm<float, unsigned int,float>(surf,xfm);
surf.copyCoordSystems(surf2);
i_arg += 4;
}else if ( command == "-copy_CoordSystems" )
{
fslSurface<float,unsigned int> surf2;
cout<<"read surface "<<argv[i_arg+1]<<endl;
read_surface(surf2, argv[i_arg+1]);
surf.copyCoordSystems(surf2);
i_arg += 2;
}else if (command == "-copy_verts"){
fslSurface<float,unsigned int> surf2;// = new fslSurface<float,unsigned int>();
read_surface(surf2, argv[i_arg+1]);
surf.copyVertices(surf2);
//surf+=surf2;
i_arg += 2;
}else if (command == "-copy_verts2vec"){
surf.copyVerticesToVectors();
++i_arg;
}else if (command == "-copy_scalar2image3D"){
volume<float> image(surf.getNumberOfVertices(),1,1);
unsigned int scind = atoi(argv[i_arg+1]);
unsigned int index=0;
for (std::vector< float >::const_iterator i_sc = surf.const_scbegin(scind); i_sc != surf.const_scend(scind); ++i_sc,++index)
{
image.value(index,0,0) = *i_sc;
}
save_volume(image, argv[i_arg+2]);
i_arg += 3;
if (i_arg == argc)
return 0;
}else if (command == "-copy_scalars2image4D"){
unsigned int Nt=surf.getNumberOfScalarData();
volume4D<float> image(surf.getNumberOfVertices(),1,1,Nt);
// unsigned int scind = atoi(argv[i_arg+1]);
for ( unsigned int scind = 0 ; scind < Nt;++scind)
{
unsigned int index=0;
for (std::vector< float >::const_iterator i_sc = surf.const_scbegin(scind); i_sc != surf.const_scend(scind); ++i_sc,++index)
{
image[scind].value(index,0,0) = *i_sc;
}
}
save_volume4D(image, argv[i_arg+1]);
i_arg += 2;
if (i_arg == argc)
return 0;
}else if (command == "-copy_vec2image3D"){
cout<<"FOUND copy_vec2image3D "<<endl;
unsigned int N = surf.getNumberOfVertices();
volume<float> image(N,3,1);
unsigned int vecind = atoi(argv[i_arg+1]);
unsigned int index=0;
for (vector<float>::const_iterator i_vec = surf.const_vecbegin(vecind); i_vec != surf.const_vecend(vecind); ++i_vec,++index)
{
image.value(index,0,0)=*i_vec;
++i_vec;
image.value(index,1,0)=*i_vec;
++i_vec;
image.value(index,2,0)=*i_vec;
}
cout<<"save image "<<argv[i_arg+2]<<endl;
save_volume(image, argv[i_arg+2]);
i_arg += 3;
if (i_arg == argc)
return 0;
}else if (command == "-vmag"){
cout<<"FOUND vmag "<<endl;
unsigned int N = surf.getNumberOfVertices();
unsigned int vecind = atoi(argv[i_arg+1]);
vector<float> sc(N);
vector<float>::iterator i_sc = sc.begin();
for (vector<float>::const_iterator i_vec = surf.const_vecbegin(vecind); i_vec != surf.const_vecend(vecind); ++i_vec,++i_sc)
{
float x = *i_vec;
++i_vec;
float y = *i_vec;
++i_vec;
float z = *i_vec;
*i_sc = sqrtf( x*x + y*y + z*z );
}
surf.insertScalars(sc, 0, argv[i_arg+2]);
// surf.addScalars(sc, argv[i_arg+2]);
i_arg += 3;
}else if (command == "-copy_image3D2scalar"){
unsigned int N = surf.getNumberOfVertices();
volume<float> image;
read_volume(image,argv[i_arg+1]);
if ((static_cast<unsigned int>(image.xsize())!=N) || (static_cast<unsigned int>(image.ysize())!=1) || (static_cast<unsigned int>(image.zsize())!=1))
{
cerr<<"Error : copy_image3D2scalar : Incompatible image dimensions "<<endl;
exit (EXIT_FAILURE);
}
vector<float> sc(N);
vector<float>::iterator i_sc = sc.begin();
for ( unsigned int x = 0 ; x < N; ++x,++i_sc)
{
*i_sc = image.value(x,0,0);
cout<<"sc "<<*i_sc<<endl;
}
cout<<"insert the scalars"<<endl;
surf.insertScalars(sc,0,argv[i_arg+2]);
i_arg += 3;
}else if (command == "-copy_image4D2scalar"){
unsigned int N = surf.getNumberOfVertices();
volume4D<float> image;
read_volume4D(image,argv[i_arg+1]);
if ((static_cast<unsigned int>(image.xsize())!=N) || (static_cast<unsigned int>(image.ysize())!=1) || (static_cast<unsigned int>(image.zsize())!=1))
{
cerr<<"Error : copy_image4D2scalar : Incompatible image dimensions "<<endl;
exit (EXIT_FAILURE);
}
insertScalars<float,unsigned int,float>(surf,image,argv[i_arg+2]);
/*
vector<float> sc(N);
vector<float>::iterator i_sc = sc.begin();
for ( unsigned int x = 0 ; x < N; ++x,++i_sc)
{
*i_sc = image.value(x,0,0);
cout<<"sc "<<*i_sc<<endl;
}
cout<<"insert the scalars"<<endl;
surf.insertScalars(sc,0,argv[i_arg+2]);
*/
i_arg += 3;
}else if (command == "-copy_image3D2vec"){
cout<<"FOUND copy_image3D2vec "<<endl;
unsigned int N = surf.getNumberOfVertices();
volume<float> image;
read_volume(image,argv[i_arg+1]);
cout<<"N "<<N<<" "<<image.xsize()<<" "<<image.ysize()<<" "<<image.zsize()<<endl;
if ((static_cast<unsigned int>(image.xsize())!=N) || (static_cast<unsigned int>(image.ysize()) !=3) || (static_cast<unsigned int>(image.zsize())!=1))
{
cerr<<"Error : copy_image3D2vec : Incompatible image dimensions "<<endl;
exit (EXIT_FAILURE);
}
//(N,3,1);
vector<float> vec(N*3);
string comp = string(argv[i_arg+4]);
bool cpx = false;
bool cpy = false;
bool cpz = false;
for ( unsigned int i =0 ; i<comp.length();++i)
{
string c = comp.substr(i,1);
cout<<"comp "<<c<<endl;
if (c=="x")
cpx=true;
else if (c=="y")
cpy=true;
else if (c=="z")
cpz=true;
}
vector<float>::iterator i=vec.begin();
for ( unsigned int x = 0 ; x < N; ++x)
{
if (cpx)
*i=image.value(x,0,0);
else
*i=0;
++i;
if (cpy)
*i=image.value(x,1,0);
else
*i=0;
++i;
if (cpz)
*i=image.value(x,2,0);
else
*i=0;
++i;
}
unsigned int vecind = atoi(argv[i_arg+3]);
surf.addVectors(vec, argv[i_arg+2], vecind);
i_arg += 5;
}else if ( command == "-sampleTimeSeries" ) {
volume4D<float> image;
read_volume4D(image,argv[i_arg+1]);
surf.clearScalars();
sampleTimeSeries(surf , image, argv[i_arg+2] );
i_arg += 3;
}else if ( command == "-writeTimeSeries" ){
volume4D<float> image;
read_volume4D(image,argv[i_arg+1]);
writeTimeSeries( surf , image , argv[i_arg+2]);
i_arg += 3;
}else if ( command == "-marchingCubes" ){
volume<float> image;
read_volume(image,argv[i_arg+1]);
image_dims dims(image.xsize(), image.ysize(), image.zsize(), image.xdim(), image.ydim(), image.zdim());
marchingCubes<float,unsigned int, float>( surf, image.fbegin(), dims, atof(argv[i_arg+2]), atof(argv[i_arg+3]), static_cast<MarchingCubesMode>(atof(argv[i_arg+4])));
i_arg += 5;
}else if (command == "-reconFromBvars"){
cout<<"do recon "<<endl;
char* fsldir = getenv("FSLDIR");
if (fsldir == NULL)
{
cerr<<"FSLDIR has not been set. "<<endl;
exit(EXIT_FAILURE);
}
//file.bvars,mni_template.nii.gz
// string mni = string(fsldir)+"/data/standard/MNI152_T1_1mm";
reconSurface_from_bvars( surf, string(argv[i_arg+1]));
i_arg += 2;
cout<<"done recon"<<endl;
}else if (command == "-reconAllFromBvarsAndSave"){
cout<<"do recon+save "<<argc<<" "<<i_arg<<endl;
char* fsldir = getenv("FSLDIR");
if (fsldir == NULL)
{
cerr<<"FSLDIR has not been set. "<<endl;
exit(EXIT_FAILURE);
}
//file.bvars,mni_template.nii.gz
// string mni = string(fsldir)+"/data/standard/MNI152_T1_1mm";
cout<<"recon "<< string(argv[i_arg+1])<<endl;
cout<<" "<<string(argv[i_arg+2])<<endl;
reconAllSurfacesAndSave( string(argv[i_arg+1]), string(argv[i_arg+2]));
i_arg += 3;
cout<<"done recon"<<endl;
return 0;
}else if ( command == "-FtoP" ){
cout<<"do FtoP"<<endl;
vector<int> fdofs=surf.getNonVertIntScalars("FStatDOFs");
cout<<"got dofs "<<fdofs.size()<<endl;
int df1=fdofs[0];
int df2=fdofs[1];
cout << "FStat DOFs = " << df1 << " and " << df2 << endl;
surf.insertScalars(FtoP(surf.getScalars("F-stats_EV_1"),df1,df2),0,"FtoP");
++i_arg;
}else if ( command == "-vertexMVGLM" ){
fslSurface<float,unsigned int> *surf2 = new fslSurface<float,unsigned int>();
//list of surfaces, deign matrx name, save vertices, norm name
cout<<"dovertex glm"<<endl;
vertexMVglm( *surf2, string(argv[i_arg+1]), string(argv[i_arg+2]), "",string(argv[i_arg+3]));
cout<<"done glm"<<endl;
surf=*surf2;
delete surf2;
i_arg += 4;
}else if ( command == "-warp" ){
volume4D<float> im_warp;
cout<<"warp file "<<argv[i_arg+1]<<endl;
read_volume4D(im_warp,argv[i_arg+1]);
apply_warp(surf, im_warp);
i_arg += 2;
}else if ( command == "-deform" ){
cout<<"deform"<<endl;
// int win = glutInitAndCreateWindow(&argc,argv,argv[i_arg+1]);
// glutDisplayFunc(glutDisp);
// glutIdleFunc(glutIdle);
// glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glutKeyboardFunc(keyb);
//glutRender(surf);
// glBegin(GL_TRIANGLES);
//glVertex3f(-0.5,-0.5,0.0);
//glVertex3f(0.5,0.0,0.0);
//glVertex3f(0.0,0.5,0.0);
//glEnd();
// glutMainLoop();
// glutDestroyWindow(win);
// glutSwapBuffers();
cout<<"done deform "<<endl;
i_arg+=2;
}else if ( command == "-fillMesh" ){
int lb = atoi(argv[i_arg+2]);
vector< vec3<float> > test ;
test.push_back(vec3<float>(4,5,6));
test.push_back(vec3<float>(1,3,2));
// float* fs=static_cast<float*>(&(test[0].x));
// for (int i =0 ; i< 6; ++i)
// cout<<"fs "<<fs[i]<<" "<<lb<<endl;
volume<short> mask;
read_volume(mask,argv[i_arg+1]);
mask=0;
mask=fillMesh( surf, mask, lb);
save_volume(mask,argv[i_arg+3]);
i_arg += 4;
}else{
cerr<<"Unrecognized command "<<command<<endl;
Usage();
exit(EXIT_FAILURE);
}
}
cout<<"do write "<<i_arg<<" "<<argc<<" "<<argv[i_arg]<<" "<<surf.getNumberOfCoordinateSystems()<<endl;
if (surf.getNumberOfCoordinateSystems() == 0 )
{
vector<double> identity(16,0);
identity[0] = identity[5] = identity[10] = identity[15] = 1.0;
surf.addCoordSystem(identity, "NIFTI_XFORM_UNKNOWN");
}
if (i_arg > argc)
{
cerr<<"Did not specify output name"<<endl;
exit (EXIT_FAILURE);
}
cout<<"write gifti"<<endl;
writeGIFTI(surf, string(argv[i_arg]));
cout<<"done writing gifti"<<endl;
// delete surf;
return 0;
}
| utf-8 | 1 | unknown | unknown |
qtbase-opensource-src-5.15.2+dfsg/src/widgets/doc/snippets/qlistview-dnd/model.cpp | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the documentation of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** BSD License Usage
** Alternatively, you may use this file under the terms of the BSD license
** as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
** * Redistributions of source code must retain the above copyright
** notice, this list of conditions and the following disclaimer.
** * Redistributions in binary form must reproduce the above copyright
** notice, this list of conditions and the following disclaimer in
** the documentation and/or other materials provided with the
** distribution.
** * Neither the name of The Qt Company Ltd nor the names of its
** contributors may be used to endorse or promote products derived
** from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/
/*
model.cpp
A simple model that uses a QStringList as its data source.
*/
#include <QtWidgets>
#include "model.h"
DragDropListModel::DragDropListModel(const QStringList &strings,
QObject *parent)
: QStringListModel(strings, parent)
{
}
//! [0]
bool DragDropListModel::canDropMimeData(const QMimeData *data,
Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
Q_UNUSED(action);
Q_UNUSED(row);
Q_UNUSED(parent);
if (!data->hasFormat("application/vnd.text.list"))
return false;
if (column > 0)
return false;
return true;
}
//! [0]
//! [1]
bool DragDropListModel::dropMimeData(const QMimeData *data,
Qt::DropAction action, int row, int column, const QModelIndex &parent)
{
if (!canDropMimeData(data, action, row, column, parent))
return false;
if (action == Qt::IgnoreAction)
return true;
//! [1]
//! [2]
int beginRow;
if (row != -1)
beginRow = row;
//! [2] //! [3]
else if (parent.isValid())
beginRow = parent.row();
//! [3] //! [4]
else
beginRow = rowCount(QModelIndex());
//! [4]
//! [5]
QByteArray encodedData = data->data("application/vnd.text.list");
QDataStream stream(&encodedData, QIODevice::ReadOnly);
QStringList newItems;
int rows = 0;
while (!stream.atEnd()) {
QString text;
stream >> text;
newItems << text;
++rows;
}
//! [5]
//! [6]
insertRows(beginRow, rows, QModelIndex());
for (const QString &text : qAsConst(newItems)) {
QModelIndex idx = index(beginRow, 0, QModelIndex());
setData(idx, text);
beginRow++;
}
return true;
}
//! [6]
//! [7]
Qt::ItemFlags DragDropListModel::flags(const QModelIndex &index) const
{
Qt::ItemFlags defaultFlags = QStringListModel::flags(index);
if (index.isValid())
return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
else
return Qt::ItemIsDropEnabled | defaultFlags;
}
//! [7]
//! [8]
QMimeData *DragDropListModel::mimeData(const QModelIndexList &indexes) const
{
QMimeData *mimeData = new QMimeData;
QByteArray encodedData;
QDataStream stream(&encodedData, QIODevice::WriteOnly);
for (const QModelIndex &index : indexes) {
if (index.isValid()) {
QString text = data(index, Qt::DisplayRole).toString();
stream << text;
}
}
mimeData->setData("application/vnd.text.list", encodedData);
return mimeData;
}
//! [8]
//! [9]
QStringList DragDropListModel::mimeTypes() const
{
QStringList types;
types << "application/vnd.text.list";
return types;
}
//! [9]
//! [10]
Qt::DropActions DragDropListModel::supportedDropActions() const
{
return Qt::CopyAction | Qt::MoveAction;
}
//! [10]
| utf-8 | 1 | LGPL-3 or GPL-2 | 2016-2020 The Qt Company Ltd. |
qtwebengine-opensource-src-5.15.8+dfsg/src/3rdparty/chromium/ui/display/screen.cc | // Copyright 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/display/screen.h"
#include <utility>
#include "base/check.h"
#include "base/notreached.h"
#include "ui/display/display.h"
#include "ui/display/types/display_constants.h"
#include "ui/gfx/geometry/rect.h"
namespace display {
namespace {
Screen* g_screen = nullptr;
} // namespace
Screen::Screen() : display_id_for_new_windows_(kInvalidDisplayId) {}
Screen::~Screen() = default;
// static
Screen* Screen::GetScreen() {
#if defined(OS_APPLE)
// TODO(scottmg): https://crbug.com/558054
if (!g_screen)
g_screen = CreateNativeScreen();
#endif
return g_screen;
}
// static
Screen* Screen::SetScreenInstance(Screen* instance) {
return std::exchange(g_screen, instance);
}
Display Screen::GetDisplayNearestView(gfx::NativeView view) const {
return GetDisplayNearestWindow(GetWindowForView(view));
}
display::Display Screen::GetDisplayForNewWindows() const {
display::Display display;
// Scoped value can override if it is set.
if (scoped_display_id_for_new_windows_ != kInvalidDisplayId &&
GetDisplayWithDisplayId(scoped_display_id_for_new_windows_, &display)) {
return display;
}
if (GetDisplayWithDisplayId(display_id_for_new_windows_, &display))
return display;
// Fallback to primary display.
return GetPrimaryDisplay();
}
void Screen::SetDisplayForNewWindows(int64_t display_id) {
// GetDisplayForNewWindows() handles invalid display ids.
display_id_for_new_windows_ = display_id;
}
void Screen::SetScreenSaverSuspended(bool suspend) {
NOTIMPLEMENTED_LOG_ONCE();
}
gfx::Rect Screen::ScreenToDIPRectInWindow(gfx::NativeWindow window,
const gfx::Rect& screen_rect) const {
float scale = GetDisplayNearestWindow(window).device_scale_factor();
return ScaleToEnclosingRect(screen_rect, 1.0f / scale);
}
gfx::Rect Screen::DIPToScreenRectInWindow(gfx::NativeWindow window,
const gfx::Rect& dip_rect) const {
float scale = GetDisplayNearestWindow(window).device_scale_factor();
return ScaleToEnclosingRect(dip_rect, scale);
}
bool Screen::GetDisplayWithDisplayId(int64_t display_id,
Display* display) const {
for (const Display& display_in_list : GetAllDisplays()) {
if (display_in_list.id() == display_id) {
*display = display_in_list;
return true;
}
}
return false;
}
void Screen::SetPanelRotationForTesting(int64_t display_id,
Display::Rotation rotation) {
// Not implemented.
DCHECK(false);
}
std::string Screen::GetCurrentWorkspace() {
NOTIMPLEMENTED_LOG_ONCE();
return {};
}
void Screen::SetScopedDisplayForNewWindows(int64_t display_id) {
if (display_id == scoped_display_id_for_new_windows_)
return;
// Only allow set and clear, not switch.
DCHECK(display_id == kInvalidDisplayId ^
scoped_display_id_for_new_windows_ == kInvalidDisplayId)
<< "display_id=" << display_id << ", scoped_display_id_for_new_windows_="
<< scoped_display_id_for_new_windows_;
scoped_display_id_for_new_windows_ = display_id;
}
} // namespace display
| utf-8 | 1 | LGPL-3 or GPL-2 | 2006-2021 The Chromium Authors
2016-2021 The Qt Company Ltd. |
mesa-21.3.5/src/gallium/drivers/swr/rasterizer/core/format_conversion.h | /****************************************************************************
* Copyright (C) 2014-2015 Intel Corporation. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*
* @file format_conversion.h
*
* @brief API implementation
*
******************************************************************************/
#include "format_types.h"
#include "format_traits.h"
//////////////////////////////////////////////////////////////////////////
/// @brief Load SIMD packed pixels in SOA format and converts to
/// SOA RGBA32_FLOAT format.
/// @param pSrc - source data in SOA form
/// @param dst - output data in SOA form
template <typename SIMD_T, SWR_FORMAT SrcFormat>
INLINE void SIMDCALL LoadSOA(const uint8_t* pSrc, Vec4<SIMD_T>& dst)
{
// fast path for float32
if ((FormatTraits<SrcFormat>::GetType(0) == SWR_TYPE_FLOAT) &&
(FormatTraits<SrcFormat>::GetBPC(0) == 32))
{
auto lambda = [&](int comp)
{
Float<SIMD_T> vComp =
SIMD_T::load_ps(reinterpret_cast<const float*>(pSrc + comp * sizeof(Float<SIMD_T>)));
dst.v[FormatTraits<SrcFormat>::swizzle(comp)] = vComp;
};
UnrollerL<0, FormatTraits<SrcFormat>::numComps, 1>::step(lambda);
return;
}
auto lambda = [&](int comp)
{
// load SIMD components
Float<SIMD_T> vComp;
FormatTraits<SrcFormat>::loadSOA(comp, pSrc, vComp);
// unpack
vComp = FormatTraits<SrcFormat>::unpack(comp, vComp);
// convert
if (FormatTraits<SrcFormat>::isNormalized(comp))
{
vComp = SIMD_T::cvtepi32_ps(SIMD_T::castps_si(vComp));
vComp = SIMD_T::mul_ps(vComp, SIMD_T::set1_ps(FormatTraits<SrcFormat>::toFloat(comp)));
}
dst.v[FormatTraits<SrcFormat>::swizzle(comp)] = vComp;
// is there a better way to get this from the SIMD traits?
const uint32_t SIMD_WIDTH = sizeof(typename SIMD_T::Float) / sizeof(float);
pSrc += (FormatTraits<SrcFormat>::GetBPC(comp) * SIMD_WIDTH) / 8;
};
UnrollerL<0, FormatTraits<SrcFormat>::numComps, 1>::step(lambda);
}
template <SWR_FORMAT SrcFormat>
INLINE void SIMDCALL LoadSOA(const uint8_t* pSrc, simdvector& dst)
{
LoadSOA<SIMD256, SrcFormat>(pSrc, dst);
}
template <SWR_FORMAT SrcFormat>
INLINE void SIMDCALL LoadSOA(const uint8_t* pSrc, simd16vector& dst)
{
LoadSOA<SIMD512, SrcFormat>(pSrc, dst);
}
//////////////////////////////////////////////////////////////////////////
/// @brief Clamps the given component based on the requirements on the
/// Format template arg
/// @param vComp - SIMD vector of floats
/// @param Component - component
template <typename SIMD_T, SWR_FORMAT Format>
INLINE Float<SIMD_T> SIMDCALL Clamp(Float<SIMD_T> const& v, uint32_t Component)
{
Float<SIMD_T> vComp = v;
if (Component >= 4 || Component < 0)
{
// Component shouldn't out of <0;3> range
assert(false);
return vComp;
}
if (FormatTraits<Format>::isNormalized(Component))
{
if (FormatTraits<Format>::GetType(Component) == SWR_TYPE_UNORM)
{
vComp = SIMD_T::max_ps(vComp, SIMD_T::setzero_ps());
}
if (FormatTraits<Format>::GetType(Component) == SWR_TYPE_SNORM)
{
vComp = SIMD_T::max_ps(vComp, SIMD_T::set1_ps(-1.0f));
}
vComp = SIMD_T::min_ps(vComp, SIMD_T::set1_ps(1.0f));
}
else if (FormatTraits<Format>::GetBPC(Component) < 32)
{
if (FormatTraits<Format>::GetType(Component) == SWR_TYPE_UINT)
{
int iMax = (1 << FormatTraits<Format>::GetBPC(Component)) - 1;
int iMin = 0;
Integer<SIMD_T> vCompi = SIMD_T::castps_si(vComp);
vCompi = SIMD_T::max_epu32(vCompi, SIMD_T::set1_epi32(iMin));
vCompi = SIMD_T::min_epu32(vCompi, SIMD_T::set1_epi32(iMax));
vComp = SIMD_T::castsi_ps(vCompi);
}
else if (FormatTraits<Format>::GetType(Component) == SWR_TYPE_SINT)
{
int iMax = (1 << (FormatTraits<Format>::GetBPC(Component) - 1)) - 1;
int iMin = -1 - iMax;
Integer<SIMD_T> vCompi = SIMD_T::castps_si(vComp);
vCompi = SIMD_T::max_epi32(vCompi, SIMD_T::set1_epi32(iMin));
vCompi = SIMD_T::min_epi32(vCompi, SIMD_T::set1_epi32(iMax));
vComp = SIMD_T::castsi_ps(vCompi);
}
}
return vComp;
}
template <SWR_FORMAT Format>
INLINE simdscalar SIMDCALL Clamp(simdscalar const& v, uint32_t Component)
{
return Clamp<SIMD256, Format>(v, Component);
}
template <SWR_FORMAT Format>
INLINE simd16scalar SIMDCALL Clamp(simd16scalar const& v, uint32_t Component)
{
return Clamp<SIMD512, Format>(v, Component);
}
//////////////////////////////////////////////////////////////////////////
/// @brief Normalize the given component based on the requirements on the
/// Format template arg
/// @param vComp - SIMD vector of floats
/// @param Component - component
template <typename SIMD_T, SWR_FORMAT Format>
INLINE Float<SIMD_T> SIMDCALL Normalize(Float<SIMD_T> const& vComp, uint32_t Component)
{
Float<SIMD_T> r = vComp;
if (FormatTraits<Format>::isNormalized(Component))
{
r = SIMD_T::mul_ps(r, SIMD_T::set1_ps(FormatTraits<Format>::fromFloat(Component)));
r = SIMD_T::castsi_ps(SIMD_T::cvtps_epi32(r));
}
return r;
}
template <SWR_FORMAT Format>
INLINE simdscalar SIMDCALL Normalize(simdscalar const& vComp, uint32_t Component)
{
return Normalize<SIMD256, Format>(vComp, Component);
}
template <SWR_FORMAT Format>
INLINE simd16scalar SIMDCALL Normalize(simd16scalar const& vComp, uint32_t Component)
{
return Normalize<SIMD512, Format>(vComp, Component);
}
//////////////////////////////////////////////////////////////////////////
/// @brief Convert and store simdvector of pixels in SOA
/// RGBA32_FLOAT to SOA format
/// @param src - source data in SOA form
/// @param dst - output data in SOA form
template <typename SIMD_T, SWR_FORMAT DstFormat>
INLINE void SIMDCALL StoreSOA(const Vec4<SIMD_T>& src, uint8_t* pDst)
{
// fast path for float32
if ((FormatTraits<DstFormat>::GetType(0) == SWR_TYPE_FLOAT) &&
(FormatTraits<DstFormat>::GetBPC(0) == 32))
{
for (uint32_t comp = 0; comp < FormatTraits<DstFormat>::numComps; ++comp)
{
Float<SIMD_T> vComp = src.v[FormatTraits<DstFormat>::swizzle(comp)];
// Gamma-correct
if (FormatTraits<DstFormat>::isSRGB)
{
if (comp < 3) // Input format is always RGBA32_FLOAT.
{
vComp = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(comp, vComp);
}
}
SIMD_T::store_ps(reinterpret_cast<float*>(pDst + comp * sizeof(simd16scalar)), vComp);
}
return;
}
auto lambda = [&](int comp) {
Float<SIMD_T> vComp = src.v[FormatTraits<DstFormat>::swizzle(comp)];
// Gamma-correct
if (FormatTraits<DstFormat>::isSRGB)
{
if (comp < 3) // Input format is always RGBA32_FLOAT.
{
vComp = FormatTraits<R32G32B32A32_FLOAT>::convertSrgb(comp, vComp);
}
}
// clamp
vComp = Clamp<SIMD_T, DstFormat>(vComp, comp);
// normalize
vComp = Normalize<SIMD_T, DstFormat>(vComp, comp);
// pack
vComp = FormatTraits<DstFormat>::pack(comp, vComp);
// store
FormatTraits<DstFormat>::storeSOA(comp, pDst, vComp);
// is there a better way to get this from the SIMD traits?
const uint32_t SIMD_WIDTH = sizeof(typename SIMD_T::Float) / sizeof(float);
pDst += (FormatTraits<DstFormat>::GetBPC(comp) * SIMD_WIDTH) / 8;
};
UnrollerL<0, FormatTraits<DstFormat>::numComps, 1>::step(lambda);
}
template <SWR_FORMAT DstFormat>
INLINE void SIMDCALL StoreSOA(const simdvector& src, uint8_t* pDst)
{
StoreSOA<SIMD256, DstFormat>(src, pDst);
}
template <SWR_FORMAT DstFormat>
INLINE void SIMDCALL StoreSOA(const simd16vector& src, uint8_t* pDst)
{
StoreSOA<SIMD512, DstFormat>(src, pDst);
}
| utf-8 | 1 | MIT |
2005 Aapo Tahkola
2011 Adam Rak <[email protected]>
2014 Adrián Arroyo Calle <[email protected]>
2010-2018 Advanced Micro Devices, Inc.
2002-2012 Apple Inc.
2009 Artur Wyszynski <[email protected]>
2000-2001 ATI Technologies Inc.
2015-2016 Axel Davy <[email protected]>
1988-2004 Bart Massey
2016 Bas Nieuwenhuizen
2011 Benjamin Franzke
2005-2008 Ben Skeggs
2015 Boyan Ding
1999-2016 Brian Paul
2014-2018 Broadcom
2011 Bryan Cain
2007 Carl Worth
2009-2011 Chia-I Wu <[email protected]>
2016 Christian Gmeiner <[email protected]>
2010-2014 Christian König
2010-2012 Christoph Bumiller
2014-2017 Connor Abbott
2008-2010 Corbin Simpson
1999-2016 Dave Airlie
2008 Dennis Smit
2012-2017 Etnaviv Project
2003 Felix Kuehling
2009-2016 Francisco Jerez
2008-2010 George Sapountzis <[email protected]>
2017 Gert Wollny
2013-2017 Google, Inc.
2017 Grazvydas Ignotas
2013 Gregory Hainaut <[email protected]>
2002 Greg Parker
2013 Grigori Goronzy <[email protected]>
2008-2013 Haiku, Inc.
2002-2006 IBM Corporation
2011-2017 Ilia Mirkin
2006-2018 Intel Corporation
2007-2012 Jakob Bornecrantz
2017 Jason Ekstrand
2008-2010 Jerome Glisse <[email protected]>
2009-2013 Joakim Sindholt <[email protected]>
2007 Joe Perches <[email protected]>
2006 John Maddock
2014-2017 Jon Turney
2008-2009 Jose Fonseca
1988-2017 Keith Packard
1997 Keith Whitwell
2011 Lauri Kasanen
2010 Luca Barbieri
2010-2013 LunarG, Inc.
2011-2013 Maarten Lankhorst
2008-2010 Maciej Cencora <[email protected]>
2010-2014 Marek Olšák <[email protected]>
2011 Morgan Armand <[email protected]>
2016 Nayan Deshmukh
2004-2009 Nicolai Haehnle <[email protected]>
2007-2013 Nouveau Project
2012-2018 NVIDIA Corporation
2010 Orasanu Lucian
2015-2016 Patrick Rudolph <[email protected]>
2009 Pauli Nieminen
2006-2008 Philippe Houdoin
2015 Philip Taylor <[email protected]>
1998-1999 Precision Insight, Inc.
2007-2018 Red Hat, Inc.
2018 Rhys Perry
2012-2018 Rob Clark <[email protected]>
2004 Roland Scheidegger
2015 Samuel Pitoiset
1991-2000 Silicon Graphics, Inc.
2018 Stefan Schake <[email protected]>
2003-2005 Stefan Gustavson
2008 Steven G. Johnson
2016 Steven Toth <[email protected]>
2011-2014 The Chromium OS authors
2007-2013 The Nouveau Project
2001-2004 The SCons Foundation
2002 The Weather Channel, Inc.
2006 Thierry Reding <[email protected]>
2010 Thomas Balling Sörensen
2015-2017 Thomas Helland
1995 Thorsten Ohl
2013-2018 Timothy Arceri
2002 Todd C. Miller <[email protected]>
2010-2014 Tom Stellard <[email protected]>
2004 Torrey T. Lyons
2003-2008 Tungsten Graphics, Inc.
2012-2013 Vadim Girlin <[email protected]>
2000 VA Linux Systems Inc.
2015-2018 Valve Corporation
1998-2017 VMware, Inc.
1992 Vrije Universiteit, The Netherlands
1999 Wittawat Yamwong
2005 Zack Rusin |
linux-5.16.7/drivers/phy/socionext/phy-uniphier-usb2.c | // SPDX-License-Identifier: GPL-2.0
/*
* phy-uniphier-usb2.c - PHY driver for UniPhier USB2 controller
* Copyright 2015-2018 Socionext Inc.
* Author:
* Kunihiko Hayashi <[email protected]>
*/
#include <linux/mfd/syscon.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/of_platform.h>
#include <linux/phy/phy.h>
#include <linux/platform_device.h>
#include <linux/regmap.h>
#include <linux/regulator/consumer.h>
#define SG_USBPHY1CTRL 0x500
#define SG_USBPHY1CTRL2 0x504
#define SG_USBPHY2CTRL 0x508
#define SG_USBPHY2CTRL2 0x50c /* LD11 */
#define SG_USBPHY12PLL 0x50c /* Pro4 */
#define SG_USBPHY3CTRL 0x510
#define SG_USBPHY3CTRL2 0x514
#define SG_USBPHY4CTRL 0x518 /* Pro4 */
#define SG_USBPHY4CTRL2 0x51c /* Pro4 */
#define SG_USBPHY34PLL 0x51c /* Pro4 */
struct uniphier_u2phy_param {
u32 offset;
u32 value;
};
struct uniphier_u2phy_soc_data {
struct uniphier_u2phy_param config0;
struct uniphier_u2phy_param config1;
};
struct uniphier_u2phy_priv {
struct regmap *regmap;
struct phy *phy;
struct regulator *vbus;
const struct uniphier_u2phy_soc_data *data;
struct uniphier_u2phy_priv *next;
};
static int uniphier_u2phy_power_on(struct phy *phy)
{
struct uniphier_u2phy_priv *priv = phy_get_drvdata(phy);
int ret = 0;
if (priv->vbus)
ret = regulator_enable(priv->vbus);
return ret;
}
static int uniphier_u2phy_power_off(struct phy *phy)
{
struct uniphier_u2phy_priv *priv = phy_get_drvdata(phy);
if (priv->vbus)
regulator_disable(priv->vbus);
return 0;
}
static int uniphier_u2phy_init(struct phy *phy)
{
struct uniphier_u2phy_priv *priv = phy_get_drvdata(phy);
if (!priv->data)
return 0;
regmap_write(priv->regmap, priv->data->config0.offset,
priv->data->config0.value);
regmap_write(priv->regmap, priv->data->config1.offset,
priv->data->config1.value);
return 0;
}
static struct phy *uniphier_u2phy_xlate(struct device *dev,
struct of_phandle_args *args)
{
struct uniphier_u2phy_priv *priv = dev_get_drvdata(dev);
while (priv && args->np != priv->phy->dev.of_node)
priv = priv->next;
if (!priv) {
dev_err(dev, "Failed to find appropriate phy\n");
return ERR_PTR(-EINVAL);
}
return priv->phy;
}
static const struct phy_ops uniphier_u2phy_ops = {
.init = uniphier_u2phy_init,
.power_on = uniphier_u2phy_power_on,
.power_off = uniphier_u2phy_power_off,
.owner = THIS_MODULE,
};
static int uniphier_u2phy_probe(struct platform_device *pdev)
{
struct device *dev = &pdev->dev;
struct device_node *parent, *child;
struct uniphier_u2phy_priv *priv = NULL, *next = NULL;
struct phy_provider *phy_provider;
struct regmap *regmap;
const struct uniphier_u2phy_soc_data *data;
int ret, data_idx, ndatas;
data = of_device_get_match_data(dev);
if (WARN_ON(!data))
return -EINVAL;
/* get number of data */
for (ndatas = 0; data[ndatas].config0.offset; ndatas++)
;
parent = of_get_parent(dev->of_node);
regmap = syscon_node_to_regmap(parent);
of_node_put(parent);
if (IS_ERR(regmap)) {
dev_err(dev, "Failed to get regmap\n");
return PTR_ERR(regmap);
}
for_each_child_of_node(dev->of_node, child) {
priv = devm_kzalloc(dev, sizeof(*priv), GFP_KERNEL);
if (!priv) {
ret = -ENOMEM;
goto out_put_child;
}
priv->regmap = regmap;
priv->vbus = devm_regulator_get_optional(dev, "vbus");
if (IS_ERR(priv->vbus)) {
if (PTR_ERR(priv->vbus) == -EPROBE_DEFER) {
ret = PTR_ERR(priv->vbus);
goto out_put_child;
}
priv->vbus = NULL;
}
priv->phy = devm_phy_create(dev, child, &uniphier_u2phy_ops);
if (IS_ERR(priv->phy)) {
dev_err(dev, "Failed to create phy\n");
ret = PTR_ERR(priv->phy);
goto out_put_child;
}
ret = of_property_read_u32(child, "reg", &data_idx);
if (ret) {
dev_err(dev, "Failed to get reg property\n");
goto out_put_child;
}
if (data_idx < ndatas)
priv->data = &data[data_idx];
else
dev_warn(dev, "No phy configuration: %s\n",
child->full_name);
phy_set_drvdata(priv->phy, priv);
priv->next = next;
next = priv;
}
dev_set_drvdata(dev, priv);
phy_provider = devm_of_phy_provider_register(dev,
uniphier_u2phy_xlate);
return PTR_ERR_OR_ZERO(phy_provider);
out_put_child:
of_node_put(child);
return ret;
}
static const struct uniphier_u2phy_soc_data uniphier_pro4_data[] = {
{
.config0 = { SG_USBPHY1CTRL, 0x05142400 },
.config1 = { SG_USBPHY12PLL, 0x00010010 },
},
{
.config0 = { SG_USBPHY2CTRL, 0x05142400 },
.config1 = { SG_USBPHY12PLL, 0x00010010 },
},
{
.config0 = { SG_USBPHY3CTRL, 0x05142400 },
.config1 = { SG_USBPHY34PLL, 0x00010010 },
},
{
.config0 = { SG_USBPHY4CTRL, 0x05142400 },
.config1 = { SG_USBPHY34PLL, 0x00010010 },
},
{ /* sentinel */ }
};
static const struct uniphier_u2phy_soc_data uniphier_ld11_data[] = {
{
.config0 = { SG_USBPHY1CTRL, 0x82280000 },
.config1 = { SG_USBPHY1CTRL2, 0x00000106 },
},
{
.config0 = { SG_USBPHY2CTRL, 0x82280000 },
.config1 = { SG_USBPHY2CTRL2, 0x00000106 },
},
{
.config0 = { SG_USBPHY3CTRL, 0x82280000 },
.config1 = { SG_USBPHY3CTRL2, 0x00000106 },
},
{ /* sentinel */ }
};
static const struct of_device_id uniphier_u2phy_match[] = {
{
.compatible = "socionext,uniphier-pro4-usb2-phy",
.data = &uniphier_pro4_data,
},
{
.compatible = "socionext,uniphier-ld11-usb2-phy",
.data = &uniphier_ld11_data,
},
{ /* sentinel */ }
};
MODULE_DEVICE_TABLE(of, uniphier_u2phy_match);
static struct platform_driver uniphier_u2phy_driver = {
.probe = uniphier_u2phy_probe,
.driver = {
.name = "uniphier-usb2-phy",
.of_match_table = uniphier_u2phy_match,
},
};
module_platform_driver(uniphier_u2phy_driver);
MODULE_AUTHOR("Kunihiko Hayashi <[email protected]>");
MODULE_DESCRIPTION("UniPhier PHY driver for USB2 controller");
MODULE_LICENSE("GPL v2");
| utf-8 | 1 | GPL-2 | 1991-2012 Linus Torvalds and many others |
linux-5.16.7/include/linux/mfd/da9150/core.h | /* SPDX-License-Identifier: GPL-2.0-or-later */
/*
* DA9150 MFD Driver - Core Data
*
* Copyright (c) 2014 Dialog Semiconductor
*
* Author: Adam Thomson <[email protected]>
*/
#ifndef __DA9150_CORE_H
#define __DA9150_CORE_H
#include <linux/device.h>
#include <linux/i2c.h>
#include <linux/interrupt.h>
#include <linux/regmap.h>
/* I2C address paging */
#define DA9150_REG_PAGE_SHIFT 8
#define DA9150_REG_PAGE_MASK 0xFF
/* IRQs */
#define DA9150_NUM_IRQ_REGS 4
#define DA9150_IRQ_VBUS 0
#define DA9150_IRQ_CHG 1
#define DA9150_IRQ_TCLASS 2
#define DA9150_IRQ_TJUNC 3
#define DA9150_IRQ_VFAULT 4
#define DA9150_IRQ_CONF 5
#define DA9150_IRQ_DAT 6
#define DA9150_IRQ_DTYPE 7
#define DA9150_IRQ_ID 8
#define DA9150_IRQ_ADP 9
#define DA9150_IRQ_SESS_END 10
#define DA9150_IRQ_SESS_VLD 11
#define DA9150_IRQ_FG 12
#define DA9150_IRQ_GP 13
#define DA9150_IRQ_TBAT 14
#define DA9150_IRQ_GPIOA 15
#define DA9150_IRQ_GPIOB 16
#define DA9150_IRQ_GPIOC 17
#define DA9150_IRQ_GPIOD 18
#define DA9150_IRQ_GPADC 19
#define DA9150_IRQ_WKUP 20
/* I2C sub-device address */
#define DA9150_QIF_I2C_ADDR_LSB 0x5
struct da9150_fg_pdata {
u32 update_interval; /* msecs */
u8 warn_soc_lvl; /* % value */
u8 crit_soc_lvl; /* % value */
};
struct da9150_pdata {
int irq_base;
struct da9150_fg_pdata *fg_pdata;
};
struct da9150 {
struct device *dev;
struct regmap *regmap;
struct i2c_client *core_qif;
struct regmap_irq_chip_data *regmap_irq_data;
int irq;
int irq_base;
};
/* Device I/O - Query Interface for FG and standard register access */
void da9150_read_qif(struct da9150 *da9150, u8 addr, int count, u8 *buf);
void da9150_write_qif(struct da9150 *da9150, u8 addr, int count, const u8 *buf);
u8 da9150_reg_read(struct da9150 *da9150, u16 reg);
void da9150_reg_write(struct da9150 *da9150, u16 reg, u8 val);
void da9150_set_bits(struct da9150 *da9150, u16 reg, u8 mask, u8 val);
void da9150_bulk_read(struct da9150 *da9150, u16 reg, int count, u8 *buf);
void da9150_bulk_write(struct da9150 *da9150, u16 reg, int count, const u8 *buf);
#endif /* __DA9150_CORE_H */
| utf-8 | 1 | GPL-2 | 1991-2012 Linus Torvalds and many others |
goldencheetah-3.5/qwt/src/qwt_event_pattern.cpp | /* -*- mode: C++ ; c-file-style: "stroustrup" -*- *****************************
* Qwt Widget Library
* Copyright (C) 1997 Josef Wilgen
* Copyright (C) 2002 Uwe Rathmann
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the Qwt License, Version 1.0
*****************************************************************************/
#include "qwt_event_pattern.h"
#include <qevent.h>
/*!
Constructor
\sa MousePatternCode, KeyPatternCode
*/
QwtEventPattern::QwtEventPattern():
d_mousePattern( MousePatternCount ),
d_keyPattern( KeyPatternCount )
{
initKeyPattern();
initMousePattern( 3 );
}
//! Destructor
QwtEventPattern::~QwtEventPattern()
{
}
/*!
Set default mouse patterns, depending on the number of mouse buttons
\param numButtons Number of mouse buttons ( <= 3 )
\sa MousePatternCode
*/
void QwtEventPattern::initMousePattern( int numButtons )
{
d_mousePattern.resize( MousePatternCount );
switch ( numButtons )
{
case 1:
{
setMousePattern( MouseSelect1, Qt::LeftButton );
setMousePattern( MouseSelect2, Qt::LeftButton, Qt::ControlModifier );
setMousePattern( MouseSelect3, Qt::LeftButton, Qt::AltModifier );
break;
}
case 2:
{
setMousePattern( MouseSelect1, Qt::LeftButton );
setMousePattern( MouseSelect2, Qt::RightButton );
setMousePattern( MouseSelect3, Qt::LeftButton, Qt::AltModifier );
break;
}
default:
{
setMousePattern( MouseSelect1, Qt::LeftButton );
setMousePattern( MouseSelect2, Qt::RightButton );
setMousePattern( MouseSelect3, Qt::MidButton );
}
}
setMousePattern( MouseSelect4, d_mousePattern[MouseSelect1].button,
d_mousePattern[MouseSelect1].modifiers | Qt::ShiftModifier );
setMousePattern( MouseSelect5, d_mousePattern[MouseSelect2].button,
d_mousePattern[MouseSelect2].modifiers | Qt::ShiftModifier );
setMousePattern( MouseSelect6, d_mousePattern[MouseSelect3].button,
d_mousePattern[MouseSelect3].modifiers | Qt::ShiftModifier );
}
/*!
Set default mouse patterns.
\sa KeyPatternCode
*/
void QwtEventPattern::initKeyPattern()
{
d_keyPattern.resize( KeyPatternCount );
setKeyPattern( KeySelect1, Qt::Key_Return );
setKeyPattern( KeySelect2, Qt::Key_Space );
setKeyPattern( KeyAbort, Qt::Key_Escape );
setKeyPattern( KeyLeft, Qt::Key_Left );
setKeyPattern( KeyRight, Qt::Key_Right );
setKeyPattern( KeyUp, Qt::Key_Up );
setKeyPattern( KeyDown, Qt::Key_Down );
setKeyPattern( KeyRedo, Qt::Key_Plus );
setKeyPattern( KeyUndo, Qt::Key_Minus );
setKeyPattern( KeyHome, Qt::Key_Escape );
}
/*!
Change one mouse pattern
\param pattern Index of the pattern
\param button Button
\param modifiers Keyboard modifiers
\sa QMouseEvent
*/
void QwtEventPattern::setMousePattern( MousePatternCode pattern,
Qt::MouseButton button, Qt::KeyboardModifiers modifiers )
{
if ( pattern >= 0 && pattern < MousePatternCount )
{
d_mousePattern[ pattern ].button = button;
d_mousePattern[ pattern ].modifiers = modifiers;
}
}
/*!
Change one key pattern
\param pattern Index of the pattern
\param key Key
\param modifiers Keyboard modifiers
\sa QKeyEvent
*/
void QwtEventPattern::setKeyPattern( KeyPatternCode pattern,
int key, Qt::KeyboardModifiers modifiers )
{
if ( pattern >= 0 && pattern < KeyPatternCount )
{
d_keyPattern[ pattern ].key = key;
d_keyPattern[ pattern ].modifiers = modifiers;
}
}
//! Change the mouse event patterns
void QwtEventPattern::setMousePattern( const QVector<MousePattern> &pattern )
{
d_mousePattern = pattern;
}
//! Change the key event patterns
void QwtEventPattern::setKeyPattern( const QVector<KeyPattern> &pattern )
{
d_keyPattern = pattern;
}
//! \return Mouse pattern
const QVector<QwtEventPattern::MousePattern> &
QwtEventPattern::mousePattern() const
{
return d_mousePattern;
}
//! \return Key pattern
const QVector<QwtEventPattern::KeyPattern> &
QwtEventPattern::keyPattern() const
{
return d_keyPattern;
}
//! \return Mouse pattern
QVector<QwtEventPattern::MousePattern> &QwtEventPattern::mousePattern()
{
return d_mousePattern;
}
//! \return Key pattern
QVector<QwtEventPattern::KeyPattern> &QwtEventPattern::keyPattern()
{
return d_keyPattern;
}
/*!
\brief Compare a mouse event with an event pattern.
A mouse event matches the pattern when both have the same button
value and in the state value the same key flags(Qt::KeyButtonMask)
are set.
\param code Index of the event pattern
\param event Mouse event
\return true if matches
\sa keyMatch()
*/
bool QwtEventPattern::mouseMatch( MousePatternCode code,
const QMouseEvent *event ) const
{
if ( code >= 0 && code < MousePatternCount )
return mouseMatch( d_mousePattern[ code ], event );
return false;
}
/*!
\brief Compare a mouse event with an event pattern.
A mouse event matches the pattern when both have the same button
value and in the state value the same key flags(Qt::KeyButtonMask)
are set.
\param pattern Mouse event pattern
\param event Mouse event
\return true if matches
\sa keyMatch()
*/
bool QwtEventPattern::mouseMatch( const MousePattern &pattern,
const QMouseEvent *event ) const
{
if ( event == NULL )
return false;
const MousePattern mousePattern( event->button(), event->modifiers() );
return mousePattern == pattern;
}
/*!
\brief Compare a key event with an event pattern.
A key event matches the pattern when both have the same key
value and in the state value the same key flags (Qt::KeyButtonMask)
are set.
\param code Index of the event pattern
\param event Key event
\return true if matches
\sa mouseMatch()
*/
bool QwtEventPattern::keyMatch( KeyPatternCode code,
const QKeyEvent *event ) const
{
if ( code >= 0 && code < KeyPatternCount )
return keyMatch( d_keyPattern[ code ], event );
return false;
}
/*!
\brief Compare a key event with an event pattern.
A key event matches the pattern when both have the same key
value and in the state value the same key flags (Qt::KeyButtonMask)
are set.
\param pattern Key event pattern
\param event Key event
\return true if matches
\sa mouseMatch()
*/
bool QwtEventPattern::keyMatch(
const KeyPattern &pattern, const QKeyEvent *event ) const
{
if ( event == NULL )
return false;
const KeyPattern keyPattern( event->key(), event->modifiers() );
return keyPattern == pattern;
}
| utf-8 | 1 | GPL-3+ | 2006-2010, Sean C. Rhea ([email protected])
2000-2015, Mark Liversedge ([email protected])
1997, Josef Wilgen
2002, Uwe Rathmann
2009, Andy M. Froncioni ([email protected])
2010, Damien Grauser ([email protected])
2009, Eric Murray ([email protected])
2009, Greg Lonnon ([email protected])
2010, Ilja Booij ([email protected])
2006-2009, Justin F. Knotzke ([email protected])
2008, J.T Conklin ([email protected])
2009, Mark Rages ([email protected])
2009, Ned Harding ([email protected])
2009, Robert Carlsen ([email protected])
2009, Steve Gribble (gribble [at] cs.washington.edu) |
linphone-desktop-4.2.5/linphone-app/src/app/providers/ImageProvider.cpp | /*
* Copyright (c) 2010-2020 Belledonne Communications SARL.
*
* This file is part of linphone-desktop
* (see https://www.linphone.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 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 <QElapsedTimer>
#include <QFileInfo>
#include <QPainter>
#include <QScreen>
#include <QSvgRenderer>
#include "app/App.hpp"
#include "components/other/colors/Colors.hpp"
#include "ImageProvider.hpp"
// =============================================================================
using namespace std;
namespace {
// Max image size in bytes. (100Kb)
constexpr qint64 MaxImageSize = 102400;
}
static void removeAttribute (QXmlStreamAttributes &readerAttributes, const QString &name) {
auto it = find_if(readerAttributes.cbegin(), readerAttributes.cend(), [&name](const QXmlStreamAttribute &attribute) {
return name == attribute.name() && !attribute.prefix().length();
});
if (it != readerAttributes.cend())
readerAttributes.remove(int(distance(readerAttributes.cbegin(), it)));
}
static QByteArray buildByteArrayAttribute (const QByteArray &name, const QByteArray &value) {
QByteArray attribute = name;
attribute.append("=\"");
attribute.append(value);
attribute.append("\" ");
return attribute;
}
static QByteArray parseFillAndStroke (QXmlStreamAttributes &readerAttributes, const Colors &colors) {
static QRegExp regex("^color-([^-]+)-(fill|stroke)$");
QByteArray attributes;
for (const auto &classValue : readerAttributes.value("class").toLatin1().split(' ')) {
regex.indexIn(classValue.trimmed());
if (Q_LIKELY(regex.pos() == -1))
continue;
const QStringList list = regex.capturedTexts();
const QVariant colorValue = colors.property(list[1].toStdString().c_str());
if (Q_UNLIKELY(!colorValue.isValid())) {
qWarning() << QStringLiteral("Color name `%1` does not exist.").arg(list[1]);
continue;
}
removeAttribute(readerAttributes, list[2]);
attributes.append(buildByteArrayAttribute(list[2].toLatin1(), colorValue.value<QColor>().name().toLatin1()));
}
return attributes;
}
static QByteArray parseStyle (QXmlStreamAttributes &readerAttributes, const Colors &colors) {
static QRegExp regex("^color-([^-]+)-style-(fill|stroke)$");
QByteArray attribute;
QSet<QString> overrode;
for (const auto &classValue : readerAttributes.value("class").toLatin1().split(' ')) {
regex.indexIn(classValue.trimmed());
if (Q_LIKELY(regex.pos() == -1))
continue;
const QStringList list = regex.capturedTexts();
overrode.insert(list[2]);
const QVariant colorValue = colors.property(list[1].toStdString().c_str());
if (Q_UNLIKELY(!colorValue.isValid())) {
qWarning() << QStringLiteral("Color name `%1` does not exist.").arg(list[1]);
continue;
}
attribute.append(list[2].toLatin1());
attribute.append(":");
attribute.append(colorValue.value<QColor>().name().toLatin1());
attribute.append(";");
}
const QByteArrayList styleValues = readerAttributes.value("style").toLatin1().split(';');
for (const auto &styleValue : styleValues) {
const QByteArrayList list = styleValue.split(':');
if (Q_UNLIKELY(list.length() > 0 && !overrode.contains(list[0]))) {
attribute.append(styleValue);
attribute.append(";");
}
}
removeAttribute(readerAttributes, "style");
if (attribute.length() > 0) {
attribute.prepend("style=\"");
attribute.append("\" ");
}
return attribute;
}
static QByteArray parseAttributes (const QXmlStreamReader &reader, const Colors &colors) {
QXmlStreamAttributes readerAttributes = reader.attributes();
QByteArray attributes = parseFillAndStroke(readerAttributes, colors);
attributes.append(parseStyle(readerAttributes, colors));
for (const auto &attribute : readerAttributes) {
const QByteArray prefix = attribute.prefix().toLatin1();
if (Q_UNLIKELY(prefix.length() > 0)) {
attributes.append(prefix);
attributes.append(":");
}
attributes.append(
buildByteArrayAttribute(attribute.name().toLatin1(), attribute.value().toLatin1())
);
}
return attributes;
}
static QByteArray parseDeclarations (const QXmlStreamReader &reader) {
QByteArray declarations;
for (const auto &declaration : reader.namespaceDeclarations()) {
const QByteArray prefix = declaration.prefix().toLatin1();
if (Q_UNLIKELY(prefix.length() > 0)) {
declarations.append("xmlns:");
declarations.append(prefix);
} else
declarations.append("xmlns");
declarations.append("=\"");
declarations.append(declaration.namespaceUri().toLatin1());
declarations.append("\" ");
}
return declarations;
}
static QByteArray parseStartDocument (const QXmlStreamReader &reader) {
QByteArray startDocument = "<?xml version=\"";
startDocument.append(reader.documentVersion().toLatin1());
startDocument.append("\" encoding=\"");
startDocument.append(reader.documentEncoding().toLatin1());
startDocument.append("\"?>");
return startDocument;
}
static QByteArray parseStartElement (const QXmlStreamReader &reader, const Colors &colors) {
QByteArray startElement = "<";
startElement.append(reader.name().toLatin1());
startElement.append(" ");
startElement.append(parseAttributes(reader, colors));
startElement.append(" ");
startElement.append(parseDeclarations(reader));
startElement.append(">");
return startElement;
}
static QByteArray parseEndElement (const QXmlStreamReader &reader) {
QByteArray endElement = "</";
endElement.append(reader.name().toLatin1());
endElement.append(">");
return endElement;
}
// -----------------------------------------------------------------------------
static QByteArray computeContent (QFile &file) {
const Colors *colors = App::getInstance()->getColors();
QByteArray content;
QXmlStreamReader reader(&file);
while (!reader.atEnd())
switch (reader.readNext()) {
case QXmlStreamReader::Comment:
case QXmlStreamReader::DTD:
case QXmlStreamReader::EndDocument:
case QXmlStreamReader::Invalid:
case QXmlStreamReader::NoToken:
case QXmlStreamReader::ProcessingInstruction:
break;
case QXmlStreamReader::StartDocument:
content.append(parseStartDocument(reader));
break;
case QXmlStreamReader::StartElement:
content.append(parseStartElement(reader, *colors));
break;
case QXmlStreamReader::EndElement:
content.append(parseEndElement(reader));
break;
case QXmlStreamReader::Characters:
content.append(reader.text().toLatin1());
break;
case QXmlStreamReader::EntityReference:
content.append(reader.name().toLatin1());
break;
}
return reader.hasError() ? QByteArray() : content;
}
// -----------------------------------------------------------------------------
const QString ImageProvider::ProviderId = "internal";
ImageProvider::ImageProvider () : QQuickImageProvider(
QQmlImageProviderBase::Image,
QQmlImageProviderBase::ForceAsynchronousImageLoading
) {}
// -----------------------------------------------------------------------------
QImage ImageProvider::requestImage (const QString &id, QSize *size, const QSize &requestedSize) {
const QString path = QStringLiteral(":%1").arg(id);
// qDebug() << QStringLiteral("Image `%1` requested with size: (%2, %3).")
// .arg(path).arg(requestedSize.width()).arg(requestedSize.height());
QElapsedTimer timer;
timer.start();
// 1. Read and update XML content.
*size = QSize();
QFile file(path);
if (Q_UNLIKELY(QFileInfo(file).size() > MaxImageSize)) {
qWarning() << QStringLiteral("Unable to open large file: `%1`.").arg(path);
return QImage();
}
if (Q_UNLIKELY(!file.open(QIODevice::ReadOnly))) {
qWarning() << QStringLiteral("Unable to open file: `%1`.").arg(path);
return QImage();
}
const QByteArray content = computeContent(file);
if (Q_UNLIKELY(!content.length())) {
qWarning() << QStringLiteral("Unable to parse file: `%1`.").arg(path);
return QImage();
}
// 2. Build svg renderer.
QSvgRenderer renderer(content);
if (Q_UNLIKELY(!renderer.isValid())) {
qWarning() << QStringLiteral("Invalid svg file: `%1`.").arg(path);
return QImage();
}
QSize askedSize = !requestedSize.isEmpty()
? requestedSize
: renderer.defaultSize() * QGuiApplication::primaryScreen()->devicePixelRatio();
// 3. Create image.
QImage image(askedSize, QImage::Format_ARGB32_Premultiplied);
if (Q_UNLIKELY(image.isNull())) {
qWarning() << QStringLiteral("Unable to create image from path: `%1`.")
.arg(path);
return QImage(); // Memory cannot be allocated.
}
image.fill(Qt::transparent);// Fill with transparent to set alpha channel
*size = image.size();
// 4. Paint!
QPainter painter(&image);
renderer.render(&painter);
// qDebug() << QStringLiteral("Image `%1` loaded in %2 milliseconds.").arg(path).arg(timer.elapsed());
return image;
}
QPixmap ImageProvider::requestPixmap (const QString &id, QSize *size, const QSize &requestedSize) {
return QPixmap::fromImage(requestImage(id, size, requestedSize));
}
| utf-8 | 1 | GPL-3+ | 2010-2020 Belledonne Communications SARL. |
avro-java-1.8.2/lang/c/src/avro/allocation.h | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to you under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
* implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#ifndef AVRO_ALLOCATION_H
#define AVRO_ALLOCATION_H
#ifdef __cplusplus
extern "C" {
#define CLOSE_EXTERN }
#else
#define CLOSE_EXTERN
#endif
#include <stdlib.h>
/*
* Allocation interface. You can provide a custom allocator for the
* library, should you wish. The allocator is provided as a single
* generic function, which can emulate the standard malloc, realloc, and
* free functions. The design of this allocation interface is inspired
* by the implementation of the Lua interpreter.
*
* The ptr parameter will be the location of any existing memory
* buffer. The osize parameter will be the size of this existing
* buffer. If ptr is NULL, then osize will be 0. The nsize parameter
* will be the size of the new buffer, or 0 if the new buffer should be
* freed.
*
* If nsize is 0, then the allocation function must return NULL. If
* nsize is not 0, then it should return NULL if the allocation fails.
*/
typedef void *
(*avro_allocator_t)(void *user_data, void *ptr, size_t osize, size_t nsize);
void avro_set_allocator(avro_allocator_t alloc, void *user_data);
struct avro_allocator_state {
avro_allocator_t alloc;
void *user_data;
};
extern struct avro_allocator_state AVRO_CURRENT_ALLOCATOR;
#define avro_realloc(ptr, osz, nsz) \
(AVRO_CURRENT_ALLOCATOR.alloc \
(AVRO_CURRENT_ALLOCATOR.user_data, \
(ptr), (osz), (nsz)))
#define avro_malloc(sz) (avro_realloc(NULL, 0, (sz)))
#define avro_free(ptr, osz) (avro_realloc((ptr), (osz), 0))
#define avro_new(type) (avro_realloc(NULL, 0, sizeof(type)))
#define avro_freet(type, ptr) (avro_realloc((ptr), sizeof(type), 0))
void *avro_calloc(size_t count, size_t size);
/*
* This is probably too clever for our own good, but when we duplicate a
* string, we actually store its size in the same allocated memory
* buffer. That lets us free the string later, without having to call
* strlen to get its size, and without the containing struct having to
* manually store the strings length.
*
* This means that any string return by avro_strdup MUST be freed using
* avro_str_free, and the only thing that can be passed into
* avro_str_free is a string created via avro_strdup.
*/
char *avro_str_alloc(size_t str_size);
char *avro_strdup(const char *str);
char *avro_strndup(const char *str, size_t size);
void avro_str_free(char *str);
CLOSE_EXTERN
#endif
| utf-8 | 1 | Apache-2.0 | 2009-2015, The Apache Software Foundation |
qt6-webengine-6.2.2+dfsg/src/3rdparty/chromium/third_party/tflite/src/tensorflow/compiler/xla/service/fusion_node_indexing_evaluation.cc | /* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/service/fusion_node_indexing_evaluation.h"
#include "absl/container/flat_hash_map.h"
#include "absl/container/flat_hash_set.h"
#include "tensorflow/compiler/xla/service/hlo_computation.h"
#include "tensorflow/compiler/xla/service/hlo_instruction.h"
#include "tensorflow/compiler/xla/types.h"
#include "tensorflow/core/platform/logging.h"
namespace xla {
FusionNodeIndexingEvaluation::FusionNodeIndexingEvaluation(
const HloInstruction* fusion)
: fusion_(fusion) {
total_emitted_instructions_ = 0;
HloInstruction* root = fusion->fused_expression_root();
indexing_users_[root].insert(fusion);
index_usage_count_[fusion] = 1;
RecomputeCache();
}
bool FusionNodeIndexingEvaluation::AverageCodeDuplicationTooHigh(
const HloInstruction* producer) const {
// This constant is arbitrarily chosen. Essentially we don't want to have too
// much code duplication, because it slows down the compilation time. There is
// a tradeoff between compilation time and runtime here.
const int64 kAllowedCodeDuplication = 15;
// index_usage_count_ contains an entry for each instruction in the fusion
// computation (except parameter instructions), plus an entry for the 'fusion'
// instruction. So the size of this map is already one bigger than the number
// of instructions in the fusion node that are emitted, thus accounting for
// the number of instructions after 'producer' is fused.
return EvaluateTotalEmittedInstructions(producer) /
index_usage_count_.size() >
kAllowedCodeDuplication;
}
int64 FusionNodeIndexingEvaluation::EvaluateTotalEmittedInstructions(
const HloInstruction* producer) const {
int64 total = total_emitted_instructions_;
for (const auto* user : indexing_users_.at(producer)) {
total += index_usage_count_.at(user);
}
return total;
}
void FusionNodeIndexingEvaluation::UpdateEvaluationCache(
const HloInstruction* producer,
absl::flat_hash_set<const HloInstruction*> indexing_users_of_producer) {
CHECK(!indexing_users_.contains(producer));
indexing_users_[producer] = std::move(indexing_users_of_producer);
UpdateIndexUsageCount(producer);
UpdateIndexingUsersOfOperands(producer);
}
absl::flat_hash_set<const HloInstruction*>
FusionNodeIndexingEvaluation::RemoveFusionOperand(
HloInstruction* fusion_operand) {
auto indexing_users_of_operand =
std::move(indexing_users_.at(fusion_operand));
indexing_users_.erase(fusion_operand);
CHECK(!index_usage_count_.contains(fusion_operand));
return indexing_users_of_operand;
}
void FusionNodeIndexingEvaluation::RecomputeCache() {
auto postorder =
fusion_->fused_instructions_computation()->MakeInstructionPostOrder();
std::reverse(postorder.begin(), postorder.end());
for (const auto* instruction : postorder) {
if (instruction->opcode() == HloOpcode::kParameter) {
continue;
}
UpdateIndexUsageCount(instruction);
UpdateIndexingUsersOfOperands(instruction);
}
}
void FusionNodeIndexingEvaluation::UpdateIndexUsageCount(
const HloInstruction* instruction) {
int64 total = 0;
for (const auto* user : indexing_users_[instruction]) {
int64 weight = 1;
// Concatenate is special: the index differs for each operand, so
// in the worst case we have to deal with as many index values as
// the number of operands of Concatenate. By considering the worst
// case, we are more conservative than necessary regarding
// counting the index usage.
if (user->opcode() == HloOpcode::kConcatenate) {
weight = user->operand_count();
}
total += index_usage_count_.at(user) * weight;
}
CHECK(index_usage_count_.emplace(instruction, total).second);
total_emitted_instructions_ += total;
}
void FusionNodeIndexingEvaluation::UpdateIndexingUsersOfOperands(
const HloInstruction* instruction) {
for (const auto* operand : instruction->operands()) {
if (operand->opcode() == HloOpcode::kParameter) {
// Although actually the parameter gets indexed, we store it as indexing
// of the corresponding fusion operand instead because parameter
// instruction pointers can be invalidated when we fuse another
// instruction into 'fusion_'.
operand = fusion_->operand(operand->parameter_number());
}
// For simplicity we assume that all shape and layout changing
// operations except Transposes invalidate index reuse. Transposes are
// special: although they are shape changing, we can reuse the
// multi-dimensional index for the operand by permuting it.
if (instruction->opcode() == HloOpcode::kTranspose ||
Shape::Equal().IgnoreElementType()(operand->shape(),
instruction->shape())) {
// If the index is reused, it means the operand gets index values
// from the same set of (indirect) users as 'instruction' itself.
indexing_users_[operand].insert(indexing_users_[instruction].begin(),
indexing_users_[instruction].end());
} else {
// If the index is not reused, it means 'instruction' computes a
// new index derived from the index it gets.
indexing_users_[operand].insert(instruction);
}
}
}
} // namespace xla
| utf-8 | 1 | LGPL-3 or GPL-2 | 2006-2021 The Chromium Authors
2016-2021 The Qt Company Ltd. |
burp-2.4.0/src/ssl.c | #include "burp.h"
#include "alloc.h"
#include "conf.h"
#include "log.h"
#include "server/ca.h"
#include "ssl.h"
static const char *pass=NULL;
int ssl_do_accept(SSL *ssl)
{
while(1)
{
int r;
ERR_clear_error();
switch((r=SSL_accept(ssl)))
{
case 1:
return 0;
case 0:
goto error;
default:
switch(SSL_get_error(ssl, r))
{
case SSL_ERROR_WANT_READ:
continue;
default:
goto error;
}
break;
}
}
error:
logp_ssl_err("SSL_accept error\n");
return -1;
}
int ssl_load_dh_params(SSL_CTX *ctx, struct conf **confs)
{
DH *ret=0;
BIO *bio=NULL;
const char *ssl_dhfile=get_string(confs[OPT_SSL_DHFILE]);
if(!(bio=BIO_new_file(ssl_dhfile, "r")))
{
logp_ssl_err("Couldn't open ssl_dhfile: %s\n", ssl_dhfile);
return -1;
}
ret=PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
BIO_free(bio);
if(SSL_CTX_set_tmp_dh(ctx, ret)<0)
{
logp_ssl_err("Couldn't set DH parameters");
return -1;
}
return 0;
}
static int password_cb(char *buf, int num,
__attribute__ ((unused)) int rwflag,
__attribute__ ((unused)) void *userdata)
{
if(num<(int)strlen(pass)+1) return 0;
strcpy(buf, pass);
return strlen(pass);
}
void ssl_load_globals(void)
{
// Global system initialization.
SSL_library_init();
SSL_load_error_strings();
}
static int check_path(const char *path, const char *what)
{
struct stat statp;
if(!path) return -1;
if(stat(path, &statp))
{
logp("Could not find %s %s: %s\n",
what, path, strerror(errno));
return -1;
}
return 0;
}
static int ssl_load_keys_and_certs(SSL_CTX *ctx, struct conf **confs)
{
char *ssl_key=NULL;
const char *ssl_cert=get_string(confs[OPT_SSL_CERT]);
const char *ssl_cert_ca=get_string(confs[OPT_SSL_CERT_CA]);
// Load our keys and certificates if the path exists.
if(!check_path(ssl_cert, "ssl_cert")
&& !SSL_CTX_use_certificate_chain_file(ctx, ssl_cert))
{
logp_ssl_err("Can't read ssl_cert: %s\n", ssl_cert);
return -1;
}
pass=get_string(confs[OPT_SSL_KEY_PASSWORD]);
SSL_CTX_set_default_passwd_cb(ctx, password_cb);
ssl_key=get_string(confs[OPT_SSL_KEY]);
if(!ssl_key) ssl_key=get_string(confs[OPT_SSL_CERT]);
// Load the key file, if the path exists.
if(!check_path(ssl_key, "ssl_key")
&& !SSL_CTX_use_PrivateKey_file(ctx, ssl_key, SSL_FILETYPE_PEM))
{
logp_ssl_err("Can't read ssl_key file: %s\n", ssl_key);
return -1;
}
// Load the CAs we trust, if the path exists.
if(!check_path(ssl_cert_ca, "ssl_cert_ca")
&& !SSL_CTX_load_verify_locations(ctx, ssl_cert_ca, 0))
{
logp_ssl_err("Can't read ssl_cert_ca file: %s\n", ssl_cert_ca);
return -1;
}
return 0;
}
SSL_CTX *ssl_initialise_ctx(struct conf **confs)
{
SSL_CTX *ctx=NULL;
SSL_METHOD *meth=NULL;
const char *ssl_ciphers=get_string(confs[OPT_SSL_CIPHERS]);
// Create our context.
meth=(SSL_METHOD *)SSLv23_method();
ctx=(SSL_CTX *)SSL_CTX_new(meth);
if(ssl_load_keys_and_certs(ctx, confs)) return NULL;
if(ssl_ciphers)
SSL_CTX_set_cipher_list(ctx, ssl_ciphers);
// Unclear what is negotiated, so keep quiet until I figure that out.
if(!get_int(confs[OPT_SSL_COMPRESSION]))
{
#ifdef SSL_OP_NO_COMPRESSION
SSL_CTX_set_options(ctx, SSL_OP_NO_COMPRESSION);
#else
logp("This version of openssl has no SSL_OP_NO_COMPRESSION option, so turning off config option '%s' will not work. You should probably upgrade openssl.\n", confs[OPT_SSL_COMPRESSION]->field);
#endif
}
// Default is zlib5, which needs no option set.
SSL_CTX_set_options(ctx, SSL_OP_NO_SSLv2|SSL_OP_NO_SSLv3);
return ctx;
}
void ssl_destroy_ctx(SSL_CTX *ctx)
{
SSL_CTX_free(ctx);
}
#ifndef HAVE_WIN32
static void sanitise(char *buf)
{
char *cp=NULL;
for(cp=buf; *cp; cp++)
{
if(!isalnum(*cp)
&& !isblank(*cp)
&& *cp!='_'
&& *cp!='-'
&& *cp!='.'
&& *cp!=':'
&& *cp!='@')
*cp='_';
}
}
// This function taken from openvpn-2.2.1 and tidied up a bit.
static int setenv_x509(X509_NAME *x509, const char *type)
{
int i, n;
int fn_nid;
ASN1_OBJECT *fn;
ASN1_STRING *val;
X509_NAME_ENTRY *ent;
const char *objbuf;
uint8_t *buf;
char *name_expand;
size_t name_expand_size;
n=X509_NAME_entry_count (x509);
for(i=0; i<n; ++i)
{
if(!(ent=X509_NAME_get_entry (x509, i))
|| !(fn=X509_NAME_ENTRY_get_object(ent))
|| !(val=X509_NAME_ENTRY_get_data(ent))
|| (fn_nid=OBJ_obj2nid(fn))==NID_undef
|| !(objbuf=OBJ_nid2sn(fn_nid)))
continue;
buf=(uint8_t *)1; /* bug in OpenSSL 0.9.6b ASN1_STRING_to_UTF8 requires this workaround */
if(ASN1_STRING_to_UTF8(&buf, val)<=0) continue;
name_expand_size=64+strlen(objbuf);
if(!(name_expand=(char *)malloc_w(name_expand_size, __func__)))
return -1;
snprintf(name_expand, name_expand_size,
"X509_%s_%s", type, objbuf);
sanitise(name_expand);
sanitise((char*)buf);
setenv(name_expand, (char*)buf, 1);
free_w(&name_expand);
OPENSSL_free(buf);
}
return 0;
}
static int setenv_x509_date(ASN1_TIME *tm, const char *env)
{
BIO *bio_out=NULL;
BUF_MEM *bptr=NULL;
char tmpbuf[256]="";
if(!(bio_out=BIO_new(BIO_s_mem())))
{
log_out_of_memory(__func__);
return -1;
}
ASN1_TIME_print(bio_out, tm);
BIO_get_mem_ptr(bio_out, &bptr);
BIO_gets(bio_out, tmpbuf, sizeof(tmpbuf)-1);
BIO_free_all(bio_out);
sanitise(tmpbuf);
setenv(env, (char*)tmpbuf, 1);
return 0;
}
static int setenv_x509_serialnumber(ASN1_INTEGER *i, const char *env)
{
BIO *bio_out=NULL;
BUF_MEM *bptr=NULL;
char tmpbuf[256]="";
if(!(bio_out=BIO_new(BIO_s_mem())))
{
log_out_of_memory(__func__);
return -1;
}
i2a_ASN1_INTEGER(bio_out, i);
BIO_get_mem_ptr(bio_out, &bptr);
BIO_gets(bio_out, tmpbuf, sizeof(tmpbuf)-1);
BIO_free_all(bio_out);
sanitise(tmpbuf);
setenv(env, (char*)tmpbuf, 1);
return 0;
}
#endif
int ssl_check_cert(SSL *ssl, struct conf **confs, struct conf **cconfs)
{
X509 *peer;
int result;
char tmpbuf[256]="";
const char *ssl_peer_cn=get_string(cconfs[OPT_SSL_PEER_CN]);
if(!ssl_peer_cn)
{
logp("ssl_peer_cn not set.\n");
return -1;
}
SSL_CIPHER_description(SSL_get_current_cipher(ssl),
tmpbuf, sizeof(tmpbuf));
logp("SSL is using cipher: %s\n", tmpbuf);
if(!(peer=SSL_get_peer_certificate(ssl)))
{
logp("Could not get peer certificate.\n");
return -1;
}
result=SSL_get_verify_result(ssl);
if(result!=X509_V_OK)
{
logp_ssl_err("Certificate doesn't verify (%d).\n", result);
return -1;
}
X509_NAME_get_text_by_NID(X509_get_subject_name(peer),
NID_commonName, tmpbuf, sizeof(tmpbuf));
if(strcasecmp(tmpbuf, ssl_peer_cn))
{
logp("cert common name doesn't match configured ssl_peer_cn\n");
logp("'%s'!='%s'\n", tmpbuf, ssl_peer_cn);
return -1;
}
#ifndef HAVE_WIN32
// Check the peer certificate against the CRL list only if set
// in the configuration file. Thus if not set it is not
// breaking the 'ssl_extra_checks_script' configuration.
if(confs && ca_x509_verify_crl(confs, peer, ssl_peer_cn))
return -1;
if(setenv_x509(X509_get_subject_name(peer), "PEER")
|| setenv_x509(X509_get_issuer_name(peer), "ISSUER"))
return -1;
if(setenv_x509_date(X509_get_notBefore(peer), "X509_PEER_NOT_BEFORE")
|| setenv_x509_date(X509_get_notAfter(peer), "X509_PEER_NOT_AFTER"))
return -1;
if(setenv_x509_serialnumber(X509_get_serialNumber(peer),
"X509_PEER_SERIALNUMBER"))
return -1;
#endif
//if((comp=SSL_get_current_compression(ssl)))
// logp("SSL is using compression: %s\n", comp->name);
return 0;
}
| utf-8 | 1 | AGPL-3 | 2011-2014, Graham Keeling |
sigviewer-0.6.4/src/gui_impl/commands/mouse_mode_gui_command.h | // Copyright (c) 2016 The SigViewer Development Team
// Licensed under the GNU General Public License (GPL)
// https://www.gnu.org/licenses/gpl
#ifndef MOUSE_MODE_GUI_COMMAND_H
#define MOUSE_MODE_GUI_COMMAND_H
#include "gui/gui_action_command.h"
#include "gui/gui_action_factory_registrator.h"
#include "gui/signal_visualisation_modes.h"
#include <QStringList>
#include <QActionGroup>
namespace sigviewer
{
class MouseModeGuiCommand : public GuiActionCommand
{
Q_OBJECT
public:
MouseModeGuiCommand ();
virtual ~MouseModeGuiCommand ();
virtual void init ();
public slots:
//-------------------------------------------------------------------------
virtual void trigger (QString const& action_name);
protected:
//-------------------------------------------------------------------------
virtual void applicationStateChanged ();
//-------------------------------------------------------------------------
virtual void evaluateEnabledness ();
private:
static QString const NEW_MODE_TEXT_;
static QString const POINTER_MODE_TEXT_;
static QString const HAND_MODE_TEXT_;
static QString const VIEW_OPTIONS_TEXT_;
static QString const INFO_MODE_TEXT_;
static QStringList const MODE_TEXTS_;
static GuiActionFactoryRegistrator registrator_;
QMap<QString, SignalVisualisationMode> action_to_mode_map_;
};
}
#endif // MOUSE_MODE_GUI_COMMAND_H
| utf-8 | 1 | GPL-3+ | 2004-2009, Alois Schloegl <[email protected]>
2006,2007, Thomas Brunner
2006-2011, Clemens Brunner
2007-2011, Christoph Eibel <[email protected]>
2008, Oliver Terbu
2010, BCI Lab, Institute for Knowledge Discovery, TU Graz, Austria |
freespace2-launcher-wxlauncher-0.11.0+dfsg/code/tabs/InstallPage.cpp | /*
Copyright (C) 2009-2010 wxLauncher Team
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <wx/wx.h>
#include <wx/filename.h>
#include "global/ids.h"
#include "apis/ProfileManager.h"
#include "tabs/InstallPage.h"
#include "apis/HelpManager.h"
#include "generated/configure_launcher.h"
#include "global/MemoryDebugging.h" // Last include for memory debugging
InstallPage::InstallPage(wxWindow* parent): wxPanel(parent, wxID_ANY) {
}
BEGIN_EVENT_TABLE(InstallPage, wxPanel)
END_EVENT_TABLE() | utf-8 | 1 | GPL-2+ | 2009-2016 wxLauncher Team |
chromium-98.0.4758.102/third_party/blink/renderer/core/timing/background_tracing_helper.cc | // Copyright 2021 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/renderer/core/timing/background_tracing_helper.h"
#include "base/cxx17_backports.h"
#include "base/feature_list.h"
#include "base/hash/md5.h"
#include "base/rand_util.h"
#include "base/sys_byteorder.h"
#include "base/trace_event/typed_macros.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/renderer/core/execution_context/execution_context.h"
#include "third_party/blink/renderer/core/timing/performance_mark.h"
#include "third_party/blink/renderer/platform/instrumentation/resource_coordinator/renderer_resource_coordinator.h"
#include "third_party/blink/renderer/platform/weborigin/kurl.h"
#include "third_party/blink/renderer/platform/wtf/text/ascii_ctype.h"
#include "third_party/blink/renderer/platform/wtf/text/number_parsing_options.h"
#include "third_party/blink/renderer/platform/wtf/text/string_operators.h"
#include "third_party/blink/renderer/platform/wtf/text/string_to_number.h"
#include "url/url_constants.h"
namespace blink {
namespace {
enum TerminationCondition {
kMustHaveTerminator,
kMayHaveTerminator,
};
// Consumes a 1-8 byte hash from the given string, and the terminator if one is
// encountered. On success, the parsed hash is output via the optional |hash|
// and the new position of the cursor is returned. On failure, nullptr is
// returned.
const char* ParseHash(const char* begin,
const char* end,
uint32_t& hash,
TerminationCondition termination,
char valid_terminator0,
char valid_terminator1 = 0,
char valid_terminator2 = 0) {
DCHECK(begin);
DCHECK(end);
DCHECK_LE(begin, end);
DCHECK_NE(valid_terminator0, 0);
const char* cur = begin;
while (cur < end) {
// Stop when a terminator is encountered.
if (*cur == valid_terminator0)
break;
if (valid_terminator1 != 0 && *cur == valid_terminator1)
break;
if (valid_terminator2 != 0 && *cur == valid_terminator2)
break;
// Stop if any invalid characters are encountered.
if (!IsASCIIHexDigit(*cur))
return nullptr;
++cur;
// Stop if the hash string is too long.
if (cur - begin > 8)
return nullptr;
}
// Stop if the hash is empty.
if (cur == begin)
return nullptr;
// Enforce mandatory terminator characters.
if (termination == kMustHaveTerminator && cur == end)
return nullptr;
// At this point we've successfully consumed a hash, so parse it.
bool parsed = false;
hash = WTF::HexCharactersToUInt(reinterpret_cast<const unsigned char*>(begin),
cur - begin, WTF::NumberParsingOptions::kNone,
&parsed);
DCHECK(parsed);
// If there's a terminator, advance past it.
if (cur < end)
++cur;
// Finally, return the advanced cursor.
return cur;
}
static constexpr char kTriggerPrefix[] = "trigger:";
bool MarkNameIsTrigger(const String& mark_name) {
return mark_name.StartsWith(kTriggerPrefix);
}
String GenerateFullTrigger(const String& site, const String& mark_name) {
DCHECK(MarkNameIsTrigger(mark_name));
return site + "-" + mark_name.Substring(base::size(kTriggerPrefix) - 1);
}
} // namespace
// A thin wrapper around a SiteMarkHashMap that populates it at construction by
// parsing the relevant Finch parameters.
struct BackgroundTracingHelper::SiteMarkHashMapContainer {
SiteMarkHashMapContainer();
~SiteMarkHashMapContainer() = default;
SiteMarkHashMap site_mark_hash_map;
};
BackgroundTracingHelper::SiteMarkHashMapContainer::SiteMarkHashMapContainer() {
// Do nothing if the feature is not enabled.
if (!base::FeatureList::IsEnabled(
features::kBackgroundTracingPerformanceMark))
return;
// Get the allow-list from the Finch configuration.
std::string allow_list =
features::kBackgroundTracingPerformanceMark_AllowList.Get();
// Parse the allow-list. Silently ignoring malformed configuration data simply
// means the feature will be disabled when this occurs.
BackgroundTracingHelper::ParseBackgroundTracingPerformanceMarkHashes(
allow_list, site_mark_hash_map);
}
BackgroundTracingHelper::BackgroundTracingHelper(ExecutionContext* context) {
// Used to configure a per-origin allowlist of performance.mark events that
// are permitted to be included in background traces. See crbug.com/1181774.
// If there's no allow-list, then bail early.
if (GetSiteMarkHashMap().IsEmpty())
return;
// Only support http and https origins to actual remote servers.
auto* origin = context->GetSecurityOrigin();
if (origin->IsLocal() || origin->IsOpaque() || origin->IsLocalhost())
return;
if (origin->Protocol() != url::kHttpScheme &&
origin->Protocol() != url::kHttpsScheme) {
return;
}
// Get the hash of the domain in an encoded format (friendly for converting to
// ASCII, and matching the format in which URLs will be encoded prior to
// hashing in the Finch list).
String this_site = EncodeWithURLEscapeSequences(origin->Domain());
uint32_t this_site_hash = MD5Hash32(this_site.Ascii());
// Get the allow-list for this site, if there is one.
mark_hashes_ = GetMarkHashSetForSiteHash(this_site_hash);
// We only need the site information if there's actually a set of mark hashes.
if (mark_hashes_) {
site_ = this_site;
site_hash_ = this_site_hash;
}
// Extract a unique ID for the ExecutionContext, using the UnguessableToken
// associated with it. This squishes the 128 bits of token down into a 32-bit
// ID.
auto token = context->GetExecutionContextToken();
uint64_t merged = token.value().GetHighForSerialization() ^
token.value().GetLowForSerialization();
execution_context_id_ = static_cast<uint32_t>(merged & 0xffffffff) ^
static_cast<uint32_t>((merged >> 32) & 0xffffffff);
// Generate a random sequence number offset to be used by this context.
sequence_number_offset_ = static_cast<uint32_t>(base::RandUint64());
}
BackgroundTracingHelper::~BackgroundTracingHelper() = default;
void BackgroundTracingHelper::MaybeEmitBackgroundTracingPerformanceMarkEvent(
const PerformanceMark& mark) {
if (!mark_hashes_)
return;
// Get the mark name in ASCII.
const String& mark_name = mark.name();
std::string mark_name_ascii = mark_name.Ascii();
// Parse the mark and the sequence number, if any.
uint32_t mark_hash = 0;
uint32_t sequence_number = 0;
GetMarkHashAndSequenceNumber(mark_name_ascii, sequence_number_offset_,
&mark_hash, &sequence_number);
// See if the mark hash is in the permitted list.
if (!mark_hashes_->Contains(mark_hash))
return;
// Emit the trace events. We emit hashes and strings to facilitate local trace
// consumption. However, the strings will be stripped and only the hashes
// shipped externally.
auto event_lambda = [&](perfetto::EventContext ctx) {
auto* event = ctx.event<perfetto::protos::pbzero::ChromeTrackEvent>();
auto* data = event->set_chrome_hashed_performance_mark();
data->set_site_hash(site_hash_);
data->set_site(site_.Ascii());
data->set_mark_hash(mark_hash);
data->set_mark(mark_name_ascii);
data->set_execution_context_id(execution_context_id_);
data->set_sequence_number(sequence_number);
};
// For additional context, also emit a paired event marking *when* the
// performance.mark was actually created.
TRACE_EVENT_INSTANT("blink", "performance.mark.created", event_lambda);
// Emit an event with the actual timestamp associated with the mark.
TRACE_EVENT_INSTANT("blink", "performance.mark", mark.UnsafeTimeForTraces(),
event_lambda);
// If this is a slow-reports trigger then fire it.
if (MarkNameIsTrigger(mark_name)) {
RendererResourceCoordinator::Get()->FireBackgroundTracingTrigger(
GenerateFullTrigger(site_, mark_name));
}
}
void BackgroundTracingHelper::Trace(Visitor*) const {}
// static
const BackgroundTracingHelper::SiteMarkHashMap&
BackgroundTracingHelper::GetSiteMarkHashMap() {
// This needs to be thread-safe because performance.mark is supported by both
// windows and workers.
DEFINE_THREAD_SAFE_STATIC_LOCAL(SiteMarkHashMapContainer,
site_mark_hash_map_container, ());
return site_mark_hash_map_container.site_mark_hash_map;
}
// static
const BackgroundTracingHelper::MarkHashSet*
BackgroundTracingHelper::GetMarkHashSetForSiteHash(uint32_t site_hash) {
const SiteMarkHashMap& site_mark_hash_map = GetSiteMarkHashMap();
auto it = site_mark_hash_map.find(site_hash);
if (it == site_mark_hash_map.end())
return nullptr;
return &(it->value);
}
// static
size_t BackgroundTracingHelper::GetSequenceNumberPos(base::StringPiece string) {
// Extract any trailing integers.
size_t cursor = string.size();
while (cursor > 0) {
char c = string[cursor - 1];
if (c < '0' || c > '9')
break;
--cursor;
}
// A valid suffix must have 1 or more integers.
if (cursor == string.size())
return 0;
// A valid suffix must be preceded by an underscore and at least one prefix
// character.
if (cursor < 2)
return 0;
// A valid suffix must be preceded by an underscore.
if (string[cursor - 1] != '_')
return 0;
// Return the location of the underscore.
return cursor - 1;
}
// static
uint32_t BackgroundTracingHelper::MD5Hash32(base::StringPiece string) {
base::MD5Digest digest;
base::MD5Sum(string.data(), string.size(), &digest);
uint32_t value;
DCHECK_GE(sizeof(digest.a), sizeof(value));
memcpy(&value, digest.a, sizeof(value));
return base::NetToHost32(value);
}
// static
void BackgroundTracingHelper::GetMarkHashAndSequenceNumber(
base::StringPiece mark_name,
uint32_t sequence_number_offset,
uint32_t* mark_hash,
uint32_t* sequence_number) {
*sequence_number = 0;
// Extract a sequence number suffix, if it exists.
size_t sequence_number_pos = GetSequenceNumberPos(mark_name);
if (sequence_number_pos != 0) {
// Parse the suffix.
auto suffix = mark_name.substr(sequence_number_pos + 1);
bool result = false;
int seq_num = WTF::CharactersToInt(
reinterpret_cast<const unsigned char*>(suffix.data()), suffix.size(),
WTF::NumberParsingOptions::kNone, &result);
if (result) {
// Cap the sequence number to an easily human-consumable size. It is fine
// for this calculation to overflow.
*sequence_number =
(static_cast<uint32_t>(seq_num) + sequence_number_offset) % 1000;
}
// Remove the suffix from the mark name.
mark_name = mark_name.substr(0, sequence_number_pos);
}
// Hash the mark name.
*mark_hash = MD5Hash32(mark_name);
}
// static
bool BackgroundTracingHelper::ParseBackgroundTracingPerformanceMarkHashes(
base::StringPiece allow_list,
SiteMarkHashMap& allow_listed_hashes) {
// We parse into this temporary structure, and move into the output on
// success.
SiteMarkHashMap parsed_allow_listed_hashes;
// The format is:
//
// sitehash0=markhash0,...,markhashn;sitehash1=markhash0,...,markhashn
//
// where each hash is a 32-bit hex hash. We also allow commas to be replaced
// with underscores so that they can be easily specified via the
// --enable-features command-line.
const char* cur = allow_list.data();
const char* end = allow_list.data() + allow_list.size();
while (cur < end) {
// Parse a site hash.
uint32_t site_hash = 0;
cur = ParseHash(cur, end, site_hash, kMustHaveTerminator, '=');
if (!cur)
return false;
// The site hash must be unique.
if (parsed_allow_listed_hashes.Contains(site_hash))
return false;
// Parse the mark hashes.
MarkHashSet parsed_mark_hashes;
while (true) {
// At least a single mark hash entry is expected per site hash.
uint32_t mark_hash = 0;
cur = ParseHash(cur, end, mark_hash, kMayHaveTerminator, ',', ';', '_');
if (!cur)
return false;
// Duplicate entries are an error.
auto result = parsed_mark_hashes.insert(mark_hash);
if (!result.is_new_entry)
return false;
// We're done processing the current list of mark hashes if there's no
// data left to consume, or if the terminator was a ';'.
if (cur == end || cur[-1] == ';')
break;
}
auto result = parsed_allow_listed_hashes.insert(
site_hash, std::move(parsed_mark_hashes));
// We guaranteed uniqueness of insertion by checking for the |site_hash|
// before parsing the mark hashes.
DCHECK(result.is_new_entry);
}
// Getting here means we successfully parsed the whole list.
allow_listed_hashes = std::move(parsed_allow_listed_hashes);
return true;
}
} // namespace blink
| utf-8 | 1 | BSD-3-clause | The Chromium Authors. All rights reserved. |
algobox-1.1.0+dfsg/toolbox.h | /***************************************************************************
* copyright : (C) 2009-2021 by Pascal Brachet *
* https://www.xm1math.net/algobox/ *
* *
* 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. *
* *
* @license GPL-2.0+ <https://spdx.org/licenses/GPL-2.0+.html> *
***************************************************************************/
#ifndef TOOLBOX_H
#define TOOLBOX_H
#include <QToolBar>
#include <QAction>
class ToolBox : public QToolBar
{
Q_OBJECT
public:
ToolBox(QWidget* parent=0);
~ToolBox();
QAction *actionSauver;
};
#endif // TOOLBOX_H
| utf-8 | 1 | GPL-2+ | 2003-2021, Pascal Brachet <[email protected]> |
virtualbox-6.1.32-dfsg/src/VBox/Devices/EFI/Firmware/MdeModulePkg/Application/DumpDynPcd/DumpDynPcd.c | /** @file
A shell application to dump dynamic PCD settings.
Copyright (c) 2019, Intel Corporation. All rights reserved.<BR>
SPDX-License-Identifier: BSD-2-Clause-Patent
**/
#include <Uefi.h>
#include <PiDxe.h>
#include <Library/BaseLib.h>
#include <Library/DebugLib.h>
#include <Library/MemoryAllocationLib.h>
#include <Library/UefiBootServicesTableLib.h>
#include <Library/UefiLib.h>
#include <Protocol/UnicodeCollation.h>
#include <Protocol/PiPcd.h>
#include <Protocol/Pcd.h>
#include <Protocol/PiPcdInfo.h>
#include <Protocol/PcdInfo.h>
#include <Protocol/ShellParameters.h>
#include <Protocol/Shell.h>
//
// String token ID of help message text.
// Shell supports to find help message in the resource section of an application image if
// .MAN file is not found. This global variable is added to make build tool recognizes
// that the help string is consumed by user and then build tool will add the string into
// the resource section. Thus the application can use '-?' option to show help message in
// Shell.
//
GLOBAL_REMOVE_IF_UNREFERENCED EFI_STRING_ID mStrDumpDynPcdHelpTokenId = STRING_TOKEN (STR_DUMP_DYN_PCD_HELP_INFORMATION);
#define MAJOR_VERSION 1
#define MINOR_VERSION 0
static EFI_UNICODE_COLLATION_PROTOCOL *mUnicodeCollation = NULL;
static EFI_PCD_PROTOCOL *mPiPcd = NULL;
static PCD_PROTOCOL *mPcd = NULL;
static EFI_GET_PCD_INFO_PROTOCOL *mPiPcdInfo = NULL;
static GET_PCD_INFO_PROTOCOL *mPcdInfo = NULL;
static CHAR16 *mTempPcdNameBuffer = NULL;
static UINTN mTempPcdNameBufferSize = 0;
static CONST CHAR8 mHex[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
static UINTN Argc;
static CHAR16 **Argv;
/**
This function parse application ARG.
@return Status
**/
static
EFI_STATUS
GetArg (
VOID
)
{
EFI_STATUS Status;
EFI_SHELL_PARAMETERS_PROTOCOL *ShellParameters;
Status = gBS->HandleProtocol (
gImageHandle,
&gEfiShellParametersProtocolGuid,
(VOID**)&ShellParameters
);
if (EFI_ERROR(Status)) {
return Status;
}
Argc = ShellParameters->Argc;
Argv = ShellParameters->Argv;
return EFI_SUCCESS;
}
/**
Display current version.
**/
static
VOID
ShowVersion (
)
{
Print (L"DumpDynPcd Version %d.%02d\n", MAJOR_VERSION, MINOR_VERSION);
}
/**
Display Usage and Help information.
**/
static
VOID
ShowHelp (
)
{
Print (L"Dump dynamic[ex] PCD info.\n");
Print (L"\n");
Print (L"DumpDynPcd [PcdName]\n");
Print (L"\n");
Print (L" PcdName Specifies the name of PCD.\n");
Print (L" A literal[or partial] name or a pattern as specified in\n");
Print (L" the MetaiMatch() function of the EFI_UNICODE_COLLATION2_PROCOOL.\n");
Print (L" If it is absent, dump all PCDs' info.\n");
Print (L"The PCD data is printed as hexadecimal dump.\n");
}
/**
Dump some hexadecimal data to the screen.
@param[in] Indent How many spaces to indent the output.
@param[in] Offset The offset of the printing.
@param[in] DataSize The size in bytes of UserData.
@param[in] UserData The data to print out.
**/
static
VOID
DumpHex (
IN UINTN Indent,
IN UINTN Offset,
IN UINTN DataSize,
IN VOID *UserData
)
{
UINT8 *Data;
CHAR8 Val[50];
CHAR8 Str[20];
UINT8 TempByte;
UINTN Size;
UINTN Index;
Data = UserData;
while (DataSize != 0) {
Size = 16;
if (Size > DataSize) {
Size = DataSize;
}
for (Index = 0; Index < Size; Index += 1) {
TempByte = Data[Index];
Val[Index * 3 + 0] = mHex[TempByte >> 4];
Val[Index * 3 + 1] = mHex[TempByte & 0xF];
Val[Index * 3 + 2] = (CHAR8) ((Index == 7) ? '-' : ' ');
Str[Index] = (CHAR8) ((TempByte < ' ' || TempByte > 'z') ? '.' : TempByte);
}
Val[Index * 3] = 0;
Str[Index] = 0;
Print (L"%*a%08X: %-48a *%a*\r\n", Indent, "", Offset, Val, Str);
Data += Size;
Offset += Size;
DataSize -= Size;
}
}
/**
Safely append with automatic string resizing given length of Destination and
desired length of copy from Source.
append the first D characters of Source to the end of Destination, where D is
the lesser of Count and the StrLen() of Source. If appending those D characters
will fit within Destination (whose Size is given as CurrentSize) and
still leave room for a NULL terminator, then those characters are appended,
starting at the original terminating NULL of Destination, and a new terminating
NULL is appended.
If appending D characters onto Destination will result in a overflow of the size
given in CurrentSize the string will be grown such that the copy can be performed
and CurrentSize will be updated to the new size.
If Source is NULL, there is nothing to append, just return the current buffer in
Destination.
if Destination is NULL, then ASSERT()
if Destination's current length (including NULL terminator) is already more then
CurrentSize, then ASSERT()
@param[in, out] Destination The String to append onto
@param[in, out] CurrentSize on call the number of bytes in Destination. On
return possibly the new size (still in bytes). if NULL
then allocate whatever is needed.
@param[in] Source The String to append from
@return Destination return the resultant string.
**/
static
CHAR16*
InternalStrnCatGrow (
IN OUT CHAR16 **Destination,
IN OUT UINTN *CurrentSize,
IN CONST CHAR16 *Source
)
{
UINTN DestinationStartSize;
UINTN NewSize;
UINTN SourceLen;
SourceLen = StrLen(Source);
//
// ASSERTs
//
ASSERT(Destination != NULL);
//
// If there's nothing to do then just return Destination
//
if (Source == NULL) {
return (*Destination);
}
//
// allow for un-initialized pointers, based on size being 0
//
if (CurrentSize != NULL && *CurrentSize == 0) {
*Destination = NULL;
}
//
// allow for NULL pointers address as Destination
//
if (*Destination != NULL) {
ASSERT(CurrentSize != 0);
DestinationStartSize = StrSize(*Destination);
ASSERT(DestinationStartSize <= *CurrentSize);
} else {
DestinationStartSize = 0;
}
//
// Test and grow if required
//
if (CurrentSize != NULL) {
NewSize = *CurrentSize;
if (NewSize < DestinationStartSize + (SourceLen * sizeof(CHAR16))) {
while (NewSize < (DestinationStartSize + (SourceLen*sizeof(CHAR16)))) {
NewSize += 2 * SourceLen * sizeof(CHAR16);
}
*Destination = ReallocatePool(*CurrentSize, NewSize, *Destination);
*CurrentSize = NewSize;
}
} else {
NewSize = (SourceLen + 1)*sizeof(CHAR16);
*Destination = AllocateZeroPool(NewSize);
}
//
// Now use standard StrnCat on a big enough buffer
//
if (*Destination == NULL) {
return (NULL);
}
StrnCatS(*Destination, NewSize/sizeof(CHAR16), Source, SourceLen);
return *Destination;
}
/**
Get PCD type string based on input PCD type.
@param[in] TokenSpace PCD Token Space.
@param[in] PcdType The input PCD type.
@return Pointer to PCD type string.
**/
static
CHAR16 *
GetPcdTypeString (
IN CONST EFI_GUID *TokenSpace,
IN EFI_PCD_TYPE PcdType
)
{
UINTN BufLen;
CHAR16 *RetString;
BufLen = 0;
RetString = NULL;
switch (PcdType) {
case EFI_PCD_TYPE_8:
InternalStrnCatGrow (&RetString, &BufLen, L"UINT8");
break;
case EFI_PCD_TYPE_16:
InternalStrnCatGrow (&RetString, &BufLen, L"UINT16");
break;
case EFI_PCD_TYPE_32:
InternalStrnCatGrow (&RetString, &BufLen, L"UINT32");
break;
case EFI_PCD_TYPE_64:
InternalStrnCatGrow (&RetString, &BufLen, L"UINT64");
break;
case EFI_PCD_TYPE_BOOL:
InternalStrnCatGrow (&RetString, &BufLen, L"BOOLEAN");
break;
case EFI_PCD_TYPE_PTR:
InternalStrnCatGrow (&RetString, &BufLen, L"POINTER");
break;
default:
InternalStrnCatGrow (&RetString, &BufLen, L"UNKNOWN");
break;
}
if (TokenSpace == NULL) {
InternalStrnCatGrow (&RetString, &BufLen, L":DYNAMIC");
} else {
InternalStrnCatGrow (&RetString, &BufLen, L":DYNAMICEX");
}
return RetString;
}
/**
Dump PCD info.
@param[in] TokenSpace PCD Token Space.
@param[in] TokenNumber PCD Token Number.
@param[in] PcdInfo Pointer to PCD info.
**/
static
VOID
DumpPcdInfo (
IN CONST EFI_GUID *TokenSpace,
IN UINTN TokenNumber,
IN EFI_PCD_INFO *PcdInfo
)
{
CHAR16 *RetString;
UINT8 Uint8;
UINT16 Uint16;
UINT32 Uint32;
UINT64 Uint64;
BOOLEAN Boolean;
VOID *PcdData;
RetString = NULL;
if (PcdInfo->PcdName != NULL) {
Print (L"%a\n", PcdInfo->PcdName);
} else {
if (TokenSpace == NULL) {
Print (L"Default Token Space\n");
} else {
Print (L"%g\n", TokenSpace);
}
}
RetString = GetPcdTypeString (TokenSpace, PcdInfo->PcdType);
switch (PcdInfo->PcdType) {
case EFI_PCD_TYPE_8:
if (TokenSpace == NULL) {
Uint8 = mPcd->Get8 (TokenNumber);
} else {
Uint8 = mPiPcd->Get8 (TokenSpace, TokenNumber);
}
Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint8);
break;
case EFI_PCD_TYPE_16:
if (TokenSpace == NULL) {
Uint16 = mPcd->Get16 (TokenNumber);
} else {
Uint16 = mPiPcd->Get16 (TokenSpace, TokenNumber);
}
Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint16);
break;
case EFI_PCD_TYPE_32:
if (TokenSpace == NULL) {
Uint32 = mPcd->Get32 (TokenNumber);
} else {
Uint32 = mPiPcd->Get32 (TokenSpace, TokenNumber);
}
Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint32);
break;
case EFI_PCD_TYPE_64:
if (TokenSpace == NULL) {
Uint64 = mPcd->Get64 (TokenNumber);
} else {
Uint64 = mPiPcd->Get64 (TokenSpace, TokenNumber);
}
Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = 0x%lx\n", TokenNumber, RetString, PcdInfo->PcdSize, Uint64);
break;
case EFI_PCD_TYPE_BOOL:
if (TokenSpace == NULL) {
Boolean = mPcd->GetBool (TokenNumber);
} else {
Boolean = mPiPcd->GetBool (TokenSpace, TokenNumber);
}
Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x - Value = %a\n", TokenNumber, RetString, PcdInfo->PcdSize, Boolean ? "TRUE" : "FALSE");
break;
case EFI_PCD_TYPE_PTR:
if (TokenSpace == NULL) {
PcdData = mPcd->GetPtr (TokenNumber);
} else {
PcdData = mPiPcd->GetPtr (TokenSpace, TokenNumber);
}
Print (L" Token = 0x%08x - Type = %H%-17s%N - Size = 0x%x\n", TokenNumber, RetString, PcdInfo->PcdSize);
DumpHex (2, 0, PcdInfo->PcdSize, PcdData);
break;
default:
return;
}
if (RetString != NULL) {
FreePool (RetString);
}
Print (L"\n");
}
/**
Show one or all PCDs' info.
@param[in] InputPcdName Pointer to PCD name to show. If NULL, show all PCDs' info.
@retval EFI_SUCCESS Command completed successfully.
@retval EFI_OUT_OF_RESOURCES Not enough resources were available to run the command.
@retval EFI_ABORTED Aborted by user.
@retval EFI_NOT_FOUND The specified PCD is not found.
**/
static
EFI_STATUS
ProcessPcd (
IN CHAR16 *InputPcdName
)
{
EFI_STATUS Status;
EFI_GUID *TokenSpace;
UINTN TokenNumber;
EFI_PCD_INFO PcdInfo;
BOOLEAN Found;
UINTN PcdNameSize;
PcdInfo.PcdName = NULL;
PcdInfo.PcdSize = 0;
PcdInfo.PcdType = 0xFF;
Found = FALSE;
Print (L"Current system SKU ID: 0x%x\n\n", mPiPcdInfo->GetSku ());
TokenSpace = NULL;
do {
TokenNumber = 0;
do {
Status = mPiPcd->GetNextToken (TokenSpace, &TokenNumber);
if (!EFI_ERROR (Status) && TokenNumber != 0) {
if (TokenSpace == NULL) {
//
// PCD in default Token Space.
//
mPcdInfo->GetInfo (TokenNumber, &PcdInfo);
} else {
mPiPcdInfo->GetInfo (TokenSpace, TokenNumber, &PcdInfo);
}
if (InputPcdName != NULL) {
if (PcdInfo.PcdName == NULL) {
continue;
}
PcdNameSize = AsciiStrSize (PcdInfo.PcdName) * sizeof (CHAR16);
if (mTempPcdNameBuffer == NULL) {
mTempPcdNameBufferSize = PcdNameSize;
mTempPcdNameBuffer = AllocatePool (mTempPcdNameBufferSize);
} else if (mTempPcdNameBufferSize < PcdNameSize) {
mTempPcdNameBuffer = ReallocatePool (mTempPcdNameBufferSize, PcdNameSize, mTempPcdNameBuffer);
mTempPcdNameBufferSize = PcdNameSize;
}
if (mTempPcdNameBuffer == NULL) {
return EFI_OUT_OF_RESOURCES;
}
AsciiStrToUnicodeStrS (PcdInfo.PcdName, mTempPcdNameBuffer, mTempPcdNameBufferSize / sizeof (CHAR16));
//
// Compare the input PCD name with the PCD name in PCD database.
//
if ((StrStr (mTempPcdNameBuffer, InputPcdName) != NULL) ||
(mUnicodeCollation != NULL && mUnicodeCollation->MetaiMatch (mUnicodeCollation, mTempPcdNameBuffer, InputPcdName))) {
//
// Found matched PCD.
//
DumpPcdInfo (TokenSpace, TokenNumber, &PcdInfo);
Found = TRUE;
}
} else {
DumpPcdInfo (TokenSpace, TokenNumber, &PcdInfo);
}
}
} while (!EFI_ERROR (Status) && TokenNumber != 0);
Status = mPiPcd->GetNextTokenSpace ((CONST EFI_GUID **) &TokenSpace);
} while (!EFI_ERROR (Status) && TokenSpace != NULL);
if ((InputPcdName != NULL) && !Found) {
//
// The specified PCD is not found, print error.
//
Print (L"%EError. %NNo matching PCD found: %s.\n", InputPcdName);
return EFI_NOT_FOUND;
}
return EFI_SUCCESS;
}
/**
Main entrypoint for DumpDynPcd shell application.
@param[in] ImageHandle The image handle.
@param[in] SystemTable The system table.
@retval EFI_SUCCESS Command completed successfully.
@retval EFI_INVALID_PARAMETER Command usage error.
@retval EFI_OUT_OF_RESOURCES Not enough resources were available to run the command.
@retval EFI_ABORTED Aborted by user.
@retval EFI_NOT_FOUND The specified PCD is not found.
@retval Others Error status returned from gBS->LocateProtocol.
**/
EFI_STATUS
EFIAPI
DumpDynPcdMain (
IN EFI_HANDLE ImageHandle,
IN EFI_SYSTEM_TABLE *SystemTable
)
{
EFI_STATUS Status;
CHAR16 *InputPcdName;
InputPcdName = NULL;
Status = gBS->LocateProtocol(&gEfiUnicodeCollation2ProtocolGuid, NULL, (VOID **) &mUnicodeCollation);
if (EFI_ERROR (Status)) {
mUnicodeCollation = NULL;
}
Status = gBS->LocateProtocol (&gEfiPcdProtocolGuid, NULL, (VOID **) &mPiPcd);
if (EFI_ERROR (Status)) {
Print (L"DumpDynPcd: %EError. %NPI PCD protocol is not present.\n");
return Status;
}
Status = gBS->LocateProtocol (&gEfiGetPcdInfoProtocolGuid, NULL, (VOID **) &mPiPcdInfo);
if (EFI_ERROR (Status)) {
Print (L"DumpDynPcd: %EError. %NPI PCD info protocol is not present.\n");
return Status;
}
Status = gBS->LocateProtocol (&gPcdProtocolGuid, NULL, (VOID **) &mPcd);
if (EFI_ERROR (Status)) {
Print (L"DumpDynPcd: %EError. %NPCD protocol is not present.\n");
return Status;
}
Status = gBS->LocateProtocol (&gGetPcdInfoProtocolGuid, NULL, (VOID **) &mPcdInfo);
if (EFI_ERROR (Status)) {
Print (L"DumpDynPcd: %EError. %NPCD info protocol is not present.\n");
return Status;
}
//
// get the command line arguments
//
Status = GetArg();
if (EFI_ERROR(Status)){
Print (L"DumpDynPcd: %EError. %NThe input parameters are not recognized.\n");
Status = EFI_INVALID_PARAMETER;
return Status;
}
if (Argc > 2){
Print (L"DumpDynPcd: %EError. %NToo many arguments specified.\n");
Status = EFI_INVALID_PARAMETER;
return Status;
}
if (Argc == 1){
Status = ProcessPcd (InputPcdName);
goto Done;
}
if ((StrCmp(Argv[1], L"-?") == 0)||(StrCmp(Argv[1], L"-h") == 0)||(StrCmp(Argv[1], L"-H") == 0)){
ShowHelp ();
goto Done;
} else {
if ((StrCmp(Argv[1], L"-v") == 0)||(StrCmp(Argv[1], L"-V") == 0)){
ShowVersion ();
goto Done;
} else {
if (StrStr(Argv[1], L"-") != NULL){
Print (L"DumpDynPcd: %EError. %NThe argument '%B%s%N' is invalid.\n", Argv[1]);
goto Done;
}
}
}
InputPcdName = Argv[1];
Status = ProcessPcd (InputPcdName);
Done:
if (mTempPcdNameBuffer != NULL) {
FreePool (mTempPcdNameBuffer);
}
return Status;
}
| utf-8 | 1 | unknown | unknown |
r-bioc-affxparser-1.66.0/src/fusion/util/test-tmpfilefactory.cpp | ////////////////////////////////////////////////////////////////
//
// Copyright (C) 2005 Affymetrix, Inc.
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License
// (version 2.1) as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
// or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
// for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this library; if not, write to the Free Software Foundation, Inc.,
// 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
////////////////////////////////////////////////////////////////
//
#include "util/Fs.h"
#include "util/PgOptions.h"
#include "util/TmpFileFactory.h"
#include "util/Util.h"
//
#include <cassert>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <string>
//
//////////
int opt_debug=0;
int opt_verbose=0;
//////////
/// @brief Dump the filename to the file as test data.
/// @param filename filename to create
void
test_write_data(const std::string& filename)
{
assert(!Fs::isReadable(filename));
std::ofstream outs;
outs.open(filename.c_str());
outs<<filename<<std::endl;
outs.close();
}
//////////
void
test_1()
{
// make a new factory to generate temp files.
TmpFileFactory* tff=new TmpFileFactory();
std::string tfn;
tff->setPrefix("tff-test1-");
tff->setDebug(opt_debug);
tff->setVerbose(opt_verbose);
//
for (int i=0;i<10;i++) {
// this allocates a tmp file name and remembers it.
tfn=tff->genFilename();
if (opt_verbose>0) {
printf("%4d : '%s'\n",i,tfn.c_str());
}
// put something in the file.
test_write_data(tfn);
}
// When the object is deleted, it cleans up all the tmpfiles.
delete tff;
}
/// this function has a TmpFileFactory pointer passed into it.
/// the allocations are done within its context.
void
test_2_helper(TmpFileFactory* tff,int cnt)
{
for (int i=0;i<cnt;i++) {
printf("%4d : '%s'\n",i,tff->genFilename().c_str());
}
}
void
test_2()
{
TmpFileFactory* tff=new TmpFileFactory();
tff->setPrefix("tff-test2-");
tff->setDebug(opt_debug);
tff->setVerbose(opt_verbose);
// passing the context into a fuctions
test_2_helper(tff,5);
test_2_helper(tff,5);
// now clean up.
delete tff;
}
void
test_3()
{
TmpFileFactory* tff=new TmpFileFactory();
tff->setPrefix("tff-test3-");
tff->setDebug(opt_debug);
tff->setVerbose(opt_verbose);
//
for (int i=0;i<10;i++) {
tff->genDirname();
}
// make a subdir and allocate future tmp files in that subdir.
tff->setTmpdir(tff->genDirname());
//
test_2_helper(tff,5);
test_2_helper(tff,5);
//
delete tff;
}
void
test_4()
{
// generate 10 dirs for fun.
for (int i=0;i<10;i++) {
GlobalTmpFileFactory()->genDirname();
}
// set the dir to /var/tmp on unix. (Where on windows?)
GlobalTmpFileFactory()->setTmpdir(GlobalTmpFileFactory()->getSystemTmpDir());
// gen a subdir in that directory and set our tmp dir to dir we made.
GlobalTmpFileFactory()->setTmpdir(GlobalTmpFileFactory()->genDirname());
// generate 10 filenames in the new tmp dir for fun.
for (int i=0;i<10;i++) {
test_write_data(GlobalTmpFileFactory()->genFilename());
}
}
//////////
int
main(int argc,char* argv[])
{
PgOptions* opts=new PgOptions();
//
opts->setUsage("Example and test program for generating test filenames."
"\n"
);
//
opts->defineOption("h","help", PgOpt::BOOL_OPT,
"Show help for the program.",
"false");
opts->defineOption("v","verbose",PgOpt::INT_OPT,
"verbose level",
"0");
opts->defineOption("d","debug",PgOpt::INT_OPT,
"debugging level.\n"
"0 => None.\n"
"1 => Print the tmp filename as they are generated.\n"
"2 => Dont remove tmp files, leave them there for analysis.\n",
"0");
//
opts->parseArgv(argv);
//
opt_debug =opts->getInt("debug");
opt_verbose=opts->getInt("verbose");
// set some options. (this is optional.)
GlobalTmpFileFactory()->setPrefix("tff-global-");
GlobalTmpFileFactory()->setDebug(opt_debug);
GlobalTmpFileFactory()->setVerbose(opt_verbose);
//
test_1();
test_2();
test_3();
test_4();
// need to clean up when exiting.
GlobalTmpFileFactoryFree();
//
printf("ok.\n");
}
| utf-8 | 1 | LGPL-2+ | 2009-2020 Henrik Bengtsson
James Bullard
Robert Gentleman
Kasper Daniel Hansen
Jim Hester
Martin Morgan |
leveldb-1.23/util/env_posix_test.cc | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
#include <sys/resource.h>
#include <sys/wait.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <unordered_set>
#include <vector>
#include "gtest/gtest.h"
#include "leveldb/env.h"
#include "port/port.h"
#include "util/env_posix_test_helper.h"
#include "util/testutil.h"
#if HAVE_O_CLOEXEC
namespace {
// Exit codes for the helper process spawned by TestCloseOnExec* tests.
// Useful for debugging test failures.
constexpr int kTextCloseOnExecHelperExecFailedCode = 61;
constexpr int kTextCloseOnExecHelperDup2FailedCode = 62;
constexpr int kTextCloseOnExecHelperFoundOpenFdCode = 63;
// Global set by main() and read in TestCloseOnExec.
//
// The argv[0] value is stored in a std::vector instead of a std::string because
// std::string does not return a mutable pointer to its buffer until C++17.
//
// The vector stores the string pointed to by argv[0], plus the trailing null.
std::vector<char>* GetArgvZero() {
static std::vector<char> program_name;
return &program_name;
}
// Command-line switch used to run this test as the CloseOnExecSwitch helper.
static const char kTestCloseOnExecSwitch[] = "--test-close-on-exec-helper";
// Executed in a separate process by TestCloseOnExec* tests.
//
// main() delegates to this function when the test executable is launched with
// a special command-line switch. TestCloseOnExec* tests fork()+exec() the test
// executable and pass the special command-line switch.
//
// main() delegates to this function when the test executable is launched with
// a special command-line switch. TestCloseOnExec* tests fork()+exec() the test
// executable and pass the special command-line switch.
//
// When main() delegates to this function, the process probes whether a given
// file descriptor is open, and communicates the result via its exit code.
int TestCloseOnExecHelperMain(char* pid_arg) {
int fd = std::atoi(pid_arg);
// When given the same file descriptor twice, dup2() returns -1 if the
// file descriptor is closed, or the given file descriptor if it is open.
if (::dup2(fd, fd) == fd) {
std::fprintf(stderr, "Unexpected open fd %d\n", fd);
return kTextCloseOnExecHelperFoundOpenFdCode;
}
// Double-check that dup2() is saying the file descriptor is closed.
if (errno != EBADF) {
std::fprintf(stderr, "Unexpected errno after calling dup2 on fd %d: %s\n",
fd, std::strerror(errno));
return kTextCloseOnExecHelperDup2FailedCode;
}
return 0;
}
// File descriptors are small non-negative integers.
//
// Returns void so the implementation can use ASSERT_EQ.
void GetMaxFileDescriptor(int* result_fd) {
// Get the maximum file descriptor number.
::rlimit fd_rlimit;
ASSERT_EQ(0, ::getrlimit(RLIMIT_NOFILE, &fd_rlimit));
*result_fd = fd_rlimit.rlim_cur;
}
// Iterates through all possible FDs and returns the currently open ones.
//
// Returns void so the implementation can use ASSERT_EQ.
void GetOpenFileDescriptors(std::unordered_set<int>* open_fds) {
int max_fd = 0;
GetMaxFileDescriptor(&max_fd);
for (int fd = 0; fd < max_fd; ++fd) {
if (::dup2(fd, fd) != fd) {
// When given the same file descriptor twice, dup2() returns -1 if the
// file descriptor is closed, or the given file descriptor if it is open.
//
// Double-check that dup2() is saying the fd is closed.
ASSERT_EQ(EBADF, errno)
<< "dup2() should set errno to EBADF on closed file descriptors";
continue;
}
open_fds->insert(fd);
}
}
// Finds an FD open since a previous call to GetOpenFileDescriptors().
//
// |baseline_open_fds| is the result of a previous GetOpenFileDescriptors()
// call. Assumes that exactly one FD was opened since that call.
//
// Returns void so the implementation can use ASSERT_EQ.
void GetNewlyOpenedFileDescriptor(
const std::unordered_set<int>& baseline_open_fds, int* result_fd) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
for (int fd : baseline_open_fds) {
ASSERT_EQ(1, open_fds.count(fd))
<< "Previously opened file descriptor was closed during test setup";
open_fds.erase(fd);
}
ASSERT_EQ(1, open_fds.size())
<< "Expected exactly one newly opened file descriptor during test setup";
*result_fd = *open_fds.begin();
}
// Check that a fork()+exec()-ed child process does not have an extra open FD.
void CheckCloseOnExecDoesNotLeakFDs(
const std::unordered_set<int>& baseline_open_fds) {
// Prepare the argument list for the child process.
// execv() wants mutable buffers.
char switch_buffer[sizeof(kTestCloseOnExecSwitch)];
std::memcpy(switch_buffer, kTestCloseOnExecSwitch,
sizeof(kTestCloseOnExecSwitch));
int probed_fd;
GetNewlyOpenedFileDescriptor(baseline_open_fds, &probed_fd);
std::string fd_string = std::to_string(probed_fd);
std::vector<char> fd_buffer(fd_string.begin(), fd_string.end());
fd_buffer.emplace_back('\0');
// The helper process is launched with the command below.
// env_posix_tests --test-close-on-exec-helper 3
char* child_argv[] = {GetArgvZero()->data(), switch_buffer, fd_buffer.data(),
nullptr};
constexpr int kForkInChildProcessReturnValue = 0;
int child_pid = fork();
if (child_pid == kForkInChildProcessReturnValue) {
::execv(child_argv[0], child_argv);
std::fprintf(stderr, "Error spawning child process: %s\n", strerror(errno));
std::exit(kTextCloseOnExecHelperExecFailedCode);
}
int child_status = 0;
ASSERT_EQ(child_pid, ::waitpid(child_pid, &child_status, 0));
ASSERT_TRUE(WIFEXITED(child_status))
<< "The helper process did not exit with an exit code";
ASSERT_EQ(0, WEXITSTATUS(child_status))
<< "The helper process encountered an error";
}
} // namespace
#endif // HAVE_O_CLOEXEC
namespace leveldb {
static const int kReadOnlyFileLimit = 4;
static const int kMMapLimit = 4;
class EnvPosixTest : public testing::Test {
public:
static void SetFileLimits(int read_only_file_limit, int mmap_limit) {
EnvPosixTestHelper::SetReadOnlyFDLimit(read_only_file_limit);
EnvPosixTestHelper::SetReadOnlyMMapLimit(mmap_limit);
}
EnvPosixTest() : env_(Env::Default()) {}
Env* env_;
};
TEST_F(EnvPosixTest, TestOpenOnRead) {
// Write some test data to a single file that will be opened |n| times.
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string test_file = test_dir + "/open_on_read.txt";
FILE* f = std::fopen(test_file.c_str(), "we");
ASSERT_TRUE(f != nullptr);
const char kFileData[] = "abcdefghijklmnopqrstuvwxyz";
fputs(kFileData, f);
std::fclose(f);
// Open test file some number above the sum of the two limits to force
// open-on-read behavior of POSIX Env leveldb::RandomAccessFile.
const int kNumFiles = kReadOnlyFileLimit + kMMapLimit + 5;
leveldb::RandomAccessFile* files[kNumFiles] = {0};
for (int i = 0; i < kNumFiles; i++) {
ASSERT_LEVELDB_OK(env_->NewRandomAccessFile(test_file, &files[i]));
}
char scratch;
Slice read_result;
for (int i = 0; i < kNumFiles; i++) {
ASSERT_LEVELDB_OK(files[i]->Read(i, 1, &read_result, &scratch));
ASSERT_EQ(kFileData[i], read_result[0]);
}
for (int i = 0; i < kNumFiles; i++) {
delete files[i];
}
ASSERT_LEVELDB_OK(env_->RemoveFile(test_file));
}
#if HAVE_O_CLOEXEC
TEST_F(EnvPosixTest, TestCloseOnExecSequentialFile) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string file_path = test_dir + "/close_on_exec_sequential.txt";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, "0123456789", file_path));
leveldb::SequentialFile* file = nullptr;
ASSERT_LEVELDB_OK(env_->NewSequentialFile(file_path, &file));
CheckCloseOnExecDoesNotLeakFDs(open_fds);
delete file;
ASSERT_LEVELDB_OK(env_->RemoveFile(file_path));
}
TEST_F(EnvPosixTest, TestCloseOnExecRandomAccessFile) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string file_path = test_dir + "/close_on_exec_random_access.txt";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, "0123456789", file_path));
// Exhaust the RandomAccessFile mmap limit. This way, the test
// RandomAccessFile instance below is backed by a file descriptor, not by an
// mmap region.
leveldb::RandomAccessFile* mmapped_files[kReadOnlyFileLimit] = {nullptr};
for (int i = 0; i < kReadOnlyFileLimit; i++) {
ASSERT_LEVELDB_OK(env_->NewRandomAccessFile(file_path, &mmapped_files[i]));
}
leveldb::RandomAccessFile* file = nullptr;
ASSERT_LEVELDB_OK(env_->NewRandomAccessFile(file_path, &file));
CheckCloseOnExecDoesNotLeakFDs(open_fds);
delete file;
for (int i = 0; i < kReadOnlyFileLimit; i++) {
delete mmapped_files[i];
}
ASSERT_LEVELDB_OK(env_->RemoveFile(file_path));
}
TEST_F(EnvPosixTest, TestCloseOnExecWritableFile) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string file_path = test_dir + "/close_on_exec_writable.txt";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, "0123456789", file_path));
leveldb::WritableFile* file = nullptr;
ASSERT_LEVELDB_OK(env_->NewWritableFile(file_path, &file));
CheckCloseOnExecDoesNotLeakFDs(open_fds);
delete file;
ASSERT_LEVELDB_OK(env_->RemoveFile(file_path));
}
TEST_F(EnvPosixTest, TestCloseOnExecAppendableFile) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string file_path = test_dir + "/close_on_exec_appendable.txt";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, "0123456789", file_path));
leveldb::WritableFile* file = nullptr;
ASSERT_LEVELDB_OK(env_->NewAppendableFile(file_path, &file));
CheckCloseOnExecDoesNotLeakFDs(open_fds);
delete file;
ASSERT_LEVELDB_OK(env_->RemoveFile(file_path));
}
TEST_F(EnvPosixTest, TestCloseOnExecLockFile) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string file_path = test_dir + "/close_on_exec_lock.txt";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, "0123456789", file_path));
leveldb::FileLock* lock = nullptr;
ASSERT_LEVELDB_OK(env_->LockFile(file_path, &lock));
CheckCloseOnExecDoesNotLeakFDs(open_fds);
ASSERT_LEVELDB_OK(env_->UnlockFile(lock));
ASSERT_LEVELDB_OK(env_->RemoveFile(file_path));
}
TEST_F(EnvPosixTest, TestCloseOnExecLogger) {
std::unordered_set<int> open_fds;
GetOpenFileDescriptors(&open_fds);
std::string test_dir;
ASSERT_LEVELDB_OK(env_->GetTestDirectory(&test_dir));
std::string file_path = test_dir + "/close_on_exec_logger.txt";
ASSERT_LEVELDB_OK(WriteStringToFile(env_, "0123456789", file_path));
leveldb::Logger* file = nullptr;
ASSERT_LEVELDB_OK(env_->NewLogger(file_path, &file));
CheckCloseOnExecDoesNotLeakFDs(open_fds);
delete file;
ASSERT_LEVELDB_OK(env_->RemoveFile(file_path));
}
#endif // HAVE_O_CLOEXEC
} // namespace leveldb
int main(int argc, char** argv) {
#if HAVE_O_CLOEXEC
// Check if we're invoked as a helper program, or as the test suite.
for (int i = 1; i < argc; ++i) {
if (!std::strcmp(argv[i], kTestCloseOnExecSwitch)) {
return TestCloseOnExecHelperMain(argv[i + 1]);
}
}
// Save argv[0] early, because googletest may modify argv.
GetArgvZero()->assign(argv[0], argv[0] + std::strlen(argv[0]) + 1);
#endif // HAVE_O_CLOEXEC
// All tests currently run with the same read-only file limits.
leveldb::EnvPosixTest::SetFileLimits(leveldb::kReadOnlyFileLimit,
leveldb::kMMapLimit);
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| utf-8 | 1 | BSD-3-clause | 2011-2012 The LevelDB Authors |
libnl3-3.5.0/src/lib/ct.c | /* SPDX-License-Identifier: LGPL-2.1-only */
/*
* src/lib/ct.c CLI Conntrack Helpers
*
* 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 version 2.1
* of the License.
*
* Copyright (c) 2008-2009 Thomas Graf <[email protected]>
*/
/**
* @ingroup cli
* @defgroup cli_ct Connection Tracking
*
* @{
*/
#include <netlink/cli/utils.h>
#include <netlink/cli/ct.h>
struct nfnl_ct *nl_cli_ct_alloc(void)
{
struct nfnl_ct *ct;
ct = nfnl_ct_alloc();
if (!ct)
nl_cli_fatal(ENOMEM, "Unable to allocate conntrack object");
return ct;
}
struct nl_cache *nl_cli_ct_alloc_cache(struct nl_sock *sk)
{
return nl_cli_alloc_cache(sk, "conntrack", nfnl_ct_alloc_cache);
}
void nl_cli_ct_parse_family(struct nfnl_ct *ct, char *arg)
{
int family;
if ((family = nl_str2af(arg)) == AF_UNSPEC)
nl_cli_fatal(EINVAL,
"Unable to nl_cli_ct_parse family \"%s\": %s",
arg, nl_geterror(NLE_INVAL));
nfnl_ct_set_family(ct, family);
}
void nl_cli_ct_parse_protocol(struct nfnl_ct *ct, char *arg)
{
int proto;
if ((proto = nl_str2ip_proto(arg)) < 0)
nl_cli_fatal(proto,
"Unable to nl_cli_ct_parse protocol \"%s\": %s",
arg, nl_geterror(proto));
nfnl_ct_set_proto(ct, proto);
}
void nl_cli_ct_parse_mark(struct nfnl_ct *ct, char *arg)
{
uint32_t mark = nl_cli_parse_u32(arg);
nfnl_ct_set_mark(ct, mark);
}
void nl_cli_ct_parse_timeout(struct nfnl_ct *ct, char *arg)
{
uint32_t timeout = nl_cli_parse_u32(arg);
nfnl_ct_set_timeout(ct, timeout);
}
void nl_cli_ct_parse_id(struct nfnl_ct *ct, char *arg)
{
uint32_t id = nl_cli_parse_u32(arg);
nfnl_ct_set_id(ct, id);
}
void nl_cli_ct_parse_use(struct nfnl_ct *ct, char *arg)
{
uint32_t use = nl_cli_parse_u32(arg);
nfnl_ct_set_use(ct, use);
}
void nl_cli_ct_parse_src(struct nfnl_ct *ct, int reply, char *arg)
{
int err;
struct nl_addr *a = nl_cli_addr_parse(arg, nfnl_ct_get_family(ct));
if ((err = nfnl_ct_set_src(ct, reply, a)) < 0)
nl_cli_fatal(err, "Unable to set source address: %s",
nl_geterror(err));
}
void nl_cli_ct_parse_dst(struct nfnl_ct *ct, int reply, char *arg)
{
int err;
struct nl_addr *a = nl_cli_addr_parse(arg, nfnl_ct_get_family(ct));
if ((err = nfnl_ct_set_dst(ct, reply, a)) < 0)
nl_cli_fatal(err, "Unable to set destination address: %s",
nl_geterror(err));
}
void nl_cli_ct_parse_src_port(struct nfnl_ct *ct, int reply, char *arg)
{
uint32_t port = nl_cli_parse_u32(arg);
nfnl_ct_set_src_port(ct, reply, port);
}
void nl_cli_ct_parse_dst_port(struct nfnl_ct *ct, int reply, char *arg)
{
uint32_t port = nl_cli_parse_u32(arg);
nfnl_ct_set_dst_port(ct, reply, port);
}
void nl_cli_ct_parse_tcp_state(struct nfnl_ct *ct, char *arg)
{
int state;
if ((state = nfnl_ct_str2tcp_state(arg)) < 0)
nl_cli_fatal(state,
"Unable to nl_cli_ct_parse tcp state \"%s\": %s",
arg, nl_geterror(state));
nfnl_ct_set_tcp_state(ct, state);
}
void nl_cli_ct_parse_status(struct nfnl_ct *ct, char *arg)
{
int status;
if ((status = nfnl_ct_str2status(arg)) < 0)
nl_cli_fatal(status,
"Unable to nl_cli_ct_parse flags \"%s\": %s",
arg, nl_geterror(status));
nfnl_ct_set_status(ct, status);
}
void nl_cli_ct_parse_zone(struct nfnl_ct *ct, char *arg)
{
uint32_t zone = nl_cli_parse_u32(arg);
nfnl_ct_set_zone(ct, zone);
}
#if 0
} else if (arg_match("origicmpid")) {
if (argc > ++idx)
nfnl_ct_set_icmp_id(ct, 0, strtoul(argv[idx++], NULL, 0));
} else if (arg_match("origicmptype")) {
if (argc > ++idx)
nfnl_ct_set_icmp_type(ct, 0, strtoul(argv[idx++], NULL, 0));
} else if (arg_match("origicmpcode")) {
if (argc > ++idx)
nfnl_ct_set_icmp_code(ct, 0, strtoul(argv[idx++], NULL, 0));
} else if (arg_match("replyicmpid")) {
if (argc > ++idx)
nfnl_ct_set_icmp_id(ct, 1, strtoul(argv[idx++], NULL, 0));
} else if (arg_match("replyicmptype")) {
if (argc > ++idx)
nfnl_ct_set_icmp_type(ct, 1, strtoul(argv[idx++], NULL, 0));
} else if (arg_match("replyicmpcode")) {
if (argc > ++idx)
nfnl_ct_set_icmp_code(ct, 1, strtoul(argv[idx++], NULL, 0));
}
#endif
/** @} */
| utf-8 | 1 | unknown | unknown |
pdal-2.3.0+ds/kernels/TranslateKernel.cpp | /******************************************************************************
* Copyright (c) 2011, Michael P. Gerlek ([email protected])
* Copyright (c) 2015, Bradley J Chambers ([email protected])
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following
* conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Hobu, Inc. or Flaxen Geo Consulting nor the
* names of its contributors may be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
****************************************************************************/
#include "TranslateKernel.hpp"
#include <pdal/PipelineWriter.hpp>
#include <pdal/PointTable.hpp>
#include <pdal/PointView.hpp>
#include <pdal/Reader.hpp>
#include <pdal/StageFactory.hpp>
#include <pdal/PipelineReaderJSON.hpp>
#include <pdal/Writer.hpp>
#include <pdal/util/FileUtils.hpp>
#include <memory>
#include <string>
#include <vector>
namespace pdal
{
static StaticPluginInfo const s_info
{
"kernels.translate",
"The Translate kernel allows users to construct a pipeline " \
"consisting of a reader, a writer, and N filter stages. " \
"Any supported stage type can be specified from the command " \
"line, reducing the need to create custom kernels for every " \
"combination.",
"http://pdal.io/apps/translate.html"
};
CREATE_STATIC_KERNEL(TranslateKernel, s_info)
std::string TranslateKernel::getName() const
{
return s_info.name;
}
TranslateKernel::TranslateKernel()
{}
void TranslateKernel::addSwitches(ProgramArgs& args)
{
args.add("input,i", "Input filename", m_inputFile).
setPositional();
args.add("output,o", "Output filename", m_outputFile).
setPositional();
args.add("filter,f", "Filter type", m_filterType).
setOptionalPositional();
args.add("json", "PDAL pipeline from which to extract filters.",
m_filterJSON);
args.add("pipeline,p", "Pipeline output", m_pipelineOutputFile);
args.add("metadata,m", "Dump metadata output to the specified file",
m_metadataFile);
args.add("reader,r", "Reader type", m_readerType);
args.add("writer,w", "Writer type", m_writerType);
args.add("nostream", "Run in standard mode", m_noStream);
args.add("stream", "Run in stream mode. Error if not possible.", m_stream);
args.add("dims", "Dimensions to store", m_dimNames);
}
void TranslateKernel::validateSwitches(ProgramArgs&)
{
if (m_stream && m_noStream)
throw pdal_error("Can't specify both 'stream' and 'nostream' options.");
if (m_stream)
m_mode = ExecMode::Stream;
else if (m_noStream)
m_mode = ExecMode::Standard;
else
m_mode = ExecMode::PreferStream;
}
/*
Build a pipeline from a JSON filter specification.
*/
void TranslateKernel::makeJSONPipeline()
{
std::string json;
if (pdal::FileUtils::fileExists(m_filterJSON))
json = pdal::FileUtils::readFileIntoString(m_filterJSON);
if (json.empty())
json = m_filterJSON;
std::stringstream in(json);
m_manager.readPipeline(in);
std::vector<Stage *> roots = m_manager.roots();
if (roots.size() > 1)
throw pdal_error("Can't process pipeline with more than one root.");
Stage *r(nullptr);
if (roots.size())
r = dynamic_cast<Reader *>(roots[0]);
if (r)
{
StageCreationOptions ops { m_inputFile, m_readerType, nullptr,
Options(), r->tag() };
m_manager.replace(r, &m_manager.makeReader(ops));
}
else
{
r = &m_manager.makeReader(m_inputFile, m_readerType);
if (roots.size())
roots[0]->setInput(*r);
}
std::vector<Stage *> leaves = m_manager.leaves();
if (leaves.size() != 1)
throw pdal_error("Can't process pipeline with more than one "
"terminal stage.");
Stage *w = dynamic_cast<Writer *>(leaves[0]);
if (w)
m_manager.replace(w, &m_manager.makeWriter(m_outputFile, m_writerType));
else
{
// We know we have a leaf because we added a reader.
StageCreationOptions ops { m_outputFile, m_writerType, leaves[0],
Options(), "" }; // These last two args just keep compiler quiet.
m_manager.makeWriter(ops);
}
}
/*
Build a pipeline from filters specified as command-line arguments.
*/
void TranslateKernel::makeArgPipeline()
{
std::string readerType(m_readerType);
if (!readerType.empty() && !Utils::startsWith(readerType, "readers."))
readerType.insert(0, "readers.");
Stage& reader = m_manager.makeReader(m_inputFile, readerType);
Stage* stage = &reader;
// add each filter provided on the command-line,
// updating the stage pointer
for (auto const& f : m_filterType)
{
std::string filter_name(f);
if (!Utils::startsWith(f, "filters."))
filter_name.insert(0, "filters.");
Stage& filter = m_manager.makeFilter(filter_name, *stage);
stage = &filter;
}
std::string writerType(m_writerType);
if (!writerType.empty() && !Utils::startsWith(writerType, "writers."))
writerType.insert(0, "writers.");
m_manager.makeWriter(m_outputFile, writerType, *stage);
}
int TranslateKernel::execute()
{
std::ostream *metaOut(nullptr);
if (m_filterJSON.size() && m_filterType.size())
throw pdal_error("Cannot set both --filter options and --json options");
if (m_metadataFile.size())
{
if (m_pipelineOutputFile.size())
m_log->get(LogLevel::Info) << "Metadata will not be written. "
"'pipeline' option prevents execution.";
else
{
metaOut = FileUtils::createFile(m_metadataFile);
if (! metaOut)
throw pdal_error("Couldn't output metadata output file '" +
m_metadataFile + "'.");
}
}
if (!m_filterJSON.empty())
makeJSONPipeline();
else
makeArgPipeline();
// If we write pipeline output, we don't run, and therefore don't write
if (m_pipelineOutputFile.size() > 0)
{
PipelineWriter::writePipeline(m_manager.getStage(),
m_pipelineOutputFile);
return 0;
}
m_manager.pointTable().layout()->setAllowedDims(m_dimNames);
if (m_manager.execute(m_mode).m_mode == ExecMode::None)
throw pdal_error("Couldn't run translation pipeline in requested "
"execution mode.");
if (metaOut)
{
MetadataNode m = m_manager.getMetadata();
*metaOut << Utils::toJSON(m);
FileUtils::closeFile(metaOut);
}
return 0;
}
} // namespace pdal
| utf-8 | 1 | BSD-3-Clause | 2014-2021, Hobu, Inc. <[email protected]>
2021, Preston J. Hartzell <[email protected]>
2011-2020, Bradley J Chambers <[email protected]>
2020, Julian Fell <[email protected]>
2020, Ryan Pals <[email protected]>
2014, 2016-2019, Connor Manning <[email protected]>
2011-2012, 2014, 2019, Michael P. Gerlek <[email protected]>
2019, Aurelien Vila <[email protected]>
2019, Guilhem Villemin <[email protected]>
2019, Helix Re Inc.
2019, Kirk McKelvey ([email protected])
2019, Peter L. Svendsen <[email protected]>
2019, TileDB, Inc
2018, Danish Agency for Data Supply and Efficiency
2018, Kyle Mann <[email protected]>
2018, Paul Blottiere <[email protected]>
2018, RIEGL Laser Measurement Systems GmbH <[email protected]>
2009-2017, Howard Butler <[email protected]>
2014-2017, Peter J. Gadomski <[email protected]>
2017, Jason Beverage <[email protected]>
2014-2016, RadiantBlue Technologies, Inc
2015, James W. O'Meara <[email protected]>
2010, 2013-2014, Andrew Bell
2013, Paul Ramsey <[email protected]>
2009-2012, Willow Garage, Inc
2012, Open Perception, Inc
2011, Michael S. Rosen <[email protected]>
2010, Frank Warmerdam
2008, Mateusz Loskot
2008, Phil Vachon
2005, Google Inc.
1996-1997, Theodore Ts'o
Mathias Panzenböck |
dosbox-0.74-3/src/ints/bios.cpp | /*
* Copyright (C) 2002-2010 The DOSBox Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
/* $Id: bios.cpp,v 1.78 2009-10-10 13:26:46 h-a-l-9000 Exp $ */
#include "dosbox.h"
#include "mem.h"
#include "bios.h"
#include "regs.h"
#include "cpu.h"
#include "callback.h"
#include "inout.h"
#include "pic.h"
#include "hardware.h"
#include "joystick.h"
#include "mouse.h"
#include "setup.h"
#include "serialport.h"
/* if mem_systems 0 then size_extended is reported as the real size else
* zero is reported. ems and xms can increase or decrease the other_memsystems
* counter using the BIOS_ZeroExtendedSize call */
static Bit16u size_extended;
static Bits other_memsystems=0;
void CMOS_SetRegister(Bitu regNr, Bit8u val); //For setting equipment word
static Bitu INT70_Handler(void) {
/* Acknowledge irq with cmos */
IO_Write(0x70,0xc);
IO_Read(0x71);
if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) {
Bit32u count=mem_readd(BIOS_WAIT_FLAG_COUNT);
if (count>997) {
mem_writed(BIOS_WAIT_FLAG_COUNT,count-997);
} else {
mem_writed(BIOS_WAIT_FLAG_COUNT,0);
PhysPt where=Real2Phys(mem_readd(BIOS_WAIT_FLAG_POINTER));
mem_writeb(where,mem_readb(where)|0x80);
mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0);
mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP));
IO_Write(0x70,0xb);
IO_Write(0x71,IO_Read(0x71)&~0x40);
}
}
/* Signal EOI to both pics */
IO_Write(0xa0,0x20);
IO_Write(0x20,0x20);
return 0;
}
CALLBACK_HandlerObject* tandy_DAC_callback[2];
static struct {
Bit16u port;
Bit8u irq;
Bit8u dma;
} tandy_sb;
static struct {
Bit16u port;
Bit8u irq;
Bit8u dma;
} tandy_dac;
static bool Tandy_InitializeSB() {
/* see if soundblaster module available and at what port/IRQ/DMA */
Bitu sbport, sbirq, sbdma;
if (SB_Get_Address(sbport, sbirq, sbdma)) {
tandy_sb.port=(Bit16u)(sbport&0xffff);
tandy_sb.irq =(Bit8u)(sbirq&0xff);
tandy_sb.dma =(Bit8u)(sbdma&0xff);
return true;
} else {
/* no soundblaster accessible, disable Tandy DAC */
tandy_sb.port=0;
return false;
}
}
static bool Tandy_InitializeTS() {
/* see if Tandy DAC module available and at what port/IRQ/DMA */
Bitu tsport, tsirq, tsdma;
if (TS_Get_Address(tsport, tsirq, tsdma)) {
tandy_dac.port=(Bit16u)(tsport&0xffff);
tandy_dac.irq =(Bit8u)(tsirq&0xff);
tandy_dac.dma =(Bit8u)(tsdma&0xff);
return true;
} else {
/* no Tandy DAC accessible */
tandy_dac.port=0;
return false;
}
}
/* check if Tandy DAC is still playing */
static bool Tandy_TransferInProgress(void) {
if (real_readw(0x40,0xd0)) return true; /* not yet done */
if (real_readb(0x40,0xd4)==0xff) return false; /* still in init-state */
Bit8u tandy_dma = 1;
if (tandy_sb.port) tandy_dma = tandy_sb.dma;
else if (tandy_dac.port) tandy_dma = tandy_dac.dma;
IO_Write(0x0c,0x00);
Bit16u datalen=(Bit8u)(IO_ReadB(tandy_dma*2+1)&0xff);
datalen|=(IO_ReadB(tandy_dma*2+1)<<8);
if (datalen==0xffff) return false; /* no DMA transfer */
else if ((datalen<0x10) && (real_readb(0x40,0xd4)==0x0f) && (real_readw(0x40,0xd2)==0x1c)) {
/* stop already requested */
return false;
}
return true;
}
static void Tandy_SetupTransfer(PhysPt bufpt,bool isplayback) {
Bitu length=real_readw(0x40,0xd0);
if (length==0) return; /* nothing to do... */
if ((tandy_sb.port==0) && (tandy_dac.port==0)) return;
Bit8u tandy_irq = 7;
if (tandy_sb.port) tandy_irq = tandy_sb.irq;
else if (tandy_dac.port) tandy_irq = tandy_dac.irq;
Bit8u tandy_irq_vector = tandy_irq;
if (tandy_irq_vector<8) tandy_irq_vector += 8;
else tandy_irq_vector += (0x70-8);
/* revector IRQ-handler if necessary */
RealPt current_irq=RealGetVec(tandy_irq_vector);
if (current_irq!=tandy_DAC_callback[0]->Get_RealPointer()) {
real_writed(0x40,0xd6,current_irq);
RealSetVec(tandy_irq_vector,tandy_DAC_callback[0]->Get_RealPointer());
}
Bit8u tandy_dma = 1;
if (tandy_sb.port) tandy_dma = tandy_sb.dma;
else if (tandy_dac.port) tandy_dma = tandy_dac.dma;
if (tandy_sb.port) {
IO_Write(tandy_sb.port+0xc,0xd0); /* stop DMA transfer */
IO_Write(0x21,IO_Read(0x21)&(~(1<<tandy_irq))); /* unmask IRQ */
IO_Write(tandy_sb.port+0xc,0xd1); /* turn speaker on */
} else {
IO_Write(tandy_dac.port,IO_Read(tandy_dac.port)&0x60); /* disable DAC */
IO_Write(0x21,IO_Read(0x21)&(~(1<<tandy_irq))); /* unmask IRQ */
}
IO_Write(0x0a,0x04|tandy_dma); /* mask DMA channel */
IO_Write(0x0c,0x00); /* clear DMA flipflop */
if (isplayback) IO_Write(0x0b,0x48|tandy_dma);
else IO_Write(0x0b,0x44|tandy_dma);
/* set physical address of buffer */
Bit8u bufpage=(Bit8u)((bufpt>>16)&0xff);
IO_Write(tandy_dma*2,(Bit8u)(bufpt&0xff));
IO_Write(tandy_dma*2,(Bit8u)((bufpt>>8)&0xff));
switch (tandy_dma) {
case 0: IO_Write(0x87,bufpage); break;
case 1: IO_Write(0x83,bufpage); break;
case 2: IO_Write(0x81,bufpage); break;
case 3: IO_Write(0x82,bufpage); break;
}
real_writeb(0x40,0xd4,bufpage);
/* calculate transfer size (respects segment boundaries) */
Bit32u tlength=length;
if (tlength+(bufpt&0xffff)>0x10000) tlength=0x10000-(bufpt&0xffff);
real_writew(0x40,0xd0,(Bit16u)(length-tlength)); /* remaining buffer length */
tlength--;
/* set transfer size */
IO_Write(tandy_dma*2+1,(Bit8u)(tlength&0xff));
IO_Write(tandy_dma*2+1,(Bit8u)((tlength>>8)&0xff));
Bit16u delay=(Bit16u)(real_readw(0x40,0xd2)&0xfff);
Bit8u amplitude=(Bit8u)((real_readw(0x40,0xd2)>>13)&0x7);
if (tandy_sb.port) {
IO_Write(0x0a,tandy_dma); /* enable DMA channel */
/* set frequency */
IO_Write(tandy_sb.port+0xc,0x40);
IO_Write(tandy_sb.port+0xc,256-delay*100/358);
/* set playback type to 8bit */
if (isplayback) IO_Write(tandy_sb.port+0xc,0x14);
else IO_Write(tandy_sb.port+0xc,0x24);
/* set transfer size */
IO_Write(tandy_sb.port+0xc,(Bit8u)(tlength&0xff));
IO_Write(tandy_sb.port+0xc,(Bit8u)((tlength>>8)&0xff));
} else {
if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x03);
else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x02);
IO_Write(tandy_dac.port+2,(Bit8u)(delay&0xff));
IO_Write(tandy_dac.port+3,(Bit8u)(((delay>>8)&0xf) | (amplitude<<5)));
if (isplayback) IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x1f);
else IO_Write(tandy_dac.port,(IO_Read(tandy_dac.port)&0x7c) | 0x1e);
IO_Write(0x0a,tandy_dma); /* enable DMA channel */
}
if (!isplayback) {
/* mark transfer as recording operation */
real_writew(0x40,0xd2,(Bit16u)(delay|0x1000));
}
}
static Bitu IRQ_TandyDAC(void) {
if (tandy_dac.port) {
IO_Read(tandy_dac.port);
}
if (real_readw(0x40,0xd0)) { /* play/record next buffer */
/* acknowledge IRQ */
IO_Write(0x20,0x20);
if (tandy_sb.port) {
IO_Read(tandy_sb.port+0xe);
}
/* buffer starts at the next page */
Bit8u npage=real_readb(0x40,0xd4)+1;
real_writeb(0x40,0xd4,npage);
Bitu rb=real_readb(0x40,0xd3);
if (rb&0x10) {
/* start recording */
real_writeb(0x40,0xd3,rb&0xef);
Tandy_SetupTransfer(npage<<16,false);
} else {
/* start playback */
Tandy_SetupTransfer(npage<<16,true);
}
} else { /* playing/recording is finished */
Bit8u tandy_irq = 7;
if (tandy_sb.port) tandy_irq = tandy_sb.irq;
else if (tandy_dac.port) tandy_irq = tandy_dac.irq;
Bit8u tandy_irq_vector = tandy_irq;
if (tandy_irq_vector<8) tandy_irq_vector += 8;
else tandy_irq_vector += (0x70-8);
RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6));
/* turn off speaker and acknowledge soundblaster IRQ */
if (tandy_sb.port) {
IO_Write(tandy_sb.port+0xc,0xd3);
IO_Read(tandy_sb.port+0xe);
}
/* issue BIOS tandy sound device busy callout */
SegSet16(cs, RealSeg(tandy_DAC_callback[1]->Get_RealPointer()));
reg_ip = RealOff(tandy_DAC_callback[1]->Get_RealPointer());
}
return CBRET_NONE;
}
static void TandyDAC_Handler(Bit8u tfunction) {
if ((!tandy_sb.port) && (!tandy_dac.port)) return;
switch (tfunction) {
case 0x81: /* Tandy sound system check */
if (tandy_dac.port) {
reg_ax=tandy_dac.port;
} else {
reg_ax=0xc4;
}
CALLBACK_SCF(Tandy_TransferInProgress());
break;
case 0x82: /* Tandy sound system start recording */
case 0x83: /* Tandy sound system start playback */
if (Tandy_TransferInProgress()) {
/* cannot play yet as the last transfer isn't finished yet */
reg_ah=0x00;
CALLBACK_SCF(true);
break;
}
/* store buffer length */
real_writew(0x40,0xd0,reg_cx);
/* store delay and volume */
real_writew(0x40,0xd2,(reg_dx&0xfff)|((reg_al&7)<<13));
Tandy_SetupTransfer(PhysMake(SegValue(es),reg_bx),reg_ah==0x83);
reg_ah=0x00;
CALLBACK_SCF(false);
break;
case 0x84: /* Tandy sound system stop playing */
reg_ah=0x00;
/* setup for a small buffer with silence */
real_writew(0x40,0xd0,0x0a);
real_writew(0x40,0xd2,0x1c);
Tandy_SetupTransfer(PhysMake(0xf000,0xa084),true);
CALLBACK_SCF(false);
break;
case 0x85: /* Tandy sound system reset */
if (tandy_dac.port) {
IO_Write(tandy_dac.port,(Bit8u)(IO_Read(tandy_dac.port)&0xe0));
}
reg_ah=0x00;
CALLBACK_SCF(false);
break;
}
}
static Bitu INT1A_Handler(void) {
switch (reg_ah) {
case 0x00: /* Get System time */
{
Bit32u ticks=mem_readd(BIOS_TIMER);
reg_al=0; /* Midnight never passes :) */
reg_cx=(Bit16u)(ticks >> 16);
reg_dx=(Bit16u)(ticks & 0xffff);
break;
}
case 0x01: /* Set System time */
mem_writed(BIOS_TIMER,(reg_cx<<16)|reg_dx);
break;
case 0x02: /* GET REAL-TIME CLOCK TIME (AT,XT286,PS) */
IO_Write(0x70,0x04); //Hours
reg_ch=IO_Read(0x71);
IO_Write(0x70,0x02); //Minutes
reg_cl=IO_Read(0x71);
IO_Write(0x70,0x00); //Seconds
reg_dh=IO_Read(0x71);
reg_dl=0; //Daylight saving disabled
CALLBACK_SCF(false);
break;
case 0x04: /* GET REAL-TIME ClOCK DATE (AT,XT286,PS) */
IO_Write(0x70,0x32); //Centuries
reg_ch=IO_Read(0x71);
IO_Write(0x70,0x09); //Years
reg_cl=IO_Read(0x71);
IO_Write(0x70,0x08); //Months
reg_dh=IO_Read(0x71);
IO_Write(0x70,0x07); //Days
reg_dl=IO_Read(0x71);
CALLBACK_SCF(false);
break;
case 0x80: /* Pcjr Setup Sound Multiplexer */
LOG(LOG_BIOS,LOG_ERROR)("INT1A:80:Setup tandy sound multiplexer to %d",reg_al);
break;
case 0x81: /* Tandy sound system check */
case 0x82: /* Tandy sound system start recording */
case 0x83: /* Tandy sound system start playback */
case 0x84: /* Tandy sound system stop playing */
case 0x85: /* Tandy sound system reset */
TandyDAC_Handler(reg_ah);
break;
case 0xb1: /* PCI Bios Calls */
LOG(LOG_BIOS,LOG_ERROR)("INT1A:PCI bios call %2X",reg_al);
CALLBACK_SCF(true);
break;
default:
LOG(LOG_BIOS,LOG_ERROR)("INT1A:Undefined call %2X",reg_ah);
}
return CBRET_NONE;
}
static Bitu INT11_Handler(void) {
reg_ax=mem_readw(BIOS_CONFIGURATION);
return CBRET_NONE;
}
/*
* Define the following define to 1 if you want dosbox to check
* the system time every 5 seconds and adjust 1/2 a second to sync them.
*/
#ifndef DOSBOX_CLOCKSYNC
#define DOSBOX_CLOCKSYNC 0
#endif
static Bitu INT8_Handler(void) {
/* Increase the bios tick counter */
Bit32u value = mem_readd(BIOS_TIMER) + 1;
#if DOSBOX_CLOCKSYNC
static bool check = false;
if((value %50)==0) {
if(((value %100)==0) && check) {
check = false;
time_t curtime;struct tm *loctime;
curtime = time (NULL);loctime = localtime (&curtime);
Bit32u ticksnu = (Bit32u)((loctime->tm_hour*3600+loctime->tm_min*60+loctime->tm_sec)*(float)PIT_TICK_RATE/65536.0);
Bit32s bios = value;Bit32s tn = ticksnu;
Bit32s diff = tn - bios;
if(diff>0) {
if(diff < 18) { diff = 0; } else diff = 9;
} else {
if(diff > -18) { diff = 0; } else diff = -9;
}
value += diff;
} else if((value%100)==50) check = true;
}
#endif
mem_writed(BIOS_TIMER,value);
/* decrease floppy motor timer */
Bit8u val = mem_readb(BIOS_DISK_MOTOR_TIMEOUT);
if (val) mem_writeb(BIOS_DISK_MOTOR_TIMEOUT,val-1);
/* and running drive */
mem_writeb(BIOS_DRIVE_RUNNING,mem_readb(BIOS_DRIVE_RUNNING) & 0xF0);
return CBRET_NONE;
}
#undef DOSBOX_CLOCKSYNC
static Bitu INT1C_Handler(void) {
return CBRET_NONE;
}
static Bitu INT12_Handler(void) {
reg_ax=mem_readw(BIOS_MEMORY_SIZE);
return CBRET_NONE;
}
static Bitu INT17_Handler(void) {
LOG(LOG_BIOS,LOG_NORMAL)("INT17:Function %X",reg_ah);
switch(reg_ah) {
case 0x00: /* PRINTER: Write Character */
reg_ah=1; /* Report a timeout */
break;
case 0x01: /* PRINTER: Initialize port */
break;
case 0x02: /* PRINTER: Get Status */
reg_ah=0;
break;
case 0x20: /* Some sort of printerdriver install check*/
break;
default:
E_Exit("Unhandled INT 17 call %2X",reg_ah);
};
return CBRET_NONE;
}
static Bit8u INT14_Wait(Bit16u port, Bit8u mask, Bit8u timeout) {
double starttime = PIC_FullIndex();
double timeout_f = timeout * 1000.0;
Bit8u retval;
while (((retval = IO_ReadB(port)) & mask) != mask) {
if (starttime < (PIC_FullIndex() - timeout_f)) {
retval |= 0x80;
break;
}
CALLBACK_Idle();
}
return retval;
}
static Bitu INT14_Handler(void) {
if (reg_ah > 0x3 || reg_dx > 0x3) { // 0-3 serial port functions
// and no more than 4 serial ports
LOG_MSG("BIOS INT14: Unhandled call AH=%2X DX=%4x",reg_ah,reg_dx);
return CBRET_NONE;
}
Bit16u port = real_readw(0x40,reg_dx*2); // DX is always port number
Bit8u timeout = mem_readb(BIOS_COM1_TIMEOUT + reg_dx);
if (port==0) {
LOG(LOG_BIOS,LOG_NORMAL)("BIOS INT14: port %d does not exist.",reg_dx);
return CBRET_NONE;
}
switch (reg_ah) {
case 0x00: {
// Initialize port
// Parameters: Return:
// AL: port parameters AL: modem status
// AH: line status
// set baud rate
Bitu baudrate = 9600;
Bit16u baudresult;
Bitu rawbaud=reg_al>>5;
if (rawbaud==0){ baudrate=110;}
else if (rawbaud==1){ baudrate=150;}
else if (rawbaud==2){ baudrate=300;}
else if (rawbaud==3){ baudrate=600;}
else if (rawbaud==4){ baudrate=1200;}
else if (rawbaud==5){ baudrate=2400;}
else if (rawbaud==6){ baudrate=4800;}
else if (rawbaud==7){ baudrate=9600;}
baudresult = (Bit16u)(115200 / baudrate);
IO_WriteB(port+3, 0x80); // enable divider access
IO_WriteB(port, (Bit8u)baudresult&0xff);
IO_WriteB(port+1, (Bit8u)(baudresult>>8));
// set line parameters, disable divider access
IO_WriteB(port+3, reg_al&0x1F); // LCR
// disable interrupts
IO_WriteB(port+1, 0); // IER
// get result
reg_ah=(Bit8u)(IO_ReadB(port+5)&0xff);
reg_al=(Bit8u)(IO_ReadB(port+6)&0xff);
CALLBACK_SCF(false);
break;
}
case 0x01: { // Transmit character
// Parameters: Return:
// AL: character AL: unchanged
// AH: 0x01 AH: line status from just before the char was sent
// (0x80 | unpredicted) in case of timeout
// [undoc] (0x80 | line status) in case of tx timeout
// [undoc] (0x80 | modem status) in case of dsr/cts timeout
// set DTR & RTS on
IO_WriteB(port+4,0x3);
// wait for DSR & CTS
reg_ah = INT14_Wait(port+6, 0x30, timeout);
if (!(reg_ah & 0x80)) {
// wait for TX buffer empty
reg_ah = INT14_Wait(port+5, 0x20, timeout);
if (!(reg_ah & 0x80)) {
// fianlly send the character
IO_WriteB(port,reg_al);
}
} // else timed out
CALLBACK_SCF(false);
break;
}
case 0x02: // Read character
// Parameters: Return:
// AH: 0x02 AL: received character
// [undoc] will be trashed in case of timeout
// AH: (line status & 0x1E) in case of success
// (0x80 | unpredicted) in case of timeout
// [undoc] (0x80 | line status) in case of rx timeout
// [undoc] (0x80 | modem status) in case of dsr timeout
// set DTR on
IO_WriteB(port+4,0x1);
// wait for DSR
reg_ah = INT14_Wait(port+6, 0x20, timeout);
if (!(reg_ah & 0x80)) {
// wait for character to arrive
reg_ah = INT14_Wait(port+5, 0x01, timeout);
if (!(reg_ah & 0x80)) {
reg_ah &= 0x1E;
reg_al = IO_ReadB(port);
}
}
CALLBACK_SCF(false);
break;
case 0x03: // get status
reg_ah=(Bit8u)(IO_ReadB(port+5)&0xff);
reg_al=(Bit8u)(IO_ReadB(port+6)&0xff);
CALLBACK_SCF(false);
break;
}
return CBRET_NONE;
}
static Bitu INT15_Handler(void) {
static Bit16u biosConfigSeg=0;
switch (reg_ah) {
case 0x06:
LOG(LOG_BIOS,LOG_NORMAL)("INT15 Unknown Function 6");
break;
case 0xC0: /* Get Configuration*/
{
if (biosConfigSeg==0) biosConfigSeg = DOS_GetMemory(1); //We have 16 bytes
PhysPt data = PhysMake(biosConfigSeg,0);
mem_writew(data,8); // 8 Bytes following
if (IS_TANDY_ARCH) {
if (machine==MCH_TANDY) {
// Model ID (Tandy)
mem_writeb(data+2,0xFF);
} else {
// Model ID (PCJR)
mem_writeb(data+2,0xFD);
}
mem_writeb(data+3,0x0A); // Submodel ID
mem_writeb(data+4,0x10); // Bios Revision
/* Tandy doesn't have a 2nd PIC, left as is for now */
mem_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1
} else {
mem_writeb(data+2,0xFC); // Model ID (PC)
mem_writeb(data+3,0x00); // Submodel ID
mem_writeb(data+4,0x01); // Bios Revision
mem_writeb(data+5,(1<<6)|(1<<5)|(1<<4)); // Feature Byte 1
}
mem_writeb(data+6,(1<<6)); // Feature Byte 2
mem_writeb(data+7,0); // Feature Byte 3
mem_writeb(data+8,0); // Feature Byte 4
mem_writeb(data+9,0); // Feature Byte 5
CPU_SetSegGeneral(es,biosConfigSeg);
reg_bx = 0;
reg_ah = 0;
CALLBACK_SCF(false);
}; break;
case 0x4f: /* BIOS - Keyboard intercept */
/* Carry should be set but let's just set it just in case */
CALLBACK_SCF(true);
break;
case 0x83: /* BIOS - SET EVENT WAIT INTERVAL */
{
if(reg_al == 0x01) { /* Cancel it */
mem_writeb(BIOS_WAIT_FLAG_ACTIVE,0);
IO_Write(0x70,0xb);
IO_Write(0x71,IO_Read(0x71)&~0x40);
CALLBACK_SCF(false);
break;
}
if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) {
reg_ah=0x80;
CALLBACK_SCF(true);
break;
}
Bit32u count=(reg_cx<<16)|reg_dx;
mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(SegValue(es),reg_bx));
mem_writed(BIOS_WAIT_FLAG_COUNT,count);
mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1);
/* Reprogram RTC to start */
IO_Write(0x70,0xb);
IO_Write(0x71,IO_Read(0x71)|0x40);
CALLBACK_SCF(false);
}
break;
case 0x84: /* BIOS - JOYSTICK SUPPORT (XT after 11/8/82,AT,XT286,PS) */
if (reg_dx == 0x0000) {
// Get Joystick button status
if (JOYSTICK_IsEnabled(0) || JOYSTICK_IsEnabled(1)) {
reg_al = IO_ReadB(0x201)&0xf0;
CALLBACK_SCF(false);
} else {
// dos values
reg_ax = 0x00f0; reg_dx = 0x0201;
CALLBACK_SCF(true);
}
} else if (reg_dx == 0x0001) {
if (JOYSTICK_IsEnabled(0)) {
reg_ax = (Bit16u)(JOYSTICK_GetMove_X(0)*127+128);
reg_bx = (Bit16u)(JOYSTICK_GetMove_Y(0)*127+128);
if(JOYSTICK_IsEnabled(1)) {
reg_cx = (Bit16u)(JOYSTICK_GetMove_X(1)*127+128);
reg_dx = (Bit16u)(JOYSTICK_GetMove_Y(1)*127+128);
}
else {
reg_cx = reg_dx = 0;
}
CALLBACK_SCF(false);
} else if (JOYSTICK_IsEnabled(1)) {
reg_ax = reg_bx = 0;
reg_cx = (Bit16u)(JOYSTICK_GetMove_X(1)*127+128);
reg_dx = (Bit16u)(JOYSTICK_GetMove_Y(1)*127+128);
CALLBACK_SCF(false);
} else {
reg_ax = reg_bx = reg_cx = reg_dx = 0;
CALLBACK_SCF(true);
}
} else {
LOG(LOG_BIOS,LOG_ERROR)("INT15:84:Unknown Bios Joystick functionality.");
}
break;
case 0x86: /* BIOS - WAIT (AT,PS) */
{
if (mem_readb(BIOS_WAIT_FLAG_ACTIVE)) {
reg_ah=0x83;
CALLBACK_SCF(true);
break;
}
Bit32u count=(reg_cx<<16)|reg_dx;
mem_writed(BIOS_WAIT_FLAG_POINTER,RealMake(0,BIOS_WAIT_FLAG_TEMP));
mem_writed(BIOS_WAIT_FLAG_COUNT,count);
mem_writeb(BIOS_WAIT_FLAG_ACTIVE,1);
/* Reprogram RTC to start */
IO_Write(0x70,0xb);
IO_Write(0x71,IO_Read(0x71)|0x40);
while (mem_readd(BIOS_WAIT_FLAG_COUNT)) {
CALLBACK_Idle();
}
CALLBACK_SCF(false);
}
case 0x87: /* Copy extended memory */
{
bool enabled = MEM_A20_Enabled();
MEM_A20_Enable(true);
Bitu bytes = reg_cx * 2;
PhysPt data = SegPhys(es)+reg_si;
PhysPt source = (mem_readd(data+0x12) & 0x00FFFFFF) + (mem_readb(data+0x16)<<24);
PhysPt dest = (mem_readd(data+0x1A) & 0x00FFFFFF) + (mem_readb(data+0x1E)<<24);
MEM_BlockCopy(dest,source,bytes);
reg_ax = 0x00;
MEM_A20_Enable(enabled);
CALLBACK_SCF(false);
break;
}
case 0x88: /* SYSTEM - GET EXTENDED MEMORY SIZE (286+) */
reg_ax=other_memsystems?0:size_extended;
LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function 0x88 Remaining %04X kb",reg_ax);
CALLBACK_SCF(false);
break;
case 0x89: /* SYSTEM - SWITCH TO PROTECTED MODE */
{
IO_Write(0x20,0x10);IO_Write(0x21,reg_bh);IO_Write(0x21,0);
IO_Write(0xA0,0x10);IO_Write(0xA1,reg_bl);IO_Write(0xA1,0);
MEM_A20_Enable(true);
PhysPt table=SegPhys(es)+reg_si;
CPU_LGDT(mem_readw(table+0x8),mem_readd(table+0x8+0x2) & 0xFFFFFF);
CPU_LIDT(mem_readw(table+0x10),mem_readd(table+0x10+0x2) & 0xFFFFFF);
CPU_SET_CRX(0,CPU_GET_CRX(0)|1);
CPU_SetSegGeneral(ds,0x18);
CPU_SetSegGeneral(es,0x20);
CPU_SetSegGeneral(ss,0x28);
reg_sp+=6; //Clear stack of interrupt frame
CPU_SetFlags(0,FMASK_ALL);
reg_ax=0;
CPU_JMP(false,0x30,reg_cx,0);
}
break;
case 0x90: /* OS HOOK - DEVICE BUSY */
CALLBACK_SCF(false);
reg_ah=0;
break;
case 0x91: /* OS HOOK - DEVICE POST */
CALLBACK_SCF(false);
reg_ah=0;
break;
case 0xc2: /* BIOS PS2 Pointing Device Support */
switch (reg_al) {
case 0x00: // enable/disable
if (reg_bh==0) { // disable
Mouse_SetPS2State(false);
reg_ah=0;
CALLBACK_SCF(false);
} else if (reg_bh==0x01) { //enable
if (!Mouse_SetPS2State(true)) {
reg_ah=5;
CALLBACK_SCF(true);
break;
}
reg_ah=0;
CALLBACK_SCF(false);
} else {
CALLBACK_SCF(true);
reg_ah=1;
}
break;
case 0x01: // reset
reg_bx=0x00aa; // mouse
// fall through
case 0x05: // initialize
Mouse_SetPS2State(false);
CALLBACK_SCF(false);
reg_ah=0;
break;
case 0x02: // set sampling rate
case 0x03: // set resolution
CALLBACK_SCF(false);
reg_ah=0;
break;
case 0x04: // get type
reg_bh=0; // ID
CALLBACK_SCF(false);
reg_ah=0;
break;
case 0x06: // extended commands
if ((reg_bh==0x01) || (reg_bh==0x02)) {
CALLBACK_SCF(false);
reg_ah=0;
} else {
CALLBACK_SCF(true);
reg_ah=1;
}
break;
case 0x07: // set callback
Mouse_ChangePS2Callback(SegValue(es),reg_bx);
CALLBACK_SCF(false);
reg_ah=0;
break;
default:
CALLBACK_SCF(true);
reg_ah=1;
break;
}
break;
case 0xc3: /* set carry flag so BorlandRTM doesn't assume a VECTRA/PS2 */
reg_ah=0x86;
CALLBACK_SCF(true);
break;
case 0xc4: /* BIOS POS Programm option Select */
LOG(LOG_BIOS,LOG_NORMAL)("INT15:Function %X called, bios mouse not supported",reg_ah);
CALLBACK_SCF(true);
break;
default:
LOG(LOG_BIOS,LOG_ERROR)("INT15:Unknown call %4X",reg_ax);
reg_ah=0x86;
CALLBACK_SCF(true);
if ((IS_EGAVGA_ARCH) || (machine==MCH_CGA)) {
/* relict from comparisons, as int15 exits with a retf2 instead of an iret */
CALLBACK_SZF(false);
}
}
return CBRET_NONE;
}
static Bitu Reboot_Handler(void) {
// switch to text mode, notify user (let's hope INT10 still works)
const char* const text = "\n\n Reboot requested, quitting now.";
reg_ax = 0;
CALLBACK_RunRealInt(0x10);
reg_ah = 0xe;
reg_bx = 0;
for(Bitu i = 0; i < strlen(text);i++) {
reg_al = text[i];
CALLBACK_RunRealInt(0x10);
}
LOG_MSG(text);
double start = PIC_FullIndex();
while((PIC_FullIndex()-start)<3000) CALLBACK_Idle();
throw 1;
return CBRET_NONE;
}
void BIOS_ZeroExtendedSize(bool in) {
if(in) other_memsystems++;
else other_memsystems--;
if(other_memsystems < 0) other_memsystems=0;
}
void BIOS_SetupKeyboard(void);
void BIOS_SetupDisks(void);
class BIOS:public Module_base{
private:
CALLBACK_HandlerObject callback[11];
public:
BIOS(Section* configuration):Module_base(configuration){
/* tandy DAC can be requested in tandy_sound.cpp by initializing this field */
bool use_tandyDAC=(real_readb(0x40,0xd4)==0xff);
/* Clear the Bios Data Area (0x400-0x5ff, 0x600- is accounted to DOS) */
for (Bit16u i=0;i<0x200;i++) real_writeb(0x40,i,0);
/* Setup all the interrupt handlers the bios controls */
/* INT 8 Clock IRQ Handler */
Bitu call_irq0=CALLBACK_Allocate();
CALLBACK_Setup(call_irq0,INT8_Handler,CB_IRQ0,Real2Phys(BIOS_DEFAULT_IRQ0_LOCATION),"IRQ 0 Clock");
RealSetVec(0x08,BIOS_DEFAULT_IRQ0_LOCATION);
// pseudocode for CB_IRQ0:
// callback INT8_Handler
// push ax,dx,ds
// int 0x1c
// cli
// pop ds,dx
// mov al, 0x20
// out 0x20, al
// pop ax
// iret
mem_writed(BIOS_TIMER,0); //Calculate the correct time
/* INT 11 Get equipment list */
callback[1].Install(&INT11_Handler,CB_IRET,"Int 11 Equipment");
callback[1].Set_RealVec(0x11);
/* INT 12 Memory Size default at 640 kb */
callback[2].Install(&INT12_Handler,CB_IRET,"Int 12 Memory");
callback[2].Set_RealVec(0x12);
if (IS_TANDY_ARCH) {
/* reduce reported memory size for the Tandy (32k graphics memory
at the end of the conventional 640k) */
if (machine==MCH_TANDY) mem_writew(BIOS_MEMORY_SIZE,608);
else mem_writew(BIOS_MEMORY_SIZE,640);
mem_writew(BIOS_TRUE_MEMORY_SIZE,640);
} else mem_writew(BIOS_MEMORY_SIZE,640);
/* INT 13 Bios Disk Support */
BIOS_SetupDisks();
/* INT 14 Serial Ports */
callback[3].Install(&INT14_Handler,CB_IRET_STI,"Int 14 COM-port");
callback[3].Set_RealVec(0x14);
/* INT 15 Misc Calls */
callback[4].Install(&INT15_Handler,CB_IRET,"Int 15 Bios");
callback[4].Set_RealVec(0x15);
/* INT 16 Keyboard handled in another file */
BIOS_SetupKeyboard();
/* INT 17 Printer Routines */
callback[5].Install(&INT17_Handler,CB_IRET_STI,"Int 17 Printer");
callback[5].Set_RealVec(0x17);
/* INT 1A TIME and some other functions */
callback[6].Install(&INT1A_Handler,CB_IRET_STI,"Int 1a Time");
callback[6].Set_RealVec(0x1A);
/* INT 1C System Timer tick called from INT 8 */
callback[7].Install(&INT1C_Handler,CB_IRET,"Int 1c Timer");
callback[7].Set_RealVec(0x1C);
/* IRQ 8 RTC Handler */
callback[8].Install(&INT70_Handler,CB_IRET,"Int 70 RTC");
callback[8].Set_RealVec(0x70);
/* Irq 9 rerouted to irq 2 */
callback[9].Install(NULL,CB_IRQ9,"irq 9 bios");
callback[9].Set_RealVec(0x71);
/* Reboot */
callback[10].Install(&Reboot_Handler,CB_IRET,"reboot");
callback[10].Set_RealVec(0x18);
RealPt rptr = callback[10].Get_RealPointer();
RealSetVec(0x19,rptr);
// set system BIOS entry point too
phys_writeb(0xFFFF0,0xEA); // FARJMP
phys_writew(0xFFFF1,RealOff(rptr)); // offset
phys_writew(0xFFFF3,RealSeg(rptr)); // segment
/* Irq 2 */
Bitu call_irq2=CALLBACK_Allocate();
CALLBACK_Setup(call_irq2,NULL,CB_IRET_EOI_PIC1,Real2Phys(BIOS_DEFAULT_IRQ2_LOCATION),"irq 2 bios");
RealSetVec(0x0a,BIOS_DEFAULT_IRQ2_LOCATION);
/* Some hardcoded vectors */
phys_writeb(Real2Phys(BIOS_DEFAULT_HANDLER_LOCATION),0xcf); /* bios default interrupt vector location -> IRET */
phys_writew(Real2Phys(RealGetVec(0x12))+0x12,0x20); //Hack for Jurresic
if (machine==MCH_TANDY) phys_writeb(0xffffe,0xff) ; /* Tandy model */
else if (machine==MCH_PCJR) phys_writeb(0xffffe,0xfd); /* PCJr model */
else phys_writeb(0xffffe,0xfc); /* PC */
// System BIOS identification
const char* const b_type =
"IBM COMPATIBLE 486 BIOS COPYRIGHT The DOSBox Team.";
for(Bitu i = 0; i < strlen(b_type); i++) phys_writeb(0xfe00e + i,b_type[i]);
// System BIOS version
const char* const b_vers =
"DOSBox FakeBIOS v1.0";
for(Bitu i = 0; i < strlen(b_vers); i++) phys_writeb(0xfe061+i,b_vers[i]);
// write system BIOS date
const char* const b_date = "01/01/92";
for(Bitu i = 0; i < strlen(b_date); i++) phys_writeb(0xffff5+i,b_date[i]);
phys_writeb(0xfffff,0x55); // signature
tandy_sb.port=0;
tandy_dac.port=0;
if (use_tandyDAC) {
/* tandy DAC sound requested, see if soundblaster device is available */
Bitu tandy_dac_type = 0;
if (Tandy_InitializeSB()) {
tandy_dac_type = 1;
} else if (Tandy_InitializeTS()) {
tandy_dac_type = 2;
}
if (tandy_dac_type) {
real_writew(0x40,0xd0,0x0000);
real_writew(0x40,0xd2,0x0000);
real_writeb(0x40,0xd4,0xff); /* tandy DAC init value */
real_writed(0x40,0xd6,0x00000000);
/* install the DAC callback handler */
tandy_DAC_callback[0]=new CALLBACK_HandlerObject();
tandy_DAC_callback[1]=new CALLBACK_HandlerObject();
tandy_DAC_callback[0]->Install(&IRQ_TandyDAC,CB_IRET,"Tandy DAC IRQ");
tandy_DAC_callback[1]->Install(NULL,CB_TDE_IRET,"Tandy DAC end transfer");
// pseudocode for CB_TDE_IRET:
// push ax
// mov ax, 0x91fb
// int 15
// cli
// mov al, 0x20
// out 0x20, al
// pop ax
// iret
Bit8u tandy_irq = 7;
if (tandy_dac_type==1) tandy_irq = tandy_sb.irq;
else if (tandy_dac_type==2) tandy_irq = tandy_dac.irq;
Bit8u tandy_irq_vector = tandy_irq;
if (tandy_irq_vector<8) tandy_irq_vector += 8;
else tandy_irq_vector += (0x70-8);
RealPt current_irq=RealGetVec(tandy_irq_vector);
real_writed(0x40,0xd6,current_irq);
for (Bit16u i=0; i<0x10; i++) phys_writeb(PhysMake(0xf000,0xa084+i),0x80);
} else real_writeb(0x40,0xd4,0x00);
}
/* Setup some stuff in 0x40 bios segment */
// port timeouts
// always 1 second even if the port does not exist
mem_writeb(BIOS_LPT1_TIMEOUT,1);
mem_writeb(BIOS_LPT2_TIMEOUT,1);
mem_writeb(BIOS_LPT3_TIMEOUT,1);
mem_writeb(BIOS_COM1_TIMEOUT,1);
mem_writeb(BIOS_COM2_TIMEOUT,1);
mem_writeb(BIOS_COM3_TIMEOUT,1);
mem_writeb(BIOS_COM4_TIMEOUT,1);
/* detect parallel ports */
Bitu ppindex=0; // number of lpt ports
if ((IO_Read(0x378)!=0xff)|(IO_Read(0x379)!=0xff)) {
// this is our LPT1
mem_writew(BIOS_ADDRESS_LPT1,0x378);
ppindex++;
if((IO_Read(0x278)!=0xff)|(IO_Read(0x279)!=0xff)) {
// this is our LPT2
mem_writew(BIOS_ADDRESS_LPT2,0x278);
ppindex++;
if((IO_Read(0x3bc)!=0xff)|(IO_Read(0x3be)!=0xff)) {
// this is our LPT3
mem_writew(BIOS_ADDRESS_LPT3,0x3bc);
ppindex++;
}
} else if((IO_Read(0x3bc)!=0xff)|(IO_Read(0x3be)!=0xff)) {
// this is our LPT2
mem_writew(BIOS_ADDRESS_LPT2,0x3bc);
ppindex++;
}
} else if((IO_Read(0x3bc)!=0xff)|(IO_Read(0x3be)!=0xff)) {
// this is our LPT1
mem_writew(BIOS_ADDRESS_LPT1,0x3bc);
ppindex++;
if((IO_Read(0x278)!=0xff)|(IO_Read(0x279)!=0xff)) {
// this is our LPT2
mem_writew(BIOS_ADDRESS_LPT2,0x278);
ppindex++;
}
} else if((IO_Read(0x278)!=0xff)|(IO_Read(0x279)!=0xff)) {
// this is our LPT1
mem_writew(BIOS_ADDRESS_LPT1,0x278);
ppindex++;
}
/* Setup equipment list */
// look http://www.bioscentral.com/misc/bda.htm
//Bit16u config=0x4400; //1 Floppy, 2 serial and 1 parallel
Bit16u config = 0x0;
// set number of parallel ports
// if(ppindex == 0) config |= 0x8000; // looks like 0 ports are not specified
//else if(ppindex == 1) config |= 0x0000;
if(ppindex == 2) config |= 0x4000;
else config |= 0xc000; // 3 ports
#if (C_FPU)
//FPU
config|=0x2;
#endif
switch (machine) {
case MCH_HERC:
//Startup monochrome
config|=0x30;
break;
case EGAVGA_ARCH_CASE:
case MCH_CGA:
case TANDY_ARCH_CASE:
//Startup 80x25 color
config|=0x20;
break;
default:
//EGA VGA
config|=0;
break;
}
// PS2 mouse
config |= 0x04;
// Gameport
config |= 0x1000;
mem_writew(BIOS_CONFIGURATION,config);
CMOS_SetRegister(0x14,(Bit8u)(config&0xff)); //Should be updated on changes
/* Setup extended memory size */
IO_Write(0x70,0x30);
size_extended=IO_Read(0x71);
IO_Write(0x70,0x31);
size_extended|=(IO_Read(0x71) << 8);
}
~BIOS(){
/* abort DAC playing */
if (tandy_sb.port) {
IO_Write(tandy_sb.port+0xc,0xd3);
IO_Write(tandy_sb.port+0xc,0xd0);
}
real_writeb(0x40,0xd4,0x00);
if (tandy_DAC_callback[0]) {
Bit32u orig_vector=real_readd(0x40,0xd6);
if (orig_vector==tandy_DAC_callback[0]->Get_RealPointer()) {
/* set IRQ vector to old value */
Bit8u tandy_irq = 7;
if (tandy_sb.port) tandy_irq = tandy_sb.irq;
else if (tandy_dac.port) tandy_irq = tandy_dac.irq;
Bit8u tandy_irq_vector = tandy_irq;
if (tandy_irq_vector<8) tandy_irq_vector += 8;
else tandy_irq_vector += (0x70-8);
RealSetVec(tandy_irq_vector,real_readd(0x40,0xd6));
real_writed(0x40,0xd6,0x00000000);
}
delete tandy_DAC_callback[0];
delete tandy_DAC_callback[1];
tandy_DAC_callback[0]=NULL;
tandy_DAC_callback[1]=NULL;
}
}
};
// set com port data in bios data area
// parameter: array of 4 com port base addresses, 0 = none
void BIOS_SetComPorts(Bit16u baseaddr[]) {
Bit16u portcount=0;
Bit16u equipmentword;
for(Bitu i = 0; i < 4; i++) {
if(baseaddr[i]!=0) portcount++;
if(i==0) mem_writew(BIOS_BASE_ADDRESS_COM1,baseaddr[i]);
else if(i==1) mem_writew(BIOS_BASE_ADDRESS_COM2,baseaddr[i]);
else if(i==2) mem_writew(BIOS_BASE_ADDRESS_COM3,baseaddr[i]);
else mem_writew(BIOS_BASE_ADDRESS_COM4,baseaddr[i]);
}
// set equipment word
equipmentword = mem_readw(BIOS_CONFIGURATION);
equipmentword &= (~0x0E00);
equipmentword |= (portcount << 9);
mem_writew(BIOS_CONFIGURATION,equipmentword);
CMOS_SetRegister(0x14,(Bit8u)(equipmentword&0xff)); //Should be updated on changes
}
static BIOS* test;
void BIOS_Destroy(Section* /*sec*/){
delete test;
}
void BIOS_Init(Section* sec) {
test = new BIOS(sec);
sec->AddDestroyFunction(&BIOS_Destroy,false);
}
| utf-8 | 1 | GPL-2 | 2002-2018 The DOSBox Team
Sjoerd v.d. Berg <[email protected]>
Peter Veenstra <[email protected]>
Ulf Wohlers <[email protected]>
Tommy Frössman <[email protected]>
Dean Beeler <[email protected]>
Sebastian Strohhäcker <[email protected]>
Ralf Grillenberger <[email protected]> |
ns3-3.35+dfsg/ns-3.35/src/core/test/callback-test-suite.cc | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 University of Washington
*
* 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "ns3/test.h"
#include "ns3/callback.h"
#include "ns3/unused.h"
#include <stdint.h>
using namespace ns3;
// ===========================================================================
// Test the basic Callback mechanism
// ===========================================================================
class BasicCallbackTestCase : public TestCase
{
public:
BasicCallbackTestCase ();
virtual ~BasicCallbackTestCase ()
{}
void Target1 (void)
{
m_test1 = true;
}
int Target2 (void)
{
m_test2 = true;
return 2;
}
void Target3 (double a)
{
NS_UNUSED (a);
m_test3 = true;
}
int Target4 (double a, int b)
{
NS_UNUSED (a);
NS_UNUSED (b);
m_test4 = true;
return 4;
}
private:
virtual void DoRun (void);
virtual void DoSetup (void);
bool m_test1;
bool m_test2;
bool m_test3;
bool m_test4;
};
static bool gBasicCallbackTest5;
static bool gBasicCallbackTest6;
static bool gBasicCallbackTest7;
void
BasicCallbackTarget5 (void)
{
gBasicCallbackTest5 = true;
}
void
BasicCallbackTarget6 (int)
{
gBasicCallbackTest6 = true;
}
int
BasicCallbackTarget7 (int a)
{
gBasicCallbackTest7 = true;
return a;
}
BasicCallbackTestCase::BasicCallbackTestCase ()
: TestCase ("Check basic Callback mechansim")
{}
void
BasicCallbackTestCase::DoSetup (void)
{
m_test1 = false;
m_test2 = false;
m_test3 = false;
m_test4 = false;
gBasicCallbackTest5 = false;
gBasicCallbackTest6 = false;
gBasicCallbackTest7 = false;
}
void
BasicCallbackTestCase::DoRun (void)
{
//
// Make sure we can declare and compile a Callback pointing to a member
// function returning void and execute it.
//
Callback<void> target1 (this, &BasicCallbackTestCase::Target1);
target1 ();
NS_TEST_ASSERT_MSG_EQ (m_test1, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a member
// function that returns an int and execute it.
//
Callback<int> target2;
target2 = Callback<int> (this, &BasicCallbackTestCase::Target2);
target2 ();
NS_TEST_ASSERT_MSG_EQ (m_test2, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a member
// function that returns void, takes a double parameter, and execute it.
//
Callback<void, double> target3 = Callback<void, double> (this, &BasicCallbackTestCase::Target3);
target3 (0.0);
NS_TEST_ASSERT_MSG_EQ (m_test3, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a member
// function that returns void, takes two parameters, and execute it.
//
Callback<int, double, int> target4 = Callback<int, double, int> (this, &BasicCallbackTestCase::Target4);
target4 (0.0, 1);
NS_TEST_ASSERT_MSG_EQ (m_test4, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a non-member
// function that returns void, and execute it. This is a lower level call
// than MakeCallback so we have got to include at least two arguments to make
// sure that the constructor is properly disambiguated. If the arguments are
// not needed, we just pass in dummy values.
//
Callback<void> target5 = Callback<void> (&BasicCallbackTarget5, true, true);
target5 ();
NS_TEST_ASSERT_MSG_EQ (gBasicCallbackTest5, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a non-member
// function that returns void, takes one integer argument and execute it.
// We also need to provide two dummy arguments to the constructor here.
//
Callback<void, int> target6 = Callback<void, int> (&BasicCallbackTarget6, true, true);
target6 (1);
NS_TEST_ASSERT_MSG_EQ (gBasicCallbackTest6, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a non-member
// function that returns int, takes one integer argument and execute it.
// We also need to provide two dummy arguments to the constructor here.
//
Callback<int, int> target7 = Callback<int, int> (&BasicCallbackTarget7, true, true);
target7 (1);
NS_TEST_ASSERT_MSG_EQ (gBasicCallbackTest7, true, "Callback did not fire");
}
// ===========================================================================
// Test the MakeCallback mechanism
// ===========================================================================
class MakeCallbackTestCase : public TestCase
{
public:
MakeCallbackTestCase ();
virtual ~MakeCallbackTestCase ()
{}
void Target1 (void)
{
m_test1 = true;
}
int Target2 (void)
{
m_test2 = true;
return 2;
}
void Target3 (double a)
{
NS_UNUSED (a);
m_test3 = true;
}
int Target4 (double a, int b)
{
NS_UNUSED (a);
NS_UNUSED (b);
m_test4 = true;
return 4;
}
private:
virtual void DoRun (void);
virtual void DoSetup (void);
bool m_test1;
bool m_test2;
bool m_test3;
bool m_test4;
};
static bool gMakeCallbackTest5;
static bool gMakeCallbackTest6;
static bool gMakeCallbackTest7;
void
MakeCallbackTarget5 (void)
{
gMakeCallbackTest5 = true;
}
void
MakeCallbackTarget6 (int)
{
gMakeCallbackTest6 = true;
}
int
MakeCallbackTarget7 (int a)
{
gMakeCallbackTest7 = true;
return a;
}
MakeCallbackTestCase::MakeCallbackTestCase ()
: TestCase ("Check MakeCallback() mechanism")
{}
void
MakeCallbackTestCase::DoSetup (void)
{
m_test1 = false;
m_test2 = false;
m_test3 = false;
m_test4 = false;
gMakeCallbackTest5 = false;
gMakeCallbackTest6 = false;
gMakeCallbackTest7 = false;
}
void
MakeCallbackTestCase::DoRun (void)
{
//
// Make sure we can declare and make a Callback pointing to a member
// function returning void and execute it.
//
Callback<void> target1 = MakeCallback (&MakeCallbackTestCase::Target1, this);
target1 ();
NS_TEST_ASSERT_MSG_EQ (m_test1, true, "Callback did not fire");
//
// Make sure we can declare and make a Callback pointing to a member
// function that returns an int and execute it.
//
Callback<int> target2 = MakeCallback (&MakeCallbackTestCase::Target2, this);
target2 ();
NS_TEST_ASSERT_MSG_EQ (m_test2, true, "Callback did not fire");
//
// Make sure we can declare and make a Callback pointing to a member
// function that returns void, takes a double parameter, and execute it.
//
Callback<void, double> target3 = MakeCallback (&MakeCallbackTestCase::Target3, this);
target3 (0.0);
NS_TEST_ASSERT_MSG_EQ (m_test3, true, "Callback did not fire");
//
// Make sure we can declare and make a Callback pointing to a member
// function that returns void, takes two parameters, and execute it.
//
Callback<int, double, int> target4 = MakeCallback (&MakeCallbackTestCase::Target4, this);
target4 (0.0, 1);
NS_TEST_ASSERT_MSG_EQ (m_test4, true, "Callback did not fire");
//
// Make sure we can declare and make a Callback pointing to a non-member
// function that returns void, and execute it. This uses a higher level call
// than in the basic tests so we do not need to include any dummy arguments
// here.
//
Callback<void> target5 = MakeCallback (&MakeCallbackTarget5);
target5 ();
NS_TEST_ASSERT_MSG_EQ (gMakeCallbackTest5, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a non-member
// function that returns void, takes one integer argument and execute it.
// This uses a higher level call than in the basic tests so we do not need to
// include any dummy arguments here.
//
Callback<void, int> target6 = MakeCallback (&MakeCallbackTarget6);
target6 (1);
NS_TEST_ASSERT_MSG_EQ (gMakeCallbackTest6, true, "Callback did not fire");
//
// Make sure we can declare and compile a Callback pointing to a non-member
// function that returns int, takes one integer argument and execute it.
// This uses a higher level call than in the basic tests so we do not need to
// include any dummy arguments here.
//
Callback<int, int> target7 = MakeCallback (&MakeCallbackTarget7);
target7 (1);
NS_TEST_ASSERT_MSG_EQ (gMakeCallbackTest7, true, "Callback did not fire");
}
// ===========================================================================
// Test the MakeBoundCallback mechanism
// ===========================================================================
class MakeBoundCallbackTestCase : public TestCase
{
public:
MakeBoundCallbackTestCase ();
virtual ~MakeBoundCallbackTestCase ()
{}
private:
virtual void DoRun (void);
virtual void DoSetup (void);
};
static int gMakeBoundCallbackTest1;
static bool *gMakeBoundCallbackTest2;
static bool *gMakeBoundCallbackTest3a;
static int gMakeBoundCallbackTest3b;
static int gMakeBoundCallbackTest4a;
static int gMakeBoundCallbackTest4b;
static int gMakeBoundCallbackTest5a;
static int gMakeBoundCallbackTest5b;
static int gMakeBoundCallbackTest5c;
static int gMakeBoundCallbackTest6a;
static int gMakeBoundCallbackTest6b;
static int gMakeBoundCallbackTest6c;
static int gMakeBoundCallbackTest7a;
static int gMakeBoundCallbackTest7b;
static int gMakeBoundCallbackTest7c;
static int gMakeBoundCallbackTest8a;
static int gMakeBoundCallbackTest8b;
static int gMakeBoundCallbackTest8c;
static int gMakeBoundCallbackTest9a;
static int gMakeBoundCallbackTest9b;
static int gMakeBoundCallbackTest9c;
static int gMakeBoundCallbackTest9d;
void
MakeBoundCallbackTarget1 (int a)
{
gMakeBoundCallbackTest1 = a;
}
void
MakeBoundCallbackTarget2 (bool *a)
{
gMakeBoundCallbackTest2 = a;
}
int
MakeBoundCallbackTarget3 (bool *a, int b)
{
gMakeBoundCallbackTest3a = a;
gMakeBoundCallbackTest3b = b;
return 1234;
}
void
MakeBoundCallbackTarget4 (int a, int b)
{
gMakeBoundCallbackTest4a = a;
gMakeBoundCallbackTest4b = b;
}
int
MakeBoundCallbackTarget5 (int a, int b)
{
gMakeBoundCallbackTest5a = a;
gMakeBoundCallbackTest5b = b;
return 1234;
}
int
MakeBoundCallbackTarget6 (int a, int b, int c)
{
gMakeBoundCallbackTest6a = a;
gMakeBoundCallbackTest6b = b;
gMakeBoundCallbackTest6c = c;
return 1234;
}
void
MakeBoundCallbackTarget7 (int a, int b, int c)
{
gMakeBoundCallbackTest7a = a;
gMakeBoundCallbackTest7b = b;
gMakeBoundCallbackTest7c = c;
}
int
MakeBoundCallbackTarget8 (int a, int b, int c)
{
gMakeBoundCallbackTest8a = a;
gMakeBoundCallbackTest8b = b;
gMakeBoundCallbackTest8c = c;
return 1234;
}
int
MakeBoundCallbackTarget9 (int a, int b, int c, int d)
{
gMakeBoundCallbackTest9a = a;
gMakeBoundCallbackTest9b = b;
gMakeBoundCallbackTest9c = c;
gMakeBoundCallbackTest9d = d;
return 1234;
}
MakeBoundCallbackTestCase::MakeBoundCallbackTestCase ()
: TestCase ("Check MakeBoundCallback() mechanism")
{}
void
MakeBoundCallbackTestCase::DoSetup (void)
{
gMakeBoundCallbackTest1 = 0;
gMakeBoundCallbackTest2 = 0;
gMakeBoundCallbackTest3a = 0;
gMakeBoundCallbackTest3b = 0;
gMakeBoundCallbackTest4a = 0;
gMakeBoundCallbackTest4b = 0;
gMakeBoundCallbackTest5a = 0;
gMakeBoundCallbackTest5b = 0;
gMakeBoundCallbackTest5c = 0;
gMakeBoundCallbackTest6a = 0;
gMakeBoundCallbackTest6b = 0;
gMakeBoundCallbackTest6c = 0;
gMakeBoundCallbackTest7a = 0;
gMakeBoundCallbackTest7b = 0;
gMakeBoundCallbackTest7c = 0;
gMakeBoundCallbackTest8a = 0;
gMakeBoundCallbackTest8b = 0;
gMakeBoundCallbackTest8c = 0;
gMakeBoundCallbackTest9a = 0;
gMakeBoundCallbackTest9b = 0;
gMakeBoundCallbackTest9c = 0;
gMakeBoundCallbackTest9d = 0;
}
void
MakeBoundCallbackTestCase::DoRun (void)
{
//
// This is slightly tricky to explain. A bound Callback allows us to package
// up arguments for use later. The arguments are bound when the callback is
// created and the code that fires the Callback does not know they are there.
//
// Since the callback is *declared* according to the way it will be used, the
// arguments are not seen there. However, the target function of the callback
// will have the provided arguments present. The MakeBoundCallback template
// function is what connects the two together and where you provide the
// arguments to be bound.
//
// Here we declare a Callback that returns a void and takes no parameters.
// MakeBoundCallback connects this Callback to a target function that returns
// void and takes an integer argument. That integer argument is bound to the
// value 1234. When the Callback is fired, no integer argument is provided
// directly. The argument is provided by bound Callback mechanism.
//
Callback<void> target1 = MakeBoundCallback (&MakeBoundCallbackTarget1, 1234);
target1 ();
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest1, 1234, "Callback did not fire or binding not correct");
//
// Make sure we can bind a pointer value (a common use case).
//
bool a;
Callback<void> target2 = MakeBoundCallback (&MakeBoundCallbackTarget2, &a);
target2 ();
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest2, &a, "Callback did not fire or binding not correct");
//
// Make sure we can mix and match bound and unbound arguments. This callback
// returns an integer so we should see that appear.
//
Callback<int, int> target3 = MakeBoundCallback (&MakeBoundCallbackTarget3, &a);
int result = target3 (2468);
NS_TEST_ASSERT_MSG_EQ (result, 1234, "Return value of callback not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest3a, &a, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest3b, 2468, "Callback did not fire or argument not correct");
//
// Test the TwoBound variant
//
Callback<void> target4 = MakeBoundCallback (&MakeBoundCallbackTarget4, 3456, 5678);
target4 ();
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest4a, 3456, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest4b, 5678, "Callback did not fire or binding not correct");
Callback<int> target5 = MakeBoundCallback (&MakeBoundCallbackTarget5, 3456, 5678);
int resultTwoA = target5 ();
NS_TEST_ASSERT_MSG_EQ (resultTwoA, 1234, "Return value of callback not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest5a, 3456, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest5b, 5678, "Callback did not fire or binding not correct");
Callback<int, int> target6 = MakeBoundCallback (&MakeBoundCallbackTarget6, 3456, 5678);
int resultTwoB = target6 (6789);
NS_TEST_ASSERT_MSG_EQ (resultTwoB, 1234, "Return value of callback not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest6a, 3456, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest6b, 5678, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest6c, 6789, "Callback did not fire or argument not correct");
//
// Test the ThreeBound variant
//
Callback<void> target7 = MakeBoundCallback (&MakeBoundCallbackTarget7, 2345, 3456, 4567);
target7 ();
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest7a, 2345, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest7b, 3456, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest7c, 4567, "Callback did not fire or binding not correct");
Callback<int> target8 = MakeBoundCallback (&MakeBoundCallbackTarget8, 2345, 3456, 4567);
int resultThreeA = target8 ();
NS_TEST_ASSERT_MSG_EQ (resultThreeA, 1234, "Return value of callback not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest8a, 2345, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest8b, 3456, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest8c, 4567, "Callback did not fire or binding not correct");
Callback<int, int> target9 = MakeBoundCallback (&MakeBoundCallbackTarget9, 2345, 3456, 4567);
int resultThreeB = target9 (5678);
NS_TEST_ASSERT_MSG_EQ (resultThreeB, 1234, "Return value of callback not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest9a, 2345, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest9b, 3456, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest9c, 4567, "Callback did not fire or binding not correct");
NS_TEST_ASSERT_MSG_EQ (gMakeBoundCallbackTest9d, 5678, "Callback did not fire or binding not correct");
}
// ===========================================================================
// Test the Nullify mechanism
// ===========================================================================
class NullifyCallbackTestCase : public TestCase
{
public:
NullifyCallbackTestCase ();
virtual ~NullifyCallbackTestCase ()
{}
void Target1 (void)
{
m_test1 = true;
}
private:
virtual void DoRun (void);
virtual void DoSetup (void);
bool m_test1;
};
NullifyCallbackTestCase::NullifyCallbackTestCase ()
: TestCase ("Check Nullify() and IsNull()")
{}
void
NullifyCallbackTestCase::DoSetup (void)
{
m_test1 = false;
}
void
NullifyCallbackTestCase::DoRun (void)
{
//
// Make sure we can declare and make a Callback pointing to a member
// function returning void and execute it.
//
Callback<void> target1 = MakeCallback (&NullifyCallbackTestCase::Target1, this);
target1 ();
NS_TEST_ASSERT_MSG_EQ (m_test1, true, "Callback did not fire");
NS_TEST_ASSERT_MSG_EQ (target1.IsNull (), false, "Working Callback reports IsNull()");
target1.Nullify ();
NS_TEST_ASSERT_MSG_EQ (target1.IsNull (), true, "Nullified Callback reports not IsNull()");
}
// ===========================================================================
// Make sure that various MakeCallback template functions compile and execute.
// Doesn't check an results of the execution.
// ===========================================================================
class MakeCallbackTemplatesTestCase : public TestCase
{
public:
MakeCallbackTemplatesTestCase ();
virtual ~MakeCallbackTemplatesTestCase ()
{}
void Target1 (void)
{
m_test1 = true;
}
private:
virtual void DoRun (void);
bool m_test1;
};
/* *NS_CHECK_STYLE_OFF* */
void TestFZero (void) {}
void TestFOne (int) {}
void TestFTwo (int, int) {}
void TestFThree (int, int, int) {}
void TestFFour (int, int, int, int) {}
void TestFFive (int, int, int, int, int) {}
void TestFSix (int, int, int, int, int, int) {}
void TestFROne (int &) {}
void TestFRTwo (int &, int &) {}
void TestFRThree (int &, int &, int &) {}
void TestFRFour (int &, int &, int &, int &) {}
void TestFRFive (int &, int &, int &, int &, int &) {}
void TestFRSix (int &, int &, int &, int &, int &, int &) {}
/* *NS_CHECK_STYLE_ON* */
class CallbackTestParent
{
public:
void PublicParent (void)
{}
protected:
void ProtectedParent (void)
{}
static void StaticProtectedParent (void)
{}
private:
void PrivateParent (void)
{}
};
class CallbackTestClass : public CallbackTestParent
{
public:
/* *NS_CHECK_STYLE_OFF* */
void TestZero (void) {}
void TestOne (int) {}
void TestTwo (int, int) {}
void TestThree (int, int, int) {}
void TestFour (int, int, int, int) {}
void TestFive (int, int, int, int, int) {}
void TestSix (int, int, int, int, int, int) {}
void TestCZero (void) const {}
void TestCOne (int) const {}
void TestCTwo (int, int) const {}
void TestCThree (int, int, int) const {}
void TestCFour (int, int, int, int) const {}
void TestCFive (int, int, int, int, int) const {}
void TestCSix (int, int, int, int, int, int) const {}
/* *NS_CHECK_STYLE_ON* */
void CheckParentalRights (void)
{
MakeCallback (&CallbackTestParent::StaticProtectedParent);
MakeCallback (&CallbackTestParent::PublicParent, this);
MakeCallback (&CallbackTestClass::ProtectedParent, this);
// as expected, fails.
// MakeCallback (&CallbackTestParent::PrivateParent, this);
// unexpected, but fails too. It does fumble me.
// MakeCallback (&CallbackTestParent::ProtectedParent, this);
}
};
MakeCallbackTemplatesTestCase::MakeCallbackTemplatesTestCase ()
: TestCase ("Check various MakeCallback() template functions")
{}
void
MakeCallbackTemplatesTestCase::DoRun (void)
{
CallbackTestClass that;
MakeCallback (&CallbackTestClass::TestZero, &that);
MakeCallback (&CallbackTestClass::TestOne, &that);
MakeCallback (&CallbackTestClass::TestTwo, &that);
MakeCallback (&CallbackTestClass::TestThree, &that);
MakeCallback (&CallbackTestClass::TestFour, &that);
MakeCallback (&CallbackTestClass::TestFive, &that);
MakeCallback (&CallbackTestClass::TestSix, &that);
MakeCallback (&CallbackTestClass::TestCZero, &that);
MakeCallback (&CallbackTestClass::TestCOne, &that);
MakeCallback (&CallbackTestClass::TestCTwo, &that);
MakeCallback (&CallbackTestClass::TestCThree, &that);
MakeCallback (&CallbackTestClass::TestCFour, &that);
MakeCallback (&CallbackTestClass::TestCFive, &that);
MakeCallback (&CallbackTestClass::TestCSix, &that);
MakeCallback (&TestFZero);
MakeCallback (&TestFOne);
MakeCallback (&TestFTwo);
MakeCallback (&TestFThree);
MakeCallback (&TestFFour);
MakeCallback (&TestFFive);
MakeCallback (&TestFSix);
MakeCallback (&TestFROne);
MakeCallback (&TestFRTwo);
MakeCallback (&TestFRThree);
MakeCallback (&TestFRFour);
MakeCallback (&TestFRFive);
MakeCallback (&TestFRSix);
MakeBoundCallback (&TestFOne, 1);
MakeBoundCallback (&TestFTwo, 1);
MakeBoundCallback (&TestFThree, 1);
MakeBoundCallback (&TestFFour, 1);
MakeBoundCallback (&TestFFive, 1);
MakeBoundCallback (&TestFROne, 1);
MakeBoundCallback (&TestFRTwo, 1);
MakeBoundCallback (&TestFRThree, 1);
MakeBoundCallback (&TestFRFour, 1);
MakeBoundCallback (&TestFRFive, 1);
that.CheckParentalRights ();
}
// ===========================================================================
// The Test Suite that glues all of the Test Cases together.
// ===========================================================================
class CallbackTestSuite : public TestSuite
{
public:
CallbackTestSuite ();
};
CallbackTestSuite::CallbackTestSuite ()
: TestSuite ("callback", UNIT)
{
AddTestCase (new BasicCallbackTestCase, TestCase::QUICK);
AddTestCase (new MakeCallbackTestCase, TestCase::QUICK);
AddTestCase (new MakeBoundCallbackTestCase, TestCase::QUICK);
AddTestCase (new NullifyCallbackTestCase, TestCase::QUICK);
AddTestCase (new MakeCallbackTemplatesTestCase, TestCase::QUICK);
}
static CallbackTestSuite CallbackTestSuite;
| utf-8 | 1 | unknown | unknown |
chromium-98.0.4758.102/third_party/ruy/src/ruy/perchannel_buffers_reallocation_test.cc | #include "ruy/context.h"
#include "ruy/gtest_wrapper.h"
#include "ruy/kernel.h"
#include "ruy/matrix.h"
#include "ruy/path.h"
#include "ruy/performance_advisory.h"
#include "ruy/ruy.h"
namespace ruy {
namespace {
constexpr Path kPath = Path::kInternalStandardCppVariant3;
constexpr int kBufferSize = 64;
template <typename AccumScalar, typename DstScalar,
bool HaveQuantizedMultipliers =
std::is_same<AccumScalar, std::int32_t>::value &&
!std::is_same<DstScalar, std::int32_t>::value>
struct PopulatePerChannelBuffersImpl {
static void Run(MulParams<AccumScalar, DstScalar>* mul_params) {
static const AccumScalar bias_buf[kBufferSize] = {0};
static const AccumScalar multiplier_fixedpoint_buf[kBufferSize] = {0};
static const int multiplier_exponent_buf[kBufferSize] = {0};
mul_params->set_bias(bias_buf);
mul_params->set_multiplier_fixedpoint_perchannel(multiplier_fixedpoint_buf);
mul_params->set_multiplier_exponent_perchannel(multiplier_exponent_buf);
}
};
template <typename AccumScalar, typename DstScalar>
struct PopulatePerChannelBuffersImpl<AccumScalar, DstScalar, false> {
static void Run(MulParams<AccumScalar, DstScalar>* mul_params) {
static const AccumScalar bias_buf[kBufferSize] = {0};
mul_params->set_bias(bias_buf);
}
};
template <typename AccumScalar, typename DstScalar>
void PopulatePerChannelBuffers(MulParams<AccumScalar, DstScalar>* mul_params) {
PopulatePerChannelBuffersImpl<AccumScalar, DstScalar>::Run(mul_params);
}
template <typename LhsScalar, typename RhsScalar, typename AccumScalar,
typename DstScalar>
void TestPerChannelBuffersReallocation() {
using KernelType = Kernel<kPath, float, float, float, float>;
MulParams<AccumScalar, DstScalar> mul_params;
PopulatePerChannelBuffers(&mul_params);
const int kMatrixSize = 3;
ruy::Matrix<LhsScalar> lhs;
ruy::MakeSimpleLayout(kMatrixSize, kMatrixSize, ruy::Order::kRowMajor,
lhs.mutable_layout());
const LhsScalar lhs_data[kMatrixSize * kMatrixSize] = {0};
lhs.set_data(lhs_data);
ruy::Matrix<RhsScalar> rhs;
ruy::MakeSimpleLayout(kMatrixSize, kMatrixSize, ruy::Order::kColMajor,
rhs.mutable_layout());
const RhsScalar rhs_data[kMatrixSize * kMatrixSize] = {0};
rhs.set_data(rhs_data);
DstScalar dst_data[kMatrixSize * kMatrixSize] = {0};
ruy::Matrix<DstScalar> dst;
ruy::MakeSimpleLayout(kMatrixSize, kMatrixSize, ruy::Order::kColMajor,
dst.mutable_layout());
dst.set_data(dst_data);
ruy::Context context;
auto test_advisory = [&](bool expect_advisory,
ChannelDimension channel_dimension,
int capacity_rounding) {
mul_params.set_channel_dimension(channel_dimension);
mul_params.set_perchannel_buffers_capacity_rounding(capacity_rounding);
ruy::Mul<kPath>(lhs, rhs, mul_params, &context, &dst);
EXPECT_EQ(context.performance_advisory(
PerformanceAdvisory::kReallocatedPerChannelBuffer),
expect_advisory);
};
static_assert(KernelType::LhsLayout::kCols == 16, "");
test_advisory(true, ChannelDimension::kRow, 1);
test_advisory(true, ChannelDimension::kRow, 2);
test_advisory(true, ChannelDimension::kRow, 4);
test_advisory(true, ChannelDimension::kRow, 8);
test_advisory(false, ChannelDimension::kRow, 16);
test_advisory(false, ChannelDimension::kRow, 32);
test_advisory(false, ChannelDimension::kRow, 64);
static_assert(KernelType::RhsLayout::kCols == 8, "");
test_advisory(true, ChannelDimension::kCol, 1);
test_advisory(true, ChannelDimension::kCol, 2);
test_advisory(true, ChannelDimension::kCol, 4);
test_advisory(false, ChannelDimension::kCol, 8);
test_advisory(false, ChannelDimension::kCol, 16);
test_advisory(false, ChannelDimension::kCol, 32);
test_advisory(false, ChannelDimension::kCol, 64);
}
TEST(PerChannelBuffersReallocationTest, Float) {
TestPerChannelBuffersReallocation<float, float, float, float>();
}
TEST(PerChannelBuffersReallocationTest, Quantized) {
TestPerChannelBuffersReallocation<std::int8_t, std::int8_t, std::int32_t,
std::int8_t>();
}
TEST(PerChannelBuffersReallocationTest, RawInt32) {
TestPerChannelBuffersReallocation<std::int8_t, std::int8_t, std::int32_t,
std::int32_t>();
}
} // namespace
} // namespace ruy
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| utf-8 | 1 | BSD-3-clause | The Chromium Authors. All rights reserved. |
azure-uamqp-python-1.5.1/src/vendor/azure-uamqp-c/deps/umock-c/tests/umockalloc_ut/umockalloc_ut.c | // Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#ifdef __cplusplus
#include <cstdlib>
#else
#include <stdlib.h>
#endif
#include "testrunnerswitcher.h"
#include "umock_c/umockalloc.h"
#include "umock_c/umock_log.h"
void UMOCK_LOG(const char* format, ...)
{
(void)format;
}
typedef struct test_malloc_CALL_TAG
{
size_t size;
} test_malloc_CALL;
static test_malloc_CALL* test_malloc_calls;
static size_t test_malloc_call_count;
static void* test_malloc_expected_result;
typedef struct test_calloc_CALL_TAG
{
size_t size;
size_t nmemb;
} test_calloc_CALL;
static test_calloc_CALL* test_calloc_calls;
static size_t test_calloc_call_count;
static void* test_calloc_expected_result;
typedef struct test_realloc_CALL_TAG
{
size_t size;
void* ptr;
} test_realloc_CALL;
static test_realloc_CALL* test_realloc_calls;
static size_t test_realloc_call_count;
static void* test_realloc_expected_result;
typedef struct test_free_CALL_TAG
{
void* ptr;
} test_free_CALL;
static test_free_CALL* test_free_calls;
static size_t test_free_call_count;
#ifdef __cplusplus
extern "C" {
#endif
void* mock_malloc(size_t size)
{
test_malloc_CALL* new_calls = (test_malloc_CALL*)realloc(test_malloc_calls, sizeof(test_malloc_CALL) * (test_malloc_call_count + 1));
if (new_calls != NULL)
{
test_malloc_calls = new_calls;
test_malloc_calls[test_malloc_call_count].size = size;
test_malloc_call_count++;
}
return test_malloc_expected_result;
}
void* mock_calloc(size_t nmemb, size_t size)
{
test_calloc_CALL* new_calls = (test_calloc_CALL*)realloc(test_calloc_calls, sizeof(test_calloc_CALL) * (test_calloc_call_count + 1));
if (new_calls != NULL)
{
test_calloc_calls = new_calls;
test_calloc_calls[test_calloc_call_count].nmemb = nmemb;
test_calloc_calls[test_calloc_call_count].size = size;
test_calloc_call_count++;
}
return test_calloc_expected_result;
}
void* mock_realloc(void* ptr, size_t size)
{
test_realloc_CALL* new_calls = (test_realloc_CALL*)realloc(test_realloc_calls, sizeof(test_realloc_CALL) * (test_realloc_call_count + 1));
if (new_calls != NULL)
{
test_realloc_calls = new_calls;
test_realloc_calls[test_realloc_call_count].ptr = ptr;
test_realloc_calls[test_realloc_call_count].size = size;
test_realloc_call_count++;
}
return test_realloc_expected_result;
}
void mock_free(void* ptr)
{
test_free_CALL* new_calls = (test_free_CALL*)realloc(test_free_calls, sizeof(test_free_CALL) * (test_free_call_count + 1));
if (new_calls != NULL)
{
test_free_calls = new_calls;
test_free_calls[test_free_call_count].ptr = ptr;
test_free_call_count++;
}
}
#ifdef __cplusplus
}
#endif
static TEST_MUTEX_HANDLE test_mutex;
static TEST_MUTEX_HANDLE global_mutex;
BEGIN_TEST_SUITE(umockalloc_unittests)
TEST_SUITE_INITIALIZE(suite_init)
{
test_mutex = TEST_MUTEX_CREATE();
ASSERT_IS_NOT_NULL(test_mutex);
}
TEST_SUITE_CLEANUP(suite_cleanup)
{
TEST_MUTEX_DESTROY(test_mutex);
}
TEST_FUNCTION_INITIALIZE(test_function_init)
{
int mutex_acquire_result = TEST_MUTEX_ACQUIRE(test_mutex);
ASSERT_ARE_EQUAL(int, 0, mutex_acquire_result);
test_free_calls = NULL;
test_free_call_count = 0;
test_malloc_calls = NULL;
test_malloc_call_count = 0;
test_malloc_expected_result = (void*)0x4242;
test_calloc_calls = NULL;
test_calloc_call_count = 0;
test_calloc_expected_result = (void*)0x4242;
test_realloc_calls = NULL;
test_realloc_call_count = 0;
test_realloc_expected_result = (void*)0x4243;
}
TEST_FUNCTION_CLEANUP(test_function_cleanup)
{
free(test_malloc_calls);
test_malloc_calls = NULL;
test_malloc_call_count = 0;
free(test_calloc_calls);
test_calloc_calls = NULL;
test_calloc_call_count = 0;
free(test_realloc_calls);
test_realloc_calls = NULL;
test_realloc_call_count = 0;
free(test_free_calls);
test_free_calls = NULL;
test_free_call_count = 0;
TEST_MUTEX_RELEASE(test_mutex);
}
/* umockalloc_malloc */
/* Tests_SRS_UMOCKALLOC_01_001: [ umockalloc_malloc shall call malloc, while passing the size argument to malloc. ] */
/* Tests_SRS_UMOCKALLOC_01_002: [ umockalloc_malloc shall return the result of malloc. ]*/
TEST_FUNCTION(umockalloc_malloc_calls_malloc)
{
// arrange
void* result;
test_malloc_expected_result = (void*)0x4242;
// act
result = umockalloc_malloc(42);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x4242, result);
ASSERT_ARE_EQUAL(size_t, 1, test_malloc_call_count);
ASSERT_ARE_EQUAL(size_t, 42, test_malloc_calls[0].size);
}
/* Tests_SRS_UMOCKALLOC_01_001: [ umockalloc_malloc shall call malloc, while passing the size argument to malloc. ] */
/* Tests_SRS_UMOCKALLOC_01_002: [ umockalloc_malloc shall return the result of malloc. ]*/
TEST_FUNCTION(umockalloc_malloc_calls_malloc_other_value)
{
// arrange
void* result;
test_malloc_expected_result = (void*)0x5252;
// act
result = umockalloc_malloc(43);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x5252, result);
ASSERT_ARE_EQUAL(size_t, 1, test_malloc_call_count);
ASSERT_ARE_EQUAL(size_t, 43, test_malloc_calls[0].size);
}
/* Tests_SRS_UMOCKALLOC_01_001: [ umockalloc_malloc shall call malloc, while passing the size argument to malloc. ] */
TEST_FUNCTION(when_malloc_returns_NULL_umockalloc_malloc_returns_NULL)
{
// arrange
void* result;
test_malloc_expected_result = NULL;
// act
result = umockalloc_malloc(43);
// assert
ASSERT_IS_NULL(result);
ASSERT_ARE_EQUAL(size_t, 1, test_malloc_call_count);
ASSERT_ARE_EQUAL(size_t, 43, test_malloc_calls[0].size);
}
/* umockalloc_calloc */
/* Tests_SRS_UMOCKALLOC_09_001: [ umockalloc_calloc shall call calloc, while passing the number of members and size arguments to calloc. ] */
/* Tests_SRS_UMOCKALLOC_09_002: [ umockalloc_calloc shall return the result of calloc. ]*/
TEST_FUNCTION(umockalloc_calloc_calls_calloc)
{
// arrange
void* result;
test_calloc_expected_result = (void*)0x4242;
// act
result = umockalloc_calloc(1, 42);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x4242, result);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_call_count);
ASSERT_ARE_EQUAL(size_t, 42, test_calloc_calls[0].size);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_calls[0].nmemb);
}
/* Tests_SRS_UMOCKALLOC_09_001: [ umockalloc_calloc shall call calloc, while passing the number of members and size arguments to calloc. ] */
/* Tests_SRS_UMOCKALLOC_09_002: [ umockalloc_calloc shall return the result of calloc. ]*/
TEST_FUNCTION(umockalloc_calloc_calls_calloc_other_value)
{
// arrange
void* result;
test_calloc_expected_result = (void*)0x5252;
// act
result = umockalloc_calloc(1, 43);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x5252, result);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_call_count);
ASSERT_ARE_EQUAL(size_t, 43, test_calloc_calls[0].size);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_calls[0].nmemb);
}
/* Tests_SRS_UMOCKALLOC_09_001: [ umockalloc_calloc shall call calloc, while passing the number of members and size arguments to calloc. ] */
/* Tests_SRS_UMOCKALLOC_09_002: [ umockalloc_calloc shall return the result of calloc. ]*/
TEST_FUNCTION(umockalloc_calloc_calls_calloc_2_members)
{
// arrange
void* result;
test_calloc_expected_result = (void*)0x4242;
// act
result = umockalloc_calloc(2, 40);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x4242, result);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_call_count);
ASSERT_ARE_EQUAL(size_t, 40, test_calloc_calls[0].size);
ASSERT_ARE_EQUAL(size_t, 2, test_calloc_calls[0].nmemb);
}
/* Tests_SRS_UMOCKALLOC_09_001: [ umockalloc_calloc shall call calloc, while passing the number of members and size arguments to calloc. ] */
/* Tests_SRS_UMOCKALLOC_09_002: [ umockalloc_calloc shall return the result of calloc. ]*/
TEST_FUNCTION(umockalloc_calloc_calls_calloc_0_members)
{
// arrange
void* result;
test_calloc_expected_result = NULL;
// act
result = umockalloc_calloc(0, 40);
// assert
ASSERT_IS_NULL(result);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_call_count);
ASSERT_ARE_EQUAL(size_t, 40, test_calloc_calls[0].size);
ASSERT_ARE_EQUAL(size_t, 0, test_calloc_calls[0].nmemb);
}
/* Tests_SRS_UMOCKALLOC_09_001: [ umockalloc_malloc shall call malloc, while passing the size argument to malloc. ] */
TEST_FUNCTION(when_calloc_returns_NULL_umockalloc_calloc_returns_NULL)
{
// arrange
void* result;
test_calloc_expected_result = NULL;
// act
result = umockalloc_calloc(1, 43);
// assert
ASSERT_IS_NULL(result);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_call_count);
ASSERT_ARE_EQUAL(size_t, 43, test_calloc_calls[0].size);
ASSERT_ARE_EQUAL(size_t, 1, test_calloc_calls[0].nmemb);
}
/* umockalloc_realloc */
/* Tests_SRS_UMOCKALLOC_01_005: [ umockalloc_realloc shall call realloc, while passing the ptr and size arguments to realloc. ] */
/* Tests_SRS_UMOCKALLOC_01_006: [ umockalloc_realloc shall return the result of realloc. ]*/
TEST_FUNCTION(umockalloc_realloc_calls_realloc)
{
// arrange
void* result;
test_realloc_expected_result = (void*)0x4242;
// act
result = umockalloc_realloc((void*)0x2222, 42);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x4242, result);
ASSERT_ARE_EQUAL(size_t, 1, test_realloc_call_count);
ASSERT_ARE_EQUAL(size_t, 42, test_realloc_calls[0].size);
ASSERT_ARE_EQUAL(void_ptr, (void*)0x2222, test_realloc_calls[0].ptr);
}
/* Tests_SRS_UMOCKALLOC_01_005: [ umockalloc_realloc shall call realloc, while passing the ptr and size arguments to realloc. ] */
/* Tests_SRS_UMOCKALLOC_01_006: [ umockalloc_realloc shall return the result of realloc. ]*/
TEST_FUNCTION(umockalloc_realloc_calls_realloc_other_value)
{
// arrange
void* result;
test_realloc_expected_result = (void*)0x5252;
// act
result = umockalloc_realloc((void*)0x3232, 43);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x5252, result);
ASSERT_ARE_EQUAL(size_t, 1, test_realloc_call_count);
ASSERT_ARE_EQUAL(size_t, 43, test_realloc_calls[0].size);
ASSERT_ARE_EQUAL(void_ptr, (void*)0x3232, test_realloc_calls[0].ptr);
}
/* Tests_SRS_UMOCKALLOC_01_005: [ umockalloc_realloc shall call realloc, while passing the ptr and size arguments to realloc. ] */
/* Tests_SRS_UMOCKALLOC_01_006: [ umockalloc_realloc shall return the result of realloc. ]*/
TEST_FUNCTION(when_realloc_returns_NULL_umockalloc_realloc_returns_NULL)
{
// arrange
void* result;
test_realloc_expected_result = NULL;
// act
result = umockalloc_realloc((void*)0x3232, 43);
// assert
ASSERT_IS_NULL(result);
ASSERT_ARE_EQUAL(size_t, 1, test_realloc_call_count);
ASSERT_ARE_EQUAL(size_t, 43, test_realloc_calls[0].size);
ASSERT_ARE_EQUAL(void_ptr, (void*)0x3232, test_realloc_calls[0].ptr);
}
/* Tests_SRS_UMOCKALLOC_01_005: [ umockalloc_realloc shall call realloc, while passing the ptr and size arguments to realloc. ] */
/* Tests_SRS_UMOCKALLOC_01_006: [ umockalloc_realloc shall return the result of realloc. ]*/
TEST_FUNCTION(umockalloc_realloc_with_NULL_and_0_size_calls_the_underlying_realloc)
{
// arrange
void* result;
test_realloc_expected_result = (void*)0x4242;
// act
result = umockalloc_realloc(NULL, 0);
// assert
ASSERT_ARE_EQUAL(void_ptr, (void*)0x4242, result);
ASSERT_ARE_EQUAL(size_t, 1, test_realloc_call_count);
ASSERT_ARE_EQUAL(size_t, 0, test_realloc_calls[0].size);
ASSERT_ARE_EQUAL(void_ptr, NULL, test_realloc_calls[0].ptr);
}
/* umockalloc_free */
/* Tests_SRS_UMOCKALLOC_01_007: [ umockalloc_free shall call free, while passing the ptr argument to free. ]*/
TEST_FUNCTION(umockalloc_free_calls_free)
{
// arrange
// act
umockalloc_free((void*)0x4242);
// assert
ASSERT_ARE_EQUAL(size_t, 1, test_free_call_count);
ASSERT_ARE_EQUAL(void_ptr, (void*)0x4242, test_free_calls[0].ptr);
}
/* Tests_SRS_UMOCKALLOC_01_007: [ umockalloc_free shall call free, while passing the ptr argument to free. ]*/
TEST_FUNCTION(umockalloc_free_with_NULL_calls_free_with_NULL)
{
// arrange
// act
umockalloc_free(NULL);
// assert
ASSERT_ARE_EQUAL(size_t, 1, test_free_call_count);
ASSERT_ARE_EQUAL(void_ptr, NULL, test_free_calls[0].ptr);
}
END_TEST_SUITE(umockalloc_unittests)
| utf-8 | 1 | Expat | 2018-2022 Microsoft Corporation |